1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // 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
25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 // too, why the expression could not be folded.
27 //
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 //
33 //===----------------------------------------------------------------------===//
34
35 #include "ByteCode/Context.h"
36 #include "ByteCode/Frame.h"
37 #include "ByteCode/State.h"
38 #include "ExprConstShared.h"
39 #include "clang/AST/APValue.h"
40 #include "clang/AST/ASTContext.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/Type.h"
52 #include "clang/AST/TypeLoc.h"
53 #include "clang/Basic/Builtins.h"
54 #include "clang/Basic/DiagnosticSema.h"
55 #include "clang/Basic/TargetBuiltins.h"
56 #include "clang/Basic/TargetInfo.h"
57 #include "llvm/ADT/APFixedPoint.h"
58 #include "llvm/ADT/Sequence.h"
59 #include "llvm/ADT/SmallBitVector.h"
60 #include "llvm/ADT/StringExtras.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/SaveAndRestore.h"
64 #include "llvm/Support/SipHash.h"
65 #include "llvm/Support/TimeProfiler.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include <cstring>
68 #include <functional>
69 #include <limits>
70 #include <optional>
71
72 #define DEBUG_TYPE "exprconstant"
73
74 using namespace clang;
75 using llvm::APFixedPoint;
76 using llvm::APInt;
77 using llvm::APSInt;
78 using llvm::APFloat;
79 using llvm::FixedPointSemantics;
80
81 namespace {
82 struct LValue;
83 class CallStackFrame;
84 class EvalInfo;
85
86 using SourceLocExprScopeGuard =
87 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
88
getType(APValue::LValueBase B)89 static QualType getType(APValue::LValueBase B) {
90 return B.getType();
91 }
92
93 /// Get an LValue path entry, which is known to not be an array index, as a
94 /// field declaration.
getAsField(APValue::LValuePathEntry E)95 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
96 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
97 }
98 /// Get an LValue path entry, which is known to not be an array index, as a
99 /// base class declaration.
getAsBaseClass(APValue::LValuePathEntry E)100 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
101 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
102 }
103 /// Determine whether this LValue path entry for a base class names a virtual
104 /// base class.
isVirtualBaseClass(APValue::LValuePathEntry E)105 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
106 return E.getAsBaseOrMember().getInt();
107 }
108
109 /// Given an expression, determine the type used to store the result of
110 /// evaluating that expression.
getStorageType(const ASTContext & Ctx,const Expr * E)111 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
112 if (E->isPRValue())
113 return E->getType();
114 return Ctx.getLValueReferenceType(E->getType());
115 }
116
117 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
getAllocSizeAttr(const CallExpr * CE)118 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
119 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
120 return DirectCallee->getAttr<AllocSizeAttr>();
121 if (const Decl *IndirectCallee = CE->getCalleeDecl())
122 return IndirectCallee->getAttr<AllocSizeAttr>();
123 return nullptr;
124 }
125
126 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
127 /// This will look through a single cast.
128 ///
129 /// Returns null if we couldn't unwrap a function with alloc_size.
tryUnwrapAllocSizeCall(const Expr * E)130 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
131 if (!E->getType()->isPointerType())
132 return nullptr;
133
134 E = E->IgnoreParens();
135 // If we're doing a variable assignment from e.g. malloc(N), there will
136 // probably be a cast of some kind. In exotic cases, we might also see a
137 // top-level ExprWithCleanups. Ignore them either way.
138 if (const auto *FE = dyn_cast<FullExpr>(E))
139 E = FE->getSubExpr()->IgnoreParens();
140
141 if (const auto *Cast = dyn_cast<CastExpr>(E))
142 E = Cast->getSubExpr()->IgnoreParens();
143
144 if (const auto *CE = dyn_cast<CallExpr>(E))
145 return getAllocSizeAttr(CE) ? CE : nullptr;
146 return nullptr;
147 }
148
149 /// Determines whether or not the given Base contains a call to a function
150 /// with the alloc_size attribute.
isBaseAnAllocSizeCall(APValue::LValueBase Base)151 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
152 const auto *E = Base.dyn_cast<const Expr *>();
153 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
154 }
155
156 /// Determines whether the given kind of constant expression is only ever
157 /// used for name mangling. If so, it's permitted to reference things that we
158 /// can't generate code for (in particular, dllimported functions).
isForManglingOnly(ConstantExprKind Kind)159 static bool isForManglingOnly(ConstantExprKind Kind) {
160 switch (Kind) {
161 case ConstantExprKind::Normal:
162 case ConstantExprKind::ClassTemplateArgument:
163 case ConstantExprKind::ImmediateInvocation:
164 // Note that non-type template arguments of class type are emitted as
165 // template parameter objects.
166 return false;
167
168 case ConstantExprKind::NonClassTemplateArgument:
169 return true;
170 }
171 llvm_unreachable("unknown ConstantExprKind");
172 }
173
isTemplateArgument(ConstantExprKind Kind)174 static bool isTemplateArgument(ConstantExprKind Kind) {
175 switch (Kind) {
176 case ConstantExprKind::Normal:
177 case ConstantExprKind::ImmediateInvocation:
178 return false;
179
180 case ConstantExprKind::ClassTemplateArgument:
181 case ConstantExprKind::NonClassTemplateArgument:
182 return true;
183 }
184 llvm_unreachable("unknown ConstantExprKind");
185 }
186
187 /// The bound to claim that an array of unknown bound has.
188 /// The value in MostDerivedArraySize is undefined in this case. So, set it
189 /// to an arbitrary value that's likely to loudly break things if it's used.
190 static const uint64_t AssumedSizeForUnsizedArray =
191 std::numeric_limits<uint64_t>::max() / 2;
192
193 /// Determines if an LValue with the given LValueBase will have an unsized
194 /// array in its designator.
195 /// Find the path length and type of the most-derived subobject in the given
196 /// path, and find the size of the containing array, if any.
197 static unsigned
findMostDerivedSubobject(ASTContext & Ctx,APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path,uint64_t & ArraySize,QualType & Type,bool & IsArray,bool & FirstEntryIsUnsizedArray)198 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
199 ArrayRef<APValue::LValuePathEntry> Path,
200 uint64_t &ArraySize, QualType &Type, bool &IsArray,
201 bool &FirstEntryIsUnsizedArray) {
202 // This only accepts LValueBases from APValues, and APValues don't support
203 // arrays that lack size info.
204 assert(!isBaseAnAllocSizeCall(Base) &&
205 "Unsized arrays shouldn't appear here");
206 unsigned MostDerivedLength = 0;
207 // The type of Base is a reference type if the base is a constexpr-unknown
208 // variable. In that case, look through the reference type.
209 Type = getType(Base).getNonReferenceType();
210
211 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
212 if (Type->isArrayType()) {
213 const ArrayType *AT = Ctx.getAsArrayType(Type);
214 Type = AT->getElementType();
215 MostDerivedLength = I + 1;
216 IsArray = true;
217
218 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
219 ArraySize = CAT->getZExtSize();
220 } else {
221 assert(I == 0 && "unexpected unsized array designator");
222 FirstEntryIsUnsizedArray = true;
223 ArraySize = AssumedSizeForUnsizedArray;
224 }
225 } else if (Type->isAnyComplexType()) {
226 const ComplexType *CT = Type->castAs<ComplexType>();
227 Type = CT->getElementType();
228 ArraySize = 2;
229 MostDerivedLength = I + 1;
230 IsArray = true;
231 } else if (const auto *VT = Type->getAs<VectorType>()) {
232 Type = VT->getElementType();
233 ArraySize = VT->getNumElements();
234 MostDerivedLength = I + 1;
235 IsArray = true;
236 } else if (const FieldDecl *FD = getAsField(Path[I])) {
237 Type = FD->getType();
238 ArraySize = 0;
239 MostDerivedLength = I + 1;
240 IsArray = false;
241 } else {
242 // Path[I] describes a base class.
243 ArraySize = 0;
244 IsArray = false;
245 }
246 }
247 return MostDerivedLength;
248 }
249
250 /// A path from a glvalue to a subobject of that glvalue.
251 struct SubobjectDesignator {
252 /// True if the subobject was named in a manner not supported by C++11. Such
253 /// lvalues can still be folded, but they are not core constant expressions
254 /// and we cannot perform lvalue-to-rvalue conversions on them.
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned Invalid : 1;
257
258 /// Is this a pointer one past the end of an object?
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned IsOnePastTheEnd : 1;
261
262 /// Indicator of whether the first entry is an unsized array.
263 LLVM_PREFERRED_TYPE(bool)
264 unsigned FirstEntryIsAnUnsizedArray : 1;
265
266 /// Indicator of whether the most-derived object is an array element.
267 LLVM_PREFERRED_TYPE(bool)
268 unsigned MostDerivedIsArrayElement : 1;
269
270 /// The length of the path to the most-derived object of which this is a
271 /// subobject.
272 unsigned MostDerivedPathLength : 28;
273
274 /// The size of the array of which the most-derived object is an element.
275 /// This will always be 0 if the most-derived object is not an array
276 /// element. 0 is not an indicator of whether or not the most-derived object
277 /// is an array, however, because 0-length arrays are allowed.
278 ///
279 /// If the current array is an unsized array, the value of this is
280 /// undefined.
281 uint64_t MostDerivedArraySize;
282 /// The type of the most derived object referred to by this address.
283 QualType MostDerivedType;
284
285 typedef APValue::LValuePathEntry PathEntry;
286
287 /// The entries on the path from the glvalue to the designated subobject.
288 SmallVector<PathEntry, 8> Entries;
289
SubobjectDesignator__anonfb577fba0111::SubobjectDesignator290 SubobjectDesignator() : Invalid(true) {}
291
SubobjectDesignator__anonfb577fba0111::SubobjectDesignator292 explicit SubobjectDesignator(QualType T)
293 : Invalid(false), IsOnePastTheEnd(false),
294 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
295 MostDerivedPathLength(0), MostDerivedArraySize(0),
296 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
297
SubobjectDesignator__anonfb577fba0111::SubobjectDesignator298 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
299 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
300 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
301 MostDerivedPathLength(0), MostDerivedArraySize(0) {
302 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
303 if (!Invalid) {
304 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
305 llvm::append_range(Entries, V.getLValuePath());
306 if (V.getLValueBase()) {
307 bool IsArray = false;
308 bool FirstIsUnsizedArray = false;
309 MostDerivedPathLength = findMostDerivedSubobject(
310 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
311 MostDerivedType, IsArray, FirstIsUnsizedArray);
312 MostDerivedIsArrayElement = IsArray;
313 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
314 }
315 }
316 }
317
truncate__anonfb577fba0111::SubobjectDesignator318 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
319 unsigned NewLength) {
320 if (Invalid)
321 return;
322
323 assert(Base && "cannot truncate path for null pointer");
324 assert(NewLength <= Entries.size() && "not a truncation");
325
326 if (NewLength == Entries.size())
327 return;
328 Entries.resize(NewLength);
329
330 bool IsArray = false;
331 bool FirstIsUnsizedArray = false;
332 MostDerivedPathLength = findMostDerivedSubobject(
333 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
334 FirstIsUnsizedArray);
335 MostDerivedIsArrayElement = IsArray;
336 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
337 }
338
setInvalid__anonfb577fba0111::SubobjectDesignator339 void setInvalid() {
340 Invalid = true;
341 Entries.clear();
342 }
343
344 /// Determine whether the most derived subobject is an array without a
345 /// known bound.
isMostDerivedAnUnsizedArray__anonfb577fba0111::SubobjectDesignator346 bool isMostDerivedAnUnsizedArray() const {
347 assert(!Invalid && "Calling this makes no sense on invalid designators");
348 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
349 }
350
351 /// Determine what the most derived array's size is. Results in an assertion
352 /// failure if the most derived array lacks a size.
getMostDerivedArraySize__anonfb577fba0111::SubobjectDesignator353 uint64_t getMostDerivedArraySize() const {
354 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
355 return MostDerivedArraySize;
356 }
357
358 /// Determine whether this is a one-past-the-end pointer.
isOnePastTheEnd__anonfb577fba0111::SubobjectDesignator359 bool isOnePastTheEnd() const {
360 assert(!Invalid);
361 if (IsOnePastTheEnd)
362 return true;
363 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
364 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
365 MostDerivedArraySize)
366 return true;
367 return false;
368 }
369
370 /// Get the range of valid index adjustments in the form
371 /// {maximum value that can be subtracted from this pointer,
372 /// maximum value that can be added to this pointer}
validIndexAdjustments__anonfb577fba0111::SubobjectDesignator373 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
374 if (Invalid || isMostDerivedAnUnsizedArray())
375 return {0, 0};
376
377 // [expr.add]p4: For the purposes of these operators, a pointer to a
378 // nonarray object behaves the same as a pointer to the first element of
379 // an array of length one with the type of the object as its element type.
380 bool IsArray = MostDerivedPathLength == Entries.size() &&
381 MostDerivedIsArrayElement;
382 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
383 : (uint64_t)IsOnePastTheEnd;
384 uint64_t ArraySize =
385 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
386 return {ArrayIndex, ArraySize - ArrayIndex};
387 }
388
389 /// Check that this refers to a valid subobject.
isValidSubobject__anonfb577fba0111::SubobjectDesignator390 bool isValidSubobject() const {
391 if (Invalid)
392 return false;
393 return !isOnePastTheEnd();
394 }
395 /// Check that this refers to a valid subobject, and if not, produce a
396 /// relevant diagnostic and set the designator as invalid.
397 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
398
399 /// Get the type of the designated object.
getType__anonfb577fba0111::SubobjectDesignator400 QualType getType(ASTContext &Ctx) const {
401 assert(!Invalid && "invalid designator has no subobject type");
402 return MostDerivedPathLength == Entries.size()
403 ? MostDerivedType
404 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
405 }
406
407 /// Update this designator to refer to the first element within this array.
addArrayUnchecked__anonfb577fba0111::SubobjectDesignator408 void addArrayUnchecked(const ConstantArrayType *CAT) {
409 Entries.push_back(PathEntry::ArrayIndex(0));
410
411 // This is a most-derived object.
412 MostDerivedType = CAT->getElementType();
413 MostDerivedIsArrayElement = true;
414 MostDerivedArraySize = CAT->getZExtSize();
415 MostDerivedPathLength = Entries.size();
416 }
417 /// Update this designator to refer to the first element within the array of
418 /// elements of type T. This is an array of unknown size.
addUnsizedArrayUnchecked__anonfb577fba0111::SubobjectDesignator419 void addUnsizedArrayUnchecked(QualType ElemTy) {
420 Entries.push_back(PathEntry::ArrayIndex(0));
421
422 MostDerivedType = ElemTy;
423 MostDerivedIsArrayElement = true;
424 // The value in MostDerivedArraySize is undefined in this case. So, set it
425 // to an arbitrary value that's likely to loudly break things if it's
426 // used.
427 MostDerivedArraySize = AssumedSizeForUnsizedArray;
428 MostDerivedPathLength = Entries.size();
429 }
430 /// Update this designator to refer to the given base or member of this
431 /// object.
addDeclUnchecked__anonfb577fba0111::SubobjectDesignator432 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
433 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
434
435 // If this isn't a base class, it's a new most-derived object.
436 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
437 MostDerivedType = FD->getType();
438 MostDerivedIsArrayElement = false;
439 MostDerivedArraySize = 0;
440 MostDerivedPathLength = Entries.size();
441 }
442 }
443 /// Update this designator to refer to the given complex component.
addComplexUnchecked__anonfb577fba0111::SubobjectDesignator444 void addComplexUnchecked(QualType EltTy, bool Imag) {
445 Entries.push_back(PathEntry::ArrayIndex(Imag));
446
447 // This is technically a most-derived object, though in practice this
448 // is unlikely to matter.
449 MostDerivedType = EltTy;
450 MostDerivedIsArrayElement = true;
451 MostDerivedArraySize = 2;
452 MostDerivedPathLength = Entries.size();
453 }
454
addVectorElementUnchecked__anonfb577fba0111::SubobjectDesignator455 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
456 uint64_t Idx) {
457 Entries.push_back(PathEntry::ArrayIndex(Idx));
458 MostDerivedType = EltTy;
459 MostDerivedPathLength = Entries.size();
460 MostDerivedArraySize = 0;
461 MostDerivedIsArrayElement = false;
462 }
463
464 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
465 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
466 const APSInt &N);
467 /// Add N to the address of this subobject.
adjustIndex__anonfb577fba0111::SubobjectDesignator468 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
469 if (Invalid || !N) return;
470 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
471 if (isMostDerivedAnUnsizedArray()) {
472 diagnoseUnsizedArrayPointerArithmetic(Info, E);
473 // Can't verify -- trust that the user is doing the right thing (or if
474 // not, trust that the caller will catch the bad behavior).
475 // FIXME: Should we reject if this overflows, at least?
476 Entries.back() = PathEntry::ArrayIndex(
477 Entries.back().getAsArrayIndex() + TruncatedN);
478 return;
479 }
480
481 // [expr.add]p4: For the purposes of these operators, a pointer to a
482 // nonarray object behaves the same as a pointer to the first element of
483 // an array of length one with the type of the object as its element type.
484 bool IsArray = MostDerivedPathLength == Entries.size() &&
485 MostDerivedIsArrayElement;
486 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
487 : (uint64_t)IsOnePastTheEnd;
488 uint64_t ArraySize =
489 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
490
491 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
492 // Calculate the actual index in a wide enough type, so we can include
493 // it in the note.
494 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
495 (llvm::APInt&)N += ArrayIndex;
496 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
497 diagnosePointerArithmetic(Info, E, N);
498 setInvalid();
499 return;
500 }
501
502 ArrayIndex += TruncatedN;
503 assert(ArrayIndex <= ArraySize &&
504 "bounds check succeeded for out-of-bounds index");
505
506 if (IsArray)
507 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
508 else
509 IsOnePastTheEnd = (ArrayIndex != 0);
510 }
511 };
512
513 /// A scope at the end of which an object can need to be destroyed.
514 enum class ScopeKind {
515 Block,
516 FullExpression,
517 Call
518 };
519
520 /// A reference to a particular call and its arguments.
521 struct CallRef {
CallRef__anonfb577fba0111::CallRef522 CallRef() : OrigCallee(), CallIndex(0), Version() {}
CallRef__anonfb577fba0111::CallRef523 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
524 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
525
operator bool__anonfb577fba0111::CallRef526 explicit operator bool() const { return OrigCallee; }
527
528 /// Get the parameter that the caller initialized, corresponding to the
529 /// given parameter in the callee.
getOrigParam__anonfb577fba0111::CallRef530 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
531 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
532 : PVD;
533 }
534
535 /// The callee at the point where the arguments were evaluated. This might
536 /// be different from the actual callee (a different redeclaration, or a
537 /// virtual override), but this function's parameters are the ones that
538 /// appear in the parameter map.
539 const FunctionDecl *OrigCallee;
540 /// The call index of the frame that holds the argument values.
541 unsigned CallIndex;
542 /// The version of the parameters corresponding to this call.
543 unsigned Version;
544 };
545
546 /// A stack frame in the constexpr call stack.
547 class CallStackFrame : public interp::Frame {
548 public:
549 EvalInfo &Info;
550
551 /// Parent - The caller of this stack frame.
552 CallStackFrame *Caller;
553
554 /// Callee - The function which was called.
555 const FunctionDecl *Callee;
556
557 /// This - The binding for the this pointer in this call, if any.
558 const LValue *This;
559
560 /// CallExpr - The syntactical structure of member function calls
561 const Expr *CallExpr;
562
563 /// Information on how to find the arguments to this call. Our arguments
564 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
565 /// key and this value as the version.
566 CallRef Arguments;
567
568 /// Source location information about the default argument or default
569 /// initializer expression we're evaluating, if any.
570 CurrentSourceLocExprScope CurSourceLocExprScope;
571
572 // Note that we intentionally use std::map here so that references to
573 // values are stable.
574 typedef std::pair<const void *, unsigned> MapKeyTy;
575 typedef std::map<MapKeyTy, APValue> MapTy;
576 /// Temporaries - Temporary lvalues materialized within this stack frame.
577 MapTy Temporaries;
578
579 /// CallRange - The source range of the call expression for this call.
580 SourceRange CallRange;
581
582 /// Index - The call index of this call.
583 unsigned Index;
584
585 /// The stack of integers for tracking version numbers for temporaries.
586 SmallVector<unsigned, 2> TempVersionStack = {1};
587 unsigned CurTempVersion = TempVersionStack.back();
588
getTempVersion() const589 unsigned getTempVersion() const { return TempVersionStack.back(); }
590
pushTempVersion()591 void pushTempVersion() {
592 TempVersionStack.push_back(++CurTempVersion);
593 }
594
popTempVersion()595 void popTempVersion() {
596 TempVersionStack.pop_back();
597 }
598
createCall(const FunctionDecl * Callee)599 CallRef createCall(const FunctionDecl *Callee) {
600 return {Callee, Index, ++CurTempVersion};
601 }
602
603 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
604 // on the overall stack usage of deeply-recursing constexpr evaluations.
605 // (We should cache this map rather than recomputing it repeatedly.)
606 // But let's try this and see how it goes; we can look into caching the map
607 // as a later change.
608
609 /// LambdaCaptureFields - Mapping from captured variables/this to
610 /// corresponding data members in the closure class.
611 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
612 FieldDecl *LambdaThisCaptureField = nullptr;
613
614 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
615 const FunctionDecl *Callee, const LValue *This,
616 const Expr *CallExpr, CallRef Arguments);
617 ~CallStackFrame();
618
619 // Return the temporary for Key whose version number is Version.
getTemporary(const void * Key,unsigned Version)620 APValue *getTemporary(const void *Key, unsigned Version) {
621 MapKeyTy KV(Key, Version);
622 auto LB = Temporaries.lower_bound(KV);
623 if (LB != Temporaries.end() && LB->first == KV)
624 return &LB->second;
625 return nullptr;
626 }
627
628 // Return the current temporary for Key in the map.
getCurrentTemporary(const void * Key)629 APValue *getCurrentTemporary(const void *Key) {
630 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
631 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
632 return &std::prev(UB)->second;
633 return nullptr;
634 }
635
636 // Return the version number of the current temporary for Key.
getCurrentTemporaryVersion(const void * Key) const637 unsigned getCurrentTemporaryVersion(const void *Key) const {
638 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
639 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
640 return std::prev(UB)->first.second;
641 return 0;
642 }
643
644 /// Allocate storage for an object of type T in this stack frame.
645 /// Populates LV with a handle to the created object. Key identifies
646 /// the temporary within the stack frame, and must not be reused without
647 /// bumping the temporary version number.
648 template<typename KeyT>
649 APValue &createTemporary(const KeyT *Key, QualType T,
650 ScopeKind Scope, LValue &LV);
651
652 /// Allocate storage for a parameter of a function call made in this frame.
653 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
654
655 void describe(llvm::raw_ostream &OS) const override;
656
getCaller() const657 Frame *getCaller() const override { return Caller; }
getCallRange() const658 SourceRange getCallRange() const override { return CallRange; }
getCallee() const659 const FunctionDecl *getCallee() const override { return Callee; }
660
isStdFunction() const661 bool isStdFunction() const {
662 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
663 if (DC->isStdNamespace())
664 return true;
665 return false;
666 }
667
668 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
669 /// permitted. See MSConstexprDocs for description of permitted contexts.
670 bool CanEvalMSConstexpr = false;
671
672 private:
673 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
674 ScopeKind Scope);
675 };
676
677 /// Temporarily override 'this'.
678 class ThisOverrideRAII {
679 public:
ThisOverrideRAII(CallStackFrame & Frame,const LValue * NewThis,bool Enable)680 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
681 : Frame(Frame), OldThis(Frame.This) {
682 if (Enable)
683 Frame.This = NewThis;
684 }
~ThisOverrideRAII()685 ~ThisOverrideRAII() {
686 Frame.This = OldThis;
687 }
688 private:
689 CallStackFrame &Frame;
690 const LValue *OldThis;
691 };
692
693 // A shorthand time trace scope struct, prints source range, for example
694 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
695 class ExprTimeTraceScope {
696 public:
ExprTimeTraceScope(const Expr * E,const ASTContext & Ctx,StringRef Name)697 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
698 : TimeScope(Name, [E, &Ctx] {
699 return E->getSourceRange().printToString(Ctx.getSourceManager());
700 }) {}
701
702 private:
703 llvm::TimeTraceScope TimeScope;
704 };
705
706 /// RAII object used to change the current ability of
707 /// [[msvc::constexpr]] evaulation.
708 struct MSConstexprContextRAII {
709 CallStackFrame &Frame;
710 bool OldValue;
MSConstexprContextRAII__anonfb577fba0111::MSConstexprContextRAII711 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
712 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
713 Frame.CanEvalMSConstexpr = Value;
714 }
715
~MSConstexprContextRAII__anonfb577fba0111::MSConstexprContextRAII716 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
717 };
718 }
719
720 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
721 const LValue &This, QualType ThisType);
722 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
723 APValue::LValueBase LVBase, APValue &Value,
724 QualType T);
725
726 namespace {
727 /// A cleanup, and a flag indicating whether it is lifetime-extended.
728 class Cleanup {
729 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
730 APValue::LValueBase Base;
731 QualType T;
732
733 public:
Cleanup(APValue * Val,APValue::LValueBase Base,QualType T,ScopeKind Scope)734 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
735 ScopeKind Scope)
736 : Value(Val, Scope), Base(Base), T(T) {}
737
738 /// Determine whether this cleanup should be performed at the end of the
739 /// given kind of scope.
isDestroyedAtEndOf(ScopeKind K) const740 bool isDestroyedAtEndOf(ScopeKind K) const {
741 return (int)Value.getInt() >= (int)K;
742 }
endLifetime(EvalInfo & Info,bool RunDestructors)743 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
744 if (RunDestructors) {
745 SourceLocation Loc;
746 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
747 Loc = VD->getLocation();
748 else if (const Expr *E = Base.dyn_cast<const Expr*>())
749 Loc = E->getExprLoc();
750 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
751 }
752 *Value.getPointer() = APValue();
753 return true;
754 }
755
hasSideEffect()756 bool hasSideEffect() {
757 return T.isDestructedType();
758 }
759 };
760
761 /// A reference to an object whose construction we are currently evaluating.
762 struct ObjectUnderConstruction {
763 APValue::LValueBase Base;
764 ArrayRef<APValue::LValuePathEntry> Path;
operator ==(const ObjectUnderConstruction & LHS,const ObjectUnderConstruction & RHS)765 friend bool operator==(const ObjectUnderConstruction &LHS,
766 const ObjectUnderConstruction &RHS) {
767 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
768 }
hash_value(const ObjectUnderConstruction & Obj)769 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
770 return llvm::hash_combine(Obj.Base, Obj.Path);
771 }
772 };
773 enum class ConstructionPhase {
774 None,
775 Bases,
776 AfterBases,
777 AfterFields,
778 Destroying,
779 DestroyingBases
780 };
781 }
782
783 namespace llvm {
784 template<> struct DenseMapInfo<ObjectUnderConstruction> {
785 using Base = DenseMapInfo<APValue::LValueBase>;
getEmptyKeyllvm::DenseMapInfo786 static ObjectUnderConstruction getEmptyKey() {
787 return {Base::getEmptyKey(), {}}; }
getTombstoneKeyllvm::DenseMapInfo788 static ObjectUnderConstruction getTombstoneKey() {
789 return {Base::getTombstoneKey(), {}};
790 }
getHashValuellvm::DenseMapInfo791 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
792 return hash_value(Object);
793 }
isEqualllvm::DenseMapInfo794 static bool isEqual(const ObjectUnderConstruction &LHS,
795 const ObjectUnderConstruction &RHS) {
796 return LHS == RHS;
797 }
798 };
799 }
800
801 namespace {
802 /// A dynamically-allocated heap object.
803 struct DynAlloc {
804 /// The value of this heap-allocated object.
805 APValue Value;
806 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
807 /// or a CallExpr (the latter is for direct calls to operator new inside
808 /// std::allocator<T>::allocate).
809 const Expr *AllocExpr = nullptr;
810
811 enum Kind {
812 New,
813 ArrayNew,
814 StdAllocator
815 };
816
817 /// Get the kind of the allocation. This must match between allocation
818 /// and deallocation.
getKind__anonfb577fba0411::DynAlloc819 Kind getKind() const {
820 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
821 return NE->isArray() ? ArrayNew : New;
822 assert(isa<CallExpr>(AllocExpr));
823 return StdAllocator;
824 }
825 };
826
827 struct DynAllocOrder {
operator ()__anonfb577fba0411::DynAllocOrder828 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
829 return L.getIndex() < R.getIndex();
830 }
831 };
832
833 /// EvalInfo - This is a private struct used by the evaluator to capture
834 /// information about a subexpression as it is folded. It retains information
835 /// about the AST context, but also maintains information about the folded
836 /// expression.
837 ///
838 /// If an expression could be evaluated, it is still possible it is not a C
839 /// "integer constant expression" or constant expression. If not, this struct
840 /// captures information about how and why not.
841 ///
842 /// One bit of information passed *into* the request for constant folding
843 /// indicates whether the subexpression is "evaluated" or not according to C
844 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
845 /// evaluate the expression regardless of what the RHS is, but C only allows
846 /// certain things in certain situations.
847 class EvalInfo : public interp::State {
848 public:
849 ASTContext &Ctx;
850
851 /// EvalStatus - Contains information about the evaluation.
852 Expr::EvalStatus &EvalStatus;
853
854 /// CurrentCall - The top of the constexpr call stack.
855 CallStackFrame *CurrentCall;
856
857 /// CallStackDepth - The number of calls in the call stack right now.
858 unsigned CallStackDepth;
859
860 /// NextCallIndex - The next call index to assign.
861 unsigned NextCallIndex;
862
863 /// StepsLeft - The remaining number of evaluation steps we're permitted
864 /// to perform. This is essentially a limit for the number of statements
865 /// we will evaluate.
866 unsigned StepsLeft;
867
868 /// Enable the experimental new constant interpreter. If an expression is
869 /// not supported by the interpreter, an error is triggered.
870 bool EnableNewConstInterp;
871
872 /// BottomFrame - The frame in which evaluation started. This must be
873 /// initialized after CurrentCall and CallStackDepth.
874 CallStackFrame BottomFrame;
875
876 /// A stack of values whose lifetimes end at the end of some surrounding
877 /// evaluation frame.
878 llvm::SmallVector<Cleanup, 16> CleanupStack;
879
880 /// EvaluatingDecl - This is the declaration whose initializer is being
881 /// evaluated, if any.
882 APValue::LValueBase EvaluatingDecl;
883
884 enum class EvaluatingDeclKind {
885 None,
886 /// We're evaluating the construction of EvaluatingDecl.
887 Ctor,
888 /// We're evaluating the destruction of EvaluatingDecl.
889 Dtor,
890 };
891 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
892
893 /// EvaluatingDeclValue - This is the value being constructed for the
894 /// declaration whose initializer is being evaluated, if any.
895 APValue *EvaluatingDeclValue;
896
897 /// Set of objects that are currently being constructed.
898 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
899 ObjectsUnderConstruction;
900
901 /// Current heap allocations, along with the location where each was
902 /// allocated. We use std::map here because we need stable addresses
903 /// for the stored APValues.
904 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
905
906 /// The number of heap allocations performed so far in this evaluation.
907 unsigned NumHeapAllocs = 0;
908
909 struct EvaluatingConstructorRAII {
910 EvalInfo &EI;
911 ObjectUnderConstruction Object;
912 bool DidInsert;
EvaluatingConstructorRAII__anonfb577fba0411::EvalInfo::EvaluatingConstructorRAII913 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
914 bool HasBases)
915 : EI(EI), Object(Object) {
916 DidInsert =
917 EI.ObjectsUnderConstruction
918 .insert({Object, HasBases ? ConstructionPhase::Bases
919 : ConstructionPhase::AfterBases})
920 .second;
921 }
finishedConstructingBases__anonfb577fba0411::EvalInfo::EvaluatingConstructorRAII922 void finishedConstructingBases() {
923 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
924 }
finishedConstructingFields__anonfb577fba0411::EvalInfo::EvaluatingConstructorRAII925 void finishedConstructingFields() {
926 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
927 }
~EvaluatingConstructorRAII__anonfb577fba0411::EvalInfo::EvaluatingConstructorRAII928 ~EvaluatingConstructorRAII() {
929 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
930 }
931 };
932
933 struct EvaluatingDestructorRAII {
934 EvalInfo &EI;
935 ObjectUnderConstruction Object;
936 bool DidInsert;
EvaluatingDestructorRAII__anonfb577fba0411::EvalInfo::EvaluatingDestructorRAII937 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
938 : EI(EI), Object(Object) {
939 DidInsert = EI.ObjectsUnderConstruction
940 .insert({Object, ConstructionPhase::Destroying})
941 .second;
942 }
startedDestroyingBases__anonfb577fba0411::EvalInfo::EvaluatingDestructorRAII943 void startedDestroyingBases() {
944 EI.ObjectsUnderConstruction[Object] =
945 ConstructionPhase::DestroyingBases;
946 }
~EvaluatingDestructorRAII__anonfb577fba0411::EvalInfo::EvaluatingDestructorRAII947 ~EvaluatingDestructorRAII() {
948 if (DidInsert)
949 EI.ObjectsUnderConstruction.erase(Object);
950 }
951 };
952
953 ConstructionPhase
isEvaluatingCtorDtor(APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path)954 isEvaluatingCtorDtor(APValue::LValueBase Base,
955 ArrayRef<APValue::LValuePathEntry> Path) {
956 return ObjectsUnderConstruction.lookup({Base, Path});
957 }
958
959 /// If we're currently speculatively evaluating, the outermost call stack
960 /// depth at which we can mutate state, otherwise 0.
961 unsigned SpeculativeEvaluationDepth = 0;
962
963 /// The current array initialization index, if we're performing array
964 /// initialization.
965 uint64_t ArrayInitIndex = -1;
966
967 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
968 /// notes attached to it will also be stored, otherwise they will not be.
969 bool HasActiveDiagnostic;
970
971 /// Have we emitted a diagnostic explaining why we couldn't constant
972 /// fold (not just why it's not strictly a constant expression)?
973 bool HasFoldFailureDiagnostic;
974
975 /// Whether we're checking that an expression is a potential constant
976 /// expression. If so, do not fail on constructs that could become constant
977 /// later on (such as a use of an undefined global).
978 bool CheckingPotentialConstantExpression = false;
979
980 /// Whether we're checking for an expression that has undefined behavior.
981 /// If so, we will produce warnings if we encounter an operation that is
982 /// always undefined.
983 ///
984 /// Note that we still need to evaluate the expression normally when this
985 /// is set; this is used when evaluating ICEs in C.
986 bool CheckingForUndefinedBehavior = false;
987
988 enum EvaluationMode {
989 /// Evaluate as a constant expression. Stop if we find that the expression
990 /// is not a constant expression.
991 EM_ConstantExpression,
992
993 /// Evaluate as a constant expression. Stop if we find that the expression
994 /// is not a constant expression. Some expressions can be retried in the
995 /// optimizer if we don't constant fold them here, but in an unevaluated
996 /// context we try to fold them immediately since the optimizer never
997 /// gets a chance to look at it.
998 EM_ConstantExpressionUnevaluated,
999
1000 /// Fold the expression to a constant. Stop if we hit a side-effect that
1001 /// we can't model.
1002 EM_ConstantFold,
1003
1004 /// Evaluate in any way we know how. Don't worry about side-effects that
1005 /// can't be modeled.
1006 EM_IgnoreSideEffects,
1007 } EvalMode;
1008
1009 /// Are we checking whether the expression is a potential constant
1010 /// expression?
checkingPotentialConstantExpression() const1011 bool checkingPotentialConstantExpression() const override {
1012 return CheckingPotentialConstantExpression;
1013 }
1014
1015 /// Are we checking an expression for overflow?
1016 // FIXME: We should check for any kind of undefined or suspicious behavior
1017 // in such constructs, not just overflow.
checkingForUndefinedBehavior() const1018 bool checkingForUndefinedBehavior() const override {
1019 return CheckingForUndefinedBehavior;
1020 }
1021
EvalInfo(const ASTContext & C,Expr::EvalStatus & S,EvaluationMode Mode)1022 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1023 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1024 CallStackDepth(0), NextCallIndex(1),
1025 StepsLeft(C.getLangOpts().ConstexprStepLimit),
1026 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1027 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1028 /*This=*/nullptr,
1029 /*CallExpr=*/nullptr, CallRef()),
1030 EvaluatingDecl((const ValueDecl *)nullptr),
1031 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1032 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1033
~EvalInfo()1034 ~EvalInfo() {
1035 discardCleanups();
1036 }
1037
getASTContext() const1038 ASTContext &getASTContext() const override { return Ctx; }
1039
setEvaluatingDecl(APValue::LValueBase Base,APValue & Value,EvaluatingDeclKind EDK=EvaluatingDeclKind::Ctor)1040 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1041 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1042 EvaluatingDecl = Base;
1043 IsEvaluatingDecl = EDK;
1044 EvaluatingDeclValue = &Value;
1045 }
1046
CheckCallLimit(SourceLocation Loc)1047 bool CheckCallLimit(SourceLocation Loc) {
1048 // Don't perform any constexpr calls (other than the call we're checking)
1049 // when checking a potential constant expression.
1050 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1051 return false;
1052 if (NextCallIndex == 0) {
1053 // NextCallIndex has wrapped around.
1054 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1055 return false;
1056 }
1057 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1058 return true;
1059 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1060 << getLangOpts().ConstexprCallDepth;
1061 return false;
1062 }
1063
CheckArraySize(SourceLocation Loc,unsigned BitWidth,uint64_t ElemCount,bool Diag)1064 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1065 uint64_t ElemCount, bool Diag) {
1066 // FIXME: GH63562
1067 // APValue stores array extents as unsigned,
1068 // so anything that is greater that unsigned would overflow when
1069 // constructing the array, we catch this here.
1070 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1071 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1072 if (Diag)
1073 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1074 return false;
1075 }
1076
1077 // FIXME: GH63562
1078 // Arrays allocate an APValue per element.
1079 // We use the number of constexpr steps as a proxy for the maximum size
1080 // of arrays to avoid exhausting the system resources, as initialization
1081 // of each element is likely to take some number of steps anyway.
1082 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1083 if (ElemCount > Limit) {
1084 if (Diag)
1085 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1086 << ElemCount << Limit;
1087 return false;
1088 }
1089 return true;
1090 }
1091
1092 std::pair<CallStackFrame *, unsigned>
getCallFrameAndDepth(unsigned CallIndex)1093 getCallFrameAndDepth(unsigned CallIndex) {
1094 assert(CallIndex && "no call index in getCallFrameAndDepth");
1095 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1096 // be null in this loop.
1097 unsigned Depth = CallStackDepth;
1098 CallStackFrame *Frame = CurrentCall;
1099 while (Frame->Index > CallIndex) {
1100 Frame = Frame->Caller;
1101 --Depth;
1102 }
1103 if (Frame->Index == CallIndex)
1104 return {Frame, Depth};
1105 return {nullptr, 0};
1106 }
1107
nextStep(const Stmt * S)1108 bool nextStep(const Stmt *S) {
1109 if (!StepsLeft) {
1110 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1111 return false;
1112 }
1113 --StepsLeft;
1114 return true;
1115 }
1116
1117 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1118
lookupDynamicAlloc(DynamicAllocLValue DA)1119 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1120 std::optional<DynAlloc *> Result;
1121 auto It = HeapAllocs.find(DA);
1122 if (It != HeapAllocs.end())
1123 Result = &It->second;
1124 return Result;
1125 }
1126
1127 /// Get the allocated storage for the given parameter of the given call.
getParamSlot(CallRef Call,const ParmVarDecl * PVD)1128 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1129 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1130 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1131 : nullptr;
1132 }
1133
1134 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1135 struct StdAllocatorCaller {
1136 unsigned FrameIndex;
1137 QualType ElemType;
1138 const Expr *Call;
operator bool__anonfb577fba0411::EvalInfo::StdAllocatorCaller1139 explicit operator bool() const { return FrameIndex != 0; };
1140 };
1141
getStdAllocatorCaller(StringRef FnName) const1142 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1143 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1144 Call = Call->Caller) {
1145 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1146 if (!MD)
1147 continue;
1148 const IdentifierInfo *FnII = MD->getIdentifier();
1149 if (!FnII || !FnII->isStr(FnName))
1150 continue;
1151
1152 const auto *CTSD =
1153 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1154 if (!CTSD)
1155 continue;
1156
1157 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1158 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1159 if (CTSD->isInStdNamespace() && ClassII &&
1160 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1161 TAL[0].getKind() == TemplateArgument::Type)
1162 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1163 }
1164
1165 return {};
1166 }
1167
performLifetimeExtension()1168 void performLifetimeExtension() {
1169 // Disable the cleanups for lifetime-extended temporaries.
1170 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1171 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1172 });
1173 }
1174
1175 /// Throw away any remaining cleanups at the end of evaluation. If any
1176 /// cleanups would have had a side-effect, note that as an unmodeled
1177 /// side-effect and return false. Otherwise, return true.
discardCleanups()1178 bool discardCleanups() {
1179 for (Cleanup &C : CleanupStack) {
1180 if (C.hasSideEffect() && !noteSideEffect()) {
1181 CleanupStack.clear();
1182 return false;
1183 }
1184 }
1185 CleanupStack.clear();
1186 return true;
1187 }
1188
1189 private:
getCurrentFrame()1190 interp::Frame *getCurrentFrame() override { return CurrentCall; }
getBottomFrame() const1191 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1192
hasActiveDiagnostic()1193 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
setActiveDiagnostic(bool Flag)1194 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1195
setFoldFailureDiagnostic(bool Flag)1196 void setFoldFailureDiagnostic(bool Flag) override {
1197 HasFoldFailureDiagnostic = Flag;
1198 }
1199
getEvalStatus() const1200 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1201
1202 // If we have a prior diagnostic, it will be noting that the expression
1203 // isn't a constant expression. This diagnostic is more important,
1204 // unless we require this evaluation to produce a constant expression.
1205 //
1206 // FIXME: We might want to show both diagnostics to the user in
1207 // EM_ConstantFold mode.
hasPriorDiagnostic()1208 bool hasPriorDiagnostic() override {
1209 if (!EvalStatus.Diag->empty()) {
1210 switch (EvalMode) {
1211 case EM_ConstantFold:
1212 case EM_IgnoreSideEffects:
1213 if (!HasFoldFailureDiagnostic)
1214 break;
1215 // We've already failed to fold something. Keep that diagnostic.
1216 [[fallthrough]];
1217 case EM_ConstantExpression:
1218 case EM_ConstantExpressionUnevaluated:
1219 setActiveDiagnostic(false);
1220 return true;
1221 }
1222 }
1223 return false;
1224 }
1225
getCallStackDepth()1226 unsigned getCallStackDepth() override { return CallStackDepth; }
1227
1228 public:
1229 /// Should we continue evaluation after encountering a side-effect that we
1230 /// couldn't model?
keepEvaluatingAfterSideEffect() const1231 bool keepEvaluatingAfterSideEffect() const override {
1232 switch (EvalMode) {
1233 case EM_IgnoreSideEffects:
1234 return true;
1235
1236 case EM_ConstantExpression:
1237 case EM_ConstantExpressionUnevaluated:
1238 case EM_ConstantFold:
1239 // By default, assume any side effect might be valid in some other
1240 // evaluation of this expression from a different context.
1241 return checkingPotentialConstantExpression() ||
1242 checkingForUndefinedBehavior();
1243 }
1244 llvm_unreachable("Missed EvalMode case");
1245 }
1246
1247 /// Note that we have had a side-effect, and determine whether we should
1248 /// keep evaluating.
noteSideEffect()1249 bool noteSideEffect() override {
1250 EvalStatus.HasSideEffects = true;
1251 return keepEvaluatingAfterSideEffect();
1252 }
1253
1254 /// Should we continue evaluation after encountering undefined behavior?
keepEvaluatingAfterUndefinedBehavior()1255 bool keepEvaluatingAfterUndefinedBehavior() {
1256 switch (EvalMode) {
1257 case EM_IgnoreSideEffects:
1258 case EM_ConstantFold:
1259 return true;
1260
1261 case EM_ConstantExpression:
1262 case EM_ConstantExpressionUnevaluated:
1263 return checkingForUndefinedBehavior();
1264 }
1265 llvm_unreachable("Missed EvalMode case");
1266 }
1267
1268 /// Note that we hit something that was technically undefined behavior, but
1269 /// that we can evaluate past it (such as signed overflow or floating-point
1270 /// division by zero.)
noteUndefinedBehavior()1271 bool noteUndefinedBehavior() override {
1272 EvalStatus.HasUndefinedBehavior = true;
1273 return keepEvaluatingAfterUndefinedBehavior();
1274 }
1275
1276 /// Should we continue evaluation as much as possible after encountering a
1277 /// construct which can't be reduced to a value?
keepEvaluatingAfterFailure() const1278 bool keepEvaluatingAfterFailure() const override {
1279 if (!StepsLeft)
1280 return false;
1281
1282 switch (EvalMode) {
1283 case EM_ConstantExpression:
1284 case EM_ConstantExpressionUnevaluated:
1285 case EM_ConstantFold:
1286 case EM_IgnoreSideEffects:
1287 return checkingPotentialConstantExpression() ||
1288 checkingForUndefinedBehavior();
1289 }
1290 llvm_unreachable("Missed EvalMode case");
1291 }
1292
1293 /// Notes that we failed to evaluate an expression that other expressions
1294 /// directly depend on, and determine if we should keep evaluating. This
1295 /// should only be called if we actually intend to keep evaluating.
1296 ///
1297 /// Call noteSideEffect() instead if we may be able to ignore the value that
1298 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1299 ///
1300 /// (Foo(), 1) // use noteSideEffect
1301 /// (Foo() || true) // use noteSideEffect
1302 /// Foo() + 1 // use noteFailure
noteFailure()1303 [[nodiscard]] bool noteFailure() {
1304 // Failure when evaluating some expression often means there is some
1305 // subexpression whose evaluation was skipped. Therefore, (because we
1306 // don't track whether we skipped an expression when unwinding after an
1307 // evaluation failure) every evaluation failure that bubbles up from a
1308 // subexpression implies that a side-effect has potentially happened. We
1309 // skip setting the HasSideEffects flag to true until we decide to
1310 // continue evaluating after that point, which happens here.
1311 bool KeepGoing = keepEvaluatingAfterFailure();
1312 EvalStatus.HasSideEffects |= KeepGoing;
1313 return KeepGoing;
1314 }
1315
1316 class ArrayInitLoopIndex {
1317 EvalInfo &Info;
1318 uint64_t OuterIndex;
1319
1320 public:
ArrayInitLoopIndex(EvalInfo & Info)1321 ArrayInitLoopIndex(EvalInfo &Info)
1322 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1323 Info.ArrayInitIndex = 0;
1324 }
~ArrayInitLoopIndex()1325 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1326
operator uint64_t&()1327 operator uint64_t&() { return Info.ArrayInitIndex; }
1328 };
1329 };
1330
1331 /// Object used to treat all foldable expressions as constant expressions.
1332 struct FoldConstant {
1333 EvalInfo &Info;
1334 bool Enabled;
1335 bool HadNoPriorDiags;
1336 EvalInfo::EvaluationMode OldMode;
1337
FoldConstant__anonfb577fba0411::FoldConstant1338 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1339 : Info(Info),
1340 Enabled(Enabled),
1341 HadNoPriorDiags(Info.EvalStatus.Diag &&
1342 Info.EvalStatus.Diag->empty() &&
1343 !Info.EvalStatus.HasSideEffects),
1344 OldMode(Info.EvalMode) {
1345 if (Enabled)
1346 Info.EvalMode = EvalInfo::EM_ConstantFold;
1347 }
keepDiagnostics__anonfb577fba0411::FoldConstant1348 void keepDiagnostics() { Enabled = false; }
~FoldConstant__anonfb577fba0411::FoldConstant1349 ~FoldConstant() {
1350 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1351 !Info.EvalStatus.HasSideEffects)
1352 Info.EvalStatus.Diag->clear();
1353 Info.EvalMode = OldMode;
1354 }
1355 };
1356
1357 /// RAII object used to set the current evaluation mode to ignore
1358 /// side-effects.
1359 struct IgnoreSideEffectsRAII {
1360 EvalInfo &Info;
1361 EvalInfo::EvaluationMode OldMode;
IgnoreSideEffectsRAII__anonfb577fba0411::IgnoreSideEffectsRAII1362 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1363 : Info(Info), OldMode(Info.EvalMode) {
1364 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1365 }
1366
~IgnoreSideEffectsRAII__anonfb577fba0411::IgnoreSideEffectsRAII1367 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1368 };
1369
1370 /// RAII object used to optionally suppress diagnostics and side-effects from
1371 /// a speculative evaluation.
1372 class SpeculativeEvaluationRAII {
1373 EvalInfo *Info = nullptr;
1374 Expr::EvalStatus OldStatus;
1375 unsigned OldSpeculativeEvaluationDepth = 0;
1376
moveFromAndCancel(SpeculativeEvaluationRAII && Other)1377 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1378 Info = Other.Info;
1379 OldStatus = Other.OldStatus;
1380 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1381 Other.Info = nullptr;
1382 }
1383
maybeRestoreState()1384 void maybeRestoreState() {
1385 if (!Info)
1386 return;
1387
1388 Info->EvalStatus = OldStatus;
1389 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1390 }
1391
1392 public:
1393 SpeculativeEvaluationRAII() = default;
1394
SpeculativeEvaluationRAII(EvalInfo & Info,SmallVectorImpl<PartialDiagnosticAt> * NewDiag=nullptr)1395 SpeculativeEvaluationRAII(
1396 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1397 : Info(&Info), OldStatus(Info.EvalStatus),
1398 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1399 Info.EvalStatus.Diag = NewDiag;
1400 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1401 }
1402
1403 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
SpeculativeEvaluationRAII(SpeculativeEvaluationRAII && Other)1404 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1405 moveFromAndCancel(std::move(Other));
1406 }
1407
operator =(SpeculativeEvaluationRAII && Other)1408 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1409 maybeRestoreState();
1410 moveFromAndCancel(std::move(Other));
1411 return *this;
1412 }
1413
~SpeculativeEvaluationRAII()1414 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1415 };
1416
1417 /// RAII object wrapping a full-expression or block scope, and handling
1418 /// the ending of the lifetime of temporaries created within it.
1419 template<ScopeKind Kind>
1420 class ScopeRAII {
1421 EvalInfo &Info;
1422 unsigned OldStackSize;
1423 public:
ScopeRAII(EvalInfo & Info)1424 ScopeRAII(EvalInfo &Info)
1425 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1426 // Push a new temporary version. This is needed to distinguish between
1427 // temporaries created in different iterations of a loop.
1428 Info.CurrentCall->pushTempVersion();
1429 }
destroy(bool RunDestructors=true)1430 bool destroy(bool RunDestructors = true) {
1431 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1432 OldStackSize = std::numeric_limits<unsigned>::max();
1433 return OK;
1434 }
~ScopeRAII()1435 ~ScopeRAII() {
1436 if (OldStackSize != std::numeric_limits<unsigned>::max())
1437 destroy(false);
1438 // Body moved to a static method to encourage the compiler to inline away
1439 // instances of this class.
1440 Info.CurrentCall->popTempVersion();
1441 }
1442 private:
cleanup(EvalInfo & Info,bool RunDestructors,unsigned OldStackSize)1443 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1444 unsigned OldStackSize) {
1445 assert(OldStackSize <= Info.CleanupStack.size() &&
1446 "running cleanups out of order?");
1447
1448 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1449 // for a full-expression scope.
1450 bool Success = true;
1451 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1452 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1453 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1454 Success = false;
1455 break;
1456 }
1457 }
1458 }
1459
1460 // Compact any retained cleanups.
1461 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1462 if (Kind != ScopeKind::Block)
1463 NewEnd =
1464 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1465 return C.isDestroyedAtEndOf(Kind);
1466 });
1467 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1468 return Success;
1469 }
1470 };
1471 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1472 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1473 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1474 }
1475
checkSubobject(EvalInfo & Info,const Expr * E,CheckSubobjectKind CSK)1476 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1477 CheckSubobjectKind CSK) {
1478 if (Invalid)
1479 return false;
1480 if (isOnePastTheEnd()) {
1481 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1482 << CSK;
1483 setInvalid();
1484 return false;
1485 }
1486 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1487 // must actually be at least one array element; even a VLA cannot have a
1488 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1489 return true;
1490 }
1491
diagnoseUnsizedArrayPointerArithmetic(EvalInfo & Info,const Expr * E)1492 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1493 const Expr *E) {
1494 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1495 // Do not set the designator as invalid: we can represent this situation,
1496 // and correct handling of __builtin_object_size requires us to do so.
1497 }
1498
diagnosePointerArithmetic(EvalInfo & Info,const Expr * E,const APSInt & N)1499 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1500 const Expr *E,
1501 const APSInt &N) {
1502 // If we're complaining, we must be able to statically determine the size of
1503 // the most derived array.
1504 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1505 Info.CCEDiag(E, diag::note_constexpr_array_index)
1506 << N << /*array*/ 0
1507 << static_cast<unsigned>(getMostDerivedArraySize());
1508 else
1509 Info.CCEDiag(E, diag::note_constexpr_array_index)
1510 << N << /*non-array*/ 1;
1511 setInvalid();
1512 }
1513
CallStackFrame(EvalInfo & Info,SourceRange CallRange,const FunctionDecl * Callee,const LValue * This,const Expr * CallExpr,CallRef Call)1514 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1515 const FunctionDecl *Callee, const LValue *This,
1516 const Expr *CallExpr, CallRef Call)
1517 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1518 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1519 Index(Info.NextCallIndex++) {
1520 Info.CurrentCall = this;
1521 ++Info.CallStackDepth;
1522 }
1523
~CallStackFrame()1524 CallStackFrame::~CallStackFrame() {
1525 assert(Info.CurrentCall == this && "calls retired out of order");
1526 --Info.CallStackDepth;
1527 Info.CurrentCall = Caller;
1528 }
1529
isRead(AccessKinds AK)1530 static bool isRead(AccessKinds AK) {
1531 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1532 AK == AK_IsWithinLifetime;
1533 }
1534
isModification(AccessKinds AK)1535 static bool isModification(AccessKinds AK) {
1536 switch (AK) {
1537 case AK_Read:
1538 case AK_ReadObjectRepresentation:
1539 case AK_MemberCall:
1540 case AK_DynamicCast:
1541 case AK_TypeId:
1542 case AK_IsWithinLifetime:
1543 return false;
1544 case AK_Assign:
1545 case AK_Increment:
1546 case AK_Decrement:
1547 case AK_Construct:
1548 case AK_Destroy:
1549 return true;
1550 }
1551 llvm_unreachable("unknown access kind");
1552 }
1553
isAnyAccess(AccessKinds AK)1554 static bool isAnyAccess(AccessKinds AK) {
1555 return isRead(AK) || isModification(AK);
1556 }
1557
1558 /// Is this an access per the C++ definition?
isFormalAccess(AccessKinds AK)1559 static bool isFormalAccess(AccessKinds AK) {
1560 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1561 AK != AK_IsWithinLifetime;
1562 }
1563
1564 /// Is this kind of axcess valid on an indeterminate object value?
isValidIndeterminateAccess(AccessKinds AK)1565 static bool isValidIndeterminateAccess(AccessKinds AK) {
1566 switch (AK) {
1567 case AK_Read:
1568 case AK_Increment:
1569 case AK_Decrement:
1570 // These need the object's value.
1571 return false;
1572
1573 case AK_IsWithinLifetime:
1574 case AK_ReadObjectRepresentation:
1575 case AK_Assign:
1576 case AK_Construct:
1577 case AK_Destroy:
1578 // Construction and destruction don't need the value.
1579 return true;
1580
1581 case AK_MemberCall:
1582 case AK_DynamicCast:
1583 case AK_TypeId:
1584 // These aren't really meaningful on scalars.
1585 return true;
1586 }
1587 llvm_unreachable("unknown access kind");
1588 }
1589
1590 namespace {
1591 struct ComplexValue {
1592 private:
1593 bool IsInt;
1594
1595 public:
1596 APSInt IntReal, IntImag;
1597 APFloat FloatReal, FloatImag;
1598
ComplexValue__anonfb577fba0711::ComplexValue1599 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1600
makeComplexFloat__anonfb577fba0711::ComplexValue1601 void makeComplexFloat() { IsInt = false; }
isComplexFloat__anonfb577fba0711::ComplexValue1602 bool isComplexFloat() const { return !IsInt; }
getComplexFloatReal__anonfb577fba0711::ComplexValue1603 APFloat &getComplexFloatReal() { return FloatReal; }
getComplexFloatImag__anonfb577fba0711::ComplexValue1604 APFloat &getComplexFloatImag() { return FloatImag; }
1605
makeComplexInt__anonfb577fba0711::ComplexValue1606 void makeComplexInt() { IsInt = true; }
isComplexInt__anonfb577fba0711::ComplexValue1607 bool isComplexInt() const { return IsInt; }
getComplexIntReal__anonfb577fba0711::ComplexValue1608 APSInt &getComplexIntReal() { return IntReal; }
getComplexIntImag__anonfb577fba0711::ComplexValue1609 APSInt &getComplexIntImag() { return IntImag; }
1610
moveInto__anonfb577fba0711::ComplexValue1611 void moveInto(APValue &v) const {
1612 if (isComplexFloat())
1613 v = APValue(FloatReal, FloatImag);
1614 else
1615 v = APValue(IntReal, IntImag);
1616 }
setFrom__anonfb577fba0711::ComplexValue1617 void setFrom(const APValue &v) {
1618 assert(v.isComplexFloat() || v.isComplexInt());
1619 if (v.isComplexFloat()) {
1620 makeComplexFloat();
1621 FloatReal = v.getComplexFloatReal();
1622 FloatImag = v.getComplexFloatImag();
1623 } else {
1624 makeComplexInt();
1625 IntReal = v.getComplexIntReal();
1626 IntImag = v.getComplexIntImag();
1627 }
1628 }
1629 };
1630
1631 struct LValue {
1632 APValue::LValueBase Base;
1633 CharUnits Offset;
1634 SubobjectDesignator Designator;
1635 bool IsNullPtr : 1;
1636 bool InvalidBase : 1;
1637 // P2280R4 track if we have an unknown reference or pointer.
1638 bool AllowConstexprUnknown = false;
1639
getLValueBase__anonfb577fba0711::LValue1640 const APValue::LValueBase getLValueBase() const { return Base; }
allowConstexprUnknown__anonfb577fba0711::LValue1641 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
getLValueOffset__anonfb577fba0711::LValue1642 CharUnits &getLValueOffset() { return Offset; }
getLValueOffset__anonfb577fba0711::LValue1643 const CharUnits &getLValueOffset() const { return Offset; }
getLValueDesignator__anonfb577fba0711::LValue1644 SubobjectDesignator &getLValueDesignator() { return Designator; }
getLValueDesignator__anonfb577fba0711::LValue1645 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
isNullPointer__anonfb577fba0711::LValue1646 bool isNullPointer() const { return IsNullPtr;}
1647
getLValueCallIndex__anonfb577fba0711::LValue1648 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
getLValueVersion__anonfb577fba0711::LValue1649 unsigned getLValueVersion() const { return Base.getVersion(); }
1650
moveInto__anonfb577fba0711::LValue1651 void moveInto(APValue &V) const {
1652 if (Designator.Invalid)
1653 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1654 else {
1655 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1656 V = APValue(Base, Offset, Designator.Entries,
1657 Designator.IsOnePastTheEnd, IsNullPtr);
1658 }
1659 if (AllowConstexprUnknown)
1660 V.setConstexprUnknown();
1661 }
setFrom__anonfb577fba0711::LValue1662 void setFrom(ASTContext &Ctx, const APValue &V) {
1663 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1664 Base = V.getLValueBase();
1665 Offset = V.getLValueOffset();
1666 InvalidBase = false;
1667 Designator = SubobjectDesignator(Ctx, V);
1668 IsNullPtr = V.isNullPointer();
1669 AllowConstexprUnknown = V.allowConstexprUnknown();
1670 }
1671
set__anonfb577fba0711::LValue1672 void set(APValue::LValueBase B, bool BInvalid = false) {
1673 #ifndef NDEBUG
1674 // We only allow a few types of invalid bases. Enforce that here.
1675 if (BInvalid) {
1676 const auto *E = B.get<const Expr *>();
1677 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1678 "Unexpected type of invalid base");
1679 }
1680 #endif
1681
1682 Base = B;
1683 Offset = CharUnits::fromQuantity(0);
1684 InvalidBase = BInvalid;
1685 Designator = SubobjectDesignator(getType(B));
1686 IsNullPtr = false;
1687 AllowConstexprUnknown = false;
1688 }
1689
setNull__anonfb577fba0711::LValue1690 void setNull(ASTContext &Ctx, QualType PointerTy) {
1691 Base = (const ValueDecl *)nullptr;
1692 Offset =
1693 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1694 InvalidBase = false;
1695 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1696 IsNullPtr = true;
1697 AllowConstexprUnknown = false;
1698 }
1699
setInvalid__anonfb577fba0711::LValue1700 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1701 set(B, true);
1702 }
1703
toString__anonfb577fba0711::LValue1704 std::string toString(ASTContext &Ctx, QualType T) const {
1705 APValue Printable;
1706 moveInto(Printable);
1707 return Printable.getAsString(Ctx, T);
1708 }
1709
1710 private:
1711 // Check that this LValue is not based on a null pointer. If it is, produce
1712 // a diagnostic and mark the designator as invalid.
1713 template <typename GenDiagType>
checkNullPointerDiagnosingWith__anonfb577fba0711::LValue1714 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1715 if (Designator.Invalid)
1716 return false;
1717 if (IsNullPtr) {
1718 GenDiag();
1719 Designator.setInvalid();
1720 return false;
1721 }
1722 return true;
1723 }
1724
1725 public:
checkNullPointer__anonfb577fba0711::LValue1726 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1727 CheckSubobjectKind CSK) {
1728 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1729 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1730 });
1731 }
1732
checkNullPointerForFoldAccess__anonfb577fba0711::LValue1733 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1734 AccessKinds AK) {
1735 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1736 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1737 });
1738 }
1739
1740 // Check this LValue refers to an object. If not, set the designator to be
1741 // invalid and emit a diagnostic.
checkSubobject__anonfb577fba0711::LValue1742 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1743 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1744 Designator.checkSubobject(Info, E, CSK);
1745 }
1746
addDecl__anonfb577fba0711::LValue1747 void addDecl(EvalInfo &Info, const Expr *E,
1748 const Decl *D, bool Virtual = false) {
1749 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1750 Designator.addDeclUnchecked(D, Virtual);
1751 }
addUnsizedArray__anonfb577fba0711::LValue1752 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1753 if (!Designator.Entries.empty()) {
1754 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1755 Designator.setInvalid();
1756 return;
1757 }
1758 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1759 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1760 getType(Base).getNonReferenceType()->isArrayType());
1761 Designator.FirstEntryIsAnUnsizedArray = true;
1762 Designator.addUnsizedArrayUnchecked(ElemTy);
1763 }
1764 }
addArray__anonfb577fba0711::LValue1765 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1766 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1767 Designator.addArrayUnchecked(CAT);
1768 }
addComplex__anonfb577fba0711::LValue1769 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1770 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1771 Designator.addComplexUnchecked(EltTy, Imag);
1772 }
addVectorElement__anonfb577fba0711::LValue1773 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1774 uint64_t Size, uint64_t Idx) {
1775 if (checkSubobject(Info, E, CSK_VectorElement))
1776 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1777 }
clearIsNullPointer__anonfb577fba0711::LValue1778 void clearIsNullPointer() {
1779 IsNullPtr = false;
1780 }
adjustOffsetAndIndex__anonfb577fba0711::LValue1781 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1782 const APSInt &Index, CharUnits ElementSize) {
1783 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1784 // but we're not required to diagnose it and it's valid in C++.)
1785 if (!Index)
1786 return;
1787
1788 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1789 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1790 // offsets.
1791 uint64_t Offset64 = Offset.getQuantity();
1792 uint64_t ElemSize64 = ElementSize.getQuantity();
1793 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1794 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1795
1796 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1797 Designator.adjustIndex(Info, E, Index);
1798 clearIsNullPointer();
1799 }
adjustOffset__anonfb577fba0711::LValue1800 void adjustOffset(CharUnits N) {
1801 Offset += N;
1802 if (N.getQuantity())
1803 clearIsNullPointer();
1804 }
1805 };
1806
1807 struct MemberPtr {
MemberPtr__anonfb577fba0711::MemberPtr1808 MemberPtr() {}
MemberPtr__anonfb577fba0711::MemberPtr1809 explicit MemberPtr(const ValueDecl *Decl)
1810 : DeclAndIsDerivedMember(Decl, false) {}
1811
1812 /// The member or (direct or indirect) field referred to by this member
1813 /// pointer, or 0 if this is a null member pointer.
getDecl__anonfb577fba0711::MemberPtr1814 const ValueDecl *getDecl() const {
1815 return DeclAndIsDerivedMember.getPointer();
1816 }
1817 /// Is this actually a member of some type derived from the relevant class?
isDerivedMember__anonfb577fba0711::MemberPtr1818 bool isDerivedMember() const {
1819 return DeclAndIsDerivedMember.getInt();
1820 }
1821 /// Get the class which the declaration actually lives in.
getContainingRecord__anonfb577fba0711::MemberPtr1822 const CXXRecordDecl *getContainingRecord() const {
1823 return cast<CXXRecordDecl>(
1824 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1825 }
1826
moveInto__anonfb577fba0711::MemberPtr1827 void moveInto(APValue &V) const {
1828 V = APValue(getDecl(), isDerivedMember(), Path);
1829 }
setFrom__anonfb577fba0711::MemberPtr1830 void setFrom(const APValue &V) {
1831 assert(V.isMemberPointer());
1832 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1833 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1834 Path.clear();
1835 llvm::append_range(Path, V.getMemberPointerPath());
1836 }
1837
1838 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1839 /// whether the member is a member of some class derived from the class type
1840 /// of the member pointer.
1841 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1842 /// Path - The path of base/derived classes from the member declaration's
1843 /// class (exclusive) to the class type of the member pointer (inclusive).
1844 SmallVector<const CXXRecordDecl*, 4> Path;
1845
1846 /// Perform a cast towards the class of the Decl (either up or down the
1847 /// hierarchy).
castBack__anonfb577fba0711::MemberPtr1848 bool castBack(const CXXRecordDecl *Class) {
1849 assert(!Path.empty());
1850 const CXXRecordDecl *Expected;
1851 if (Path.size() >= 2)
1852 Expected = Path[Path.size() - 2];
1853 else
1854 Expected = getContainingRecord();
1855 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1856 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1857 // if B does not contain the original member and is not a base or
1858 // derived class of the class containing the original member, the result
1859 // of the cast is undefined.
1860 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1861 // (D::*). We consider that to be a language defect.
1862 return false;
1863 }
1864 Path.pop_back();
1865 return true;
1866 }
1867 /// Perform a base-to-derived member pointer cast.
castToDerived__anonfb577fba0711::MemberPtr1868 bool castToDerived(const CXXRecordDecl *Derived) {
1869 if (!getDecl())
1870 return true;
1871 if (!isDerivedMember()) {
1872 Path.push_back(Derived);
1873 return true;
1874 }
1875 if (!castBack(Derived))
1876 return false;
1877 if (Path.empty())
1878 DeclAndIsDerivedMember.setInt(false);
1879 return true;
1880 }
1881 /// Perform a derived-to-base member pointer cast.
castToBase__anonfb577fba0711::MemberPtr1882 bool castToBase(const CXXRecordDecl *Base) {
1883 if (!getDecl())
1884 return true;
1885 if (Path.empty())
1886 DeclAndIsDerivedMember.setInt(true);
1887 if (isDerivedMember()) {
1888 Path.push_back(Base);
1889 return true;
1890 }
1891 return castBack(Base);
1892 }
1893 };
1894
1895 /// Compare two member pointers, which are assumed to be of the same type.
operator ==(const MemberPtr & LHS,const MemberPtr & RHS)1896 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1897 if (!LHS.getDecl() || !RHS.getDecl())
1898 return !LHS.getDecl() && !RHS.getDecl();
1899 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1900 return false;
1901 return LHS.Path == RHS.Path;
1902 }
1903 }
1904
1905 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1906 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1907 const LValue &This, const Expr *E,
1908 bool AllowNonLiteralTypes = false);
1909 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1910 bool InvalidBaseOK = false);
1911 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1912 bool InvalidBaseOK = false);
1913 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1914 EvalInfo &Info);
1915 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1916 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1917 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1918 EvalInfo &Info);
1919 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1920 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1921 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1922 EvalInfo &Info);
1923 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1924 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1925 EvalInfo &Info,
1926 std::string *StringResult = nullptr);
1927
1928 /// Evaluate an integer or fixed point expression into an APResult.
1929 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1930 EvalInfo &Info);
1931
1932 /// Evaluate only a fixed point expression into an APResult.
1933 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1934 EvalInfo &Info);
1935
1936 //===----------------------------------------------------------------------===//
1937 // Misc utilities
1938 //===----------------------------------------------------------------------===//
1939
1940 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1941 /// preserving its value (by extending by up to one bit as needed).
negateAsSigned(APSInt & Int)1942 static void negateAsSigned(APSInt &Int) {
1943 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1944 Int = Int.extend(Int.getBitWidth() + 1);
1945 Int.setIsSigned(true);
1946 }
1947 Int = -Int;
1948 }
1949
1950 template<typename KeyT>
createTemporary(const KeyT * Key,QualType T,ScopeKind Scope,LValue & LV)1951 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1952 ScopeKind Scope, LValue &LV) {
1953 unsigned Version = getTempVersion();
1954 APValue::LValueBase Base(Key, Index, Version);
1955 LV.set(Base);
1956 return createLocal(Base, Key, T, Scope);
1957 }
1958
1959 /// Allocate storage for a parameter of a function call made in this frame.
createParam(CallRef Args,const ParmVarDecl * PVD,LValue & LV)1960 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1961 LValue &LV) {
1962 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1963 APValue::LValueBase Base(PVD, Index, Args.Version);
1964 LV.set(Base);
1965 // We always destroy parameters at the end of the call, even if we'd allow
1966 // them to live to the end of the full-expression at runtime, in order to
1967 // give portable results and match other compilers.
1968 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1969 }
1970
createLocal(APValue::LValueBase Base,const void * Key,QualType T,ScopeKind Scope)1971 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1972 QualType T, ScopeKind Scope) {
1973 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1974 unsigned Version = Base.getVersion();
1975 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1976 assert(Result.isAbsent() && "local created multiple times");
1977
1978 // If we're creating a local immediately in the operand of a speculative
1979 // evaluation, don't register a cleanup to be run outside the speculative
1980 // evaluation context, since we won't actually be able to initialize this
1981 // object.
1982 if (Index <= Info.SpeculativeEvaluationDepth) {
1983 if (T.isDestructedType())
1984 Info.noteSideEffect();
1985 } else {
1986 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1987 }
1988 return Result;
1989 }
1990
createHeapAlloc(const Expr * E,QualType T,LValue & LV)1991 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1992 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1993 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1994 return nullptr;
1995 }
1996
1997 DynamicAllocLValue DA(NumHeapAllocs++);
1998 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1999 auto Result = HeapAllocs.emplace(std::piecewise_construct,
2000 std::forward_as_tuple(DA), std::tuple<>());
2001 assert(Result.second && "reused a heap alloc index?");
2002 Result.first->second.AllocExpr = E;
2003 return &Result.first->second.Value;
2004 }
2005
2006 /// Produce a string describing the given constexpr call.
describe(raw_ostream & Out) const2007 void CallStackFrame::describe(raw_ostream &Out) const {
2008 unsigned ArgIndex = 0;
2009 bool IsMemberCall =
2010 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
2011 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
2012
2013 if (!IsMemberCall)
2014 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2015 /*Qualified=*/false);
2016
2017 if (This && IsMemberCall) {
2018 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
2019 const Expr *Object = MCE->getImplicitObjectArgument();
2020 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
2021 /*Indentation=*/0);
2022 if (Object->getType()->isPointerType())
2023 Out << "->";
2024 else
2025 Out << ".";
2026 } else if (const auto *OCE =
2027 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
2028 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
2029 Info.Ctx.getPrintingPolicy(),
2030 /*Indentation=*/0);
2031 Out << ".";
2032 } else {
2033 APValue Val;
2034 This->moveInto(Val);
2035 Val.printPretty(
2036 Out, Info.Ctx,
2037 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2038 Out << ".";
2039 }
2040 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2041 /*Qualified=*/false);
2042 IsMemberCall = false;
2043 }
2044
2045 Out << '(';
2046
2047 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2048 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2049 if (ArgIndex > (unsigned)IsMemberCall)
2050 Out << ", ";
2051
2052 const ParmVarDecl *Param = *I;
2053 APValue *V = Info.getParamSlot(Arguments, Param);
2054 if (V)
2055 V->printPretty(Out, Info.Ctx, Param->getType());
2056 else
2057 Out << "<...>";
2058
2059 if (ArgIndex == 0 && IsMemberCall)
2060 Out << "->" << *Callee << '(';
2061 }
2062
2063 Out << ')';
2064 }
2065
2066 /// Evaluate an expression to see if it had side-effects, and discard its
2067 /// result.
2068 /// \return \c true if the caller should keep evaluating.
EvaluateIgnoredValue(EvalInfo & Info,const Expr * E)2069 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2070 assert(!E->isValueDependent());
2071 APValue Scratch;
2072 if (!Evaluate(Scratch, Info, E))
2073 // We don't need the value, but we might have skipped a side effect here.
2074 return Info.noteSideEffect();
2075 return true;
2076 }
2077
2078 /// Should this call expression be treated as forming an opaque constant?
IsOpaqueConstantCall(const CallExpr * E)2079 static bool IsOpaqueConstantCall(const CallExpr *E) {
2080 unsigned Builtin = E->getBuiltinCallee();
2081 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2082 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2083 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2084 Builtin == Builtin::BI__builtin_function_start);
2085 }
2086
IsOpaqueConstantCall(const LValue & LVal)2087 static bool IsOpaqueConstantCall(const LValue &LVal) {
2088 const auto *BaseExpr =
2089 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2090 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2091 }
2092
IsGlobalLValue(APValue::LValueBase B)2093 static bool IsGlobalLValue(APValue::LValueBase B) {
2094 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2095 // constant expression of pointer type that evaluates to...
2096
2097 // ... a null pointer value, or a prvalue core constant expression of type
2098 // std::nullptr_t.
2099 if (!B)
2100 return true;
2101
2102 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2103 // ... the address of an object with static storage duration,
2104 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2105 return VD->hasGlobalStorage();
2106 if (isa<TemplateParamObjectDecl>(D))
2107 return true;
2108 // ... the address of a function,
2109 // ... the address of a GUID [MS extension],
2110 // ... the address of an unnamed global constant
2111 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2112 }
2113
2114 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2115 return true;
2116
2117 const Expr *E = B.get<const Expr*>();
2118 switch (E->getStmtClass()) {
2119 default:
2120 return false;
2121 case Expr::CompoundLiteralExprClass: {
2122 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2123 return CLE->isFileScope() && CLE->isLValue();
2124 }
2125 case Expr::MaterializeTemporaryExprClass:
2126 // A materialized temporary might have been lifetime-extended to static
2127 // storage duration.
2128 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2129 // A string literal has static storage duration.
2130 case Expr::StringLiteralClass:
2131 case Expr::PredefinedExprClass:
2132 case Expr::ObjCStringLiteralClass:
2133 case Expr::ObjCEncodeExprClass:
2134 return true;
2135 case Expr::ObjCBoxedExprClass:
2136 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2137 case Expr::CallExprClass:
2138 return IsOpaqueConstantCall(cast<CallExpr>(E));
2139 // For GCC compatibility, &&label has static storage duration.
2140 case Expr::AddrLabelExprClass:
2141 return true;
2142 // A Block literal expression may be used as the initialization value for
2143 // Block variables at global or local static scope.
2144 case Expr::BlockExprClass:
2145 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2146 // The APValue generated from a __builtin_source_location will be emitted as a
2147 // literal.
2148 case Expr::SourceLocExprClass:
2149 return true;
2150 case Expr::ImplicitValueInitExprClass:
2151 // FIXME:
2152 // We can never form an lvalue with an implicit value initialization as its
2153 // base through expression evaluation, so these only appear in one case: the
2154 // implicit variable declaration we invent when checking whether a constexpr
2155 // constructor can produce a constant expression. We must assume that such
2156 // an expression might be a global lvalue.
2157 return true;
2158 }
2159 }
2160
GetLValueBaseDecl(const LValue & LVal)2161 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2162 return LVal.Base.dyn_cast<const ValueDecl*>();
2163 }
2164
2165 // Information about an LValueBase that is some kind of string.
2166 struct LValueBaseString {
2167 std::string ObjCEncodeStorage;
2168 StringRef Bytes;
2169 int CharWidth;
2170 };
2171
2172 // Gets the lvalue base of LVal as a string.
GetLValueBaseAsString(const EvalInfo & Info,const LValue & LVal,LValueBaseString & AsString)2173 static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2174 LValueBaseString &AsString) {
2175 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2176 if (!BaseExpr)
2177 return false;
2178
2179 // For ObjCEncodeExpr, we need to compute and store the string.
2180 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2181 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2182 AsString.ObjCEncodeStorage);
2183 AsString.Bytes = AsString.ObjCEncodeStorage;
2184 AsString.CharWidth = 1;
2185 return true;
2186 }
2187
2188 // Otherwise, we have a StringLiteral.
2189 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2190 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2191 Lit = PE->getFunctionName();
2192
2193 if (!Lit)
2194 return false;
2195
2196 AsString.Bytes = Lit->getBytes();
2197 AsString.CharWidth = Lit->getCharByteWidth();
2198 return true;
2199 }
2200
2201 // Determine whether two string literals potentially overlap. This will be the
2202 // case if they agree on the values of all the bytes on the overlapping region
2203 // between them.
2204 //
2205 // The overlapping region is the portion of the two string literals that must
2206 // overlap in memory if the pointers actually point to the same address at
2207 // runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2208 // the overlapping region is "cdef\0", which in this case does agree, so the
2209 // strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2210 // "bazbar" + 3, the overlapping region contains all of both strings, so they
2211 // are not potentially overlapping, even though they agree from the given
2212 // addresses onwards.
2213 //
2214 // See open core issue CWG2765 which is discussing the desired rule here.
ArePotentiallyOverlappingStringLiterals(const EvalInfo & Info,const LValue & LHS,const LValue & RHS)2215 static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2216 const LValue &LHS,
2217 const LValue &RHS) {
2218 LValueBaseString LHSString, RHSString;
2219 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2220 !GetLValueBaseAsString(Info, RHS, RHSString))
2221 return false;
2222
2223 // This is the byte offset to the location of the first character of LHS
2224 // within RHS. We don't need to look at the characters of one string that
2225 // would appear before the start of the other string if they were merged.
2226 CharUnits Offset = RHS.Offset - LHS.Offset;
2227 if (Offset.isNegative()) {
2228 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2229 return false;
2230 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2231 } else {
2232 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2233 return false;
2234 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2235 }
2236
2237 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2238 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2239 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2240 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2241
2242 // The null terminator isn't included in the string data, so check for it
2243 // manually. If the longer string doesn't have a null terminator where the
2244 // shorter string ends, they aren't potentially overlapping.
2245 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2246 if (Shorter.size() + NullByte >= Longer.size())
2247 break;
2248 if (Longer[Shorter.size() + NullByte])
2249 return false;
2250 }
2251
2252 // Otherwise, they're potentially overlapping if and only if the overlapping
2253 // region is the same.
2254 return Shorter == Longer.take_front(Shorter.size());
2255 }
2256
IsWeakLValue(const LValue & Value)2257 static bool IsWeakLValue(const LValue &Value) {
2258 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2259 return Decl && Decl->isWeak();
2260 }
2261
isZeroSized(const LValue & Value)2262 static bool isZeroSized(const LValue &Value) {
2263 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2264 if (isa_and_nonnull<VarDecl>(Decl)) {
2265 QualType Ty = Decl->getType();
2266 if (Ty->isArrayType())
2267 return Ty->isIncompleteType() ||
2268 Decl->getASTContext().getTypeSize(Ty) == 0;
2269 }
2270 return false;
2271 }
2272
HasSameBase(const LValue & A,const LValue & B)2273 static bool HasSameBase(const LValue &A, const LValue &B) {
2274 if (!A.getLValueBase())
2275 return !B.getLValueBase();
2276 if (!B.getLValueBase())
2277 return false;
2278
2279 if (A.getLValueBase().getOpaqueValue() !=
2280 B.getLValueBase().getOpaqueValue())
2281 return false;
2282
2283 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2284 A.getLValueVersion() == B.getLValueVersion();
2285 }
2286
NoteLValueLocation(EvalInfo & Info,APValue::LValueBase Base)2287 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2288 assert(Base && "no location for a null lvalue");
2289 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2290
2291 // For a parameter, find the corresponding call stack frame (if it still
2292 // exists), and point at the parameter of the function definition we actually
2293 // invoked.
2294 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2295 unsigned Idx = PVD->getFunctionScopeIndex();
2296 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2297 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2298 F->Arguments.Version == Base.getVersion() && F->Callee &&
2299 Idx < F->Callee->getNumParams()) {
2300 VD = F->Callee->getParamDecl(Idx);
2301 break;
2302 }
2303 }
2304 }
2305
2306 if (VD)
2307 Info.Note(VD->getLocation(), diag::note_declared_at);
2308 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2309 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2310 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2311 // FIXME: Produce a note for dangling pointers too.
2312 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2313 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2314 diag::note_constexpr_dynamic_alloc_here);
2315 }
2316
2317 // We have no information to show for a typeid(T) object.
2318 }
2319
2320 enum class CheckEvaluationResultKind {
2321 ConstantExpression,
2322 FullyInitialized,
2323 };
2324
2325 /// Materialized temporaries that we've already checked to determine if they're
2326 /// initializsed by a constant expression.
2327 using CheckedTemporaries =
2328 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2329
2330 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2331 EvalInfo &Info, SourceLocation DiagLoc,
2332 QualType Type, const APValue &Value,
2333 ConstantExprKind Kind,
2334 const FieldDecl *SubobjectDecl,
2335 CheckedTemporaries &CheckedTemps);
2336
2337 /// Check that this reference or pointer core constant expression is a valid
2338 /// value for an address or reference constant expression. Return true if we
2339 /// can fold this expression, whether or not it's a constant expression.
CheckLValueConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const LValue & LVal,ConstantExprKind Kind,CheckedTemporaries & CheckedTemps)2340 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2341 QualType Type, const LValue &LVal,
2342 ConstantExprKind Kind,
2343 CheckedTemporaries &CheckedTemps) {
2344 bool IsReferenceType = Type->isReferenceType();
2345
2346 APValue::LValueBase Base = LVal.getLValueBase();
2347 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2348
2349 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2350 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2351
2352 // Additional restrictions apply in a template argument. We only enforce the
2353 // C++20 restrictions here; additional syntactic and semantic restrictions
2354 // are applied elsewhere.
2355 if (isTemplateArgument(Kind)) {
2356 int InvalidBaseKind = -1;
2357 StringRef Ident;
2358 if (Base.is<TypeInfoLValue>())
2359 InvalidBaseKind = 0;
2360 else if (isa_and_nonnull<StringLiteral>(BaseE))
2361 InvalidBaseKind = 1;
2362 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2363 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2364 InvalidBaseKind = 2;
2365 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2366 InvalidBaseKind = 3;
2367 Ident = PE->getIdentKindName();
2368 }
2369
2370 if (InvalidBaseKind != -1) {
2371 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2372 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2373 << Ident;
2374 return false;
2375 }
2376 }
2377
2378 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2379 FD && FD->isImmediateFunction()) {
2380 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2381 << !Type->isAnyPointerType();
2382 Info.Note(FD->getLocation(), diag::note_declared_at);
2383 return false;
2384 }
2385
2386 // Check that the object is a global. Note that the fake 'this' object we
2387 // manufacture when checking potential constant expressions is conservatively
2388 // assumed to be global here.
2389 if (!IsGlobalLValue(Base)) {
2390 if (Info.getLangOpts().CPlusPlus11) {
2391 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2392 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2393 << BaseVD;
2394 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2395 if (VarD && VarD->isConstexpr()) {
2396 // Non-static local constexpr variables have unintuitive semantics:
2397 // constexpr int a = 1;
2398 // constexpr const int *p = &a;
2399 // ... is invalid because the address of 'a' is not constant. Suggest
2400 // adding a 'static' in this case.
2401 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2402 << VarD
2403 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2404 } else {
2405 NoteLValueLocation(Info, Base);
2406 }
2407 } else {
2408 Info.FFDiag(Loc);
2409 }
2410 // Don't allow references to temporaries to escape.
2411 return false;
2412 }
2413 assert((Info.checkingPotentialConstantExpression() ||
2414 LVal.getLValueCallIndex() == 0) &&
2415 "have call index for global lvalue");
2416
2417 if (LVal.allowConstexprUnknown()) {
2418 if (BaseVD) {
2419 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2420 NoteLValueLocation(Info, Base);
2421 } else {
2422 Info.FFDiag(Loc);
2423 }
2424 return false;
2425 }
2426
2427 if (Base.is<DynamicAllocLValue>()) {
2428 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2429 << IsReferenceType << !Designator.Entries.empty();
2430 NoteLValueLocation(Info, Base);
2431 return false;
2432 }
2433
2434 if (BaseVD) {
2435 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2436 // Check if this is a thread-local variable.
2437 if (Var->getTLSKind())
2438 // FIXME: Diagnostic!
2439 return false;
2440
2441 // A dllimport variable never acts like a constant, unless we're
2442 // evaluating a value for use only in name mangling.
2443 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2444 // FIXME: Diagnostic!
2445 return false;
2446
2447 // In CUDA/HIP device compilation, only device side variables have
2448 // constant addresses.
2449 if (Info.getASTContext().getLangOpts().CUDA &&
2450 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2451 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2452 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2453 !Var->hasAttr<CUDAConstantAttr>() &&
2454 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2455 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2456 Var->hasAttr<HIPManagedAttr>())
2457 return false;
2458 }
2459 }
2460 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2461 // __declspec(dllimport) must be handled very carefully:
2462 // We must never initialize an expression with the thunk in C++.
2463 // Doing otherwise would allow the same id-expression to yield
2464 // different addresses for the same function in different translation
2465 // units. However, this means that we must dynamically initialize the
2466 // expression with the contents of the import address table at runtime.
2467 //
2468 // The C language has no notion of ODR; furthermore, it has no notion of
2469 // dynamic initialization. This means that we are permitted to
2470 // perform initialization with the address of the thunk.
2471 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2472 FD->hasAttr<DLLImportAttr>())
2473 // FIXME: Diagnostic!
2474 return false;
2475 }
2476 } else if (const auto *MTE =
2477 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2478 if (CheckedTemps.insert(MTE).second) {
2479 QualType TempType = getType(Base);
2480 if (TempType.isDestructedType()) {
2481 Info.FFDiag(MTE->getExprLoc(),
2482 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2483 << TempType;
2484 return false;
2485 }
2486
2487 APValue *V = MTE->getOrCreateValue(false);
2488 assert(V && "evasluation result refers to uninitialised temporary");
2489 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2490 Info, MTE->getExprLoc(), TempType, *V, Kind,
2491 /*SubobjectDecl=*/nullptr, CheckedTemps))
2492 return false;
2493 }
2494 }
2495
2496 // Allow address constant expressions to be past-the-end pointers. This is
2497 // an extension: the standard requires them to point to an object.
2498 if (!IsReferenceType)
2499 return true;
2500
2501 // A reference constant expression must refer to an object.
2502 if (!Base) {
2503 // FIXME: diagnostic
2504 Info.CCEDiag(Loc);
2505 return true;
2506 }
2507
2508 // Does this refer one past the end of some object?
2509 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2510 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2511 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2512 NoteLValueLocation(Info, Base);
2513 }
2514
2515 return true;
2516 }
2517
2518 /// Member pointers are constant expressions unless they point to a
2519 /// non-virtual dllimport member function.
CheckMemberPointerConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const APValue & Value,ConstantExprKind Kind)2520 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2521 SourceLocation Loc,
2522 QualType Type,
2523 const APValue &Value,
2524 ConstantExprKind Kind) {
2525 const ValueDecl *Member = Value.getMemberPointerDecl();
2526 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2527 if (!FD)
2528 return true;
2529 if (FD->isImmediateFunction()) {
2530 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2531 Info.Note(FD->getLocation(), diag::note_declared_at);
2532 return false;
2533 }
2534 return isForManglingOnly(Kind) || FD->isVirtual() ||
2535 !FD->hasAttr<DLLImportAttr>();
2536 }
2537
2538 /// Check that this core constant expression is of literal type, and if not,
2539 /// produce an appropriate diagnostic.
CheckLiteralType(EvalInfo & Info,const Expr * E,const LValue * This=nullptr)2540 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2541 const LValue *This = nullptr) {
2542 // The restriction to literal types does not exist in C++23 anymore.
2543 if (Info.getLangOpts().CPlusPlus23)
2544 return true;
2545
2546 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2547 return true;
2548
2549 // C++1y: A constant initializer for an object o [...] may also invoke
2550 // constexpr constructors for o and its subobjects even if those objects
2551 // are of non-literal class types.
2552 //
2553 // C++11 missed this detail for aggregates, so classes like this:
2554 // struct foo_t { union { int i; volatile int j; } u; };
2555 // are not (obviously) initializable like so:
2556 // __attribute__((__require_constant_initialization__))
2557 // static const foo_t x = {{0}};
2558 // because "i" is a subobject with non-literal initialization (due to the
2559 // volatile member of the union). See:
2560 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2561 // Therefore, we use the C++1y behavior.
2562 if (This && Info.EvaluatingDecl == This->getLValueBase())
2563 return true;
2564
2565 // Prvalue constant expressions must be of literal types.
2566 if (Info.getLangOpts().CPlusPlus11)
2567 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2568 << E->getType();
2569 else
2570 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2571 return false;
2572 }
2573
CheckEvaluationResult(CheckEvaluationResultKind CERK,EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind,const FieldDecl * SubobjectDecl,CheckedTemporaries & CheckedTemps)2574 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2575 EvalInfo &Info, SourceLocation DiagLoc,
2576 QualType Type, const APValue &Value,
2577 ConstantExprKind Kind,
2578 const FieldDecl *SubobjectDecl,
2579 CheckedTemporaries &CheckedTemps) {
2580 if (!Value.hasValue()) {
2581 if (SubobjectDecl) {
2582 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2583 << /*(name)*/ 1 << SubobjectDecl;
2584 Info.Note(SubobjectDecl->getLocation(),
2585 diag::note_constexpr_subobject_declared_here);
2586 } else {
2587 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2588 << /*of type*/ 0 << Type;
2589 }
2590 return false;
2591 }
2592
2593 // We allow _Atomic(T) to be initialized from anything that T can be
2594 // initialized from.
2595 if (const AtomicType *AT = Type->getAs<AtomicType>())
2596 Type = AT->getValueType();
2597
2598 // Core issue 1454: For a literal constant expression of array or class type,
2599 // each subobject of its value shall have been initialized by a constant
2600 // expression.
2601 if (Value.isArray()) {
2602 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2603 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2604 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2605 Value.getArrayInitializedElt(I), Kind,
2606 SubobjectDecl, CheckedTemps))
2607 return false;
2608 }
2609 if (!Value.hasArrayFiller())
2610 return true;
2611 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2612 Value.getArrayFiller(), Kind, SubobjectDecl,
2613 CheckedTemps);
2614 }
2615 if (Value.isUnion() && Value.getUnionField()) {
2616 return CheckEvaluationResult(
2617 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2618 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2619 }
2620 if (Value.isStruct()) {
2621 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2622 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2623 unsigned BaseIndex = 0;
2624 for (const CXXBaseSpecifier &BS : CD->bases()) {
2625 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2626 if (!BaseValue.hasValue()) {
2627 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2628 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2629 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2630 return false;
2631 }
2632 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2633 Kind, /*SubobjectDecl=*/nullptr,
2634 CheckedTemps))
2635 return false;
2636 ++BaseIndex;
2637 }
2638 }
2639 for (const auto *I : RD->fields()) {
2640 if (I->isUnnamedBitField())
2641 continue;
2642
2643 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2644 Value.getStructField(I->getFieldIndex()), Kind,
2645 I, CheckedTemps))
2646 return false;
2647 }
2648 }
2649
2650 if (Value.isLValue() &&
2651 CERK == CheckEvaluationResultKind::ConstantExpression) {
2652 LValue LVal;
2653 LVal.setFrom(Info.Ctx, Value);
2654 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2655 CheckedTemps);
2656 }
2657
2658 if (Value.isMemberPointer() &&
2659 CERK == CheckEvaluationResultKind::ConstantExpression)
2660 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2661
2662 // Everything else is fine.
2663 return true;
2664 }
2665
2666 /// Check that this core constant expression value is a valid value for a
2667 /// constant expression. If not, report an appropriate diagnostic. Does not
2668 /// check that the expression is of literal type.
CheckConstantExpression(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind)2669 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2670 QualType Type, const APValue &Value,
2671 ConstantExprKind Kind) {
2672 // Nothing to check for a constant expression of type 'cv void'.
2673 if (Type->isVoidType())
2674 return true;
2675
2676 CheckedTemporaries CheckedTemps;
2677 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2678 Info, DiagLoc, Type, Value, Kind,
2679 /*SubobjectDecl=*/nullptr, CheckedTemps);
2680 }
2681
2682 /// Check that this evaluated value is fully-initialized and can be loaded by
2683 /// an lvalue-to-rvalue conversion.
CheckFullyInitialized(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value)2684 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2685 QualType Type, const APValue &Value) {
2686 CheckedTemporaries CheckedTemps;
2687 return CheckEvaluationResult(
2688 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2689 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2690 }
2691
2692 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2693 /// "the allocated storage is deallocated within the evaluation".
CheckMemoryLeaks(EvalInfo & Info)2694 static bool CheckMemoryLeaks(EvalInfo &Info) {
2695 if (!Info.HeapAllocs.empty()) {
2696 // We can still fold to a constant despite a compile-time memory leak,
2697 // so long as the heap allocation isn't referenced in the result (we check
2698 // that in CheckConstantExpression).
2699 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2700 diag::note_constexpr_memory_leak)
2701 << unsigned(Info.HeapAllocs.size() - 1);
2702 }
2703 return true;
2704 }
2705
EvalPointerValueAsBool(const APValue & Value,bool & Result)2706 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2707 // A null base expression indicates a null pointer. These are always
2708 // evaluatable, and they are false unless the offset is zero.
2709 if (!Value.getLValueBase()) {
2710 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2711 Result = !Value.getLValueOffset().isZero();
2712 return true;
2713 }
2714
2715 // We have a non-null base. These are generally known to be true, but if it's
2716 // a weak declaration it can be null at runtime.
2717 Result = true;
2718 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2719 return !Decl || !Decl->isWeak();
2720 }
2721
HandleConversionToBool(const APValue & Val,bool & Result)2722 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2723 // TODO: This function should produce notes if it fails.
2724 switch (Val.getKind()) {
2725 case APValue::None:
2726 case APValue::Indeterminate:
2727 return false;
2728 case APValue::Int:
2729 Result = Val.getInt().getBoolValue();
2730 return true;
2731 case APValue::FixedPoint:
2732 Result = Val.getFixedPoint().getBoolValue();
2733 return true;
2734 case APValue::Float:
2735 Result = !Val.getFloat().isZero();
2736 return true;
2737 case APValue::ComplexInt:
2738 Result = Val.getComplexIntReal().getBoolValue() ||
2739 Val.getComplexIntImag().getBoolValue();
2740 return true;
2741 case APValue::ComplexFloat:
2742 Result = !Val.getComplexFloatReal().isZero() ||
2743 !Val.getComplexFloatImag().isZero();
2744 return true;
2745 case APValue::LValue:
2746 return EvalPointerValueAsBool(Val, Result);
2747 case APValue::MemberPointer:
2748 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2749 return false;
2750 }
2751 Result = Val.getMemberPointerDecl();
2752 return true;
2753 case APValue::Vector:
2754 case APValue::Array:
2755 case APValue::Struct:
2756 case APValue::Union:
2757 case APValue::AddrLabelDiff:
2758 return false;
2759 }
2760
2761 llvm_unreachable("unknown APValue kind");
2762 }
2763
EvaluateAsBooleanCondition(const Expr * E,bool & Result,EvalInfo & Info)2764 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2765 EvalInfo &Info) {
2766 assert(!E->isValueDependent());
2767 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2768 APValue Val;
2769 if (!Evaluate(Val, Info, E))
2770 return false;
2771 return HandleConversionToBool(Val, Result);
2772 }
2773
2774 template<typename T>
HandleOverflow(EvalInfo & Info,const Expr * E,const T & SrcValue,QualType DestType)2775 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2776 const T &SrcValue, QualType DestType) {
2777 Info.CCEDiag(E, diag::note_constexpr_overflow)
2778 << SrcValue << DestType;
2779 return Info.noteUndefinedBehavior();
2780 }
2781
HandleFloatToIntCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APFloat & Value,QualType DestType,APSInt & Result)2782 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2783 QualType SrcType, const APFloat &Value,
2784 QualType DestType, APSInt &Result) {
2785 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2786 // Determine whether we are converting to unsigned or signed.
2787 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2788
2789 Result = APSInt(DestWidth, !DestSigned);
2790 bool ignored;
2791 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2792 & APFloat::opInvalidOp)
2793 return HandleOverflow(Info, E, Value, DestType);
2794 return true;
2795 }
2796
2797 /// Get rounding mode to use in evaluation of the specified expression.
2798 ///
2799 /// If rounding mode is unknown at compile time, still try to evaluate the
2800 /// expression. If the result is exact, it does not depend on rounding mode.
2801 /// So return "tonearest" mode instead of "dynamic".
getActiveRoundingMode(EvalInfo & Info,const Expr * E)2802 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2803 llvm::RoundingMode RM =
2804 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2805 if (RM == llvm::RoundingMode::Dynamic)
2806 RM = llvm::RoundingMode::NearestTiesToEven;
2807 return RM;
2808 }
2809
2810 /// Check if the given evaluation result is allowed for constant evaluation.
checkFloatingPointResult(EvalInfo & Info,const Expr * E,APFloat::opStatus St)2811 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2812 APFloat::opStatus St) {
2813 // In a constant context, assume that any dynamic rounding mode or FP
2814 // exception state matches the default floating-point environment.
2815 if (Info.InConstantContext)
2816 return true;
2817
2818 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2819 if ((St & APFloat::opInexact) &&
2820 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2821 // Inexact result means that it depends on rounding mode. If the requested
2822 // mode is dynamic, the evaluation cannot be made in compile time.
2823 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2824 return false;
2825 }
2826
2827 if ((St != APFloat::opOK) &&
2828 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2829 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2830 FPO.getAllowFEnvAccess())) {
2831 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2832 return false;
2833 }
2834
2835 if ((St & APFloat::opStatus::opInvalidOp) &&
2836 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2837 // There is no usefully definable result.
2838 Info.FFDiag(E);
2839 return false;
2840 }
2841
2842 // FIXME: if:
2843 // - evaluation triggered other FP exception, and
2844 // - exception mode is not "ignore", and
2845 // - the expression being evaluated is not a part of global variable
2846 // initializer,
2847 // the evaluation probably need to be rejected.
2848 return true;
2849 }
2850
HandleFloatToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,QualType DestType,APFloat & Result)2851 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2852 QualType SrcType, QualType DestType,
2853 APFloat &Result) {
2854 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2855 isa<ConvertVectorExpr>(E)) &&
2856 "HandleFloatToFloatCast has been checked with only CastExpr, "
2857 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2858 "the new expression or address the root cause of this usage.");
2859 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2860 APFloat::opStatus St;
2861 APFloat Value = Result;
2862 bool ignored;
2863 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2864 return checkFloatingPointResult(Info, E, St);
2865 }
2866
HandleIntToIntCast(EvalInfo & Info,const Expr * E,QualType DestType,QualType SrcType,const APSInt & Value)2867 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2868 QualType DestType, QualType SrcType,
2869 const APSInt &Value) {
2870 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2871 // Figure out if this is a truncate, extend or noop cast.
2872 // If the input is signed, do a sign extend, noop, or truncate.
2873 APSInt Result = Value.extOrTrunc(DestWidth);
2874 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2875 if (DestType->isBooleanType())
2876 Result = Value.getBoolValue();
2877 return Result;
2878 }
2879
HandleIntToFloatCast(EvalInfo & Info,const Expr * E,const FPOptions FPO,QualType SrcType,const APSInt & Value,QualType DestType,APFloat & Result)2880 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2881 const FPOptions FPO,
2882 QualType SrcType, const APSInt &Value,
2883 QualType DestType, APFloat &Result) {
2884 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2885 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2886 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2887 return checkFloatingPointResult(Info, E, St);
2888 }
2889
truncateBitfieldValue(EvalInfo & Info,const Expr * E,APValue & Value,const FieldDecl * FD)2890 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2891 APValue &Value, const FieldDecl *FD) {
2892 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2893
2894 if (!Value.isInt()) {
2895 // Trying to store a pointer-cast-to-integer into a bitfield.
2896 // FIXME: In this case, we should provide the diagnostic for casting
2897 // a pointer to an integer.
2898 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2899 Info.FFDiag(E);
2900 return false;
2901 }
2902
2903 APSInt &Int = Value.getInt();
2904 unsigned OldBitWidth = Int.getBitWidth();
2905 unsigned NewBitWidth = FD->getBitWidthValue();
2906 if (NewBitWidth < OldBitWidth)
2907 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2908 return true;
2909 }
2910
2911 /// Perform the given integer operation, which is known to need at most BitWidth
2912 /// bits, and check for overflow in the original type (if that type was not an
2913 /// unsigned type).
2914 template<typename Operation>
CheckedIntArithmetic(EvalInfo & Info,const Expr * E,const APSInt & LHS,const APSInt & RHS,unsigned BitWidth,Operation Op,APSInt & Result)2915 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2916 const APSInt &LHS, const APSInt &RHS,
2917 unsigned BitWidth, Operation Op,
2918 APSInt &Result) {
2919 if (LHS.isUnsigned()) {
2920 Result = Op(LHS, RHS);
2921 return true;
2922 }
2923
2924 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2925 Result = Value.trunc(LHS.getBitWidth());
2926 if (Result.extend(BitWidth) != Value) {
2927 if (Info.checkingForUndefinedBehavior())
2928 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2929 diag::warn_integer_constant_overflow)
2930 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2931 /*UpperCase=*/true, /*InsertSeparators=*/true)
2932 << E->getType() << E->getSourceRange();
2933 return HandleOverflow(Info, E, Value, E->getType());
2934 }
2935 return true;
2936 }
2937
2938 /// Perform the given binary integer operation.
handleIntIntBinOp(EvalInfo & Info,const BinaryOperator * E,const APSInt & LHS,BinaryOperatorKind Opcode,APSInt RHS,APSInt & Result)2939 static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2940 const APSInt &LHS, BinaryOperatorKind Opcode,
2941 APSInt RHS, APSInt &Result) {
2942 bool HandleOverflowResult = true;
2943 switch (Opcode) {
2944 default:
2945 Info.FFDiag(E);
2946 return false;
2947 case BO_Mul:
2948 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2949 std::multiplies<APSInt>(), Result);
2950 case BO_Add:
2951 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2952 std::plus<APSInt>(), Result);
2953 case BO_Sub:
2954 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2955 std::minus<APSInt>(), Result);
2956 case BO_And: Result = LHS & RHS; return true;
2957 case BO_Xor: Result = LHS ^ RHS; return true;
2958 case BO_Or: Result = LHS | RHS; return true;
2959 case BO_Div:
2960 case BO_Rem:
2961 if (RHS == 0) {
2962 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2963 << E->getRHS()->getSourceRange();
2964 return false;
2965 }
2966 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2967 // this operation and gives the two's complement result.
2968 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2969 LHS.isMinSignedValue())
2970 HandleOverflowResult = HandleOverflow(
2971 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2972 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2973 return HandleOverflowResult;
2974 case BO_Shl: {
2975 if (Info.getLangOpts().OpenCL)
2976 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2977 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2978 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2979 RHS.isUnsigned());
2980 else if (RHS.isSigned() && RHS.isNegative()) {
2981 // During constant-folding, a negative shift is an opposite shift. Such
2982 // a shift is not a constant expression.
2983 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2984 if (!Info.noteUndefinedBehavior())
2985 return false;
2986 RHS = -RHS;
2987 goto shift_right;
2988 }
2989 shift_left:
2990 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2991 // the shifted type.
2992 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2993 if (SA != RHS) {
2994 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2995 << RHS << E->getType() << LHS.getBitWidth();
2996 if (!Info.noteUndefinedBehavior())
2997 return false;
2998 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2999 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
3000 // operand, and must not overflow the corresponding unsigned type.
3001 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
3002 // E1 x 2^E2 module 2^N.
3003 if (LHS.isNegative()) {
3004 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
3005 if (!Info.noteUndefinedBehavior())
3006 return false;
3007 } else if (LHS.countl_zero() < SA) {
3008 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
3009 if (!Info.noteUndefinedBehavior())
3010 return false;
3011 }
3012 }
3013 Result = LHS << SA;
3014 return true;
3015 }
3016 case BO_Shr: {
3017 if (Info.getLangOpts().OpenCL)
3018 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3019 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
3020 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
3021 RHS.isUnsigned());
3022 else if (RHS.isSigned() && RHS.isNegative()) {
3023 // During constant-folding, a negative shift is an opposite shift. Such a
3024 // shift is not a constant expression.
3025 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
3026 if (!Info.noteUndefinedBehavior())
3027 return false;
3028 RHS = -RHS;
3029 goto shift_left;
3030 }
3031 shift_right:
3032 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3033 // shifted type.
3034 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3035 if (SA != RHS) {
3036 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3037 << RHS << E->getType() << LHS.getBitWidth();
3038 if (!Info.noteUndefinedBehavior())
3039 return false;
3040 }
3041
3042 Result = LHS >> SA;
3043 return true;
3044 }
3045
3046 case BO_LT: Result = LHS < RHS; return true;
3047 case BO_GT: Result = LHS > RHS; return true;
3048 case BO_LE: Result = LHS <= RHS; return true;
3049 case BO_GE: Result = LHS >= RHS; return true;
3050 case BO_EQ: Result = LHS == RHS; return true;
3051 case BO_NE: Result = LHS != RHS; return true;
3052 case BO_Cmp:
3053 llvm_unreachable("BO_Cmp should be handled elsewhere");
3054 }
3055 }
3056
3057 /// Perform the given binary floating-point operation, in-place, on LHS.
handleFloatFloatBinOp(EvalInfo & Info,const BinaryOperator * E,APFloat & LHS,BinaryOperatorKind Opcode,const APFloat & RHS)3058 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3059 APFloat &LHS, BinaryOperatorKind Opcode,
3060 const APFloat &RHS) {
3061 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3062 APFloat::opStatus St;
3063 switch (Opcode) {
3064 default:
3065 Info.FFDiag(E);
3066 return false;
3067 case BO_Mul:
3068 St = LHS.multiply(RHS, RM);
3069 break;
3070 case BO_Add:
3071 St = LHS.add(RHS, RM);
3072 break;
3073 case BO_Sub:
3074 St = LHS.subtract(RHS, RM);
3075 break;
3076 case BO_Div:
3077 // [expr.mul]p4:
3078 // If the second operand of / or % is zero the behavior is undefined.
3079 if (RHS.isZero())
3080 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3081 St = LHS.divide(RHS, RM);
3082 break;
3083 }
3084
3085 // [expr.pre]p4:
3086 // If during the evaluation of an expression, the result is not
3087 // mathematically defined [...], the behavior is undefined.
3088 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3089 if (LHS.isNaN()) {
3090 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3091 return Info.noteUndefinedBehavior();
3092 }
3093
3094 return checkFloatingPointResult(Info, E, St);
3095 }
3096
handleLogicalOpForVector(const APInt & LHSValue,BinaryOperatorKind Opcode,const APInt & RHSValue,APInt & Result)3097 static bool handleLogicalOpForVector(const APInt &LHSValue,
3098 BinaryOperatorKind Opcode,
3099 const APInt &RHSValue, APInt &Result) {
3100 bool LHS = (LHSValue != 0);
3101 bool RHS = (RHSValue != 0);
3102
3103 if (Opcode == BO_LAnd)
3104 Result = LHS && RHS;
3105 else
3106 Result = LHS || RHS;
3107 return true;
3108 }
handleLogicalOpForVector(const APFloat & LHSValue,BinaryOperatorKind Opcode,const APFloat & RHSValue,APInt & Result)3109 static bool handleLogicalOpForVector(const APFloat &LHSValue,
3110 BinaryOperatorKind Opcode,
3111 const APFloat &RHSValue, APInt &Result) {
3112 bool LHS = !LHSValue.isZero();
3113 bool RHS = !RHSValue.isZero();
3114
3115 if (Opcode == BO_LAnd)
3116 Result = LHS && RHS;
3117 else
3118 Result = LHS || RHS;
3119 return true;
3120 }
3121
handleLogicalOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)3122 static bool handleLogicalOpForVector(const APValue &LHSValue,
3123 BinaryOperatorKind Opcode,
3124 const APValue &RHSValue, APInt &Result) {
3125 // The result is always an int type, however operands match the first.
3126 if (LHSValue.getKind() == APValue::Int)
3127 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3128 RHSValue.getInt(), Result);
3129 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3130 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3131 RHSValue.getFloat(), Result);
3132 }
3133
3134 template <typename APTy>
3135 static bool
handleCompareOpForVectorHelper(const APTy & LHSValue,BinaryOperatorKind Opcode,const APTy & RHSValue,APInt & Result)3136 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
3137 const APTy &RHSValue, APInt &Result) {
3138 switch (Opcode) {
3139 default:
3140 llvm_unreachable("unsupported binary operator");
3141 case BO_EQ:
3142 Result = (LHSValue == RHSValue);
3143 break;
3144 case BO_NE:
3145 Result = (LHSValue != RHSValue);
3146 break;
3147 case BO_LT:
3148 Result = (LHSValue < RHSValue);
3149 break;
3150 case BO_GT:
3151 Result = (LHSValue > RHSValue);
3152 break;
3153 case BO_LE:
3154 Result = (LHSValue <= RHSValue);
3155 break;
3156 case BO_GE:
3157 Result = (LHSValue >= RHSValue);
3158 break;
3159 }
3160
3161 // The boolean operations on these vector types use an instruction that
3162 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3163 // to -1 to make sure that we produce the correct value.
3164 Result.negate();
3165
3166 return true;
3167 }
3168
handleCompareOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)3169 static bool handleCompareOpForVector(const APValue &LHSValue,
3170 BinaryOperatorKind Opcode,
3171 const APValue &RHSValue, APInt &Result) {
3172 // The result is always an int type, however operands match the first.
3173 if (LHSValue.getKind() == APValue::Int)
3174 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3175 RHSValue.getInt(), Result);
3176 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3177 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3178 RHSValue.getFloat(), Result);
3179 }
3180
3181 // Perform binary operations for vector types, in place on the LHS.
handleVectorVectorBinOp(EvalInfo & Info,const BinaryOperator * E,BinaryOperatorKind Opcode,APValue & LHSValue,const APValue & RHSValue)3182 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3183 BinaryOperatorKind Opcode,
3184 APValue &LHSValue,
3185 const APValue &RHSValue) {
3186 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3187 "Operation not supported on vector types");
3188
3189 const auto *VT = E->getType()->castAs<VectorType>();
3190 unsigned NumElements = VT->getNumElements();
3191 QualType EltTy = VT->getElementType();
3192
3193 // In the cases (typically C as I've observed) where we aren't evaluating
3194 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3195 // just give up.
3196 if (!LHSValue.isVector()) {
3197 assert(LHSValue.isLValue() &&
3198 "A vector result that isn't a vector OR uncalculated LValue");
3199 Info.FFDiag(E);
3200 return false;
3201 }
3202
3203 assert(LHSValue.getVectorLength() == NumElements &&
3204 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3205
3206 SmallVector<APValue, 4> ResultElements;
3207
3208 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3209 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3210 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3211
3212 if (EltTy->isIntegerType()) {
3213 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3214 EltTy->isUnsignedIntegerType()};
3215 bool Success = true;
3216
3217 if (BinaryOperator::isLogicalOp(Opcode))
3218 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3219 else if (BinaryOperator::isComparisonOp(Opcode))
3220 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3221 else
3222 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3223 RHSElt.getInt(), EltResult);
3224
3225 if (!Success) {
3226 Info.FFDiag(E);
3227 return false;
3228 }
3229 ResultElements.emplace_back(EltResult);
3230
3231 } else if (EltTy->isFloatingType()) {
3232 assert(LHSElt.getKind() == APValue::Float &&
3233 RHSElt.getKind() == APValue::Float &&
3234 "Mismatched LHS/RHS/Result Type");
3235 APFloat LHSFloat = LHSElt.getFloat();
3236
3237 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3238 RHSElt.getFloat())) {
3239 Info.FFDiag(E);
3240 return false;
3241 }
3242
3243 ResultElements.emplace_back(LHSFloat);
3244 }
3245 }
3246
3247 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3248 return true;
3249 }
3250
3251 /// Cast an lvalue referring to a base subobject to a derived class, by
3252 /// truncating the lvalue's path to the given length.
CastToDerivedClass(EvalInfo & Info,const Expr * E,LValue & Result,const RecordDecl * TruncatedType,unsigned TruncatedElements)3253 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3254 const RecordDecl *TruncatedType,
3255 unsigned TruncatedElements) {
3256 SubobjectDesignator &D = Result.Designator;
3257
3258 // Check we actually point to a derived class object.
3259 if (TruncatedElements == D.Entries.size())
3260 return true;
3261 assert(TruncatedElements >= D.MostDerivedPathLength &&
3262 "not casting to a derived class");
3263 if (!Result.checkSubobject(Info, E, CSK_Derived))
3264 return false;
3265
3266 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3267 const RecordDecl *RD = TruncatedType;
3268 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3269 if (RD->isInvalidDecl()) return false;
3270 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3271 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3272 if (isVirtualBaseClass(D.Entries[I]))
3273 Result.Offset -= Layout.getVBaseClassOffset(Base);
3274 else
3275 Result.Offset -= Layout.getBaseClassOffset(Base);
3276 RD = Base;
3277 }
3278 D.Entries.resize(TruncatedElements);
3279 return true;
3280 }
3281
HandleLValueDirectBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,const ASTRecordLayout * RL=nullptr)3282 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3283 const CXXRecordDecl *Derived,
3284 const CXXRecordDecl *Base,
3285 const ASTRecordLayout *RL = nullptr) {
3286 if (!RL) {
3287 if (Derived->isInvalidDecl()) return false;
3288 RL = &Info.Ctx.getASTRecordLayout(Derived);
3289 }
3290
3291 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3292 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3293 return true;
3294 }
3295
HandleLValueBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * DerivedDecl,const CXXBaseSpecifier * Base)3296 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3297 const CXXRecordDecl *DerivedDecl,
3298 const CXXBaseSpecifier *Base) {
3299 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3300
3301 if (!Base->isVirtual())
3302 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3303
3304 SubobjectDesignator &D = Obj.Designator;
3305 if (D.Invalid)
3306 return false;
3307
3308 // Extract most-derived object and corresponding type.
3309 // FIXME: After implementing P2280R4 it became possible to get references
3310 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3311 // locations and if we see crashes in those locations in the future
3312 // it may make more sense to move this fix into Lvalue::set.
3313 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3314 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3315 return false;
3316
3317 // Find the virtual base class.
3318 if (DerivedDecl->isInvalidDecl()) return false;
3319 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3320 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3321 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3322 return true;
3323 }
3324
HandleLValueBasePath(EvalInfo & Info,const CastExpr * E,QualType Type,LValue & Result)3325 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3326 QualType Type, LValue &Result) {
3327 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3328 PathE = E->path_end();
3329 PathI != PathE; ++PathI) {
3330 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3331 *PathI))
3332 return false;
3333 Type = (*PathI)->getType();
3334 }
3335 return true;
3336 }
3337
3338 /// Cast an lvalue referring to a derived class to a known base subobject.
CastToBaseClass(EvalInfo & Info,const Expr * E,LValue & Result,const CXXRecordDecl * DerivedRD,const CXXRecordDecl * BaseRD)3339 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3340 const CXXRecordDecl *DerivedRD,
3341 const CXXRecordDecl *BaseRD) {
3342 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3343 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3344 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3345 llvm_unreachable("Class must be derived from the passed in base class!");
3346
3347 for (CXXBasePathElement &Elem : Paths.front())
3348 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3349 return false;
3350 return true;
3351 }
3352
3353 /// Update LVal to refer to the given field, which must be a member of the type
3354 /// currently described by LVal.
HandleLValueMember(EvalInfo & Info,const Expr * E,LValue & LVal,const FieldDecl * FD,const ASTRecordLayout * RL=nullptr)3355 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3356 const FieldDecl *FD,
3357 const ASTRecordLayout *RL = nullptr) {
3358 if (!RL) {
3359 if (FD->getParent()->isInvalidDecl()) return false;
3360 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3361 }
3362
3363 unsigned I = FD->getFieldIndex();
3364 LVal.addDecl(Info, E, FD);
3365 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3366 return true;
3367 }
3368
3369 /// Update LVal to refer to the given indirect field.
HandleLValueIndirectMember(EvalInfo & Info,const Expr * E,LValue & LVal,const IndirectFieldDecl * IFD)3370 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3371 LValue &LVal,
3372 const IndirectFieldDecl *IFD) {
3373 for (const auto *C : IFD->chain())
3374 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3375 return false;
3376 return true;
3377 }
3378
3379 enum class SizeOfType {
3380 SizeOf,
3381 DataSizeOf,
3382 };
3383
3384 /// Get the size of the given type in char units.
HandleSizeof(EvalInfo & Info,SourceLocation Loc,QualType Type,CharUnits & Size,SizeOfType SOT=SizeOfType::SizeOf)3385 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3386 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3387 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3388 // extension.
3389 if (Type->isVoidType() || Type->isFunctionType()) {
3390 Size = CharUnits::One();
3391 return true;
3392 }
3393
3394 if (Type->isDependentType()) {
3395 Info.FFDiag(Loc);
3396 return false;
3397 }
3398
3399 if (!Type->isConstantSizeType()) {
3400 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3401 // FIXME: Better diagnostic.
3402 Info.FFDiag(Loc);
3403 return false;
3404 }
3405
3406 if (SOT == SizeOfType::SizeOf)
3407 Size = Info.Ctx.getTypeSizeInChars(Type);
3408 else
3409 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3410 return true;
3411 }
3412
3413 /// Update a pointer value to model pointer arithmetic.
3414 /// \param Info - Information about the ongoing evaluation.
3415 /// \param E - The expression being evaluated, for diagnostic purposes.
3416 /// \param LVal - The pointer value to be updated.
3417 /// \param EltTy - The pointee type represented by LVal.
3418 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,APSInt Adjustment)3419 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3420 LValue &LVal, QualType EltTy,
3421 APSInt Adjustment) {
3422 CharUnits SizeOfPointee;
3423 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3424 return false;
3425
3426 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3427 return true;
3428 }
3429
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,int64_t Adjustment)3430 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3431 LValue &LVal, QualType EltTy,
3432 int64_t Adjustment) {
3433 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3434 APSInt::get(Adjustment));
3435 }
3436
3437 /// Update an lvalue to refer to a component of a complex number.
3438 /// \param Info - Information about the ongoing evaluation.
3439 /// \param LVal - The lvalue to be updated.
3440 /// \param EltTy - The complex number's component type.
3441 /// \param Imag - False for the real component, true for the imaginary.
HandleLValueComplexElement(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,bool Imag)3442 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3443 LValue &LVal, QualType EltTy,
3444 bool Imag) {
3445 if (Imag) {
3446 CharUnits SizeOfComponent;
3447 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3448 return false;
3449 LVal.Offset += SizeOfComponent;
3450 }
3451 LVal.addComplex(Info, E, EltTy, Imag);
3452 return true;
3453 }
3454
HandleLValueVectorElement(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,uint64_t Size,uint64_t Idx)3455 static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3456 LValue &LVal, QualType EltTy,
3457 uint64_t Size, uint64_t Idx) {
3458 if (Idx) {
3459 CharUnits SizeOfElement;
3460 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3461 return false;
3462 LVal.Offset += SizeOfElement * Idx;
3463 }
3464 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3465 return true;
3466 }
3467
3468 /// Try to evaluate the initializer for a variable declaration.
3469 ///
3470 /// \param Info Information about the ongoing evaluation.
3471 /// \param E An expression to be used when printing diagnostics.
3472 /// \param VD The variable whose initializer should be obtained.
3473 /// \param Version The version of the variable within the frame.
3474 /// \param Frame The frame in which the variable was created. Must be null
3475 /// if this variable is not local to the evaluation.
3476 /// \param Result Filled in with a pointer to the value of the variable.
evaluateVarDeclInit(EvalInfo & Info,const Expr * E,const VarDecl * VD,CallStackFrame * Frame,unsigned Version,APValue * & Result)3477 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3478 const VarDecl *VD, CallStackFrame *Frame,
3479 unsigned Version, APValue *&Result) {
3480 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3481 // and pointers.
3482 bool AllowConstexprUnknown =
3483 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3484
3485 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3486
3487 auto CheckUninitReference = [&](bool IsLocalVariable) {
3488 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3489 // C++23 [expr.const]p8
3490 // ... For such an object that is not usable in constant expressions, the
3491 // dynamic type of the object is constexpr-unknown. For such a reference
3492 // that is not usable in constant expressions, the reference is treated
3493 // as binding to an unspecified object of the referenced type whose
3494 // lifetime and that of all subobjects includes the entire constant
3495 // evaluation and whose dynamic type is constexpr-unknown.
3496 //
3497 // Variables that are part of the current evaluation are not
3498 // constexpr-unknown.
3499 if (!AllowConstexprUnknown || IsLocalVariable) {
3500 if (!Info.checkingPotentialConstantExpression())
3501 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3502 return false;
3503 }
3504 Result = nullptr;
3505 }
3506 return true;
3507 };
3508
3509 // If this is a local variable, dig out its value.
3510 if (Frame) {
3511 Result = Frame->getTemporary(VD, Version);
3512 if (Result)
3513 return CheckUninitReference(/*IsLocalVariable=*/true);
3514
3515 if (!isa<ParmVarDecl>(VD)) {
3516 // Assume variables referenced within a lambda's call operator that were
3517 // not declared within the call operator are captures and during checking
3518 // of a potential constant expression, assume they are unknown constant
3519 // expressions.
3520 assert(isLambdaCallOperator(Frame->Callee) &&
3521 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3522 "missing value for local variable");
3523 if (Info.checkingPotentialConstantExpression())
3524 return false;
3525 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3526 // still reachable at all?
3527 Info.FFDiag(E->getBeginLoc(),
3528 diag::note_unimplemented_constexpr_lambda_feature_ast)
3529 << "captures not currently allowed";
3530 return false;
3531 }
3532 }
3533
3534 // If we're currently evaluating the initializer of this declaration, use that
3535 // in-flight value.
3536 if (Info.EvaluatingDecl == Base) {
3537 Result = Info.EvaluatingDeclValue;
3538 return CheckUninitReference(/*IsLocalVariable=*/false);
3539 }
3540
3541 // P2280R4 struck the restriction that variable of reference type lifetime
3542 // should begin within the evaluation of E
3543 // Used to be C++20 [expr.const]p5.12.2:
3544 // ... its lifetime began within the evaluation of E;
3545 if (isa<ParmVarDecl>(VD)) {
3546 if (AllowConstexprUnknown) {
3547 Result = nullptr;
3548 return true;
3549 }
3550
3551 // Assume parameters of a potential constant expression are usable in
3552 // constant expressions.
3553 if (!Info.checkingPotentialConstantExpression() ||
3554 !Info.CurrentCall->Callee ||
3555 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3556 if (Info.getLangOpts().CPlusPlus11) {
3557 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3558 << VD;
3559 NoteLValueLocation(Info, Base);
3560 } else {
3561 Info.FFDiag(E);
3562 }
3563 }
3564 return false;
3565 }
3566
3567 if (E->isValueDependent())
3568 return false;
3569
3570 // Dig out the initializer, and use the declaration which it's attached to.
3571 // FIXME: We should eventually check whether the variable has a reachable
3572 // initializing declaration.
3573 const Expr *Init = VD->getAnyInitializer(VD);
3574 // P2280R4 struck the restriction that variable of reference type should have
3575 // a preceding initialization.
3576 // Used to be C++20 [expr.const]p5.12:
3577 // ... reference has a preceding initialization and either ...
3578 if (!Init && !AllowConstexprUnknown) {
3579 // Don't diagnose during potential constant expression checking; an
3580 // initializer might be added later.
3581 if (!Info.checkingPotentialConstantExpression()) {
3582 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3583 << VD;
3584 NoteLValueLocation(Info, Base);
3585 }
3586 return false;
3587 }
3588
3589 // P2280R4 struck the initialization requirement for variables of reference
3590 // type so we can no longer assume we have an Init.
3591 // Used to be C++20 [expr.const]p5.12:
3592 // ... reference has a preceding initialization and either ...
3593 if (Init && Init->isValueDependent()) {
3594 // The DeclRefExpr is not value-dependent, but the variable it refers to
3595 // has a value-dependent initializer. This should only happen in
3596 // constant-folding cases, where the variable is not actually of a suitable
3597 // type for use in a constant expression (otherwise the DeclRefExpr would
3598 // have been value-dependent too), so diagnose that.
3599 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3600 if (!Info.checkingPotentialConstantExpression()) {
3601 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3602 ? diag::note_constexpr_ltor_non_constexpr
3603 : diag::note_constexpr_ltor_non_integral, 1)
3604 << VD << VD->getType();
3605 NoteLValueLocation(Info, Base);
3606 }
3607 return false;
3608 }
3609
3610 // Check that we can fold the initializer. In C++, we will have already done
3611 // this in the cases where it matters for conformance.
3612 // P2280R4 struck the initialization requirement for variables of reference
3613 // type so we can no longer assume we have an Init.
3614 // Used to be C++20 [expr.const]p5.12:
3615 // ... reference has a preceding initialization and either ...
3616 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3617 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3618 NoteLValueLocation(Info, Base);
3619 return false;
3620 }
3621
3622 // Check that the variable is actually usable in constant expressions. For a
3623 // const integral variable or a reference, we might have a non-constant
3624 // initializer that we can nonetheless evaluate the initializer for. Such
3625 // variables are not usable in constant expressions. In C++98, the
3626 // initializer also syntactically needs to be an ICE.
3627 //
3628 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3629 // expressions here; doing so would regress diagnostics for things like
3630 // reading from a volatile constexpr variable.
3631 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3632 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3633 !AllowConstexprUnknown) ||
3634 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3635 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3636 if (Init) {
3637 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3638 NoteLValueLocation(Info, Base);
3639 } else {
3640 Info.CCEDiag(E);
3641 }
3642 }
3643
3644 // Never use the initializer of a weak variable, not even for constant
3645 // folding. We can't be sure that this is the definition that will be used.
3646 if (VD->isWeak()) {
3647 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3648 NoteLValueLocation(Info, Base);
3649 return false;
3650 }
3651
3652 Result = VD->getEvaluatedValue();
3653
3654 if (!Result && !AllowConstexprUnknown)
3655 return false;
3656
3657 return CheckUninitReference(/*IsLocalVariable=*/false);
3658 }
3659
3660 /// Get the base index of the given base class within an APValue representing
3661 /// the given derived class.
getBaseIndex(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)3662 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3663 const CXXRecordDecl *Base) {
3664 Base = Base->getCanonicalDecl();
3665 unsigned Index = 0;
3666 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3667 E = Derived->bases_end(); I != E; ++I, ++Index) {
3668 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3669 return Index;
3670 }
3671
3672 llvm_unreachable("base class missing from derived class's bases list");
3673 }
3674
3675 /// Extract the value of a character from a string literal.
extractStringLiteralCharacter(EvalInfo & Info,const Expr * Lit,uint64_t Index)3676 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3677 uint64_t Index) {
3678 assert(!isa<SourceLocExpr>(Lit) &&
3679 "SourceLocExpr should have already been converted to a StringLiteral");
3680
3681 // FIXME: Support MakeStringConstant
3682 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3683 std::string Str;
3684 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3685 assert(Index <= Str.size() && "Index too large");
3686 return APSInt::getUnsigned(Str.c_str()[Index]);
3687 }
3688
3689 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3690 Lit = PE->getFunctionName();
3691 const StringLiteral *S = cast<StringLiteral>(Lit);
3692 const ConstantArrayType *CAT =
3693 Info.Ctx.getAsConstantArrayType(S->getType());
3694 assert(CAT && "string literal isn't an array");
3695 QualType CharType = CAT->getElementType();
3696 assert(CharType->isIntegerType() && "unexpected character type");
3697 APSInt Value(Info.Ctx.getTypeSize(CharType),
3698 CharType->isUnsignedIntegerType());
3699 if (Index < S->getLength())
3700 Value = S->getCodeUnit(Index);
3701 return Value;
3702 }
3703
3704 // Expand a string literal into an array of characters.
3705 //
3706 // FIXME: This is inefficient; we should probably introduce something similar
3707 // to the LLVM ConstantDataArray to make this cheaper.
expandStringLiteral(EvalInfo & Info,const StringLiteral * S,APValue & Result,QualType AllocType=QualType ())3708 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3709 APValue &Result,
3710 QualType AllocType = QualType()) {
3711 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3712 AllocType.isNull() ? S->getType() : AllocType);
3713 assert(CAT && "string literal isn't an array");
3714 QualType CharType = CAT->getElementType();
3715 assert(CharType->isIntegerType() && "unexpected character type");
3716
3717 unsigned Elts = CAT->getZExtSize();
3718 Result = APValue(APValue::UninitArray(),
3719 std::min(S->getLength(), Elts), Elts);
3720 APSInt Value(Info.Ctx.getTypeSize(CharType),
3721 CharType->isUnsignedIntegerType());
3722 if (Result.hasArrayFiller())
3723 Result.getArrayFiller() = APValue(Value);
3724 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3725 Value = S->getCodeUnit(I);
3726 Result.getArrayInitializedElt(I) = APValue(Value);
3727 }
3728 }
3729
3730 // Expand an array so that it has more than Index filled elements.
expandArray(APValue & Array,unsigned Index)3731 static void expandArray(APValue &Array, unsigned Index) {
3732 unsigned Size = Array.getArraySize();
3733 assert(Index < Size);
3734
3735 // Always at least double the number of elements for which we store a value.
3736 unsigned OldElts = Array.getArrayInitializedElts();
3737 unsigned NewElts = std::max(Index+1, OldElts * 2);
3738 NewElts = std::min(Size, std::max(NewElts, 8u));
3739
3740 // Copy the data across.
3741 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3742 for (unsigned I = 0; I != OldElts; ++I)
3743 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3744 for (unsigned I = OldElts; I != NewElts; ++I)
3745 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3746 if (NewValue.hasArrayFiller())
3747 NewValue.getArrayFiller() = Array.getArrayFiller();
3748 Array.swap(NewValue);
3749 }
3750
3751 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3752 /// conversion. If it's of class type, we may assume that the copy operation
3753 /// is trivial. Note that this is never true for a union type with fields
3754 /// (because the copy always "reads" the active member) and always true for
3755 /// a non-class type.
3756 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
isReadByLvalueToRvalueConversion(QualType T)3757 static bool isReadByLvalueToRvalueConversion(QualType T) {
3758 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3759 return !RD || isReadByLvalueToRvalueConversion(RD);
3760 }
isReadByLvalueToRvalueConversion(const CXXRecordDecl * RD)3761 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3762 // FIXME: A trivial copy of a union copies the object representation, even if
3763 // the union is empty.
3764 if (RD->isUnion())
3765 return !RD->field_empty();
3766 if (RD->isEmpty())
3767 return false;
3768
3769 for (auto *Field : RD->fields())
3770 if (!Field->isUnnamedBitField() &&
3771 isReadByLvalueToRvalueConversion(Field->getType()))
3772 return true;
3773
3774 for (auto &BaseSpec : RD->bases())
3775 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3776 return true;
3777
3778 return false;
3779 }
3780
3781 /// Diagnose an attempt to read from any unreadable field within the specified
3782 /// type, which might be a class type.
diagnoseMutableFields(EvalInfo & Info,const Expr * E,AccessKinds AK,QualType T)3783 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3784 QualType T) {
3785 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3786 if (!RD)
3787 return false;
3788
3789 if (!RD->hasMutableFields())
3790 return false;
3791
3792 for (auto *Field : RD->fields()) {
3793 // If we're actually going to read this field in some way, then it can't
3794 // be mutable. If we're in a union, then assigning to a mutable field
3795 // (even an empty one) can change the active member, so that's not OK.
3796 // FIXME: Add core issue number for the union case.
3797 if (Field->isMutable() &&
3798 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3799 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3800 Info.Note(Field->getLocation(), diag::note_declared_at);
3801 return true;
3802 }
3803
3804 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3805 return true;
3806 }
3807
3808 for (auto &BaseSpec : RD->bases())
3809 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3810 return true;
3811
3812 // All mutable fields were empty, and thus not actually read.
3813 return false;
3814 }
3815
lifetimeStartedInEvaluation(EvalInfo & Info,APValue::LValueBase Base,bool MutableSubobject=false)3816 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3817 APValue::LValueBase Base,
3818 bool MutableSubobject = false) {
3819 // A temporary or transient heap allocation we created.
3820 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3821 return true;
3822
3823 switch (Info.IsEvaluatingDecl) {
3824 case EvalInfo::EvaluatingDeclKind::None:
3825 return false;
3826
3827 case EvalInfo::EvaluatingDeclKind::Ctor:
3828 // The variable whose initializer we're evaluating.
3829 if (Info.EvaluatingDecl == Base)
3830 return true;
3831
3832 // A temporary lifetime-extended by the variable whose initializer we're
3833 // evaluating.
3834 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3835 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3836 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3837 return false;
3838
3839 case EvalInfo::EvaluatingDeclKind::Dtor:
3840 // C++2a [expr.const]p6:
3841 // [during constant destruction] the lifetime of a and its non-mutable
3842 // subobjects (but not its mutable subobjects) [are] considered to start
3843 // within e.
3844 if (MutableSubobject || Base != Info.EvaluatingDecl)
3845 return false;
3846 // FIXME: We can meaningfully extend this to cover non-const objects, but
3847 // we will need special handling: we should be able to access only
3848 // subobjects of such objects that are themselves declared const.
3849 QualType T = getType(Base);
3850 return T.isConstQualified() || T->isReferenceType();
3851 }
3852
3853 llvm_unreachable("unknown evaluating decl kind");
3854 }
3855
CheckArraySize(EvalInfo & Info,const ConstantArrayType * CAT,SourceLocation CallLoc={})3856 static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3857 SourceLocation CallLoc = {}) {
3858 return Info.CheckArraySize(
3859 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3860 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3861 /*Diag=*/true);
3862 }
3863
3864 namespace {
3865 /// A handle to a complete object (an object that is not a subobject of
3866 /// another object).
3867 struct CompleteObject {
3868 /// The identity of the object.
3869 APValue::LValueBase Base;
3870 /// The value of the complete object.
3871 APValue *Value;
3872 /// The type of the complete object.
3873 QualType Type;
3874
CompleteObject__anonfb577fba0b11::CompleteObject3875 CompleteObject() : Value(nullptr) {}
CompleteObject__anonfb577fba0b11::CompleteObject3876 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3877 : Base(Base), Value(Value), Type(Type) {}
3878
mayAccessMutableMembers__anonfb577fba0b11::CompleteObject3879 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3880 // If this isn't a "real" access (eg, if it's just accessing the type
3881 // info), allow it. We assume the type doesn't change dynamically for
3882 // subobjects of constexpr objects (even though we'd hit UB here if it
3883 // did). FIXME: Is this right?
3884 if (!isAnyAccess(AK))
3885 return true;
3886
3887 // In C++14 onwards, it is permitted to read a mutable member whose
3888 // lifetime began within the evaluation.
3889 // FIXME: Should we also allow this in C++11?
3890 if (!Info.getLangOpts().CPlusPlus14 &&
3891 AK != AccessKinds::AK_IsWithinLifetime)
3892 return false;
3893 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3894 }
3895
operator bool__anonfb577fba0b11::CompleteObject3896 explicit operator bool() const { return !Type.isNull(); }
3897 };
3898 } // end anonymous namespace
3899
getSubobjectType(QualType ObjType,QualType SubobjType,bool IsMutable=false)3900 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3901 bool IsMutable = false) {
3902 // C++ [basic.type.qualifier]p1:
3903 // - A const object is an object of type const T or a non-mutable subobject
3904 // of a const object.
3905 if (ObjType.isConstQualified() && !IsMutable)
3906 SubobjType.addConst();
3907 // - A volatile object is an object of type const T or a subobject of a
3908 // volatile object.
3909 if (ObjType.isVolatileQualified())
3910 SubobjType.addVolatile();
3911 return SubobjType;
3912 }
3913
3914 /// Find the designated sub-object of an rvalue.
3915 template <typename SubobjectHandler>
3916 static typename SubobjectHandler::result_type
findSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,SubobjectHandler & handler)3917 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3918 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3919 if (Sub.Invalid)
3920 // A diagnostic will have already been produced.
3921 return handler.failed();
3922 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3923 if (Info.getLangOpts().CPlusPlus11)
3924 Info.FFDiag(E, Sub.isOnePastTheEnd()
3925 ? diag::note_constexpr_access_past_end
3926 : diag::note_constexpr_access_unsized_array)
3927 << handler.AccessKind;
3928 else
3929 Info.FFDiag(E);
3930 return handler.failed();
3931 }
3932
3933 APValue *O = Obj.Value;
3934 QualType ObjType = Obj.Type;
3935 const FieldDecl *LastField = nullptr;
3936 const FieldDecl *VolatileField = nullptr;
3937
3938 // Walk the designator's path to find the subobject.
3939 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3940 // Reading an indeterminate value is undefined, but assigning over one is OK.
3941 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3942 (O->isIndeterminate() &&
3943 !isValidIndeterminateAccess(handler.AccessKind))) {
3944 // Object has ended lifetime.
3945 // If I is non-zero, some subobject (member or array element) of a
3946 // complete object has ended its lifetime, so this is valid for
3947 // IsWithinLifetime, resulting in false.
3948 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3949 return false;
3950 if (!Info.checkingPotentialConstantExpression())
3951 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3952 << handler.AccessKind << O->isIndeterminate()
3953 << E->getSourceRange();
3954 return handler.failed();
3955 }
3956
3957 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3958 // const and volatile semantics are not applied on an object under
3959 // {con,de}struction.
3960 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3961 ObjType->isRecordType() &&
3962 Info.isEvaluatingCtorDtor(
3963 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3964 ConstructionPhase::None) {
3965 ObjType = Info.Ctx.getCanonicalType(ObjType);
3966 ObjType.removeLocalConst();
3967 ObjType.removeLocalVolatile();
3968 }
3969
3970 // If this is our last pass, check that the final object type is OK.
3971 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3972 // Accesses to volatile objects are prohibited.
3973 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3974 if (Info.getLangOpts().CPlusPlus) {
3975 int DiagKind;
3976 SourceLocation Loc;
3977 const NamedDecl *Decl = nullptr;
3978 if (VolatileField) {
3979 DiagKind = 2;
3980 Loc = VolatileField->getLocation();
3981 Decl = VolatileField;
3982 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3983 DiagKind = 1;
3984 Loc = VD->getLocation();
3985 Decl = VD;
3986 } else {
3987 DiagKind = 0;
3988 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3989 Loc = E->getExprLoc();
3990 }
3991 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3992 << handler.AccessKind << DiagKind << Decl;
3993 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3994 } else {
3995 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3996 }
3997 return handler.failed();
3998 }
3999
4000 // If we are reading an object of class type, there may still be more
4001 // things we need to check: if there are any mutable subobjects, we
4002 // cannot perform this read. (This only happens when performing a trivial
4003 // copy or assignment.)
4004 if (ObjType->isRecordType() &&
4005 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4006 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4007 return handler.failed();
4008 }
4009
4010 if (I == N) {
4011 if (!handler.found(*O, ObjType))
4012 return false;
4013
4014 // If we modified a bit-field, truncate it to the right width.
4015 if (isModification(handler.AccessKind) &&
4016 LastField && LastField->isBitField() &&
4017 !truncateBitfieldValue(Info, E, *O, LastField))
4018 return false;
4019
4020 return true;
4021 }
4022
4023 LastField = nullptr;
4024 if (ObjType->isArrayType()) {
4025 // Next subobject is an array element.
4026 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
4027 assert(CAT && "vla in literal type?");
4028 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4029 if (CAT->getSize().ule(Index)) {
4030 // Note, it should not be possible to form a pointer with a valid
4031 // designator which points more than one past the end of the array.
4032 if (Info.getLangOpts().CPlusPlus11)
4033 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4034 << handler.AccessKind;
4035 else
4036 Info.FFDiag(E);
4037 return handler.failed();
4038 }
4039
4040 ObjType = CAT->getElementType();
4041
4042 if (O->getArrayInitializedElts() > Index)
4043 O = &O->getArrayInitializedElt(Index);
4044 else if (!isRead(handler.AccessKind)) {
4045 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
4046 return handler.failed();
4047
4048 expandArray(*O, Index);
4049 O = &O->getArrayInitializedElt(Index);
4050 } else
4051 O = &O->getArrayFiller();
4052 } else if (ObjType->isAnyComplexType()) {
4053 // Next subobject is a complex number.
4054 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4055 if (Index > 1) {
4056 if (Info.getLangOpts().CPlusPlus11)
4057 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4058 << handler.AccessKind;
4059 else
4060 Info.FFDiag(E);
4061 return handler.failed();
4062 }
4063
4064 ObjType = getSubobjectType(
4065 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4066
4067 assert(I == N - 1 && "extracting subobject of scalar?");
4068 if (O->isComplexInt()) {
4069 return handler.found(Index ? O->getComplexIntImag()
4070 : O->getComplexIntReal(), ObjType);
4071 } else {
4072 assert(O->isComplexFloat());
4073 return handler.found(Index ? O->getComplexFloatImag()
4074 : O->getComplexFloatReal(), ObjType);
4075 }
4076 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4077 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4078 unsigned NumElements = VT->getNumElements();
4079 if (Index == NumElements) {
4080 if (Info.getLangOpts().CPlusPlus11)
4081 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4082 << handler.AccessKind;
4083 else
4084 Info.FFDiag(E);
4085 return handler.failed();
4086 }
4087
4088 if (Index > NumElements) {
4089 Info.CCEDiag(E, diag::note_constexpr_array_index)
4090 << Index << /*array*/ 0 << NumElements;
4091 return handler.failed();
4092 }
4093
4094 ObjType = VT->getElementType();
4095 assert(I == N - 1 && "extracting subobject of scalar?");
4096 return handler.found(O->getVectorElt(Index), ObjType);
4097 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4098 if (Field->isMutable() &&
4099 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4100 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4101 << handler.AccessKind << Field;
4102 Info.Note(Field->getLocation(), diag::note_declared_at);
4103 return handler.failed();
4104 }
4105
4106 // Next subobject is a class, struct or union field.
4107 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
4108 if (RD->isUnion()) {
4109 const FieldDecl *UnionField = O->getUnionField();
4110 if (!UnionField ||
4111 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4112 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4113 // Placement new onto an inactive union member makes it active.
4114 O->setUnion(Field, APValue());
4115 } else {
4116 // Pointer to/into inactive union member: Not within lifetime
4117 if (handler.AccessKind == AK_IsWithinLifetime)
4118 return false;
4119 // FIXME: If O->getUnionValue() is absent, report that there's no
4120 // active union member rather than reporting the prior active union
4121 // member. We'll need to fix nullptr_t to not use APValue() as its
4122 // representation first.
4123 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4124 << handler.AccessKind << Field << !UnionField << UnionField;
4125 return handler.failed();
4126 }
4127 }
4128 O = &O->getUnionValue();
4129 } else
4130 O = &O->getStructField(Field->getFieldIndex());
4131
4132 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4133 LastField = Field;
4134 if (Field->getType().isVolatileQualified())
4135 VolatileField = Field;
4136 } else {
4137 // Next subobject is a base class.
4138 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4139 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4140 O = &O->getStructBase(getBaseIndex(Derived, Base));
4141
4142 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
4143 }
4144 }
4145 }
4146
4147 namespace {
4148 struct ExtractSubobjectHandler {
4149 EvalInfo &Info;
4150 const Expr *E;
4151 APValue &Result;
4152 const AccessKinds AccessKind;
4153
4154 typedef bool result_type;
failed__anonfb577fba0c11::ExtractSubobjectHandler4155 bool failed() { return false; }
found__anonfb577fba0c11::ExtractSubobjectHandler4156 bool found(APValue &Subobj, QualType SubobjType) {
4157 Result = Subobj;
4158 if (AccessKind == AK_ReadObjectRepresentation)
4159 return true;
4160 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4161 }
found__anonfb577fba0c11::ExtractSubobjectHandler4162 bool found(APSInt &Value, QualType SubobjType) {
4163 Result = APValue(Value);
4164 return true;
4165 }
found__anonfb577fba0c11::ExtractSubobjectHandler4166 bool found(APFloat &Value, QualType SubobjType) {
4167 Result = APValue(Value);
4168 return true;
4169 }
4170 };
4171 } // end anonymous namespace
4172
4173 /// Extract the designated sub-object of an rvalue.
extractSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,APValue & Result,AccessKinds AK=AK_Read)4174 static bool extractSubobject(EvalInfo &Info, const Expr *E,
4175 const CompleteObject &Obj,
4176 const SubobjectDesignator &Sub, APValue &Result,
4177 AccessKinds AK = AK_Read) {
4178 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4179 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4180 return findSubobject(Info, E, Obj, Sub, Handler);
4181 }
4182
4183 namespace {
4184 struct ModifySubobjectHandler {
4185 EvalInfo &Info;
4186 APValue &NewVal;
4187 const Expr *E;
4188
4189 typedef bool result_type;
4190 static const AccessKinds AccessKind = AK_Assign;
4191
checkConst__anonfb577fba0d11::ModifySubobjectHandler4192 bool checkConst(QualType QT) {
4193 // Assigning to a const object has undefined behavior.
4194 if (QT.isConstQualified()) {
4195 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4196 return false;
4197 }
4198 return true;
4199 }
4200
failed__anonfb577fba0d11::ModifySubobjectHandler4201 bool failed() { return false; }
found__anonfb577fba0d11::ModifySubobjectHandler4202 bool found(APValue &Subobj, QualType SubobjType) {
4203 if (!checkConst(SubobjType))
4204 return false;
4205 // We've been given ownership of NewVal, so just swap it in.
4206 Subobj.swap(NewVal);
4207 return true;
4208 }
found__anonfb577fba0d11::ModifySubobjectHandler4209 bool found(APSInt &Value, QualType SubobjType) {
4210 if (!checkConst(SubobjType))
4211 return false;
4212 if (!NewVal.isInt()) {
4213 // Maybe trying to write a cast pointer value into a complex?
4214 Info.FFDiag(E);
4215 return false;
4216 }
4217 Value = NewVal.getInt();
4218 return true;
4219 }
found__anonfb577fba0d11::ModifySubobjectHandler4220 bool found(APFloat &Value, QualType SubobjType) {
4221 if (!checkConst(SubobjType))
4222 return false;
4223 Value = NewVal.getFloat();
4224 return true;
4225 }
4226 };
4227 } // end anonymous namespace
4228
4229 const AccessKinds ModifySubobjectHandler::AccessKind;
4230
4231 /// Update the designated sub-object of an rvalue to the given value.
modifySubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,APValue & NewVal)4232 static bool modifySubobject(EvalInfo &Info, const Expr *E,
4233 const CompleteObject &Obj,
4234 const SubobjectDesignator &Sub,
4235 APValue &NewVal) {
4236 ModifySubobjectHandler Handler = { Info, NewVal, E };
4237 return findSubobject(Info, E, Obj, Sub, Handler);
4238 }
4239
4240 /// Find the position where two subobject designators diverge, or equivalently
4241 /// the length of the common initial subsequence.
FindDesignatorMismatch(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B,bool & WasArrayIndex)4242 static unsigned FindDesignatorMismatch(QualType ObjType,
4243 const SubobjectDesignator &A,
4244 const SubobjectDesignator &B,
4245 bool &WasArrayIndex) {
4246 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4247 for (/**/; I != N; ++I) {
4248 if (!ObjType.isNull() &&
4249 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4250 // Next subobject is an array element.
4251 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4252 WasArrayIndex = true;
4253 return I;
4254 }
4255 if (ObjType->isAnyComplexType())
4256 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4257 else
4258 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4259 } else {
4260 if (A.Entries[I].getAsBaseOrMember() !=
4261 B.Entries[I].getAsBaseOrMember()) {
4262 WasArrayIndex = false;
4263 return I;
4264 }
4265 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4266 // Next subobject is a field.
4267 ObjType = FD->getType();
4268 else
4269 // Next subobject is a base class.
4270 ObjType = QualType();
4271 }
4272 }
4273 WasArrayIndex = false;
4274 return I;
4275 }
4276
4277 /// Determine whether the given subobject designators refer to elements of the
4278 /// same array object.
AreElementsOfSameArray(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B)4279 static bool AreElementsOfSameArray(QualType ObjType,
4280 const SubobjectDesignator &A,
4281 const SubobjectDesignator &B) {
4282 if (A.Entries.size() != B.Entries.size())
4283 return false;
4284
4285 bool IsArray = A.MostDerivedIsArrayElement;
4286 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4287 // A is a subobject of the array element.
4288 return false;
4289
4290 // If A (and B) designates an array element, the last entry will be the array
4291 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4292 // of length 1' case, and the entire path must match.
4293 bool WasArrayIndex;
4294 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4295 return CommonLength >= A.Entries.size() - IsArray;
4296 }
4297
4298 /// Find the complete object to which an LValue refers.
findCompleteObject(EvalInfo & Info,const Expr * E,AccessKinds AK,const LValue & LVal,QualType LValType)4299 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4300 AccessKinds AK, const LValue &LVal,
4301 QualType LValType) {
4302 if (LVal.InvalidBase) {
4303 Info.FFDiag(E);
4304 return CompleteObject();
4305 }
4306
4307 if (!LVal.Base) {
4308 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4309 return CompleteObject();
4310 }
4311
4312 CallStackFrame *Frame = nullptr;
4313 unsigned Depth = 0;
4314 if (LVal.getLValueCallIndex()) {
4315 std::tie(Frame, Depth) =
4316 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4317 if (!Frame) {
4318 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4319 << AK << LVal.Base.is<const ValueDecl*>();
4320 NoteLValueLocation(Info, LVal.Base);
4321 return CompleteObject();
4322 }
4323 }
4324
4325 bool IsAccess = isAnyAccess(AK);
4326
4327 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4328 // is not a constant expression (even if the object is non-volatile). We also
4329 // apply this rule to C++98, in order to conform to the expected 'volatile'
4330 // semantics.
4331 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4332 if (Info.getLangOpts().CPlusPlus)
4333 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4334 << AK << LValType;
4335 else
4336 Info.FFDiag(E);
4337 return CompleteObject();
4338 }
4339
4340 // Compute value storage location and type of base object.
4341 APValue *BaseVal = nullptr;
4342 QualType BaseType = getType(LVal.Base);
4343
4344 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4345 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4346 // This is the object whose initializer we're evaluating, so its lifetime
4347 // started in the current evaluation.
4348 BaseVal = Info.EvaluatingDeclValue;
4349 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4350 // Allow reading from a GUID declaration.
4351 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4352 if (isModification(AK)) {
4353 // All the remaining cases do not permit modification of the object.
4354 Info.FFDiag(E, diag::note_constexpr_modify_global);
4355 return CompleteObject();
4356 }
4357 APValue &V = GD->getAsAPValue();
4358 if (V.isAbsent()) {
4359 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4360 << GD->getType();
4361 return CompleteObject();
4362 }
4363 return CompleteObject(LVal.Base, &V, GD->getType());
4364 }
4365
4366 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4367 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4368 if (isModification(AK)) {
4369 Info.FFDiag(E, diag::note_constexpr_modify_global);
4370 return CompleteObject();
4371 }
4372 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4373 GCD->getType());
4374 }
4375
4376 // Allow reading from template parameter objects.
4377 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4378 if (isModification(AK)) {
4379 Info.FFDiag(E, diag::note_constexpr_modify_global);
4380 return CompleteObject();
4381 }
4382 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4383 TPO->getType());
4384 }
4385
4386 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4387 // In C++11, constexpr, non-volatile variables initialized with constant
4388 // expressions are constant expressions too. Inside constexpr functions,
4389 // parameters are constant expressions even if they're non-const.
4390 // In C++1y, objects local to a constant expression (those with a Frame) are
4391 // both readable and writable inside constant expressions.
4392 // In C, such things can also be folded, although they are not ICEs.
4393 const VarDecl *VD = dyn_cast<VarDecl>(D);
4394 if (VD) {
4395 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4396 VD = VDef;
4397 }
4398 if (!VD || VD->isInvalidDecl()) {
4399 Info.FFDiag(E);
4400 return CompleteObject();
4401 }
4402
4403 bool IsConstant = BaseType.isConstant(Info.Ctx);
4404 bool ConstexprVar = false;
4405 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4406 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4407 ConstexprVar = VD->isConstexpr();
4408
4409 // Unless we're looking at a local variable or argument in a constexpr call,
4410 // the variable we're reading must be const.
4411 if (!Frame) {
4412 if (IsAccess && isa<ParmVarDecl>(VD)) {
4413 // Access of a parameter that's not associated with a frame isn't going
4414 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4415 // suitable diagnostic.
4416 } else if (Info.getLangOpts().CPlusPlus14 &&
4417 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4418 // OK, we can read and modify an object if we're in the process of
4419 // evaluating its initializer, because its lifetime began in this
4420 // evaluation.
4421 } else if (isModification(AK)) {
4422 // All the remaining cases do not permit modification of the object.
4423 Info.FFDiag(E, diag::note_constexpr_modify_global);
4424 return CompleteObject();
4425 } else if (VD->isConstexpr()) {
4426 // OK, we can read this variable.
4427 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4428 Info.FFDiag(E);
4429 return CompleteObject();
4430 } else if (BaseType->isIntegralOrEnumerationType()) {
4431 if (!IsConstant) {
4432 if (!IsAccess)
4433 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4434 if (Info.getLangOpts().CPlusPlus) {
4435 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4436 Info.Note(VD->getLocation(), diag::note_declared_at);
4437 } else {
4438 Info.FFDiag(E);
4439 }
4440 return CompleteObject();
4441 }
4442 } else if (!IsAccess) {
4443 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4444 } else if ((IsConstant || BaseType->isReferenceType()) &&
4445 Info.checkingPotentialConstantExpression() &&
4446 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4447 // This variable might end up being constexpr. Don't diagnose it yet.
4448 } else if (IsConstant) {
4449 // Keep evaluating to see what we can do. In particular, we support
4450 // folding of const floating-point types, in order to make static const
4451 // data members of such types (supported as an extension) more useful.
4452 if (Info.getLangOpts().CPlusPlus) {
4453 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4454 ? diag::note_constexpr_ltor_non_constexpr
4455 : diag::note_constexpr_ltor_non_integral, 1)
4456 << VD << BaseType;
4457 Info.Note(VD->getLocation(), diag::note_declared_at);
4458 } else {
4459 Info.CCEDiag(E);
4460 }
4461 } else {
4462 // Never allow reading a non-const value.
4463 if (Info.getLangOpts().CPlusPlus) {
4464 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4465 ? diag::note_constexpr_ltor_non_constexpr
4466 : diag::note_constexpr_ltor_non_integral, 1)
4467 << VD << BaseType;
4468 Info.Note(VD->getLocation(), diag::note_declared_at);
4469 } else {
4470 Info.FFDiag(E);
4471 }
4472 return CompleteObject();
4473 }
4474 }
4475
4476 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4477 return CompleteObject();
4478 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4479 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4480 // we can't access a constexpr-unknown object.
4481 if (!BaseVal) {
4482 if (!Info.checkingPotentialConstantExpression()) {
4483 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4484 << AK << VD;
4485 Info.Note(VD->getLocation(), diag::note_declared_at);
4486 }
4487 return CompleteObject();
4488 }
4489 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4490 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4491 if (!Alloc) {
4492 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4493 return CompleteObject();
4494 }
4495 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4496 LVal.Base.getDynamicAllocType());
4497 } else {
4498 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4499
4500 if (!Frame) {
4501 if (const MaterializeTemporaryExpr *MTE =
4502 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4503 assert(MTE->getStorageDuration() == SD_Static &&
4504 "should have a frame for a non-global materialized temporary");
4505
4506 // C++20 [expr.const]p4: [DR2126]
4507 // An object or reference is usable in constant expressions if it is
4508 // - a temporary object of non-volatile const-qualified literal type
4509 // whose lifetime is extended to that of a variable that is usable
4510 // in constant expressions
4511 //
4512 // C++20 [expr.const]p5:
4513 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4514 // - a non-volatile glvalue that refers to an object that is usable
4515 // in constant expressions, or
4516 // - a non-volatile glvalue of literal type that refers to a
4517 // non-volatile object whose lifetime began within the evaluation
4518 // of E;
4519 //
4520 // C++11 misses the 'began within the evaluation of e' check and
4521 // instead allows all temporaries, including things like:
4522 // int &&r = 1;
4523 // int x = ++r;
4524 // constexpr int k = r;
4525 // Therefore we use the C++14-onwards rules in C++11 too.
4526 //
4527 // Note that temporaries whose lifetimes began while evaluating a
4528 // variable's constructor are not usable while evaluating the
4529 // corresponding destructor, not even if they're of const-qualified
4530 // types.
4531 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4532 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4533 if (!IsAccess)
4534 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4535 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4536 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4537 return CompleteObject();
4538 }
4539
4540 BaseVal = MTE->getOrCreateValue(false);
4541 assert(BaseVal && "got reference to unevaluated temporary");
4542 } else if (const CompoundLiteralExpr *CLE =
4543 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4544 // According to GCC info page:
4545 //
4546 // 6.28 Compound Literals
4547 //
4548 // As an optimization, G++ sometimes gives array compound literals
4549 // longer lifetimes: when the array either appears outside a function or
4550 // has a const-qualified type. If foo and its initializer had elements
4551 // of type char *const rather than char *, or if foo were a global
4552 // variable, the array would have static storage duration. But it is
4553 // probably safest just to avoid the use of array compound literals in
4554 // C++ code.
4555 //
4556 // Obey that rule by checking constness for converted array types.
4557 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4558 !LValType->isArrayType() &&
4559 !CLETy.isConstant(Info.Ctx)) {
4560 Info.FFDiag(E);
4561 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4562 return CompleteObject();
4563 }
4564
4565 BaseVal = &CLE->getStaticValue();
4566 } else {
4567 if (!IsAccess)
4568 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4569 APValue Val;
4570 LVal.moveInto(Val);
4571 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4572 << AK
4573 << Val.getAsString(Info.Ctx,
4574 Info.Ctx.getLValueReferenceType(LValType));
4575 NoteLValueLocation(Info, LVal.Base);
4576 return CompleteObject();
4577 }
4578 } else {
4579 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4580 assert(BaseVal && "missing value for temporary");
4581 }
4582 }
4583
4584 // In C++14, we can't safely access any mutable state when we might be
4585 // evaluating after an unmodeled side effect. Parameters are modeled as state
4586 // in the caller, but aren't visible once the call returns, so they can be
4587 // modified in a speculatively-evaluated call.
4588 //
4589 // FIXME: Not all local state is mutable. Allow local constant subobjects
4590 // to be read here (but take care with 'mutable' fields).
4591 unsigned VisibleDepth = Depth;
4592 if (llvm::isa_and_nonnull<ParmVarDecl>(
4593 LVal.Base.dyn_cast<const ValueDecl *>()))
4594 ++VisibleDepth;
4595 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4596 Info.EvalStatus.HasSideEffects) ||
4597 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4598 return CompleteObject();
4599
4600 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4601 }
4602
4603 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4604 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4605 /// glvalue referred to by an entity of reference type.
4606 ///
4607 /// \param Info - Information about the ongoing evaluation.
4608 /// \param Conv - The expression for which we are performing the conversion.
4609 /// Used for diagnostics.
4610 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4611 /// case of a non-class type).
4612 /// \param LVal - The glvalue on which we are attempting to perform this action.
4613 /// \param RVal - The produced value will be placed here.
4614 /// \param WantObjectRepresentation - If true, we're looking for the object
4615 /// representation rather than the value, and in particular,
4616 /// there is no requirement that the result be fully initialized.
4617 static bool
handleLValueToRValueConversion(EvalInfo & Info,const Expr * Conv,QualType Type,const LValue & LVal,APValue & RVal,bool WantObjectRepresentation=false)4618 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4619 const LValue &LVal, APValue &RVal,
4620 bool WantObjectRepresentation = false) {
4621 if (LVal.Designator.Invalid)
4622 return false;
4623
4624 // Check for special cases where there is no existing APValue to look at.
4625 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4626
4627 AccessKinds AK =
4628 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4629
4630 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4631 if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4632 // Special-case character extraction so we don't have to construct an
4633 // APValue for the whole string.
4634 assert(LVal.Designator.Entries.size() <= 1 &&
4635 "Can only read characters from string literals");
4636 if (LVal.Designator.Entries.empty()) {
4637 // Fail for now for LValue to RValue conversion of an array.
4638 // (This shouldn't show up in C/C++, but it could be triggered by a
4639 // weird EvaluateAsRValue call from a tool.)
4640 Info.FFDiag(Conv);
4641 return false;
4642 }
4643 if (LVal.Designator.isOnePastTheEnd()) {
4644 if (Info.getLangOpts().CPlusPlus11)
4645 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4646 else
4647 Info.FFDiag(Conv);
4648 return false;
4649 }
4650 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4651 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4652 return true;
4653 }
4654 }
4655
4656 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4657 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4658 }
4659
4660 /// Perform an assignment of Val to LVal. Takes ownership of Val.
handleAssignment(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,APValue & Val)4661 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4662 QualType LValType, APValue &Val) {
4663 if (LVal.Designator.Invalid)
4664 return false;
4665
4666 if (!Info.getLangOpts().CPlusPlus14) {
4667 Info.FFDiag(E);
4668 return false;
4669 }
4670
4671 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4672 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4673 }
4674
4675 namespace {
4676 struct CompoundAssignSubobjectHandler {
4677 EvalInfo &Info;
4678 const CompoundAssignOperator *E;
4679 QualType PromotedLHSType;
4680 BinaryOperatorKind Opcode;
4681 const APValue &RHS;
4682
4683 static const AccessKinds AccessKind = AK_Assign;
4684
4685 typedef bool result_type;
4686
checkConst__anonfb577fba0e11::CompoundAssignSubobjectHandler4687 bool checkConst(QualType QT) {
4688 // Assigning to a const object has undefined behavior.
4689 if (QT.isConstQualified()) {
4690 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4691 return false;
4692 }
4693 return true;
4694 }
4695
failed__anonfb577fba0e11::CompoundAssignSubobjectHandler4696 bool failed() { return false; }
found__anonfb577fba0e11::CompoundAssignSubobjectHandler4697 bool found(APValue &Subobj, QualType SubobjType) {
4698 switch (Subobj.getKind()) {
4699 case APValue::Int:
4700 return found(Subobj.getInt(), SubobjType);
4701 case APValue::Float:
4702 return found(Subobj.getFloat(), SubobjType);
4703 case APValue::ComplexInt:
4704 case APValue::ComplexFloat:
4705 // FIXME: Implement complex compound assignment.
4706 Info.FFDiag(E);
4707 return false;
4708 case APValue::LValue:
4709 return foundPointer(Subobj, SubobjType);
4710 case APValue::Vector:
4711 return foundVector(Subobj, SubobjType);
4712 case APValue::Indeterminate:
4713 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4714 << /*read of=*/0 << /*uninitialized object=*/1
4715 << E->getLHS()->getSourceRange();
4716 return false;
4717 default:
4718 // FIXME: can this happen?
4719 Info.FFDiag(E);
4720 return false;
4721 }
4722 }
4723
foundVector__anonfb577fba0e11::CompoundAssignSubobjectHandler4724 bool foundVector(APValue &Value, QualType SubobjType) {
4725 if (!checkConst(SubobjType))
4726 return false;
4727
4728 if (!SubobjType->isVectorType()) {
4729 Info.FFDiag(E);
4730 return false;
4731 }
4732 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4733 }
4734
found__anonfb577fba0e11::CompoundAssignSubobjectHandler4735 bool found(APSInt &Value, QualType SubobjType) {
4736 if (!checkConst(SubobjType))
4737 return false;
4738
4739 if (!SubobjType->isIntegerType()) {
4740 // We don't support compound assignment on integer-cast-to-pointer
4741 // values.
4742 Info.FFDiag(E);
4743 return false;
4744 }
4745
4746 if (RHS.isInt()) {
4747 APSInt LHS =
4748 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4749 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4750 return false;
4751 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4752 return true;
4753 } else if (RHS.isFloat()) {
4754 const FPOptions FPO = E->getFPFeaturesInEffect(
4755 Info.Ctx.getLangOpts());
4756 APFloat FValue(0.0);
4757 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4758 PromotedLHSType, FValue) &&
4759 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4760 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4761 Value);
4762 }
4763
4764 Info.FFDiag(E);
4765 return false;
4766 }
found__anonfb577fba0e11::CompoundAssignSubobjectHandler4767 bool found(APFloat &Value, QualType SubobjType) {
4768 return checkConst(SubobjType) &&
4769 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4770 Value) &&
4771 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4772 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4773 }
foundPointer__anonfb577fba0e11::CompoundAssignSubobjectHandler4774 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4775 if (!checkConst(SubobjType))
4776 return false;
4777
4778 QualType PointeeType;
4779 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4780 PointeeType = PT->getPointeeType();
4781
4782 if (PointeeType.isNull() || !RHS.isInt() ||
4783 (Opcode != BO_Add && Opcode != BO_Sub)) {
4784 Info.FFDiag(E);
4785 return false;
4786 }
4787
4788 APSInt Offset = RHS.getInt();
4789 if (Opcode == BO_Sub)
4790 negateAsSigned(Offset);
4791
4792 LValue LVal;
4793 LVal.setFrom(Info.Ctx, Subobj);
4794 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4795 return false;
4796 LVal.moveInto(Subobj);
4797 return true;
4798 }
4799 };
4800 } // end anonymous namespace
4801
4802 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4803
4804 /// Perform a compound assignment of LVal <op>= RVal.
handleCompoundAssignment(EvalInfo & Info,const CompoundAssignOperator * E,const LValue & LVal,QualType LValType,QualType PromotedLValType,BinaryOperatorKind Opcode,const APValue & RVal)4805 static bool handleCompoundAssignment(EvalInfo &Info,
4806 const CompoundAssignOperator *E,
4807 const LValue &LVal, QualType LValType,
4808 QualType PromotedLValType,
4809 BinaryOperatorKind Opcode,
4810 const APValue &RVal) {
4811 if (LVal.Designator.Invalid)
4812 return false;
4813
4814 if (!Info.getLangOpts().CPlusPlus14) {
4815 Info.FFDiag(E);
4816 return false;
4817 }
4818
4819 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4820 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4821 RVal };
4822 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4823 }
4824
4825 namespace {
4826 struct IncDecSubobjectHandler {
4827 EvalInfo &Info;
4828 const UnaryOperator *E;
4829 AccessKinds AccessKind;
4830 APValue *Old;
4831
4832 typedef bool result_type;
4833
checkConst__anonfb577fba0f11::IncDecSubobjectHandler4834 bool checkConst(QualType QT) {
4835 // Assigning to a const object has undefined behavior.
4836 if (QT.isConstQualified()) {
4837 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4838 return false;
4839 }
4840 return true;
4841 }
4842
failed__anonfb577fba0f11::IncDecSubobjectHandler4843 bool failed() { return false; }
found__anonfb577fba0f11::IncDecSubobjectHandler4844 bool found(APValue &Subobj, QualType SubobjType) {
4845 // Stash the old value. Also clear Old, so we don't clobber it later
4846 // if we're post-incrementing a complex.
4847 if (Old) {
4848 *Old = Subobj;
4849 Old = nullptr;
4850 }
4851
4852 switch (Subobj.getKind()) {
4853 case APValue::Int:
4854 return found(Subobj.getInt(), SubobjType);
4855 case APValue::Float:
4856 return found(Subobj.getFloat(), SubobjType);
4857 case APValue::ComplexInt:
4858 return found(Subobj.getComplexIntReal(),
4859 SubobjType->castAs<ComplexType>()->getElementType()
4860 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4861 case APValue::ComplexFloat:
4862 return found(Subobj.getComplexFloatReal(),
4863 SubobjType->castAs<ComplexType>()->getElementType()
4864 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4865 case APValue::LValue:
4866 return foundPointer(Subobj, SubobjType);
4867 default:
4868 // FIXME: can this happen?
4869 Info.FFDiag(E);
4870 return false;
4871 }
4872 }
found__anonfb577fba0f11::IncDecSubobjectHandler4873 bool found(APSInt &Value, QualType SubobjType) {
4874 if (!checkConst(SubobjType))
4875 return false;
4876
4877 if (!SubobjType->isIntegerType()) {
4878 // We don't support increment / decrement on integer-cast-to-pointer
4879 // values.
4880 Info.FFDiag(E);
4881 return false;
4882 }
4883
4884 if (Old) *Old = APValue(Value);
4885
4886 // bool arithmetic promotes to int, and the conversion back to bool
4887 // doesn't reduce mod 2^n, so special-case it.
4888 if (SubobjType->isBooleanType()) {
4889 if (AccessKind == AK_Increment)
4890 Value = 1;
4891 else
4892 Value = !Value;
4893 return true;
4894 }
4895
4896 bool WasNegative = Value.isNegative();
4897 if (AccessKind == AK_Increment) {
4898 ++Value;
4899
4900 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4901 APSInt ActualValue(Value, /*IsUnsigned*/true);
4902 return HandleOverflow(Info, E, ActualValue, SubobjType);
4903 }
4904 } else {
4905 --Value;
4906
4907 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4908 unsigned BitWidth = Value.getBitWidth();
4909 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4910 ActualValue.setBit(BitWidth);
4911 return HandleOverflow(Info, E, ActualValue, SubobjType);
4912 }
4913 }
4914 return true;
4915 }
found__anonfb577fba0f11::IncDecSubobjectHandler4916 bool found(APFloat &Value, QualType SubobjType) {
4917 if (!checkConst(SubobjType))
4918 return false;
4919
4920 if (Old) *Old = APValue(Value);
4921
4922 APFloat One(Value.getSemantics(), 1);
4923 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4924 APFloat::opStatus St;
4925 if (AccessKind == AK_Increment)
4926 St = Value.add(One, RM);
4927 else
4928 St = Value.subtract(One, RM);
4929 return checkFloatingPointResult(Info, E, St);
4930 }
foundPointer__anonfb577fba0f11::IncDecSubobjectHandler4931 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4932 if (!checkConst(SubobjType))
4933 return false;
4934
4935 QualType PointeeType;
4936 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4937 PointeeType = PT->getPointeeType();
4938 else {
4939 Info.FFDiag(E);
4940 return false;
4941 }
4942
4943 LValue LVal;
4944 LVal.setFrom(Info.Ctx, Subobj);
4945 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4946 AccessKind == AK_Increment ? 1 : -1))
4947 return false;
4948 LVal.moveInto(Subobj);
4949 return true;
4950 }
4951 };
4952 } // end anonymous namespace
4953
4954 /// Perform an increment or decrement on LVal.
handleIncDec(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,bool IsIncrement,APValue * Old)4955 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4956 QualType LValType, bool IsIncrement, APValue *Old) {
4957 if (LVal.Designator.Invalid)
4958 return false;
4959
4960 if (!Info.getLangOpts().CPlusPlus14) {
4961 Info.FFDiag(E);
4962 return false;
4963 }
4964
4965 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4966 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4967 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4968 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4969 }
4970
4971 /// Build an lvalue for the object argument of a member function call.
EvaluateObjectArgument(EvalInfo & Info,const Expr * Object,LValue & This)4972 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4973 LValue &This) {
4974 if (Object->getType()->isPointerType() && Object->isPRValue())
4975 return EvaluatePointer(Object, This, Info);
4976
4977 if (Object->isGLValue())
4978 return EvaluateLValue(Object, This, Info);
4979
4980 if (Object->getType()->isLiteralType(Info.Ctx))
4981 return EvaluateTemporary(Object, This, Info);
4982
4983 if (Object->getType()->isRecordType() && Object->isPRValue())
4984 return EvaluateTemporary(Object, This, Info);
4985
4986 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4987 return false;
4988 }
4989
4990 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4991 /// lvalue referring to the result.
4992 ///
4993 /// \param Info - Information about the ongoing evaluation.
4994 /// \param LV - An lvalue referring to the base of the member pointer.
4995 /// \param RHS - The member pointer expression.
4996 /// \param IncludeMember - Specifies whether the member itself is included in
4997 /// the resulting LValue subobject designator. This is not possible when
4998 /// creating a bound member function.
4999 /// \return The field or method declaration to which the member pointer refers,
5000 /// or 0 if evaluation fails.
HandleMemberPointerAccess(EvalInfo & Info,QualType LVType,LValue & LV,const Expr * RHS,bool IncludeMember=true)5001 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5002 QualType LVType,
5003 LValue &LV,
5004 const Expr *RHS,
5005 bool IncludeMember = true) {
5006 MemberPtr MemPtr;
5007 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5008 return nullptr;
5009
5010 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5011 // member value, the behavior is undefined.
5012 if (!MemPtr.getDecl()) {
5013 // FIXME: Specific diagnostic.
5014 Info.FFDiag(RHS);
5015 return nullptr;
5016 }
5017
5018 if (MemPtr.isDerivedMember()) {
5019 // This is a member of some derived class. Truncate LV appropriately.
5020 // The end of the derived-to-base path for the base object must match the
5021 // derived-to-base path for the member pointer.
5022 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5023 LV.Designator.Entries.size()) {
5024 Info.FFDiag(RHS);
5025 return nullptr;
5026 }
5027 unsigned PathLengthToMember =
5028 LV.Designator.Entries.size() - MemPtr.Path.size();
5029 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5030 const CXXRecordDecl *LVDecl = getAsBaseClass(
5031 LV.Designator.Entries[PathLengthToMember + I]);
5032 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5033 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5034 Info.FFDiag(RHS);
5035 return nullptr;
5036 }
5037 }
5038
5039 // Truncate the lvalue to the appropriate derived class.
5040 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5041 PathLengthToMember))
5042 return nullptr;
5043 } else if (!MemPtr.Path.empty()) {
5044 // Extend the LValue path with the member pointer's path.
5045 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5046 MemPtr.Path.size() + IncludeMember);
5047
5048 // Walk down to the appropriate base class.
5049 if (const PointerType *PT = LVType->getAs<PointerType>())
5050 LVType = PT->getPointeeType();
5051 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5052 assert(RD && "member pointer access on non-class-type expression");
5053 // The first class in the path is that of the lvalue.
5054 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5055 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5056 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5057 return nullptr;
5058 RD = Base;
5059 }
5060 // Finally cast to the class containing the member.
5061 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5062 MemPtr.getContainingRecord()))
5063 return nullptr;
5064 }
5065
5066 // Add the member. Note that we cannot build bound member functions here.
5067 if (IncludeMember) {
5068 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5069 if (!HandleLValueMember(Info, RHS, LV, FD))
5070 return nullptr;
5071 } else if (const IndirectFieldDecl *IFD =
5072 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5073 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5074 return nullptr;
5075 } else {
5076 llvm_unreachable("can't construct reference to bound member function");
5077 }
5078 }
5079
5080 return MemPtr.getDecl();
5081 }
5082
HandleMemberPointerAccess(EvalInfo & Info,const BinaryOperator * BO,LValue & LV,bool IncludeMember=true)5083 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5084 const BinaryOperator *BO,
5085 LValue &LV,
5086 bool IncludeMember = true) {
5087 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5088
5089 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5090 if (Info.noteFailure()) {
5091 MemberPtr MemPtr;
5092 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5093 }
5094 return nullptr;
5095 }
5096
5097 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5098 BO->getRHS(), IncludeMember);
5099 }
5100
5101 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5102 /// the provided lvalue, which currently refers to the base object.
HandleBaseToDerivedCast(EvalInfo & Info,const CastExpr * E,LValue & Result)5103 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5104 LValue &Result) {
5105 SubobjectDesignator &D = Result.Designator;
5106 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5107 return false;
5108
5109 QualType TargetQT = E->getType();
5110 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5111 TargetQT = PT->getPointeeType();
5112
5113 // Check this cast lands within the final derived-to-base subobject path.
5114 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
5115 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5116 << D.MostDerivedType << TargetQT;
5117 return false;
5118 }
5119
5120 // Check the type of the final cast. We don't need to check the path,
5121 // since a cast can only be formed if the path is unique.
5122 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5123 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5124 const CXXRecordDecl *FinalType;
5125 if (NewEntriesSize == D.MostDerivedPathLength)
5126 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5127 else
5128 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5129 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
5130 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5131 << D.MostDerivedType << TargetQT;
5132 return false;
5133 }
5134
5135 // Truncate the lvalue to the appropriate derived class.
5136 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5137 }
5138
5139 /// Get the value to use for a default-initialized object of type T.
5140 /// Return false if it encounters something invalid.
handleDefaultInitValue(QualType T,APValue & Result)5141 static bool handleDefaultInitValue(QualType T, APValue &Result) {
5142 bool Success = true;
5143
5144 // If there is already a value present don't overwrite it.
5145 if (!Result.isAbsent())
5146 return true;
5147
5148 if (auto *RD = T->getAsCXXRecordDecl()) {
5149 if (RD->isInvalidDecl()) {
5150 Result = APValue();
5151 return false;
5152 }
5153 if (RD->isUnion()) {
5154 Result = APValue((const FieldDecl *)nullptr);
5155 return true;
5156 }
5157 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5158 std::distance(RD->field_begin(), RD->field_end()));
5159
5160 unsigned Index = 0;
5161 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5162 End = RD->bases_end();
5163 I != End; ++I, ++Index)
5164 Success &=
5165 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5166
5167 for (const auto *I : RD->fields()) {
5168 if (I->isUnnamedBitField())
5169 continue;
5170 Success &= handleDefaultInitValue(
5171 I->getType(), Result.getStructField(I->getFieldIndex()));
5172 }
5173 return Success;
5174 }
5175
5176 if (auto *AT =
5177 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5178 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5179 if (Result.hasArrayFiller())
5180 Success &=
5181 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5182
5183 return Success;
5184 }
5185
5186 Result = APValue::IndeterminateValue();
5187 return true;
5188 }
5189
5190 namespace {
5191 enum EvalStmtResult {
5192 /// Evaluation failed.
5193 ESR_Failed,
5194 /// Hit a 'return' statement.
5195 ESR_Returned,
5196 /// Evaluation succeeded.
5197 ESR_Succeeded,
5198 /// Hit a 'continue' statement.
5199 ESR_Continue,
5200 /// Hit a 'break' statement.
5201 ESR_Break,
5202 /// Still scanning for 'case' or 'default' statement.
5203 ESR_CaseNotFound
5204 };
5205 }
5206
EvaluateVarDecl(EvalInfo & Info,const VarDecl * VD)5207 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5208 if (VD->isInvalidDecl())
5209 return false;
5210 // We don't need to evaluate the initializer for a static local.
5211 if (!VD->hasLocalStorage())
5212 return true;
5213
5214 LValue Result;
5215 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5216 ScopeKind::Block, Result);
5217
5218 const Expr *InitE = VD->getInit();
5219 if (!InitE) {
5220 if (VD->getType()->isDependentType())
5221 return Info.noteSideEffect();
5222 return handleDefaultInitValue(VD->getType(), Val);
5223 }
5224 if (InitE->isValueDependent())
5225 return false;
5226
5227 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5228 // Wipe out any partially-computed value, to allow tracking that this
5229 // evaluation failed.
5230 Val = APValue();
5231 return false;
5232 }
5233
5234 return true;
5235 }
5236
5237 static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5238 const DecompositionDecl *DD);
5239
EvaluateDecl(EvalInfo & Info,const Decl * D,bool EvaluateConditionDecl=false)5240 static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5241 bool EvaluateConditionDecl = false) {
5242 bool OK = true;
5243 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5244 OK &= EvaluateVarDecl(Info, VD);
5245
5246 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5247 EvaluateConditionDecl && DD)
5248 OK &= EvaluateDecompositionDeclInit(Info, DD);
5249
5250 return OK;
5251 }
5252
EvaluateDecompositionDeclInit(EvalInfo & Info,const DecompositionDecl * DD)5253 static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5254 const DecompositionDecl *DD) {
5255 bool OK = true;
5256 for (auto *BD : DD->flat_bindings())
5257 if (auto *VD = BD->getHoldingVar())
5258 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5259
5260 return OK;
5261 }
5262
MaybeEvaluateDeferredVarDeclInit(EvalInfo & Info,const VarDecl * VD)5263 static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5264 const VarDecl *VD) {
5265 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5266 if (!EvaluateDecompositionDeclInit(Info, DD))
5267 return false;
5268 }
5269 return true;
5270 }
5271
EvaluateDependentExpr(const Expr * E,EvalInfo & Info)5272 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5273 assert(E->isValueDependent());
5274 if (Info.noteSideEffect())
5275 return true;
5276 assert(E->containsErrors() && "valid value-dependent expression should never "
5277 "reach invalid code path.");
5278 return false;
5279 }
5280
5281 /// Evaluate a condition (either a variable declaration or an expression).
EvaluateCond(EvalInfo & Info,const VarDecl * CondDecl,const Expr * Cond,bool & Result)5282 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5283 const Expr *Cond, bool &Result) {
5284 if (Cond->isValueDependent())
5285 return false;
5286 FullExpressionRAII Scope(Info);
5287 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5288 return false;
5289 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5290 return false;
5291 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5292 return false;
5293 return Scope.destroy();
5294 }
5295
5296 namespace {
5297 /// A location where the result (returned value) of evaluating a
5298 /// statement should be stored.
5299 struct StmtResult {
5300 /// The APValue that should be filled in with the returned value.
5301 APValue &Value;
5302 /// The location containing the result, if any (used to support RVO).
5303 const LValue *Slot;
5304 };
5305
5306 struct TempVersionRAII {
5307 CallStackFrame &Frame;
5308
TempVersionRAII__anonfb577fba1111::TempVersionRAII5309 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5310 Frame.pushTempVersion();
5311 }
5312
~TempVersionRAII__anonfb577fba1111::TempVersionRAII5313 ~TempVersionRAII() {
5314 Frame.popTempVersion();
5315 }
5316 };
5317
5318 }
5319
5320 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5321 const Stmt *S,
5322 const SwitchCase *SC = nullptr);
5323
5324 /// Evaluate the body of a loop, and translate the result as appropriate.
EvaluateLoopBody(StmtResult & Result,EvalInfo & Info,const Stmt * Body,const SwitchCase * Case=nullptr)5325 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5326 const Stmt *Body,
5327 const SwitchCase *Case = nullptr) {
5328 BlockScopeRAII Scope(Info);
5329
5330 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5331 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5332 ESR = ESR_Failed;
5333
5334 switch (ESR) {
5335 case ESR_Break:
5336 return ESR_Succeeded;
5337 case ESR_Succeeded:
5338 case ESR_Continue:
5339 return ESR_Continue;
5340 case ESR_Failed:
5341 case ESR_Returned:
5342 case ESR_CaseNotFound:
5343 return ESR;
5344 }
5345 llvm_unreachable("Invalid EvalStmtResult!");
5346 }
5347
5348 /// Evaluate a switch statement.
EvaluateSwitch(StmtResult & Result,EvalInfo & Info,const SwitchStmt * SS)5349 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5350 const SwitchStmt *SS) {
5351 BlockScopeRAII Scope(Info);
5352
5353 // Evaluate the switch condition.
5354 APSInt Value;
5355 {
5356 if (const Stmt *Init = SS->getInit()) {
5357 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5358 if (ESR != ESR_Succeeded) {
5359 if (ESR != ESR_Failed && !Scope.destroy())
5360 ESR = ESR_Failed;
5361 return ESR;
5362 }
5363 }
5364
5365 FullExpressionRAII CondScope(Info);
5366 if (SS->getConditionVariable() &&
5367 !EvaluateDecl(Info, SS->getConditionVariable()))
5368 return ESR_Failed;
5369 if (SS->getCond()->isValueDependent()) {
5370 // We don't know what the value is, and which branch should jump to.
5371 EvaluateDependentExpr(SS->getCond(), Info);
5372 return ESR_Failed;
5373 }
5374 if (!EvaluateInteger(SS->getCond(), Value, Info))
5375 return ESR_Failed;
5376
5377 if (!MaybeEvaluateDeferredVarDeclInit(Info, SS->getConditionVariable()))
5378 return ESR_Failed;
5379
5380 if (!CondScope.destroy())
5381 return ESR_Failed;
5382 }
5383
5384 // Find the switch case corresponding to the value of the condition.
5385 // FIXME: Cache this lookup.
5386 const SwitchCase *Found = nullptr;
5387 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5388 SC = SC->getNextSwitchCase()) {
5389 if (isa<DefaultStmt>(SC)) {
5390 Found = SC;
5391 continue;
5392 }
5393
5394 const CaseStmt *CS = cast<CaseStmt>(SC);
5395 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5396 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5397 : LHS;
5398 if (LHS <= Value && Value <= RHS) {
5399 Found = SC;
5400 break;
5401 }
5402 }
5403
5404 if (!Found)
5405 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5406
5407 // Search the switch body for the switch case and evaluate it from there.
5408 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5409 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5410 return ESR_Failed;
5411
5412 switch (ESR) {
5413 case ESR_Break:
5414 return ESR_Succeeded;
5415 case ESR_Succeeded:
5416 case ESR_Continue:
5417 case ESR_Failed:
5418 case ESR_Returned:
5419 return ESR;
5420 case ESR_CaseNotFound:
5421 // This can only happen if the switch case is nested within a statement
5422 // expression. We have no intention of supporting that.
5423 Info.FFDiag(Found->getBeginLoc(),
5424 diag::note_constexpr_stmt_expr_unsupported);
5425 return ESR_Failed;
5426 }
5427 llvm_unreachable("Invalid EvalStmtResult!");
5428 }
5429
CheckLocalVariableDeclaration(EvalInfo & Info,const VarDecl * VD)5430 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5431 // An expression E is a core constant expression unless the evaluation of E
5432 // would evaluate one of the following: [C++23] - a control flow that passes
5433 // through a declaration of a variable with static or thread storage duration
5434 // unless that variable is usable in constant expressions.
5435 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5436 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5437 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5438 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5439 return false;
5440 }
5441 return true;
5442 }
5443
5444 // Evaluate a statement.
EvaluateStmt(StmtResult & Result,EvalInfo & Info,const Stmt * S,const SwitchCase * Case)5445 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5446 const Stmt *S, const SwitchCase *Case) {
5447 if (!Info.nextStep(S))
5448 return ESR_Failed;
5449
5450 // If we're hunting down a 'case' or 'default' label, recurse through
5451 // substatements until we hit the label.
5452 if (Case) {
5453 switch (S->getStmtClass()) {
5454 case Stmt::CompoundStmtClass:
5455 // FIXME: Precompute which substatement of a compound statement we
5456 // would jump to, and go straight there rather than performing a
5457 // linear scan each time.
5458 case Stmt::LabelStmtClass:
5459 case Stmt::AttributedStmtClass:
5460 case Stmt::DoStmtClass:
5461 break;
5462
5463 case Stmt::CaseStmtClass:
5464 case Stmt::DefaultStmtClass:
5465 if (Case == S)
5466 Case = nullptr;
5467 break;
5468
5469 case Stmt::IfStmtClass: {
5470 // FIXME: Precompute which side of an 'if' we would jump to, and go
5471 // straight there rather than scanning both sides.
5472 const IfStmt *IS = cast<IfStmt>(S);
5473
5474 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5475 // preceded by our switch label.
5476 BlockScopeRAII Scope(Info);
5477
5478 // Step into the init statement in case it brings an (uninitialized)
5479 // variable into scope.
5480 if (const Stmt *Init = IS->getInit()) {
5481 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5482 if (ESR != ESR_CaseNotFound) {
5483 assert(ESR != ESR_Succeeded);
5484 return ESR;
5485 }
5486 }
5487
5488 // Condition variable must be initialized if it exists.
5489 // FIXME: We can skip evaluating the body if there's a condition
5490 // variable, as there can't be any case labels within it.
5491 // (The same is true for 'for' statements.)
5492
5493 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5494 if (ESR == ESR_Failed)
5495 return ESR;
5496 if (ESR != ESR_CaseNotFound)
5497 return Scope.destroy() ? ESR : ESR_Failed;
5498 if (!IS->getElse())
5499 return ESR_CaseNotFound;
5500
5501 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5502 if (ESR == ESR_Failed)
5503 return ESR;
5504 if (ESR != ESR_CaseNotFound)
5505 return Scope.destroy() ? ESR : ESR_Failed;
5506 return ESR_CaseNotFound;
5507 }
5508
5509 case Stmt::WhileStmtClass: {
5510 EvalStmtResult ESR =
5511 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5512 if (ESR != ESR_Continue)
5513 return ESR;
5514 break;
5515 }
5516
5517 case Stmt::ForStmtClass: {
5518 const ForStmt *FS = cast<ForStmt>(S);
5519 BlockScopeRAII Scope(Info);
5520
5521 // Step into the init statement in case it brings an (uninitialized)
5522 // variable into scope.
5523 if (const Stmt *Init = FS->getInit()) {
5524 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5525 if (ESR != ESR_CaseNotFound) {
5526 assert(ESR != ESR_Succeeded);
5527 return ESR;
5528 }
5529 }
5530
5531 EvalStmtResult ESR =
5532 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5533 if (ESR != ESR_Continue)
5534 return ESR;
5535 if (const auto *Inc = FS->getInc()) {
5536 if (Inc->isValueDependent()) {
5537 if (!EvaluateDependentExpr(Inc, Info))
5538 return ESR_Failed;
5539 } else {
5540 FullExpressionRAII IncScope(Info);
5541 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5542 return ESR_Failed;
5543 }
5544 }
5545 break;
5546 }
5547
5548 case Stmt::DeclStmtClass: {
5549 // Start the lifetime of any uninitialized variables we encounter. They
5550 // might be used by the selected branch of the switch.
5551 const DeclStmt *DS = cast<DeclStmt>(S);
5552 for (const auto *D : DS->decls()) {
5553 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5554 if (!CheckLocalVariableDeclaration(Info, VD))
5555 return ESR_Failed;
5556 if (VD->hasLocalStorage() && !VD->getInit())
5557 if (!EvaluateVarDecl(Info, VD))
5558 return ESR_Failed;
5559 // FIXME: If the variable has initialization that can't be jumped
5560 // over, bail out of any immediately-surrounding compound-statement
5561 // too. There can't be any case labels here.
5562 }
5563 }
5564 return ESR_CaseNotFound;
5565 }
5566
5567 default:
5568 return ESR_CaseNotFound;
5569 }
5570 }
5571
5572 switch (S->getStmtClass()) {
5573 default:
5574 if (const Expr *E = dyn_cast<Expr>(S)) {
5575 if (E->isValueDependent()) {
5576 if (!EvaluateDependentExpr(E, Info))
5577 return ESR_Failed;
5578 } else {
5579 // Don't bother evaluating beyond an expression-statement which couldn't
5580 // be evaluated.
5581 // FIXME: Do we need the FullExpressionRAII object here?
5582 // VisitExprWithCleanups should create one when necessary.
5583 FullExpressionRAII Scope(Info);
5584 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5585 return ESR_Failed;
5586 }
5587 return ESR_Succeeded;
5588 }
5589
5590 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5591 return ESR_Failed;
5592
5593 case Stmt::NullStmtClass:
5594 return ESR_Succeeded;
5595
5596 case Stmt::DeclStmtClass: {
5597 const DeclStmt *DS = cast<DeclStmt>(S);
5598 for (const auto *D : DS->decls()) {
5599 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5600 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5601 return ESR_Failed;
5602 // Each declaration initialization is its own full-expression.
5603 FullExpressionRAII Scope(Info);
5604 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5605 !Info.noteFailure())
5606 return ESR_Failed;
5607 if (!Scope.destroy())
5608 return ESR_Failed;
5609 }
5610 return ESR_Succeeded;
5611 }
5612
5613 case Stmt::ReturnStmtClass: {
5614 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5615 FullExpressionRAII Scope(Info);
5616 if (RetExpr && RetExpr->isValueDependent()) {
5617 EvaluateDependentExpr(RetExpr, Info);
5618 // We know we returned, but we don't know what the value is.
5619 return ESR_Failed;
5620 }
5621 if (RetExpr &&
5622 !(Result.Slot
5623 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5624 : Evaluate(Result.Value, Info, RetExpr)))
5625 return ESR_Failed;
5626 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5627 }
5628
5629 case Stmt::CompoundStmtClass: {
5630 BlockScopeRAII Scope(Info);
5631
5632 const CompoundStmt *CS = cast<CompoundStmt>(S);
5633 for (const auto *BI : CS->body()) {
5634 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5635 if (ESR == ESR_Succeeded)
5636 Case = nullptr;
5637 else if (ESR != ESR_CaseNotFound) {
5638 if (ESR != ESR_Failed && !Scope.destroy())
5639 return ESR_Failed;
5640 return ESR;
5641 }
5642 }
5643 if (Case)
5644 return ESR_CaseNotFound;
5645 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5646 }
5647
5648 case Stmt::IfStmtClass: {
5649 const IfStmt *IS = cast<IfStmt>(S);
5650
5651 // Evaluate the condition, as either a var decl or as an expression.
5652 BlockScopeRAII Scope(Info);
5653 if (const Stmt *Init = IS->getInit()) {
5654 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5655 if (ESR != ESR_Succeeded) {
5656 if (ESR != ESR_Failed && !Scope.destroy())
5657 return ESR_Failed;
5658 return ESR;
5659 }
5660 }
5661 bool Cond;
5662 if (IS->isConsteval()) {
5663 Cond = IS->isNonNegatedConsteval();
5664 // If we are not in a constant context, if consteval should not evaluate
5665 // to true.
5666 if (!Info.InConstantContext)
5667 Cond = !Cond;
5668 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5669 Cond))
5670 return ESR_Failed;
5671
5672 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5673 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5674 if (ESR != ESR_Succeeded) {
5675 if (ESR != ESR_Failed && !Scope.destroy())
5676 return ESR_Failed;
5677 return ESR;
5678 }
5679 }
5680 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5681 }
5682
5683 case Stmt::WhileStmtClass: {
5684 const WhileStmt *WS = cast<WhileStmt>(S);
5685 while (true) {
5686 BlockScopeRAII Scope(Info);
5687 bool Continue;
5688 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5689 Continue))
5690 return ESR_Failed;
5691 if (!Continue)
5692 break;
5693
5694 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5695 if (ESR != ESR_Continue) {
5696 if (ESR != ESR_Failed && !Scope.destroy())
5697 return ESR_Failed;
5698 return ESR;
5699 }
5700 if (!Scope.destroy())
5701 return ESR_Failed;
5702 }
5703 return ESR_Succeeded;
5704 }
5705
5706 case Stmt::DoStmtClass: {
5707 const DoStmt *DS = cast<DoStmt>(S);
5708 bool Continue;
5709 do {
5710 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5711 if (ESR != ESR_Continue)
5712 return ESR;
5713 Case = nullptr;
5714
5715 if (DS->getCond()->isValueDependent()) {
5716 EvaluateDependentExpr(DS->getCond(), Info);
5717 // Bailout as we don't know whether to keep going or terminate the loop.
5718 return ESR_Failed;
5719 }
5720 FullExpressionRAII CondScope(Info);
5721 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5722 !CondScope.destroy())
5723 return ESR_Failed;
5724 } while (Continue);
5725 return ESR_Succeeded;
5726 }
5727
5728 case Stmt::ForStmtClass: {
5729 const ForStmt *FS = cast<ForStmt>(S);
5730 BlockScopeRAII ForScope(Info);
5731 if (FS->getInit()) {
5732 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5733 if (ESR != ESR_Succeeded) {
5734 if (ESR != ESR_Failed && !ForScope.destroy())
5735 return ESR_Failed;
5736 return ESR;
5737 }
5738 }
5739 while (true) {
5740 BlockScopeRAII IterScope(Info);
5741 bool Continue = true;
5742 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5743 FS->getCond(), Continue))
5744 return ESR_Failed;
5745
5746 if (!Continue) {
5747 if (!IterScope.destroy())
5748 return ESR_Failed;
5749 break;
5750 }
5751
5752 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5753 if (ESR != ESR_Continue) {
5754 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5755 return ESR_Failed;
5756 return ESR;
5757 }
5758
5759 if (const auto *Inc = FS->getInc()) {
5760 if (Inc->isValueDependent()) {
5761 if (!EvaluateDependentExpr(Inc, Info))
5762 return ESR_Failed;
5763 } else {
5764 FullExpressionRAII IncScope(Info);
5765 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5766 return ESR_Failed;
5767 }
5768 }
5769
5770 if (!IterScope.destroy())
5771 return ESR_Failed;
5772 }
5773 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5774 }
5775
5776 case Stmt::CXXForRangeStmtClass: {
5777 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5778 BlockScopeRAII Scope(Info);
5779
5780 // Evaluate the init-statement if present.
5781 if (FS->getInit()) {
5782 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5783 if (ESR != ESR_Succeeded) {
5784 if (ESR != ESR_Failed && !Scope.destroy())
5785 return ESR_Failed;
5786 return ESR;
5787 }
5788 }
5789
5790 // Initialize the __range variable.
5791 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5792 if (ESR != ESR_Succeeded) {
5793 if (ESR != ESR_Failed && !Scope.destroy())
5794 return ESR_Failed;
5795 return ESR;
5796 }
5797
5798 // In error-recovery cases it's possible to get here even if we failed to
5799 // synthesize the __begin and __end variables.
5800 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5801 return ESR_Failed;
5802
5803 // Create the __begin and __end iterators.
5804 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5805 if (ESR != ESR_Succeeded) {
5806 if (ESR != ESR_Failed && !Scope.destroy())
5807 return ESR_Failed;
5808 return ESR;
5809 }
5810 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5811 if (ESR != ESR_Succeeded) {
5812 if (ESR != ESR_Failed && !Scope.destroy())
5813 return ESR_Failed;
5814 return ESR;
5815 }
5816
5817 while (true) {
5818 // Condition: __begin != __end.
5819 {
5820 if (FS->getCond()->isValueDependent()) {
5821 EvaluateDependentExpr(FS->getCond(), Info);
5822 // We don't know whether to keep going or terminate the loop.
5823 return ESR_Failed;
5824 }
5825 bool Continue = true;
5826 FullExpressionRAII CondExpr(Info);
5827 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5828 return ESR_Failed;
5829 if (!Continue)
5830 break;
5831 }
5832
5833 // User's variable declaration, initialized by *__begin.
5834 BlockScopeRAII InnerScope(Info);
5835 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5836 if (ESR != ESR_Succeeded) {
5837 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5838 return ESR_Failed;
5839 return ESR;
5840 }
5841
5842 // Loop body.
5843 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5844 if (ESR != ESR_Continue) {
5845 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5846 return ESR_Failed;
5847 return ESR;
5848 }
5849 if (FS->getInc()->isValueDependent()) {
5850 if (!EvaluateDependentExpr(FS->getInc(), Info))
5851 return ESR_Failed;
5852 } else {
5853 // Increment: ++__begin
5854 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5855 return ESR_Failed;
5856 }
5857
5858 if (!InnerScope.destroy())
5859 return ESR_Failed;
5860 }
5861
5862 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5863 }
5864
5865 case Stmt::SwitchStmtClass:
5866 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5867
5868 case Stmt::ContinueStmtClass:
5869 return ESR_Continue;
5870
5871 case Stmt::BreakStmtClass:
5872 return ESR_Break;
5873
5874 case Stmt::LabelStmtClass:
5875 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5876
5877 case Stmt::AttributedStmtClass: {
5878 const auto *AS = cast<AttributedStmt>(S);
5879 const auto *SS = AS->getSubStmt();
5880 MSConstexprContextRAII ConstexprContext(
5881 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5882 isa<ReturnStmt>(SS));
5883
5884 auto LO = Info.getASTContext().getLangOpts();
5885 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5886 for (auto *Attr : AS->getAttrs()) {
5887 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5888 if (!AA)
5889 continue;
5890
5891 auto *Assumption = AA->getAssumption();
5892 if (Assumption->isValueDependent())
5893 return ESR_Failed;
5894
5895 if (Assumption->HasSideEffects(Info.getASTContext()))
5896 continue;
5897
5898 bool Value;
5899 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5900 return ESR_Failed;
5901 if (!Value) {
5902 Info.CCEDiag(Assumption->getExprLoc(),
5903 diag::note_constexpr_assumption_failed);
5904 return ESR_Failed;
5905 }
5906 }
5907 }
5908
5909 return EvaluateStmt(Result, Info, SS, Case);
5910 }
5911
5912 case Stmt::CaseStmtClass:
5913 case Stmt::DefaultStmtClass:
5914 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5915 case Stmt::CXXTryStmtClass:
5916 // Evaluate try blocks by evaluating all sub statements.
5917 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5918 }
5919 }
5920
5921 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5922 /// default constructor. If so, we'll fold it whether or not it's marked as
5923 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5924 /// so we need special handling.
CheckTrivialDefaultConstructor(EvalInfo & Info,SourceLocation Loc,const CXXConstructorDecl * CD,bool IsValueInitialization)5925 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5926 const CXXConstructorDecl *CD,
5927 bool IsValueInitialization) {
5928 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5929 return false;
5930
5931 // Value-initialization does not call a trivial default constructor, so such a
5932 // call is a core constant expression whether or not the constructor is
5933 // constexpr.
5934 if (!CD->isConstexpr() && !IsValueInitialization) {
5935 if (Info.getLangOpts().CPlusPlus11) {
5936 // FIXME: If DiagDecl is an implicitly-declared special member function,
5937 // we should be much more explicit about why it's not constexpr.
5938 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5939 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5940 Info.Note(CD->getLocation(), diag::note_declared_at);
5941 } else {
5942 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5943 }
5944 }
5945 return true;
5946 }
5947
5948 /// CheckConstexprFunction - Check that a function can be called in a constant
5949 /// expression.
CheckConstexprFunction(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Declaration,const FunctionDecl * Definition,const Stmt * Body)5950 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5951 const FunctionDecl *Declaration,
5952 const FunctionDecl *Definition,
5953 const Stmt *Body) {
5954 // Potential constant expressions can contain calls to declared, but not yet
5955 // defined, constexpr functions.
5956 if (Info.checkingPotentialConstantExpression() && !Definition &&
5957 Declaration->isConstexpr())
5958 return false;
5959
5960 // Bail out if the function declaration itself is invalid. We will
5961 // have produced a relevant diagnostic while parsing it, so just
5962 // note the problematic sub-expression.
5963 if (Declaration->isInvalidDecl()) {
5964 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5965 return false;
5966 }
5967
5968 // DR1872: An instantiated virtual constexpr function can't be called in a
5969 // constant expression (prior to C++20). We can still constant-fold such a
5970 // call.
5971 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5972 cast<CXXMethodDecl>(Declaration)->isVirtual())
5973 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5974
5975 if (Definition && Definition->isInvalidDecl()) {
5976 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5977 return false;
5978 }
5979
5980 // Can we evaluate this function call?
5981 if (Definition && Body &&
5982 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5983 Definition->hasAttr<MSConstexprAttr>())))
5984 return true;
5985
5986 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5987 // Special note for the assert() macro, as the normal error message falsely
5988 // implies we cannot use an assertion during constant evaluation.
5989 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
5990 // FIXME: Instead of checking for an implementation-defined function,
5991 // check and evaluate the assert() macro.
5992 StringRef Name = DiagDecl->getName();
5993 bool AssertFailed =
5994 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
5995 if (AssertFailed) {
5996 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
5997 return false;
5998 }
5999 }
6000
6001 if (Info.getLangOpts().CPlusPlus11) {
6002 // If this function is not constexpr because it is an inherited
6003 // non-constexpr constructor, diagnose that directly.
6004 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6005 if (CD && CD->isInheritingConstructor()) {
6006 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6007 if (!Inherited->isConstexpr())
6008 DiagDecl = CD = Inherited;
6009 }
6010
6011 // FIXME: If DiagDecl is an implicitly-declared special member function
6012 // or an inheriting constructor, we should be much more explicit about why
6013 // it's not constexpr.
6014 if (CD && CD->isInheritingConstructor())
6015 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6016 << CD->getInheritedConstructor().getConstructor()->getParent();
6017 else
6018 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6019 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6020 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6021 } else {
6022 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6023 }
6024 return false;
6025 }
6026
6027 namespace {
6028 struct CheckDynamicTypeHandler {
6029 AccessKinds AccessKind;
6030 typedef bool result_type;
failed__anonfb577fba1211::CheckDynamicTypeHandler6031 bool failed() { return false; }
found__anonfb577fba1211::CheckDynamicTypeHandler6032 bool found(APValue &Subobj, QualType SubobjType) { return true; }
found__anonfb577fba1211::CheckDynamicTypeHandler6033 bool found(APSInt &Value, QualType SubobjType) { return true; }
found__anonfb577fba1211::CheckDynamicTypeHandler6034 bool found(APFloat &Value, QualType SubobjType) { return true; }
6035 };
6036 } // end anonymous namespace
6037
6038 /// Check that we can access the notional vptr of an object / determine its
6039 /// dynamic type.
checkDynamicType(EvalInfo & Info,const Expr * E,const LValue & This,AccessKinds AK,bool Polymorphic)6040 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6041 AccessKinds AK, bool Polymorphic) {
6042 if (This.Designator.Invalid)
6043 return false;
6044
6045 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6046
6047 if (!Obj)
6048 return false;
6049
6050 if (!Obj.Value) {
6051 // The object is not usable in constant expressions, so we can't inspect
6052 // its value to see if it's in-lifetime or what the active union members
6053 // are. We can still check for a one-past-the-end lvalue.
6054 if (This.Designator.isOnePastTheEnd() ||
6055 This.Designator.isMostDerivedAnUnsizedArray()) {
6056 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6057 ? diag::note_constexpr_access_past_end
6058 : diag::note_constexpr_access_unsized_array)
6059 << AK;
6060 return false;
6061 } else if (Polymorphic) {
6062 // Conservatively refuse to perform a polymorphic operation if we would
6063 // not be able to read a notional 'vptr' value.
6064 APValue Val;
6065 This.moveInto(Val);
6066 QualType StarThisType =
6067 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6068 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6069 << AK << Val.getAsString(Info.Ctx, StarThisType);
6070 return false;
6071 }
6072 return true;
6073 }
6074
6075 CheckDynamicTypeHandler Handler{AK};
6076 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6077 }
6078
6079 /// Check that the pointee of the 'this' pointer in a member function call is
6080 /// either within its lifetime or in its period of construction or destruction.
6081 static bool
checkNonVirtualMemberCallThisPointer(EvalInfo & Info,const Expr * E,const LValue & This,const CXXMethodDecl * NamedMember)6082 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
6083 const LValue &This,
6084 const CXXMethodDecl *NamedMember) {
6085 return checkDynamicType(
6086 Info, E, This,
6087 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6088 }
6089
6090 struct DynamicType {
6091 /// The dynamic class type of the object.
6092 const CXXRecordDecl *Type;
6093 /// The corresponding path length in the lvalue.
6094 unsigned PathLength;
6095 };
6096
getBaseClassType(SubobjectDesignator & Designator,unsigned PathLength)6097 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6098 unsigned PathLength) {
6099 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6100 Designator.Entries.size() && "invalid path length");
6101 return (PathLength == Designator.MostDerivedPathLength)
6102 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6103 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6104 }
6105
6106 /// Determine the dynamic type of an object.
ComputeDynamicType(EvalInfo & Info,const Expr * E,LValue & This,AccessKinds AK)6107 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6108 const Expr *E,
6109 LValue &This,
6110 AccessKinds AK) {
6111 // If we don't have an lvalue denoting an object of class type, there is no
6112 // meaningful dynamic type. (We consider objects of non-class type to have no
6113 // dynamic type.)
6114 if (!checkDynamicType(Info, E, This, AK,
6115 AK != AK_TypeId || This.AllowConstexprUnknown))
6116 return std::nullopt;
6117
6118 if (This.Designator.Invalid)
6119 return std::nullopt;
6120
6121 // Refuse to compute a dynamic type in the presence of virtual bases. This
6122 // shouldn't happen other than in constant-folding situations, since literal
6123 // types can't have virtual bases.
6124 //
6125 // Note that consumers of DynamicType assume that the type has no virtual
6126 // bases, and will need modifications if this restriction is relaxed.
6127 const CXXRecordDecl *Class =
6128 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6129 if (!Class || Class->getNumVBases()) {
6130 Info.FFDiag(E);
6131 return std::nullopt;
6132 }
6133
6134 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6135 // binary search here instead. But the overwhelmingly common case is that
6136 // we're not in the middle of a constructor, so it probably doesn't matter
6137 // in practice.
6138 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6139 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6140 PathLength <= Path.size(); ++PathLength) {
6141 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6142 Path.slice(0, PathLength))) {
6143 case ConstructionPhase::Bases:
6144 case ConstructionPhase::DestroyingBases:
6145 // We're constructing or destroying a base class. This is not the dynamic
6146 // type.
6147 break;
6148
6149 case ConstructionPhase::None:
6150 case ConstructionPhase::AfterBases:
6151 case ConstructionPhase::AfterFields:
6152 case ConstructionPhase::Destroying:
6153 // We've finished constructing the base classes and not yet started
6154 // destroying them again, so this is the dynamic type.
6155 return DynamicType{getBaseClassType(This.Designator, PathLength),
6156 PathLength};
6157 }
6158 }
6159
6160 // CWG issue 1517: we're constructing a base class of the object described by
6161 // 'This', so that object has not yet begun its period of construction and
6162 // any polymorphic operation on it results in undefined behavior.
6163 Info.FFDiag(E);
6164 return std::nullopt;
6165 }
6166
6167 /// Perform virtual dispatch.
HandleVirtualDispatch(EvalInfo & Info,const Expr * E,LValue & This,const CXXMethodDecl * Found,llvm::SmallVectorImpl<QualType> & CovariantAdjustmentPath)6168 static const CXXMethodDecl *HandleVirtualDispatch(
6169 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6170 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6171 std::optional<DynamicType> DynType = ComputeDynamicType(
6172 Info, E, This,
6173 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
6174 if (!DynType)
6175 return nullptr;
6176
6177 // Find the final overrider. It must be declared in one of the classes on the
6178 // path from the dynamic type to the static type.
6179 // FIXME: If we ever allow literal types to have virtual base classes, that
6180 // won't be true.
6181 const CXXMethodDecl *Callee = Found;
6182 unsigned PathLength = DynType->PathLength;
6183 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6184 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6185 const CXXMethodDecl *Overrider =
6186 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6187 if (Overrider) {
6188 Callee = Overrider;
6189 break;
6190 }
6191 }
6192
6193 // C++2a [class.abstract]p6:
6194 // the effect of making a virtual call to a pure virtual function [...] is
6195 // undefined
6196 if (Callee->isPureVirtual()) {
6197 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6198 Info.Note(Callee->getLocation(), diag::note_declared_at);
6199 return nullptr;
6200 }
6201
6202 // If necessary, walk the rest of the path to determine the sequence of
6203 // covariant adjustment steps to apply.
6204 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6205 Found->getReturnType())) {
6206 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6207 for (unsigned CovariantPathLength = PathLength + 1;
6208 CovariantPathLength != This.Designator.Entries.size();
6209 ++CovariantPathLength) {
6210 const CXXRecordDecl *NextClass =
6211 getBaseClassType(This.Designator, CovariantPathLength);
6212 const CXXMethodDecl *Next =
6213 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6214 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6215 Next->getReturnType(), CovariantAdjustmentPath.back()))
6216 CovariantAdjustmentPath.push_back(Next->getReturnType());
6217 }
6218 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6219 CovariantAdjustmentPath.back()))
6220 CovariantAdjustmentPath.push_back(Found->getReturnType());
6221 }
6222
6223 // Perform 'this' adjustment.
6224 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6225 return nullptr;
6226
6227 return Callee;
6228 }
6229
6230 /// Perform the adjustment from a value returned by a virtual function to
6231 /// a value of the statically expected type, which may be a pointer or
6232 /// reference to a base class of the returned type.
HandleCovariantReturnAdjustment(EvalInfo & Info,const Expr * E,APValue & Result,ArrayRef<QualType> Path)6233 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6234 APValue &Result,
6235 ArrayRef<QualType> Path) {
6236 assert(Result.isLValue() &&
6237 "unexpected kind of APValue for covariant return");
6238 if (Result.isNullPointer())
6239 return true;
6240
6241 LValue LVal;
6242 LVal.setFrom(Info.Ctx, Result);
6243
6244 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6245 for (unsigned I = 1; I != Path.size(); ++I) {
6246 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6247 assert(OldClass && NewClass && "unexpected kind of covariant return");
6248 if (OldClass != NewClass &&
6249 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6250 return false;
6251 OldClass = NewClass;
6252 }
6253
6254 LVal.moveInto(Result);
6255 return true;
6256 }
6257
6258 /// Determine whether \p Base, which is known to be a direct base class of
6259 /// \p Derived, is a public base class.
isBaseClassPublic(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)6260 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6261 const CXXRecordDecl *Base) {
6262 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6263 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6264 if (BaseClass && declaresSameEntity(BaseClass, Base))
6265 return BaseSpec.getAccessSpecifier() == AS_public;
6266 }
6267 llvm_unreachable("Base is not a direct base of Derived");
6268 }
6269
6270 /// Apply the given dynamic cast operation on the provided lvalue.
6271 ///
6272 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
6273 /// to find a suitable target subobject.
HandleDynamicCast(EvalInfo & Info,const ExplicitCastExpr * E,LValue & Ptr)6274 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6275 LValue &Ptr) {
6276 // We can't do anything with a non-symbolic pointer value.
6277 SubobjectDesignator &D = Ptr.Designator;
6278 if (D.Invalid)
6279 return false;
6280
6281 // C++ [expr.dynamic.cast]p6:
6282 // If v is a null pointer value, the result is a null pointer value.
6283 if (Ptr.isNullPointer() && !E->isGLValue())
6284 return true;
6285
6286 // For all the other cases, we need the pointer to point to an object within
6287 // its lifetime / period of construction / destruction, and we need to know
6288 // its dynamic type.
6289 std::optional<DynamicType> DynType =
6290 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6291 if (!DynType)
6292 return false;
6293
6294 // C++ [expr.dynamic.cast]p7:
6295 // If T is "pointer to cv void", then the result is a pointer to the most
6296 // derived object
6297 if (E->getType()->isVoidPointerType())
6298 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6299
6300 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6301 assert(C && "dynamic_cast target is not void pointer nor class");
6302 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
6303
6304 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6305 // C++ [expr.dynamic.cast]p9:
6306 if (!E->isGLValue()) {
6307 // The value of a failed cast to pointer type is the null pointer value
6308 // of the required result type.
6309 Ptr.setNull(Info.Ctx, E->getType());
6310 return true;
6311 }
6312
6313 // A failed cast to reference type throws [...] std::bad_cast.
6314 unsigned DiagKind;
6315 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6316 DynType->Type->isDerivedFrom(C)))
6317 DiagKind = 0;
6318 else if (!Paths || Paths->begin() == Paths->end())
6319 DiagKind = 1;
6320 else if (Paths->isAmbiguous(CQT))
6321 DiagKind = 2;
6322 else {
6323 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6324 DiagKind = 3;
6325 }
6326 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6327 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6328 << Info.Ctx.getRecordType(DynType->Type)
6329 << E->getType().getUnqualifiedType();
6330 return false;
6331 };
6332
6333 // Runtime check, phase 1:
6334 // Walk from the base subobject towards the derived object looking for the
6335 // target type.
6336 for (int PathLength = Ptr.Designator.Entries.size();
6337 PathLength >= (int)DynType->PathLength; --PathLength) {
6338 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6339 if (declaresSameEntity(Class, C))
6340 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6341 // We can only walk across public inheritance edges.
6342 if (PathLength > (int)DynType->PathLength &&
6343 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6344 Class))
6345 return RuntimeCheckFailed(nullptr);
6346 }
6347
6348 // Runtime check, phase 2:
6349 // Search the dynamic type for an unambiguous public base of type C.
6350 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6351 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6352 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6353 Paths.front().Access == AS_public) {
6354 // Downcast to the dynamic type...
6355 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6356 return false;
6357 // ... then upcast to the chosen base class subobject.
6358 for (CXXBasePathElement &Elem : Paths.front())
6359 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6360 return false;
6361 return true;
6362 }
6363
6364 // Otherwise, the runtime check fails.
6365 return RuntimeCheckFailed(&Paths);
6366 }
6367
6368 namespace {
6369 struct StartLifetimeOfUnionMemberHandler {
6370 EvalInfo &Info;
6371 const Expr *LHSExpr;
6372 const FieldDecl *Field;
6373 bool DuringInit;
6374 bool Failed = false;
6375 static const AccessKinds AccessKind = AK_Assign;
6376
6377 typedef bool result_type;
failed__anonfb577fba1411::StartLifetimeOfUnionMemberHandler6378 bool failed() { return Failed; }
found__anonfb577fba1411::StartLifetimeOfUnionMemberHandler6379 bool found(APValue &Subobj, QualType SubobjType) {
6380 // We are supposed to perform no initialization but begin the lifetime of
6381 // the object. We interpret that as meaning to do what default
6382 // initialization of the object would do if all constructors involved were
6383 // trivial:
6384 // * All base, non-variant member, and array element subobjects' lifetimes
6385 // begin
6386 // * No variant members' lifetimes begin
6387 // * All scalar subobjects whose lifetimes begin have indeterminate values
6388 assert(SubobjType->isUnionType());
6389 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6390 // This union member is already active. If it's also in-lifetime, there's
6391 // nothing to do.
6392 if (Subobj.getUnionValue().hasValue())
6393 return true;
6394 } else if (DuringInit) {
6395 // We're currently in the process of initializing a different union
6396 // member. If we carried on, that initialization would attempt to
6397 // store to an inactive union member, resulting in undefined behavior.
6398 Info.FFDiag(LHSExpr,
6399 diag::note_constexpr_union_member_change_during_init);
6400 return false;
6401 }
6402 APValue Result;
6403 Failed = !handleDefaultInitValue(Field->getType(), Result);
6404 Subobj.setUnion(Field, Result);
6405 return true;
6406 }
found__anonfb577fba1411::StartLifetimeOfUnionMemberHandler6407 bool found(APSInt &Value, QualType SubobjType) {
6408 llvm_unreachable("wrong value kind for union object");
6409 }
found__anonfb577fba1411::StartLifetimeOfUnionMemberHandler6410 bool found(APFloat &Value, QualType SubobjType) {
6411 llvm_unreachable("wrong value kind for union object");
6412 }
6413 };
6414 } // end anonymous namespace
6415
6416 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6417
6418 /// Handle a builtin simple-assignment or a call to a trivial assignment
6419 /// operator whose left-hand side might involve a union member access. If it
6420 /// does, implicitly start the lifetime of any accessed union elements per
6421 /// C++20 [class.union]5.
MaybeHandleUnionActiveMemberChange(EvalInfo & Info,const Expr * LHSExpr,const LValue & LHS)6422 static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6423 const Expr *LHSExpr,
6424 const LValue &LHS) {
6425 if (LHS.InvalidBase || LHS.Designator.Invalid)
6426 return false;
6427
6428 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
6429 // C++ [class.union]p5:
6430 // define the set S(E) of subexpressions of E as follows:
6431 unsigned PathLength = LHS.Designator.Entries.size();
6432 for (const Expr *E = LHSExpr; E != nullptr;) {
6433 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6434 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6435 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6436 // Note that we can't implicitly start the lifetime of a reference,
6437 // so we don't need to proceed any further if we reach one.
6438 if (!FD || FD->getType()->isReferenceType())
6439 break;
6440
6441 // ... and also contains A.B if B names a union member ...
6442 if (FD->getParent()->isUnion()) {
6443 // ... of a non-class, non-array type, or of a class type with a
6444 // trivial default constructor that is not deleted, or an array of
6445 // such types.
6446 auto *RD =
6447 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6448 if (!RD || RD->hasTrivialDefaultConstructor())
6449 UnionPathLengths.push_back({PathLength - 1, FD});
6450 }
6451
6452 E = ME->getBase();
6453 --PathLength;
6454 assert(declaresSameEntity(FD,
6455 LHS.Designator.Entries[PathLength]
6456 .getAsBaseOrMember().getPointer()));
6457
6458 // -- If E is of the form A[B] and is interpreted as a built-in array
6459 // subscripting operator, S(E) is [S(the array operand, if any)].
6460 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6461 // Step over an ArrayToPointerDecay implicit cast.
6462 auto *Base = ASE->getBase()->IgnoreImplicit();
6463 if (!Base->getType()->isArrayType())
6464 break;
6465
6466 E = Base;
6467 --PathLength;
6468
6469 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6470 // Step over a derived-to-base conversion.
6471 E = ICE->getSubExpr();
6472 if (ICE->getCastKind() == CK_NoOp)
6473 continue;
6474 if (ICE->getCastKind() != CK_DerivedToBase &&
6475 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6476 break;
6477 // Walk path backwards as we walk up from the base to the derived class.
6478 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6479 if (Elt->isVirtual()) {
6480 // A class with virtual base classes never has a trivial default
6481 // constructor, so S(E) is empty in this case.
6482 E = nullptr;
6483 break;
6484 }
6485
6486 --PathLength;
6487 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6488 LHS.Designator.Entries[PathLength]
6489 .getAsBaseOrMember().getPointer()));
6490 }
6491
6492 // -- Otherwise, S(E) is empty.
6493 } else {
6494 break;
6495 }
6496 }
6497
6498 // Common case: no unions' lifetimes are started.
6499 if (UnionPathLengths.empty())
6500 return true;
6501
6502 // if modification of X [would access an inactive union member], an object
6503 // of the type of X is implicitly created
6504 CompleteObject Obj =
6505 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6506 if (!Obj)
6507 return false;
6508 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6509 llvm::reverse(UnionPathLengths)) {
6510 // Form a designator for the union object.
6511 SubobjectDesignator D = LHS.Designator;
6512 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6513
6514 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6515 ConstructionPhase::AfterBases;
6516 StartLifetimeOfUnionMemberHandler StartLifetime{
6517 Info, LHSExpr, LengthAndField.second, DuringInit};
6518 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6519 return false;
6520 }
6521
6522 return true;
6523 }
6524
EvaluateCallArg(const ParmVarDecl * PVD,const Expr * Arg,CallRef Call,EvalInfo & Info,bool NonNull=false,APValue ** EvaluatedArg=nullptr)6525 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6526 CallRef Call, EvalInfo &Info, bool NonNull = false,
6527 APValue **EvaluatedArg = nullptr) {
6528 LValue LV;
6529 // Create the parameter slot and register its destruction. For a vararg
6530 // argument, create a temporary.
6531 // FIXME: For calling conventions that destroy parameters in the callee,
6532 // should we consider performing destruction when the function returns
6533 // instead?
6534 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6535 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6536 ScopeKind::Call, LV);
6537 if (!EvaluateInPlace(V, Info, LV, Arg))
6538 return false;
6539
6540 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6541 // undefined behavior, so is non-constant.
6542 if (NonNull && V.isLValue() && V.isNullPointer()) {
6543 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6544 return false;
6545 }
6546
6547 if (EvaluatedArg)
6548 *EvaluatedArg = &V;
6549
6550 return true;
6551 }
6552
6553 /// Evaluate the arguments to a function call.
EvaluateArgs(ArrayRef<const Expr * > Args,CallRef Call,EvalInfo & Info,const FunctionDecl * Callee,bool RightToLeft=false,LValue * ObjectArg=nullptr)6554 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6555 EvalInfo &Info, const FunctionDecl *Callee,
6556 bool RightToLeft = false,
6557 LValue *ObjectArg = nullptr) {
6558 bool Success = true;
6559 llvm::SmallBitVector ForbiddenNullArgs;
6560 if (Callee->hasAttr<NonNullAttr>()) {
6561 ForbiddenNullArgs.resize(Args.size());
6562 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6563 if (!Attr->args_size()) {
6564 ForbiddenNullArgs.set();
6565 break;
6566 } else
6567 for (auto Idx : Attr->args()) {
6568 unsigned ASTIdx = Idx.getASTIndex();
6569 if (ASTIdx >= Args.size())
6570 continue;
6571 ForbiddenNullArgs[ASTIdx] = true;
6572 }
6573 }
6574 }
6575 for (unsigned I = 0; I < Args.size(); I++) {
6576 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6577 const ParmVarDecl *PVD =
6578 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6579 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6580 APValue *That = nullptr;
6581 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6582 // If we're checking for a potential constant expression, evaluate all
6583 // initializers even if some of them fail.
6584 if (!Info.noteFailure())
6585 return false;
6586 Success = false;
6587 }
6588 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6589 ObjectArg->setFrom(Info.Ctx, *That);
6590 }
6591 return Success;
6592 }
6593
6594 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6595 /// constructor or assignment operator.
handleTrivialCopy(EvalInfo & Info,const ParmVarDecl * Param,const Expr * E,APValue & Result,bool CopyObjectRepresentation)6596 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6597 const Expr *E, APValue &Result,
6598 bool CopyObjectRepresentation) {
6599 // Find the reference argument.
6600 CallStackFrame *Frame = Info.CurrentCall;
6601 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6602 if (!RefValue) {
6603 Info.FFDiag(E);
6604 return false;
6605 }
6606
6607 // Copy out the contents of the RHS object.
6608 LValue RefLValue;
6609 RefLValue.setFrom(Info.Ctx, *RefValue);
6610 return handleLValueToRValueConversion(
6611 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6612 CopyObjectRepresentation);
6613 }
6614
6615 /// Evaluate a function call.
HandleFunctionCall(SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * ObjectArg,const Expr * E,ArrayRef<const Expr * > Args,CallRef Call,const Stmt * Body,EvalInfo & Info,APValue & Result,const LValue * ResultSlot)6616 static bool HandleFunctionCall(SourceLocation CallLoc,
6617 const FunctionDecl *Callee,
6618 const LValue *ObjectArg, const Expr *E,
6619 ArrayRef<const Expr *> Args, CallRef Call,
6620 const Stmt *Body, EvalInfo &Info,
6621 APValue &Result, const LValue *ResultSlot) {
6622 if (!Info.CheckCallLimit(CallLoc))
6623 return false;
6624
6625 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
6626
6627 // For a trivial copy or move assignment, perform an APValue copy. This is
6628 // essential for unions, where the operations performed by the assignment
6629 // operator cannot be represented as statements.
6630 //
6631 // Skip this for non-union classes with no fields; in that case, the defaulted
6632 // copy/move does not actually read the object.
6633 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6634 if (MD && MD->isDefaulted() &&
6635 (MD->getParent()->isUnion() ||
6636 (MD->isTrivial() &&
6637 isReadByLvalueToRvalueConversion(MD->getParent())))) {
6638 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
6639 assert(ObjectArg &&
6640 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6641 APValue RHSValue;
6642 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6643 MD->getParent()->isUnion()))
6644 return false;
6645
6646 LValue Obj;
6647 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
6648 MD->getFunctionObjectParameterReferenceType(),
6649 RHSValue))
6650 return false;
6651 ObjectArg->moveInto(Result);
6652 return true;
6653 } else if (MD && isLambdaCallOperator(MD)) {
6654 // We're in a lambda; determine the lambda capture field maps unless we're
6655 // just constexpr checking a lambda's call operator. constexpr checking is
6656 // done before the captures have been added to the closure object (unless
6657 // we're inferring constexpr-ness), so we don't have access to them in this
6658 // case. But since we don't need the captures to constexpr check, we can
6659 // just ignore them.
6660 if (!Info.checkingPotentialConstantExpression())
6661 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6662 Frame.LambdaThisCaptureField);
6663 }
6664
6665 StmtResult Ret = {Result, ResultSlot};
6666 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6667 if (ESR == ESR_Succeeded) {
6668 if (Callee->getReturnType()->isVoidType())
6669 return true;
6670 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6671 }
6672 return ESR == ESR_Returned;
6673 }
6674
6675 /// Evaluate a constructor call.
HandleConstructorCall(const Expr * E,const LValue & This,CallRef Call,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6676 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6677 CallRef Call,
6678 const CXXConstructorDecl *Definition,
6679 EvalInfo &Info, APValue &Result) {
6680 SourceLocation CallLoc = E->getExprLoc();
6681 if (!Info.CheckCallLimit(CallLoc))
6682 return false;
6683
6684 const CXXRecordDecl *RD = Definition->getParent();
6685 if (RD->getNumVBases()) {
6686 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6687 return false;
6688 }
6689
6690 EvalInfo::EvaluatingConstructorRAII EvalObj(
6691 Info,
6692 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6693 RD->getNumBases());
6694 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6695
6696 // FIXME: Creating an APValue just to hold a nonexistent return value is
6697 // wasteful.
6698 APValue RetVal;
6699 StmtResult Ret = {RetVal, nullptr};
6700
6701 // If it's a delegating constructor, delegate.
6702 if (Definition->isDelegatingConstructor()) {
6703 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6704 if ((*I)->getInit()->isValueDependent()) {
6705 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6706 return false;
6707 } else {
6708 FullExpressionRAII InitScope(Info);
6709 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6710 !InitScope.destroy())
6711 return false;
6712 }
6713 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6714 }
6715
6716 // For a trivial copy or move constructor, perform an APValue copy. This is
6717 // essential for unions (or classes with anonymous union members), where the
6718 // operations performed by the constructor cannot be represented by
6719 // ctor-initializers.
6720 //
6721 // Skip this for empty non-union classes; we should not perform an
6722 // lvalue-to-rvalue conversion on them because their copy constructor does not
6723 // actually read them.
6724 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6725 (Definition->getParent()->isUnion() ||
6726 (Definition->isTrivial() &&
6727 isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6728 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6729 Definition->getParent()->isUnion());
6730 }
6731
6732 // Reserve space for the struct members.
6733 if (!Result.hasValue()) {
6734 if (!RD->isUnion())
6735 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6736 std::distance(RD->field_begin(), RD->field_end()));
6737 else
6738 // A union starts with no active member.
6739 Result = APValue((const FieldDecl*)nullptr);
6740 }
6741
6742 if (RD->isInvalidDecl()) return false;
6743 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6744
6745 // A scope for temporaries lifetime-extended by reference members.
6746 BlockScopeRAII LifetimeExtendedScope(Info);
6747
6748 bool Success = true;
6749 unsigned BasesSeen = 0;
6750 #ifndef NDEBUG
6751 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6752 #endif
6753 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6754 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6755 // We might be initializing the same field again if this is an indirect
6756 // field initialization.
6757 if (FieldIt == RD->field_end() ||
6758 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6759 assert(Indirect && "fields out of order?");
6760 return;
6761 }
6762
6763 // Default-initialize any fields with no explicit initializer.
6764 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6765 assert(FieldIt != RD->field_end() && "missing field?");
6766 if (!FieldIt->isUnnamedBitField())
6767 Success &= handleDefaultInitValue(
6768 FieldIt->getType(),
6769 Result.getStructField(FieldIt->getFieldIndex()));
6770 }
6771 ++FieldIt;
6772 };
6773 for (const auto *I : Definition->inits()) {
6774 LValue Subobject = This;
6775 LValue SubobjectParent = This;
6776 APValue *Value = &Result;
6777
6778 // Determine the subobject to initialize.
6779 FieldDecl *FD = nullptr;
6780 if (I->isBaseInitializer()) {
6781 QualType BaseType(I->getBaseClass(), 0);
6782 #ifndef NDEBUG
6783 // Non-virtual base classes are initialized in the order in the class
6784 // definition. We have already checked for virtual base classes.
6785 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6786 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6787 "base class initializers not in expected order");
6788 ++BaseIt;
6789 #endif
6790 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6791 BaseType->getAsCXXRecordDecl(), &Layout))
6792 return false;
6793 Value = &Result.getStructBase(BasesSeen++);
6794 } else if ((FD = I->getMember())) {
6795 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6796 return false;
6797 if (RD->isUnion()) {
6798 Result = APValue(FD);
6799 Value = &Result.getUnionValue();
6800 } else {
6801 SkipToField(FD, false);
6802 Value = &Result.getStructField(FD->getFieldIndex());
6803 }
6804 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6805 // Walk the indirect field decl's chain to find the object to initialize,
6806 // and make sure we've initialized every step along it.
6807 auto IndirectFieldChain = IFD->chain();
6808 for (auto *C : IndirectFieldChain) {
6809 FD = cast<FieldDecl>(C);
6810 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6811 // Switch the union field if it differs. This happens if we had
6812 // preceding zero-initialization, and we're now initializing a union
6813 // subobject other than the first.
6814 // FIXME: In this case, the values of the other subobjects are
6815 // specified, since zero-initialization sets all padding bits to zero.
6816 if (!Value->hasValue() ||
6817 (Value->isUnion() &&
6818 !declaresSameEntity(Value->getUnionField(), FD))) {
6819 if (CD->isUnion())
6820 *Value = APValue(FD);
6821 else
6822 // FIXME: This immediately starts the lifetime of all members of
6823 // an anonymous struct. It would be preferable to strictly start
6824 // member lifetime in initialization order.
6825 Success &=
6826 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6827 }
6828 // Store Subobject as its parent before updating it for the last element
6829 // in the chain.
6830 if (C == IndirectFieldChain.back())
6831 SubobjectParent = Subobject;
6832 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6833 return false;
6834 if (CD->isUnion())
6835 Value = &Value->getUnionValue();
6836 else {
6837 if (C == IndirectFieldChain.front() && !RD->isUnion())
6838 SkipToField(FD, true);
6839 Value = &Value->getStructField(FD->getFieldIndex());
6840 }
6841 }
6842 } else {
6843 llvm_unreachable("unknown base initializer kind");
6844 }
6845
6846 // Need to override This for implicit field initializers as in this case
6847 // This refers to innermost anonymous struct/union containing initializer,
6848 // not to currently constructed class.
6849 const Expr *Init = I->getInit();
6850 if (Init->isValueDependent()) {
6851 if (!EvaluateDependentExpr(Init, Info))
6852 return false;
6853 } else {
6854 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6855 isa<CXXDefaultInitExpr>(Init));
6856 FullExpressionRAII InitScope(Info);
6857 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6858 (FD && FD->isBitField() &&
6859 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6860 // If we're checking for a potential constant expression, evaluate all
6861 // initializers even if some of them fail.
6862 if (!Info.noteFailure())
6863 return false;
6864 Success = false;
6865 }
6866 }
6867
6868 // This is the point at which the dynamic type of the object becomes this
6869 // class type.
6870 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6871 EvalObj.finishedConstructingBases();
6872 }
6873
6874 // Default-initialize any remaining fields.
6875 if (!RD->isUnion()) {
6876 for (; FieldIt != RD->field_end(); ++FieldIt) {
6877 if (!FieldIt->isUnnamedBitField())
6878 Success &= handleDefaultInitValue(
6879 FieldIt->getType(),
6880 Result.getStructField(FieldIt->getFieldIndex()));
6881 }
6882 }
6883
6884 EvalObj.finishedConstructingFields();
6885
6886 return Success &&
6887 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6888 LifetimeExtendedScope.destroy();
6889 }
6890
HandleConstructorCall(const Expr * E,const LValue & This,ArrayRef<const Expr * > Args,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6891 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6892 ArrayRef<const Expr*> Args,
6893 const CXXConstructorDecl *Definition,
6894 EvalInfo &Info, APValue &Result) {
6895 CallScopeRAII CallScope(Info);
6896 CallRef Call = Info.CurrentCall->createCall(Definition);
6897 if (!EvaluateArgs(Args, Call, Info, Definition))
6898 return false;
6899
6900 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6901 CallScope.destroy();
6902 }
6903
HandleDestructionImpl(EvalInfo & Info,SourceRange CallRange,const LValue & This,APValue & Value,QualType T)6904 static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6905 const LValue &This, APValue &Value,
6906 QualType T) {
6907 // Objects can only be destroyed while they're within their lifetimes.
6908 // FIXME: We have no representation for whether an object of type nullptr_t
6909 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6910 // as indeterminate instead?
6911 if (Value.isAbsent() && !T->isNullPtrType()) {
6912 APValue Printable;
6913 This.moveInto(Printable);
6914 Info.FFDiag(CallRange.getBegin(),
6915 diag::note_constexpr_destroy_out_of_lifetime)
6916 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6917 return false;
6918 }
6919
6920 // Invent an expression for location purposes.
6921 // FIXME: We shouldn't need to do this.
6922 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6923
6924 // For arrays, destroy elements right-to-left.
6925 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6926 uint64_t Size = CAT->getZExtSize();
6927 QualType ElemT = CAT->getElementType();
6928
6929 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6930 return false;
6931
6932 LValue ElemLV = This;
6933 ElemLV.addArray(Info, &LocE, CAT);
6934 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6935 return false;
6936
6937 // Ensure that we have actual array elements available to destroy; the
6938 // destructors might mutate the value, so we can't run them on the array
6939 // filler.
6940 if (Size && Size > Value.getArrayInitializedElts())
6941 expandArray(Value, Value.getArraySize() - 1);
6942
6943 // The size of the array might have been reduced by
6944 // a placement new.
6945 for (Size = Value.getArraySize(); Size != 0; --Size) {
6946 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6947 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6948 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6949 return false;
6950 }
6951
6952 // End the lifetime of this array now.
6953 Value = APValue();
6954 return true;
6955 }
6956
6957 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6958 if (!RD) {
6959 if (T.isDestructedType()) {
6960 Info.FFDiag(CallRange.getBegin(),
6961 diag::note_constexpr_unsupported_destruction)
6962 << T;
6963 return false;
6964 }
6965
6966 Value = APValue();
6967 return true;
6968 }
6969
6970 if (RD->getNumVBases()) {
6971 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6972 return false;
6973 }
6974
6975 const CXXDestructorDecl *DD = RD->getDestructor();
6976 if (!DD && !RD->hasTrivialDestructor()) {
6977 Info.FFDiag(CallRange.getBegin());
6978 return false;
6979 }
6980
6981 if (!DD || DD->isTrivial() ||
6982 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6983 // A trivial destructor just ends the lifetime of the object. Check for
6984 // this case before checking for a body, because we might not bother
6985 // building a body for a trivial destructor. Note that it doesn't matter
6986 // whether the destructor is constexpr in this case; all trivial
6987 // destructors are constexpr.
6988 //
6989 // If an anonymous union would be destroyed, some enclosing destructor must
6990 // have been explicitly defined, and the anonymous union destruction should
6991 // have no effect.
6992 Value = APValue();
6993 return true;
6994 }
6995
6996 if (!Info.CheckCallLimit(CallRange.getBegin()))
6997 return false;
6998
6999 const FunctionDecl *Definition = nullptr;
7000 const Stmt *Body = DD->getBody(Definition);
7001
7002 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7003 return false;
7004
7005 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7006 CallRef());
7007
7008 // We're now in the period of destruction of this object.
7009 unsigned BasesLeft = RD->getNumBases();
7010 EvalInfo::EvaluatingDestructorRAII EvalObj(
7011 Info,
7012 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7013 if (!EvalObj.DidInsert) {
7014 // C++2a [class.dtor]p19:
7015 // the behavior is undefined if the destructor is invoked for an object
7016 // whose lifetime has ended
7017 // (Note that formally the lifetime ends when the period of destruction
7018 // begins, even though certain uses of the object remain valid until the
7019 // period of destruction ends.)
7020 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7021 return false;
7022 }
7023
7024 // FIXME: Creating an APValue just to hold a nonexistent return value is
7025 // wasteful.
7026 APValue RetVal;
7027 StmtResult Ret = {RetVal, nullptr};
7028 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7029 return false;
7030
7031 // A union destructor does not implicitly destroy its members.
7032 if (RD->isUnion())
7033 return true;
7034
7035 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7036
7037 // We don't have a good way to iterate fields in reverse, so collect all the
7038 // fields first and then walk them backwards.
7039 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7040 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7041 if (FD->isUnnamedBitField())
7042 continue;
7043
7044 LValue Subobject = This;
7045 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7046 return false;
7047
7048 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7049 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7050 FD->getType()))
7051 return false;
7052 }
7053
7054 if (BasesLeft != 0)
7055 EvalObj.startedDestroyingBases();
7056
7057 // Destroy base classes in reverse order.
7058 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7059 --BasesLeft;
7060
7061 QualType BaseType = Base.getType();
7062 LValue Subobject = This;
7063 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7064 BaseType->getAsCXXRecordDecl(), &Layout))
7065 return false;
7066
7067 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7068 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7069 BaseType))
7070 return false;
7071 }
7072 assert(BasesLeft == 0 && "NumBases was wrong?");
7073
7074 // The period of destruction ends now. The object is gone.
7075 Value = APValue();
7076 return true;
7077 }
7078
7079 namespace {
7080 struct DestroyObjectHandler {
7081 EvalInfo &Info;
7082 const Expr *E;
7083 const LValue &This;
7084 const AccessKinds AccessKind;
7085
7086 typedef bool result_type;
failed__anonfb577fba1611::DestroyObjectHandler7087 bool failed() { return false; }
found__anonfb577fba1611::DestroyObjectHandler7088 bool found(APValue &Subobj, QualType SubobjType) {
7089 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7090 SubobjType);
7091 }
found__anonfb577fba1611::DestroyObjectHandler7092 bool found(APSInt &Value, QualType SubobjType) {
7093 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7094 return false;
7095 }
found__anonfb577fba1611::DestroyObjectHandler7096 bool found(APFloat &Value, QualType SubobjType) {
7097 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7098 return false;
7099 }
7100 };
7101 }
7102
7103 /// Perform a destructor or pseudo-destructor call on the given object, which
7104 /// might in general not be a complete object.
HandleDestruction(EvalInfo & Info,const Expr * E,const LValue & This,QualType ThisType)7105 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7106 const LValue &This, QualType ThisType) {
7107 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7108 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7109 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7110 }
7111
7112 /// Destroy and end the lifetime of the given complete object.
HandleDestruction(EvalInfo & Info,SourceLocation Loc,APValue::LValueBase LVBase,APValue & Value,QualType T)7113 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7114 APValue::LValueBase LVBase, APValue &Value,
7115 QualType T) {
7116 // If we've had an unmodeled side-effect, we can't rely on mutable state
7117 // (such as the object we're about to destroy) being correct.
7118 if (Info.EvalStatus.HasSideEffects)
7119 return false;
7120
7121 LValue LV;
7122 LV.set({LVBase});
7123 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7124 }
7125
7126 /// Perform a call to 'operator new' or to `__builtin_operator_new'.
HandleOperatorNewCall(EvalInfo & Info,const CallExpr * E,LValue & Result)7127 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7128 LValue &Result) {
7129 if (Info.checkingPotentialConstantExpression() ||
7130 Info.SpeculativeEvaluationDepth)
7131 return false;
7132
7133 // This is permitted only within a call to std::allocator<T>::allocate.
7134 auto Caller = Info.getStdAllocatorCaller("allocate");
7135 if (!Caller) {
7136 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7137 ? diag::note_constexpr_new_untyped
7138 : diag::note_constexpr_new);
7139 return false;
7140 }
7141
7142 QualType ElemType = Caller.ElemType;
7143 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7144 Info.FFDiag(E->getExprLoc(),
7145 diag::note_constexpr_new_not_complete_object_type)
7146 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7147 return false;
7148 }
7149
7150 APSInt ByteSize;
7151 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7152 return false;
7153 bool IsNothrow = false;
7154 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7155 EvaluateIgnoredValue(Info, E->getArg(I));
7156 IsNothrow |= E->getType()->isNothrowT();
7157 }
7158
7159 CharUnits ElemSize;
7160 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7161 return false;
7162 APInt Size, Remainder;
7163 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7164 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7165 if (Remainder != 0) {
7166 // This likely indicates a bug in the implementation of 'std::allocator'.
7167 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7168 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7169 return false;
7170 }
7171
7172 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7173 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7174 if (IsNothrow) {
7175 Result.setNull(Info.Ctx, E->getType());
7176 return true;
7177 }
7178 return false;
7179 }
7180
7181 QualType AllocType = Info.Ctx.getConstantArrayType(
7182 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7183 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7184 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7185 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7186 return true;
7187 }
7188
hasVirtualDestructor(QualType T)7189 static bool hasVirtualDestructor(QualType T) {
7190 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7191 if (CXXDestructorDecl *DD = RD->getDestructor())
7192 return DD->isVirtual();
7193 return false;
7194 }
7195
getVirtualOperatorDelete(QualType T)7196 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
7197 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7198 if (CXXDestructorDecl *DD = RD->getDestructor())
7199 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7200 return nullptr;
7201 }
7202
7203 /// Check that the given object is a suitable pointer to a heap allocation that
7204 /// still exists and is of the right kind for the purpose of a deletion.
7205 ///
7206 /// On success, returns the heap allocation to deallocate. On failure, produces
7207 /// a diagnostic and returns std::nullopt.
CheckDeleteKind(EvalInfo & Info,const Expr * E,const LValue & Pointer,DynAlloc::Kind DeallocKind)7208 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7209 const LValue &Pointer,
7210 DynAlloc::Kind DeallocKind) {
7211 auto PointerAsString = [&] {
7212 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7213 };
7214
7215 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7216 if (!DA) {
7217 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7218 << PointerAsString();
7219 if (Pointer.Base)
7220 NoteLValueLocation(Info, Pointer.Base);
7221 return std::nullopt;
7222 }
7223
7224 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7225 if (!Alloc) {
7226 Info.FFDiag(E, diag::note_constexpr_double_delete);
7227 return std::nullopt;
7228 }
7229
7230 if (DeallocKind != (*Alloc)->getKind()) {
7231 QualType AllocType = Pointer.Base.getDynamicAllocType();
7232 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7233 << DeallocKind << (*Alloc)->getKind() << AllocType;
7234 NoteLValueLocation(Info, Pointer.Base);
7235 return std::nullopt;
7236 }
7237
7238 bool Subobject = false;
7239 if (DeallocKind == DynAlloc::New) {
7240 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7241 Pointer.Designator.isOnePastTheEnd();
7242 } else {
7243 Subobject = Pointer.Designator.Entries.size() != 1 ||
7244 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7245 }
7246 if (Subobject) {
7247 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7248 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7249 return std::nullopt;
7250 }
7251
7252 return Alloc;
7253 }
7254
7255 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
HandleOperatorDeleteCall(EvalInfo & Info,const CallExpr * E)7256 static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7257 if (Info.checkingPotentialConstantExpression() ||
7258 Info.SpeculativeEvaluationDepth)
7259 return false;
7260
7261 // This is permitted only within a call to std::allocator<T>::deallocate.
7262 if (!Info.getStdAllocatorCaller("deallocate")) {
7263 Info.FFDiag(E->getExprLoc());
7264 return true;
7265 }
7266
7267 LValue Pointer;
7268 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7269 return false;
7270 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7271 EvaluateIgnoredValue(Info, E->getArg(I));
7272
7273 if (Pointer.Designator.Invalid)
7274 return false;
7275
7276 // Deleting a null pointer would have no effect, but it's not permitted by
7277 // std::allocator<T>::deallocate's contract.
7278 if (Pointer.isNullPointer()) {
7279 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7280 return true;
7281 }
7282
7283 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7284 return false;
7285
7286 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7287 return true;
7288 }
7289
7290 //===----------------------------------------------------------------------===//
7291 // Generic Evaluation
7292 //===----------------------------------------------------------------------===//
7293 namespace {
7294
7295 class BitCastBuffer {
7296 // FIXME: We're going to need bit-level granularity when we support
7297 // bit-fields.
7298 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7299 // we don't support a host or target where that is the case. Still, we should
7300 // use a more generic type in case we ever do.
7301 SmallVector<std::optional<unsigned char>, 32> Bytes;
7302
7303 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7304 "Need at least 8 bit unsigned char");
7305
7306 bool TargetIsLittleEndian;
7307
7308 public:
BitCastBuffer(CharUnits Width,bool TargetIsLittleEndian)7309 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7310 : Bytes(Width.getQuantity()),
7311 TargetIsLittleEndian(TargetIsLittleEndian) {}
7312
readObject(CharUnits Offset,CharUnits Width,SmallVectorImpl<unsigned char> & Output) const7313 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7314 SmallVectorImpl<unsigned char> &Output) const {
7315 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7316 // If a byte of an integer is uninitialized, then the whole integer is
7317 // uninitialized.
7318 if (!Bytes[I.getQuantity()])
7319 return false;
7320 Output.push_back(*Bytes[I.getQuantity()]);
7321 }
7322 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7323 std::reverse(Output.begin(), Output.end());
7324 return true;
7325 }
7326
writeObject(CharUnits Offset,SmallVectorImpl<unsigned char> & Input)7327 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7328 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7329 std::reverse(Input.begin(), Input.end());
7330
7331 size_t Index = 0;
7332 for (unsigned char Byte : Input) {
7333 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7334 Bytes[Offset.getQuantity() + Index] = Byte;
7335 ++Index;
7336 }
7337 }
7338
size()7339 size_t size() { return Bytes.size(); }
7340 };
7341
7342 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7343 /// target would represent the value at runtime.
7344 class APValueToBufferConverter {
7345 EvalInfo &Info;
7346 BitCastBuffer Buffer;
7347 const CastExpr *BCE;
7348
APValueToBufferConverter(EvalInfo & Info,CharUnits ObjectWidth,const CastExpr * BCE)7349 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7350 const CastExpr *BCE)
7351 : Info(Info),
7352 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7353 BCE(BCE) {}
7354
visit(const APValue & Val,QualType Ty)7355 bool visit(const APValue &Val, QualType Ty) {
7356 return visit(Val, Ty, CharUnits::fromQuantity(0));
7357 }
7358
7359 // Write out Val with type Ty into Buffer starting at Offset.
visit(const APValue & Val,QualType Ty,CharUnits Offset)7360 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7361 assert((size_t)Offset.getQuantity() <= Buffer.size());
7362
7363 // As a special case, nullptr_t has an indeterminate value.
7364 if (Ty->isNullPtrType())
7365 return true;
7366
7367 // Dig through Src to find the byte at SrcOffset.
7368 switch (Val.getKind()) {
7369 case APValue::Indeterminate:
7370 case APValue::None:
7371 return true;
7372
7373 case APValue::Int:
7374 return visitInt(Val.getInt(), Ty, Offset);
7375 case APValue::Float:
7376 return visitFloat(Val.getFloat(), Ty, Offset);
7377 case APValue::Array:
7378 return visitArray(Val, Ty, Offset);
7379 case APValue::Struct:
7380 return visitRecord(Val, Ty, Offset);
7381 case APValue::Vector:
7382 return visitVector(Val, Ty, Offset);
7383
7384 case APValue::ComplexInt:
7385 case APValue::ComplexFloat:
7386 return visitComplex(Val, Ty, Offset);
7387 case APValue::FixedPoint:
7388 // FIXME: We should support these.
7389
7390 case APValue::Union:
7391 case APValue::MemberPointer:
7392 case APValue::AddrLabelDiff: {
7393 Info.FFDiag(BCE->getBeginLoc(),
7394 diag::note_constexpr_bit_cast_unsupported_type)
7395 << Ty;
7396 return false;
7397 }
7398
7399 case APValue::LValue:
7400 llvm_unreachable("LValue subobject in bit_cast?");
7401 }
7402 llvm_unreachable("Unhandled APValue::ValueKind");
7403 }
7404
visitRecord(const APValue & Val,QualType Ty,CharUnits Offset)7405 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7406 const RecordDecl *RD = Ty->getAsRecordDecl();
7407 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7408
7409 // Visit the base classes.
7410 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7411 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7412 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7413 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7414 const APValue &Base = Val.getStructBase(I);
7415
7416 // Can happen in error cases.
7417 if (!Base.isStruct())
7418 return false;
7419
7420 if (!visitRecord(Base, BS.getType(),
7421 Layout.getBaseClassOffset(BaseDecl) + Offset))
7422 return false;
7423 }
7424 }
7425
7426 // Visit the fields.
7427 unsigned FieldIdx = 0;
7428 for (FieldDecl *FD : RD->fields()) {
7429 if (FD->isBitField()) {
7430 Info.FFDiag(BCE->getBeginLoc(),
7431 diag::note_constexpr_bit_cast_unsupported_bitfield);
7432 return false;
7433 }
7434
7435 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7436
7437 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7438 "only bit-fields can have sub-char alignment");
7439 CharUnits FieldOffset =
7440 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7441 QualType FieldTy = FD->getType();
7442 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7443 return false;
7444 ++FieldIdx;
7445 }
7446
7447 return true;
7448 }
7449
visitArray(const APValue & Val,QualType Ty,CharUnits Offset)7450 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7451 const auto *CAT =
7452 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7453 if (!CAT)
7454 return false;
7455
7456 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7457 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7458 unsigned ArraySize = Val.getArraySize();
7459 // First, initialize the initialized elements.
7460 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7461 const APValue &SubObj = Val.getArrayInitializedElt(I);
7462 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7463 return false;
7464 }
7465
7466 // Next, initialize the rest of the array using the filler.
7467 if (Val.hasArrayFiller()) {
7468 const APValue &Filler = Val.getArrayFiller();
7469 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7470 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7471 return false;
7472 }
7473 }
7474
7475 return true;
7476 }
7477
visitComplex(const APValue & Val,QualType Ty,CharUnits Offset)7478 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7479 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7480 QualType EltTy = ComplexTy->getElementType();
7481 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7482 bool IsInt = Val.isComplexInt();
7483
7484 if (IsInt) {
7485 if (!visitInt(Val.getComplexIntReal(), EltTy,
7486 Offset + (0 * EltSizeChars)))
7487 return false;
7488 if (!visitInt(Val.getComplexIntImag(), EltTy,
7489 Offset + (1 * EltSizeChars)))
7490 return false;
7491 } else {
7492 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7493 Offset + (0 * EltSizeChars)))
7494 return false;
7495 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7496 Offset + (1 * EltSizeChars)))
7497 return false;
7498 }
7499
7500 return true;
7501 }
7502
visitVector(const APValue & Val,QualType Ty,CharUnits Offset)7503 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7504 const VectorType *VTy = Ty->castAs<VectorType>();
7505 QualType EltTy = VTy->getElementType();
7506 unsigned NElts = VTy->getNumElements();
7507
7508 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7509 // Special handling for OpenCL bool vectors:
7510 // Since these vectors are stored as packed bits, but we can't write
7511 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7512 // together into an appropriately sized APInt and write them all out at
7513 // once. Because we don't accept vectors where NElts * EltSize isn't a
7514 // multiple of the char size, there will be no padding space, so we don't
7515 // have to worry about writing data which should have been left
7516 // uninitialized.
7517 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7518
7519 llvm::APInt Res = llvm::APInt::getZero(NElts);
7520 for (unsigned I = 0; I < NElts; ++I) {
7521 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7522 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7523 "bool vector element must be 1-bit unsigned integer!");
7524
7525 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7526 }
7527
7528 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7529 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7530 Buffer.writeObject(Offset, Bytes);
7531 } else {
7532 // Iterate over each of the elements and write them out to the buffer at
7533 // the appropriate offset.
7534 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7535 for (unsigned I = 0; I < NElts; ++I) {
7536 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7537 return false;
7538 }
7539 }
7540
7541 return true;
7542 }
7543
visitInt(const APSInt & Val,QualType Ty,CharUnits Offset)7544 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7545 APSInt AdjustedVal = Val;
7546 unsigned Width = AdjustedVal.getBitWidth();
7547 if (Ty->isBooleanType()) {
7548 Width = Info.Ctx.getTypeSize(Ty);
7549 AdjustedVal = AdjustedVal.extend(Width);
7550 }
7551
7552 SmallVector<uint8_t, 8> Bytes(Width / 8);
7553 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7554 Buffer.writeObject(Offset, Bytes);
7555 return true;
7556 }
7557
visitFloat(const APFloat & Val,QualType Ty,CharUnits Offset)7558 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7559 APSInt AsInt(Val.bitcastToAPInt());
7560 return visitInt(AsInt, Ty, Offset);
7561 }
7562
7563 public:
7564 static std::optional<BitCastBuffer>
convert(EvalInfo & Info,const APValue & Src,const CastExpr * BCE)7565 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7566 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7567 APValueToBufferConverter Converter(Info, DstSize, BCE);
7568 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7569 return std::nullopt;
7570 return Converter.Buffer;
7571 }
7572 };
7573
7574 /// Write an BitCastBuffer into an APValue.
7575 class BufferToAPValueConverter {
7576 EvalInfo &Info;
7577 const BitCastBuffer &Buffer;
7578 const CastExpr *BCE;
7579
BufferToAPValueConverter(EvalInfo & Info,const BitCastBuffer & Buffer,const CastExpr * BCE)7580 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7581 const CastExpr *BCE)
7582 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7583
7584 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7585 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7586 // Ideally this will be unreachable.
unsupportedType(QualType Ty)7587 std::nullopt_t unsupportedType(QualType Ty) {
7588 Info.FFDiag(BCE->getBeginLoc(),
7589 diag::note_constexpr_bit_cast_unsupported_type)
7590 << Ty;
7591 return std::nullopt;
7592 }
7593
unrepresentableValue(QualType Ty,const APSInt & Val)7594 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7595 Info.FFDiag(BCE->getBeginLoc(),
7596 diag::note_constexpr_bit_cast_unrepresentable_value)
7597 << Ty << toString(Val, /*Radix=*/10);
7598 return std::nullopt;
7599 }
7600
visit(const BuiltinType * T,CharUnits Offset,const EnumType * EnumSugar=nullptr)7601 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7602 const EnumType *EnumSugar = nullptr) {
7603 if (T->isNullPtrType()) {
7604 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7605 return APValue((Expr *)nullptr,
7606 /*Offset=*/CharUnits::fromQuantity(NullValue),
7607 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7608 }
7609
7610 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7611
7612 // Work around floating point types that contain unused padding bytes. This
7613 // is really just `long double` on x86, which is the only fundamental type
7614 // with padding bytes.
7615 if (T->isRealFloatingType()) {
7616 const llvm::fltSemantics &Semantics =
7617 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7618 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7619 assert(NumBits % 8 == 0);
7620 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7621 if (NumBytes != SizeOf)
7622 SizeOf = NumBytes;
7623 }
7624
7625 SmallVector<uint8_t, 8> Bytes;
7626 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7627 // If this is std::byte or unsigned char, then its okay to store an
7628 // indeterminate value.
7629 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7630 bool IsUChar =
7631 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7632 T->isSpecificBuiltinType(BuiltinType::Char_U));
7633 if (!IsStdByte && !IsUChar) {
7634 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7635 Info.FFDiag(BCE->getExprLoc(),
7636 diag::note_constexpr_bit_cast_indet_dest)
7637 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7638 return std::nullopt;
7639 }
7640
7641 return APValue::IndeterminateValue();
7642 }
7643
7644 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7645 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7646
7647 if (T->isIntegralOrEnumerationType()) {
7648 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7649
7650 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7651 if (IntWidth != Val.getBitWidth()) {
7652 APSInt Truncated = Val.trunc(IntWidth);
7653 if (Truncated.extend(Val.getBitWidth()) != Val)
7654 return unrepresentableValue(QualType(T, 0), Val);
7655 Val = Truncated;
7656 }
7657
7658 return APValue(Val);
7659 }
7660
7661 if (T->isRealFloatingType()) {
7662 const llvm::fltSemantics &Semantics =
7663 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7664 return APValue(APFloat(Semantics, Val));
7665 }
7666
7667 return unsupportedType(QualType(T, 0));
7668 }
7669
visit(const RecordType * RTy,CharUnits Offset)7670 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7671 const RecordDecl *RD = RTy->getAsRecordDecl();
7672 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7673
7674 unsigned NumBases = 0;
7675 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7676 NumBases = CXXRD->getNumBases();
7677
7678 APValue ResultVal(APValue::UninitStruct(), NumBases,
7679 std::distance(RD->field_begin(), RD->field_end()));
7680
7681 // Visit the base classes.
7682 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7683 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7684 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7685 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7686
7687 std::optional<APValue> SubObj = visitType(
7688 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7689 if (!SubObj)
7690 return std::nullopt;
7691 ResultVal.getStructBase(I) = *SubObj;
7692 }
7693 }
7694
7695 // Visit the fields.
7696 unsigned FieldIdx = 0;
7697 for (FieldDecl *FD : RD->fields()) {
7698 // FIXME: We don't currently support bit-fields. A lot of the logic for
7699 // this is in CodeGen, so we need to factor it around.
7700 if (FD->isBitField()) {
7701 Info.FFDiag(BCE->getBeginLoc(),
7702 diag::note_constexpr_bit_cast_unsupported_bitfield);
7703 return std::nullopt;
7704 }
7705
7706 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7707 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7708
7709 CharUnits FieldOffset =
7710 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7711 Offset;
7712 QualType FieldTy = FD->getType();
7713 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7714 if (!SubObj)
7715 return std::nullopt;
7716 ResultVal.getStructField(FieldIdx) = *SubObj;
7717 ++FieldIdx;
7718 }
7719
7720 return ResultVal;
7721 }
7722
visit(const EnumType * Ty,CharUnits Offset)7723 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7724 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7725 assert(!RepresentationType.isNull() &&
7726 "enum forward decl should be caught by Sema");
7727 const auto *AsBuiltin =
7728 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7729 // Recurse into the underlying type. Treat std::byte transparently as
7730 // unsigned char.
7731 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7732 }
7733
visit(const ConstantArrayType * Ty,CharUnits Offset)7734 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7735 size_t Size = Ty->getLimitedSize();
7736 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7737
7738 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7739 for (size_t I = 0; I != Size; ++I) {
7740 std::optional<APValue> ElementValue =
7741 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7742 if (!ElementValue)
7743 return std::nullopt;
7744 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7745 }
7746
7747 return ArrayValue;
7748 }
7749
visit(const ComplexType * Ty,CharUnits Offset)7750 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7751 QualType ElementType = Ty->getElementType();
7752 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7753 bool IsInt = ElementType->isIntegerType();
7754
7755 std::optional<APValue> Values[2];
7756 for (unsigned I = 0; I != 2; ++I) {
7757 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7758 if (!Values[I])
7759 return std::nullopt;
7760 }
7761
7762 if (IsInt)
7763 return APValue(Values[0]->getInt(), Values[1]->getInt());
7764 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7765 }
7766
visit(const VectorType * VTy,CharUnits Offset)7767 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7768 QualType EltTy = VTy->getElementType();
7769 unsigned NElts = VTy->getNumElements();
7770 unsigned EltSize =
7771 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
7772
7773 SmallVector<APValue, 4> Elts;
7774 Elts.reserve(NElts);
7775 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7776 // Special handling for OpenCL bool vectors:
7777 // Since these vectors are stored as packed bits, but we can't read
7778 // individual bits from the BitCastBuffer, we'll buffer all of the
7779 // elements together into an appropriately sized APInt and write them all
7780 // out at once. Because we don't accept vectors where NElts * EltSize
7781 // isn't a multiple of the char size, there will be no padding space, so
7782 // we don't have to worry about reading any padding data which didn't
7783 // actually need to be accessed.
7784 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7785
7786 SmallVector<uint8_t, 8> Bytes;
7787 Bytes.reserve(NElts / 8);
7788 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7789 return std::nullopt;
7790
7791 APSInt SValInt(NElts, true);
7792 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7793
7794 for (unsigned I = 0; I < NElts; ++I) {
7795 llvm::APInt Elt =
7796 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7797 Elts.emplace_back(
7798 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7799 }
7800 } else {
7801 // Iterate over each of the elements and read them from the buffer at
7802 // the appropriate offset.
7803 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7804 for (unsigned I = 0; I < NElts; ++I) {
7805 std::optional<APValue> EltValue =
7806 visitType(EltTy, Offset + I * EltSizeChars);
7807 if (!EltValue)
7808 return std::nullopt;
7809 Elts.push_back(std::move(*EltValue));
7810 }
7811 }
7812
7813 return APValue(Elts.data(), Elts.size());
7814 }
7815
visit(const Type * Ty,CharUnits Offset)7816 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7817 return unsupportedType(QualType(Ty, 0));
7818 }
7819
visitType(QualType Ty,CharUnits Offset)7820 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7821 QualType Can = Ty.getCanonicalType();
7822
7823 switch (Can->getTypeClass()) {
7824 #define TYPE(Class, Base) \
7825 case Type::Class: \
7826 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7827 #define ABSTRACT_TYPE(Class, Base)
7828 #define NON_CANONICAL_TYPE(Class, Base) \
7829 case Type::Class: \
7830 llvm_unreachable("non-canonical type should be impossible!");
7831 #define DEPENDENT_TYPE(Class, Base) \
7832 case Type::Class: \
7833 llvm_unreachable( \
7834 "dependent types aren't supported in the constant evaluator!");
7835 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7836 case Type::Class: \
7837 llvm_unreachable("either dependent or not canonical!");
7838 #include "clang/AST/TypeNodes.inc"
7839 }
7840 llvm_unreachable("Unhandled Type::TypeClass");
7841 }
7842
7843 public:
7844 // Pull out a full value of type DstType.
convert(EvalInfo & Info,BitCastBuffer & Buffer,const CastExpr * BCE)7845 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7846 const CastExpr *BCE) {
7847 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7848 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7849 }
7850 };
7851
checkBitCastConstexprEligibilityType(SourceLocation Loc,QualType Ty,EvalInfo * Info,const ASTContext & Ctx,bool CheckingDest)7852 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7853 QualType Ty, EvalInfo *Info,
7854 const ASTContext &Ctx,
7855 bool CheckingDest) {
7856 Ty = Ty.getCanonicalType();
7857
7858 auto diag = [&](int Reason) {
7859 if (Info)
7860 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7861 << CheckingDest << (Reason == 4) << Reason;
7862 return false;
7863 };
7864 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7865 if (Info)
7866 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7867 << NoteTy << Construct << Ty;
7868 return false;
7869 };
7870
7871 if (Ty->isUnionType())
7872 return diag(0);
7873 if (Ty->isPointerType())
7874 return diag(1);
7875 if (Ty->isMemberPointerType())
7876 return diag(2);
7877 if (Ty.isVolatileQualified())
7878 return diag(3);
7879
7880 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7881 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7882 for (CXXBaseSpecifier &BS : CXXRD->bases())
7883 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7884 CheckingDest))
7885 return note(1, BS.getType(), BS.getBeginLoc());
7886 }
7887 for (FieldDecl *FD : Record->fields()) {
7888 if (FD->getType()->isReferenceType())
7889 return diag(4);
7890 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7891 CheckingDest))
7892 return note(0, FD->getType(), FD->getBeginLoc());
7893 }
7894 }
7895
7896 if (Ty->isArrayType() &&
7897 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7898 Info, Ctx, CheckingDest))
7899 return false;
7900
7901 if (const auto *VTy = Ty->getAs<VectorType>()) {
7902 QualType EltTy = VTy->getElementType();
7903 unsigned NElts = VTy->getNumElements();
7904 unsigned EltSize =
7905 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
7906
7907 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
7908 // The vector's size in bits is not a multiple of the target's byte size,
7909 // so its layout is unspecified. For now, we'll simply treat these cases
7910 // as unsupported (this should only be possible with OpenCL bool vectors
7911 // whose element count isn't a multiple of the byte size).
7912 if (Info)
7913 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
7914 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
7915 return false;
7916 }
7917
7918 if (EltTy->isRealFloatingType() &&
7919 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
7920 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7921 // by both clang and LLVM, so for now we won't allow bit_casts involving
7922 // it in a constexpr context.
7923 if (Info)
7924 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
7925 << EltTy;
7926 return false;
7927 }
7928 }
7929
7930 return true;
7931 }
7932
checkBitCastConstexprEligibility(EvalInfo * Info,const ASTContext & Ctx,const CastExpr * BCE)7933 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7934 const ASTContext &Ctx,
7935 const CastExpr *BCE) {
7936 bool DestOK = checkBitCastConstexprEligibilityType(
7937 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7938 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7939 BCE->getBeginLoc(),
7940 BCE->getSubExpr()->getType(), Info, Ctx, false);
7941 return SourceOK;
7942 }
7943
handleRValueToRValueBitCast(EvalInfo & Info,APValue & DestValue,const APValue & SourceRValue,const CastExpr * BCE)7944 static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7945 const APValue &SourceRValue,
7946 const CastExpr *BCE) {
7947 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7948 "no host or target supports non 8-bit chars");
7949
7950 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7951 return false;
7952
7953 // Read out SourceValue into a char buffer.
7954 std::optional<BitCastBuffer> Buffer =
7955 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7956 if (!Buffer)
7957 return false;
7958
7959 // Write out the buffer into a new APValue.
7960 std::optional<APValue> MaybeDestValue =
7961 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7962 if (!MaybeDestValue)
7963 return false;
7964
7965 DestValue = std::move(*MaybeDestValue);
7966 return true;
7967 }
7968
handleLValueToRValueBitCast(EvalInfo & Info,APValue & DestValue,APValue & SourceValue,const CastExpr * BCE)7969 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7970 APValue &SourceValue,
7971 const CastExpr *BCE) {
7972 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7973 "no host or target supports non 8-bit chars");
7974 assert(SourceValue.isLValue() &&
7975 "LValueToRValueBitcast requires an lvalue operand!");
7976
7977 LValue SourceLValue;
7978 APValue SourceRValue;
7979 SourceLValue.setFrom(Info.Ctx, SourceValue);
7980 if (!handleLValueToRValueConversion(
7981 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7982 SourceRValue, /*WantObjectRepresentation=*/true))
7983 return false;
7984
7985 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7986 }
7987
7988 template <class Derived>
7989 class ExprEvaluatorBase
7990 : public ConstStmtVisitor<Derived, bool> {
7991 private:
getDerived()7992 Derived &getDerived() { return static_cast<Derived&>(*this); }
DerivedSuccess(const APValue & V,const Expr * E)7993 bool DerivedSuccess(const APValue &V, const Expr *E) {
7994 return getDerived().Success(V, E);
7995 }
DerivedZeroInitialization(const Expr * E)7996 bool DerivedZeroInitialization(const Expr *E) {
7997 return getDerived().ZeroInitialization(E);
7998 }
7999
8000 // Check whether a conditional operator with a non-constant condition is a
8001 // potential constant expression. If neither arm is a potential constant
8002 // expression, then the conditional operator is not either.
8003 template<typename ConditionalOperator>
CheckPotentialConstantConditional(const ConditionalOperator * E)8004 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8005 assert(Info.checkingPotentialConstantExpression());
8006
8007 // Speculatively evaluate both arms.
8008 SmallVector<PartialDiagnosticAt, 8> Diag;
8009 {
8010 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8011 StmtVisitorTy::Visit(E->getFalseExpr());
8012 if (Diag.empty())
8013 return;
8014 }
8015
8016 {
8017 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8018 Diag.clear();
8019 StmtVisitorTy::Visit(E->getTrueExpr());
8020 if (Diag.empty())
8021 return;
8022 }
8023
8024 Error(E, diag::note_constexpr_conditional_never_const);
8025 }
8026
8027
8028 template<typename ConditionalOperator>
HandleConditionalOperator(const ConditionalOperator * E)8029 bool HandleConditionalOperator(const ConditionalOperator *E) {
8030 bool BoolResult;
8031 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8032 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8033 CheckPotentialConstantConditional(E);
8034 return false;
8035 }
8036 if (Info.noteFailure()) {
8037 StmtVisitorTy::Visit(E->getTrueExpr());
8038 StmtVisitorTy::Visit(E->getFalseExpr());
8039 }
8040 return false;
8041 }
8042
8043 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8044 return StmtVisitorTy::Visit(EvalExpr);
8045 }
8046
8047 protected:
8048 EvalInfo &Info;
8049 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8050 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8051
CCEDiag(const Expr * E,diag::kind D)8052 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8053 return Info.CCEDiag(E, D);
8054 }
8055
ZeroInitialization(const Expr * E)8056 bool ZeroInitialization(const Expr *E) { return Error(E); }
8057
IsConstantEvaluatedBuiltinCall(const CallExpr * E)8058 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8059 unsigned BuiltinOp = E->getBuiltinCallee();
8060 return BuiltinOp != 0 &&
8061 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8062 }
8063
8064 public:
ExprEvaluatorBase(EvalInfo & Info)8065 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8066
getEvalInfo()8067 EvalInfo &getEvalInfo() { return Info; }
8068
8069 /// Report an evaluation error. This should only be called when an error is
8070 /// first discovered. When propagating an error, just return false.
Error(const Expr * E,diag::kind D)8071 bool Error(const Expr *E, diag::kind D) {
8072 Info.FFDiag(E, D) << E->getSourceRange();
8073 return false;
8074 }
Error(const Expr * E)8075 bool Error(const Expr *E) {
8076 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8077 }
8078
VisitStmt(const Stmt *)8079 bool VisitStmt(const Stmt *) {
8080 llvm_unreachable("Expression evaluator should not be called on stmts");
8081 }
VisitExpr(const Expr * E)8082 bool VisitExpr(const Expr *E) {
8083 return Error(E);
8084 }
8085
VisitEmbedExpr(const EmbedExpr * E)8086 bool VisitEmbedExpr(const EmbedExpr *E) {
8087 const auto It = E->begin();
8088 return StmtVisitorTy::Visit(*It);
8089 }
8090
VisitPredefinedExpr(const PredefinedExpr * E)8091 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8092 return StmtVisitorTy::Visit(E->getFunctionName());
8093 }
VisitConstantExpr(const ConstantExpr * E)8094 bool VisitConstantExpr(const ConstantExpr *E) {
8095 if (E->hasAPValueResult())
8096 return DerivedSuccess(E->getAPValueResult(), E);
8097
8098 return StmtVisitorTy::Visit(E->getSubExpr());
8099 }
8100
VisitParenExpr(const ParenExpr * E)8101 bool VisitParenExpr(const ParenExpr *E)
8102 { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryExtension(const UnaryOperator * E)8103 bool VisitUnaryExtension(const UnaryOperator *E)
8104 { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryPlus(const UnaryOperator * E)8105 bool VisitUnaryPlus(const UnaryOperator *E)
8106 { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitChooseExpr(const ChooseExpr * E)8107 bool VisitChooseExpr(const ChooseExpr *E)
8108 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
VisitGenericSelectionExpr(const GenericSelectionExpr * E)8109 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8110 { return StmtVisitorTy::Visit(E->getResultExpr()); }
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * E)8111 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8112 { return StmtVisitorTy::Visit(E->getReplacement()); }
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)8113 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8114 TempVersionRAII RAII(*Info.CurrentCall);
8115 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8116 return StmtVisitorTy::Visit(E->getExpr());
8117 }
VisitCXXDefaultInitExpr(const CXXDefaultInitExpr * E)8118 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8119 TempVersionRAII RAII(*Info.CurrentCall);
8120 // The initializer may not have been parsed yet, or might be erroneous.
8121 if (!E->getExpr())
8122 return Error(E);
8123 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8124 return StmtVisitorTy::Visit(E->getExpr());
8125 }
8126
VisitExprWithCleanups(const ExprWithCleanups * E)8127 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8128 FullExpressionRAII Scope(Info);
8129 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8130 }
8131
8132 // Temporaries are registered when created, so we don't care about
8133 // CXXBindTemporaryExpr.
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * E)8134 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8135 return StmtVisitorTy::Visit(E->getSubExpr());
8136 }
8137
VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr * E)8138 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8139 CCEDiag(E, diag::note_constexpr_invalid_cast)
8140 << diag::ConstexprInvalidCastKind::Reinterpret;
8141 return static_cast<Derived*>(this)->VisitCastExpr(E);
8142 }
VisitCXXDynamicCastExpr(const CXXDynamicCastExpr * E)8143 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8144 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8145 CCEDiag(E, diag::note_constexpr_invalid_cast)
8146 << diag::ConstexprInvalidCastKind::Dynamic;
8147 return static_cast<Derived*>(this)->VisitCastExpr(E);
8148 }
VisitBuiltinBitCastExpr(const BuiltinBitCastExpr * E)8149 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8150 return static_cast<Derived*>(this)->VisitCastExpr(E);
8151 }
8152
VisitBinaryOperator(const BinaryOperator * E)8153 bool VisitBinaryOperator(const BinaryOperator *E) {
8154 switch (E->getOpcode()) {
8155 default:
8156 return Error(E);
8157
8158 case BO_Comma:
8159 VisitIgnoredValue(E->getLHS());
8160 return StmtVisitorTy::Visit(E->getRHS());
8161
8162 case BO_PtrMemD:
8163 case BO_PtrMemI: {
8164 LValue Obj;
8165 if (!HandleMemberPointerAccess(Info, E, Obj))
8166 return false;
8167 APValue Result;
8168 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8169 return false;
8170 return DerivedSuccess(Result, E);
8171 }
8172 }
8173 }
8174
VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator * E)8175 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8176 return StmtVisitorTy::Visit(E->getSemanticForm());
8177 }
8178
VisitBinaryConditionalOperator(const BinaryConditionalOperator * E)8179 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8180 // Evaluate and cache the common expression. We treat it as a temporary,
8181 // even though it's not quite the same thing.
8182 LValue CommonLV;
8183 if (!Evaluate(Info.CurrentCall->createTemporary(
8184 E->getOpaqueValue(),
8185 getStorageType(Info.Ctx, E->getOpaqueValue()),
8186 ScopeKind::FullExpression, CommonLV),
8187 Info, E->getCommon()))
8188 return false;
8189
8190 return HandleConditionalOperator(E);
8191 }
8192
VisitConditionalOperator(const ConditionalOperator * E)8193 bool VisitConditionalOperator(const ConditionalOperator *E) {
8194 bool IsBcpCall = false;
8195 // If the condition (ignoring parens) is a __builtin_constant_p call,
8196 // the result is a constant expression if it can be folded without
8197 // side-effects. This is an important GNU extension. See GCC PR38377
8198 // for discussion.
8199 if (const CallExpr *CallCE =
8200 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8201 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8202 IsBcpCall = true;
8203
8204 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8205 // constant expression; we can't check whether it's potentially foldable.
8206 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8207 // it would return 'false' in this mode.
8208 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8209 return false;
8210
8211 FoldConstant Fold(Info, IsBcpCall);
8212 if (!HandleConditionalOperator(E)) {
8213 Fold.keepDiagnostics();
8214 return false;
8215 }
8216
8217 return true;
8218 }
8219
VisitOpaqueValueExpr(const OpaqueValueExpr * E)8220 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8221 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8222 Value && !Value->isAbsent())
8223 return DerivedSuccess(*Value, E);
8224
8225 const Expr *Source = E->getSourceExpr();
8226 if (!Source)
8227 return Error(E);
8228 if (Source == E) {
8229 assert(0 && "OpaqueValueExpr recursively refers to itself");
8230 return Error(E);
8231 }
8232 return StmtVisitorTy::Visit(Source);
8233 }
8234
VisitPseudoObjectExpr(const PseudoObjectExpr * E)8235 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8236 for (const Expr *SemE : E->semantics()) {
8237 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8238 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8239 // result expression: there could be two different LValues that would
8240 // refer to the same object in that case, and we can't model that.
8241 if (SemE == E->getResultExpr())
8242 return Error(E);
8243
8244 // Unique OVEs get evaluated if and when we encounter them when
8245 // emitting the rest of the semantic form, rather than eagerly.
8246 if (OVE->isUnique())
8247 continue;
8248
8249 LValue LV;
8250 if (!Evaluate(Info.CurrentCall->createTemporary(
8251 OVE, getStorageType(Info.Ctx, OVE),
8252 ScopeKind::FullExpression, LV),
8253 Info, OVE->getSourceExpr()))
8254 return false;
8255 } else if (SemE == E->getResultExpr()) {
8256 if (!StmtVisitorTy::Visit(SemE))
8257 return false;
8258 } else {
8259 if (!EvaluateIgnoredValue(Info, SemE))
8260 return false;
8261 }
8262 }
8263 return true;
8264 }
8265
VisitCallExpr(const CallExpr * E)8266 bool VisitCallExpr(const CallExpr *E) {
8267 APValue Result;
8268 if (!handleCallExpr(E, Result, nullptr))
8269 return false;
8270 return DerivedSuccess(Result, E);
8271 }
8272
handleCallExpr(const CallExpr * E,APValue & Result,const LValue * ResultSlot)8273 bool handleCallExpr(const CallExpr *E, APValue &Result,
8274 const LValue *ResultSlot) {
8275 CallScopeRAII CallScope(Info);
8276
8277 const Expr *Callee = E->getCallee()->IgnoreParens();
8278 QualType CalleeType = Callee->getType();
8279
8280 const FunctionDecl *FD = nullptr;
8281 LValue *This = nullptr, ObjectArg;
8282 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8283 bool HasQualifier = false;
8284
8285 CallRef Call;
8286
8287 // Extract function decl and 'this' pointer from the callee.
8288 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8289 const CXXMethodDecl *Member = nullptr;
8290 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8291 // Explicit bound member calls, such as x.f() or p->g();
8292 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8293 return false;
8294 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8295 if (!Member)
8296 return Error(Callee);
8297 This = &ObjectArg;
8298 HasQualifier = ME->hasQualifier();
8299 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8300 // Indirect bound member calls ('.*' or '->*').
8301 const ValueDecl *D =
8302 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8303 if (!D)
8304 return false;
8305 Member = dyn_cast<CXXMethodDecl>(D);
8306 if (!Member)
8307 return Error(Callee);
8308 This = &ObjectArg;
8309 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8310 if (!Info.getLangOpts().CPlusPlus20)
8311 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8312 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8313 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8314 } else
8315 return Error(Callee);
8316 FD = Member;
8317 } else if (CalleeType->isFunctionPointerType()) {
8318 LValue CalleeLV;
8319 if (!EvaluatePointer(Callee, CalleeLV, Info))
8320 return false;
8321
8322 if (!CalleeLV.getLValueOffset().isZero())
8323 return Error(Callee);
8324 if (CalleeLV.isNullPointer()) {
8325 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8326 << const_cast<Expr *>(Callee);
8327 return false;
8328 }
8329 FD = dyn_cast_or_null<FunctionDecl>(
8330 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8331 if (!FD)
8332 return Error(Callee);
8333 // Don't call function pointers which have been cast to some other type.
8334 // Per DR (no number yet), the caller and callee can differ in noexcept.
8335 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8336 CalleeType->getPointeeType(), FD->getType())) {
8337 return Error(E);
8338 }
8339
8340 // For an (overloaded) assignment expression, evaluate the RHS before the
8341 // LHS.
8342 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8343 if (OCE && OCE->isAssignmentOp()) {
8344 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8345 Call = Info.CurrentCall->createCall(FD);
8346 bool HasThis = false;
8347 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8348 HasThis = MD->isImplicitObjectMemberFunction();
8349 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8350 /*RightToLeft=*/true, &ObjectArg))
8351 return false;
8352 }
8353
8354 // Overloaded operator calls to member functions are represented as normal
8355 // calls with '*this' as the first argument.
8356 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8357 if (MD &&
8358 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8359 // FIXME: When selecting an implicit conversion for an overloaded
8360 // operator delete, we sometimes try to evaluate calls to conversion
8361 // operators without a 'this' parameter!
8362 if (Args.empty())
8363 return Error(E);
8364
8365 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8366 return false;
8367
8368 // If we are calling a static operator, the 'this' argument needs to be
8369 // ignored after being evaluated.
8370 if (MD->isInstance())
8371 This = &ObjectArg;
8372
8373 // If this is syntactically a simple assignment using a trivial
8374 // assignment operator, start the lifetimes of union members as needed,
8375 // per C++20 [class.union]5.
8376 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8377 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8378 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8379 return false;
8380
8381 Args = Args.slice(1);
8382 } else if (MD && MD->isLambdaStaticInvoker()) {
8383 // Map the static invoker for the lambda back to the call operator.
8384 // Conveniently, we don't have to slice out the 'this' argument (as is
8385 // being done for the non-static case), since a static member function
8386 // doesn't have an implicit argument passed in.
8387 const CXXRecordDecl *ClosureClass = MD->getParent();
8388 assert(
8389 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8390 "Number of captures must be zero for conversion to function-ptr");
8391
8392 const CXXMethodDecl *LambdaCallOp =
8393 ClosureClass->getLambdaCallOperator();
8394
8395 // Set 'FD', the function that will be called below, to the call
8396 // operator. If the closure object represents a generic lambda, find
8397 // the corresponding specialization of the call operator.
8398
8399 if (ClosureClass->isGenericLambda()) {
8400 assert(MD->isFunctionTemplateSpecialization() &&
8401 "A generic lambda's static-invoker function must be a "
8402 "template specialization");
8403 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8404 FunctionTemplateDecl *CallOpTemplate =
8405 LambdaCallOp->getDescribedFunctionTemplate();
8406 void *InsertPos = nullptr;
8407 FunctionDecl *CorrespondingCallOpSpecialization =
8408 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8409 assert(CorrespondingCallOpSpecialization &&
8410 "We must always have a function call operator specialization "
8411 "that corresponds to our static invoker specialization");
8412 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8413 FD = CorrespondingCallOpSpecialization;
8414 } else
8415 FD = LambdaCallOp;
8416 } else if (FD->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
8417 if (FD->getDeclName().isAnyOperatorNew()) {
8418 LValue Ptr;
8419 if (!HandleOperatorNewCall(Info, E, Ptr))
8420 return false;
8421 Ptr.moveInto(Result);
8422 return CallScope.destroy();
8423 } else {
8424 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8425 }
8426 }
8427 } else
8428 return Error(E);
8429
8430 // Evaluate the arguments now if we've not already done so.
8431 if (!Call) {
8432 Call = Info.CurrentCall->createCall(FD);
8433 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8434 &ObjectArg))
8435 return false;
8436 }
8437
8438 SmallVector<QualType, 4> CovariantAdjustmentPath;
8439 if (This) {
8440 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8441 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8442 // Perform virtual dispatch, if necessary.
8443 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8444 CovariantAdjustmentPath);
8445 if (!FD)
8446 return false;
8447 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8448 // Check that the 'this' pointer points to an object of the right type.
8449 // FIXME: If this is an assignment operator call, we may need to change
8450 // the active union member before we check this.
8451 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8452 return false;
8453 }
8454 }
8455
8456 // Destructor calls are different enough that they have their own codepath.
8457 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8458 assert(This && "no 'this' pointer for destructor call");
8459 return HandleDestruction(Info, E, *This,
8460 Info.Ctx.getRecordType(DD->getParent())) &&
8461 CallScope.destroy();
8462 }
8463
8464 const FunctionDecl *Definition = nullptr;
8465 Stmt *Body = FD->getBody(Definition);
8466 SourceLocation Loc = E->getExprLoc();
8467
8468 // Treat the object argument as `this` when evaluating defaulted
8469 // special menmber functions
8470 if (FD->hasCXXExplicitFunctionObjectParameter())
8471 This = &ObjectArg;
8472
8473 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8474 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8475 Result, ResultSlot))
8476 return false;
8477
8478 if (!CovariantAdjustmentPath.empty() &&
8479 !HandleCovariantReturnAdjustment(Info, E, Result,
8480 CovariantAdjustmentPath))
8481 return false;
8482
8483 return CallScope.destroy();
8484 }
8485
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)8486 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8487 return StmtVisitorTy::Visit(E->getInitializer());
8488 }
VisitInitListExpr(const InitListExpr * E)8489 bool VisitInitListExpr(const InitListExpr *E) {
8490 if (E->getNumInits() == 0)
8491 return DerivedZeroInitialization(E);
8492 if (E->getNumInits() == 1)
8493 return StmtVisitorTy::Visit(E->getInit(0));
8494 return Error(E);
8495 }
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)8496 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8497 return DerivedZeroInitialization(E);
8498 }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)8499 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8500 return DerivedZeroInitialization(E);
8501 }
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)8502 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8503 return DerivedZeroInitialization(E);
8504 }
8505
8506 /// A member expression where the object is a prvalue is itself a prvalue.
VisitMemberExpr(const MemberExpr * E)8507 bool VisitMemberExpr(const MemberExpr *E) {
8508 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8509 "missing temporary materialization conversion");
8510 assert(!E->isArrow() && "missing call to bound member function?");
8511
8512 APValue Val;
8513 if (!Evaluate(Val, Info, E->getBase()))
8514 return false;
8515
8516 QualType BaseTy = E->getBase()->getType();
8517
8518 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8519 if (!FD) return Error(E);
8520 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8521 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8522 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8523
8524 // Note: there is no lvalue base here. But this case should only ever
8525 // happen in C or in C++98, where we cannot be evaluating a constexpr
8526 // constructor, which is the only case the base matters.
8527 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8528 SubobjectDesignator Designator(BaseTy);
8529 Designator.addDeclUnchecked(FD);
8530
8531 APValue Result;
8532 return extractSubobject(Info, E, Obj, Designator, Result) &&
8533 DerivedSuccess(Result, E);
8534 }
8535
VisitExtVectorElementExpr(const ExtVectorElementExpr * E)8536 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8537 APValue Val;
8538 if (!Evaluate(Val, Info, E->getBase()))
8539 return false;
8540
8541 if (Val.isVector()) {
8542 SmallVector<uint32_t, 4> Indices;
8543 E->getEncodedElementAccess(Indices);
8544 if (Indices.size() == 1) {
8545 // Return scalar.
8546 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8547 } else {
8548 // Construct new APValue vector.
8549 SmallVector<APValue, 4> Elts;
8550 for (unsigned I = 0; I < Indices.size(); ++I) {
8551 Elts.push_back(Val.getVectorElt(Indices[I]));
8552 }
8553 APValue VecResult(Elts.data(), Indices.size());
8554 return DerivedSuccess(VecResult, E);
8555 }
8556 }
8557
8558 return false;
8559 }
8560
VisitCastExpr(const CastExpr * E)8561 bool VisitCastExpr(const CastExpr *E) {
8562 switch (E->getCastKind()) {
8563 default:
8564 break;
8565
8566 case CK_AtomicToNonAtomic: {
8567 APValue AtomicVal;
8568 // This does not need to be done in place even for class/array types:
8569 // atomic-to-non-atomic conversion implies copying the object
8570 // representation.
8571 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8572 return false;
8573 return DerivedSuccess(AtomicVal, E);
8574 }
8575
8576 case CK_NoOp:
8577 case CK_UserDefinedConversion:
8578 return StmtVisitorTy::Visit(E->getSubExpr());
8579
8580 case CK_LValueToRValue: {
8581 LValue LVal;
8582 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8583 return false;
8584 APValue RVal;
8585 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8586 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8587 LVal, RVal))
8588 return false;
8589 return DerivedSuccess(RVal, E);
8590 }
8591 case CK_LValueToRValueBitCast: {
8592 APValue DestValue, SourceValue;
8593 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8594 return false;
8595 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8596 return false;
8597 return DerivedSuccess(DestValue, E);
8598 }
8599
8600 case CK_AddressSpaceConversion: {
8601 APValue Value;
8602 if (!Evaluate(Value, Info, E->getSubExpr()))
8603 return false;
8604 return DerivedSuccess(Value, E);
8605 }
8606 }
8607
8608 return Error(E);
8609 }
8610
VisitUnaryPostInc(const UnaryOperator * UO)8611 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8612 return VisitUnaryPostIncDec(UO);
8613 }
VisitUnaryPostDec(const UnaryOperator * UO)8614 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8615 return VisitUnaryPostIncDec(UO);
8616 }
VisitUnaryPostIncDec(const UnaryOperator * UO)8617 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8618 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8619 return Error(UO);
8620
8621 LValue LVal;
8622 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8623 return false;
8624 APValue RVal;
8625 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8626 UO->isIncrementOp(), &RVal))
8627 return false;
8628 return DerivedSuccess(RVal, UO);
8629 }
8630
VisitStmtExpr(const StmtExpr * E)8631 bool VisitStmtExpr(const StmtExpr *E) {
8632 // We will have checked the full-expressions inside the statement expression
8633 // when they were completed, and don't need to check them again now.
8634 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8635 false);
8636
8637 const CompoundStmt *CS = E->getSubStmt();
8638 if (CS->body_empty())
8639 return true;
8640
8641 BlockScopeRAII Scope(Info);
8642 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8643 BE = CS->body_end();
8644 /**/; ++BI) {
8645 if (BI + 1 == BE) {
8646 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8647 if (!FinalExpr) {
8648 Info.FFDiag((*BI)->getBeginLoc(),
8649 diag::note_constexpr_stmt_expr_unsupported);
8650 return false;
8651 }
8652 return this->Visit(FinalExpr) && Scope.destroy();
8653 }
8654
8655 APValue ReturnValue;
8656 StmtResult Result = { ReturnValue, nullptr };
8657 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8658 if (ESR != ESR_Succeeded) {
8659 // FIXME: If the statement-expression terminated due to 'return',
8660 // 'break', or 'continue', it would be nice to propagate that to
8661 // the outer statement evaluation rather than bailing out.
8662 if (ESR != ESR_Failed)
8663 Info.FFDiag((*BI)->getBeginLoc(),
8664 diag::note_constexpr_stmt_expr_unsupported);
8665 return false;
8666 }
8667 }
8668
8669 llvm_unreachable("Return from function from the loop above.");
8670 }
8671
VisitPackIndexingExpr(const PackIndexingExpr * E)8672 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8673 return StmtVisitorTy::Visit(E->getSelectedExpr());
8674 }
8675
8676 /// Visit a value which is evaluated, but whose value is ignored.
VisitIgnoredValue(const Expr * E)8677 void VisitIgnoredValue(const Expr *E) {
8678 EvaluateIgnoredValue(Info, E);
8679 }
8680
8681 /// Potentially visit a MemberExpr's base expression.
VisitIgnoredBaseExpression(const Expr * E)8682 void VisitIgnoredBaseExpression(const Expr *E) {
8683 // While MSVC doesn't evaluate the base expression, it does diagnose the
8684 // presence of side-effecting behavior.
8685 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8686 return;
8687 VisitIgnoredValue(E);
8688 }
8689 };
8690
8691 } // namespace
8692
8693 //===----------------------------------------------------------------------===//
8694 // Common base class for lvalue and temporary evaluation.
8695 //===----------------------------------------------------------------------===//
8696 namespace {
8697 template<class Derived>
8698 class LValueExprEvaluatorBase
8699 : public ExprEvaluatorBase<Derived> {
8700 protected:
8701 LValue &Result;
8702 bool InvalidBaseOK;
8703 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8704 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8705
Success(APValue::LValueBase B)8706 bool Success(APValue::LValueBase B) {
8707 Result.set(B);
8708 return true;
8709 }
8710
evaluatePointer(const Expr * E,LValue & Result)8711 bool evaluatePointer(const Expr *E, LValue &Result) {
8712 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8713 }
8714
8715 public:
LValueExprEvaluatorBase(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8716 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8717 : ExprEvaluatorBaseTy(Info), Result(Result),
8718 InvalidBaseOK(InvalidBaseOK) {}
8719
Success(const APValue & V,const Expr * E)8720 bool Success(const APValue &V, const Expr *E) {
8721 Result.setFrom(this->Info.Ctx, V);
8722 return true;
8723 }
8724
VisitMemberExpr(const MemberExpr * E)8725 bool VisitMemberExpr(const MemberExpr *E) {
8726 // Handle non-static data members.
8727 QualType BaseTy;
8728 bool EvalOK;
8729 if (E->isArrow()) {
8730 EvalOK = evaluatePointer(E->getBase(), Result);
8731 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8732 } else if (E->getBase()->isPRValue()) {
8733 assert(E->getBase()->getType()->isRecordType());
8734 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8735 BaseTy = E->getBase()->getType();
8736 } else {
8737 EvalOK = this->Visit(E->getBase());
8738 BaseTy = E->getBase()->getType();
8739 }
8740 if (!EvalOK) {
8741 if (!InvalidBaseOK)
8742 return false;
8743 Result.setInvalid(E);
8744 return true;
8745 }
8746
8747 const ValueDecl *MD = E->getMemberDecl();
8748 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8749 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8750 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8751 (void)BaseTy;
8752 if (!HandleLValueMember(this->Info, E, Result, FD))
8753 return false;
8754 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8755 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8756 return false;
8757 } else
8758 return this->Error(E);
8759
8760 if (MD->getType()->isReferenceType()) {
8761 APValue RefValue;
8762 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8763 RefValue))
8764 return false;
8765 return Success(RefValue, E);
8766 }
8767 return true;
8768 }
8769
VisitBinaryOperator(const BinaryOperator * E)8770 bool VisitBinaryOperator(const BinaryOperator *E) {
8771 switch (E->getOpcode()) {
8772 default:
8773 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8774
8775 case BO_PtrMemD:
8776 case BO_PtrMemI:
8777 return HandleMemberPointerAccess(this->Info, E, Result);
8778 }
8779 }
8780
VisitCastExpr(const CastExpr * E)8781 bool VisitCastExpr(const CastExpr *E) {
8782 switch (E->getCastKind()) {
8783 default:
8784 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8785
8786 case CK_DerivedToBase:
8787 case CK_UncheckedDerivedToBase:
8788 if (!this->Visit(E->getSubExpr()))
8789 return false;
8790
8791 // Now figure out the necessary offset to add to the base LV to get from
8792 // the derived class to the base class.
8793 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8794 Result);
8795 }
8796 }
8797 };
8798 }
8799
8800 //===----------------------------------------------------------------------===//
8801 // LValue Evaluation
8802 //
8803 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8804 // function designators (in C), decl references to void objects (in C), and
8805 // temporaries (if building with -Wno-address-of-temporary).
8806 //
8807 // LValue evaluation produces values comprising a base expression of one of the
8808 // following types:
8809 // - Declarations
8810 // * VarDecl
8811 // * FunctionDecl
8812 // - Literals
8813 // * CompoundLiteralExpr in C (and in global scope in C++)
8814 // * StringLiteral
8815 // * PredefinedExpr
8816 // * ObjCStringLiteralExpr
8817 // * ObjCEncodeExpr
8818 // * AddrLabelExpr
8819 // * BlockExpr
8820 // * CallExpr for a MakeStringConstant builtin
8821 // - typeid(T) expressions, as TypeInfoLValues
8822 // - Locals and temporaries
8823 // * MaterializeTemporaryExpr
8824 // * Any Expr, with a CallIndex indicating the function in which the temporary
8825 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
8826 // from the AST (FIXME).
8827 // * A MaterializeTemporaryExpr that has static storage duration, with no
8828 // CallIndex, for a lifetime-extended temporary.
8829 // * The ConstantExpr that is currently being evaluated during evaluation of an
8830 // immediate invocation.
8831 // plus an offset in bytes.
8832 //===----------------------------------------------------------------------===//
8833 namespace {
8834 class LValueExprEvaluator
8835 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8836 public:
LValueExprEvaluator(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8837 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8838 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8839
8840 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8841 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8842
8843 bool VisitCallExpr(const CallExpr *E);
8844 bool VisitDeclRefExpr(const DeclRefExpr *E);
VisitPredefinedExpr(const PredefinedExpr * E)8845 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8846 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8847 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8848 bool VisitMemberExpr(const MemberExpr *E);
VisitStringLiteral(const StringLiteral * E)8849 bool VisitStringLiteral(const StringLiteral *E) {
8850 return Success(APValue::LValueBase(
8851 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8852 }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)8853 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8854 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8855 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8856 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8857 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8858 bool VisitUnaryDeref(const UnaryOperator *E);
8859 bool VisitUnaryReal(const UnaryOperator *E);
8860 bool VisitUnaryImag(const UnaryOperator *E);
VisitUnaryPreInc(const UnaryOperator * UO)8861 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8862 return VisitUnaryPreIncDec(UO);
8863 }
VisitUnaryPreDec(const UnaryOperator * UO)8864 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8865 return VisitUnaryPreIncDec(UO);
8866 }
8867 bool VisitBinAssign(const BinaryOperator *BO);
8868 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8869
VisitCastExpr(const CastExpr * E)8870 bool VisitCastExpr(const CastExpr *E) {
8871 switch (E->getCastKind()) {
8872 default:
8873 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8874
8875 case CK_LValueBitCast:
8876 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8877 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
8878 << Info.Ctx.getLangOpts().CPlusPlus;
8879 if (!Visit(E->getSubExpr()))
8880 return false;
8881 Result.Designator.setInvalid();
8882 return true;
8883
8884 case CK_BaseToDerived:
8885 if (!Visit(E->getSubExpr()))
8886 return false;
8887 return HandleBaseToDerivedCast(Info, E, Result);
8888
8889 case CK_Dynamic:
8890 if (!Visit(E->getSubExpr()))
8891 return false;
8892 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8893 }
8894 }
8895 };
8896 } // end anonymous namespace
8897
8898 /// Get an lvalue to a field of a lambda's closure type.
HandleLambdaCapture(EvalInfo & Info,const Expr * E,LValue & Result,const CXXMethodDecl * MD,const FieldDecl * FD,bool LValueToRValueConversion)8899 static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8900 const CXXMethodDecl *MD, const FieldDecl *FD,
8901 bool LValueToRValueConversion) {
8902 // Static lambda function call operators can't have captures. We already
8903 // diagnosed this, so bail out here.
8904 if (MD->isStatic()) {
8905 assert(Info.CurrentCall->This == nullptr &&
8906 "This should not be set for a static call operator");
8907 return false;
8908 }
8909
8910 // Start with 'Result' referring to the complete closure object...
8911 if (MD->isExplicitObjectMemberFunction()) {
8912 // Self may be passed by reference or by value.
8913 const ParmVarDecl *Self = MD->getParamDecl(0);
8914 if (Self->getType()->isReferenceType()) {
8915 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8916 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
8917 Result.setFrom(Info.Ctx, *RefValue);
8918 } else {
8919 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8920 CallStackFrame *Frame =
8921 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8922 .first;
8923 unsigned Version = Info.CurrentCall->Arguments.Version;
8924 Result.set({VD, Frame->Index, Version});
8925 }
8926 } else
8927 Result = *Info.CurrentCall->This;
8928
8929 // ... then update it to refer to the field of the closure object
8930 // that represents the capture.
8931 if (!HandleLValueMember(Info, E, Result, FD))
8932 return false;
8933
8934 // And if the field is of reference type (or if we captured '*this' by
8935 // reference), update 'Result' to refer to what
8936 // the field refers to.
8937 if (LValueToRValueConversion) {
8938 APValue RVal;
8939 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
8940 return false;
8941 Result.setFrom(Info.Ctx, RVal);
8942 }
8943 return true;
8944 }
8945
8946 /// Evaluate an expression as an lvalue. This can be legitimately called on
8947 /// expressions which are not glvalues, in three cases:
8948 /// * function designators in C, and
8949 /// * "extern void" objects
8950 /// * @selector() expressions in Objective-C
EvaluateLValue(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8951 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8952 bool InvalidBaseOK) {
8953 assert(!E->isValueDependent());
8954 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8955 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8956 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8957 }
8958
VisitDeclRefExpr(const DeclRefExpr * E)8959 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8960 const ValueDecl *D = E->getDecl();
8961
8962 // If we are within a lambda's call operator, check whether the 'VD' referred
8963 // to within 'E' actually represents a lambda-capture that maps to a
8964 // data-member/field within the closure object, and if so, evaluate to the
8965 // field or what the field refers to.
8966 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8967 E->refersToEnclosingVariableOrCapture()) {
8968 // We don't always have a complete capture-map when checking or inferring if
8969 // the function call operator meets the requirements of a constexpr function
8970 // - but we don't need to evaluate the captures to determine constexprness
8971 // (dcl.constexpr C++17).
8972 if (Info.checkingPotentialConstantExpression())
8973 return false;
8974
8975 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
8976 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8977 return HandleLambdaCapture(Info, E, Result, MD, FD,
8978 FD->getType()->isReferenceType());
8979 }
8980 }
8981
8982 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8983 UnnamedGlobalConstantDecl>(D))
8984 return Success(cast<ValueDecl>(D));
8985 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8986 return VisitVarDecl(E, VD);
8987 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8988 return Visit(BD->getBinding());
8989 return Error(E);
8990 }
8991
VisitVarDecl(const Expr * E,const VarDecl * VD)8992 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8993 CallStackFrame *Frame = nullptr;
8994 unsigned Version = 0;
8995 if (VD->hasLocalStorage()) {
8996 // Only if a local variable was declared in the function currently being
8997 // evaluated, do we expect to be able to find its value in the current
8998 // frame. (Otherwise it was likely declared in an enclosing context and
8999 // could either have a valid evaluatable value (for e.g. a constexpr
9000 // variable) or be ill-formed (and trigger an appropriate evaluation
9001 // diagnostic)).
9002 CallStackFrame *CurrFrame = Info.CurrentCall;
9003 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9004 // Function parameters are stored in some caller's frame. (Usually the
9005 // immediate caller, but for an inherited constructor they may be more
9006 // distant.)
9007 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9008 if (CurrFrame->Arguments) {
9009 VD = CurrFrame->Arguments.getOrigParam(PVD);
9010 Frame =
9011 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9012 Version = CurrFrame->Arguments.Version;
9013 }
9014 } else {
9015 Frame = CurrFrame;
9016 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9017 }
9018 }
9019 }
9020
9021 if (!VD->getType()->isReferenceType()) {
9022 if (Frame) {
9023 Result.set({VD, Frame->Index, Version});
9024 return true;
9025 }
9026 return Success(VD);
9027 }
9028
9029 if (!Info.getLangOpts().CPlusPlus11) {
9030 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9031 << VD << VD->getType();
9032 Info.Note(VD->getLocation(), diag::note_declared_at);
9033 }
9034
9035 APValue *V;
9036 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9037 return false;
9038
9039 if (!V) {
9040 Result.set(VD);
9041 Result.AllowConstexprUnknown = true;
9042 return true;
9043 }
9044
9045 return Success(*V, E);
9046 }
9047
VisitCallExpr(const CallExpr * E)9048 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9049 if (!IsConstantEvaluatedBuiltinCall(E))
9050 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9051
9052 switch (E->getBuiltinCallee()) {
9053 default:
9054 return false;
9055 case Builtin::BIas_const:
9056 case Builtin::BIforward:
9057 case Builtin::BIforward_like:
9058 case Builtin::BImove:
9059 case Builtin::BImove_if_noexcept:
9060 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9061 return Visit(E->getArg(0));
9062 break;
9063 }
9064
9065 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9066 }
9067
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)9068 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9069 const MaterializeTemporaryExpr *E) {
9070 // Walk through the expression to find the materialized temporary itself.
9071 SmallVector<const Expr *, 2> CommaLHSs;
9072 SmallVector<SubobjectAdjustment, 2> Adjustments;
9073 const Expr *Inner =
9074 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9075
9076 // If we passed any comma operators, evaluate their LHSs.
9077 for (const Expr *E : CommaLHSs)
9078 if (!EvaluateIgnoredValue(Info, E))
9079 return false;
9080
9081 // A materialized temporary with static storage duration can appear within the
9082 // result of a constant expression evaluation, so we need to preserve its
9083 // value for use outside this evaluation.
9084 APValue *Value;
9085 if (E->getStorageDuration() == SD_Static) {
9086 if (Info.EvalMode == EvalInfo::EM_ConstantFold)
9087 return false;
9088 // FIXME: What about SD_Thread?
9089 Value = E->getOrCreateValue(true);
9090 *Value = APValue();
9091 Result.set(E);
9092 } else {
9093 Value = &Info.CurrentCall->createTemporary(
9094 E, Inner->getType(),
9095 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9096 : ScopeKind::Block,
9097 Result);
9098 }
9099
9100 QualType Type = Inner->getType();
9101
9102 // Materialize the temporary itself.
9103 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9104 *Value = APValue();
9105 return false;
9106 }
9107
9108 // Adjust our lvalue to refer to the desired subobject.
9109 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9110 --I;
9111 switch (Adjustments[I].Kind) {
9112 case SubobjectAdjustment::DerivedToBaseAdjustment:
9113 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9114 Type, Result))
9115 return false;
9116 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9117 break;
9118
9119 case SubobjectAdjustment::FieldAdjustment:
9120 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9121 return false;
9122 Type = Adjustments[I].Field->getType();
9123 break;
9124
9125 case SubobjectAdjustment::MemberPointerAdjustment:
9126 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9127 Adjustments[I].Ptr.RHS))
9128 return false;
9129 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9130 break;
9131 }
9132 }
9133
9134 return true;
9135 }
9136
9137 bool
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)9138 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9139 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9140 "lvalue compound literal in c++?");
9141 APValue *Lit;
9142 // If CompountLiteral has static storage, its value can be used outside
9143 // this expression. So evaluate it once and store it in ASTContext.
9144 if (E->hasStaticStorage()) {
9145 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9146 Result.set(E);
9147 // Reset any previously evaluated state, otherwise evaluation below might
9148 // fail.
9149 // FIXME: Should we just re-use the previously evaluated value instead?
9150 *Lit = APValue();
9151 } else {
9152 assert(!Info.getLangOpts().CPlusPlus);
9153 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9154 ScopeKind::Block, Result);
9155 }
9156 // FIXME: Evaluating in place isn't always right. We should figure out how to
9157 // use appropriate evaluation context here, see
9158 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9159 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9160 *Lit = APValue();
9161 return false;
9162 }
9163 return true;
9164 }
9165
VisitCXXTypeidExpr(const CXXTypeidExpr * E)9166 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9167 TypeInfoLValue TypeInfo;
9168
9169 if (!E->isPotentiallyEvaluated()) {
9170 if (E->isTypeOperand())
9171 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9172 else
9173 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9174 } else {
9175 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9176 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9177 << E->getExprOperand()->getType()
9178 << E->getExprOperand()->getSourceRange();
9179 }
9180
9181 if (!Visit(E->getExprOperand()))
9182 return false;
9183
9184 std::optional<DynamicType> DynType =
9185 ComputeDynamicType(Info, E, Result, AK_TypeId);
9186 if (!DynType)
9187 return false;
9188
9189 TypeInfo =
9190 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
9191 }
9192
9193 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9194 }
9195
VisitCXXUuidofExpr(const CXXUuidofExpr * E)9196 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9197 return Success(E->getGuidDecl());
9198 }
9199
VisitMemberExpr(const MemberExpr * E)9200 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9201 // Handle static data members.
9202 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9203 VisitIgnoredBaseExpression(E->getBase());
9204 return VisitVarDecl(E, VD);
9205 }
9206
9207 // Handle static member functions.
9208 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9209 if (MD->isStatic()) {
9210 VisitIgnoredBaseExpression(E->getBase());
9211 return Success(MD);
9212 }
9213 }
9214
9215 // Handle non-static data members.
9216 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9217 }
9218
VisitExtVectorElementExpr(const ExtVectorElementExpr * E)9219 bool LValueExprEvaluator::VisitExtVectorElementExpr(
9220 const ExtVectorElementExpr *E) {
9221 bool Success = true;
9222
9223 APValue Val;
9224 if (!Evaluate(Val, Info, E->getBase())) {
9225 if (!Info.noteFailure())
9226 return false;
9227 Success = false;
9228 }
9229
9230 SmallVector<uint32_t, 4> Indices;
9231 E->getEncodedElementAccess(Indices);
9232 // FIXME: support accessing more than one element
9233 if (Indices.size() > 1)
9234 return false;
9235
9236 if (Success) {
9237 Result.setFrom(Info.Ctx, Val);
9238 QualType BaseType = E->getBase()->getType();
9239 if (E->isArrow())
9240 BaseType = BaseType->getPointeeType();
9241 const auto *VT = BaseType->castAs<VectorType>();
9242 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9243 VT->getNumElements(), Indices[0]);
9244 }
9245
9246 return Success;
9247 }
9248
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)9249 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9250 if (E->getBase()->getType()->isSveVLSBuiltinType())
9251 return Error(E);
9252
9253 APSInt Index;
9254 bool Success = true;
9255
9256 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9257 APValue Val;
9258 if (!Evaluate(Val, Info, E->getBase())) {
9259 if (!Info.noteFailure())
9260 return false;
9261 Success = false;
9262 }
9263
9264 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9265 if (!Info.noteFailure())
9266 return false;
9267 Success = false;
9268 }
9269
9270 if (Success) {
9271 Result.setFrom(Info.Ctx, Val);
9272 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9273 VT->getNumElements(), Index.getExtValue());
9274 }
9275
9276 return Success;
9277 }
9278
9279 // C++17's rules require us to evaluate the LHS first, regardless of which
9280 // side is the base.
9281 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9282 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9283 : !EvaluateInteger(SubExpr, Index, Info)) {
9284 if (!Info.noteFailure())
9285 return false;
9286 Success = false;
9287 }
9288 }
9289
9290 return Success &&
9291 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9292 }
9293
VisitUnaryDeref(const UnaryOperator * E)9294 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9295 return evaluatePointer(E->getSubExpr(), Result);
9296 }
9297
VisitUnaryReal(const UnaryOperator * E)9298 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9299 if (!Visit(E->getSubExpr()))
9300 return false;
9301 // __real is a no-op on scalar lvalues.
9302 if (E->getSubExpr()->getType()->isAnyComplexType())
9303 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9304 return true;
9305 }
9306
VisitUnaryImag(const UnaryOperator * E)9307 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9308 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9309 "lvalue __imag__ on scalar?");
9310 if (!Visit(E->getSubExpr()))
9311 return false;
9312 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9313 return true;
9314 }
9315
VisitUnaryPreIncDec(const UnaryOperator * UO)9316 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9317 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9318 return Error(UO);
9319
9320 if (!this->Visit(UO->getSubExpr()))
9321 return false;
9322
9323 return handleIncDec(
9324 this->Info, UO, Result, UO->getSubExpr()->getType(),
9325 UO->isIncrementOp(), nullptr);
9326 }
9327
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)9328 bool LValueExprEvaluator::VisitCompoundAssignOperator(
9329 const CompoundAssignOperator *CAO) {
9330 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9331 return Error(CAO);
9332
9333 bool Success = true;
9334
9335 // C++17 onwards require that we evaluate the RHS first.
9336 APValue RHS;
9337 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9338 if (!Info.noteFailure())
9339 return false;
9340 Success = false;
9341 }
9342
9343 // The overall lvalue result is the result of evaluating the LHS.
9344 if (!this->Visit(CAO->getLHS()) || !Success)
9345 return false;
9346
9347 return handleCompoundAssignment(
9348 this->Info, CAO,
9349 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9350 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9351 }
9352
VisitBinAssign(const BinaryOperator * E)9353 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9354 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9355 return Error(E);
9356
9357 bool Success = true;
9358
9359 // C++17 onwards require that we evaluate the RHS first.
9360 APValue NewVal;
9361 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9362 if (!Info.noteFailure())
9363 return false;
9364 Success = false;
9365 }
9366
9367 if (!this->Visit(E->getLHS()) || !Success)
9368 return false;
9369
9370 if (Info.getLangOpts().CPlusPlus20 &&
9371 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
9372 return false;
9373
9374 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9375 NewVal);
9376 }
9377
9378 //===----------------------------------------------------------------------===//
9379 // Pointer Evaluation
9380 //===----------------------------------------------------------------------===//
9381
9382 /// Attempts to compute the number of bytes available at the pointer
9383 /// returned by a function with the alloc_size attribute. Returns true if we
9384 /// were successful. Places an unsigned number into `Result`.
9385 ///
9386 /// This expects the given CallExpr to be a call to a function with an
9387 /// alloc_size attribute.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const CallExpr * Call,llvm::APInt & Result)9388 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
9389 const CallExpr *Call,
9390 llvm::APInt &Result) {
9391 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
9392
9393 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
9394 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
9395 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
9396 if (Call->getNumArgs() <= SizeArgNo)
9397 return false;
9398
9399 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
9400 Expr::EvalResult ExprResult;
9401 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
9402 return false;
9403 Into = ExprResult.Val.getInt();
9404 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
9405 return false;
9406 Into = Into.zext(BitsInSizeT);
9407 return true;
9408 };
9409
9410 APSInt SizeOfElem;
9411 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
9412 return false;
9413
9414 if (!AllocSize->getNumElemsParam().isValid()) {
9415 Result = std::move(SizeOfElem);
9416 return true;
9417 }
9418
9419 APSInt NumberOfElems;
9420 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
9421 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
9422 return false;
9423
9424 bool Overflow;
9425 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
9426 if (Overflow)
9427 return false;
9428
9429 Result = std::move(BytesAvailable);
9430 return true;
9431 }
9432
9433 /// Convenience function. LVal's base must be a call to an alloc_size
9434 /// function.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const LValue & LVal,llvm::APInt & Result)9435 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
9436 const LValue &LVal,
9437 llvm::APInt &Result) {
9438 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9439 "Can't get the size of a non alloc_size function");
9440 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9441 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9442 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
9443 }
9444
9445 /// Attempts to evaluate the given LValueBase as the result of a call to
9446 /// a function with the alloc_size attribute. If it was possible to do so, this
9447 /// function will return true, make Result's Base point to said function call,
9448 /// and mark Result's Base as invalid.
evaluateLValueAsAllocSize(EvalInfo & Info,APValue::LValueBase Base,LValue & Result)9449 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
9450 LValue &Result) {
9451 if (Base.isNull())
9452 return false;
9453
9454 // Because we do no form of static analysis, we only support const variables.
9455 //
9456 // Additionally, we can't support parameters, nor can we support static
9457 // variables (in the latter case, use-before-assign isn't UB; in the former,
9458 // we have no clue what they'll be assigned to).
9459 const auto *VD =
9460 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9461 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9462 return false;
9463
9464 const Expr *Init = VD->getAnyInitializer();
9465 if (!Init || Init->getType().isNull())
9466 return false;
9467
9468 const Expr *E = Init->IgnoreParens();
9469 if (!tryUnwrapAllocSizeCall(E))
9470 return false;
9471
9472 // Store E instead of E unwrapped so that the type of the LValue's base is
9473 // what the user wanted.
9474 Result.setInvalid(E);
9475
9476 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9477 Result.addUnsizedArray(Info, E, Pointee);
9478 return true;
9479 }
9480
9481 namespace {
9482 class PointerExprEvaluator
9483 : public ExprEvaluatorBase<PointerExprEvaluator> {
9484 LValue &Result;
9485 bool InvalidBaseOK;
9486
Success(const Expr * E)9487 bool Success(const Expr *E) {
9488 Result.set(E);
9489 return true;
9490 }
9491
evaluateLValue(const Expr * E,LValue & Result)9492 bool evaluateLValue(const Expr *E, LValue &Result) {
9493 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9494 }
9495
evaluatePointer(const Expr * E,LValue & Result)9496 bool evaluatePointer(const Expr *E, LValue &Result) {
9497 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9498 }
9499
9500 bool visitNonBuiltinCallExpr(const CallExpr *E);
9501 public:
9502
PointerExprEvaluator(EvalInfo & info,LValue & Result,bool InvalidBaseOK)9503 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9504 : ExprEvaluatorBaseTy(info), Result(Result),
9505 InvalidBaseOK(InvalidBaseOK) {}
9506
Success(const APValue & V,const Expr * E)9507 bool Success(const APValue &V, const Expr *E) {
9508 Result.setFrom(Info.Ctx, V);
9509 return true;
9510 }
ZeroInitialization(const Expr * E)9511 bool ZeroInitialization(const Expr *E) {
9512 Result.setNull(Info.Ctx, E->getType());
9513 return true;
9514 }
9515
9516 bool VisitBinaryOperator(const BinaryOperator *E);
9517 bool VisitCastExpr(const CastExpr* E);
9518 bool VisitUnaryAddrOf(const UnaryOperator *E);
VisitObjCStringLiteral(const ObjCStringLiteral * E)9519 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9520 { return Success(E); }
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)9521 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9522 if (E->isExpressibleAsConstantInitializer())
9523 return Success(E);
9524 if (Info.noteFailure())
9525 EvaluateIgnoredValue(Info, E->getSubExpr());
9526 return Error(E);
9527 }
VisitAddrLabelExpr(const AddrLabelExpr * E)9528 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9529 { return Success(E); }
9530 bool VisitCallExpr(const CallExpr *E);
9531 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
VisitBlockExpr(const BlockExpr * E)9532 bool VisitBlockExpr(const BlockExpr *E) {
9533 if (!E->getBlockDecl()->hasCaptures())
9534 return Success(E);
9535 return Error(E);
9536 }
VisitCXXThisExpr(const CXXThisExpr * E)9537 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9538 auto DiagnoseInvalidUseOfThis = [&] {
9539 if (Info.getLangOpts().CPlusPlus11)
9540 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9541 else
9542 Info.FFDiag(E);
9543 };
9544
9545 // Can't look at 'this' when checking a potential constant expression.
9546 if (Info.checkingPotentialConstantExpression())
9547 return false;
9548
9549 bool IsExplicitLambda =
9550 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9551 if (!IsExplicitLambda) {
9552 if (!Info.CurrentCall->This) {
9553 DiagnoseInvalidUseOfThis();
9554 return false;
9555 }
9556
9557 Result = *Info.CurrentCall->This;
9558 }
9559
9560 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9561 // Ensure we actually have captured 'this'. If something was wrong with
9562 // 'this' capture, the error would have been previously reported.
9563 // Otherwise we can be inside of a default initialization of an object
9564 // declared by lambda's body, so no need to return false.
9565 if (!Info.CurrentCall->LambdaThisCaptureField) {
9566 if (IsExplicitLambda && !Info.CurrentCall->This) {
9567 DiagnoseInvalidUseOfThis();
9568 return false;
9569 }
9570
9571 return true;
9572 }
9573
9574 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9575 return HandleLambdaCapture(
9576 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9577 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9578 }
9579 return true;
9580 }
9581
9582 bool VisitCXXNewExpr(const CXXNewExpr *E);
9583
VisitSourceLocExpr(const SourceLocExpr * E)9584 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9585 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9586 APValue LValResult = E->EvaluateInContext(
9587 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9588 Result.setFrom(Info.Ctx, LValResult);
9589 return true;
9590 }
9591
VisitEmbedExpr(const EmbedExpr * E)9592 bool VisitEmbedExpr(const EmbedExpr *E) {
9593 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9594 return true;
9595 }
9596
VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr * E)9597 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9598 std::string ResultStr = E->ComputeName(Info.Ctx);
9599
9600 QualType CharTy = Info.Ctx.CharTy.withConst();
9601 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9602 ResultStr.size() + 1);
9603 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9604 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9605
9606 StringLiteral *SL =
9607 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9608 /*Pascal*/ false, ArrayTy, E->getLocation());
9609
9610 evaluateLValue(SL, Result);
9611 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9612 return true;
9613 }
9614
9615 // FIXME: Missing: @protocol, @selector
9616 };
9617 } // end anonymous namespace
9618
EvaluatePointer(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)9619 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9620 bool InvalidBaseOK) {
9621 assert(!E->isValueDependent());
9622 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9623 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9624 }
9625
VisitBinaryOperator(const BinaryOperator * E)9626 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9627 if (E->getOpcode() != BO_Add &&
9628 E->getOpcode() != BO_Sub)
9629 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9630
9631 const Expr *PExp = E->getLHS();
9632 const Expr *IExp = E->getRHS();
9633 if (IExp->getType()->isPointerType())
9634 std::swap(PExp, IExp);
9635
9636 bool EvalPtrOK = evaluatePointer(PExp, Result);
9637 if (!EvalPtrOK && !Info.noteFailure())
9638 return false;
9639
9640 llvm::APSInt Offset;
9641 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9642 return false;
9643
9644 if (E->getOpcode() == BO_Sub)
9645 negateAsSigned(Offset);
9646
9647 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9648 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9649 }
9650
VisitUnaryAddrOf(const UnaryOperator * E)9651 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9652 return evaluateLValue(E->getSubExpr(), Result);
9653 }
9654
9655 // Is the provided decl 'std::source_location::current'?
IsDeclSourceLocationCurrent(const FunctionDecl * FD)9656 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
9657 if (!FD)
9658 return false;
9659 const IdentifierInfo *FnII = FD->getIdentifier();
9660 if (!FnII || !FnII->isStr("current"))
9661 return false;
9662
9663 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9664 if (!RD)
9665 return false;
9666
9667 const IdentifierInfo *ClassII = RD->getIdentifier();
9668 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9669 }
9670
VisitCastExpr(const CastExpr * E)9671 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9672 const Expr *SubExpr = E->getSubExpr();
9673
9674 switch (E->getCastKind()) {
9675 default:
9676 break;
9677 case CK_BitCast:
9678 case CK_CPointerToObjCPointerCast:
9679 case CK_BlockPointerToObjCPointerCast:
9680 case CK_AnyPointerToBlockPointerCast:
9681 case CK_AddressSpaceConversion:
9682 if (!Visit(SubExpr))
9683 return false;
9684 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9685 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9686 // also static_casts, but we disallow them as a resolution to DR1312.
9687 if (!E->getType()->isVoidPointerType()) {
9688 // In some circumstances, we permit casting from void* to cv1 T*, when the
9689 // actual pointee object is actually a cv2 T.
9690 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9691 !Result.IsNullPtr;
9692 bool VoidPtrCastMaybeOK =
9693 Result.IsNullPtr ||
9694 (HasValidResult &&
9695 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9696 E->getType()->getPointeeType()));
9697 // 1. We'll allow it in std::allocator::allocate, and anything which that
9698 // calls.
9699 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9700 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9701 // We'll allow it in the body of std::source_location::current. GCC's
9702 // implementation had a parameter of type `void*`, and casts from
9703 // that back to `const __impl*` in its body.
9704 if (VoidPtrCastMaybeOK &&
9705 (Info.getStdAllocatorCaller("allocate") ||
9706 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9707 Info.getLangOpts().CPlusPlus26)) {
9708 // Permitted.
9709 } else {
9710 if (SubExpr->getType()->isVoidPointerType() &&
9711 Info.getLangOpts().CPlusPlus) {
9712 if (HasValidResult)
9713 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9714 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9715 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9716 << E->getType()->getPointeeType();
9717 else
9718 CCEDiag(E, diag::note_constexpr_invalid_cast)
9719 << diag::ConstexprInvalidCastKind::CastFrom
9720 << SubExpr->getType();
9721 } else
9722 CCEDiag(E, diag::note_constexpr_invalid_cast)
9723 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9724 << Info.Ctx.getLangOpts().CPlusPlus;
9725 Result.Designator.setInvalid();
9726 }
9727 }
9728 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9729 ZeroInitialization(E);
9730 return true;
9731
9732 case CK_DerivedToBase:
9733 case CK_UncheckedDerivedToBase:
9734 if (!evaluatePointer(E->getSubExpr(), Result))
9735 return false;
9736 if (!Result.Base && Result.Offset.isZero())
9737 return true;
9738
9739 // Now figure out the necessary offset to add to the base LV to get from
9740 // the derived class to the base class.
9741 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9742 castAs<PointerType>()->getPointeeType(),
9743 Result);
9744
9745 case CK_BaseToDerived:
9746 if (!Visit(E->getSubExpr()))
9747 return false;
9748 if (!Result.Base && Result.Offset.isZero())
9749 return true;
9750 return HandleBaseToDerivedCast(Info, E, Result);
9751
9752 case CK_Dynamic:
9753 if (!Visit(E->getSubExpr()))
9754 return false;
9755 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9756
9757 case CK_NullToPointer:
9758 VisitIgnoredValue(E->getSubExpr());
9759 return ZeroInitialization(E);
9760
9761 case CK_IntegralToPointer: {
9762 CCEDiag(E, diag::note_constexpr_invalid_cast)
9763 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9764 << Info.Ctx.getLangOpts().CPlusPlus;
9765
9766 APValue Value;
9767 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9768 break;
9769
9770 if (Value.isInt()) {
9771 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9772 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9773 Result.Base = (Expr*)nullptr;
9774 Result.InvalidBase = false;
9775 Result.Offset = CharUnits::fromQuantity(N);
9776 Result.Designator.setInvalid();
9777 Result.IsNullPtr = false;
9778 return true;
9779 } else {
9780 // In rare instances, the value isn't an lvalue.
9781 // For example, when the value is the difference between the addresses of
9782 // two labels. We reject that as a constant expression because we can't
9783 // compute a valid offset to convert into a pointer.
9784 if (!Value.isLValue())
9785 return false;
9786
9787 // Cast is of an lvalue, no need to change value.
9788 Result.setFrom(Info.Ctx, Value);
9789 return true;
9790 }
9791 }
9792
9793 case CK_ArrayToPointerDecay: {
9794 if (SubExpr->isGLValue()) {
9795 if (!evaluateLValue(SubExpr, Result))
9796 return false;
9797 } else {
9798 APValue &Value = Info.CurrentCall->createTemporary(
9799 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9800 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9801 return false;
9802 }
9803 // The result is a pointer to the first element of the array.
9804 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9805 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9806 Result.addArray(Info, E, CAT);
9807 else
9808 Result.addUnsizedArray(Info, E, AT->getElementType());
9809 return true;
9810 }
9811
9812 case CK_FunctionToPointerDecay:
9813 return evaluateLValue(SubExpr, Result);
9814
9815 case CK_LValueToRValue: {
9816 LValue LVal;
9817 if (!evaluateLValue(E->getSubExpr(), LVal))
9818 return false;
9819
9820 APValue RVal;
9821 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9822 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9823 LVal, RVal))
9824 return InvalidBaseOK &&
9825 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9826 return Success(RVal, E);
9827 }
9828 }
9829
9830 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9831 }
9832
GetAlignOfType(const ASTContext & Ctx,QualType T,UnaryExprOrTypeTrait ExprKind)9833 static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T,
9834 UnaryExprOrTypeTrait ExprKind) {
9835 // C++ [expr.alignof]p3:
9836 // When alignof is applied to a reference type, the result is the
9837 // alignment of the referenced type.
9838 T = T.getNonReferenceType();
9839
9840 if (T.getQualifiers().hasUnaligned())
9841 return CharUnits::One();
9842
9843 const bool AlignOfReturnsPreferred =
9844 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9845
9846 // __alignof is defined to return the preferred alignment.
9847 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9848 // as well.
9849 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9850 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9851 // alignof and _Alignof are defined to return the ABI alignment.
9852 else if (ExprKind == UETT_AlignOf)
9853 return Ctx.getTypeAlignInChars(T.getTypePtr());
9854 else
9855 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9856 }
9857
GetAlignOfExpr(const ASTContext & Ctx,const Expr * E,UnaryExprOrTypeTrait ExprKind)9858 CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E,
9859 UnaryExprOrTypeTrait ExprKind) {
9860 E = E->IgnoreParens();
9861
9862 // The kinds of expressions that we have special-case logic here for
9863 // should be kept up to date with the special checks for those
9864 // expressions in Sema.
9865
9866 // alignof decl is always accepted, even if it doesn't make sense: we default
9867 // to 1 in those cases.
9868 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9869 return Ctx.getDeclAlign(DRE->getDecl(),
9870 /*RefAsPointee*/ true);
9871
9872 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9873 return Ctx.getDeclAlign(ME->getMemberDecl(),
9874 /*RefAsPointee*/ true);
9875
9876 return GetAlignOfType(Ctx, E->getType(), ExprKind);
9877 }
9878
getBaseAlignment(EvalInfo & Info,const LValue & Value)9879 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9880 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9881 return Info.Ctx.getDeclAlign(VD);
9882 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9883 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9884 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9885 }
9886
9887 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9888 /// __builtin_is_aligned and __builtin_assume_aligned.
getAlignmentArgument(const Expr * E,QualType ForType,EvalInfo & Info,APSInt & Alignment)9889 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9890 EvalInfo &Info, APSInt &Alignment) {
9891 if (!EvaluateInteger(E, Alignment, Info))
9892 return false;
9893 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9894 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9895 return false;
9896 }
9897 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9898 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9899 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9900 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9901 << MaxValue << ForType << Alignment;
9902 return false;
9903 }
9904 // Ensure both alignment and source value have the same bit width so that we
9905 // don't assert when computing the resulting value.
9906 APSInt ExtAlignment =
9907 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9908 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9909 "Alignment should not be changed by ext/trunc");
9910 Alignment = ExtAlignment;
9911 assert(Alignment.getBitWidth() == SrcWidth);
9912 return true;
9913 }
9914
9915 // To be clear: this happily visits unsupported builtins. Better name welcomed.
visitNonBuiltinCallExpr(const CallExpr * E)9916 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9917 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9918 return true;
9919
9920 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9921 return false;
9922
9923 Result.setInvalid(E);
9924 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9925 Result.addUnsizedArray(Info, E, PointeeTy);
9926 return true;
9927 }
9928
VisitCallExpr(const CallExpr * E)9929 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9930 if (!IsConstantEvaluatedBuiltinCall(E))
9931 return visitNonBuiltinCallExpr(E);
9932 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9933 }
9934
9935 // Determine if T is a character type for which we guarantee that
9936 // sizeof(T) == 1.
isOneByteCharacterType(QualType T)9937 static bool isOneByteCharacterType(QualType T) {
9938 return T->isCharType() || T->isChar8Type();
9939 }
9940
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)9941 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9942 unsigned BuiltinOp) {
9943 if (IsOpaqueConstantCall(E))
9944 return Success(E);
9945
9946 switch (BuiltinOp) {
9947 case Builtin::BIaddressof:
9948 case Builtin::BI__addressof:
9949 case Builtin::BI__builtin_addressof:
9950 return evaluateLValue(E->getArg(0), Result);
9951 case Builtin::BI__builtin_assume_aligned: {
9952 // We need to be very careful here because: if the pointer does not have the
9953 // asserted alignment, then the behavior is undefined, and undefined
9954 // behavior is non-constant.
9955 if (!evaluatePointer(E->getArg(0), Result))
9956 return false;
9957
9958 LValue OffsetResult(Result);
9959 APSInt Alignment;
9960 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9961 Alignment))
9962 return false;
9963 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9964
9965 if (E->getNumArgs() > 2) {
9966 APSInt Offset;
9967 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9968 return false;
9969
9970 int64_t AdditionalOffset = -Offset.getZExtValue();
9971 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9972 }
9973
9974 // If there is a base object, then it must have the correct alignment.
9975 if (OffsetResult.Base) {
9976 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9977
9978 if (BaseAlignment < Align) {
9979 Result.Designator.setInvalid();
9980 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
9981 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
9982 return false;
9983 }
9984 }
9985
9986 // The offset must also have the correct alignment.
9987 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9988 Result.Designator.setInvalid();
9989
9990 (OffsetResult.Base
9991 ? CCEDiag(E->getArg(0),
9992 diag::note_constexpr_baa_insufficient_alignment)
9993 << 1
9994 : CCEDiag(E->getArg(0),
9995 diag::note_constexpr_baa_value_insufficient_alignment))
9996 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
9997 return false;
9998 }
9999
10000 return true;
10001 }
10002 case Builtin::BI__builtin_align_up:
10003 case Builtin::BI__builtin_align_down: {
10004 if (!evaluatePointer(E->getArg(0), Result))
10005 return false;
10006 APSInt Alignment;
10007 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10008 Alignment))
10009 return false;
10010 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10011 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10012 // For align_up/align_down, we can return the same value if the alignment
10013 // is known to be greater or equal to the requested value.
10014 if (PtrAlign.getQuantity() >= Alignment)
10015 return true;
10016
10017 // The alignment could be greater than the minimum at run-time, so we cannot
10018 // infer much about the resulting pointer value. One case is possible:
10019 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10020 // can infer the correct index if the requested alignment is smaller than
10021 // the base alignment so we can perform the computation on the offset.
10022 if (BaseAlignment.getQuantity() >= Alignment) {
10023 assert(Alignment.getBitWidth() <= 64 &&
10024 "Cannot handle > 64-bit address-space");
10025 uint64_t Alignment64 = Alignment.getZExtValue();
10026 CharUnits NewOffset = CharUnits::fromQuantity(
10027 BuiltinOp == Builtin::BI__builtin_align_down
10028 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10029 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10030 Result.adjustOffset(NewOffset - Result.Offset);
10031 // TODO: diagnose out-of-bounds values/only allow for arrays?
10032 return true;
10033 }
10034 // Otherwise, we cannot constant-evaluate the result.
10035 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10036 << Alignment;
10037 return false;
10038 }
10039 case Builtin::BI__builtin_operator_new:
10040 return HandleOperatorNewCall(Info, E, Result);
10041 case Builtin::BI__builtin_launder:
10042 return evaluatePointer(E->getArg(0), Result);
10043 case Builtin::BIstrchr:
10044 case Builtin::BIwcschr:
10045 case Builtin::BImemchr:
10046 case Builtin::BIwmemchr:
10047 if (Info.getLangOpts().CPlusPlus11)
10048 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10049 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10050 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10051 else
10052 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10053 [[fallthrough]];
10054 case Builtin::BI__builtin_strchr:
10055 case Builtin::BI__builtin_wcschr:
10056 case Builtin::BI__builtin_memchr:
10057 case Builtin::BI__builtin_char_memchr:
10058 case Builtin::BI__builtin_wmemchr: {
10059 if (!Visit(E->getArg(0)))
10060 return false;
10061 APSInt Desired;
10062 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10063 return false;
10064 uint64_t MaxLength = uint64_t(-1);
10065 if (BuiltinOp != Builtin::BIstrchr &&
10066 BuiltinOp != Builtin::BIwcschr &&
10067 BuiltinOp != Builtin::BI__builtin_strchr &&
10068 BuiltinOp != Builtin::BI__builtin_wcschr) {
10069 APSInt N;
10070 if (!EvaluateInteger(E->getArg(2), N, Info))
10071 return false;
10072 MaxLength = N.getZExtValue();
10073 }
10074 // We cannot find the value if there are no candidates to match against.
10075 if (MaxLength == 0u)
10076 return ZeroInitialization(E);
10077 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10078 Result.Designator.Invalid)
10079 return false;
10080 QualType CharTy = Result.Designator.getType(Info.Ctx);
10081 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10082 BuiltinOp == Builtin::BI__builtin_memchr;
10083 assert(IsRawByte ||
10084 Info.Ctx.hasSameUnqualifiedType(
10085 CharTy, E->getArg(0)->getType()->getPointeeType()));
10086 // Pointers to const void may point to objects of incomplete type.
10087 if (IsRawByte && CharTy->isIncompleteType()) {
10088 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10089 return false;
10090 }
10091 // Give up on byte-oriented matching against multibyte elements.
10092 // FIXME: We can compare the bytes in the correct order.
10093 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10094 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10095 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10096 return false;
10097 }
10098 // Figure out what value we're actually looking for (after converting to
10099 // the corresponding unsigned type if necessary).
10100 uint64_t DesiredVal;
10101 bool StopAtNull = false;
10102 switch (BuiltinOp) {
10103 case Builtin::BIstrchr:
10104 case Builtin::BI__builtin_strchr:
10105 // strchr compares directly to the passed integer, and therefore
10106 // always fails if given an int that is not a char.
10107 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10108 E->getArg(1)->getType(),
10109 Desired),
10110 Desired))
10111 return ZeroInitialization(E);
10112 StopAtNull = true;
10113 [[fallthrough]];
10114 case Builtin::BImemchr:
10115 case Builtin::BI__builtin_memchr:
10116 case Builtin::BI__builtin_char_memchr:
10117 // memchr compares by converting both sides to unsigned char. That's also
10118 // correct for strchr if we get this far (to cope with plain char being
10119 // unsigned in the strchr case).
10120 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10121 break;
10122
10123 case Builtin::BIwcschr:
10124 case Builtin::BI__builtin_wcschr:
10125 StopAtNull = true;
10126 [[fallthrough]];
10127 case Builtin::BIwmemchr:
10128 case Builtin::BI__builtin_wmemchr:
10129 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10130 DesiredVal = Desired.getZExtValue();
10131 break;
10132 }
10133
10134 for (; MaxLength; --MaxLength) {
10135 APValue Char;
10136 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10137 !Char.isInt())
10138 return false;
10139 if (Char.getInt().getZExtValue() == DesiredVal)
10140 return true;
10141 if (StopAtNull && !Char.getInt())
10142 break;
10143 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10144 return false;
10145 }
10146 // Not found: return nullptr.
10147 return ZeroInitialization(E);
10148 }
10149
10150 case Builtin::BImemcpy:
10151 case Builtin::BImemmove:
10152 case Builtin::BIwmemcpy:
10153 case Builtin::BIwmemmove:
10154 if (Info.getLangOpts().CPlusPlus11)
10155 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10156 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10157 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10158 else
10159 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10160 [[fallthrough]];
10161 case Builtin::BI__builtin_memcpy:
10162 case Builtin::BI__builtin_memmove:
10163 case Builtin::BI__builtin_wmemcpy:
10164 case Builtin::BI__builtin_wmemmove: {
10165 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10166 BuiltinOp == Builtin::BIwmemmove ||
10167 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10168 BuiltinOp == Builtin::BI__builtin_wmemmove;
10169 bool Move = BuiltinOp == Builtin::BImemmove ||
10170 BuiltinOp == Builtin::BIwmemmove ||
10171 BuiltinOp == Builtin::BI__builtin_memmove ||
10172 BuiltinOp == Builtin::BI__builtin_wmemmove;
10173
10174 // The result of mem* is the first argument.
10175 if (!Visit(E->getArg(0)))
10176 return false;
10177 LValue Dest = Result;
10178
10179 LValue Src;
10180 if (!EvaluatePointer(E->getArg(1), Src, Info))
10181 return false;
10182
10183 APSInt N;
10184 if (!EvaluateInteger(E->getArg(2), N, Info))
10185 return false;
10186 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10187
10188 // If the size is zero, we treat this as always being a valid no-op.
10189 // (Even if one of the src and dest pointers is null.)
10190 if (!N)
10191 return true;
10192
10193 // Otherwise, if either of the operands is null, we can't proceed. Don't
10194 // try to determine the type of the copied objects, because there aren't
10195 // any.
10196 if (!Src.Base || !Dest.Base) {
10197 APValue Val;
10198 (!Src.Base ? Src : Dest).moveInto(Val);
10199 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10200 << Move << WChar << !!Src.Base
10201 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10202 return false;
10203 }
10204 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10205 return false;
10206
10207 // We require that Src and Dest are both pointers to arrays of
10208 // trivially-copyable type. (For the wide version, the designator will be
10209 // invalid if the designated object is not a wchar_t.)
10210 QualType T = Dest.Designator.getType(Info.Ctx);
10211 QualType SrcT = Src.Designator.getType(Info.Ctx);
10212 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10213 // FIXME: Consider using our bit_cast implementation to support this.
10214 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10215 return false;
10216 }
10217 if (T->isIncompleteType()) {
10218 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10219 return false;
10220 }
10221 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10222 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10223 return false;
10224 }
10225
10226 // Figure out how many T's we're copying.
10227 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10228 if (TSize == 0)
10229 return false;
10230 if (!WChar) {
10231 uint64_t Remainder;
10232 llvm::APInt OrigN = N;
10233 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10234 if (Remainder) {
10235 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10236 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10237 << (unsigned)TSize;
10238 return false;
10239 }
10240 }
10241
10242 // Check that the copying will remain within the arrays, just so that we
10243 // can give a more meaningful diagnostic. This implicitly also checks that
10244 // N fits into 64 bits.
10245 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10246 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10247 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10248 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10249 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10250 << toString(N, 10, /*Signed*/false);
10251 return false;
10252 }
10253 uint64_t NElems = N.getZExtValue();
10254 uint64_t NBytes = NElems * TSize;
10255
10256 // Check for overlap.
10257 int Direction = 1;
10258 if (HasSameBase(Src, Dest)) {
10259 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10260 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10261 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10262 // Dest is inside the source region.
10263 if (!Move) {
10264 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10265 return false;
10266 }
10267 // For memmove and friends, copy backwards.
10268 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10269 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10270 return false;
10271 Direction = -1;
10272 } else if (!Move && SrcOffset >= DestOffset &&
10273 SrcOffset - DestOffset < NBytes) {
10274 // Src is inside the destination region for memcpy: invalid.
10275 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10276 return false;
10277 }
10278 }
10279
10280 while (true) {
10281 APValue Val;
10282 // FIXME: Set WantObjectRepresentation to true if we're copying a
10283 // char-like type?
10284 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10285 !handleAssignment(Info, E, Dest, T, Val))
10286 return false;
10287 // Do not iterate past the last element; if we're copying backwards, that
10288 // might take us off the start of the array.
10289 if (--NElems == 0)
10290 return true;
10291 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10292 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10293 return false;
10294 }
10295 }
10296
10297 default:
10298 return false;
10299 }
10300 }
10301
10302 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10303 APValue &Result, const InitListExpr *ILE,
10304 QualType AllocType);
10305 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10306 APValue &Result,
10307 const CXXConstructExpr *CCE,
10308 QualType AllocType);
10309
VisitCXXNewExpr(const CXXNewExpr * E)10310 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10311 if (!Info.getLangOpts().CPlusPlus20)
10312 Info.CCEDiag(E, diag::note_constexpr_new);
10313
10314 // We cannot speculatively evaluate a delete expression.
10315 if (Info.SpeculativeEvaluationDepth)
10316 return false;
10317
10318 FunctionDecl *OperatorNew = E->getOperatorNew();
10319 QualType AllocType = E->getAllocatedType();
10320 QualType TargetType = AllocType;
10321
10322 bool IsNothrow = false;
10323 bool IsPlacement = false;
10324
10325 // The only new-placement list we support (other than the reserved placement
10326 // form) is of the form (std::nothrow).
10327 //
10328 // FIXME: There is no restriction on this, but it's not clear that any
10329 // other form makes any sense. We get here for cases such as:
10330 //
10331 // new (std::align_val_t{N}) X(int)
10332 //
10333 // (which should presumably be valid only if N is a multiple of
10334 // alignof(int), and in any case can't be deallocated unless N is
10335 // alignof(X) and X has new-extended alignment).
10336 bool HasNothrowArg = E->getNumPlacementArgs() == 1 &&
10337 E->getPlacementArg(0)->getType()->isNothrowT();
10338
10339 if (OperatorNew->isReservedGlobalPlacementOperator()) {
10340 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10341 (Info.CurrentCall->CanEvalMSConstexpr &&
10342 OperatorNew->hasAttr<MSConstexprAttr>())) {
10343 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10344 return false;
10345 if (Result.Designator.Invalid)
10346 return false;
10347 TargetType = E->getPlacementArg(0)->getType();
10348 IsPlacement = true;
10349 } else {
10350 Info.FFDiag(E, diag::note_constexpr_new_placement)
10351 << /*C++26 feature*/ 1 << E->getSourceRange();
10352 return false;
10353 }
10354 } else if (E->getNumPlacementArgs() && !HasNothrowArg) {
10355 Info.FFDiag(E, diag::note_constexpr_new_placement)
10356 << /*Unsupported*/ 0 << E->getSourceRange();
10357 return false;
10358 } else if (!OperatorNew
10359 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10360 // [expr.const] only permits new-expressions that select a replaceable
10361 // global allocation function. Check this before evaluating a
10362 // (std::nothrow) placement argument.
10363 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10364 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10365 return false;
10366 } else if (HasNothrowArg) {
10367 LValue Nothrow;
10368 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10369 return false;
10370 IsNothrow = true;
10371 }
10372
10373 const Expr *Init = E->getInitializer();
10374 const InitListExpr *ResizedArrayILE = nullptr;
10375 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10376 bool ValueInit = false;
10377
10378 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10379 const Expr *Stripped = *ArraySize;
10380 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10381 Stripped = ICE->getSubExpr())
10382 if (ICE->getCastKind() != CK_NoOp &&
10383 ICE->getCastKind() != CK_IntegralCast)
10384 break;
10385
10386 llvm::APSInt ArrayBound;
10387 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10388 return false;
10389
10390 // C++ [expr.new]p9:
10391 // The expression is erroneous if:
10392 // -- [...] its value before converting to size_t [or] applying the
10393 // second standard conversion sequence is less than zero
10394 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10395 if (IsNothrow)
10396 return ZeroInitialization(E);
10397
10398 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10399 << ArrayBound << (*ArraySize)->getSourceRange();
10400 return false;
10401 }
10402
10403 // -- its value is such that the size of the allocated object would
10404 // exceed the implementation-defined limit
10405 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10406 ConstantArrayType::getNumAddressingBits(
10407 Info.Ctx, AllocType, ArrayBound),
10408 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10409 if (IsNothrow)
10410 return ZeroInitialization(E);
10411 return false;
10412 }
10413
10414 // -- the new-initializer is a braced-init-list and the number of
10415 // array elements for which initializers are provided [...]
10416 // exceeds the number of elements to initialize
10417 if (!Init) {
10418 // No initialization is performed.
10419 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10420 isa<ImplicitValueInitExpr>(Init)) {
10421 ValueInit = true;
10422 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10423 ResizedArrayCCE = CCE;
10424 } else {
10425 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10426 assert(CAT && "unexpected type for array initializer");
10427
10428 unsigned Bits =
10429 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10430 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10431 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10432 if (InitBound.ugt(AllocBound)) {
10433 if (IsNothrow)
10434 return ZeroInitialization(E);
10435
10436 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10437 << toString(AllocBound, 10, /*Signed=*/false)
10438 << toString(InitBound, 10, /*Signed=*/false)
10439 << (*ArraySize)->getSourceRange();
10440 return false;
10441 }
10442
10443 // If the sizes differ, we must have an initializer list, and we need
10444 // special handling for this case when we initialize.
10445 if (InitBound != AllocBound)
10446 ResizedArrayILE = cast<InitListExpr>(Init);
10447 }
10448
10449 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10450 ArraySizeModifier::Normal, 0);
10451 } else {
10452 assert(!AllocType->isArrayType() &&
10453 "array allocation with non-array new");
10454 }
10455
10456 APValue *Val;
10457 if (IsPlacement) {
10458 AccessKinds AK = AK_Construct;
10459 struct FindObjectHandler {
10460 EvalInfo &Info;
10461 const Expr *E;
10462 QualType AllocType;
10463 const AccessKinds AccessKind;
10464 APValue *Value;
10465
10466 typedef bool result_type;
10467 bool failed() { return false; }
10468 bool checkConst(QualType QT) {
10469 if (QT.isConstQualified()) {
10470 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10471 return false;
10472 }
10473 return true;
10474 }
10475 bool found(APValue &Subobj, QualType SubobjType) {
10476 if (!checkConst(SubobjType))
10477 return false;
10478 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10479 // old name of the object to be used to name the new object.
10480 unsigned SubobjectSize = 1;
10481 unsigned AllocSize = 1;
10482 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10483 AllocSize = CAT->getZExtSize();
10484 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10485 SubobjectSize = CAT->getZExtSize();
10486 if (SubobjectSize < AllocSize ||
10487 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10488 Info.Ctx.getBaseElementType(AllocType))) {
10489 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10490 << SubobjType << AllocType;
10491 return false;
10492 }
10493 Value = &Subobj;
10494 return true;
10495 }
10496 bool found(APSInt &Value, QualType SubobjType) {
10497 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10498 return false;
10499 }
10500 bool found(APFloat &Value, QualType SubobjType) {
10501 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10502 return false;
10503 }
10504 } Handler = {Info, E, AllocType, AK, nullptr};
10505
10506 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10507 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10508 return false;
10509
10510 Val = Handler.Value;
10511
10512 // [basic.life]p1:
10513 // The lifetime of an object o of type T ends when [...] the storage
10514 // which the object occupies is [...] reused by an object that is not
10515 // nested within o (6.6.2).
10516 *Val = APValue();
10517 } else {
10518 // Perform the allocation and obtain a pointer to the resulting object.
10519 Val = Info.createHeapAlloc(E, AllocType, Result);
10520 if (!Val)
10521 return false;
10522 }
10523
10524 if (ValueInit) {
10525 ImplicitValueInitExpr VIE(AllocType);
10526 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10527 return false;
10528 } else if (ResizedArrayILE) {
10529 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10530 AllocType))
10531 return false;
10532 } else if (ResizedArrayCCE) {
10533 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10534 AllocType))
10535 return false;
10536 } else if (Init) {
10537 if (!EvaluateInPlace(*Val, Info, Result, Init))
10538 return false;
10539 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10540 return false;
10541 }
10542
10543 // Array new returns a pointer to the first element, not a pointer to the
10544 // array.
10545 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10546 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10547
10548 return true;
10549 }
10550 //===----------------------------------------------------------------------===//
10551 // Member Pointer Evaluation
10552 //===----------------------------------------------------------------------===//
10553
10554 namespace {
10555 class MemberPointerExprEvaluator
10556 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10557 MemberPtr &Result;
10558
Success(const ValueDecl * D)10559 bool Success(const ValueDecl *D) {
10560 Result = MemberPtr(D);
10561 return true;
10562 }
10563 public:
10564
MemberPointerExprEvaluator(EvalInfo & Info,MemberPtr & Result)10565 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10566 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10567
Success(const APValue & V,const Expr * E)10568 bool Success(const APValue &V, const Expr *E) {
10569 Result.setFrom(V);
10570 return true;
10571 }
ZeroInitialization(const Expr * E)10572 bool ZeroInitialization(const Expr *E) {
10573 return Success((const ValueDecl*)nullptr);
10574 }
10575
10576 bool VisitCastExpr(const CastExpr *E);
10577 bool VisitUnaryAddrOf(const UnaryOperator *E);
10578 };
10579 } // end anonymous namespace
10580
EvaluateMemberPointer(const Expr * E,MemberPtr & Result,EvalInfo & Info)10581 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10582 EvalInfo &Info) {
10583 assert(!E->isValueDependent());
10584 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10585 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10586 }
10587
VisitCastExpr(const CastExpr * E)10588 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10589 switch (E->getCastKind()) {
10590 default:
10591 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10592
10593 case CK_NullToMemberPointer:
10594 VisitIgnoredValue(E->getSubExpr());
10595 return ZeroInitialization(E);
10596
10597 case CK_BaseToDerivedMemberPointer: {
10598 if (!Visit(E->getSubExpr()))
10599 return false;
10600 if (E->path_empty())
10601 return true;
10602 // Base-to-derived member pointer casts store the path in derived-to-base
10603 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10604 // the wrong end of the derived->base arc, so stagger the path by one class.
10605 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10606 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10607 PathI != PathE; ++PathI) {
10608 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10609 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10610 if (!Result.castToDerived(Derived))
10611 return Error(E);
10612 }
10613 if (!Result.castToDerived(E->getType()
10614 ->castAs<MemberPointerType>()
10615 ->getMostRecentCXXRecordDecl()))
10616 return Error(E);
10617 return true;
10618 }
10619
10620 case CK_DerivedToBaseMemberPointer:
10621 if (!Visit(E->getSubExpr()))
10622 return false;
10623 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10624 PathE = E->path_end(); PathI != PathE; ++PathI) {
10625 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10626 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10627 if (!Result.castToBase(Base))
10628 return Error(E);
10629 }
10630 return true;
10631 }
10632 }
10633
VisitUnaryAddrOf(const UnaryOperator * E)10634 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10635 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10636 // member can be formed.
10637 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10638 }
10639
10640 //===----------------------------------------------------------------------===//
10641 // Record Evaluation
10642 //===----------------------------------------------------------------------===//
10643
10644 namespace {
10645 class RecordExprEvaluator
10646 : public ExprEvaluatorBase<RecordExprEvaluator> {
10647 const LValue &This;
10648 APValue &Result;
10649 public:
10650
RecordExprEvaluator(EvalInfo & info,const LValue & This,APValue & Result)10651 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10652 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10653
Success(const APValue & V,const Expr * E)10654 bool Success(const APValue &V, const Expr *E) {
10655 Result = V;
10656 return true;
10657 }
ZeroInitialization(const Expr * E)10658 bool ZeroInitialization(const Expr *E) {
10659 return ZeroInitialization(E, E->getType());
10660 }
10661 bool ZeroInitialization(const Expr *E, QualType T);
10662
VisitCallExpr(const CallExpr * E)10663 bool VisitCallExpr(const CallExpr *E) {
10664 return handleCallExpr(E, Result, &This);
10665 }
10666 bool VisitCastExpr(const CastExpr *E);
10667 bool VisitInitListExpr(const InitListExpr *E);
VisitCXXConstructExpr(const CXXConstructExpr * E)10668 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10669 return VisitCXXConstructExpr(E, E->getType());
10670 }
10671 bool VisitLambdaExpr(const LambdaExpr *E);
10672 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10673 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10674 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10675 bool VisitBinCmp(const BinaryOperator *E);
10676 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10677 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10678 ArrayRef<Expr *> Args);
10679 };
10680 }
10681
10682 /// Perform zero-initialization on an object of non-union class type.
10683 /// C++11 [dcl.init]p5:
10684 /// To zero-initialize an object or reference of type T means:
10685 /// [...]
10686 /// -- if T is a (possibly cv-qualified) non-union class type,
10687 /// each non-static data member and each base-class subobject is
10688 /// zero-initialized
HandleClassZeroInitialization(EvalInfo & Info,const Expr * E,const RecordDecl * RD,const LValue & This,APValue & Result)10689 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10690 const RecordDecl *RD,
10691 const LValue &This, APValue &Result) {
10692 assert(!RD->isUnion() && "Expected non-union class type");
10693 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10694 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10695 std::distance(RD->field_begin(), RD->field_end()));
10696
10697 if (RD->isInvalidDecl()) return false;
10698 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10699
10700 if (CD) {
10701 unsigned Index = 0;
10702 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
10703 End = CD->bases_end(); I != End; ++I, ++Index) {
10704 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10705 LValue Subobject = This;
10706 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10707 return false;
10708 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10709 Result.getStructBase(Index)))
10710 return false;
10711 }
10712 }
10713
10714 for (const auto *I : RD->fields()) {
10715 // -- if T is a reference type, no initialization is performed.
10716 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10717 continue;
10718
10719 LValue Subobject = This;
10720 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10721 return false;
10722
10723 ImplicitValueInitExpr VIE(I->getType());
10724 if (!EvaluateInPlace(
10725 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10726 return false;
10727 }
10728
10729 return true;
10730 }
10731
ZeroInitialization(const Expr * E,QualType T)10732 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10733 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10734 if (RD->isInvalidDecl()) return false;
10735 if (RD->isUnion()) {
10736 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10737 // object's first non-static named data member is zero-initialized
10738 RecordDecl::field_iterator I = RD->field_begin();
10739 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10740 ++I;
10741 if (I == RD->field_end()) {
10742 Result = APValue((const FieldDecl*)nullptr);
10743 return true;
10744 }
10745
10746 LValue Subobject = This;
10747 if (!HandleLValueMember(Info, E, Subobject, *I))
10748 return false;
10749 Result = APValue(*I);
10750 ImplicitValueInitExpr VIE(I->getType());
10751 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10752 }
10753
10754 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10755 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10756 return false;
10757 }
10758
10759 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10760 }
10761
VisitCastExpr(const CastExpr * E)10762 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10763 switch (E->getCastKind()) {
10764 default:
10765 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10766
10767 case CK_ConstructorConversion:
10768 return Visit(E->getSubExpr());
10769
10770 case CK_DerivedToBase:
10771 case CK_UncheckedDerivedToBase: {
10772 APValue DerivedObject;
10773 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10774 return false;
10775 if (!DerivedObject.isStruct())
10776 return Error(E->getSubExpr());
10777
10778 // Derived-to-base rvalue conversion: just slice off the derived part.
10779 APValue *Value = &DerivedObject;
10780 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10781 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10782 PathE = E->path_end(); PathI != PathE; ++PathI) {
10783 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10784 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10785 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10786 RD = Base;
10787 }
10788 Result = *Value;
10789 return true;
10790 }
10791 }
10792 }
10793
VisitInitListExpr(const InitListExpr * E)10794 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10795 if (E->isTransparent())
10796 return Visit(E->getInit(0));
10797 return VisitCXXParenListOrInitListExpr(E, E->inits());
10798 }
10799
VisitCXXParenListOrInitListExpr(const Expr * ExprToVisit,ArrayRef<Expr * > Args)10800 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10801 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10802 const RecordDecl *RD =
10803 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10804 if (RD->isInvalidDecl()) return false;
10805 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10806 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10807
10808 EvalInfo::EvaluatingConstructorRAII EvalObj(
10809 Info,
10810 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10811 CXXRD && CXXRD->getNumBases());
10812
10813 if (RD->isUnion()) {
10814 const FieldDecl *Field;
10815 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10816 Field = ILE->getInitializedFieldInUnion();
10817 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10818 Field = PLIE->getInitializedFieldInUnion();
10819 } else {
10820 llvm_unreachable(
10821 "Expression is neither an init list nor a C++ paren list");
10822 }
10823
10824 Result = APValue(Field);
10825 if (!Field)
10826 return true;
10827
10828 // If the initializer list for a union does not contain any elements, the
10829 // first element of the union is value-initialized.
10830 // FIXME: The element should be initialized from an initializer list.
10831 // Is this difference ever observable for initializer lists which
10832 // we don't build?
10833 ImplicitValueInitExpr VIE(Field->getType());
10834 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10835
10836 LValue Subobject = This;
10837 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10838 return false;
10839
10840 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10841 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10842 isa<CXXDefaultInitExpr>(InitExpr));
10843
10844 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10845 if (Field->isBitField())
10846 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10847 Field);
10848 return true;
10849 }
10850
10851 return false;
10852 }
10853
10854 if (!Result.hasValue())
10855 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10856 std::distance(RD->field_begin(), RD->field_end()));
10857 unsigned ElementNo = 0;
10858 bool Success = true;
10859
10860 // Initialize base classes.
10861 if (CXXRD && CXXRD->getNumBases()) {
10862 for (const auto &Base : CXXRD->bases()) {
10863 assert(ElementNo < Args.size() && "missing init for base class");
10864 const Expr *Init = Args[ElementNo];
10865
10866 LValue Subobject = This;
10867 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10868 return false;
10869
10870 APValue &FieldVal = Result.getStructBase(ElementNo);
10871 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10872 if (!Info.noteFailure())
10873 return false;
10874 Success = false;
10875 }
10876 ++ElementNo;
10877 }
10878
10879 EvalObj.finishedConstructingBases();
10880 }
10881
10882 // Initialize members.
10883 for (const auto *Field : RD->fields()) {
10884 // Anonymous bit-fields are not considered members of the class for
10885 // purposes of aggregate initialization.
10886 if (Field->isUnnamedBitField())
10887 continue;
10888
10889 LValue Subobject = This;
10890
10891 bool HaveInit = ElementNo < Args.size();
10892
10893 // FIXME: Diagnostics here should point to the end of the initializer
10894 // list, not the start.
10895 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10896 Subobject, Field, &Layout))
10897 return false;
10898
10899 // Perform an implicit value-initialization for members beyond the end of
10900 // the initializer list.
10901 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10902 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10903
10904 if (Field->getType()->isIncompleteArrayType()) {
10905 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10906 if (!CAT->isZeroSize()) {
10907 // Bail out for now. This might sort of "work", but the rest of the
10908 // code isn't really prepared to handle it.
10909 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10910 return false;
10911 }
10912 }
10913 }
10914
10915 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10916 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10917 isa<CXXDefaultInitExpr>(Init));
10918
10919 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10920 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10921 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10922 FieldVal, Field))) {
10923 if (!Info.noteFailure())
10924 return false;
10925 Success = false;
10926 }
10927 }
10928
10929 EvalObj.finishedConstructingFields();
10930
10931 return Success;
10932 }
10933
VisitCXXConstructExpr(const CXXConstructExpr * E,QualType T)10934 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10935 QualType T) {
10936 // Note that E's type is not necessarily the type of our class here; we might
10937 // be initializing an array element instead.
10938 const CXXConstructorDecl *FD = E->getConstructor();
10939 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10940
10941 bool ZeroInit = E->requiresZeroInitialization();
10942 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10943 if (ZeroInit)
10944 return ZeroInitialization(E, T);
10945
10946 return handleDefaultInitValue(T, Result);
10947 }
10948
10949 const FunctionDecl *Definition = nullptr;
10950 auto Body = FD->getBody(Definition);
10951
10952 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10953 return false;
10954
10955 // Avoid materializing a temporary for an elidable copy/move constructor.
10956 if (E->isElidable() && !ZeroInit) {
10957 // FIXME: This only handles the simplest case, where the source object
10958 // is passed directly as the first argument to the constructor.
10959 // This should also handle stepping though implicit casts and
10960 // and conversion sequences which involve two steps, with a
10961 // conversion operator followed by a converting constructor.
10962 const Expr *SrcObj = E->getArg(0);
10963 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10964 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10965 if (const MaterializeTemporaryExpr *ME =
10966 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10967 return Visit(ME->getSubExpr());
10968 }
10969
10970 if (ZeroInit && !ZeroInitialization(E, T))
10971 return false;
10972
10973 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
10974 return HandleConstructorCall(E, This, Args,
10975 cast<CXXConstructorDecl>(Definition), Info,
10976 Result);
10977 }
10978
VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr * E)10979 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10980 const CXXInheritedCtorInitExpr *E) {
10981 if (!Info.CurrentCall) {
10982 assert(Info.checkingPotentialConstantExpression());
10983 return false;
10984 }
10985
10986 const CXXConstructorDecl *FD = E->getConstructor();
10987 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10988 return false;
10989
10990 const FunctionDecl *Definition = nullptr;
10991 auto Body = FD->getBody(Definition);
10992
10993 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10994 return false;
10995
10996 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10997 cast<CXXConstructorDecl>(Definition), Info,
10998 Result);
10999 }
11000
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)11001 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11002 const CXXStdInitializerListExpr *E) {
11003 const ConstantArrayType *ArrayType =
11004 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11005
11006 LValue Array;
11007 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11008 return false;
11009
11010 assert(ArrayType && "unexpected type for array initializer");
11011
11012 // Get a pointer to the first element of the array.
11013 Array.addArray(Info, E, ArrayType);
11014
11015 // FIXME: What if the initializer_list type has base classes, etc?
11016 Result = APValue(APValue::UninitStruct(), 0, 2);
11017 Array.moveInto(Result.getStructField(0));
11018
11019 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
11020 RecordDecl::field_iterator Field = Record->field_begin();
11021 assert(Field != Record->field_end() &&
11022 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11023 ArrayType->getElementType()) &&
11024 "Expected std::initializer_list first field to be const E *");
11025 ++Field;
11026 assert(Field != Record->field_end() &&
11027 "Expected std::initializer_list to have two fields");
11028
11029 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11030 // Length.
11031 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11032 } else {
11033 // End pointer.
11034 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11035 ArrayType->getElementType()) &&
11036 "Expected std::initializer_list second field to be const E *");
11037 if (!HandleLValueArrayAdjustment(Info, E, Array,
11038 ArrayType->getElementType(),
11039 ArrayType->getZExtSize()))
11040 return false;
11041 Array.moveInto(Result.getStructField(1));
11042 }
11043
11044 assert(++Field == Record->field_end() &&
11045 "Expected std::initializer_list to only have two fields");
11046
11047 return true;
11048 }
11049
VisitLambdaExpr(const LambdaExpr * E)11050 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11051 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11052 if (ClosureClass->isInvalidDecl())
11053 return false;
11054
11055 const size_t NumFields =
11056 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
11057
11058 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11059 E->capture_init_end()) &&
11060 "The number of lambda capture initializers should equal the number of "
11061 "fields within the closure type");
11062
11063 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11064 // Iterate through all the lambda's closure object's fields and initialize
11065 // them.
11066 auto *CaptureInitIt = E->capture_init_begin();
11067 bool Success = true;
11068 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11069 for (const auto *Field : ClosureClass->fields()) {
11070 assert(CaptureInitIt != E->capture_init_end());
11071 // Get the initializer for this field
11072 Expr *const CurFieldInit = *CaptureInitIt++;
11073
11074 // If there is no initializer, either this is a VLA or an error has
11075 // occurred.
11076 if (!CurFieldInit || CurFieldInit->containsErrors())
11077 return Error(E);
11078
11079 LValue Subobject = This;
11080
11081 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11082 return false;
11083
11084 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11085 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11086 if (!Info.keepEvaluatingAfterFailure())
11087 return false;
11088 Success = false;
11089 }
11090 }
11091 return Success;
11092 }
11093
EvaluateRecord(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)11094 static bool EvaluateRecord(const Expr *E, const LValue &This,
11095 APValue &Result, EvalInfo &Info) {
11096 assert(!E->isValueDependent());
11097 assert(E->isPRValue() && E->getType()->isRecordType() &&
11098 "can't evaluate expression as a record rvalue");
11099 return RecordExprEvaluator(Info, This, Result).Visit(E);
11100 }
11101
11102 //===----------------------------------------------------------------------===//
11103 // Temporary Evaluation
11104 //
11105 // Temporaries are represented in the AST as rvalues, but generally behave like
11106 // lvalues. The full-object of which the temporary is a subobject is implicitly
11107 // materialized so that a reference can bind to it.
11108 //===----------------------------------------------------------------------===//
11109 namespace {
11110 class TemporaryExprEvaluator
11111 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11112 public:
TemporaryExprEvaluator(EvalInfo & Info,LValue & Result)11113 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11114 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11115
11116 /// Visit an expression which constructs the value of this temporary.
VisitConstructExpr(const Expr * E)11117 bool VisitConstructExpr(const Expr *E) {
11118 APValue &Value = Info.CurrentCall->createTemporary(
11119 E, E->getType(), ScopeKind::FullExpression, Result);
11120 return EvaluateInPlace(Value, Info, Result, E);
11121 }
11122
VisitCastExpr(const CastExpr * E)11123 bool VisitCastExpr(const CastExpr *E) {
11124 switch (E->getCastKind()) {
11125 default:
11126 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11127
11128 case CK_ConstructorConversion:
11129 return VisitConstructExpr(E->getSubExpr());
11130 }
11131 }
VisitInitListExpr(const InitListExpr * E)11132 bool VisitInitListExpr(const InitListExpr *E) {
11133 return VisitConstructExpr(E);
11134 }
VisitCXXConstructExpr(const CXXConstructExpr * E)11135 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11136 return VisitConstructExpr(E);
11137 }
VisitCallExpr(const CallExpr * E)11138 bool VisitCallExpr(const CallExpr *E) {
11139 return VisitConstructExpr(E);
11140 }
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)11141 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11142 return VisitConstructExpr(E);
11143 }
VisitLambdaExpr(const LambdaExpr * E)11144 bool VisitLambdaExpr(const LambdaExpr *E) {
11145 return VisitConstructExpr(E);
11146 }
11147 };
11148 } // end anonymous namespace
11149
11150 /// Evaluate an expression of record type as a temporary.
EvaluateTemporary(const Expr * E,LValue & Result,EvalInfo & Info)11151 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11152 assert(!E->isValueDependent());
11153 assert(E->isPRValue() && E->getType()->isRecordType());
11154 return TemporaryExprEvaluator(Info, Result).Visit(E);
11155 }
11156
11157 //===----------------------------------------------------------------------===//
11158 // Vector Evaluation
11159 //===----------------------------------------------------------------------===//
11160
11161 namespace {
11162 class VectorExprEvaluator
11163 : public ExprEvaluatorBase<VectorExprEvaluator> {
11164 APValue &Result;
11165 public:
11166
VectorExprEvaluator(EvalInfo & info,APValue & Result)11167 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11168 : ExprEvaluatorBaseTy(info), Result(Result) {}
11169
Success(ArrayRef<APValue> V,const Expr * E)11170 bool Success(ArrayRef<APValue> V, const Expr *E) {
11171 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11172 // FIXME: remove this APValue copy.
11173 Result = APValue(V.data(), V.size());
11174 return true;
11175 }
Success(const APValue & V,const Expr * E)11176 bool Success(const APValue &V, const Expr *E) {
11177 assert(V.isVector());
11178 Result = V;
11179 return true;
11180 }
11181 bool ZeroInitialization(const Expr *E);
11182
VisitUnaryReal(const UnaryOperator * E)11183 bool VisitUnaryReal(const UnaryOperator *E)
11184 { return Visit(E->getSubExpr()); }
11185 bool VisitCastExpr(const CastExpr* E);
11186 bool VisitInitListExpr(const InitListExpr *E);
11187 bool VisitUnaryImag(const UnaryOperator *E);
11188 bool VisitBinaryOperator(const BinaryOperator *E);
11189 bool VisitUnaryOperator(const UnaryOperator *E);
11190 bool VisitCallExpr(const CallExpr *E);
11191 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11192 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11193
11194 // FIXME: Missing: conditional operator (for GNU
11195 // conditional select), ExtVectorElementExpr
11196 };
11197 } // end anonymous namespace
11198
EvaluateVector(const Expr * E,APValue & Result,EvalInfo & Info)11199 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11200 assert(E->isPRValue() && E->getType()->isVectorType() &&
11201 "not a vector prvalue");
11202 return VectorExprEvaluator(Info, Result).Visit(E);
11203 }
11204
VisitCastExpr(const CastExpr * E)11205 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11206 const VectorType *VTy = E->getType()->castAs<VectorType>();
11207 unsigned NElts = VTy->getNumElements();
11208
11209 const Expr *SE = E->getSubExpr();
11210 QualType SETy = SE->getType();
11211
11212 switch (E->getCastKind()) {
11213 case CK_VectorSplat: {
11214 APValue Val = APValue();
11215 if (SETy->isIntegerType()) {
11216 APSInt IntResult;
11217 if (!EvaluateInteger(SE, IntResult, Info))
11218 return false;
11219 Val = APValue(std::move(IntResult));
11220 } else if (SETy->isRealFloatingType()) {
11221 APFloat FloatResult(0.0);
11222 if (!EvaluateFloat(SE, FloatResult, Info))
11223 return false;
11224 Val = APValue(std::move(FloatResult));
11225 } else {
11226 return Error(E);
11227 }
11228
11229 // Splat and create vector APValue.
11230 SmallVector<APValue, 4> Elts(NElts, Val);
11231 return Success(Elts, E);
11232 }
11233 case CK_BitCast: {
11234 APValue SVal;
11235 if (!Evaluate(SVal, Info, SE))
11236 return false;
11237
11238 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11239 // Give up if the input isn't an int, float, or vector. For example, we
11240 // reject "(v4i16)(intptr_t)&a".
11241 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11242 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11243 << Info.Ctx.getLangOpts().CPlusPlus;
11244 return false;
11245 }
11246
11247 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11248 return false;
11249
11250 return true;
11251 }
11252 case CK_HLSLVectorTruncation: {
11253 APValue Val;
11254 SmallVector<APValue, 4> Elements;
11255 if (!EvaluateVector(SE, Val, Info))
11256 return Error(E);
11257 for (unsigned I = 0; I < NElts; I++)
11258 Elements.push_back(Val.getVectorElt(I));
11259 return Success(Elements, E);
11260 }
11261 default:
11262 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11263 }
11264 }
11265
11266 bool
VisitInitListExpr(const InitListExpr * E)11267 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11268 const VectorType *VT = E->getType()->castAs<VectorType>();
11269 unsigned NumInits = E->getNumInits();
11270 unsigned NumElements = VT->getNumElements();
11271
11272 QualType EltTy = VT->getElementType();
11273 SmallVector<APValue, 4> Elements;
11274
11275 // MFloat8 type doesn't have constants and thus constant folding
11276 // is impossible.
11277 if (EltTy->isMFloat8Type())
11278 return false;
11279
11280 // The number of initializers can be less than the number of
11281 // vector elements. For OpenCL, this can be due to nested vector
11282 // initialization. For GCC compatibility, missing trailing elements
11283 // should be initialized with zeroes.
11284 unsigned CountInits = 0, CountElts = 0;
11285 while (CountElts < NumElements) {
11286 // Handle nested vector initialization.
11287 if (CountInits < NumInits
11288 && E->getInit(CountInits)->getType()->isVectorType()) {
11289 APValue v;
11290 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11291 return Error(E);
11292 unsigned vlen = v.getVectorLength();
11293 for (unsigned j = 0; j < vlen; j++)
11294 Elements.push_back(v.getVectorElt(j));
11295 CountElts += vlen;
11296 } else if (EltTy->isIntegerType()) {
11297 llvm::APSInt sInt(32);
11298 if (CountInits < NumInits) {
11299 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11300 return false;
11301 } else // trailing integer zero.
11302 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11303 Elements.push_back(APValue(sInt));
11304 CountElts++;
11305 } else {
11306 llvm::APFloat f(0.0);
11307 if (CountInits < NumInits) {
11308 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11309 return false;
11310 } else // trailing float zero.
11311 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11312 Elements.push_back(APValue(f));
11313 CountElts++;
11314 }
11315 CountInits++;
11316 }
11317 return Success(Elements, E);
11318 }
11319
11320 bool
ZeroInitialization(const Expr * E)11321 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11322 const auto *VT = E->getType()->castAs<VectorType>();
11323 QualType EltTy = VT->getElementType();
11324 APValue ZeroElement;
11325 if (EltTy->isIntegerType())
11326 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11327 else
11328 ZeroElement =
11329 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11330
11331 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11332 return Success(Elements, E);
11333 }
11334
VisitUnaryImag(const UnaryOperator * E)11335 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11336 VisitIgnoredValue(E->getSubExpr());
11337 return ZeroInitialization(E);
11338 }
11339
VisitBinaryOperator(const BinaryOperator * E)11340 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11341 BinaryOperatorKind Op = E->getOpcode();
11342 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11343 "Operation not supported on vector types");
11344
11345 if (Op == BO_Comma)
11346 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11347
11348 Expr *LHS = E->getLHS();
11349 Expr *RHS = E->getRHS();
11350
11351 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11352 "Must both be vector types");
11353 // Checking JUST the types are the same would be fine, except shifts don't
11354 // need to have their types be the same (since you always shift by an int).
11355 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11356 E->getType()->castAs<VectorType>()->getNumElements() &&
11357 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11358 E->getType()->castAs<VectorType>()->getNumElements() &&
11359 "All operands must be the same size.");
11360
11361 APValue LHSValue;
11362 APValue RHSValue;
11363 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11364 if (!LHSOK && !Info.noteFailure())
11365 return false;
11366 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11367 return false;
11368
11369 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11370 return false;
11371
11372 return Success(LHSValue, E);
11373 }
11374
handleVectorUnaryOperator(ASTContext & Ctx,QualType ResultTy,UnaryOperatorKind Op,APValue Elt)11375 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11376 QualType ResultTy,
11377 UnaryOperatorKind Op,
11378 APValue Elt) {
11379 switch (Op) {
11380 case UO_Plus:
11381 // Nothing to do here.
11382 return Elt;
11383 case UO_Minus:
11384 if (Elt.getKind() == APValue::Int) {
11385 Elt.getInt().negate();
11386 } else {
11387 assert(Elt.getKind() == APValue::Float &&
11388 "Vector can only be int or float type");
11389 Elt.getFloat().changeSign();
11390 }
11391 return Elt;
11392 case UO_Not:
11393 // This is only valid for integral types anyway, so we don't have to handle
11394 // float here.
11395 assert(Elt.getKind() == APValue::Int &&
11396 "Vector operator ~ can only be int");
11397 Elt.getInt().flipAllBits();
11398 return Elt;
11399 case UO_LNot: {
11400 if (Elt.getKind() == APValue::Int) {
11401 Elt.getInt() = !Elt.getInt();
11402 // operator ! on vectors returns -1 for 'truth', so negate it.
11403 Elt.getInt().negate();
11404 return Elt;
11405 }
11406 assert(Elt.getKind() == APValue::Float &&
11407 "Vector can only be int or float type");
11408 // Float types result in an int of the same size, but -1 for true, or 0 for
11409 // false.
11410 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11411 ResultTy->isUnsignedIntegerType()};
11412 if (Elt.getFloat().isZero())
11413 EltResult.setAllBits();
11414 else
11415 EltResult.clearAllBits();
11416
11417 return APValue{EltResult};
11418 }
11419 default:
11420 // FIXME: Implement the rest of the unary operators.
11421 return std::nullopt;
11422 }
11423 }
11424
VisitUnaryOperator(const UnaryOperator * E)11425 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11426 Expr *SubExpr = E->getSubExpr();
11427 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11428 // This result element type differs in the case of negating a floating point
11429 // vector, since the result type is the a vector of the equivilant sized
11430 // integer.
11431 const QualType ResultEltTy = VD->getElementType();
11432 UnaryOperatorKind Op = E->getOpcode();
11433
11434 APValue SubExprValue;
11435 if (!Evaluate(SubExprValue, Info, SubExpr))
11436 return false;
11437
11438 // FIXME: This vector evaluator someday needs to be changed to be LValue
11439 // aware/keep LValue information around, rather than dealing with just vector
11440 // types directly. Until then, we cannot handle cases where the operand to
11441 // these unary operators is an LValue. The only case I've been able to see
11442 // cause this is operator++ assigning to a member expression (only valid in
11443 // altivec compilations) in C mode, so this shouldn't limit us too much.
11444 if (SubExprValue.isLValue())
11445 return false;
11446
11447 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11448 "Vector length doesn't match type?");
11449
11450 SmallVector<APValue, 4> ResultElements;
11451 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11452 std::optional<APValue> Elt = handleVectorUnaryOperator(
11453 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11454 if (!Elt)
11455 return false;
11456 ResultElements.push_back(*Elt);
11457 }
11458 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11459 }
11460
handleVectorElementCast(EvalInfo & Info,const FPOptions FPO,const Expr * E,QualType SourceTy,QualType DestTy,APValue const & Original,APValue & Result)11461 static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11462 const Expr *E, QualType SourceTy,
11463 QualType DestTy, APValue const &Original,
11464 APValue &Result) {
11465 if (SourceTy->isIntegerType()) {
11466 if (DestTy->isRealFloatingType()) {
11467 Result = APValue(APFloat(0.0));
11468 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11469 DestTy, Result.getFloat());
11470 }
11471 if (DestTy->isIntegerType()) {
11472 Result = APValue(
11473 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11474 return true;
11475 }
11476 } else if (SourceTy->isRealFloatingType()) {
11477 if (DestTy->isRealFloatingType()) {
11478 Result = Original;
11479 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11480 Result.getFloat());
11481 }
11482 if (DestTy->isIntegerType()) {
11483 Result = APValue(APSInt());
11484 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11485 DestTy, Result.getInt());
11486 }
11487 }
11488
11489 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11490 << SourceTy << DestTy;
11491 return false;
11492 }
11493
VisitCallExpr(const CallExpr * E)11494 bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11495 if (!IsConstantEvaluatedBuiltinCall(E))
11496 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11497
11498 switch (E->getBuiltinCallee()) {
11499 default:
11500 return false;
11501 case Builtin::BI__builtin_elementwise_popcount:
11502 case Builtin::BI__builtin_elementwise_bitreverse: {
11503 APValue Source;
11504 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11505 return false;
11506
11507 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11508 unsigned SourceLen = Source.getVectorLength();
11509 SmallVector<APValue, 4> ResultElements;
11510 ResultElements.reserve(SourceLen);
11511
11512 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11513 APSInt Elt = Source.getVectorElt(EltNum).getInt();
11514 switch (E->getBuiltinCallee()) {
11515 case Builtin::BI__builtin_elementwise_popcount:
11516 ResultElements.push_back(APValue(
11517 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11518 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11519 break;
11520 case Builtin::BI__builtin_elementwise_bitreverse:
11521 ResultElements.push_back(
11522 APValue(APSInt(Elt.reverseBits(),
11523 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11524 break;
11525 }
11526 }
11527
11528 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11529 }
11530 case Builtin::BI__builtin_elementwise_add_sat:
11531 case Builtin::BI__builtin_elementwise_sub_sat: {
11532 APValue SourceLHS, SourceRHS;
11533 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11534 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11535 return false;
11536
11537 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11538 unsigned SourceLen = SourceLHS.getVectorLength();
11539 SmallVector<APValue, 4> ResultElements;
11540 ResultElements.reserve(SourceLen);
11541
11542 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11543 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11544 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11545 switch (E->getBuiltinCallee()) {
11546 case Builtin::BI__builtin_elementwise_add_sat:
11547 ResultElements.push_back(APValue(
11548 APSInt(LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS),
11549 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11550 break;
11551 case Builtin::BI__builtin_elementwise_sub_sat:
11552 ResultElements.push_back(APValue(
11553 APSInt(LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS),
11554 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11555 break;
11556 }
11557 }
11558
11559 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11560 }
11561 }
11562 }
11563
VisitConvertVectorExpr(const ConvertVectorExpr * E)11564 bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11565 APValue Source;
11566 QualType SourceVecType = E->getSrcExpr()->getType();
11567 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11568 return false;
11569
11570 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11571 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11572
11573 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11574
11575 auto SourceLen = Source.getVectorLength();
11576 SmallVector<APValue, 4> ResultElements;
11577 ResultElements.reserve(SourceLen);
11578 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11579 APValue Elt;
11580 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
11581 Source.getVectorElt(EltNum), Elt))
11582 return false;
11583 ResultElements.push_back(std::move(Elt));
11584 }
11585
11586 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11587 }
11588
handleVectorShuffle(EvalInfo & Info,const ShuffleVectorExpr * E,QualType ElemType,APValue const & VecVal1,APValue const & VecVal2,unsigned EltNum,APValue & Result)11589 static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
11590 QualType ElemType, APValue const &VecVal1,
11591 APValue const &VecVal2, unsigned EltNum,
11592 APValue &Result) {
11593 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
11594 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
11595
11596 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
11597 int64_t index = IndexVal.getExtValue();
11598 // The spec says that -1 should be treated as undef for optimizations,
11599 // but in constexpr we'd have to produce an APValue::Indeterminate,
11600 // which is prohibited from being a top-level constant value. Emit a
11601 // diagnostic instead.
11602 if (index == -1) {
11603 Info.FFDiag(
11604 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
11605 << EltNum;
11606 return false;
11607 }
11608
11609 if (index < 0 ||
11610 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
11611 llvm_unreachable("Out of bounds shuffle index");
11612
11613 if (index >= TotalElementsInInputVector1)
11614 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
11615 else
11616 Result = VecVal1.getVectorElt(index);
11617 return true;
11618 }
11619
VisitShuffleVectorExpr(const ShuffleVectorExpr * E)11620 bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
11621 APValue VecVal1;
11622 const Expr *Vec1 = E->getExpr(0);
11623 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
11624 return false;
11625 APValue VecVal2;
11626 const Expr *Vec2 = E->getExpr(1);
11627 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
11628 return false;
11629
11630 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11631 QualType DestElTy = DestVecTy->getElementType();
11632
11633 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11634
11635 SmallVector<APValue, 4> ResultElements;
11636 ResultElements.reserve(TotalElementsInOutputVector);
11637 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
11638 APValue Elt;
11639 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
11640 return false;
11641 ResultElements.push_back(std::move(Elt));
11642 }
11643
11644 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11645 }
11646
11647 //===----------------------------------------------------------------------===//
11648 // Array Evaluation
11649 //===----------------------------------------------------------------------===//
11650
11651 namespace {
11652 class ArrayExprEvaluator
11653 : public ExprEvaluatorBase<ArrayExprEvaluator> {
11654 const LValue &This;
11655 APValue &Result;
11656 public:
11657
ArrayExprEvaluator(EvalInfo & Info,const LValue & This,APValue & Result)11658 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
11659 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11660
Success(const APValue & V,const Expr * E)11661 bool Success(const APValue &V, const Expr *E) {
11662 assert(V.isArray() && "expected array");
11663 Result = V;
11664 return true;
11665 }
11666
ZeroInitialization(const Expr * E)11667 bool ZeroInitialization(const Expr *E) {
11668 const ConstantArrayType *CAT =
11669 Info.Ctx.getAsConstantArrayType(E->getType());
11670 if (!CAT) {
11671 if (E->getType()->isIncompleteArrayType()) {
11672 // We can be asked to zero-initialize a flexible array member; this
11673 // is represented as an ImplicitValueInitExpr of incomplete array
11674 // type. In this case, the array has zero elements.
11675 Result = APValue(APValue::UninitArray(), 0, 0);
11676 return true;
11677 }
11678 // FIXME: We could handle VLAs here.
11679 return Error(E);
11680 }
11681
11682 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11683 if (!Result.hasArrayFiller())
11684 return true;
11685
11686 // Zero-initialize all elements.
11687 LValue Subobject = This;
11688 Subobject.addArray(Info, E, CAT);
11689 ImplicitValueInitExpr VIE(CAT->getElementType());
11690 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
11691 }
11692
VisitCallExpr(const CallExpr * E)11693 bool VisitCallExpr(const CallExpr *E) {
11694 return handleCallExpr(E, Result, &This);
11695 }
11696 bool VisitInitListExpr(const InitListExpr *E,
11697 QualType AllocType = QualType());
11698 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
11699 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
11700 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
11701 const LValue &Subobject,
11702 APValue *Value, QualType Type);
VisitStringLiteral(const StringLiteral * E,QualType AllocType=QualType ())11703 bool VisitStringLiteral(const StringLiteral *E,
11704 QualType AllocType = QualType()) {
11705 expandStringLiteral(Info, E, Result, AllocType);
11706 return true;
11707 }
11708 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11709 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11710 ArrayRef<Expr *> Args,
11711 const Expr *ArrayFiller,
11712 QualType AllocType = QualType());
11713 };
11714 } // end anonymous namespace
11715
EvaluateArray(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)11716 static bool EvaluateArray(const Expr *E, const LValue &This,
11717 APValue &Result, EvalInfo &Info) {
11718 assert(!E->isValueDependent());
11719 assert(E->isPRValue() && E->getType()->isArrayType() &&
11720 "not an array prvalue");
11721 return ArrayExprEvaluator(Info, This, Result).Visit(E);
11722 }
11723
EvaluateArrayNewInitList(EvalInfo & Info,LValue & This,APValue & Result,const InitListExpr * ILE,QualType AllocType)11724 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11725 APValue &Result, const InitListExpr *ILE,
11726 QualType AllocType) {
11727 assert(!ILE->isValueDependent());
11728 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11729 "not an array prvalue");
11730 return ArrayExprEvaluator(Info, This, Result)
11731 .VisitInitListExpr(ILE, AllocType);
11732 }
11733
EvaluateArrayNewConstructExpr(EvalInfo & Info,LValue & This,APValue & Result,const CXXConstructExpr * CCE,QualType AllocType)11734 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11735 APValue &Result,
11736 const CXXConstructExpr *CCE,
11737 QualType AllocType) {
11738 assert(!CCE->isValueDependent());
11739 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11740 "not an array prvalue");
11741 return ArrayExprEvaluator(Info, This, Result)
11742 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
11743 }
11744
11745 // Return true iff the given array filler may depend on the element index.
MaybeElementDependentArrayFiller(const Expr * FillerExpr)11746 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11747 // For now, just allow non-class value-initialization and initialization
11748 // lists comprised of them.
11749 if (isa<ImplicitValueInitExpr>(FillerExpr))
11750 return false;
11751 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11752 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11753 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11754 return true;
11755 }
11756
11757 if (ILE->hasArrayFiller() &&
11758 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11759 return true;
11760
11761 return false;
11762 }
11763 return true;
11764 }
11765
VisitInitListExpr(const InitListExpr * E,QualType AllocType)11766 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11767 QualType AllocType) {
11768 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11769 AllocType.isNull() ? E->getType() : AllocType);
11770 if (!CAT)
11771 return Error(E);
11772
11773 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11774 // an appropriately-typed string literal enclosed in braces.
11775 if (E->isStringLiteralInit()) {
11776 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11777 // FIXME: Support ObjCEncodeExpr here once we support it in
11778 // ArrayExprEvaluator generally.
11779 if (!SL)
11780 return Error(E);
11781 return VisitStringLiteral(SL, AllocType);
11782 }
11783 // Any other transparent list init will need proper handling of the
11784 // AllocType; we can't just recurse to the inner initializer.
11785 assert(!E->isTransparent() &&
11786 "transparent array list initialization is not string literal init?");
11787
11788 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11789 AllocType);
11790 }
11791
VisitCXXParenListOrInitListExpr(const Expr * ExprToVisit,ArrayRef<Expr * > Args,const Expr * ArrayFiller,QualType AllocType)11792 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11793 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11794 QualType AllocType) {
11795 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11796 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11797
11798 bool Success = true;
11799
11800 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11801 "zero-initialized array shouldn't have any initialized elts");
11802 APValue Filler;
11803 if (Result.isArray() && Result.hasArrayFiller())
11804 Filler = Result.getArrayFiller();
11805
11806 unsigned NumEltsToInit = Args.size();
11807 unsigned NumElts = CAT->getZExtSize();
11808
11809 // If the initializer might depend on the array index, run it for each
11810 // array element.
11811 if (NumEltsToInit != NumElts &&
11812 MaybeElementDependentArrayFiller(ArrayFiller)) {
11813 NumEltsToInit = NumElts;
11814 } else {
11815 for (auto *Init : Args) {
11816 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
11817 NumEltsToInit += EmbedS->getDataElementCount() - 1;
11818 }
11819 if (NumEltsToInit > NumElts)
11820 NumEltsToInit = NumElts;
11821 }
11822
11823 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11824 << NumEltsToInit << ".\n");
11825
11826 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11827
11828 // If the array was previously zero-initialized, preserve the
11829 // zero-initialized values.
11830 if (Filler.hasValue()) {
11831 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11832 Result.getArrayInitializedElt(I) = Filler;
11833 if (Result.hasArrayFiller())
11834 Result.getArrayFiller() = Filler;
11835 }
11836
11837 LValue Subobject = This;
11838 Subobject.addArray(Info, ExprToVisit, CAT);
11839 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
11840 if (Init->isValueDependent())
11841 return EvaluateDependentExpr(Init, Info);
11842
11843 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
11844 Subobject, Init) ||
11845 !HandleLValueArrayAdjustment(Info, Init, Subobject,
11846 CAT->getElementType(), 1)) {
11847 if (!Info.noteFailure())
11848 return false;
11849 Success = false;
11850 }
11851 return true;
11852 };
11853 unsigned ArrayIndex = 0;
11854 QualType DestTy = CAT->getElementType();
11855 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
11856 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11857 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11858 if (ArrayIndex >= NumEltsToInit)
11859 break;
11860 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
11861 StringLiteral *SL = EmbedS->getDataStringLiteral();
11862 for (unsigned I = EmbedS->getStartingElementPos(),
11863 N = EmbedS->getDataElementCount();
11864 I != EmbedS->getStartingElementPos() + N; ++I) {
11865 Value = SL->getCodeUnit(I);
11866 if (DestTy->isIntegerType()) {
11867 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
11868 } else {
11869 assert(DestTy->isFloatingType() && "unexpected type");
11870 const FPOptions FPO =
11871 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11872 APFloat FValue(0.0);
11873 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
11874 DestTy, FValue))
11875 return false;
11876 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
11877 }
11878 ArrayIndex++;
11879 }
11880 } else {
11881 if (!Eval(Init, ArrayIndex))
11882 return false;
11883 ++ArrayIndex;
11884 }
11885 }
11886
11887 if (!Result.hasArrayFiller())
11888 return Success;
11889
11890 // If we get here, we have a trivial filler, which we can just evaluate
11891 // once and splat over the rest of the array elements.
11892 assert(ArrayFiller && "no array filler for incomplete init list");
11893 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11894 ArrayFiller) &&
11895 Success;
11896 }
11897
VisitArrayInitLoopExpr(const ArrayInitLoopExpr * E)11898 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11899 LValue CommonLV;
11900 if (E->getCommonExpr() &&
11901 !Evaluate(Info.CurrentCall->createTemporary(
11902 E->getCommonExpr(),
11903 getStorageType(Info.Ctx, E->getCommonExpr()),
11904 ScopeKind::FullExpression, CommonLV),
11905 Info, E->getCommonExpr()->getSourceExpr()))
11906 return false;
11907
11908 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11909
11910 uint64_t Elements = CAT->getZExtSize();
11911 Result = APValue(APValue::UninitArray(), Elements, Elements);
11912
11913 LValue Subobject = This;
11914 Subobject.addArray(Info, E, CAT);
11915
11916 bool Success = true;
11917 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11918 // C++ [class.temporary]/5
11919 // There are four contexts in which temporaries are destroyed at a different
11920 // point than the end of the full-expression. [...] The second context is
11921 // when a copy constructor is called to copy an element of an array while
11922 // the entire array is copied [...]. In either case, if the constructor has
11923 // one or more default arguments, the destruction of every temporary created
11924 // in a default argument is sequenced before the construction of the next
11925 // array element, if any.
11926 FullExpressionRAII Scope(Info);
11927
11928 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11929 Info, Subobject, E->getSubExpr()) ||
11930 !HandleLValueArrayAdjustment(Info, E, Subobject,
11931 CAT->getElementType(), 1)) {
11932 if (!Info.noteFailure())
11933 return false;
11934 Success = false;
11935 }
11936
11937 // Make sure we run the destructors too.
11938 Scope.destroy();
11939 }
11940
11941 return Success;
11942 }
11943
VisitCXXConstructExpr(const CXXConstructExpr * E)11944 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11945 return VisitCXXConstructExpr(E, This, &Result, E->getType());
11946 }
11947
VisitCXXConstructExpr(const CXXConstructExpr * E,const LValue & Subobject,APValue * Value,QualType Type)11948 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11949 const LValue &Subobject,
11950 APValue *Value,
11951 QualType Type) {
11952 bool HadZeroInit = Value->hasValue();
11953
11954 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11955 unsigned FinalSize = CAT->getZExtSize();
11956
11957 // Preserve the array filler if we had prior zero-initialization.
11958 APValue Filler =
11959 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11960 : APValue();
11961
11962 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11963 if (FinalSize == 0)
11964 return true;
11965
11966 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11967 Info, E->getExprLoc(), E->getConstructor(),
11968 E->requiresZeroInitialization());
11969 LValue ArrayElt = Subobject;
11970 ArrayElt.addArray(Info, E, CAT);
11971 // We do the whole initialization in two passes, first for just one element,
11972 // then for the whole array. It's possible we may find out we can't do const
11973 // init in the first pass, in which case we avoid allocating a potentially
11974 // large array. We don't do more passes because expanding array requires
11975 // copying the data, which is wasteful.
11976 for (const unsigned N : {1u, FinalSize}) {
11977 unsigned OldElts = Value->getArrayInitializedElts();
11978 if (OldElts == N)
11979 break;
11980
11981 // Expand the array to appropriate size.
11982 APValue NewValue(APValue::UninitArray(), N, FinalSize);
11983 for (unsigned I = 0; I < OldElts; ++I)
11984 NewValue.getArrayInitializedElt(I).swap(
11985 Value->getArrayInitializedElt(I));
11986 Value->swap(NewValue);
11987
11988 if (HadZeroInit)
11989 for (unsigned I = OldElts; I < N; ++I)
11990 Value->getArrayInitializedElt(I) = Filler;
11991
11992 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11993 // If we have a trivial constructor, only evaluate it once and copy
11994 // the result into all the array elements.
11995 APValue &FirstResult = Value->getArrayInitializedElt(0);
11996 for (unsigned I = OldElts; I < FinalSize; ++I)
11997 Value->getArrayInitializedElt(I) = FirstResult;
11998 } else {
11999 for (unsigned I = OldElts; I < N; ++I) {
12000 if (!VisitCXXConstructExpr(E, ArrayElt,
12001 &Value->getArrayInitializedElt(I),
12002 CAT->getElementType()) ||
12003 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
12004 CAT->getElementType(), 1))
12005 return false;
12006 // When checking for const initilization any diagnostic is considered
12007 // an error.
12008 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
12009 !Info.keepEvaluatingAfterFailure())
12010 return false;
12011 }
12012 }
12013 }
12014
12015 return true;
12016 }
12017
12018 if (!Type->isRecordType())
12019 return Error(E);
12020
12021 return RecordExprEvaluator(Info, Subobject, *Value)
12022 .VisitCXXConstructExpr(E, Type);
12023 }
12024
VisitCXXParenListInitExpr(const CXXParenListInitExpr * E)12025 bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
12026 const CXXParenListInitExpr *E) {
12027 assert(E->getType()->isConstantArrayType() &&
12028 "Expression result is not a constant array type");
12029
12030 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
12031 E->getArrayFiller());
12032 }
12033
12034 //===----------------------------------------------------------------------===//
12035 // Integer Evaluation
12036 //
12037 // As a GNU extension, we support casting pointers to sufficiently-wide integer
12038 // types and back in constant folding. Integer values are thus represented
12039 // either as an integer-valued APValue, or as an lvalue-valued APValue.
12040 //===----------------------------------------------------------------------===//
12041
12042 namespace {
12043 class IntExprEvaluator
12044 : public ExprEvaluatorBase<IntExprEvaluator> {
12045 APValue &Result;
12046 public:
IntExprEvaluator(EvalInfo & info,APValue & result)12047 IntExprEvaluator(EvalInfo &info, APValue &result)
12048 : ExprEvaluatorBaseTy(info), Result(result) {}
12049
Success(const llvm::APSInt & SI,const Expr * E,APValue & Result)12050 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
12051 assert(E->getType()->isIntegralOrEnumerationType() &&
12052 "Invalid evaluation result.");
12053 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
12054 "Invalid evaluation result.");
12055 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12056 "Invalid evaluation result.");
12057 Result = APValue(SI);
12058 return true;
12059 }
Success(const llvm::APSInt & SI,const Expr * E)12060 bool Success(const llvm::APSInt &SI, const Expr *E) {
12061 return Success(SI, E, Result);
12062 }
12063
Success(const llvm::APInt & I,const Expr * E,APValue & Result)12064 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
12065 assert(E->getType()->isIntegralOrEnumerationType() &&
12066 "Invalid evaluation result.");
12067 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12068 "Invalid evaluation result.");
12069 Result = APValue(APSInt(I));
12070 Result.getInt().setIsUnsigned(
12071 E->getType()->isUnsignedIntegerOrEnumerationType());
12072 return true;
12073 }
Success(const llvm::APInt & I,const Expr * E)12074 bool Success(const llvm::APInt &I, const Expr *E) {
12075 return Success(I, E, Result);
12076 }
12077
Success(uint64_t Value,const Expr * E,APValue & Result)12078 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12079 assert(E->getType()->isIntegralOrEnumerationType() &&
12080 "Invalid evaluation result.");
12081 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
12082 return true;
12083 }
Success(uint64_t Value,const Expr * E)12084 bool Success(uint64_t Value, const Expr *E) {
12085 return Success(Value, E, Result);
12086 }
12087
Success(CharUnits Size,const Expr * E)12088 bool Success(CharUnits Size, const Expr *E) {
12089 return Success(Size.getQuantity(), E);
12090 }
12091
Success(const APValue & V,const Expr * E)12092 bool Success(const APValue &V, const Expr *E) {
12093 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
12094 // pointer allow further evaluation of the value.
12095 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
12096 V.allowConstexprUnknown()) {
12097 Result = V;
12098 return true;
12099 }
12100 return Success(V.getInt(), E);
12101 }
12102
ZeroInitialization(const Expr * E)12103 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
12104
12105 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
12106 const CallExpr *);
12107
12108 //===--------------------------------------------------------------------===//
12109 // Visitor Methods
12110 //===--------------------------------------------------------------------===//
12111
VisitIntegerLiteral(const IntegerLiteral * E)12112 bool VisitIntegerLiteral(const IntegerLiteral *E) {
12113 return Success(E->getValue(), E);
12114 }
VisitCharacterLiteral(const CharacterLiteral * E)12115 bool VisitCharacterLiteral(const CharacterLiteral *E) {
12116 return Success(E->getValue(), E);
12117 }
12118
12119 bool CheckReferencedDecl(const Expr *E, const Decl *D);
VisitDeclRefExpr(const DeclRefExpr * E)12120 bool VisitDeclRefExpr(const DeclRefExpr *E) {
12121 if (CheckReferencedDecl(E, E->getDecl()))
12122 return true;
12123
12124 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
12125 }
VisitMemberExpr(const MemberExpr * E)12126 bool VisitMemberExpr(const MemberExpr *E) {
12127 if (CheckReferencedDecl(E, E->getMemberDecl())) {
12128 VisitIgnoredBaseExpression(E->getBase());
12129 return true;
12130 }
12131
12132 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
12133 }
12134
12135 bool VisitCallExpr(const CallExpr *E);
12136 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
12137 bool VisitBinaryOperator(const BinaryOperator *E);
12138 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
12139 bool VisitUnaryOperator(const UnaryOperator *E);
12140
12141 bool VisitCastExpr(const CastExpr* E);
12142 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
12143
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)12144 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
12145 return Success(E->getValue(), E);
12146 }
12147
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)12148 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
12149 return Success(E->getValue(), E);
12150 }
12151
VisitArrayInitIndexExpr(const ArrayInitIndexExpr * E)12152 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
12153 if (Info.ArrayInitIndex == uint64_t(-1)) {
12154 // We were asked to evaluate this subexpression independent of the
12155 // enclosing ArrayInitLoopExpr. We can't do that.
12156 Info.FFDiag(E);
12157 return false;
12158 }
12159 return Success(Info.ArrayInitIndex, E);
12160 }
12161
12162 // Note, GNU defines __null as an integer, not a pointer.
VisitGNUNullExpr(const GNUNullExpr * E)12163 bool VisitGNUNullExpr(const GNUNullExpr *E) {
12164 return ZeroInitialization(E);
12165 }
12166
VisitTypeTraitExpr(const TypeTraitExpr * E)12167 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
12168 if (E->isStoredAsBoolean())
12169 return Success(E->getBoolValue(), E);
12170 if (E->getAPValue().isAbsent())
12171 return false;
12172 assert(E->getAPValue().isInt() && "APValue type not supported");
12173 return Success(E->getAPValue().getInt(), E);
12174 }
12175
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)12176 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
12177 return Success(E->getValue(), E);
12178 }
12179
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)12180 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
12181 return Success(E->getValue(), E);
12182 }
12183
VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr * E)12184 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
12185 // This should not be evaluated during constant expr evaluation, as it
12186 // should always be in an unevaluated context (the args list of a 'gang' or
12187 // 'tile' clause).
12188 return Error(E);
12189 }
12190
12191 bool VisitUnaryReal(const UnaryOperator *E);
12192 bool VisitUnaryImag(const UnaryOperator *E);
12193
12194 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
12195 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
12196 bool VisitSourceLocExpr(const SourceLocExpr *E);
12197 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
12198 bool VisitRequiresExpr(const RequiresExpr *E);
12199 // FIXME: Missing: array subscript of vector, member of vector
12200 };
12201
12202 class FixedPointExprEvaluator
12203 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
12204 APValue &Result;
12205
12206 public:
FixedPointExprEvaluator(EvalInfo & info,APValue & result)12207 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
12208 : ExprEvaluatorBaseTy(info), Result(result) {}
12209
Success(const llvm::APInt & I,const Expr * E)12210 bool Success(const llvm::APInt &I, const Expr *E) {
12211 return Success(
12212 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12213 }
12214
Success(uint64_t Value,const Expr * E)12215 bool Success(uint64_t Value, const Expr *E) {
12216 return Success(
12217 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12218 }
12219
Success(const APValue & V,const Expr * E)12220 bool Success(const APValue &V, const Expr *E) {
12221 return Success(V.getFixedPoint(), E);
12222 }
12223
Success(const APFixedPoint & V,const Expr * E)12224 bool Success(const APFixedPoint &V, const Expr *E) {
12225 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
12226 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12227 "Invalid evaluation result.");
12228 Result = APValue(V);
12229 return true;
12230 }
12231
ZeroInitialization(const Expr * E)12232 bool ZeroInitialization(const Expr *E) {
12233 return Success(0, E);
12234 }
12235
12236 //===--------------------------------------------------------------------===//
12237 // Visitor Methods
12238 //===--------------------------------------------------------------------===//
12239
VisitFixedPointLiteral(const FixedPointLiteral * E)12240 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
12241 return Success(E->getValue(), E);
12242 }
12243
12244 bool VisitCastExpr(const CastExpr *E);
12245 bool VisitUnaryOperator(const UnaryOperator *E);
12246 bool VisitBinaryOperator(const BinaryOperator *E);
12247 };
12248 } // end anonymous namespace
12249
12250 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
12251 /// produce either the integer value or a pointer.
12252 ///
12253 /// GCC has a heinous extension which folds casts between pointer types and
12254 /// pointer-sized integral types. We support this by allowing the evaluation of
12255 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
12256 /// Some simple arithmetic on such values is supported (they are treated much
12257 /// like char*).
EvaluateIntegerOrLValue(const Expr * E,APValue & Result,EvalInfo & Info)12258 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
12259 EvalInfo &Info) {
12260 assert(!E->isValueDependent());
12261 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
12262 return IntExprEvaluator(Info, Result).Visit(E);
12263 }
12264
EvaluateInteger(const Expr * E,APSInt & Result,EvalInfo & Info)12265 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
12266 assert(!E->isValueDependent());
12267 APValue Val;
12268 if (!EvaluateIntegerOrLValue(E, Val, Info))
12269 return false;
12270 if (!Val.isInt()) {
12271 // FIXME: It would be better to produce the diagnostic for casting
12272 // a pointer to an integer.
12273 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12274 return false;
12275 }
12276 Result = Val.getInt();
12277 return true;
12278 }
12279
VisitSourceLocExpr(const SourceLocExpr * E)12280 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
12281 APValue Evaluated = E->EvaluateInContext(
12282 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
12283 return Success(Evaluated, E);
12284 }
12285
EvaluateFixedPoint(const Expr * E,APFixedPoint & Result,EvalInfo & Info)12286 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
12287 EvalInfo &Info) {
12288 assert(!E->isValueDependent());
12289 if (E->getType()->isFixedPointType()) {
12290 APValue Val;
12291 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
12292 return false;
12293 if (!Val.isFixedPoint())
12294 return false;
12295
12296 Result = Val.getFixedPoint();
12297 return true;
12298 }
12299 return false;
12300 }
12301
EvaluateFixedPointOrInteger(const Expr * E,APFixedPoint & Result,EvalInfo & Info)12302 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
12303 EvalInfo &Info) {
12304 assert(!E->isValueDependent());
12305 if (E->getType()->isIntegerType()) {
12306 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
12307 APSInt Val;
12308 if (!EvaluateInteger(E, Val, Info))
12309 return false;
12310 Result = APFixedPoint(Val, FXSema);
12311 return true;
12312 } else if (E->getType()->isFixedPointType()) {
12313 return EvaluateFixedPoint(E, Result, Info);
12314 }
12315 return false;
12316 }
12317
12318 /// Check whether the given declaration can be directly converted to an integral
12319 /// rvalue. If not, no diagnostic is produced; there are other things we can
12320 /// try.
CheckReferencedDecl(const Expr * E,const Decl * D)12321 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
12322 // Enums are integer constant exprs.
12323 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
12324 // Check for signedness/width mismatches between E type and ECD value.
12325 bool SameSign = (ECD->getInitVal().isSigned()
12326 == E->getType()->isSignedIntegerOrEnumerationType());
12327 bool SameWidth = (ECD->getInitVal().getBitWidth()
12328 == Info.Ctx.getIntWidth(E->getType()));
12329 if (SameSign && SameWidth)
12330 return Success(ECD->getInitVal(), E);
12331 else {
12332 // Get rid of mismatch (otherwise Success assertions will fail)
12333 // by computing a new value matching the type of E.
12334 llvm::APSInt Val = ECD->getInitVal();
12335 if (!SameSign)
12336 Val.setIsSigned(!ECD->getInitVal().isSigned());
12337 if (!SameWidth)
12338 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
12339 return Success(Val, E);
12340 }
12341 }
12342 return false;
12343 }
12344
12345 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12346 /// as GCC.
EvaluateBuiltinClassifyType(QualType T,const LangOptions & LangOpts)12347 GCCTypeClass EvaluateBuiltinClassifyType(QualType T,
12348 const LangOptions &LangOpts) {
12349 assert(!T->isDependentType() && "unexpected dependent type");
12350
12351 QualType CanTy = T.getCanonicalType();
12352
12353 switch (CanTy->getTypeClass()) {
12354 #define TYPE(ID, BASE)
12355 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
12356 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
12357 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
12358 #include "clang/AST/TypeNodes.inc"
12359 case Type::Auto:
12360 case Type::DeducedTemplateSpecialization:
12361 llvm_unreachable("unexpected non-canonical or dependent type");
12362
12363 case Type::Builtin:
12364 switch (cast<BuiltinType>(CanTy)->getKind()) {
12365 #define BUILTIN_TYPE(ID, SINGLETON_ID)
12366 #define SIGNED_TYPE(ID, SINGLETON_ID) \
12367 case BuiltinType::ID: return GCCTypeClass::Integer;
12368 #define FLOATING_TYPE(ID, SINGLETON_ID) \
12369 case BuiltinType::ID: return GCCTypeClass::RealFloat;
12370 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
12371 case BuiltinType::ID: break;
12372 #include "clang/AST/BuiltinTypes.def"
12373 case BuiltinType::Void:
12374 return GCCTypeClass::Void;
12375
12376 case BuiltinType::Bool:
12377 return GCCTypeClass::Bool;
12378
12379 case BuiltinType::Char_U:
12380 case BuiltinType::UChar:
12381 case BuiltinType::WChar_U:
12382 case BuiltinType::Char8:
12383 case BuiltinType::Char16:
12384 case BuiltinType::Char32:
12385 case BuiltinType::UShort:
12386 case BuiltinType::UInt:
12387 case BuiltinType::ULong:
12388 case BuiltinType::ULongLong:
12389 case BuiltinType::UInt128:
12390 return GCCTypeClass::Integer;
12391
12392 case BuiltinType::UShortAccum:
12393 case BuiltinType::UAccum:
12394 case BuiltinType::ULongAccum:
12395 case BuiltinType::UShortFract:
12396 case BuiltinType::UFract:
12397 case BuiltinType::ULongFract:
12398 case BuiltinType::SatUShortAccum:
12399 case BuiltinType::SatUAccum:
12400 case BuiltinType::SatULongAccum:
12401 case BuiltinType::SatUShortFract:
12402 case BuiltinType::SatUFract:
12403 case BuiltinType::SatULongFract:
12404 return GCCTypeClass::None;
12405
12406 case BuiltinType::NullPtr:
12407
12408 case BuiltinType::ObjCId:
12409 case BuiltinType::ObjCClass:
12410 case BuiltinType::ObjCSel:
12411 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
12412 case BuiltinType::Id:
12413 #include "clang/Basic/OpenCLImageTypes.def"
12414 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
12415 case BuiltinType::Id:
12416 #include "clang/Basic/OpenCLExtensionTypes.def"
12417 case BuiltinType::OCLSampler:
12418 case BuiltinType::OCLEvent:
12419 case BuiltinType::OCLClkEvent:
12420 case BuiltinType::OCLQueue:
12421 case BuiltinType::OCLReserveID:
12422 #define SVE_TYPE(Name, Id, SingletonId) \
12423 case BuiltinType::Id:
12424 #include "clang/Basic/AArch64ACLETypes.def"
12425 #define PPC_VECTOR_TYPE(Name, Id, Size) \
12426 case BuiltinType::Id:
12427 #include "clang/Basic/PPCTypes.def"
12428 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12429 #include "clang/Basic/RISCVVTypes.def"
12430 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12431 #include "clang/Basic/WebAssemblyReferenceTypes.def"
12432 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
12433 #include "clang/Basic/AMDGPUTypes.def"
12434 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12435 #include "clang/Basic/HLSLIntangibleTypes.def"
12436 return GCCTypeClass::None;
12437
12438 case BuiltinType::Dependent:
12439 llvm_unreachable("unexpected dependent type");
12440 };
12441 llvm_unreachable("unexpected placeholder type");
12442
12443 case Type::Enum:
12444 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
12445
12446 case Type::Pointer:
12447 case Type::ConstantArray:
12448 case Type::VariableArray:
12449 case Type::IncompleteArray:
12450 case Type::FunctionNoProto:
12451 case Type::FunctionProto:
12452 case Type::ArrayParameter:
12453 return GCCTypeClass::Pointer;
12454
12455 case Type::MemberPointer:
12456 return CanTy->isMemberDataPointerType()
12457 ? GCCTypeClass::PointerToDataMember
12458 : GCCTypeClass::PointerToMemberFunction;
12459
12460 case Type::Complex:
12461 return GCCTypeClass::Complex;
12462
12463 case Type::Record:
12464 return CanTy->isUnionType() ? GCCTypeClass::Union
12465 : GCCTypeClass::ClassOrStruct;
12466
12467 case Type::Atomic:
12468 // GCC classifies _Atomic T the same as T.
12469 return EvaluateBuiltinClassifyType(
12470 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
12471
12472 case Type::Vector:
12473 case Type::ExtVector:
12474 return GCCTypeClass::Vector;
12475
12476 case Type::BlockPointer:
12477 case Type::ConstantMatrix:
12478 case Type::ObjCObject:
12479 case Type::ObjCInterface:
12480 case Type::ObjCObjectPointer:
12481 case Type::Pipe:
12482 case Type::HLSLAttributedResource:
12483 case Type::HLSLInlineSpirv:
12484 // Classify all other types that don't fit into the regular
12485 // classification the same way.
12486 return GCCTypeClass::None;
12487
12488 case Type::BitInt:
12489 return GCCTypeClass::BitInt;
12490
12491 case Type::LValueReference:
12492 case Type::RValueReference:
12493 llvm_unreachable("invalid type for expression");
12494 }
12495
12496 llvm_unreachable("unexpected type class");
12497 }
12498
12499 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12500 /// as GCC.
12501 static GCCTypeClass
EvaluateBuiltinClassifyType(const CallExpr * E,const LangOptions & LangOpts)12502 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
12503 // If no argument was supplied, default to None. This isn't
12504 // ideal, however it is what gcc does.
12505 if (E->getNumArgs() == 0)
12506 return GCCTypeClass::None;
12507
12508 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
12509 // being an ICE, but still folds it to a constant using the type of the first
12510 // argument.
12511 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
12512 }
12513
12514 /// EvaluateBuiltinConstantPForLValue - Determine the result of
12515 /// __builtin_constant_p when applied to the given pointer.
12516 ///
12517 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
12518 /// or it points to the first character of a string literal.
EvaluateBuiltinConstantPForLValue(const APValue & LV)12519 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
12520 APValue::LValueBase Base = LV.getLValueBase();
12521 if (Base.isNull()) {
12522 // A null base is acceptable.
12523 return true;
12524 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
12525 if (!isa<StringLiteral>(E))
12526 return false;
12527 return LV.getLValueOffset().isZero();
12528 } else if (Base.is<TypeInfoLValue>()) {
12529 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
12530 // evaluate to true.
12531 return true;
12532 } else {
12533 // Any other base is not constant enough for GCC.
12534 return false;
12535 }
12536 }
12537
12538 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
12539 /// GCC as we can manage.
EvaluateBuiltinConstantP(EvalInfo & Info,const Expr * Arg)12540 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
12541 // This evaluation is not permitted to have side-effects, so evaluate it in
12542 // a speculative evaluation context.
12543 SpeculativeEvaluationRAII SpeculativeEval(Info);
12544
12545 // Constant-folding is always enabled for the operand of __builtin_constant_p
12546 // (even when the enclosing evaluation context otherwise requires a strict
12547 // language-specific constant expression).
12548 FoldConstant Fold(Info, true);
12549
12550 QualType ArgType = Arg->getType();
12551
12552 // __builtin_constant_p always has one operand. The rules which gcc follows
12553 // are not precisely documented, but are as follows:
12554 //
12555 // - If the operand is of integral, floating, complex or enumeration type,
12556 // and can be folded to a known value of that type, it returns 1.
12557 // - If the operand can be folded to a pointer to the first character
12558 // of a string literal (or such a pointer cast to an integral type)
12559 // or to a null pointer or an integer cast to a pointer, it returns 1.
12560 //
12561 // Otherwise, it returns 0.
12562 //
12563 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
12564 // its support for this did not work prior to GCC 9 and is not yet well
12565 // understood.
12566 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12567 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12568 ArgType->isNullPtrType()) {
12569 APValue V;
12570 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
12571 Fold.keepDiagnostics();
12572 return false;
12573 }
12574
12575 // For a pointer (possibly cast to integer), there are special rules.
12576 if (V.getKind() == APValue::LValue)
12577 return EvaluateBuiltinConstantPForLValue(V);
12578
12579 // Otherwise, any constant value is good enough.
12580 return V.hasValue();
12581 }
12582
12583 // Anything else isn't considered to be sufficiently constant.
12584 return false;
12585 }
12586
12587 /// Retrieves the "underlying object type" of the given expression,
12588 /// as used by __builtin_object_size.
getObjectType(APValue::LValueBase B)12589 static QualType getObjectType(APValue::LValueBase B) {
12590 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
12591 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
12592 return VD->getType();
12593 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
12594 if (isa<CompoundLiteralExpr>(E))
12595 return E->getType();
12596 } else if (B.is<TypeInfoLValue>()) {
12597 return B.getTypeInfoType();
12598 } else if (B.is<DynamicAllocLValue>()) {
12599 return B.getDynamicAllocType();
12600 }
12601
12602 return QualType();
12603 }
12604
12605 /// A more selective version of E->IgnoreParenCasts for
12606 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
12607 /// to change the type of E.
12608 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
12609 ///
12610 /// Always returns an RValue with a pointer representation.
ignorePointerCastsAndParens(const Expr * E)12611 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
12612 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
12613
12614 const Expr *NoParens = E->IgnoreParens();
12615 const auto *Cast = dyn_cast<CastExpr>(NoParens);
12616 if (Cast == nullptr)
12617 return NoParens;
12618
12619 // We only conservatively allow a few kinds of casts, because this code is
12620 // inherently a simple solution that seeks to support the common case.
12621 auto CastKind = Cast->getCastKind();
12622 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
12623 CastKind != CK_AddressSpaceConversion)
12624 return NoParens;
12625
12626 const auto *SubExpr = Cast->getSubExpr();
12627 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12628 return NoParens;
12629 return ignorePointerCastsAndParens(SubExpr);
12630 }
12631
12632 /// Checks to see if the given LValue's Designator is at the end of the LValue's
12633 /// record layout. e.g.
12634 /// struct { struct { int a, b; } fst, snd; } obj;
12635 /// obj.fst // no
12636 /// obj.snd // yes
12637 /// obj.fst.a // no
12638 /// obj.fst.b // no
12639 /// obj.snd.a // no
12640 /// obj.snd.b // yes
12641 ///
12642 /// Please note: this function is specialized for how __builtin_object_size
12643 /// views "objects".
12644 ///
12645 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
12646 /// correct result, it will always return true.
isDesignatorAtObjectEnd(const ASTContext & Ctx,const LValue & LVal)12647 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
12648 assert(!LVal.Designator.Invalid);
12649
12650 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
12651 const RecordDecl *Parent = FD->getParent();
12652 if (Parent->isInvalidDecl() || Parent->isUnion())
12653 return true;
12654 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
12655 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12656 };
12657
12658 auto &Base = LVal.getLValueBase();
12659 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
12660 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
12661 if (!IsLastOrInvalidFieldDecl(FD))
12662 return false;
12663 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
12664 for (auto *FD : IFD->chain()) {
12665 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
12666 return false;
12667 }
12668 }
12669 }
12670
12671 unsigned I = 0;
12672 QualType BaseType = getType(Base);
12673 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
12674 // If we don't know the array bound, conservatively assume we're looking at
12675 // the final array element.
12676 ++I;
12677 if (BaseType->isIncompleteArrayType())
12678 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
12679 else
12680 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12681 }
12682
12683 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
12684 const auto &Entry = LVal.Designator.Entries[I];
12685 if (BaseType->isArrayType()) {
12686 // Because __builtin_object_size treats arrays as objects, we can ignore
12687 // the index iff this is the last array in the Designator.
12688 if (I + 1 == E)
12689 return true;
12690 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
12691 uint64_t Index = Entry.getAsArrayIndex();
12692 if (Index + 1 != CAT->getZExtSize())
12693 return false;
12694 BaseType = CAT->getElementType();
12695 } else if (BaseType->isAnyComplexType()) {
12696 const auto *CT = BaseType->castAs<ComplexType>();
12697 uint64_t Index = Entry.getAsArrayIndex();
12698 if (Index != 1)
12699 return false;
12700 BaseType = CT->getElementType();
12701 } else if (auto *FD = getAsField(Entry)) {
12702 if (!IsLastOrInvalidFieldDecl(FD))
12703 return false;
12704 BaseType = FD->getType();
12705 } else {
12706 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
12707 return false;
12708 }
12709 }
12710 return true;
12711 }
12712
12713 /// Tests to see if the LValue has a user-specified designator (that isn't
12714 /// necessarily valid). Note that this always returns 'true' if the LValue has
12715 /// an unsized array as its first designator entry, because there's currently no
12716 /// way to tell if the user typed *foo or foo[0].
refersToCompleteObject(const LValue & LVal)12717 static bool refersToCompleteObject(const LValue &LVal) {
12718 if (LVal.Designator.Invalid)
12719 return false;
12720
12721 if (!LVal.Designator.Entries.empty())
12722 return LVal.Designator.isMostDerivedAnUnsizedArray();
12723
12724 if (!LVal.InvalidBase)
12725 return true;
12726
12727 // If `E` is a MemberExpr, then the first part of the designator is hiding in
12728 // the LValueBase.
12729 const auto *E = LVal.Base.dyn_cast<const Expr *>();
12730 return !E || !isa<MemberExpr>(E);
12731 }
12732
12733 /// Attempts to detect a user writing into a piece of memory that's impossible
12734 /// to figure out the size of by just using types.
isUserWritingOffTheEnd(const ASTContext & Ctx,const LValue & LVal)12735 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
12736 const SubobjectDesignator &Designator = LVal.Designator;
12737 // Notes:
12738 // - Users can only write off of the end when we have an invalid base. Invalid
12739 // bases imply we don't know where the memory came from.
12740 // - We used to be a bit more aggressive here; we'd only be conservative if
12741 // the array at the end was flexible, or if it had 0 or 1 elements. This
12742 // broke some common standard library extensions (PR30346), but was
12743 // otherwise seemingly fine. It may be useful to reintroduce this behavior
12744 // with some sort of list. OTOH, it seems that GCC is always
12745 // conservative with the last element in structs (if it's an array), so our
12746 // current behavior is more compatible than an explicit list approach would
12747 // be.
12748 auto isFlexibleArrayMember = [&] {
12749 using FAMKind = LangOptions::StrictFlexArraysLevelKind;
12750 FAMKind StrictFlexArraysLevel =
12751 Ctx.getLangOpts().getStrictFlexArraysLevel();
12752
12753 if (Designator.isMostDerivedAnUnsizedArray())
12754 return true;
12755
12756 if (StrictFlexArraysLevel == FAMKind::Default)
12757 return true;
12758
12759 if (Designator.getMostDerivedArraySize() == 0 &&
12760 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
12761 return true;
12762
12763 if (Designator.getMostDerivedArraySize() == 1 &&
12764 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
12765 return true;
12766
12767 return false;
12768 };
12769
12770 return LVal.InvalidBase &&
12771 Designator.Entries.size() == Designator.MostDerivedPathLength &&
12772 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
12773 isDesignatorAtObjectEnd(Ctx, LVal);
12774 }
12775
12776 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
12777 /// Fails if the conversion would cause loss of precision.
convertUnsignedAPIntToCharUnits(const llvm::APInt & Int,CharUnits & Result)12778 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
12779 CharUnits &Result) {
12780 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
12781 if (Int.ugt(CharUnitsMax))
12782 return false;
12783 Result = CharUnits::fromQuantity(Int.getZExtValue());
12784 return true;
12785 }
12786
12787 /// If we're evaluating the object size of an instance of a struct that
12788 /// contains a flexible array member, add the size of the initializer.
addFlexibleArrayMemberInitSize(EvalInfo & Info,const QualType & T,const LValue & LV,CharUnits & Size)12789 static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
12790 const LValue &LV, CharUnits &Size) {
12791 if (!T.isNull() && T->isStructureType() &&
12792 T->getAsStructureType()->getDecl()->hasFlexibleArrayMember())
12793 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
12794 if (const auto *VD = dyn_cast<VarDecl>(V))
12795 if (VD->hasInit())
12796 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
12797 }
12798
12799 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12800 /// determine how many bytes exist from the beginning of the object to either
12801 /// the end of the current subobject, or the end of the object itself, depending
12802 /// on what the LValue looks like + the value of Type.
12803 ///
12804 /// If this returns false, the value of Result is undefined.
determineEndOffset(EvalInfo & Info,SourceLocation ExprLoc,unsigned Type,const LValue & LVal,CharUnits & EndOffset)12805 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
12806 unsigned Type, const LValue &LVal,
12807 CharUnits &EndOffset) {
12808 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
12809
12810 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
12811 if (Ty.isNull())
12812 return false;
12813
12814 Ty = Ty.getNonReferenceType();
12815
12816 if (Ty->isIncompleteType() || Ty->isFunctionType())
12817 return false;
12818
12819 return HandleSizeof(Info, ExprLoc, Ty, Result);
12820 };
12821
12822 // We want to evaluate the size of the entire object. This is a valid fallback
12823 // for when Type=1 and the designator is invalid, because we're asked for an
12824 // upper-bound.
12825 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12826 // Type=3 wants a lower bound, so we can't fall back to this.
12827 if (Type == 3 && !DetermineForCompleteObject)
12828 return false;
12829
12830 llvm::APInt APEndOffset;
12831 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12832 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12833 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12834
12835 if (LVal.InvalidBase)
12836 return false;
12837
12838 QualType BaseTy = getObjectType(LVal.getLValueBase());
12839 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12840 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12841 return Ret;
12842 }
12843
12844 // We want to evaluate the size of a subobject.
12845 const SubobjectDesignator &Designator = LVal.Designator;
12846
12847 // The following is a moderately common idiom in C:
12848 //
12849 // struct Foo { int a; char c[1]; };
12850 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12851 // strcpy(&F->c[0], Bar);
12852 //
12853 // In order to not break too much legacy code, we need to support it.
12854 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12855 // If we can resolve this to an alloc_size call, we can hand that back,
12856 // because we know for certain how many bytes there are to write to.
12857 llvm::APInt APEndOffset;
12858 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12859 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12860 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12861
12862 // If we cannot determine the size of the initial allocation, then we can't
12863 // given an accurate upper-bound. However, we are still able to give
12864 // conservative lower-bounds for Type=3.
12865 if (Type == 1)
12866 return false;
12867 }
12868
12869 CharUnits BytesPerElem;
12870 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12871 return false;
12872
12873 // According to the GCC documentation, we want the size of the subobject
12874 // denoted by the pointer. But that's not quite right -- what we actually
12875 // want is the size of the immediately-enclosing array, if there is one.
12876 int64_t ElemsRemaining;
12877 if (Designator.MostDerivedIsArrayElement &&
12878 Designator.Entries.size() == Designator.MostDerivedPathLength) {
12879 uint64_t ArraySize = Designator.getMostDerivedArraySize();
12880 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12881 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12882 } else {
12883 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12884 }
12885
12886 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12887 return true;
12888 }
12889
12890 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
12891 /// returns true and stores the result in @p Size.
12892 ///
12893 /// If @p WasError is non-null, this will report whether the failure to evaluate
12894 /// is to be treated as an Error in IntExprEvaluator.
tryEvaluateBuiltinObjectSize(const Expr * E,unsigned Type,EvalInfo & Info,uint64_t & Size)12895 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12896 EvalInfo &Info, uint64_t &Size) {
12897 // Determine the denoted object.
12898 LValue LVal;
12899 {
12900 // The operand of __builtin_object_size is never evaluated for side-effects.
12901 // If there are any, but we can determine the pointed-to object anyway, then
12902 // ignore the side-effects.
12903 SpeculativeEvaluationRAII SpeculativeEval(Info);
12904 IgnoreSideEffectsRAII Fold(Info);
12905
12906 if (E->isGLValue()) {
12907 // It's possible for us to be given GLValues if we're called via
12908 // Expr::tryEvaluateObjectSize.
12909 APValue RVal;
12910 if (!EvaluateAsRValue(Info, E, RVal))
12911 return false;
12912 LVal.setFrom(Info.Ctx, RVal);
12913 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12914 /*InvalidBaseOK=*/true))
12915 return false;
12916 }
12917
12918 // If we point to before the start of the object, there are no accessible
12919 // bytes.
12920 if (LVal.getLValueOffset().isNegative()) {
12921 Size = 0;
12922 return true;
12923 }
12924
12925 CharUnits EndOffset;
12926 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12927 return false;
12928
12929 // If we've fallen outside of the end offset, just pretend there's nothing to
12930 // write to/read from.
12931 if (EndOffset <= LVal.getLValueOffset())
12932 Size = 0;
12933 else
12934 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12935 return true;
12936 }
12937
VisitCallExpr(const CallExpr * E)12938 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12939 if (!IsConstantEvaluatedBuiltinCall(E))
12940 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12941 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12942 }
12943
getBuiltinAlignArguments(const CallExpr * E,EvalInfo & Info,APValue & Val,APSInt & Alignment)12944 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12945 APValue &Val, APSInt &Alignment) {
12946 QualType SrcTy = E->getArg(0)->getType();
12947 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12948 return false;
12949 // Even though we are evaluating integer expressions we could get a pointer
12950 // argument for the __builtin_is_aligned() case.
12951 if (SrcTy->isPointerType()) {
12952 LValue Ptr;
12953 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12954 return false;
12955 Ptr.moveInto(Val);
12956 } else if (!SrcTy->isIntegralOrEnumerationType()) {
12957 Info.FFDiag(E->getArg(0));
12958 return false;
12959 } else {
12960 APSInt SrcInt;
12961 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12962 return false;
12963 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12964 "Bit widths must be the same");
12965 Val = APValue(SrcInt);
12966 }
12967 assert(Val.hasValue());
12968 return true;
12969 }
12970
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)12971 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12972 unsigned BuiltinOp) {
12973 switch (BuiltinOp) {
12974 default:
12975 return false;
12976
12977 case Builtin::BI__builtin_dynamic_object_size:
12978 case Builtin::BI__builtin_object_size: {
12979 // The type was checked when we built the expression.
12980 unsigned Type =
12981 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12982 assert(Type <= 3 && "unexpected type");
12983
12984 uint64_t Size;
12985 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12986 return Success(Size, E);
12987
12988 if (E->getArg(0)->HasSideEffects(Info.Ctx))
12989 return Success((Type & 2) ? 0 : -1, E);
12990
12991 // Expression had no side effects, but we couldn't statically determine the
12992 // size of the referenced object.
12993 switch (Info.EvalMode) {
12994 case EvalInfo::EM_ConstantExpression:
12995 case EvalInfo::EM_ConstantFold:
12996 case EvalInfo::EM_IgnoreSideEffects:
12997 // Leave it to IR generation.
12998 return Error(E);
12999 case EvalInfo::EM_ConstantExpressionUnevaluated:
13000 // Reduce it to a constant now.
13001 return Success((Type & 2) ? 0 : -1, E);
13002 }
13003
13004 llvm_unreachable("unexpected EvalMode");
13005 }
13006
13007 case Builtin::BI__builtin_os_log_format_buffer_size: {
13008 analyze_os_log::OSLogBufferLayout Layout;
13009 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
13010 return Success(Layout.size().getQuantity(), E);
13011 }
13012
13013 case Builtin::BI__builtin_is_aligned: {
13014 APValue Src;
13015 APSInt Alignment;
13016 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13017 return false;
13018 if (Src.isLValue()) {
13019 // If we evaluated a pointer, check the minimum known alignment.
13020 LValue Ptr;
13021 Ptr.setFrom(Info.Ctx, Src);
13022 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
13023 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
13024 // We can return true if the known alignment at the computed offset is
13025 // greater than the requested alignment.
13026 assert(PtrAlign.isPowerOfTwo());
13027 assert(Alignment.isPowerOf2());
13028 if (PtrAlign.getQuantity() >= Alignment)
13029 return Success(1, E);
13030 // If the alignment is not known to be sufficient, some cases could still
13031 // be aligned at run time. However, if the requested alignment is less or
13032 // equal to the base alignment and the offset is not aligned, we know that
13033 // the run-time value can never be aligned.
13034 if (BaseAlignment.getQuantity() >= Alignment &&
13035 PtrAlign.getQuantity() < Alignment)
13036 return Success(0, E);
13037 // Otherwise we can't infer whether the value is sufficiently aligned.
13038 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
13039 // in cases where we can't fully evaluate the pointer.
13040 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
13041 << Alignment;
13042 return false;
13043 }
13044 assert(Src.isInt());
13045 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
13046 }
13047 case Builtin::BI__builtin_align_up: {
13048 APValue Src;
13049 APSInt Alignment;
13050 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13051 return false;
13052 if (!Src.isInt())
13053 return Error(E);
13054 APSInt AlignedVal =
13055 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
13056 Src.getInt().isUnsigned());
13057 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
13058 return Success(AlignedVal, E);
13059 }
13060 case Builtin::BI__builtin_align_down: {
13061 APValue Src;
13062 APSInt Alignment;
13063 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13064 return false;
13065 if (!Src.isInt())
13066 return Error(E);
13067 APSInt AlignedVal =
13068 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
13069 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
13070 return Success(AlignedVal, E);
13071 }
13072
13073 case Builtin::BI__builtin_bitreverse8:
13074 case Builtin::BI__builtin_bitreverse16:
13075 case Builtin::BI__builtin_bitreverse32:
13076 case Builtin::BI__builtin_bitreverse64:
13077 case Builtin::BI__builtin_elementwise_bitreverse: {
13078 APSInt Val;
13079 if (!EvaluateInteger(E->getArg(0), Val, Info))
13080 return false;
13081
13082 return Success(Val.reverseBits(), E);
13083 }
13084
13085 case Builtin::BI__builtin_bswap16:
13086 case Builtin::BI__builtin_bswap32:
13087 case Builtin::BI__builtin_bswap64: {
13088 APSInt Val;
13089 if (!EvaluateInteger(E->getArg(0), Val, Info))
13090 return false;
13091
13092 return Success(Val.byteSwap(), E);
13093 }
13094
13095 case Builtin::BI__builtin_classify_type:
13096 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
13097
13098 case Builtin::BI__builtin_clrsb:
13099 case Builtin::BI__builtin_clrsbl:
13100 case Builtin::BI__builtin_clrsbll: {
13101 APSInt Val;
13102 if (!EvaluateInteger(E->getArg(0), Val, Info))
13103 return false;
13104
13105 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
13106 }
13107
13108 case Builtin::BI__builtin_clz:
13109 case Builtin::BI__builtin_clzl:
13110 case Builtin::BI__builtin_clzll:
13111 case Builtin::BI__builtin_clzs:
13112 case Builtin::BI__builtin_clzg:
13113 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
13114 case Builtin::BI__lzcnt:
13115 case Builtin::BI__lzcnt64: {
13116 APSInt Val;
13117 if (!EvaluateInteger(E->getArg(0), Val, Info))
13118 return false;
13119
13120 std::optional<APSInt> Fallback;
13121 if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
13122 APSInt FallbackTemp;
13123 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13124 return false;
13125 Fallback = FallbackTemp;
13126 }
13127
13128 if (!Val) {
13129 if (Fallback)
13130 return Success(*Fallback, E);
13131
13132 // When the argument is 0, the result of GCC builtins is undefined,
13133 // whereas for Microsoft intrinsics, the result is the bit-width of the
13134 // argument.
13135 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
13136 BuiltinOp != Builtin::BI__lzcnt &&
13137 BuiltinOp != Builtin::BI__lzcnt64;
13138
13139 if (ZeroIsUndefined)
13140 return Error(E);
13141 }
13142
13143 return Success(Val.countl_zero(), E);
13144 }
13145
13146 case Builtin::BI__builtin_constant_p: {
13147 const Expr *Arg = E->getArg(0);
13148 if (EvaluateBuiltinConstantP(Info, Arg))
13149 return Success(true, E);
13150 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
13151 // Outside a constant context, eagerly evaluate to false in the presence
13152 // of side-effects in order to avoid -Wunsequenced false-positives in
13153 // a branch on __builtin_constant_p(expr).
13154 return Success(false, E);
13155 }
13156 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13157 return false;
13158 }
13159
13160 case Builtin::BI__noop:
13161 // __noop always evaluates successfully and returns 0.
13162 return Success(0, E);
13163
13164 case Builtin::BI__builtin_is_constant_evaluated: {
13165 const auto *Callee = Info.CurrentCall->getCallee();
13166 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
13167 (Info.CallStackDepth == 1 ||
13168 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
13169 Callee->getIdentifier() &&
13170 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
13171 // FIXME: Find a better way to avoid duplicated diagnostics.
13172 if (Info.EvalStatus.Diag)
13173 Info.report((Info.CallStackDepth == 1)
13174 ? E->getExprLoc()
13175 : Info.CurrentCall->getCallRange().getBegin(),
13176 diag::warn_is_constant_evaluated_always_true_constexpr)
13177 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
13178 : "std::is_constant_evaluated");
13179 }
13180
13181 return Success(Info.InConstantContext, E);
13182 }
13183
13184 case Builtin::BI__builtin_is_within_lifetime:
13185 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
13186 return Success(*result, E);
13187 return false;
13188
13189 case Builtin::BI__builtin_ctz:
13190 case Builtin::BI__builtin_ctzl:
13191 case Builtin::BI__builtin_ctzll:
13192 case Builtin::BI__builtin_ctzs:
13193 case Builtin::BI__builtin_ctzg: {
13194 APSInt Val;
13195 if (!EvaluateInteger(E->getArg(0), Val, Info))
13196 return false;
13197
13198 std::optional<APSInt> Fallback;
13199 if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
13200 APSInt FallbackTemp;
13201 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13202 return false;
13203 Fallback = FallbackTemp;
13204 }
13205
13206 if (!Val) {
13207 if (Fallback)
13208 return Success(*Fallback, E);
13209
13210 return Error(E);
13211 }
13212
13213 return Success(Val.countr_zero(), E);
13214 }
13215
13216 case Builtin::BI__builtin_eh_return_data_regno: {
13217 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13218 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
13219 return Success(Operand, E);
13220 }
13221
13222 case Builtin::BI__builtin_expect:
13223 case Builtin::BI__builtin_expect_with_probability:
13224 return Visit(E->getArg(0));
13225
13226 case Builtin::BI__builtin_ptrauth_string_discriminator: {
13227 const auto *Literal =
13228 cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
13229 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
13230 return Success(Result, E);
13231 }
13232
13233 case Builtin::BI__builtin_ffs:
13234 case Builtin::BI__builtin_ffsl:
13235 case Builtin::BI__builtin_ffsll: {
13236 APSInt Val;
13237 if (!EvaluateInteger(E->getArg(0), Val, Info))
13238 return false;
13239
13240 unsigned N = Val.countr_zero();
13241 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
13242 }
13243
13244 case Builtin::BI__builtin_fpclassify: {
13245 APFloat Val(0.0);
13246 if (!EvaluateFloat(E->getArg(5), Val, Info))
13247 return false;
13248 unsigned Arg;
13249 switch (Val.getCategory()) {
13250 case APFloat::fcNaN: Arg = 0; break;
13251 case APFloat::fcInfinity: Arg = 1; break;
13252 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
13253 case APFloat::fcZero: Arg = 4; break;
13254 }
13255 return Visit(E->getArg(Arg));
13256 }
13257
13258 case Builtin::BI__builtin_isinf_sign: {
13259 APFloat Val(0.0);
13260 return EvaluateFloat(E->getArg(0), Val, Info) &&
13261 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
13262 }
13263
13264 case Builtin::BI__builtin_isinf: {
13265 APFloat Val(0.0);
13266 return EvaluateFloat(E->getArg(0), Val, Info) &&
13267 Success(Val.isInfinity() ? 1 : 0, E);
13268 }
13269
13270 case Builtin::BI__builtin_isfinite: {
13271 APFloat Val(0.0);
13272 return EvaluateFloat(E->getArg(0), Val, Info) &&
13273 Success(Val.isFinite() ? 1 : 0, E);
13274 }
13275
13276 case Builtin::BI__builtin_isnan: {
13277 APFloat Val(0.0);
13278 return EvaluateFloat(E->getArg(0), Val, Info) &&
13279 Success(Val.isNaN() ? 1 : 0, E);
13280 }
13281
13282 case Builtin::BI__builtin_isnormal: {
13283 APFloat Val(0.0);
13284 return EvaluateFloat(E->getArg(0), Val, Info) &&
13285 Success(Val.isNormal() ? 1 : 0, E);
13286 }
13287
13288 case Builtin::BI__builtin_issubnormal: {
13289 APFloat Val(0.0);
13290 return EvaluateFloat(E->getArg(0), Val, Info) &&
13291 Success(Val.isDenormal() ? 1 : 0, E);
13292 }
13293
13294 case Builtin::BI__builtin_iszero: {
13295 APFloat Val(0.0);
13296 return EvaluateFloat(E->getArg(0), Val, Info) &&
13297 Success(Val.isZero() ? 1 : 0, E);
13298 }
13299
13300 case Builtin::BI__builtin_signbit:
13301 case Builtin::BI__builtin_signbitf:
13302 case Builtin::BI__builtin_signbitl: {
13303 APFloat Val(0.0);
13304 return EvaluateFloat(E->getArg(0), Val, Info) &&
13305 Success(Val.isNegative() ? 1 : 0, E);
13306 }
13307
13308 case Builtin::BI__builtin_isgreater:
13309 case Builtin::BI__builtin_isgreaterequal:
13310 case Builtin::BI__builtin_isless:
13311 case Builtin::BI__builtin_islessequal:
13312 case Builtin::BI__builtin_islessgreater:
13313 case Builtin::BI__builtin_isunordered: {
13314 APFloat LHS(0.0);
13315 APFloat RHS(0.0);
13316 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
13317 !EvaluateFloat(E->getArg(1), RHS, Info))
13318 return false;
13319
13320 return Success(
13321 [&] {
13322 switch (BuiltinOp) {
13323 case Builtin::BI__builtin_isgreater:
13324 return LHS > RHS;
13325 case Builtin::BI__builtin_isgreaterequal:
13326 return LHS >= RHS;
13327 case Builtin::BI__builtin_isless:
13328 return LHS < RHS;
13329 case Builtin::BI__builtin_islessequal:
13330 return LHS <= RHS;
13331 case Builtin::BI__builtin_islessgreater: {
13332 APFloat::cmpResult cmp = LHS.compare(RHS);
13333 return cmp == APFloat::cmpResult::cmpLessThan ||
13334 cmp == APFloat::cmpResult::cmpGreaterThan;
13335 }
13336 case Builtin::BI__builtin_isunordered:
13337 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
13338 default:
13339 llvm_unreachable("Unexpected builtin ID: Should be a floating "
13340 "point comparison function");
13341 }
13342 }()
13343 ? 1
13344 : 0,
13345 E);
13346 }
13347
13348 case Builtin::BI__builtin_issignaling: {
13349 APFloat Val(0.0);
13350 return EvaluateFloat(E->getArg(0), Val, Info) &&
13351 Success(Val.isSignaling() ? 1 : 0, E);
13352 }
13353
13354 case Builtin::BI__builtin_isfpclass: {
13355 APSInt MaskVal;
13356 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
13357 return false;
13358 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
13359 APFloat Val(0.0);
13360 return EvaluateFloat(E->getArg(0), Val, Info) &&
13361 Success((Val.classify() & Test) ? 1 : 0, E);
13362 }
13363
13364 case Builtin::BI__builtin_parity:
13365 case Builtin::BI__builtin_parityl:
13366 case Builtin::BI__builtin_parityll: {
13367 APSInt Val;
13368 if (!EvaluateInteger(E->getArg(0), Val, Info))
13369 return false;
13370
13371 return Success(Val.popcount() % 2, E);
13372 }
13373
13374 case Builtin::BI__builtin_abs:
13375 case Builtin::BI__builtin_labs:
13376 case Builtin::BI__builtin_llabs: {
13377 APSInt Val;
13378 if (!EvaluateInteger(E->getArg(0), Val, Info))
13379 return false;
13380 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
13381 /*IsUnsigned=*/false))
13382 return false;
13383 if (Val.isNegative())
13384 Val.negate();
13385 return Success(Val, E);
13386 }
13387
13388 case Builtin::BI__builtin_popcount:
13389 case Builtin::BI__builtin_popcountl:
13390 case Builtin::BI__builtin_popcountll:
13391 case Builtin::BI__builtin_popcountg:
13392 case Builtin::BI__builtin_elementwise_popcount:
13393 case Builtin::BI__popcnt16: // Microsoft variants of popcount
13394 case Builtin::BI__popcnt:
13395 case Builtin::BI__popcnt64: {
13396 APSInt Val;
13397 if (!EvaluateInteger(E->getArg(0), Val, Info))
13398 return false;
13399
13400 return Success(Val.popcount(), E);
13401 }
13402
13403 case Builtin::BI__builtin_rotateleft8:
13404 case Builtin::BI__builtin_rotateleft16:
13405 case Builtin::BI__builtin_rotateleft32:
13406 case Builtin::BI__builtin_rotateleft64:
13407 case Builtin::BI_rotl8: // Microsoft variants of rotate right
13408 case Builtin::BI_rotl16:
13409 case Builtin::BI_rotl:
13410 case Builtin::BI_lrotl:
13411 case Builtin::BI_rotl64: {
13412 APSInt Val, Amt;
13413 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13414 !EvaluateInteger(E->getArg(1), Amt, Info))
13415 return false;
13416
13417 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
13418 }
13419
13420 case Builtin::BI__builtin_rotateright8:
13421 case Builtin::BI__builtin_rotateright16:
13422 case Builtin::BI__builtin_rotateright32:
13423 case Builtin::BI__builtin_rotateright64:
13424 case Builtin::BI_rotr8: // Microsoft variants of rotate right
13425 case Builtin::BI_rotr16:
13426 case Builtin::BI_rotr:
13427 case Builtin::BI_lrotr:
13428 case Builtin::BI_rotr64: {
13429 APSInt Val, Amt;
13430 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13431 !EvaluateInteger(E->getArg(1), Amt, Info))
13432 return false;
13433
13434 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
13435 }
13436
13437 case Builtin::BI__builtin_elementwise_add_sat: {
13438 APSInt LHS, RHS;
13439 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13440 !EvaluateInteger(E->getArg(1), RHS, Info))
13441 return false;
13442
13443 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
13444 return Success(APSInt(Result, !LHS.isSigned()), E);
13445 }
13446 case Builtin::BI__builtin_elementwise_sub_sat: {
13447 APSInt LHS, RHS;
13448 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13449 !EvaluateInteger(E->getArg(1), RHS, Info))
13450 return false;
13451
13452 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
13453 return Success(APSInt(Result, !LHS.isSigned()), E);
13454 }
13455
13456 case Builtin::BIstrlen:
13457 case Builtin::BIwcslen:
13458 // A call to strlen is not a constant expression.
13459 if (Info.getLangOpts().CPlusPlus11)
13460 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13461 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13462 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
13463 else
13464 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13465 [[fallthrough]];
13466 case Builtin::BI__builtin_strlen:
13467 case Builtin::BI__builtin_wcslen: {
13468 // As an extension, we support __builtin_strlen() as a constant expression,
13469 // and support folding strlen() to a constant.
13470 uint64_t StrLen;
13471 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
13472 return Success(StrLen, E);
13473 return false;
13474 }
13475
13476 case Builtin::BIstrcmp:
13477 case Builtin::BIwcscmp:
13478 case Builtin::BIstrncmp:
13479 case Builtin::BIwcsncmp:
13480 case Builtin::BImemcmp:
13481 case Builtin::BIbcmp:
13482 case Builtin::BIwmemcmp:
13483 // A call to strlen is not a constant expression.
13484 if (Info.getLangOpts().CPlusPlus11)
13485 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13486 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13487 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
13488 else
13489 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13490 [[fallthrough]];
13491 case Builtin::BI__builtin_strcmp:
13492 case Builtin::BI__builtin_wcscmp:
13493 case Builtin::BI__builtin_strncmp:
13494 case Builtin::BI__builtin_wcsncmp:
13495 case Builtin::BI__builtin_memcmp:
13496 case Builtin::BI__builtin_bcmp:
13497 case Builtin::BI__builtin_wmemcmp: {
13498 LValue String1, String2;
13499 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
13500 !EvaluatePointer(E->getArg(1), String2, Info))
13501 return false;
13502
13503 uint64_t MaxLength = uint64_t(-1);
13504 if (BuiltinOp != Builtin::BIstrcmp &&
13505 BuiltinOp != Builtin::BIwcscmp &&
13506 BuiltinOp != Builtin::BI__builtin_strcmp &&
13507 BuiltinOp != Builtin::BI__builtin_wcscmp) {
13508 APSInt N;
13509 if (!EvaluateInteger(E->getArg(2), N, Info))
13510 return false;
13511 MaxLength = N.getZExtValue();
13512 }
13513
13514 // Empty substrings compare equal by definition.
13515 if (MaxLength == 0u)
13516 return Success(0, E);
13517
13518 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13519 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13520 String1.Designator.Invalid || String2.Designator.Invalid)
13521 return false;
13522
13523 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
13524 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
13525
13526 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
13527 BuiltinOp == Builtin::BIbcmp ||
13528 BuiltinOp == Builtin::BI__builtin_memcmp ||
13529 BuiltinOp == Builtin::BI__builtin_bcmp;
13530
13531 assert(IsRawByte ||
13532 (Info.Ctx.hasSameUnqualifiedType(
13533 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
13534 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
13535
13536 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
13537 // 'char8_t', but no other types.
13538 if (IsRawByte &&
13539 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
13540 // FIXME: Consider using our bit_cast implementation to support this.
13541 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
13542 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
13543 << CharTy2;
13544 return false;
13545 }
13546
13547 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
13548 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
13549 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
13550 Char1.isInt() && Char2.isInt();
13551 };
13552 const auto &AdvanceElems = [&] {
13553 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
13554 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
13555 };
13556
13557 bool StopAtNull =
13558 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
13559 BuiltinOp != Builtin::BIwmemcmp &&
13560 BuiltinOp != Builtin::BI__builtin_memcmp &&
13561 BuiltinOp != Builtin::BI__builtin_bcmp &&
13562 BuiltinOp != Builtin::BI__builtin_wmemcmp);
13563 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
13564 BuiltinOp == Builtin::BIwcsncmp ||
13565 BuiltinOp == Builtin::BIwmemcmp ||
13566 BuiltinOp == Builtin::BI__builtin_wcscmp ||
13567 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
13568 BuiltinOp == Builtin::BI__builtin_wmemcmp;
13569
13570 for (; MaxLength; --MaxLength) {
13571 APValue Char1, Char2;
13572 if (!ReadCurElems(Char1, Char2))
13573 return false;
13574 if (Char1.getInt().ne(Char2.getInt())) {
13575 if (IsWide) // wmemcmp compares with wchar_t signedness.
13576 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
13577 // memcmp always compares unsigned chars.
13578 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
13579 }
13580 if (StopAtNull && !Char1.getInt())
13581 return Success(0, E);
13582 assert(!(StopAtNull && !Char2.getInt()));
13583 if (!AdvanceElems())
13584 return false;
13585 }
13586 // We hit the strncmp / memcmp limit.
13587 return Success(0, E);
13588 }
13589
13590 case Builtin::BI__atomic_always_lock_free:
13591 case Builtin::BI__atomic_is_lock_free:
13592 case Builtin::BI__c11_atomic_is_lock_free: {
13593 APSInt SizeVal;
13594 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
13595 return false;
13596
13597 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
13598 // of two less than or equal to the maximum inline atomic width, we know it
13599 // is lock-free. If the size isn't a power of two, or greater than the
13600 // maximum alignment where we promote atomics, we know it is not lock-free
13601 // (at least not in the sense of atomic_is_lock_free). Otherwise,
13602 // the answer can only be determined at runtime; for example, 16-byte
13603 // atomics have lock-free implementations on some, but not all,
13604 // x86-64 processors.
13605
13606 // Check power-of-two.
13607 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
13608 if (Size.isPowerOfTwo()) {
13609 // Check against inlining width.
13610 unsigned InlineWidthBits =
13611 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
13612 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
13613 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
13614 Size == CharUnits::One())
13615 return Success(1, E);
13616
13617 // If the pointer argument can be evaluated to a compile-time constant
13618 // integer (or nullptr), check if that value is appropriately aligned.
13619 const Expr *PtrArg = E->getArg(1);
13620 Expr::EvalResult ExprResult;
13621 APSInt IntResult;
13622 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
13623 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
13624 Info.Ctx) &&
13625 IntResult.isAligned(Size.getAsAlign()))
13626 return Success(1, E);
13627
13628 // Otherwise, check if the type's alignment against Size.
13629 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
13630 // Drop the potential implicit-cast to 'const volatile void*', getting
13631 // the underlying type.
13632 if (ICE->getCastKind() == CK_BitCast)
13633 PtrArg = ICE->getSubExpr();
13634 }
13635
13636 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
13637 QualType PointeeType = PtrTy->getPointeeType();
13638 if (!PointeeType->isIncompleteType() &&
13639 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
13640 // OK, we will inline operations on this object.
13641 return Success(1, E);
13642 }
13643 }
13644 }
13645 }
13646
13647 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
13648 Success(0, E) : Error(E);
13649 }
13650 case Builtin::BI__builtin_addcb:
13651 case Builtin::BI__builtin_addcs:
13652 case Builtin::BI__builtin_addc:
13653 case Builtin::BI__builtin_addcl:
13654 case Builtin::BI__builtin_addcll:
13655 case Builtin::BI__builtin_subcb:
13656 case Builtin::BI__builtin_subcs:
13657 case Builtin::BI__builtin_subc:
13658 case Builtin::BI__builtin_subcl:
13659 case Builtin::BI__builtin_subcll: {
13660 LValue CarryOutLValue;
13661 APSInt LHS, RHS, CarryIn, CarryOut, Result;
13662 QualType ResultType = E->getArg(0)->getType();
13663 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13664 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13665 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
13666 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
13667 return false;
13668 // Copy the number of bits and sign.
13669 Result = LHS;
13670 CarryOut = LHS;
13671
13672 bool FirstOverflowed = false;
13673 bool SecondOverflowed = false;
13674 switch (BuiltinOp) {
13675 default:
13676 llvm_unreachable("Invalid value for BuiltinOp");
13677 case Builtin::BI__builtin_addcb:
13678 case Builtin::BI__builtin_addcs:
13679 case Builtin::BI__builtin_addc:
13680 case Builtin::BI__builtin_addcl:
13681 case Builtin::BI__builtin_addcll:
13682 Result =
13683 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
13684 break;
13685 case Builtin::BI__builtin_subcb:
13686 case Builtin::BI__builtin_subcs:
13687 case Builtin::BI__builtin_subc:
13688 case Builtin::BI__builtin_subcl:
13689 case Builtin::BI__builtin_subcll:
13690 Result =
13691 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
13692 break;
13693 }
13694
13695 // It is possible for both overflows to happen but CGBuiltin uses an OR so
13696 // this is consistent.
13697 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
13698 APValue APV{CarryOut};
13699 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
13700 return false;
13701 return Success(Result, E);
13702 }
13703 case Builtin::BI__builtin_add_overflow:
13704 case Builtin::BI__builtin_sub_overflow:
13705 case Builtin::BI__builtin_mul_overflow:
13706 case Builtin::BI__builtin_sadd_overflow:
13707 case Builtin::BI__builtin_uadd_overflow:
13708 case Builtin::BI__builtin_uaddl_overflow:
13709 case Builtin::BI__builtin_uaddll_overflow:
13710 case Builtin::BI__builtin_usub_overflow:
13711 case Builtin::BI__builtin_usubl_overflow:
13712 case Builtin::BI__builtin_usubll_overflow:
13713 case Builtin::BI__builtin_umul_overflow:
13714 case Builtin::BI__builtin_umull_overflow:
13715 case Builtin::BI__builtin_umulll_overflow:
13716 case Builtin::BI__builtin_saddl_overflow:
13717 case Builtin::BI__builtin_saddll_overflow:
13718 case Builtin::BI__builtin_ssub_overflow:
13719 case Builtin::BI__builtin_ssubl_overflow:
13720 case Builtin::BI__builtin_ssubll_overflow:
13721 case Builtin::BI__builtin_smul_overflow:
13722 case Builtin::BI__builtin_smull_overflow:
13723 case Builtin::BI__builtin_smulll_overflow: {
13724 LValue ResultLValue;
13725 APSInt LHS, RHS;
13726
13727 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
13728 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13729 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13730 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
13731 return false;
13732
13733 APSInt Result;
13734 bool DidOverflow = false;
13735
13736 // If the types don't have to match, enlarge all 3 to the largest of them.
13737 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13738 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13739 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13740 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
13741 ResultType->isSignedIntegerOrEnumerationType();
13742 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
13743 ResultType->isSignedIntegerOrEnumerationType();
13744 uint64_t LHSSize = LHS.getBitWidth();
13745 uint64_t RHSSize = RHS.getBitWidth();
13746 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
13747 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
13748
13749 // Add an additional bit if the signedness isn't uniformly agreed to. We
13750 // could do this ONLY if there is a signed and an unsigned that both have
13751 // MaxBits, but the code to check that is pretty nasty. The issue will be
13752 // caught in the shrink-to-result later anyway.
13753 if (IsSigned && !AllSigned)
13754 ++MaxBits;
13755
13756 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
13757 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
13758 Result = APSInt(MaxBits, !IsSigned);
13759 }
13760
13761 // Find largest int.
13762 switch (BuiltinOp) {
13763 default:
13764 llvm_unreachable("Invalid value for BuiltinOp");
13765 case Builtin::BI__builtin_add_overflow:
13766 case Builtin::BI__builtin_sadd_overflow:
13767 case Builtin::BI__builtin_saddl_overflow:
13768 case Builtin::BI__builtin_saddll_overflow:
13769 case Builtin::BI__builtin_uadd_overflow:
13770 case Builtin::BI__builtin_uaddl_overflow:
13771 case Builtin::BI__builtin_uaddll_overflow:
13772 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
13773 : LHS.uadd_ov(RHS, DidOverflow);
13774 break;
13775 case Builtin::BI__builtin_sub_overflow:
13776 case Builtin::BI__builtin_ssub_overflow:
13777 case Builtin::BI__builtin_ssubl_overflow:
13778 case Builtin::BI__builtin_ssubll_overflow:
13779 case Builtin::BI__builtin_usub_overflow:
13780 case Builtin::BI__builtin_usubl_overflow:
13781 case Builtin::BI__builtin_usubll_overflow:
13782 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
13783 : LHS.usub_ov(RHS, DidOverflow);
13784 break;
13785 case Builtin::BI__builtin_mul_overflow:
13786 case Builtin::BI__builtin_smul_overflow:
13787 case Builtin::BI__builtin_smull_overflow:
13788 case Builtin::BI__builtin_smulll_overflow:
13789 case Builtin::BI__builtin_umul_overflow:
13790 case Builtin::BI__builtin_umull_overflow:
13791 case Builtin::BI__builtin_umulll_overflow:
13792 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
13793 : LHS.umul_ov(RHS, DidOverflow);
13794 break;
13795 }
13796
13797 // In the case where multiple sizes are allowed, truncate and see if
13798 // the values are the same.
13799 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13800 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13801 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13802 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
13803 // since it will give us the behavior of a TruncOrSelf in the case where
13804 // its parameter <= its size. We previously set Result to be at least the
13805 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13806 // will work exactly like TruncOrSelf.
13807 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
13808 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13809
13810 if (!APSInt::isSameValue(Temp, Result))
13811 DidOverflow = true;
13812 Result = Temp;
13813 }
13814
13815 APValue APV{Result};
13816 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13817 return false;
13818 return Success(DidOverflow, E);
13819 }
13820
13821 case Builtin::BI__builtin_reduce_add:
13822 case Builtin::BI__builtin_reduce_mul:
13823 case Builtin::BI__builtin_reduce_and:
13824 case Builtin::BI__builtin_reduce_or:
13825 case Builtin::BI__builtin_reduce_xor:
13826 case Builtin::BI__builtin_reduce_min:
13827 case Builtin::BI__builtin_reduce_max: {
13828 APValue Source;
13829 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13830 return false;
13831
13832 unsigned SourceLen = Source.getVectorLength();
13833 APSInt Reduced = Source.getVectorElt(0).getInt();
13834 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
13835 switch (BuiltinOp) {
13836 default:
13837 return false;
13838 case Builtin::BI__builtin_reduce_add: {
13839 if (!CheckedIntArithmetic(
13840 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13841 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
13842 return false;
13843 break;
13844 }
13845 case Builtin::BI__builtin_reduce_mul: {
13846 if (!CheckedIntArithmetic(
13847 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13848 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
13849 return false;
13850 break;
13851 }
13852 case Builtin::BI__builtin_reduce_and: {
13853 Reduced &= Source.getVectorElt(EltNum).getInt();
13854 break;
13855 }
13856 case Builtin::BI__builtin_reduce_or: {
13857 Reduced |= Source.getVectorElt(EltNum).getInt();
13858 break;
13859 }
13860 case Builtin::BI__builtin_reduce_xor: {
13861 Reduced ^= Source.getVectorElt(EltNum).getInt();
13862 break;
13863 }
13864 case Builtin::BI__builtin_reduce_min: {
13865 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
13866 break;
13867 }
13868 case Builtin::BI__builtin_reduce_max: {
13869 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
13870 break;
13871 }
13872 }
13873 }
13874
13875 return Success(Reduced, E);
13876 }
13877
13878 case clang::X86::BI__builtin_ia32_addcarryx_u32:
13879 case clang::X86::BI__builtin_ia32_addcarryx_u64:
13880 case clang::X86::BI__builtin_ia32_subborrow_u32:
13881 case clang::X86::BI__builtin_ia32_subborrow_u64: {
13882 LValue ResultLValue;
13883 APSInt CarryIn, LHS, RHS;
13884 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
13885 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
13886 !EvaluateInteger(E->getArg(1), LHS, Info) ||
13887 !EvaluateInteger(E->getArg(2), RHS, Info) ||
13888 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
13889 return false;
13890
13891 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
13892 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
13893
13894 unsigned BitWidth = LHS.getBitWidth();
13895 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
13896 APInt ExResult =
13897 IsAdd
13898 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
13899 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
13900
13901 APInt Result = ExResult.extractBits(BitWidth, 0);
13902 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
13903
13904 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
13905 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13906 return false;
13907 return Success(CarryOut, E);
13908 }
13909
13910 case clang::X86::BI__builtin_ia32_bextr_u32:
13911 case clang::X86::BI__builtin_ia32_bextr_u64:
13912 case clang::X86::BI__builtin_ia32_bextri_u32:
13913 case clang::X86::BI__builtin_ia32_bextri_u64: {
13914 APSInt Val, Idx;
13915 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13916 !EvaluateInteger(E->getArg(1), Idx, Info))
13917 return false;
13918
13919 unsigned BitWidth = Val.getBitWidth();
13920 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
13921 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
13922 Length = Length > BitWidth ? BitWidth : Length;
13923
13924 // Handle out of bounds cases.
13925 if (Length == 0 || Shift >= BitWidth)
13926 return Success(0, E);
13927
13928 uint64_t Result = Val.getZExtValue() >> Shift;
13929 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
13930 return Success(Result, E);
13931 }
13932
13933 case clang::X86::BI__builtin_ia32_bzhi_si:
13934 case clang::X86::BI__builtin_ia32_bzhi_di: {
13935 APSInt Val, Idx;
13936 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13937 !EvaluateInteger(E->getArg(1), Idx, Info))
13938 return false;
13939
13940 unsigned BitWidth = Val.getBitWidth();
13941 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
13942 if (Index < BitWidth)
13943 Val.clearHighBits(BitWidth - Index);
13944 return Success(Val, E);
13945 }
13946
13947 case clang::X86::BI__builtin_ia32_lzcnt_u16:
13948 case clang::X86::BI__builtin_ia32_lzcnt_u32:
13949 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
13950 APSInt Val;
13951 if (!EvaluateInteger(E->getArg(0), Val, Info))
13952 return false;
13953 return Success(Val.countLeadingZeros(), E);
13954 }
13955
13956 case clang::X86::BI__builtin_ia32_tzcnt_u16:
13957 case clang::X86::BI__builtin_ia32_tzcnt_u32:
13958 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
13959 APSInt Val;
13960 if (!EvaluateInteger(E->getArg(0), Val, Info))
13961 return false;
13962 return Success(Val.countTrailingZeros(), E);
13963 }
13964
13965 case clang::X86::BI__builtin_ia32_pdep_si:
13966 case clang::X86::BI__builtin_ia32_pdep_di: {
13967 APSInt Val, Msk;
13968 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13969 !EvaluateInteger(E->getArg(1), Msk, Info))
13970 return false;
13971
13972 unsigned BitWidth = Val.getBitWidth();
13973 APInt Result = APInt::getZero(BitWidth);
13974 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13975 if (Msk[I])
13976 Result.setBitVal(I, Val[P++]);
13977 return Success(Result, E);
13978 }
13979
13980 case clang::X86::BI__builtin_ia32_pext_si:
13981 case clang::X86::BI__builtin_ia32_pext_di: {
13982 APSInt Val, Msk;
13983 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13984 !EvaluateInteger(E->getArg(1), Msk, Info))
13985 return false;
13986
13987 unsigned BitWidth = Val.getBitWidth();
13988 APInt Result = APInt::getZero(BitWidth);
13989 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13990 if (Msk[I])
13991 Result.setBitVal(P++, Val[I]);
13992 return Success(Result, E);
13993 }
13994 }
13995 }
13996
13997 /// Determine whether this is a pointer past the end of the complete
13998 /// object referred to by the lvalue.
isOnePastTheEndOfCompleteObject(const ASTContext & Ctx,const LValue & LV)13999 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
14000 const LValue &LV) {
14001 // A null pointer can be viewed as being "past the end" but we don't
14002 // choose to look at it that way here.
14003 if (!LV.getLValueBase())
14004 return false;
14005
14006 // If the designator is valid and refers to a subobject, we're not pointing
14007 // past the end.
14008 if (!LV.getLValueDesignator().Invalid &&
14009 !LV.getLValueDesignator().isOnePastTheEnd())
14010 return false;
14011
14012 // A pointer to an incomplete type might be past-the-end if the type's size is
14013 // zero. We cannot tell because the type is incomplete.
14014 QualType Ty = getType(LV.getLValueBase());
14015 if (Ty->isIncompleteType())
14016 return true;
14017
14018 // Can't be past the end of an invalid object.
14019 if (LV.getLValueDesignator().Invalid)
14020 return false;
14021
14022 // We're a past-the-end pointer if we point to the byte after the object,
14023 // no matter what our type or path is.
14024 auto Size = Ctx.getTypeSizeInChars(Ty);
14025 return LV.getLValueOffset() == Size;
14026 }
14027
14028 namespace {
14029
14030 /// Data recursive integer evaluator of certain binary operators.
14031 ///
14032 /// We use a data recursive algorithm for binary operators so that we are able
14033 /// to handle extreme cases of chained binary operators without causing stack
14034 /// overflow.
14035 class DataRecursiveIntBinOpEvaluator {
14036 struct EvalResult {
14037 APValue Val;
14038 bool Failed = false;
14039
14040 EvalResult() = default;
14041
swap__anonfb577fba2d11::DataRecursiveIntBinOpEvaluator::EvalResult14042 void swap(EvalResult &RHS) {
14043 Val.swap(RHS.Val);
14044 Failed = RHS.Failed;
14045 RHS.Failed = false;
14046 }
14047 };
14048
14049 struct Job {
14050 const Expr *E;
14051 EvalResult LHSResult; // meaningful only for binary operator expression.
14052 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
14053
14054 Job() = default;
14055 Job(Job &&) = default;
14056
startSpeculativeEval__anonfb577fba2d11::DataRecursiveIntBinOpEvaluator::Job14057 void startSpeculativeEval(EvalInfo &Info) {
14058 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
14059 }
14060
14061 private:
14062 SpeculativeEvaluationRAII SpecEvalRAII;
14063 };
14064
14065 SmallVector<Job, 16> Queue;
14066
14067 IntExprEvaluator &IntEval;
14068 EvalInfo &Info;
14069 APValue &FinalResult;
14070
14071 public:
DataRecursiveIntBinOpEvaluator(IntExprEvaluator & IntEval,APValue & Result)14072 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
14073 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
14074
14075 /// True if \param E is a binary operator that we are going to handle
14076 /// data recursively.
14077 /// We handle binary operators that are comma, logical, or that have operands
14078 /// with integral or enumeration type.
shouldEnqueue(const BinaryOperator * E)14079 static bool shouldEnqueue(const BinaryOperator *E) {
14080 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
14081 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
14082 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14083 E->getRHS()->getType()->isIntegralOrEnumerationType());
14084 }
14085
Traverse(const BinaryOperator * E)14086 bool Traverse(const BinaryOperator *E) {
14087 enqueue(E);
14088 EvalResult PrevResult;
14089 while (!Queue.empty())
14090 process(PrevResult);
14091
14092 if (PrevResult.Failed) return false;
14093
14094 FinalResult.swap(PrevResult.Val);
14095 return true;
14096 }
14097
14098 private:
Success(uint64_t Value,const Expr * E,APValue & Result)14099 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
14100 return IntEval.Success(Value, E, Result);
14101 }
Success(const APSInt & Value,const Expr * E,APValue & Result)14102 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
14103 return IntEval.Success(Value, E, Result);
14104 }
Error(const Expr * E)14105 bool Error(const Expr *E) {
14106 return IntEval.Error(E);
14107 }
Error(const Expr * E,diag::kind D)14108 bool Error(const Expr *E, diag::kind D) {
14109 return IntEval.Error(E, D);
14110 }
14111
CCEDiag(const Expr * E,diag::kind D)14112 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
14113 return Info.CCEDiag(E, D);
14114 }
14115
14116 // Returns true if visiting the RHS is necessary, false otherwise.
14117 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14118 bool &SuppressRHSDiags);
14119
14120 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14121 const BinaryOperator *E, APValue &Result);
14122
EvaluateExpr(const Expr * E,EvalResult & Result)14123 void EvaluateExpr(const Expr *E, EvalResult &Result) {
14124 Result.Failed = !Evaluate(Result.Val, Info, E);
14125 if (Result.Failed)
14126 Result.Val = APValue();
14127 }
14128
14129 void process(EvalResult &Result);
14130
enqueue(const Expr * E)14131 void enqueue(const Expr *E) {
14132 E = E->IgnoreParens();
14133 Queue.resize(Queue.size()+1);
14134 Queue.back().E = E;
14135 Queue.back().Kind = Job::AnyExprKind;
14136 }
14137 };
14138
14139 }
14140
14141 bool DataRecursiveIntBinOpEvaluator::
VisitBinOpLHSOnly(EvalResult & LHSResult,const BinaryOperator * E,bool & SuppressRHSDiags)14142 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14143 bool &SuppressRHSDiags) {
14144 if (E->getOpcode() == BO_Comma) {
14145 // Ignore LHS but note if we could not evaluate it.
14146 if (LHSResult.Failed)
14147 return Info.noteSideEffect();
14148 return true;
14149 }
14150
14151 if (E->isLogicalOp()) {
14152 bool LHSAsBool;
14153 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
14154 // We were able to evaluate the LHS, see if we can get away with not
14155 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
14156 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
14157 Success(LHSAsBool, E, LHSResult.Val);
14158 return false; // Ignore RHS
14159 }
14160 } else {
14161 LHSResult.Failed = true;
14162
14163 // Since we weren't able to evaluate the left hand side, it
14164 // might have had side effects.
14165 if (!Info.noteSideEffect())
14166 return false;
14167
14168 // We can't evaluate the LHS; however, sometimes the result
14169 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14170 // Don't ignore RHS and suppress diagnostics from this arm.
14171 SuppressRHSDiags = true;
14172 }
14173
14174 return true;
14175 }
14176
14177 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14178 E->getRHS()->getType()->isIntegralOrEnumerationType());
14179
14180 if (LHSResult.Failed && !Info.noteFailure())
14181 return false; // Ignore RHS;
14182
14183 return true;
14184 }
14185
addOrSubLValueAsInteger(APValue & LVal,const APSInt & Index,bool IsSub)14186 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
14187 bool IsSub) {
14188 // Compute the new offset in the appropriate width, wrapping at 64 bits.
14189 // FIXME: When compiling for a 32-bit target, we should use 32-bit
14190 // offsets.
14191 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
14192 CharUnits &Offset = LVal.getLValueOffset();
14193 uint64_t Offset64 = Offset.getQuantity();
14194 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
14195 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
14196 : Offset64 + Index64);
14197 }
14198
14199 bool DataRecursiveIntBinOpEvaluator::
VisitBinOp(const EvalResult & LHSResult,const EvalResult & RHSResult,const BinaryOperator * E,APValue & Result)14200 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14201 const BinaryOperator *E, APValue &Result) {
14202 if (E->getOpcode() == BO_Comma) {
14203 if (RHSResult.Failed)
14204 return false;
14205 Result = RHSResult.Val;
14206 return true;
14207 }
14208
14209 if (E->isLogicalOp()) {
14210 bool lhsResult, rhsResult;
14211 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
14212 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
14213
14214 if (LHSIsOK) {
14215 if (RHSIsOK) {
14216 if (E->getOpcode() == BO_LOr)
14217 return Success(lhsResult || rhsResult, E, Result);
14218 else
14219 return Success(lhsResult && rhsResult, E, Result);
14220 }
14221 } else {
14222 if (RHSIsOK) {
14223 // We can't evaluate the LHS; however, sometimes the result
14224 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14225 if (rhsResult == (E->getOpcode() == BO_LOr))
14226 return Success(rhsResult, E, Result);
14227 }
14228 }
14229
14230 return false;
14231 }
14232
14233 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14234 E->getRHS()->getType()->isIntegralOrEnumerationType());
14235
14236 if (LHSResult.Failed || RHSResult.Failed)
14237 return false;
14238
14239 const APValue &LHSVal = LHSResult.Val;
14240 const APValue &RHSVal = RHSResult.Val;
14241
14242 // Handle cases like (unsigned long)&a + 4.
14243 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
14244 Result = LHSVal;
14245 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
14246 return true;
14247 }
14248
14249 // Handle cases like 4 + (unsigned long)&a
14250 if (E->getOpcode() == BO_Add &&
14251 RHSVal.isLValue() && LHSVal.isInt()) {
14252 Result = RHSVal;
14253 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
14254 return true;
14255 }
14256
14257 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
14258 // Handle (intptr_t)&&A - (intptr_t)&&B.
14259 if (!LHSVal.getLValueOffset().isZero() ||
14260 !RHSVal.getLValueOffset().isZero())
14261 return false;
14262 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
14263 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
14264 if (!LHSExpr || !RHSExpr)
14265 return false;
14266 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14267 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14268 if (!LHSAddrExpr || !RHSAddrExpr)
14269 return false;
14270 // Make sure both labels come from the same function.
14271 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14272 RHSAddrExpr->getLabel()->getDeclContext())
14273 return false;
14274 Result = APValue(LHSAddrExpr, RHSAddrExpr);
14275 return true;
14276 }
14277
14278 // All the remaining cases expect both operands to be an integer
14279 if (!LHSVal.isInt() || !RHSVal.isInt())
14280 return Error(E);
14281
14282 // Set up the width and signedness manually, in case it can't be deduced
14283 // from the operation we're performing.
14284 // FIXME: Don't do this in the cases where we can deduce it.
14285 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
14286 E->getType()->isUnsignedIntegerOrEnumerationType());
14287 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
14288 RHSVal.getInt(), Value))
14289 return false;
14290 return Success(Value, E, Result);
14291 }
14292
process(EvalResult & Result)14293 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
14294 Job &job = Queue.back();
14295
14296 switch (job.Kind) {
14297 case Job::AnyExprKind: {
14298 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
14299 if (shouldEnqueue(Bop)) {
14300 job.Kind = Job::BinOpKind;
14301 enqueue(Bop->getLHS());
14302 return;
14303 }
14304 }
14305
14306 EvaluateExpr(job.E, Result);
14307 Queue.pop_back();
14308 return;
14309 }
14310
14311 case Job::BinOpKind: {
14312 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14313 bool SuppressRHSDiags = false;
14314 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
14315 Queue.pop_back();
14316 return;
14317 }
14318 if (SuppressRHSDiags)
14319 job.startSpeculativeEval(Info);
14320 job.LHSResult.swap(Result);
14321 job.Kind = Job::BinOpVisitedLHSKind;
14322 enqueue(Bop->getRHS());
14323 return;
14324 }
14325
14326 case Job::BinOpVisitedLHSKind: {
14327 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14328 EvalResult RHS;
14329 RHS.swap(Result);
14330 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
14331 Queue.pop_back();
14332 return;
14333 }
14334 }
14335
14336 llvm_unreachable("Invalid Job::Kind!");
14337 }
14338
14339 namespace {
14340 enum class CmpResult {
14341 Unequal,
14342 Less,
14343 Equal,
14344 Greater,
14345 Unordered,
14346 };
14347 }
14348
14349 template <class SuccessCB, class AfterCB>
14350 static bool
EvaluateComparisonBinaryOperator(EvalInfo & Info,const BinaryOperator * E,SuccessCB && Success,AfterCB && DoAfter)14351 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
14352 SuccessCB &&Success, AfterCB &&DoAfter) {
14353 assert(!E->isValueDependent());
14354 assert(E->isComparisonOp() && "expected comparison operator");
14355 assert((E->getOpcode() == BO_Cmp ||
14356 E->getType()->isIntegralOrEnumerationType()) &&
14357 "unsupported binary expression evaluation");
14358 auto Error = [&](const Expr *E) {
14359 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14360 return false;
14361 };
14362
14363 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
14364 bool IsEquality = E->isEqualityOp();
14365
14366 QualType LHSTy = E->getLHS()->getType();
14367 QualType RHSTy = E->getRHS()->getType();
14368
14369 if (LHSTy->isIntegralOrEnumerationType() &&
14370 RHSTy->isIntegralOrEnumerationType()) {
14371 APSInt LHS, RHS;
14372 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
14373 if (!LHSOK && !Info.noteFailure())
14374 return false;
14375 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
14376 return false;
14377 if (LHS < RHS)
14378 return Success(CmpResult::Less, E);
14379 if (LHS > RHS)
14380 return Success(CmpResult::Greater, E);
14381 return Success(CmpResult::Equal, E);
14382 }
14383
14384 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
14385 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
14386 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
14387
14388 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
14389 if (!LHSOK && !Info.noteFailure())
14390 return false;
14391 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
14392 return false;
14393 if (LHSFX < RHSFX)
14394 return Success(CmpResult::Less, E);
14395 if (LHSFX > RHSFX)
14396 return Success(CmpResult::Greater, E);
14397 return Success(CmpResult::Equal, E);
14398 }
14399
14400 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
14401 ComplexValue LHS, RHS;
14402 bool LHSOK;
14403 if (E->isAssignmentOp()) {
14404 LValue LV;
14405 EvaluateLValue(E->getLHS(), LV, Info);
14406 LHSOK = false;
14407 } else if (LHSTy->isRealFloatingType()) {
14408 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
14409 if (LHSOK) {
14410 LHS.makeComplexFloat();
14411 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
14412 }
14413 } else {
14414 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
14415 }
14416 if (!LHSOK && !Info.noteFailure())
14417 return false;
14418
14419 if (E->getRHS()->getType()->isRealFloatingType()) {
14420 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
14421 return false;
14422 RHS.makeComplexFloat();
14423 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
14424 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14425 return false;
14426
14427 if (LHS.isComplexFloat()) {
14428 APFloat::cmpResult CR_r =
14429 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
14430 APFloat::cmpResult CR_i =
14431 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
14432 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
14433 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14434 } else {
14435 assert(IsEquality && "invalid complex comparison");
14436 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
14437 LHS.getComplexIntImag() == RHS.getComplexIntImag();
14438 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14439 }
14440 }
14441
14442 if (LHSTy->isRealFloatingType() &&
14443 RHSTy->isRealFloatingType()) {
14444 APFloat RHS(0.0), LHS(0.0);
14445
14446 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
14447 if (!LHSOK && !Info.noteFailure())
14448 return false;
14449
14450 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
14451 return false;
14452
14453 assert(E->isComparisonOp() && "Invalid binary operator!");
14454 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
14455 if (!Info.InConstantContext &&
14456 APFloatCmpResult == APFloat::cmpUnordered &&
14457 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
14458 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
14459 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
14460 return false;
14461 }
14462 auto GetCmpRes = [&]() {
14463 switch (APFloatCmpResult) {
14464 case APFloat::cmpEqual:
14465 return CmpResult::Equal;
14466 case APFloat::cmpLessThan:
14467 return CmpResult::Less;
14468 case APFloat::cmpGreaterThan:
14469 return CmpResult::Greater;
14470 case APFloat::cmpUnordered:
14471 return CmpResult::Unordered;
14472 }
14473 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
14474 };
14475 return Success(GetCmpRes(), E);
14476 }
14477
14478 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
14479 LValue LHSValue, RHSValue;
14480
14481 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14482 if (!LHSOK && !Info.noteFailure())
14483 return false;
14484
14485 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14486 return false;
14487
14488 // Reject differing bases from the normal codepath; we special-case
14489 // comparisons to null.
14490 if (!HasSameBase(LHSValue, RHSValue)) {
14491 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
14492 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
14493 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
14494 Info.FFDiag(E, DiagID)
14495 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
14496 return false;
14497 };
14498 // Inequalities and subtractions between unrelated pointers have
14499 // unspecified or undefined behavior.
14500 if (!IsEquality)
14501 return DiagComparison(
14502 diag::note_constexpr_pointer_comparison_unspecified);
14503 // A constant address may compare equal to the address of a symbol.
14504 // The one exception is that address of an object cannot compare equal
14505 // to a null pointer constant.
14506 // TODO: Should we restrict this to actual null pointers, and exclude the
14507 // case of zero cast to pointer type?
14508 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
14509 (!RHSValue.Base && !RHSValue.Offset.isZero()))
14510 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
14511 !RHSValue.Base);
14512 // C++2c [intro.object]/10:
14513 // Two objects [...] may have the same address if [...] they are both
14514 // potentially non-unique objects.
14515 // C++2c [intro.object]/9:
14516 // An object is potentially non-unique if it is a string literal object,
14517 // the backing array of an initializer list, or a subobject thereof.
14518 //
14519 // This makes the comparison result unspecified, so it's not a constant
14520 // expression.
14521 //
14522 // TODO: Do we need to handle the initializer list case here?
14523 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
14524 return DiagComparison(diag::note_constexpr_literal_comparison);
14525 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
14526 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
14527 !IsOpaqueConstantCall(LHSValue));
14528 // We can't tell whether weak symbols will end up pointing to the same
14529 // object.
14530 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
14531 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
14532 !IsWeakLValue(LHSValue));
14533 // We can't compare the address of the start of one object with the
14534 // past-the-end address of another object, per C++ DR1652.
14535 if (LHSValue.Base && LHSValue.Offset.isZero() &&
14536 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
14537 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14538 true);
14539 if (RHSValue.Base && RHSValue.Offset.isZero() &&
14540 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
14541 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14542 false);
14543 // We can't tell whether an object is at the same address as another
14544 // zero sized object.
14545 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
14546 (LHSValue.Base && isZeroSized(RHSValue)))
14547 return DiagComparison(
14548 diag::note_constexpr_pointer_comparison_zero_sized);
14549 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
14550 return DiagComparison(
14551 diag::note_constexpr_pointer_comparison_unspecified);
14552 // FIXME: Verify both variables are live.
14553 return Success(CmpResult::Unequal, E);
14554 }
14555
14556 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14557 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14558
14559 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14560 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14561
14562 // C++11 [expr.rel]p2:
14563 // - If two pointers point to non-static data members of the same object,
14564 // or to subobjects or array elements fo such members, recursively, the
14565 // pointer to the later declared member compares greater provided the
14566 // two members have the same access control and provided their class is
14567 // not a union.
14568 // [...]
14569 // - Otherwise pointer comparisons are unspecified.
14570 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
14571 bool WasArrayIndex;
14572 unsigned Mismatch = FindDesignatorMismatch(
14573 LHSValue.Base.isNull() ? QualType()
14574 : getType(LHSValue.Base).getNonReferenceType(),
14575 LHSDesignator, RHSDesignator, WasArrayIndex);
14576 // At the point where the designators diverge, the comparison has a
14577 // specified value if:
14578 // - we are comparing array indices
14579 // - we are comparing fields of a union, or fields with the same access
14580 // Otherwise, the result is unspecified and thus the comparison is not a
14581 // constant expression.
14582 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
14583 Mismatch < RHSDesignator.Entries.size()) {
14584 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
14585 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
14586 if (!LF && !RF)
14587 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
14588 else if (!LF)
14589 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14590 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
14591 << RF->getParent() << RF;
14592 else if (!RF)
14593 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14594 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
14595 << LF->getParent() << LF;
14596 else if (!LF->getParent()->isUnion() &&
14597 LF->getAccess() != RF->getAccess())
14598 Info.CCEDiag(E,
14599 diag::note_constexpr_pointer_comparison_differing_access)
14600 << LF << LF->getAccess() << RF << RF->getAccess()
14601 << LF->getParent();
14602 }
14603 }
14604
14605 // The comparison here must be unsigned, and performed with the same
14606 // width as the pointer.
14607 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
14608 uint64_t CompareLHS = LHSOffset.getQuantity();
14609 uint64_t CompareRHS = RHSOffset.getQuantity();
14610 assert(PtrSize <= 64 && "Unexpected pointer width");
14611 uint64_t Mask = ~0ULL >> (64 - PtrSize);
14612 CompareLHS &= Mask;
14613 CompareRHS &= Mask;
14614
14615 // If there is a base and this is a relational operator, we can only
14616 // compare pointers within the object in question; otherwise, the result
14617 // depends on where the object is located in memory.
14618 if (!LHSValue.Base.isNull() && IsRelational) {
14619 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
14620 if (BaseTy->isIncompleteType())
14621 return Error(E);
14622 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
14623 uint64_t OffsetLimit = Size.getQuantity();
14624 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
14625 return Error(E);
14626 }
14627
14628 if (CompareLHS < CompareRHS)
14629 return Success(CmpResult::Less, E);
14630 if (CompareLHS > CompareRHS)
14631 return Success(CmpResult::Greater, E);
14632 return Success(CmpResult::Equal, E);
14633 }
14634
14635 if (LHSTy->isMemberPointerType()) {
14636 assert(IsEquality && "unexpected member pointer operation");
14637 assert(RHSTy->isMemberPointerType() && "invalid comparison");
14638
14639 MemberPtr LHSValue, RHSValue;
14640
14641 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
14642 if (!LHSOK && !Info.noteFailure())
14643 return false;
14644
14645 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14646 return false;
14647
14648 // If either operand is a pointer to a weak function, the comparison is not
14649 // constant.
14650 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
14651 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14652 << LHSValue.getDecl();
14653 return false;
14654 }
14655 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
14656 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14657 << RHSValue.getDecl();
14658 return false;
14659 }
14660
14661 // C++11 [expr.eq]p2:
14662 // If both operands are null, they compare equal. Otherwise if only one is
14663 // null, they compare unequal.
14664 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
14665 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
14666 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14667 }
14668
14669 // Otherwise if either is a pointer to a virtual member function, the
14670 // result is unspecified.
14671 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
14672 if (MD->isVirtual())
14673 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14674 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
14675 if (MD->isVirtual())
14676 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14677
14678 // Otherwise they compare equal if and only if they would refer to the
14679 // same member of the same most derived object or the same subobject if
14680 // they were dereferenced with a hypothetical object of the associated
14681 // class type.
14682 bool Equal = LHSValue == RHSValue;
14683 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14684 }
14685
14686 if (LHSTy->isNullPtrType()) {
14687 assert(E->isComparisonOp() && "unexpected nullptr operation");
14688 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
14689 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
14690 // are compared, the result is true of the operator is <=, >= or ==, and
14691 // false otherwise.
14692 LValue Res;
14693 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
14694 !EvaluatePointer(E->getRHS(), Res, Info))
14695 return false;
14696 return Success(CmpResult::Equal, E);
14697 }
14698
14699 return DoAfter();
14700 }
14701
VisitBinCmp(const BinaryOperator * E)14702 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
14703 if (!CheckLiteralType(Info, E))
14704 return false;
14705
14706 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14707 ComparisonCategoryResult CCR;
14708 switch (CR) {
14709 case CmpResult::Unequal:
14710 llvm_unreachable("should never produce Unequal for three-way comparison");
14711 case CmpResult::Less:
14712 CCR = ComparisonCategoryResult::Less;
14713 break;
14714 case CmpResult::Equal:
14715 CCR = ComparisonCategoryResult::Equal;
14716 break;
14717 case CmpResult::Greater:
14718 CCR = ComparisonCategoryResult::Greater;
14719 break;
14720 case CmpResult::Unordered:
14721 CCR = ComparisonCategoryResult::Unordered;
14722 break;
14723 }
14724 // Evaluation succeeded. Lookup the information for the comparison category
14725 // type and fetch the VarDecl for the result.
14726 const ComparisonCategoryInfo &CmpInfo =
14727 Info.Ctx.CompCategories.getInfoForType(E->getType());
14728 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
14729 // Check and evaluate the result as a constant expression.
14730 LValue LV;
14731 LV.set(VD);
14732 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14733 return false;
14734 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14735 ConstantExprKind::Normal);
14736 };
14737 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14738 return ExprEvaluatorBaseTy::VisitBinCmp(E);
14739 });
14740 }
14741
VisitCXXParenListInitExpr(const CXXParenListInitExpr * E)14742 bool RecordExprEvaluator::VisitCXXParenListInitExpr(
14743 const CXXParenListInitExpr *E) {
14744 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
14745 }
14746
VisitBinaryOperator(const BinaryOperator * E)14747 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14748 // We don't support assignment in C. C++ assignments don't get here because
14749 // assignment is an lvalue in C++.
14750 if (E->isAssignmentOp()) {
14751 Error(E);
14752 if (!Info.noteFailure())
14753 return false;
14754 }
14755
14756 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
14757 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
14758
14759 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
14760 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
14761 "DataRecursiveIntBinOpEvaluator should have handled integral types");
14762
14763 if (E->isComparisonOp()) {
14764 // Evaluate builtin binary comparisons by evaluating them as three-way
14765 // comparisons and then translating the result.
14766 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14767 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
14768 "should only produce Unequal for equality comparisons");
14769 bool IsEqual = CR == CmpResult::Equal,
14770 IsLess = CR == CmpResult::Less,
14771 IsGreater = CR == CmpResult::Greater;
14772 auto Op = E->getOpcode();
14773 switch (Op) {
14774 default:
14775 llvm_unreachable("unsupported binary operator");
14776 case BO_EQ:
14777 case BO_NE:
14778 return Success(IsEqual == (Op == BO_EQ), E);
14779 case BO_LT:
14780 return Success(IsLess, E);
14781 case BO_GT:
14782 return Success(IsGreater, E);
14783 case BO_LE:
14784 return Success(IsEqual || IsLess, E);
14785 case BO_GE:
14786 return Success(IsEqual || IsGreater, E);
14787 }
14788 };
14789 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14790 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14791 });
14792 }
14793
14794 QualType LHSTy = E->getLHS()->getType();
14795 QualType RHSTy = E->getRHS()->getType();
14796
14797 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
14798 E->getOpcode() == BO_Sub) {
14799 LValue LHSValue, RHSValue;
14800
14801 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14802 if (!LHSOK && !Info.noteFailure())
14803 return false;
14804
14805 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14806 return false;
14807
14808 // Reject differing bases from the normal codepath; we special-case
14809 // comparisons to null.
14810 if (!HasSameBase(LHSValue, RHSValue)) {
14811 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
14812 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
14813
14814 auto DiagArith = [&](unsigned DiagID) {
14815 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
14816 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
14817 Info.FFDiag(E, DiagID) << LHS << RHS;
14818 if (LHSExpr && LHSExpr == RHSExpr)
14819 Info.Note(LHSExpr->getExprLoc(),
14820 diag::note_constexpr_repeated_literal_eval)
14821 << LHSExpr->getSourceRange();
14822 return false;
14823 };
14824
14825 if (!LHSExpr || !RHSExpr)
14826 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
14827
14828 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
14829 return DiagArith(diag::note_constexpr_literal_arith);
14830
14831 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14832 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14833 if (!LHSAddrExpr || !RHSAddrExpr)
14834 return Error(E);
14835 // Make sure both labels come from the same function.
14836 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14837 RHSAddrExpr->getLabel()->getDeclContext())
14838 return Error(E);
14839 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
14840 }
14841 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14842 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14843
14844 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14845 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14846
14847 // C++11 [expr.add]p6:
14848 // Unless both pointers point to elements of the same array object, or
14849 // one past the last element of the array object, the behavior is
14850 // undefined.
14851 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
14852 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
14853 RHSDesignator))
14854 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
14855
14856 QualType Type = E->getLHS()->getType();
14857 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
14858
14859 CharUnits ElementSize;
14860 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
14861 return false;
14862
14863 // As an extension, a type may have zero size (empty struct or union in
14864 // C, array of zero length). Pointer subtraction in such cases has
14865 // undefined behavior, so is not constant.
14866 if (ElementSize.isZero()) {
14867 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
14868 << ElementType;
14869 return false;
14870 }
14871
14872 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
14873 // and produce incorrect results when it overflows. Such behavior
14874 // appears to be non-conforming, but is common, so perhaps we should
14875 // assume the standard intended for such cases to be undefined behavior
14876 // and check for them.
14877
14878 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
14879 // overflow in the final conversion to ptrdiff_t.
14880 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
14881 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
14882 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
14883 false);
14884 APSInt TrueResult = (LHS - RHS) / ElemSize;
14885 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
14886
14887 if (Result.extend(65) != TrueResult &&
14888 !HandleOverflow(Info, E, TrueResult, E->getType()))
14889 return false;
14890 return Success(Result, E);
14891 }
14892
14893 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14894 }
14895
14896 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
14897 /// a result as the expression's type.
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)14898 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
14899 const UnaryExprOrTypeTraitExpr *E) {
14900 switch(E->getKind()) {
14901 case UETT_PreferredAlignOf:
14902 case UETT_AlignOf: {
14903 if (E->isArgumentType())
14904 return Success(
14905 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
14906 else
14907 return Success(
14908 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
14909 }
14910
14911 case UETT_PtrAuthTypeDiscriminator: {
14912 if (E->getArgumentType()->isDependentType())
14913 return false;
14914 return Success(
14915 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
14916 }
14917 case UETT_VecStep: {
14918 QualType Ty = E->getTypeOfArgument();
14919
14920 if (Ty->isVectorType()) {
14921 unsigned n = Ty->castAs<VectorType>()->getNumElements();
14922
14923 // The vec_step built-in functions that take a 3-component
14924 // vector return 4. (OpenCL 1.1 spec 6.11.12)
14925 if (n == 3)
14926 n = 4;
14927
14928 return Success(n, E);
14929 } else
14930 return Success(1, E);
14931 }
14932
14933 case UETT_DataSizeOf:
14934 case UETT_SizeOf: {
14935 QualType SrcTy = E->getTypeOfArgument();
14936 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
14937 // the result is the size of the referenced type."
14938 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
14939 SrcTy = Ref->getPointeeType();
14940
14941 CharUnits Sizeof;
14942 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
14943 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14944 : SizeOfType::SizeOf)) {
14945 return false;
14946 }
14947 return Success(Sizeof, E);
14948 }
14949 case UETT_OpenMPRequiredSimdAlign:
14950 assert(E->isArgumentType());
14951 return Success(
14952 Info.Ctx.toCharUnitsFromBits(
14953 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
14954 .getQuantity(),
14955 E);
14956 case UETT_VectorElements: {
14957 QualType Ty = E->getTypeOfArgument();
14958 // If the vector has a fixed size, we can determine the number of elements
14959 // at compile time.
14960 if (const auto *VT = Ty->getAs<VectorType>())
14961 return Success(VT->getNumElements(), E);
14962
14963 assert(Ty->isSizelessVectorType());
14964 if (Info.InConstantContext)
14965 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
14966 << E->getSourceRange();
14967
14968 return false;
14969 }
14970 case UETT_CountOf: {
14971 QualType Ty = E->getTypeOfArgument();
14972 assert(Ty->isArrayType());
14973
14974 // We don't need to worry about array element qualifiers, so getting the
14975 // unsafe array type is fine.
14976 if (const auto *CAT =
14977 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
14978 return Success(CAT->getSize(), E);
14979 }
14980
14981 assert(!Ty->isConstantSizeType());
14982
14983 // If it's a variable-length array type, we need to check whether it is a
14984 // multidimensional array. If so, we need to check the size expression of
14985 // the VLA to see if it's a constant size. If so, we can return that value.
14986 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
14987 assert(VAT);
14988 if (VAT->getElementType()->isArrayType()) {
14989 std::optional<APSInt> Res =
14990 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
14991 if (Res) {
14992 // The resulting value always has type size_t, so we need to make the
14993 // returned APInt have the correct sign and bit-width.
14994 APInt Val{
14995 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
14996 Res->getZExtValue()};
14997 return Success(Val, E);
14998 }
14999 }
15000
15001 // Definitely a variable-length type, which is not an ICE.
15002 // FIXME: Better diagnostic.
15003 Info.FFDiag(E->getBeginLoc());
15004 return false;
15005 }
15006 }
15007
15008 llvm_unreachable("unknown expr/type trait");
15009 }
15010
VisitOffsetOfExpr(const OffsetOfExpr * OOE)15011 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
15012 CharUnits Result;
15013 unsigned n = OOE->getNumComponents();
15014 if (n == 0)
15015 return Error(OOE);
15016 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
15017 for (unsigned i = 0; i != n; ++i) {
15018 OffsetOfNode ON = OOE->getComponent(i);
15019 switch (ON.getKind()) {
15020 case OffsetOfNode::Array: {
15021 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
15022 APSInt IdxResult;
15023 if (!EvaluateInteger(Idx, IdxResult, Info))
15024 return false;
15025 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
15026 if (!AT)
15027 return Error(OOE);
15028 CurrentType = AT->getElementType();
15029 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
15030 Result += IdxResult.getSExtValue() * ElementSize;
15031 break;
15032 }
15033
15034 case OffsetOfNode::Field: {
15035 FieldDecl *MemberDecl = ON.getField();
15036 const RecordType *RT = CurrentType->getAs<RecordType>();
15037 if (!RT)
15038 return Error(OOE);
15039 RecordDecl *RD = RT->getDecl();
15040 if (RD->isInvalidDecl()) return false;
15041 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
15042 unsigned i = MemberDecl->getFieldIndex();
15043 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
15044 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
15045 CurrentType = MemberDecl->getType().getNonReferenceType();
15046 break;
15047 }
15048
15049 case OffsetOfNode::Identifier:
15050 llvm_unreachable("dependent __builtin_offsetof");
15051
15052 case OffsetOfNode::Base: {
15053 CXXBaseSpecifier *BaseSpec = ON.getBase();
15054 if (BaseSpec->isVirtual())
15055 return Error(OOE);
15056
15057 // Find the layout of the class whose base we are looking into.
15058 const RecordType *RT = CurrentType->getAs<RecordType>();
15059 if (!RT)
15060 return Error(OOE);
15061 RecordDecl *RD = RT->getDecl();
15062 if (RD->isInvalidDecl()) return false;
15063 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
15064
15065 // Find the base class itself.
15066 CurrentType = BaseSpec->getType();
15067 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
15068 if (!BaseRT)
15069 return Error(OOE);
15070
15071 // Add the offset to the base.
15072 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
15073 break;
15074 }
15075 }
15076 }
15077 return Success(Result, OOE);
15078 }
15079
VisitUnaryOperator(const UnaryOperator * E)15080 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15081 switch (E->getOpcode()) {
15082 default:
15083 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
15084 // See C99 6.6p3.
15085 return Error(E);
15086 case UO_Extension:
15087 // FIXME: Should extension allow i-c-e extension expressions in its scope?
15088 // If so, we could clear the diagnostic ID.
15089 return Visit(E->getSubExpr());
15090 case UO_Plus:
15091 // The result is just the value.
15092 return Visit(E->getSubExpr());
15093 case UO_Minus: {
15094 if (!Visit(E->getSubExpr()))
15095 return false;
15096 if (!Result.isInt()) return Error(E);
15097 const APSInt &Value = Result.getInt();
15098 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
15099 if (Info.checkingForUndefinedBehavior())
15100 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15101 diag::warn_integer_constant_overflow)
15102 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
15103 /*UpperCase=*/true, /*InsertSeparators=*/true)
15104 << E->getType() << E->getSourceRange();
15105
15106 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
15107 E->getType()))
15108 return false;
15109 }
15110 return Success(-Value, E);
15111 }
15112 case UO_Not: {
15113 if (!Visit(E->getSubExpr()))
15114 return false;
15115 if (!Result.isInt()) return Error(E);
15116 return Success(~Result.getInt(), E);
15117 }
15118 case UO_LNot: {
15119 bool bres;
15120 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15121 return false;
15122 return Success(!bres, E);
15123 }
15124 }
15125 }
15126
15127 /// HandleCast - This is used to evaluate implicit or explicit casts where the
15128 /// result type is integer.
VisitCastExpr(const CastExpr * E)15129 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
15130 const Expr *SubExpr = E->getSubExpr();
15131 QualType DestType = E->getType();
15132 QualType SrcType = SubExpr->getType();
15133
15134 switch (E->getCastKind()) {
15135 case CK_BaseToDerived:
15136 case CK_DerivedToBase:
15137 case CK_UncheckedDerivedToBase:
15138 case CK_Dynamic:
15139 case CK_ToUnion:
15140 case CK_ArrayToPointerDecay:
15141 case CK_FunctionToPointerDecay:
15142 case CK_NullToPointer:
15143 case CK_NullToMemberPointer:
15144 case CK_BaseToDerivedMemberPointer:
15145 case CK_DerivedToBaseMemberPointer:
15146 case CK_ReinterpretMemberPointer:
15147 case CK_ConstructorConversion:
15148 case CK_IntegralToPointer:
15149 case CK_ToVoid:
15150 case CK_VectorSplat:
15151 case CK_IntegralToFloating:
15152 case CK_FloatingCast:
15153 case CK_CPointerToObjCPointerCast:
15154 case CK_BlockPointerToObjCPointerCast:
15155 case CK_AnyPointerToBlockPointerCast:
15156 case CK_ObjCObjectLValueCast:
15157 case CK_FloatingRealToComplex:
15158 case CK_FloatingComplexToReal:
15159 case CK_FloatingComplexCast:
15160 case CK_FloatingComplexToIntegralComplex:
15161 case CK_IntegralRealToComplex:
15162 case CK_IntegralComplexCast:
15163 case CK_IntegralComplexToFloatingComplex:
15164 case CK_BuiltinFnToFnPtr:
15165 case CK_ZeroToOCLOpaqueType:
15166 case CK_NonAtomicToAtomic:
15167 case CK_AddressSpaceConversion:
15168 case CK_IntToOCLSampler:
15169 case CK_FloatingToFixedPoint:
15170 case CK_FixedPointToFloating:
15171 case CK_FixedPointCast:
15172 case CK_IntegralToFixedPoint:
15173 case CK_MatrixCast:
15174 case CK_HLSLAggregateSplatCast:
15175 llvm_unreachable("invalid cast kind for integral value");
15176
15177 case CK_BitCast:
15178 case CK_Dependent:
15179 case CK_LValueBitCast:
15180 case CK_ARCProduceObject:
15181 case CK_ARCConsumeObject:
15182 case CK_ARCReclaimReturnedObject:
15183 case CK_ARCExtendBlockObject:
15184 case CK_CopyAndAutoreleaseBlockObject:
15185 return Error(E);
15186
15187 case CK_UserDefinedConversion:
15188 case CK_LValueToRValue:
15189 case CK_AtomicToNonAtomic:
15190 case CK_NoOp:
15191 case CK_LValueToRValueBitCast:
15192 case CK_HLSLArrayRValue:
15193 case CK_HLSLElementwiseCast:
15194 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15195
15196 case CK_MemberPointerToBoolean:
15197 case CK_PointerToBoolean:
15198 case CK_IntegralToBoolean:
15199 case CK_FloatingToBoolean:
15200 case CK_BooleanToSignedIntegral:
15201 case CK_FloatingComplexToBoolean:
15202 case CK_IntegralComplexToBoolean: {
15203 bool BoolResult;
15204 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
15205 return false;
15206 uint64_t IntResult = BoolResult;
15207 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
15208 IntResult = (uint64_t)-1;
15209 return Success(IntResult, E);
15210 }
15211
15212 case CK_FixedPointToIntegral: {
15213 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
15214 if (!EvaluateFixedPoint(SubExpr, Src, Info))
15215 return false;
15216 bool Overflowed;
15217 llvm::APSInt Result = Src.convertToInt(
15218 Info.Ctx.getIntWidth(DestType),
15219 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
15220 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
15221 return false;
15222 return Success(Result, E);
15223 }
15224
15225 case CK_FixedPointToBoolean: {
15226 // Unsigned padding does not affect this.
15227 APValue Val;
15228 if (!Evaluate(Val, Info, SubExpr))
15229 return false;
15230 return Success(Val.getFixedPoint().getBoolValue(), E);
15231 }
15232
15233 case CK_IntegralCast: {
15234 if (!Visit(SubExpr))
15235 return false;
15236
15237 if (!Result.isInt()) {
15238 // Allow casts of address-of-label differences if they are no-ops
15239 // or narrowing. (The narrowing case isn't actually guaranteed to
15240 // be constant-evaluatable except in some narrow cases which are hard
15241 // to detect here. We let it through on the assumption the user knows
15242 // what they are doing.)
15243 if (Result.isAddrLabelDiff())
15244 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
15245 // Only allow casts of lvalues if they are lossless.
15246 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
15247 }
15248
15249 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
15250 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
15251 const EnumDecl *ED = ET->getDecl();
15252 // Check that the value is within the range of the enumeration values.
15253 //
15254 // This corressponds to [expr.static.cast]p10 which says:
15255 // A value of integral or enumeration type can be explicitly converted
15256 // to a complete enumeration type ... If the enumeration type does not
15257 // have a fixed underlying type, the value is unchanged if the original
15258 // value is within the range of the enumeration values ([dcl.enum]), and
15259 // otherwise, the behavior is undefined.
15260 //
15261 // This was resolved as part of DR2338 which has CD5 status.
15262 if (!ED->isFixed()) {
15263 llvm::APInt Min;
15264 llvm::APInt Max;
15265
15266 ED->getValueRange(Max, Min);
15267 --Max;
15268
15269 if (ED->getNumNegativeBits() &&
15270 (Max.slt(Result.getInt().getSExtValue()) ||
15271 Min.sgt(Result.getInt().getSExtValue())))
15272 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15273 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
15274 << Max.getSExtValue() << ED;
15275 else if (!ED->getNumNegativeBits() &&
15276 Max.ult(Result.getInt().getZExtValue()))
15277 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15278 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
15279 << Max.getZExtValue() << ED;
15280 }
15281 }
15282
15283 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
15284 Result.getInt()), E);
15285 }
15286
15287 case CK_PointerToIntegral: {
15288 CCEDiag(E, diag::note_constexpr_invalid_cast)
15289 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
15290 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
15291
15292 LValue LV;
15293 if (!EvaluatePointer(SubExpr, LV, Info))
15294 return false;
15295
15296 if (LV.getLValueBase()) {
15297 // Only allow based lvalue casts if they are lossless.
15298 // FIXME: Allow a larger integer size than the pointer size, and allow
15299 // narrowing back down to pointer width in subsequent integral casts.
15300 // FIXME: Check integer type's active bits, not its type size.
15301 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
15302 return Error(E);
15303
15304 LV.Designator.setInvalid();
15305 LV.moveInto(Result);
15306 return true;
15307 }
15308
15309 APSInt AsInt;
15310 APValue V;
15311 LV.moveInto(V);
15312 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
15313 llvm_unreachable("Can't cast this!");
15314
15315 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
15316 }
15317
15318 case CK_IntegralComplexToReal: {
15319 ComplexValue C;
15320 if (!EvaluateComplex(SubExpr, C, Info))
15321 return false;
15322 return Success(C.getComplexIntReal(), E);
15323 }
15324
15325 case CK_FloatingToIntegral: {
15326 APFloat F(0.0);
15327 if (!EvaluateFloat(SubExpr, F, Info))
15328 return false;
15329
15330 APSInt Value;
15331 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
15332 return false;
15333 return Success(Value, E);
15334 }
15335 case CK_HLSLVectorTruncation: {
15336 APValue Val;
15337 if (!EvaluateVector(SubExpr, Val, Info))
15338 return Error(E);
15339 return Success(Val.getVectorElt(0), E);
15340 }
15341 }
15342
15343 llvm_unreachable("unknown cast resulting in integral value");
15344 }
15345
VisitUnaryReal(const UnaryOperator * E)15346 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15347 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15348 ComplexValue LV;
15349 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15350 return false;
15351 if (!LV.isComplexInt())
15352 return Error(E);
15353 return Success(LV.getComplexIntReal(), E);
15354 }
15355
15356 return Visit(E->getSubExpr());
15357 }
15358
VisitUnaryImag(const UnaryOperator * E)15359 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15360 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
15361 ComplexValue LV;
15362 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15363 return false;
15364 if (!LV.isComplexInt())
15365 return Error(E);
15366 return Success(LV.getComplexIntImag(), E);
15367 }
15368
15369 VisitIgnoredValue(E->getSubExpr());
15370 return Success(0, E);
15371 }
15372
VisitSizeOfPackExpr(const SizeOfPackExpr * E)15373 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
15374 return Success(E->getPackLength(), E);
15375 }
15376
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)15377 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
15378 return Success(E->getValue(), E);
15379 }
15380
VisitConceptSpecializationExpr(const ConceptSpecializationExpr * E)15381 bool IntExprEvaluator::VisitConceptSpecializationExpr(
15382 const ConceptSpecializationExpr *E) {
15383 return Success(E->isSatisfied(), E);
15384 }
15385
VisitRequiresExpr(const RequiresExpr * E)15386 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
15387 return Success(E->isSatisfied(), E);
15388 }
15389
VisitUnaryOperator(const UnaryOperator * E)15390 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15391 switch (E->getOpcode()) {
15392 default:
15393 // Invalid unary operators
15394 return Error(E);
15395 case UO_Plus:
15396 // The result is just the value.
15397 return Visit(E->getSubExpr());
15398 case UO_Minus: {
15399 if (!Visit(E->getSubExpr())) return false;
15400 if (!Result.isFixedPoint())
15401 return Error(E);
15402 bool Overflowed;
15403 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
15404 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
15405 return false;
15406 return Success(Negated, E);
15407 }
15408 case UO_LNot: {
15409 bool bres;
15410 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15411 return false;
15412 return Success(!bres, E);
15413 }
15414 }
15415 }
15416
VisitCastExpr(const CastExpr * E)15417 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
15418 const Expr *SubExpr = E->getSubExpr();
15419 QualType DestType = E->getType();
15420 assert(DestType->isFixedPointType() &&
15421 "Expected destination type to be a fixed point type");
15422 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
15423
15424 switch (E->getCastKind()) {
15425 case CK_FixedPointCast: {
15426 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15427 if (!EvaluateFixedPoint(SubExpr, Src, Info))
15428 return false;
15429 bool Overflowed;
15430 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
15431 if (Overflowed) {
15432 if (Info.checkingForUndefinedBehavior())
15433 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15434 diag::warn_fixedpoint_constant_overflow)
15435 << Result.toString() << E->getType();
15436 if (!HandleOverflow(Info, E, Result, E->getType()))
15437 return false;
15438 }
15439 return Success(Result, E);
15440 }
15441 case CK_IntegralToFixedPoint: {
15442 APSInt Src;
15443 if (!EvaluateInteger(SubExpr, Src, Info))
15444 return false;
15445
15446 bool Overflowed;
15447 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
15448 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15449
15450 if (Overflowed) {
15451 if (Info.checkingForUndefinedBehavior())
15452 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15453 diag::warn_fixedpoint_constant_overflow)
15454 << IntResult.toString() << E->getType();
15455 if (!HandleOverflow(Info, E, IntResult, E->getType()))
15456 return false;
15457 }
15458
15459 return Success(IntResult, E);
15460 }
15461 case CK_FloatingToFixedPoint: {
15462 APFloat Src(0.0);
15463 if (!EvaluateFloat(SubExpr, Src, Info))
15464 return false;
15465
15466 bool Overflowed;
15467 APFixedPoint Result = APFixedPoint::getFromFloatValue(
15468 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15469
15470 if (Overflowed) {
15471 if (Info.checkingForUndefinedBehavior())
15472 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15473 diag::warn_fixedpoint_constant_overflow)
15474 << Result.toString() << E->getType();
15475 if (!HandleOverflow(Info, E, Result, E->getType()))
15476 return false;
15477 }
15478
15479 return Success(Result, E);
15480 }
15481 case CK_NoOp:
15482 case CK_LValueToRValue:
15483 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15484 default:
15485 return Error(E);
15486 }
15487 }
15488
VisitBinaryOperator(const BinaryOperator * E)15489 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15490 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15491 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15492
15493 const Expr *LHS = E->getLHS();
15494 const Expr *RHS = E->getRHS();
15495 FixedPointSemantics ResultFXSema =
15496 Info.Ctx.getFixedPointSemantics(E->getType());
15497
15498 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
15499 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
15500 return false;
15501 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
15502 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
15503 return false;
15504
15505 bool OpOverflow = false, ConversionOverflow = false;
15506 APFixedPoint Result(LHSFX.getSemantics());
15507 switch (E->getOpcode()) {
15508 case BO_Add: {
15509 Result = LHSFX.add(RHSFX, &OpOverflow)
15510 .convert(ResultFXSema, &ConversionOverflow);
15511 break;
15512 }
15513 case BO_Sub: {
15514 Result = LHSFX.sub(RHSFX, &OpOverflow)
15515 .convert(ResultFXSema, &ConversionOverflow);
15516 break;
15517 }
15518 case BO_Mul: {
15519 Result = LHSFX.mul(RHSFX, &OpOverflow)
15520 .convert(ResultFXSema, &ConversionOverflow);
15521 break;
15522 }
15523 case BO_Div: {
15524 if (RHSFX.getValue() == 0) {
15525 Info.FFDiag(E, diag::note_expr_divide_by_zero);
15526 return false;
15527 }
15528 Result = LHSFX.div(RHSFX, &OpOverflow)
15529 .convert(ResultFXSema, &ConversionOverflow);
15530 break;
15531 }
15532 case BO_Shl:
15533 case BO_Shr: {
15534 FixedPointSemantics LHSSema = LHSFX.getSemantics();
15535 llvm::APSInt RHSVal = RHSFX.getValue();
15536
15537 unsigned ShiftBW =
15538 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
15539 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
15540 // Embedded-C 4.1.6.2.2:
15541 // The right operand must be nonnegative and less than the total number
15542 // of (nonpadding) bits of the fixed-point operand ...
15543 if (RHSVal.isNegative())
15544 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
15545 else if (Amt != RHSVal)
15546 Info.CCEDiag(E, diag::note_constexpr_large_shift)
15547 << RHSVal << E->getType() << ShiftBW;
15548
15549 if (E->getOpcode() == BO_Shl)
15550 Result = LHSFX.shl(Amt, &OpOverflow);
15551 else
15552 Result = LHSFX.shr(Amt, &OpOverflow);
15553 break;
15554 }
15555 default:
15556 return false;
15557 }
15558 if (OpOverflow || ConversionOverflow) {
15559 if (Info.checkingForUndefinedBehavior())
15560 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15561 diag::warn_fixedpoint_constant_overflow)
15562 << Result.toString() << E->getType();
15563 if (!HandleOverflow(Info, E, Result, E->getType()))
15564 return false;
15565 }
15566 return Success(Result, E);
15567 }
15568
15569 //===----------------------------------------------------------------------===//
15570 // Float Evaluation
15571 //===----------------------------------------------------------------------===//
15572
15573 namespace {
15574 class FloatExprEvaluator
15575 : public ExprEvaluatorBase<FloatExprEvaluator> {
15576 APFloat &Result;
15577 public:
FloatExprEvaluator(EvalInfo & info,APFloat & result)15578 FloatExprEvaluator(EvalInfo &info, APFloat &result)
15579 : ExprEvaluatorBaseTy(info), Result(result) {}
15580
Success(const APValue & V,const Expr * e)15581 bool Success(const APValue &V, const Expr *e) {
15582 Result = V.getFloat();
15583 return true;
15584 }
15585
ZeroInitialization(const Expr * E)15586 bool ZeroInitialization(const Expr *E) {
15587 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
15588 return true;
15589 }
15590
15591 bool VisitCallExpr(const CallExpr *E);
15592
15593 bool VisitUnaryOperator(const UnaryOperator *E);
15594 bool VisitBinaryOperator(const BinaryOperator *E);
15595 bool VisitFloatingLiteral(const FloatingLiteral *E);
15596 bool VisitCastExpr(const CastExpr *E);
15597
15598 bool VisitUnaryReal(const UnaryOperator *E);
15599 bool VisitUnaryImag(const UnaryOperator *E);
15600
15601 // FIXME: Missing: array subscript of vector, member of vector
15602 };
15603 } // end anonymous namespace
15604
EvaluateFloat(const Expr * E,APFloat & Result,EvalInfo & Info)15605 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
15606 assert(!E->isValueDependent());
15607 assert(E->isPRValue() && E->getType()->isRealFloatingType());
15608 return FloatExprEvaluator(Info, Result).Visit(E);
15609 }
15610
TryEvaluateBuiltinNaN(const ASTContext & Context,QualType ResultTy,const Expr * Arg,bool SNaN,llvm::APFloat & Result)15611 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
15612 QualType ResultTy,
15613 const Expr *Arg,
15614 bool SNaN,
15615 llvm::APFloat &Result) {
15616 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
15617 if (!S) return false;
15618
15619 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
15620
15621 llvm::APInt fill;
15622
15623 // Treat empty strings as if they were zero.
15624 if (S->getString().empty())
15625 fill = llvm::APInt(32, 0);
15626 else if (S->getString().getAsInteger(0, fill))
15627 return false;
15628
15629 if (Context.getTargetInfo().isNan2008()) {
15630 if (SNaN)
15631 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15632 else
15633 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15634 } else {
15635 // Prior to IEEE 754-2008, architectures were allowed to choose whether
15636 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
15637 // a different encoding to what became a standard in 2008, and for pre-
15638 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
15639 // sNaN. This is now known as "legacy NaN" encoding.
15640 if (SNaN)
15641 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15642 else
15643 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15644 }
15645
15646 return true;
15647 }
15648
VisitCallExpr(const CallExpr * E)15649 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
15650 if (!IsConstantEvaluatedBuiltinCall(E))
15651 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15652
15653 switch (E->getBuiltinCallee()) {
15654 default:
15655 return false;
15656
15657 case Builtin::BI__builtin_huge_val:
15658 case Builtin::BI__builtin_huge_valf:
15659 case Builtin::BI__builtin_huge_vall:
15660 case Builtin::BI__builtin_huge_valf16:
15661 case Builtin::BI__builtin_huge_valf128:
15662 case Builtin::BI__builtin_inf:
15663 case Builtin::BI__builtin_inff:
15664 case Builtin::BI__builtin_infl:
15665 case Builtin::BI__builtin_inff16:
15666 case Builtin::BI__builtin_inff128: {
15667 const llvm::fltSemantics &Sem =
15668 Info.Ctx.getFloatTypeSemantics(E->getType());
15669 Result = llvm::APFloat::getInf(Sem);
15670 return true;
15671 }
15672
15673 case Builtin::BI__builtin_nans:
15674 case Builtin::BI__builtin_nansf:
15675 case Builtin::BI__builtin_nansl:
15676 case Builtin::BI__builtin_nansf16:
15677 case Builtin::BI__builtin_nansf128:
15678 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15679 true, Result))
15680 return Error(E);
15681 return true;
15682
15683 case Builtin::BI__builtin_nan:
15684 case Builtin::BI__builtin_nanf:
15685 case Builtin::BI__builtin_nanl:
15686 case Builtin::BI__builtin_nanf16:
15687 case Builtin::BI__builtin_nanf128:
15688 // If this is __builtin_nan() turn this into a nan, otherwise we
15689 // can't constant fold it.
15690 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15691 false, Result))
15692 return Error(E);
15693 return true;
15694
15695 case Builtin::BI__builtin_fabs:
15696 case Builtin::BI__builtin_fabsf:
15697 case Builtin::BI__builtin_fabsl:
15698 case Builtin::BI__builtin_fabsf128:
15699 // The C standard says "fabs raises no floating-point exceptions,
15700 // even if x is a signaling NaN. The returned value is independent of
15701 // the current rounding direction mode." Therefore constant folding can
15702 // proceed without regard to the floating point settings.
15703 // Reference, WG14 N2478 F.10.4.3
15704 if (!EvaluateFloat(E->getArg(0), Result, Info))
15705 return false;
15706
15707 if (Result.isNegative())
15708 Result.changeSign();
15709 return true;
15710
15711 case Builtin::BI__arithmetic_fence:
15712 return EvaluateFloat(E->getArg(0), Result, Info);
15713
15714 // FIXME: Builtin::BI__builtin_powi
15715 // FIXME: Builtin::BI__builtin_powif
15716 // FIXME: Builtin::BI__builtin_powil
15717
15718 case Builtin::BI__builtin_copysign:
15719 case Builtin::BI__builtin_copysignf:
15720 case Builtin::BI__builtin_copysignl:
15721 case Builtin::BI__builtin_copysignf128: {
15722 APFloat RHS(0.);
15723 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15724 !EvaluateFloat(E->getArg(1), RHS, Info))
15725 return false;
15726 Result.copySign(RHS);
15727 return true;
15728 }
15729
15730 case Builtin::BI__builtin_fmax:
15731 case Builtin::BI__builtin_fmaxf:
15732 case Builtin::BI__builtin_fmaxl:
15733 case Builtin::BI__builtin_fmaxf16:
15734 case Builtin::BI__builtin_fmaxf128: {
15735 APFloat RHS(0.);
15736 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15737 !EvaluateFloat(E->getArg(1), RHS, Info))
15738 return false;
15739 Result = maxnum(Result, RHS);
15740 return true;
15741 }
15742
15743 case Builtin::BI__builtin_fmin:
15744 case Builtin::BI__builtin_fminf:
15745 case Builtin::BI__builtin_fminl:
15746 case Builtin::BI__builtin_fminf16:
15747 case Builtin::BI__builtin_fminf128: {
15748 APFloat RHS(0.);
15749 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15750 !EvaluateFloat(E->getArg(1), RHS, Info))
15751 return false;
15752 Result = minnum(Result, RHS);
15753 return true;
15754 }
15755
15756 case Builtin::BI__builtin_fmaximum_num:
15757 case Builtin::BI__builtin_fmaximum_numf:
15758 case Builtin::BI__builtin_fmaximum_numl:
15759 case Builtin::BI__builtin_fmaximum_numf16:
15760 case Builtin::BI__builtin_fmaximum_numf128: {
15761 APFloat RHS(0.);
15762 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15763 !EvaluateFloat(E->getArg(1), RHS, Info))
15764 return false;
15765 Result = maximumnum(Result, RHS);
15766 return true;
15767 }
15768
15769 case Builtin::BI__builtin_fminimum_num:
15770 case Builtin::BI__builtin_fminimum_numf:
15771 case Builtin::BI__builtin_fminimum_numl:
15772 case Builtin::BI__builtin_fminimum_numf16:
15773 case Builtin::BI__builtin_fminimum_numf128: {
15774 APFloat RHS(0.);
15775 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15776 !EvaluateFloat(E->getArg(1), RHS, Info))
15777 return false;
15778 Result = minimumnum(Result, RHS);
15779 return true;
15780 }
15781 }
15782 }
15783
VisitUnaryReal(const UnaryOperator * E)15784 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15785 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15786 ComplexValue CV;
15787 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15788 return false;
15789 Result = CV.FloatReal;
15790 return true;
15791 }
15792
15793 return Visit(E->getSubExpr());
15794 }
15795
VisitUnaryImag(const UnaryOperator * E)15796 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15797 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15798 ComplexValue CV;
15799 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15800 return false;
15801 Result = CV.FloatImag;
15802 return true;
15803 }
15804
15805 VisitIgnoredValue(E->getSubExpr());
15806 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
15807 Result = llvm::APFloat::getZero(Sem);
15808 return true;
15809 }
15810
VisitUnaryOperator(const UnaryOperator * E)15811 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15812 switch (E->getOpcode()) {
15813 default: return Error(E);
15814 case UO_Plus:
15815 return EvaluateFloat(E->getSubExpr(), Result, Info);
15816 case UO_Minus:
15817 // In C standard, WG14 N2478 F.3 p4
15818 // "the unary - raises no floating point exceptions,
15819 // even if the operand is signalling."
15820 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
15821 return false;
15822 Result.changeSign();
15823 return true;
15824 }
15825 }
15826
VisitBinaryOperator(const BinaryOperator * E)15827 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15828 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15829 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15830
15831 APFloat RHS(0.0);
15832 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
15833 if (!LHSOK && !Info.noteFailure())
15834 return false;
15835 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
15836 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
15837 }
15838
VisitFloatingLiteral(const FloatingLiteral * E)15839 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
15840 Result = E->getValue();
15841 return true;
15842 }
15843
VisitCastExpr(const CastExpr * E)15844 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
15845 const Expr* SubExpr = E->getSubExpr();
15846
15847 switch (E->getCastKind()) {
15848 default:
15849 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15850
15851 case CK_IntegralToFloating: {
15852 APSInt IntResult;
15853 const FPOptions FPO = E->getFPFeaturesInEffect(
15854 Info.Ctx.getLangOpts());
15855 return EvaluateInteger(SubExpr, IntResult, Info) &&
15856 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
15857 IntResult, E->getType(), Result);
15858 }
15859
15860 case CK_FixedPointToFloating: {
15861 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15862 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
15863 return false;
15864 Result =
15865 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
15866 return true;
15867 }
15868
15869 case CK_FloatingCast: {
15870 if (!Visit(SubExpr))
15871 return false;
15872 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
15873 Result);
15874 }
15875
15876 case CK_FloatingComplexToReal: {
15877 ComplexValue V;
15878 if (!EvaluateComplex(SubExpr, V, Info))
15879 return false;
15880 Result = V.getComplexFloatReal();
15881 return true;
15882 }
15883 case CK_HLSLVectorTruncation: {
15884 APValue Val;
15885 if (!EvaluateVector(SubExpr, Val, Info))
15886 return Error(E);
15887 return Success(Val.getVectorElt(0), E);
15888 }
15889 }
15890 }
15891
15892 //===----------------------------------------------------------------------===//
15893 // Complex Evaluation (for float and integer)
15894 //===----------------------------------------------------------------------===//
15895
15896 namespace {
15897 class ComplexExprEvaluator
15898 : public ExprEvaluatorBase<ComplexExprEvaluator> {
15899 ComplexValue &Result;
15900
15901 public:
ComplexExprEvaluator(EvalInfo & info,ComplexValue & Result)15902 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
15903 : ExprEvaluatorBaseTy(info), Result(Result) {}
15904
Success(const APValue & V,const Expr * e)15905 bool Success(const APValue &V, const Expr *e) {
15906 Result.setFrom(V);
15907 return true;
15908 }
15909
15910 bool ZeroInitialization(const Expr *E);
15911
15912 //===--------------------------------------------------------------------===//
15913 // Visitor Methods
15914 //===--------------------------------------------------------------------===//
15915
15916 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
15917 bool VisitCastExpr(const CastExpr *E);
15918 bool VisitBinaryOperator(const BinaryOperator *E);
15919 bool VisitUnaryOperator(const UnaryOperator *E);
15920 bool VisitInitListExpr(const InitListExpr *E);
15921 bool VisitCallExpr(const CallExpr *E);
15922 };
15923 } // end anonymous namespace
15924
EvaluateComplex(const Expr * E,ComplexValue & Result,EvalInfo & Info)15925 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
15926 EvalInfo &Info) {
15927 assert(!E->isValueDependent());
15928 assert(E->isPRValue() && E->getType()->isAnyComplexType());
15929 return ComplexExprEvaluator(Info, Result).Visit(E);
15930 }
15931
ZeroInitialization(const Expr * E)15932 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
15933 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
15934 if (ElemTy->isRealFloatingType()) {
15935 Result.makeComplexFloat();
15936 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
15937 Result.FloatReal = Zero;
15938 Result.FloatImag = Zero;
15939 } else {
15940 Result.makeComplexInt();
15941 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
15942 Result.IntReal = Zero;
15943 Result.IntImag = Zero;
15944 }
15945 return true;
15946 }
15947
VisitImaginaryLiteral(const ImaginaryLiteral * E)15948 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
15949 const Expr* SubExpr = E->getSubExpr();
15950
15951 if (SubExpr->getType()->isRealFloatingType()) {
15952 Result.makeComplexFloat();
15953 APFloat &Imag = Result.FloatImag;
15954 if (!EvaluateFloat(SubExpr, Imag, Info))
15955 return false;
15956
15957 Result.FloatReal = APFloat(Imag.getSemantics());
15958 return true;
15959 } else {
15960 assert(SubExpr->getType()->isIntegerType() &&
15961 "Unexpected imaginary literal.");
15962
15963 Result.makeComplexInt();
15964 APSInt &Imag = Result.IntImag;
15965 if (!EvaluateInteger(SubExpr, Imag, Info))
15966 return false;
15967
15968 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
15969 return true;
15970 }
15971 }
15972
VisitCastExpr(const CastExpr * E)15973 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
15974
15975 switch (E->getCastKind()) {
15976 case CK_BitCast:
15977 case CK_BaseToDerived:
15978 case CK_DerivedToBase:
15979 case CK_UncheckedDerivedToBase:
15980 case CK_Dynamic:
15981 case CK_ToUnion:
15982 case CK_ArrayToPointerDecay:
15983 case CK_FunctionToPointerDecay:
15984 case CK_NullToPointer:
15985 case CK_NullToMemberPointer:
15986 case CK_BaseToDerivedMemberPointer:
15987 case CK_DerivedToBaseMemberPointer:
15988 case CK_MemberPointerToBoolean:
15989 case CK_ReinterpretMemberPointer:
15990 case CK_ConstructorConversion:
15991 case CK_IntegralToPointer:
15992 case CK_PointerToIntegral:
15993 case CK_PointerToBoolean:
15994 case CK_ToVoid:
15995 case CK_VectorSplat:
15996 case CK_IntegralCast:
15997 case CK_BooleanToSignedIntegral:
15998 case CK_IntegralToBoolean:
15999 case CK_IntegralToFloating:
16000 case CK_FloatingToIntegral:
16001 case CK_FloatingToBoolean:
16002 case CK_FloatingCast:
16003 case CK_CPointerToObjCPointerCast:
16004 case CK_BlockPointerToObjCPointerCast:
16005 case CK_AnyPointerToBlockPointerCast:
16006 case CK_ObjCObjectLValueCast:
16007 case CK_FloatingComplexToReal:
16008 case CK_FloatingComplexToBoolean:
16009 case CK_IntegralComplexToReal:
16010 case CK_IntegralComplexToBoolean:
16011 case CK_ARCProduceObject:
16012 case CK_ARCConsumeObject:
16013 case CK_ARCReclaimReturnedObject:
16014 case CK_ARCExtendBlockObject:
16015 case CK_CopyAndAutoreleaseBlockObject:
16016 case CK_BuiltinFnToFnPtr:
16017 case CK_ZeroToOCLOpaqueType:
16018 case CK_NonAtomicToAtomic:
16019 case CK_AddressSpaceConversion:
16020 case CK_IntToOCLSampler:
16021 case CK_FloatingToFixedPoint:
16022 case CK_FixedPointToFloating:
16023 case CK_FixedPointCast:
16024 case CK_FixedPointToBoolean:
16025 case CK_FixedPointToIntegral:
16026 case CK_IntegralToFixedPoint:
16027 case CK_MatrixCast:
16028 case CK_HLSLVectorTruncation:
16029 case CK_HLSLElementwiseCast:
16030 case CK_HLSLAggregateSplatCast:
16031 llvm_unreachable("invalid cast kind for complex value");
16032
16033 case CK_LValueToRValue:
16034 case CK_AtomicToNonAtomic:
16035 case CK_NoOp:
16036 case CK_LValueToRValueBitCast:
16037 case CK_HLSLArrayRValue:
16038 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16039
16040 case CK_Dependent:
16041 case CK_LValueBitCast:
16042 case CK_UserDefinedConversion:
16043 return Error(E);
16044
16045 case CK_FloatingRealToComplex: {
16046 APFloat &Real = Result.FloatReal;
16047 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
16048 return false;
16049
16050 Result.makeComplexFloat();
16051 Result.FloatImag = APFloat(Real.getSemantics());
16052 return true;
16053 }
16054
16055 case CK_FloatingComplexCast: {
16056 if (!Visit(E->getSubExpr()))
16057 return false;
16058
16059 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16060 QualType From
16061 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16062
16063 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
16064 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
16065 }
16066
16067 case CK_FloatingComplexToIntegralComplex: {
16068 if (!Visit(E->getSubExpr()))
16069 return false;
16070
16071 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16072 QualType From
16073 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16074 Result.makeComplexInt();
16075 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
16076 To, Result.IntReal) &&
16077 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
16078 To, Result.IntImag);
16079 }
16080
16081 case CK_IntegralRealToComplex: {
16082 APSInt &Real = Result.IntReal;
16083 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
16084 return false;
16085
16086 Result.makeComplexInt();
16087 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
16088 return true;
16089 }
16090
16091 case CK_IntegralComplexCast: {
16092 if (!Visit(E->getSubExpr()))
16093 return false;
16094
16095 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16096 QualType From
16097 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16098
16099 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
16100 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
16101 return true;
16102 }
16103
16104 case CK_IntegralComplexToFloatingComplex: {
16105 if (!Visit(E->getSubExpr()))
16106 return false;
16107
16108 const FPOptions FPO = E->getFPFeaturesInEffect(
16109 Info.Ctx.getLangOpts());
16110 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16111 QualType From
16112 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16113 Result.makeComplexFloat();
16114 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
16115 To, Result.FloatReal) &&
16116 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
16117 To, Result.FloatImag);
16118 }
16119 }
16120
16121 llvm_unreachable("unknown cast resulting in complex value");
16122 }
16123
HandleComplexComplexMul(APFloat A,APFloat B,APFloat C,APFloat D,APFloat & ResR,APFloat & ResI)16124 void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
16125 APFloat &ResR, APFloat &ResI) {
16126 // This is an implementation of complex multiplication according to the
16127 // constraints laid out in C11 Annex G. The implementation uses the
16128 // following naming scheme:
16129 // (a + ib) * (c + id)
16130
16131 APFloat AC = A * C;
16132 APFloat BD = B * D;
16133 APFloat AD = A * D;
16134 APFloat BC = B * C;
16135 ResR = AC - BD;
16136 ResI = AD + BC;
16137 if (ResR.isNaN() && ResI.isNaN()) {
16138 bool Recalc = false;
16139 if (A.isInfinity() || B.isInfinity()) {
16140 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16141 A);
16142 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16143 B);
16144 if (C.isNaN())
16145 C = APFloat::copySign(APFloat(C.getSemantics()), C);
16146 if (D.isNaN())
16147 D = APFloat::copySign(APFloat(D.getSemantics()), D);
16148 Recalc = true;
16149 }
16150 if (C.isInfinity() || D.isInfinity()) {
16151 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16152 C);
16153 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16154 D);
16155 if (A.isNaN())
16156 A = APFloat::copySign(APFloat(A.getSemantics()), A);
16157 if (B.isNaN())
16158 B = APFloat::copySign(APFloat(B.getSemantics()), B);
16159 Recalc = true;
16160 }
16161 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
16162 BC.isInfinity())) {
16163 if (A.isNaN())
16164 A = APFloat::copySign(APFloat(A.getSemantics()), A);
16165 if (B.isNaN())
16166 B = APFloat::copySign(APFloat(B.getSemantics()), B);
16167 if (C.isNaN())
16168 C = APFloat::copySign(APFloat(C.getSemantics()), C);
16169 if (D.isNaN())
16170 D = APFloat::copySign(APFloat(D.getSemantics()), D);
16171 Recalc = true;
16172 }
16173 if (Recalc) {
16174 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
16175 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
16176 }
16177 }
16178 }
16179
HandleComplexComplexDiv(APFloat A,APFloat B,APFloat C,APFloat D,APFloat & ResR,APFloat & ResI)16180 void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
16181 APFloat &ResR, APFloat &ResI) {
16182 // This is an implementation of complex division according to the
16183 // constraints laid out in C11 Annex G. The implementation uses the
16184 // following naming scheme:
16185 // (a + ib) / (c + id)
16186
16187 int DenomLogB = 0;
16188 APFloat MaxCD = maxnum(abs(C), abs(D));
16189 if (MaxCD.isFinite()) {
16190 DenomLogB = ilogb(MaxCD);
16191 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
16192 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
16193 }
16194 APFloat Denom = C * C + D * D;
16195 ResR =
16196 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16197 ResI =
16198 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16199 if (ResR.isNaN() && ResI.isNaN()) {
16200 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
16201 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
16202 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
16203 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
16204 D.isFinite()) {
16205 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16206 A);
16207 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16208 B);
16209 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
16210 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
16211 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
16212 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16213 C);
16214 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16215 D);
16216 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
16217 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
16218 }
16219 }
16220 }
16221
VisitBinaryOperator(const BinaryOperator * E)16222 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16223 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16224 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16225
16226 // Track whether the LHS or RHS is real at the type system level. When this is
16227 // the case we can simplify our evaluation strategy.
16228 bool LHSReal = false, RHSReal = false;
16229
16230 bool LHSOK;
16231 if (E->getLHS()->getType()->isRealFloatingType()) {
16232 LHSReal = true;
16233 APFloat &Real = Result.FloatReal;
16234 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
16235 if (LHSOK) {
16236 Result.makeComplexFloat();
16237 Result.FloatImag = APFloat(Real.getSemantics());
16238 }
16239 } else {
16240 LHSOK = Visit(E->getLHS());
16241 }
16242 if (!LHSOK && !Info.noteFailure())
16243 return false;
16244
16245 ComplexValue RHS;
16246 if (E->getRHS()->getType()->isRealFloatingType()) {
16247 RHSReal = true;
16248 APFloat &Real = RHS.FloatReal;
16249 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
16250 return false;
16251 RHS.makeComplexFloat();
16252 RHS.FloatImag = APFloat(Real.getSemantics());
16253 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
16254 return false;
16255
16256 assert(!(LHSReal && RHSReal) &&
16257 "Cannot have both operands of a complex operation be real.");
16258 switch (E->getOpcode()) {
16259 default: return Error(E);
16260 case BO_Add:
16261 if (Result.isComplexFloat()) {
16262 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
16263 APFloat::rmNearestTiesToEven);
16264 if (LHSReal)
16265 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16266 else if (!RHSReal)
16267 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
16268 APFloat::rmNearestTiesToEven);
16269 } else {
16270 Result.getComplexIntReal() += RHS.getComplexIntReal();
16271 Result.getComplexIntImag() += RHS.getComplexIntImag();
16272 }
16273 break;
16274 case BO_Sub:
16275 if (Result.isComplexFloat()) {
16276 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
16277 APFloat::rmNearestTiesToEven);
16278 if (LHSReal) {
16279 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16280 Result.getComplexFloatImag().changeSign();
16281 } else if (!RHSReal) {
16282 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
16283 APFloat::rmNearestTiesToEven);
16284 }
16285 } else {
16286 Result.getComplexIntReal() -= RHS.getComplexIntReal();
16287 Result.getComplexIntImag() -= RHS.getComplexIntImag();
16288 }
16289 break;
16290 case BO_Mul:
16291 if (Result.isComplexFloat()) {
16292 // This is an implementation of complex multiplication according to the
16293 // constraints laid out in C11 Annex G. The implementation uses the
16294 // following naming scheme:
16295 // (a + ib) * (c + id)
16296 ComplexValue LHS = Result;
16297 APFloat &A = LHS.getComplexFloatReal();
16298 APFloat &B = LHS.getComplexFloatImag();
16299 APFloat &C = RHS.getComplexFloatReal();
16300 APFloat &D = RHS.getComplexFloatImag();
16301 APFloat &ResR = Result.getComplexFloatReal();
16302 APFloat &ResI = Result.getComplexFloatImag();
16303 if (LHSReal) {
16304 assert(!RHSReal && "Cannot have two real operands for a complex op!");
16305 ResR = A;
16306 ResI = A;
16307 // ResR = A * C;
16308 // ResI = A * D;
16309 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
16310 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
16311 return false;
16312 } else if (RHSReal) {
16313 // ResR = C * A;
16314 // ResI = C * B;
16315 ResR = C;
16316 ResI = C;
16317 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
16318 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
16319 return false;
16320 } else {
16321 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
16322 }
16323 } else {
16324 ComplexValue LHS = Result;
16325 Result.getComplexIntReal() =
16326 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
16327 LHS.getComplexIntImag() * RHS.getComplexIntImag());
16328 Result.getComplexIntImag() =
16329 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
16330 LHS.getComplexIntImag() * RHS.getComplexIntReal());
16331 }
16332 break;
16333 case BO_Div:
16334 if (Result.isComplexFloat()) {
16335 // This is an implementation of complex division according to the
16336 // constraints laid out in C11 Annex G. The implementation uses the
16337 // following naming scheme:
16338 // (a + ib) / (c + id)
16339 ComplexValue LHS = Result;
16340 APFloat &A = LHS.getComplexFloatReal();
16341 APFloat &B = LHS.getComplexFloatImag();
16342 APFloat &C = RHS.getComplexFloatReal();
16343 APFloat &D = RHS.getComplexFloatImag();
16344 APFloat &ResR = Result.getComplexFloatReal();
16345 APFloat &ResI = Result.getComplexFloatImag();
16346 if (RHSReal) {
16347 ResR = A;
16348 ResI = B;
16349 // ResR = A / C;
16350 // ResI = B / C;
16351 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
16352 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
16353 return false;
16354 } else {
16355 if (LHSReal) {
16356 // No real optimizations we can do here, stub out with zero.
16357 B = APFloat::getZero(A.getSemantics());
16358 }
16359 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
16360 }
16361 } else {
16362 ComplexValue LHS = Result;
16363 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
16364 RHS.getComplexIntImag() * RHS.getComplexIntImag();
16365 if (Den.isZero())
16366 return Error(E, diag::note_expr_divide_by_zero);
16367
16368 Result.getComplexIntReal() =
16369 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
16370 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
16371 Result.getComplexIntImag() =
16372 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
16373 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
16374 }
16375 break;
16376 }
16377
16378 return true;
16379 }
16380
VisitUnaryOperator(const UnaryOperator * E)16381 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16382 // Get the operand value into 'Result'.
16383 if (!Visit(E->getSubExpr()))
16384 return false;
16385
16386 switch (E->getOpcode()) {
16387 default:
16388 return Error(E);
16389 case UO_Extension:
16390 return true;
16391 case UO_Plus:
16392 // The result is always just the subexpr.
16393 return true;
16394 case UO_Minus:
16395 if (Result.isComplexFloat()) {
16396 Result.getComplexFloatReal().changeSign();
16397 Result.getComplexFloatImag().changeSign();
16398 }
16399 else {
16400 Result.getComplexIntReal() = -Result.getComplexIntReal();
16401 Result.getComplexIntImag() = -Result.getComplexIntImag();
16402 }
16403 return true;
16404 case UO_Not:
16405 if (Result.isComplexFloat())
16406 Result.getComplexFloatImag().changeSign();
16407 else
16408 Result.getComplexIntImag() = -Result.getComplexIntImag();
16409 return true;
16410 }
16411 }
16412
VisitInitListExpr(const InitListExpr * E)16413 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
16414 if (E->getNumInits() == 2) {
16415 if (E->getType()->isComplexType()) {
16416 Result.makeComplexFloat();
16417 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
16418 return false;
16419 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
16420 return false;
16421 } else {
16422 Result.makeComplexInt();
16423 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
16424 return false;
16425 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
16426 return false;
16427 }
16428 return true;
16429 }
16430 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
16431 }
16432
VisitCallExpr(const CallExpr * E)16433 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
16434 if (!IsConstantEvaluatedBuiltinCall(E))
16435 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16436
16437 switch (E->getBuiltinCallee()) {
16438 case Builtin::BI__builtin_complex:
16439 Result.makeComplexFloat();
16440 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
16441 return false;
16442 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
16443 return false;
16444 return true;
16445
16446 default:
16447 return false;
16448 }
16449 }
16450
16451 //===----------------------------------------------------------------------===//
16452 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
16453 // implicit conversion.
16454 //===----------------------------------------------------------------------===//
16455
16456 namespace {
16457 class AtomicExprEvaluator :
16458 public ExprEvaluatorBase<AtomicExprEvaluator> {
16459 const LValue *This;
16460 APValue &Result;
16461 public:
AtomicExprEvaluator(EvalInfo & Info,const LValue * This,APValue & Result)16462 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
16463 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
16464
Success(const APValue & V,const Expr * E)16465 bool Success(const APValue &V, const Expr *E) {
16466 Result = V;
16467 return true;
16468 }
16469
ZeroInitialization(const Expr * E)16470 bool ZeroInitialization(const Expr *E) {
16471 ImplicitValueInitExpr VIE(
16472 E->getType()->castAs<AtomicType>()->getValueType());
16473 // For atomic-qualified class (and array) types in C++, initialize the
16474 // _Atomic-wrapped subobject directly, in-place.
16475 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
16476 : Evaluate(Result, Info, &VIE);
16477 }
16478
VisitCastExpr(const CastExpr * E)16479 bool VisitCastExpr(const CastExpr *E) {
16480 switch (E->getCastKind()) {
16481 default:
16482 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16483 case CK_NullToPointer:
16484 VisitIgnoredValue(E->getSubExpr());
16485 return ZeroInitialization(E);
16486 case CK_NonAtomicToAtomic:
16487 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
16488 : Evaluate(Result, Info, E->getSubExpr());
16489 }
16490 }
16491 };
16492 } // end anonymous namespace
16493
EvaluateAtomic(const Expr * E,const LValue * This,APValue & Result,EvalInfo & Info)16494 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
16495 EvalInfo &Info) {
16496 assert(!E->isValueDependent());
16497 assert(E->isPRValue() && E->getType()->isAtomicType());
16498 return AtomicExprEvaluator(Info, This, Result).Visit(E);
16499 }
16500
16501 //===----------------------------------------------------------------------===//
16502 // Void expression evaluation, primarily for a cast to void on the LHS of a
16503 // comma operator
16504 //===----------------------------------------------------------------------===//
16505
16506 namespace {
16507 class VoidExprEvaluator
16508 : public ExprEvaluatorBase<VoidExprEvaluator> {
16509 public:
VoidExprEvaluator(EvalInfo & Info)16510 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
16511
Success(const APValue & V,const Expr * e)16512 bool Success(const APValue &V, const Expr *e) { return true; }
16513
ZeroInitialization(const Expr * E)16514 bool ZeroInitialization(const Expr *E) { return true; }
16515
VisitCastExpr(const CastExpr * E)16516 bool VisitCastExpr(const CastExpr *E) {
16517 switch (E->getCastKind()) {
16518 default:
16519 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16520 case CK_ToVoid:
16521 VisitIgnoredValue(E->getSubExpr());
16522 return true;
16523 }
16524 }
16525
VisitCallExpr(const CallExpr * E)16526 bool VisitCallExpr(const CallExpr *E) {
16527 if (!IsConstantEvaluatedBuiltinCall(E))
16528 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16529
16530 switch (E->getBuiltinCallee()) {
16531 case Builtin::BI__assume:
16532 case Builtin::BI__builtin_assume:
16533 // The argument is not evaluated!
16534 return true;
16535
16536 case Builtin::BI__builtin_operator_delete:
16537 return HandleOperatorDeleteCall(Info, E);
16538
16539 default:
16540 return false;
16541 }
16542 }
16543
16544 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
16545 };
16546 } // end anonymous namespace
16547
VisitCXXDeleteExpr(const CXXDeleteExpr * E)16548 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
16549 // We cannot speculatively evaluate a delete expression.
16550 if (Info.SpeculativeEvaluationDepth)
16551 return false;
16552
16553 FunctionDecl *OperatorDelete = E->getOperatorDelete();
16554 if (!OperatorDelete
16555 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
16556 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16557 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
16558 return false;
16559 }
16560
16561 const Expr *Arg = E->getArgument();
16562
16563 LValue Pointer;
16564 if (!EvaluatePointer(Arg, Pointer, Info))
16565 return false;
16566 if (Pointer.Designator.Invalid)
16567 return false;
16568
16569 // Deleting a null pointer has no effect.
16570 if (Pointer.isNullPointer()) {
16571 // This is the only case where we need to produce an extension warning:
16572 // the only other way we can succeed is if we find a dynamic allocation,
16573 // and we will have warned when we allocated it in that case.
16574 if (!Info.getLangOpts().CPlusPlus20)
16575 Info.CCEDiag(E, diag::note_constexpr_new);
16576 return true;
16577 }
16578
16579 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
16580 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
16581 if (!Alloc)
16582 return false;
16583 QualType AllocType = Pointer.Base.getDynamicAllocType();
16584
16585 // For the non-array case, the designator must be empty if the static type
16586 // does not have a virtual destructor.
16587 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
16588 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
16589 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
16590 << Arg->getType()->getPointeeType() << AllocType;
16591 return false;
16592 }
16593
16594 // For a class type with a virtual destructor, the selected operator delete
16595 // is the one looked up when building the destructor.
16596 if (!E->isArrayForm() && !E->isGlobalDelete()) {
16597 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
16598 if (VirtualDelete &&
16599 !VirtualDelete
16600 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
16601 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16602 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
16603 return false;
16604 }
16605 }
16606
16607 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
16608 (*Alloc)->Value, AllocType))
16609 return false;
16610
16611 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
16612 // The element was already erased. This means the destructor call also
16613 // deleted the object.
16614 // FIXME: This probably results in undefined behavior before we get this
16615 // far, and should be diagnosed elsewhere first.
16616 Info.FFDiag(E, diag::note_constexpr_double_delete);
16617 return false;
16618 }
16619
16620 return true;
16621 }
16622
EvaluateVoid(const Expr * E,EvalInfo & Info)16623 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
16624 assert(!E->isValueDependent());
16625 assert(E->isPRValue() && E->getType()->isVoidType());
16626 return VoidExprEvaluator(Info).Visit(E);
16627 }
16628
16629 //===----------------------------------------------------------------------===//
16630 // Top level Expr::EvaluateAsRValue method.
16631 //===----------------------------------------------------------------------===//
16632
Evaluate(APValue & Result,EvalInfo & Info,const Expr * E)16633 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
16634 assert(!E->isValueDependent());
16635 // In C, function designators are not lvalues, but we evaluate them as if they
16636 // are.
16637 QualType T = E->getType();
16638 if (E->isGLValue() || T->isFunctionType()) {
16639 LValue LV;
16640 if (!EvaluateLValue(E, LV, Info))
16641 return false;
16642 LV.moveInto(Result);
16643 } else if (T->isVectorType()) {
16644 if (!EvaluateVector(E, Result, Info))
16645 return false;
16646 } else if (T->isIntegralOrEnumerationType()) {
16647 if (!IntExprEvaluator(Info, Result).Visit(E))
16648 return false;
16649 } else if (T->hasPointerRepresentation()) {
16650 LValue LV;
16651 if (!EvaluatePointer(E, LV, Info))
16652 return false;
16653 LV.moveInto(Result);
16654 } else if (T->isRealFloatingType()) {
16655 llvm::APFloat F(0.0);
16656 if (!EvaluateFloat(E, F, Info))
16657 return false;
16658 Result = APValue(F);
16659 } else if (T->isAnyComplexType()) {
16660 ComplexValue C;
16661 if (!EvaluateComplex(E, C, Info))
16662 return false;
16663 C.moveInto(Result);
16664 } else if (T->isFixedPointType()) {
16665 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
16666 } else if (T->isMemberPointerType()) {
16667 MemberPtr P;
16668 if (!EvaluateMemberPointer(E, P, Info))
16669 return false;
16670 P.moveInto(Result);
16671 return true;
16672 } else if (T->isArrayType()) {
16673 LValue LV;
16674 APValue &Value =
16675 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16676 if (!EvaluateArray(E, LV, Value, Info))
16677 return false;
16678 Result = Value;
16679 } else if (T->isRecordType()) {
16680 LValue LV;
16681 APValue &Value =
16682 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16683 if (!EvaluateRecord(E, LV, Value, Info))
16684 return false;
16685 Result = Value;
16686 } else if (T->isVoidType()) {
16687 if (!Info.getLangOpts().CPlusPlus11)
16688 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
16689 << E->getType();
16690 if (!EvaluateVoid(E, Info))
16691 return false;
16692 } else if (T->isAtomicType()) {
16693 QualType Unqual = T.getAtomicUnqualifiedType();
16694 if (Unqual->isArrayType() || Unqual->isRecordType()) {
16695 LValue LV;
16696 APValue &Value = Info.CurrentCall->createTemporary(
16697 E, Unqual, ScopeKind::FullExpression, LV);
16698 if (!EvaluateAtomic(E, &LV, Value, Info))
16699 return false;
16700 Result = Value;
16701 } else {
16702 if (!EvaluateAtomic(E, nullptr, Result, Info))
16703 return false;
16704 }
16705 } else if (Info.getLangOpts().CPlusPlus11) {
16706 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
16707 return false;
16708 } else {
16709 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16710 return false;
16711 }
16712
16713 return true;
16714 }
16715
16716 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
16717 /// cases, the in-place evaluation is essential, since later initializers for
16718 /// an object can indirectly refer to subobjects which were initialized earlier.
EvaluateInPlace(APValue & Result,EvalInfo & Info,const LValue & This,const Expr * E,bool AllowNonLiteralTypes)16719 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
16720 const Expr *E, bool AllowNonLiteralTypes) {
16721 assert(!E->isValueDependent());
16722
16723 // Normally expressions passed to EvaluateInPlace have a type, but not when
16724 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
16725 // replaced with a CXXConstructExpr. This can happen in LLDB.
16726 if (E->getType().isNull())
16727 return false;
16728
16729 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
16730 return false;
16731
16732 if (E->isPRValue()) {
16733 // Evaluate arrays and record types in-place, so that later initializers can
16734 // refer to earlier-initialized members of the object.
16735 QualType T = E->getType();
16736 if (T->isArrayType())
16737 return EvaluateArray(E, This, Result, Info);
16738 else if (T->isRecordType())
16739 return EvaluateRecord(E, This, Result, Info);
16740 else if (T->isAtomicType()) {
16741 QualType Unqual = T.getAtomicUnqualifiedType();
16742 if (Unqual->isArrayType() || Unqual->isRecordType())
16743 return EvaluateAtomic(E, &This, Result, Info);
16744 }
16745 }
16746
16747 // For any other type, in-place evaluation is unimportant.
16748 return Evaluate(Result, Info, E);
16749 }
16750
16751 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
16752 /// lvalue-to-rvalue cast if it is an lvalue.
EvaluateAsRValue(EvalInfo & Info,const Expr * E,APValue & Result)16753 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
16754 assert(!E->isValueDependent());
16755
16756 if (E->getType().isNull())
16757 return false;
16758
16759 if (!CheckLiteralType(Info, E))
16760 return false;
16761
16762 if (Info.EnableNewConstInterp) {
16763 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
16764 return false;
16765 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16766 ConstantExprKind::Normal);
16767 }
16768
16769 if (!::Evaluate(Result, Info, E))
16770 return false;
16771
16772 // Implicit lvalue-to-rvalue cast.
16773 if (E->isGLValue()) {
16774 LValue LV;
16775 LV.setFrom(Info.Ctx, Result);
16776 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
16777 return false;
16778 }
16779
16780 // Check this core constant expression is a constant expression.
16781 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16782 ConstantExprKind::Normal) &&
16783 CheckMemoryLeaks(Info);
16784 }
16785
FastEvaluateAsRValue(const Expr * Exp,Expr::EvalResult & Result,const ASTContext & Ctx,bool & IsConst)16786 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
16787 const ASTContext &Ctx, bool &IsConst) {
16788 // Fast-path evaluations of integer literals, since we sometimes see files
16789 // containing vast quantities of these.
16790 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
16791 Result.Val = APValue(APSInt(L->getValue(),
16792 L->getType()->isUnsignedIntegerType()));
16793 IsConst = true;
16794 return true;
16795 }
16796
16797 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
16798 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
16799 IsConst = true;
16800 return true;
16801 }
16802
16803 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
16804 Result.Val = APValue(FL->getValue());
16805 IsConst = true;
16806 return true;
16807 }
16808
16809 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
16810 Result.Val = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
16811 IsConst = true;
16812 return true;
16813 }
16814
16815 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
16816 if (CE->hasAPValueResult()) {
16817 APValue APV = CE->getAPValueResult();
16818 if (!APV.isLValue()) {
16819 Result.Val = std::move(APV);
16820 IsConst = true;
16821 return true;
16822 }
16823 }
16824
16825 // The SubExpr is usually just an IntegerLiteral.
16826 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
16827 }
16828
16829 // This case should be rare, but we need to check it before we check on
16830 // the type below.
16831 if (Exp->getType().isNull()) {
16832 IsConst = false;
16833 return true;
16834 }
16835
16836 return false;
16837 }
16838
hasUnacceptableSideEffect(Expr::EvalStatus & Result,Expr::SideEffectsKind SEK)16839 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
16840 Expr::SideEffectsKind SEK) {
16841 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
16842 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
16843 }
16844
EvaluateAsRValue(const Expr * E,Expr::EvalResult & Result,const ASTContext & Ctx,EvalInfo & Info)16845 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
16846 const ASTContext &Ctx, EvalInfo &Info) {
16847 assert(!E->isValueDependent());
16848 bool IsConst;
16849 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
16850 return IsConst;
16851
16852 return EvaluateAsRValue(Info, E, Result.Val);
16853 }
16854
EvaluateAsInt(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)16855 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
16856 const ASTContext &Ctx,
16857 Expr::SideEffectsKind AllowSideEffects,
16858 EvalInfo &Info) {
16859 assert(!E->isValueDependent());
16860 if (!E->getType()->isIntegralOrEnumerationType())
16861 return false;
16862
16863 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
16864 !ExprResult.Val.isInt() ||
16865 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16866 return false;
16867
16868 return true;
16869 }
16870
EvaluateAsFixedPoint(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)16871 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
16872 const ASTContext &Ctx,
16873 Expr::SideEffectsKind AllowSideEffects,
16874 EvalInfo &Info) {
16875 assert(!E->isValueDependent());
16876 if (!E->getType()->isFixedPointType())
16877 return false;
16878
16879 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
16880 return false;
16881
16882 if (!ExprResult.Val.isFixedPoint() ||
16883 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16884 return false;
16885
16886 return true;
16887 }
16888
16889 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
16890 /// any crazy technique (that has nothing to do with language standards) that
16891 /// we want to. If this function returns true, it returns the folded constant
16892 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
16893 /// will be applied to the result.
EvaluateAsRValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const16894 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
16895 bool InConstantContext) const {
16896 assert(!isValueDependent() &&
16897 "Expression evaluator can't be called on a dependent expression.");
16898 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
16899 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16900 Info.InConstantContext = InConstantContext;
16901 return ::EvaluateAsRValue(this, Result, Ctx, Info);
16902 }
16903
EvaluateAsBooleanCondition(bool & Result,const ASTContext & Ctx,bool InConstantContext) const16904 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
16905 bool InConstantContext) const {
16906 assert(!isValueDependent() &&
16907 "Expression evaluator can't be called on a dependent expression.");
16908 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
16909 EvalResult Scratch;
16910 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
16911 HandleConversionToBool(Scratch.Val, Result);
16912 }
16913
EvaluateAsInt(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const16914 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
16915 SideEffectsKind AllowSideEffects,
16916 bool InConstantContext) const {
16917 assert(!isValueDependent() &&
16918 "Expression evaluator can't be called on a dependent expression.");
16919 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
16920 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16921 Info.InConstantContext = InConstantContext;
16922 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
16923 }
16924
EvaluateAsFixedPoint(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const16925 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
16926 SideEffectsKind AllowSideEffects,
16927 bool InConstantContext) const {
16928 assert(!isValueDependent() &&
16929 "Expression evaluator can't be called on a dependent expression.");
16930 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
16931 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16932 Info.InConstantContext = InConstantContext;
16933 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
16934 }
16935
EvaluateAsFloat(APFloat & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const16936 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
16937 SideEffectsKind AllowSideEffects,
16938 bool InConstantContext) const {
16939 assert(!isValueDependent() &&
16940 "Expression evaluator can't be called on a dependent expression.");
16941
16942 if (!getType()->isRealFloatingType())
16943 return false;
16944
16945 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
16946 EvalResult ExprResult;
16947 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
16948 !ExprResult.Val.isFloat() ||
16949 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16950 return false;
16951
16952 Result = ExprResult.Val.getFloat();
16953 return true;
16954 }
16955
EvaluateAsLValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const16956 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
16957 bool InConstantContext) const {
16958 assert(!isValueDependent() &&
16959 "Expression evaluator can't be called on a dependent expression.");
16960
16961 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
16962 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
16963 Info.InConstantContext = InConstantContext;
16964 LValue LV;
16965 CheckedTemporaries CheckedTemps;
16966 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
16967 Result.HasSideEffects ||
16968 !CheckLValueConstantExpression(Info, getExprLoc(),
16969 Ctx.getLValueReferenceType(getType()), LV,
16970 ConstantExprKind::Normal, CheckedTemps))
16971 return false;
16972
16973 LV.moveInto(Result.Val);
16974 return true;
16975 }
16976
EvaluateDestruction(const ASTContext & Ctx,APValue::LValueBase Base,APValue DestroyedValue,QualType Type,SourceLocation Loc,Expr::EvalStatus & EStatus,bool IsConstantDestruction)16977 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
16978 APValue DestroyedValue, QualType Type,
16979 SourceLocation Loc, Expr::EvalStatus &EStatus,
16980 bool IsConstantDestruction) {
16981 EvalInfo Info(Ctx, EStatus,
16982 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
16983 : EvalInfo::EM_ConstantFold);
16984 Info.setEvaluatingDecl(Base, DestroyedValue,
16985 EvalInfo::EvaluatingDeclKind::Dtor);
16986 Info.InConstantContext = IsConstantDestruction;
16987
16988 LValue LVal;
16989 LVal.set(Base);
16990
16991 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
16992 EStatus.HasSideEffects)
16993 return false;
16994
16995 if (!Info.discardCleanups())
16996 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16997
16998 return true;
16999 }
17000
EvaluateAsConstantExpr(EvalResult & Result,const ASTContext & Ctx,ConstantExprKind Kind) const17001 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
17002 ConstantExprKind Kind) const {
17003 assert(!isValueDependent() &&
17004 "Expression evaluator can't be called on a dependent expression.");
17005 bool IsConst;
17006 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
17007 return true;
17008
17009 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
17010 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
17011 EvalInfo Info(Ctx, Result, EM);
17012 Info.InConstantContext = true;
17013
17014 if (Info.EnableNewConstInterp) {
17015 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
17016 return false;
17017 return CheckConstantExpression(Info, getExprLoc(),
17018 getStorageType(Ctx, this), Result.Val, Kind);
17019 }
17020
17021 // The type of the object we're initializing is 'const T' for a class NTTP.
17022 QualType T = getType();
17023 if (Kind == ConstantExprKind::ClassTemplateArgument)
17024 T.addConst();
17025
17026 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
17027 // represent the result of the evaluation. CheckConstantExpression ensures
17028 // this doesn't escape.
17029 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
17030 APValue::LValueBase Base(&BaseMTE);
17031 Info.setEvaluatingDecl(Base, Result.Val);
17032
17033 LValue LVal;
17034 LVal.set(Base);
17035 // C++23 [intro.execution]/p5
17036 // A full-expression is [...] a constant-expression
17037 // So we need to make sure temporary objects are destroyed after having
17038 // evaluating the expression (per C++23 [class.temporary]/p4).
17039 FullExpressionRAII Scope(Info);
17040 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
17041 Result.HasSideEffects || !Scope.destroy())
17042 return false;
17043
17044 if (!Info.discardCleanups())
17045 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17046
17047 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
17048 Result.Val, Kind))
17049 return false;
17050 if (!CheckMemoryLeaks(Info))
17051 return false;
17052
17053 // If this is a class template argument, it's required to have constant
17054 // destruction too.
17055 if (Kind == ConstantExprKind::ClassTemplateArgument &&
17056 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
17057 true) ||
17058 Result.HasSideEffects)) {
17059 // FIXME: Prefix a note to indicate that the problem is lack of constant
17060 // destruction.
17061 return false;
17062 }
17063
17064 return true;
17065 }
17066
EvaluateAsInitializer(APValue & Value,const ASTContext & Ctx,const VarDecl * VD,SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const17067 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
17068 const VarDecl *VD,
17069 SmallVectorImpl<PartialDiagnosticAt> &Notes,
17070 bool IsConstantInitialization) const {
17071 assert(!isValueDependent() &&
17072 "Expression evaluator can't be called on a dependent expression.");
17073
17074 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
17075 std::string Name;
17076 llvm::raw_string_ostream OS(Name);
17077 VD->printQualifiedName(OS);
17078 return Name;
17079 });
17080
17081 Expr::EvalStatus EStatus;
17082 EStatus.Diag = &Notes;
17083
17084 EvalInfo Info(Ctx, EStatus,
17085 (IsConstantInitialization &&
17086 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
17087 ? EvalInfo::EM_ConstantExpression
17088 : EvalInfo::EM_ConstantFold);
17089 Info.setEvaluatingDecl(VD, Value);
17090 Info.InConstantContext = IsConstantInitialization;
17091
17092 SourceLocation DeclLoc = VD->getLocation();
17093 QualType DeclTy = VD->getType();
17094
17095 if (Info.EnableNewConstInterp) {
17096 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
17097 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
17098 return false;
17099
17100 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17101 ConstantExprKind::Normal);
17102 } else {
17103 LValue LVal;
17104 LVal.set(VD);
17105
17106 {
17107 // C++23 [intro.execution]/p5
17108 // A full-expression is ... an init-declarator ([dcl.decl]) or a
17109 // mem-initializer.
17110 // So we need to make sure temporary objects are destroyed after having
17111 // evaluated the expression (per C++23 [class.temporary]/p4).
17112 //
17113 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
17114 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
17115 // outermost FullExpr, such as ExprWithCleanups.
17116 FullExpressionRAII Scope(Info);
17117 if (!EvaluateInPlace(Value, Info, LVal, this,
17118 /*AllowNonLiteralTypes=*/true) ||
17119 EStatus.HasSideEffects)
17120 return false;
17121 }
17122
17123 // At this point, any lifetime-extended temporaries are completely
17124 // initialized.
17125 Info.performLifetimeExtension();
17126
17127 if (!Info.discardCleanups())
17128 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17129 }
17130
17131 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17132 ConstantExprKind::Normal) &&
17133 CheckMemoryLeaks(Info);
17134 }
17135
evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> & Notes) const17136 bool VarDecl::evaluateDestruction(
17137 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
17138 Expr::EvalStatus EStatus;
17139 EStatus.Diag = &Notes;
17140
17141 // Only treat the destruction as constant destruction if we formally have
17142 // constant initialization (or are usable in a constant expression).
17143 bool IsConstantDestruction = hasConstantInitialization();
17144
17145 // Make a copy of the value for the destructor to mutate, if we know it.
17146 // Otherwise, treat the value as default-initialized; if the destructor works
17147 // anyway, then the destruction is constant (and must be essentially empty).
17148 APValue DestroyedValue;
17149 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
17150 DestroyedValue = *getEvaluatedValue();
17151 else if (!handleDefaultInitValue(getType(), DestroyedValue))
17152 return false;
17153
17154 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
17155 getType(), getLocation(), EStatus,
17156 IsConstantDestruction) ||
17157 EStatus.HasSideEffects)
17158 return false;
17159
17160 ensureEvaluatedStmt()->HasConstantDestruction = true;
17161 return true;
17162 }
17163
17164 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
17165 /// constant folded, but discard the result.
isEvaluatable(const ASTContext & Ctx,SideEffectsKind SEK) const17166 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
17167 assert(!isValueDependent() &&
17168 "Expression evaluator can't be called on a dependent expression.");
17169
17170 EvalResult Result;
17171 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
17172 !hasUnacceptableSideEffect(Result, SEK);
17173 }
17174
EvaluateKnownConstInt(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const17175 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
17176 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
17177 assert(!isValueDependent() &&
17178 "Expression evaluator can't be called on a dependent expression.");
17179
17180 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
17181 EvalResult EVResult;
17182 EVResult.Diag = Diag;
17183 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17184 Info.InConstantContext = true;
17185
17186 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
17187 (void)Result;
17188 assert(Result && "Could not evaluate expression");
17189 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17190
17191 return EVResult.Val.getInt();
17192 }
17193
EvaluateKnownConstIntCheckOverflow(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const17194 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
17195 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
17196 assert(!isValueDependent() &&
17197 "Expression evaluator can't be called on a dependent expression.");
17198
17199 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
17200 EvalResult EVResult;
17201 EVResult.Diag = Diag;
17202 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17203 Info.InConstantContext = true;
17204 Info.CheckingForUndefinedBehavior = true;
17205
17206 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
17207 (void)Result;
17208 assert(Result && "Could not evaluate expression");
17209 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17210
17211 return EVResult.Val.getInt();
17212 }
17213
EvaluateForOverflow(const ASTContext & Ctx) const17214 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
17215 assert(!isValueDependent() &&
17216 "Expression evaluator can't be called on a dependent expression.");
17217
17218 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
17219 bool IsConst;
17220 EvalResult EVResult;
17221 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
17222 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17223 Info.CheckingForUndefinedBehavior = true;
17224 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
17225 }
17226 }
17227
isGlobalLValue() const17228 bool Expr::EvalResult::isGlobalLValue() const {
17229 assert(Val.isLValue());
17230 return IsGlobalLValue(Val.getLValueBase());
17231 }
17232
17233 /// isIntegerConstantExpr - this recursive routine will test if an expression is
17234 /// an integer constant expression.
17235
17236 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
17237 /// comma, etc
17238
17239 // CheckICE - This function does the fundamental ICE checking: the returned
17240 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
17241 // and a (possibly null) SourceLocation indicating the location of the problem.
17242 //
17243 // Note that to reduce code duplication, this helper does no evaluation
17244 // itself; the caller checks whether the expression is evaluatable, and
17245 // in the rare cases where CheckICE actually cares about the evaluated
17246 // value, it calls into Evaluate.
17247
17248 namespace {
17249
17250 enum ICEKind {
17251 /// This expression is an ICE.
17252 IK_ICE,
17253 /// This expression is not an ICE, but if it isn't evaluated, it's
17254 /// a legal subexpression for an ICE. This return value is used to handle
17255 /// the comma operator in C99 mode, and non-constant subexpressions.
17256 IK_ICEIfUnevaluated,
17257 /// This expression is not an ICE, and is not a legal subexpression for one.
17258 IK_NotICE
17259 };
17260
17261 struct ICEDiag {
17262 ICEKind Kind;
17263 SourceLocation Loc;
17264
ICEDiag__anonfb577fba3d11::ICEDiag17265 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
17266 };
17267
17268 }
17269
NoDiag()17270 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
17271
Worst(ICEDiag A,ICEDiag B)17272 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
17273
CheckEvalInICE(const Expr * E,const ASTContext & Ctx)17274 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
17275 Expr::EvalResult EVResult;
17276 Expr::EvalStatus Status;
17277 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17278
17279 Info.InConstantContext = true;
17280 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
17281 !EVResult.Val.isInt())
17282 return ICEDiag(IK_NotICE, E->getBeginLoc());
17283
17284 return NoDiag();
17285 }
17286
CheckICE(const Expr * E,const ASTContext & Ctx)17287 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
17288 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
17289 if (!E->getType()->isIntegralOrEnumerationType())
17290 return ICEDiag(IK_NotICE, E->getBeginLoc());
17291
17292 switch (E->getStmtClass()) {
17293 #define ABSTRACT_STMT(Node)
17294 #define STMT(Node, Base) case Expr::Node##Class:
17295 #define EXPR(Node, Base)
17296 #include "clang/AST/StmtNodes.inc"
17297 case Expr::PredefinedExprClass:
17298 case Expr::FloatingLiteralClass:
17299 case Expr::ImaginaryLiteralClass:
17300 case Expr::StringLiteralClass:
17301 case Expr::ArraySubscriptExprClass:
17302 case Expr::MatrixSubscriptExprClass:
17303 case Expr::ArraySectionExprClass:
17304 case Expr::OMPArrayShapingExprClass:
17305 case Expr::OMPIteratorExprClass:
17306 case Expr::MemberExprClass:
17307 case Expr::CompoundAssignOperatorClass:
17308 case Expr::CompoundLiteralExprClass:
17309 case Expr::ExtVectorElementExprClass:
17310 case Expr::DesignatedInitExprClass:
17311 case Expr::ArrayInitLoopExprClass:
17312 case Expr::ArrayInitIndexExprClass:
17313 case Expr::NoInitExprClass:
17314 case Expr::DesignatedInitUpdateExprClass:
17315 case Expr::ImplicitValueInitExprClass:
17316 case Expr::ParenListExprClass:
17317 case Expr::VAArgExprClass:
17318 case Expr::AddrLabelExprClass:
17319 case Expr::StmtExprClass:
17320 case Expr::CXXMemberCallExprClass:
17321 case Expr::CUDAKernelCallExprClass:
17322 case Expr::CXXAddrspaceCastExprClass:
17323 case Expr::CXXDynamicCastExprClass:
17324 case Expr::CXXTypeidExprClass:
17325 case Expr::CXXUuidofExprClass:
17326 case Expr::MSPropertyRefExprClass:
17327 case Expr::MSPropertySubscriptExprClass:
17328 case Expr::CXXNullPtrLiteralExprClass:
17329 case Expr::UserDefinedLiteralClass:
17330 case Expr::CXXThisExprClass:
17331 case Expr::CXXThrowExprClass:
17332 case Expr::CXXNewExprClass:
17333 case Expr::CXXDeleteExprClass:
17334 case Expr::CXXPseudoDestructorExprClass:
17335 case Expr::UnresolvedLookupExprClass:
17336 case Expr::RecoveryExprClass:
17337 case Expr::DependentScopeDeclRefExprClass:
17338 case Expr::CXXConstructExprClass:
17339 case Expr::CXXInheritedCtorInitExprClass:
17340 case Expr::CXXStdInitializerListExprClass:
17341 case Expr::CXXBindTemporaryExprClass:
17342 case Expr::ExprWithCleanupsClass:
17343 case Expr::CXXTemporaryObjectExprClass:
17344 case Expr::CXXUnresolvedConstructExprClass:
17345 case Expr::CXXDependentScopeMemberExprClass:
17346 case Expr::UnresolvedMemberExprClass:
17347 case Expr::ObjCStringLiteralClass:
17348 case Expr::ObjCBoxedExprClass:
17349 case Expr::ObjCArrayLiteralClass:
17350 case Expr::ObjCDictionaryLiteralClass:
17351 case Expr::ObjCEncodeExprClass:
17352 case Expr::ObjCMessageExprClass:
17353 case Expr::ObjCSelectorExprClass:
17354 case Expr::ObjCProtocolExprClass:
17355 case Expr::ObjCIvarRefExprClass:
17356 case Expr::ObjCPropertyRefExprClass:
17357 case Expr::ObjCSubscriptRefExprClass:
17358 case Expr::ObjCIsaExprClass:
17359 case Expr::ObjCAvailabilityCheckExprClass:
17360 case Expr::ShuffleVectorExprClass:
17361 case Expr::ConvertVectorExprClass:
17362 case Expr::BlockExprClass:
17363 case Expr::NoStmtClass:
17364 case Expr::OpaqueValueExprClass:
17365 case Expr::PackExpansionExprClass:
17366 case Expr::SubstNonTypeTemplateParmPackExprClass:
17367 case Expr::FunctionParmPackExprClass:
17368 case Expr::AsTypeExprClass:
17369 case Expr::ObjCIndirectCopyRestoreExprClass:
17370 case Expr::MaterializeTemporaryExprClass:
17371 case Expr::PseudoObjectExprClass:
17372 case Expr::AtomicExprClass:
17373 case Expr::LambdaExprClass:
17374 case Expr::CXXFoldExprClass:
17375 case Expr::CoawaitExprClass:
17376 case Expr::DependentCoawaitExprClass:
17377 case Expr::CoyieldExprClass:
17378 case Expr::SYCLUniqueStableNameExprClass:
17379 case Expr::CXXParenListInitExprClass:
17380 case Expr::HLSLOutArgExprClass:
17381 return ICEDiag(IK_NotICE, E->getBeginLoc());
17382
17383 case Expr::InitListExprClass: {
17384 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
17385 // form "T x = { a };" is equivalent to "T x = a;".
17386 // Unless we're initializing a reference, T is a scalar as it is known to be
17387 // of integral or enumeration type.
17388 if (E->isPRValue())
17389 if (cast<InitListExpr>(E)->getNumInits() == 1)
17390 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
17391 return ICEDiag(IK_NotICE, E->getBeginLoc());
17392 }
17393
17394 case Expr::SizeOfPackExprClass:
17395 case Expr::GNUNullExprClass:
17396 case Expr::SourceLocExprClass:
17397 case Expr::EmbedExprClass:
17398 case Expr::OpenACCAsteriskSizeExprClass:
17399 return NoDiag();
17400
17401 case Expr::PackIndexingExprClass:
17402 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
17403
17404 case Expr::SubstNonTypeTemplateParmExprClass:
17405 return
17406 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
17407
17408 case Expr::ConstantExprClass:
17409 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
17410
17411 case Expr::ParenExprClass:
17412 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
17413 case Expr::GenericSelectionExprClass:
17414 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
17415 case Expr::IntegerLiteralClass:
17416 case Expr::FixedPointLiteralClass:
17417 case Expr::CharacterLiteralClass:
17418 case Expr::ObjCBoolLiteralExprClass:
17419 case Expr::CXXBoolLiteralExprClass:
17420 case Expr::CXXScalarValueInitExprClass:
17421 case Expr::TypeTraitExprClass:
17422 case Expr::ConceptSpecializationExprClass:
17423 case Expr::RequiresExprClass:
17424 case Expr::ArrayTypeTraitExprClass:
17425 case Expr::ExpressionTraitExprClass:
17426 case Expr::CXXNoexceptExprClass:
17427 return NoDiag();
17428 case Expr::CallExprClass:
17429 case Expr::CXXOperatorCallExprClass: {
17430 // C99 6.6/3 allows function calls within unevaluated subexpressions of
17431 // constant expressions, but they can never be ICEs because an ICE cannot
17432 // contain an operand of (pointer to) function type.
17433 const CallExpr *CE = cast<CallExpr>(E);
17434 if (CE->getBuiltinCallee())
17435 return CheckEvalInICE(E, Ctx);
17436 return ICEDiag(IK_NotICE, E->getBeginLoc());
17437 }
17438 case Expr::CXXRewrittenBinaryOperatorClass:
17439 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
17440 Ctx);
17441 case Expr::DeclRefExprClass: {
17442 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
17443 if (isa<EnumConstantDecl>(D))
17444 return NoDiag();
17445
17446 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
17447 // integer variables in constant expressions:
17448 //
17449 // C++ 7.1.5.1p2
17450 // A variable of non-volatile const-qualified integral or enumeration
17451 // type initialized by an ICE can be used in ICEs.
17452 //
17453 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
17454 // that mode, use of reference variables should not be allowed.
17455 const VarDecl *VD = dyn_cast<VarDecl>(D);
17456 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
17457 !VD->getType()->isReferenceType())
17458 return NoDiag();
17459
17460 return ICEDiag(IK_NotICE, E->getBeginLoc());
17461 }
17462 case Expr::UnaryOperatorClass: {
17463 const UnaryOperator *Exp = cast<UnaryOperator>(E);
17464 switch (Exp->getOpcode()) {
17465 case UO_PostInc:
17466 case UO_PostDec:
17467 case UO_PreInc:
17468 case UO_PreDec:
17469 case UO_AddrOf:
17470 case UO_Deref:
17471 case UO_Coawait:
17472 // C99 6.6/3 allows increment and decrement within unevaluated
17473 // subexpressions of constant expressions, but they can never be ICEs
17474 // because an ICE cannot contain an lvalue operand.
17475 return ICEDiag(IK_NotICE, E->getBeginLoc());
17476 case UO_Extension:
17477 case UO_LNot:
17478 case UO_Plus:
17479 case UO_Minus:
17480 case UO_Not:
17481 case UO_Real:
17482 case UO_Imag:
17483 return CheckICE(Exp->getSubExpr(), Ctx);
17484 }
17485 llvm_unreachable("invalid unary operator class");
17486 }
17487 case Expr::OffsetOfExprClass: {
17488 // Note that per C99, offsetof must be an ICE. And AFAIK, using
17489 // EvaluateAsRValue matches the proposed gcc behavior for cases like
17490 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
17491 // compliance: we should warn earlier for offsetof expressions with
17492 // array subscripts that aren't ICEs, and if the array subscripts
17493 // are ICEs, the value of the offsetof must be an integer constant.
17494 return CheckEvalInICE(E, Ctx);
17495 }
17496 case Expr::UnaryExprOrTypeTraitExprClass: {
17497 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
17498 if ((Exp->getKind() == UETT_SizeOf) &&
17499 Exp->getTypeOfArgument()->isVariableArrayType())
17500 return ICEDiag(IK_NotICE, E->getBeginLoc());
17501 if (Exp->getKind() == UETT_CountOf) {
17502 QualType ArgTy = Exp->getTypeOfArgument();
17503 if (ArgTy->isVariableArrayType()) {
17504 // We need to look whether the array is multidimensional. If it is,
17505 // then we want to check the size expression manually to see whether
17506 // it is an ICE or not.
17507 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
17508 if (VAT->getElementType()->isArrayType())
17509 return CheckICE(VAT->getSizeExpr(), Ctx);
17510
17511 // Otherwise, this is a regular VLA, which is definitely not an ICE.
17512 return ICEDiag(IK_NotICE, E->getBeginLoc());
17513 }
17514 }
17515 return NoDiag();
17516 }
17517 case Expr::BinaryOperatorClass: {
17518 const BinaryOperator *Exp = cast<BinaryOperator>(E);
17519 switch (Exp->getOpcode()) {
17520 case BO_PtrMemD:
17521 case BO_PtrMemI:
17522 case BO_Assign:
17523 case BO_MulAssign:
17524 case BO_DivAssign:
17525 case BO_RemAssign:
17526 case BO_AddAssign:
17527 case BO_SubAssign:
17528 case BO_ShlAssign:
17529 case BO_ShrAssign:
17530 case BO_AndAssign:
17531 case BO_XorAssign:
17532 case BO_OrAssign:
17533 // C99 6.6/3 allows assignments within unevaluated subexpressions of
17534 // constant expressions, but they can never be ICEs because an ICE cannot
17535 // contain an lvalue operand.
17536 return ICEDiag(IK_NotICE, E->getBeginLoc());
17537
17538 case BO_Mul:
17539 case BO_Div:
17540 case BO_Rem:
17541 case BO_Add:
17542 case BO_Sub:
17543 case BO_Shl:
17544 case BO_Shr:
17545 case BO_LT:
17546 case BO_GT:
17547 case BO_LE:
17548 case BO_GE:
17549 case BO_EQ:
17550 case BO_NE:
17551 case BO_And:
17552 case BO_Xor:
17553 case BO_Or:
17554 case BO_Comma:
17555 case BO_Cmp: {
17556 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17557 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17558 if (Exp->getOpcode() == BO_Div ||
17559 Exp->getOpcode() == BO_Rem) {
17560 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
17561 // we don't evaluate one.
17562 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
17563 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
17564 if (REval == 0)
17565 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17566 if (REval.isSigned() && REval.isAllOnes()) {
17567 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
17568 if (LEval.isMinSignedValue())
17569 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17570 }
17571 }
17572 }
17573 if (Exp->getOpcode() == BO_Comma) {
17574 if (Ctx.getLangOpts().C99) {
17575 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
17576 // if it isn't evaluated.
17577 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
17578 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17579 } else {
17580 // In both C89 and C++, commas in ICEs are illegal.
17581 return ICEDiag(IK_NotICE, E->getBeginLoc());
17582 }
17583 }
17584 return Worst(LHSResult, RHSResult);
17585 }
17586 case BO_LAnd:
17587 case BO_LOr: {
17588 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17589 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17590 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
17591 // Rare case where the RHS has a comma "side-effect"; we need
17592 // to actually check the condition to see whether the side
17593 // with the comma is evaluated.
17594 if ((Exp->getOpcode() == BO_LAnd) !=
17595 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
17596 return RHSResult;
17597 return NoDiag();
17598 }
17599
17600 return Worst(LHSResult, RHSResult);
17601 }
17602 }
17603 llvm_unreachable("invalid binary operator kind");
17604 }
17605 case Expr::ImplicitCastExprClass:
17606 case Expr::CStyleCastExprClass:
17607 case Expr::CXXFunctionalCastExprClass:
17608 case Expr::CXXStaticCastExprClass:
17609 case Expr::CXXReinterpretCastExprClass:
17610 case Expr::CXXConstCastExprClass:
17611 case Expr::ObjCBridgedCastExprClass: {
17612 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
17613 if (isa<ExplicitCastExpr>(E)) {
17614 if (const FloatingLiteral *FL
17615 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
17616 unsigned DestWidth = Ctx.getIntWidth(E->getType());
17617 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
17618 APSInt IgnoredVal(DestWidth, !DestSigned);
17619 bool Ignored;
17620 // If the value does not fit in the destination type, the behavior is
17621 // undefined, so we are not required to treat it as a constant
17622 // expression.
17623 if (FL->getValue().convertToInteger(IgnoredVal,
17624 llvm::APFloat::rmTowardZero,
17625 &Ignored) & APFloat::opInvalidOp)
17626 return ICEDiag(IK_NotICE, E->getBeginLoc());
17627 return NoDiag();
17628 }
17629 }
17630 switch (cast<CastExpr>(E)->getCastKind()) {
17631 case CK_LValueToRValue:
17632 case CK_AtomicToNonAtomic:
17633 case CK_NonAtomicToAtomic:
17634 case CK_NoOp:
17635 case CK_IntegralToBoolean:
17636 case CK_IntegralCast:
17637 return CheckICE(SubExpr, Ctx);
17638 default:
17639 return ICEDiag(IK_NotICE, E->getBeginLoc());
17640 }
17641 }
17642 case Expr::BinaryConditionalOperatorClass: {
17643 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
17644 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
17645 if (CommonResult.Kind == IK_NotICE) return CommonResult;
17646 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17647 if (FalseResult.Kind == IK_NotICE) return FalseResult;
17648 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
17649 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
17650 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
17651 return FalseResult;
17652 }
17653 case Expr::ConditionalOperatorClass: {
17654 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
17655 // If the condition (ignoring parens) is a __builtin_constant_p call,
17656 // then only the true side is actually considered in an integer constant
17657 // expression, and it is fully evaluated. This is an important GNU
17658 // extension. See GCC PR38377 for discussion.
17659 if (const CallExpr *CallCE
17660 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
17661 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
17662 return CheckEvalInICE(E, Ctx);
17663 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
17664 if (CondResult.Kind == IK_NotICE)
17665 return CondResult;
17666
17667 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
17668 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17669
17670 if (TrueResult.Kind == IK_NotICE)
17671 return TrueResult;
17672 if (FalseResult.Kind == IK_NotICE)
17673 return FalseResult;
17674 if (CondResult.Kind == IK_ICEIfUnevaluated)
17675 return CondResult;
17676 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
17677 return NoDiag();
17678 // Rare case where the diagnostics depend on which side is evaluated
17679 // Note that if we get here, CondResult is 0, and at least one of
17680 // TrueResult and FalseResult is non-zero.
17681 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
17682 return FalseResult;
17683 return TrueResult;
17684 }
17685 case Expr::CXXDefaultArgExprClass:
17686 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
17687 case Expr::CXXDefaultInitExprClass:
17688 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
17689 case Expr::ChooseExprClass: {
17690 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
17691 }
17692 case Expr::BuiltinBitCastExprClass: {
17693 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
17694 return ICEDiag(IK_NotICE, E->getBeginLoc());
17695 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
17696 }
17697 }
17698
17699 llvm_unreachable("Invalid StmtClass!");
17700 }
17701
17702 /// Evaluate an expression as a C++11 integral constant expression.
EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext & Ctx,const Expr * E,llvm::APSInt * Value,SourceLocation * Loc)17703 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
17704 const Expr *E,
17705 llvm::APSInt *Value,
17706 SourceLocation *Loc) {
17707 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17708 if (Loc) *Loc = E->getExprLoc();
17709 return false;
17710 }
17711
17712 APValue Result;
17713 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
17714 return false;
17715
17716 if (!Result.isInt()) {
17717 if (Loc) *Loc = E->getExprLoc();
17718 return false;
17719 }
17720
17721 if (Value) *Value = Result.getInt();
17722 return true;
17723 }
17724
isIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const17725 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
17726 SourceLocation *Loc) const {
17727 assert(!isValueDependent() &&
17728 "Expression evaluator can't be called on a dependent expression.");
17729
17730 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
17731
17732 if (Ctx.getLangOpts().CPlusPlus11)
17733 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
17734
17735 ICEDiag D = CheckICE(this, Ctx);
17736 if (D.Kind != IK_ICE) {
17737 if (Loc) *Loc = D.Loc;
17738 return false;
17739 }
17740 return true;
17741 }
17742
17743 std::optional<llvm::APSInt>
getIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const17744 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc) const {
17745 if (isValueDependent()) {
17746 // Expression evaluator can't succeed on a dependent expression.
17747 return std::nullopt;
17748 }
17749
17750 APSInt Value;
17751
17752 if (Ctx.getLangOpts().CPlusPlus11) {
17753 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
17754 return Value;
17755 return std::nullopt;
17756 }
17757
17758 if (!isIntegerConstantExpr(Ctx, Loc))
17759 return std::nullopt;
17760
17761 // The only possible side-effects here are due to UB discovered in the
17762 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
17763 // required to treat the expression as an ICE, so we produce the folded
17764 // value.
17765 EvalResult ExprResult;
17766 Expr::EvalStatus Status;
17767 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
17768 Info.InConstantContext = true;
17769
17770 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
17771 llvm_unreachable("ICE cannot be evaluated!");
17772
17773 return ExprResult.Val.getInt();
17774 }
17775
isCXX98IntegralConstantExpr(const ASTContext & Ctx) const17776 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
17777 assert(!isValueDependent() &&
17778 "Expression evaluator can't be called on a dependent expression.");
17779
17780 return CheckICE(this, Ctx).Kind == IK_ICE;
17781 }
17782
isCXX11ConstantExpr(const ASTContext & Ctx,APValue * Result,SourceLocation * Loc) const17783 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
17784 SourceLocation *Loc) const {
17785 assert(!isValueDependent() &&
17786 "Expression evaluator can't be called on a dependent expression.");
17787
17788 // We support this checking in C++98 mode in order to diagnose compatibility
17789 // issues.
17790 assert(Ctx.getLangOpts().CPlusPlus);
17791
17792 // Build evaluation settings.
17793 Expr::EvalStatus Status;
17794 SmallVector<PartialDiagnosticAt, 8> Diags;
17795 Status.Diag = &Diags;
17796 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17797
17798 APValue Scratch;
17799 bool IsConstExpr =
17800 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
17801 // FIXME: We don't produce a diagnostic for this, but the callers that
17802 // call us on arbitrary full-expressions should generally not care.
17803 Info.discardCleanups() && !Status.HasSideEffects;
17804
17805 if (!Diags.empty()) {
17806 IsConstExpr = false;
17807 if (Loc) *Loc = Diags[0].first;
17808 } else if (!IsConstExpr) {
17809 // FIXME: This shouldn't happen.
17810 if (Loc) *Loc = getExprLoc();
17811 }
17812
17813 return IsConstExpr;
17814 }
17815
EvaluateWithSubstitution(APValue & Value,ASTContext & Ctx,const FunctionDecl * Callee,ArrayRef<const Expr * > Args,const Expr * This) const17816 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
17817 const FunctionDecl *Callee,
17818 ArrayRef<const Expr*> Args,
17819 const Expr *This) const {
17820 assert(!isValueDependent() &&
17821 "Expression evaluator can't be called on a dependent expression.");
17822
17823 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
17824 std::string Name;
17825 llvm::raw_string_ostream OS(Name);
17826 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
17827 /*Qualified=*/true);
17828 return Name;
17829 });
17830
17831 Expr::EvalStatus Status;
17832 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
17833 Info.InConstantContext = true;
17834
17835 LValue ThisVal;
17836 const LValue *ThisPtr = nullptr;
17837 if (This) {
17838 #ifndef NDEBUG
17839 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
17840 assert(MD && "Don't provide `this` for non-methods.");
17841 assert(MD->isImplicitObjectMemberFunction() &&
17842 "Don't provide `this` for methods without an implicit object.");
17843 #endif
17844 if (!This->isValueDependent() &&
17845 EvaluateObjectArgument(Info, This, ThisVal) &&
17846 !Info.EvalStatus.HasSideEffects)
17847 ThisPtr = &ThisVal;
17848
17849 // Ignore any side-effects from a failed evaluation. This is safe because
17850 // they can't interfere with any other argument evaluation.
17851 Info.EvalStatus.HasSideEffects = false;
17852 }
17853
17854 CallRef Call = Info.CurrentCall->createCall(Callee);
17855 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
17856 I != E; ++I) {
17857 unsigned Idx = I - Args.begin();
17858 if (Idx >= Callee->getNumParams())
17859 break;
17860 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
17861 if ((*I)->isValueDependent() ||
17862 !EvaluateCallArg(PVD, *I, Call, Info) ||
17863 Info.EvalStatus.HasSideEffects) {
17864 // If evaluation fails, throw away the argument entirely.
17865 if (APValue *Slot = Info.getParamSlot(Call, PVD))
17866 *Slot = APValue();
17867 }
17868
17869 // Ignore any side-effects from a failed evaluation. This is safe because
17870 // they can't interfere with any other argument evaluation.
17871 Info.EvalStatus.HasSideEffects = false;
17872 }
17873
17874 // Parameter cleanups happen in the caller and are not part of this
17875 // evaluation.
17876 Info.discardCleanups();
17877 Info.EvalStatus.HasSideEffects = false;
17878
17879 // Build fake call to Callee.
17880 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
17881 Call);
17882 // FIXME: Missing ExprWithCleanups in enable_if conditions?
17883 FullExpressionRAII Scope(Info);
17884 return Evaluate(Value, Info, this) && Scope.destroy() &&
17885 !Info.EvalStatus.HasSideEffects;
17886 }
17887
isPotentialConstantExpr(const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)17888 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
17889 SmallVectorImpl<
17890 PartialDiagnosticAt> &Diags) {
17891 // FIXME: It would be useful to check constexpr function templates, but at the
17892 // moment the constant expression evaluator cannot cope with the non-rigorous
17893 // ASTs which we build for dependent expressions.
17894 if (FD->isDependentContext())
17895 return true;
17896
17897 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
17898 std::string Name;
17899 llvm::raw_string_ostream OS(Name);
17900 FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
17901 /*Qualified=*/true);
17902 return Name;
17903 });
17904
17905 Expr::EvalStatus Status;
17906 Status.Diag = &Diags;
17907
17908 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
17909 Info.InConstantContext = true;
17910 Info.CheckingPotentialConstantExpression = true;
17911
17912 // The constexpr VM attempts to compile all methods to bytecode here.
17913 if (Info.EnableNewConstInterp) {
17914 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
17915 return Diags.empty();
17916 }
17917
17918 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
17919 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
17920
17921 // Fabricate an arbitrary expression on the stack and pretend that it
17922 // is a temporary being used as the 'this' pointer.
17923 LValue This;
17924 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
17925 This.set({&VIE, Info.CurrentCall->Index});
17926
17927 ArrayRef<const Expr*> Args;
17928
17929 APValue Scratch;
17930 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
17931 // Evaluate the call as a constant initializer, to allow the construction
17932 // of objects of non-literal types.
17933 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
17934 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
17935 } else {
17936 SourceLocation Loc = FD->getLocation();
17937 HandleFunctionCall(
17938 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
17939 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
17940 /*ResultSlot=*/nullptr);
17941 }
17942
17943 return Diags.empty();
17944 }
17945
isPotentialConstantExprUnevaluated(Expr * E,const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)17946 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
17947 const FunctionDecl *FD,
17948 SmallVectorImpl<
17949 PartialDiagnosticAt> &Diags) {
17950 assert(!E->isValueDependent() &&
17951 "Expression evaluator can't be called on a dependent expression.");
17952
17953 Expr::EvalStatus Status;
17954 Status.Diag = &Diags;
17955
17956 EvalInfo Info(FD->getASTContext(), Status,
17957 EvalInfo::EM_ConstantExpressionUnevaluated);
17958 Info.InConstantContext = true;
17959 Info.CheckingPotentialConstantExpression = true;
17960
17961 // Fabricate a call stack frame to give the arguments a plausible cover story.
17962 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
17963 /*CallExpr=*/nullptr, CallRef());
17964
17965 APValue ResultScratch;
17966 Evaluate(ResultScratch, Info, E);
17967 return Diags.empty();
17968 }
17969
tryEvaluateObjectSize(uint64_t & Result,ASTContext & Ctx,unsigned Type) const17970 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
17971 unsigned Type) const {
17972 if (!getType()->isPointerType())
17973 return false;
17974
17975 Expr::EvalStatus Status;
17976 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17977 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
17978 }
17979
EvaluateBuiltinStrLen(const Expr * E,uint64_t & Result,EvalInfo & Info,std::string * StringResult)17980 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
17981 EvalInfo &Info, std::string *StringResult) {
17982 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
17983 return false;
17984
17985 LValue String;
17986
17987 if (!EvaluatePointer(E, String, Info))
17988 return false;
17989
17990 QualType CharTy = E->getType()->getPointeeType();
17991
17992 // Fast path: if it's a string literal, search the string value.
17993 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
17994 String.getLValueBase().dyn_cast<const Expr *>())) {
17995 StringRef Str = S->getBytes();
17996 int64_t Off = String.Offset.getQuantity();
17997 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
17998 S->getCharByteWidth() == 1 &&
17999 // FIXME: Add fast-path for wchar_t too.
18000 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
18001 Str = Str.substr(Off);
18002
18003 StringRef::size_type Pos = Str.find(0);
18004 if (Pos != StringRef::npos)
18005 Str = Str.substr(0, Pos);
18006
18007 Result = Str.size();
18008 if (StringResult)
18009 *StringResult = Str;
18010 return true;
18011 }
18012
18013 // Fall through to slow path.
18014 }
18015
18016 // Slow path: scan the bytes of the string looking for the terminating 0.
18017 for (uint64_t Strlen = 0; /**/; ++Strlen) {
18018 APValue Char;
18019 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
18020 !Char.isInt())
18021 return false;
18022 if (!Char.getInt()) {
18023 Result = Strlen;
18024 return true;
18025 } else if (StringResult)
18026 StringResult->push_back(Char.getInt().getExtValue());
18027 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
18028 return false;
18029 }
18030 }
18031
tryEvaluateString(ASTContext & Ctx) const18032 std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
18033 Expr::EvalStatus Status;
18034 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
18035 uint64_t Result;
18036 std::string StringResult;
18037
18038 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
18039 return StringResult;
18040 return {};
18041 }
18042
18043 template <typename T>
EvaluateCharRangeAsStringImpl(const Expr *,T & Result,const Expr * SizeExpression,const Expr * PtrExpression,ASTContext & Ctx,Expr::EvalResult & Status)18044 static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
18045 const Expr *SizeExpression,
18046 const Expr *PtrExpression,
18047 ASTContext &Ctx,
18048 Expr::EvalResult &Status) {
18049 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
18050 Info.InConstantContext = true;
18051
18052 if (Info.EnableNewConstInterp)
18053 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
18054 PtrExpression, Result);
18055
18056 LValue String;
18057 FullExpressionRAII Scope(Info);
18058 APSInt SizeValue;
18059 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
18060 return false;
18061
18062 uint64_t Size = SizeValue.getZExtValue();
18063
18064 // FIXME: better protect against invalid or excessive sizes
18065 if constexpr (std::is_same_v<APValue, T>)
18066 Result = APValue(APValue::UninitArray{}, Size, Size);
18067 else {
18068 if (Size < Result.max_size())
18069 Result.reserve(Size);
18070 }
18071 if (!::EvaluatePointer(PtrExpression, String, Info))
18072 return false;
18073
18074 QualType CharTy = PtrExpression->getType()->getPointeeType();
18075 for (uint64_t I = 0; I < Size; ++I) {
18076 APValue Char;
18077 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
18078 Char))
18079 return false;
18080
18081 if constexpr (std::is_same_v<APValue, T>) {
18082 Result.getArrayInitializedElt(I) = std::move(Char);
18083 } else {
18084 APSInt C = Char.getInt();
18085
18086 assert(C.getBitWidth() <= 8 &&
18087 "string element not representable in char");
18088
18089 Result.push_back(static_cast<char>(C.getExtValue()));
18090 }
18091
18092 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
18093 return false;
18094 }
18095
18096 return Scope.destroy() && CheckMemoryLeaks(Info);
18097 }
18098
EvaluateCharRangeAsString(std::string & Result,const Expr * SizeExpression,const Expr * PtrExpression,ASTContext & Ctx,EvalResult & Status) const18099 bool Expr::EvaluateCharRangeAsString(std::string &Result,
18100 const Expr *SizeExpression,
18101 const Expr *PtrExpression, ASTContext &Ctx,
18102 EvalResult &Status) const {
18103 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
18104 PtrExpression, Ctx, Status);
18105 }
18106
EvaluateCharRangeAsString(APValue & Result,const Expr * SizeExpression,const Expr * PtrExpression,ASTContext & Ctx,EvalResult & Status) const18107 bool Expr::EvaluateCharRangeAsString(APValue &Result,
18108 const Expr *SizeExpression,
18109 const Expr *PtrExpression, ASTContext &Ctx,
18110 EvalResult &Status) const {
18111 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
18112 PtrExpression, Ctx, Status);
18113 }
18114
tryEvaluateStrLen(uint64_t & Result,ASTContext & Ctx) const18115 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
18116 Expr::EvalStatus Status;
18117 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
18118 return EvaluateBuiltinStrLen(this, Result, Info);
18119 }
18120
18121 namespace {
18122 struct IsWithinLifetimeHandler {
18123 EvalInfo &Info;
18124 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
18125 using result_type = std::optional<bool>;
failed__anonfb577fba4011::IsWithinLifetimeHandler18126 std::optional<bool> failed() { return std::nullopt; }
18127 template <typename T>
found__anonfb577fba4011::IsWithinLifetimeHandler18128 std::optional<bool> found(T &Subobj, QualType SubobjType) {
18129 return true;
18130 }
18131 };
18132
EvaluateBuiltinIsWithinLifetime(IntExprEvaluator & IEE,const CallExpr * E)18133 std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
18134 const CallExpr *E) {
18135 EvalInfo &Info = IEE.Info;
18136 // Sometimes this is called during some sorts of constant folding / early
18137 // evaluation. These are meant for non-constant expressions and are not
18138 // necessary since this consteval builtin will never be evaluated at runtime.
18139 // Just fail to evaluate when not in a constant context.
18140 if (!Info.InConstantContext)
18141 return std::nullopt;
18142 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
18143 const Expr *Arg = E->getArg(0);
18144 if (Arg->isValueDependent())
18145 return std::nullopt;
18146 LValue Val;
18147 if (!EvaluatePointer(Arg, Val, Info))
18148 return std::nullopt;
18149
18150 if (Val.allowConstexprUnknown())
18151 return true;
18152
18153 auto Error = [&](int Diag) {
18154 bool CalledFromStd = false;
18155 const auto *Callee = Info.CurrentCall->getCallee();
18156 if (Callee && Callee->isInStdNamespace()) {
18157 const IdentifierInfo *Identifier = Callee->getIdentifier();
18158 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
18159 }
18160 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
18161 : E->getExprLoc(),
18162 diag::err_invalid_is_within_lifetime)
18163 << (CalledFromStd ? "std::is_within_lifetime"
18164 : "__builtin_is_within_lifetime")
18165 << Diag;
18166 return std::nullopt;
18167 };
18168 // C++2c [meta.const.eval]p4:
18169 // During the evaluation of an expression E as a core constant expression, a
18170 // call to this function is ill-formed unless p points to an object that is
18171 // usable in constant expressions or whose complete object's lifetime began
18172 // within E.
18173
18174 // Make sure it points to an object
18175 // nullptr does not point to an object
18176 if (Val.isNullPointer() || Val.getLValueBase().isNull())
18177 return Error(0);
18178 QualType T = Val.getLValueBase().getType();
18179 assert(!T->isFunctionType() &&
18180 "Pointers to functions should have been typed as function pointers "
18181 "which would have been rejected earlier");
18182 assert(T->isObjectType());
18183 // Hypothetical array element is not an object
18184 if (Val.getLValueDesignator().isOnePastTheEnd())
18185 return Error(1);
18186 assert(Val.getLValueDesignator().isValidSubobject() &&
18187 "Unchecked case for valid subobject");
18188 // All other ill-formed values should have failed EvaluatePointer, so the
18189 // object should be a pointer to an object that is usable in a constant
18190 // expression or whose complete lifetime began within the expression
18191 CompleteObject CO =
18192 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
18193 // The lifetime hasn't begun yet if we are still evaluating the
18194 // initializer ([basic.life]p(1.2))
18195 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
18196 return Error(2);
18197
18198 if (!CO)
18199 return false;
18200 IsWithinLifetimeHandler handler{Info};
18201 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
18202 }
18203 } // namespace
18204