1//===--- APValue.cpp - Union class for APFloat/APSInt/Complex -------------===//
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 APValue class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/APValue.h"
14#include "Linkage.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/Type.h"
20#include "llvm/Support/ErrorHandling.h"
21#include "llvm/Support/raw_ostream.h"
22using namespace clang;
23
24static bool visitAPValue(const APValue &Value,
25 llvm::function_ref<bool(const APValue &)> Visitor) {
26 if (!Visitor(Value))
27 return false;
28
29 switch (Value.getKind()) {
30 case APValue::None:
31 case APValue::Indeterminate:
32 case APValue::Int:
33 case APValue::Float:
34 case APValue::FixedPoint:
35 case APValue::ComplexInt:
36 case APValue::ComplexFloat:
37 case APValue::LValue:
38 case APValue::MemberPointer:
39 case APValue::AddrLabelDiff:
40 case APValue::Reflection:
41 return true;
42
43 case APValue::Vector:
44 for (unsigned I = 0, N = Value.getVectorLength(); I != N; ++I)
45 if (!visitAPValue(Value: Value.getVectorElt(I), Visitor))
46 return false;
47 return true;
48
49 case APValue::Matrix:
50 for (unsigned I = 0, N = Value.getMatrixNumElements(); I != N; ++I)
51 if (!visitAPValue(Value: Value.getMatrixElt(Idx: I), Visitor))
52 return false;
53 return true;
54
55 case APValue::Array:
56 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I)
57 if (!visitAPValue(Value: Value.getArrayInitializedElt(I), Visitor))
58 return false;
59 return !Value.hasArrayFiller() ||
60 visitAPValue(Value: Value.getArrayFiller(), Visitor);
61
62 case APValue::Struct:
63 for (unsigned I = 0, N = Value.getStructNumBases(); I != N; ++I)
64 if (!visitAPValue(Value: Value.getStructBase(i: I), Visitor))
65 return false;
66 for (unsigned I = 0, N = Value.getStructNumFields(); I != N; ++I)
67 if (!visitAPValue(Value: Value.getStructField(i: I), Visitor))
68 return false;
69 for (unsigned I = 0, N = Value.getStructNumVirtualBases(); I != N; ++I)
70 if (!visitAPValue(Value: Value.getStructVirtualBase(i: I), Visitor))
71 return false;
72 return true;
73
74 case APValue::Union:
75 return !Value.getUnionField() ||
76 visitAPValue(Value: Value.getUnionValue(), Visitor);
77 }
78 llvm_unreachable("unknown APValue kind");
79}
80
81void APValue::visit(llvm::function_ref<bool(const APValue &)> Visitor) const {
82 visitAPValue(Value: *this, Visitor);
83}
84
85/// The identity of a type_info object depends on the canonical unqualified
86/// type only.
87TypeInfoLValue::TypeInfoLValue(const Type *T)
88 : T(T->getCanonicalTypeUnqualified().getTypePtr()) {}
89
90void TypeInfoLValue::print(llvm::raw_ostream &Out,
91 const PrintingPolicy &Policy) const {
92 Out << "typeid(";
93 QualType(getType(), 0).print(OS&: Out, Policy);
94 Out << ")";
95}
96
97static_assert(
98 1 << llvm::PointerLikeTypeTraits<TypeInfoLValue>::NumLowBitsAvailable <=
99 alignof(Type),
100 "Type is insufficiently aligned");
101
102APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I, unsigned V)
103 : Ptr(P ? cast<ValueDecl>(Val: P->getCanonicalDecl()) : nullptr), Local{.CallIndex: I, .Version: V} {}
104APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
105 : Ptr(P), Local{.CallIndex: I, .Version: V} {}
106
107APValue::LValueBase APValue::LValueBase::getDynamicAlloc(DynamicAllocLValue LV,
108 QualType Type) {
109 LValueBase Base;
110 Base.Ptr = LV;
111 Base.DynamicAllocType = Type.getAsOpaquePtr();
112 return Base;
113}
114
115APValue::LValueBase APValue::LValueBase::getTypeInfo(TypeInfoLValue LV,
116 QualType TypeInfo) {
117 LValueBase Base;
118 Base.Ptr = LV;
119 Base.TypeInfoType = TypeInfo.getAsOpaquePtr();
120 return Base;
121}
122
123QualType APValue::LValueBase::getType() const {
124 if (!*this) return QualType();
125 if (const ValueDecl *D = dyn_cast<const ValueDecl*>()) {
126 // FIXME: It's unclear where we're supposed to take the type from, and
127 // this actually matters for arrays of unknown bound. Eg:
128 //
129 // extern int arr[]; void f() { extern int arr[3]; };
130 // constexpr int *p = &arr[1]; // valid?
131 //
132 // For now, we take the most complete type we can find.
133 for (auto *Redecl = cast<ValueDecl>(Val: D->getMostRecentDecl()); Redecl;
134 Redecl = cast_or_null<ValueDecl>(Val: Redecl->getPreviousDecl())) {
135 QualType T = Redecl->getType();
136 if (!T->isIncompleteArrayType())
137 return T;
138 }
139 return D->getType();
140 }
141
142 if (is<TypeInfoLValue>())
143 return getTypeInfoType();
144
145 if (is<DynamicAllocLValue>())
146 return getDynamicAllocType();
147
148 const Expr *Base = get<const Expr*>();
149
150 // For a materialized temporary, the type of the temporary we materialized
151 // may not be the type of the expression.
152 if (const MaterializeTemporaryExpr *MTE =
153 llvm::dyn_cast<MaterializeTemporaryExpr>(Val: Base)) {
154 SmallVector<const Expr *, 2> CommaLHSs;
155 SmallVector<SubobjectAdjustment, 2> Adjustments;
156 const Expr *Temp = MTE->getSubExpr();
157 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHS&: CommaLHSs,
158 Adjustments);
159 // Keep any cv-qualifiers from the reference if we generated a temporary
160 // for it directly. Otherwise use the type after adjustment.
161 if (!Adjustments.empty())
162 return Inner->getType();
163 }
164
165 return Base->getType();
166}
167
168unsigned APValue::LValueBase::getCallIndex() const {
169 return (is<TypeInfoLValue>() || is<DynamicAllocLValue>()) ? 0
170 : Local.CallIndex;
171}
172
173unsigned APValue::LValueBase::getVersion() const {
174 return (is<TypeInfoLValue>() || is<DynamicAllocLValue>()) ? 0 : Local.Version;
175}
176
177QualType APValue::LValueBase::getTypeInfoType() const {
178 assert(is<TypeInfoLValue>() && "not a type_info lvalue");
179 return QualType::getFromOpaquePtr(Ptr: TypeInfoType);
180}
181
182QualType APValue::LValueBase::getDynamicAllocType() const {
183 assert(is<DynamicAllocLValue>() && "not a dynamic allocation lvalue");
184 return QualType::getFromOpaquePtr(Ptr: DynamicAllocType);
185}
186
187void APValue::LValueBase::Profile(llvm::FoldingSetNodeID &ID) const {
188 ID.AddPointer(Ptr: Ptr.getOpaqueValue());
189 if (is<TypeInfoLValue>() || is<DynamicAllocLValue>())
190 return;
191 ID.AddInteger(I: Local.CallIndex);
192 ID.AddInteger(I: Local.Version);
193}
194
195namespace clang {
196bool operator==(const APValue::LValueBase &LHS,
197 const APValue::LValueBase &RHS) {
198 if (LHS.Ptr != RHS.Ptr)
199 return false;
200 if (LHS.is<TypeInfoLValue>() || LHS.is<DynamicAllocLValue>())
201 return true;
202 return LHS.Local.CallIndex == RHS.Local.CallIndex &&
203 LHS.Local.Version == RHS.Local.Version;
204}
205}
206
207APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType BaseOrMember) {
208 if (const Decl *D = BaseOrMember.getPointer())
209 BaseOrMember.setPointer(D->getCanonicalDecl());
210 Value = reinterpret_cast<uintptr_t>(BaseOrMember.getOpaqueValue());
211}
212
213void APValue::LValuePathEntry::Profile(llvm::FoldingSetNodeID &ID) const {
214 ID.AddInteger(I: Value);
215}
216
217APValue::LValuePathSerializationHelper::LValuePathSerializationHelper(
218 ArrayRef<LValuePathEntry> Path, QualType ElemTy)
219 : Ty((const void *)ElemTy.getTypePtrOrNull()), Path(Path) {}
220
221QualType APValue::LValuePathSerializationHelper::getType() {
222 return QualType::getFromOpaquePtr(Ptr: Ty);
223}
224
225namespace {
226 struct LVBase {
227 APValue::LValueBase Base;
228 CharUnits Offset;
229 unsigned PathLength;
230 bool IsNullPtr : 1;
231 bool IsOnePastTheEnd : 1;
232 };
233}
234
235void *APValue::LValueBase::getOpaqueValue() const {
236 return Ptr.getOpaqueValue();
237}
238
239bool APValue::LValueBase::isNull() const {
240 return Ptr.isNull();
241}
242
243APValue::LValueBase::operator bool () const {
244 return static_cast<bool>(Ptr);
245}
246
247namespace clang {
248llvm::hash_code hash_value(const APValue::LValueBase &Base) {
249 if (Base.is<TypeInfoLValue>() || Base.is<DynamicAllocLValue>())
250 return llvm::hash_value(ptr: Base.getOpaqueValue());
251 return llvm::hash_combine(args: Base.getOpaqueValue(), args: Base.getCallIndex(),
252 args: Base.getVersion());
253}
254}
255
256unsigned llvm::DenseMapInfo<clang::APValue::LValueBase>::getHashValue(
257 const clang::APValue::LValueBase &Base) {
258 return hash_value(Base);
259}
260
261bool llvm::DenseMapInfo<clang::APValue::LValueBase>::isEqual(
262 const clang::APValue::LValueBase &LHS,
263 const clang::APValue::LValueBase &RHS) {
264 return LHS == RHS;
265}
266
267struct APValue::LV : LVBase {
268 static const unsigned InlinePathSpace =
269 (DataSize - sizeof(LVBase)) / sizeof(LValuePathEntry);
270
271 /// Path - The sequence of base classes, fields and array indices to follow to
272 /// walk from Base to the subobject. When performing GCC-style folding, there
273 /// may not be such a path.
274 union {
275 LValuePathEntry Path[InlinePathSpace];
276 LValuePathEntry *PathPtr;
277 };
278
279 LV() { PathLength = (unsigned)-1; }
280 ~LV() { resizePath(Length: 0); }
281
282 void resizePath(unsigned Length) {
283 if (Length == PathLength)
284 return;
285 if (hasPathPtr())
286 delete [] PathPtr;
287 PathLength = Length;
288 if (hasPathPtr())
289 PathPtr = new LValuePathEntry[Length];
290 }
291
292 bool hasPath() const { return PathLength != (unsigned)-1; }
293 bool hasPathPtr() const { return hasPath() && PathLength > InlinePathSpace; }
294
295 LValuePathEntry *getPath() { return hasPathPtr() ? PathPtr : Path; }
296 const LValuePathEntry *getPath() const {
297 return hasPathPtr() ? PathPtr : Path;
298 }
299};
300
301namespace {
302 struct MemberPointerBase {
303 llvm::PointerIntPair<const ValueDecl*, 1, bool> MemberAndIsDerivedMember;
304 unsigned PathLength;
305 };
306}
307
308struct APValue::MemberPointerData : MemberPointerBase {
309 static const unsigned InlinePathSpace =
310 (DataSize - sizeof(MemberPointerBase)) / sizeof(const CXXRecordDecl*);
311 typedef const CXXRecordDecl *PathElem;
312 union {
313 PathElem Path[InlinePathSpace];
314 PathElem *PathPtr;
315 };
316
317 MemberPointerData() { PathLength = 0; }
318 ~MemberPointerData() { resizePath(Length: 0); }
319
320 void resizePath(unsigned Length) {
321 if (Length == PathLength)
322 return;
323 if (hasPathPtr())
324 delete [] PathPtr;
325 PathLength = Length;
326 if (hasPathPtr())
327 PathPtr = new PathElem[Length];
328 }
329
330 bool hasPathPtr() const { return PathLength > InlinePathSpace; }
331
332 PathElem *getPath() { return hasPathPtr() ? PathPtr : Path; }
333 const PathElem *getPath() const {
334 return hasPathPtr() ? PathPtr : Path;
335 }
336};
337
338// FIXME: Reduce the malloc traffic here.
339
340APValue::Arr::Arr(unsigned NumElts, unsigned Size) :
341 Elts(new APValue[NumElts + (NumElts != Size ? 1 : 0)]),
342 NumElts(NumElts), ArrSize(Size) {}
343APValue::Arr::~Arr() { delete [] Elts; }
344
345APValue::StructData::StructData(unsigned NumBases, unsigned NumFields,
346 unsigned NumVirtualBases)
347 : Elts(new APValue[NumBases + NumFields + NumVirtualBases]),
348 NumBases(NumBases), NumFields(NumFields),
349 NumVirtualBases(NumVirtualBases) {}
350
351APValue::StructData::~StructData() {
352 delete [] Elts;
353}
354
355APValue::UnionData::UnionData() : Field(nullptr), Value(new APValue) {}
356APValue::UnionData::~UnionData () {
357 delete Value;
358}
359
360APValue::APValue(const APValue &RHS)
361 : Kind(None), AllowConstexprUnknown(RHS.AllowConstexprUnknown) {
362 switch (RHS.getKind()) {
363 case None:
364 case Indeterminate:
365 Kind = RHS.getKind();
366 break;
367 case Int:
368 MakeInt(I: RHS.getInt());
369 break;
370 case Float:
371 MakeFloat(F: RHS.getFloat());
372 break;
373 case FixedPoint: {
374 APFixedPoint FXCopy = RHS.getFixedPoint();
375 MakeFixedPoint(FX: std::move(FXCopy));
376 break;
377 }
378 case Vector:
379 MakeVector();
380 setVector(E: ((const Vec *)(const char *)&RHS.Data)->Elts,
381 N: RHS.getVectorLength());
382 break;
383 case Matrix:
384 MakeMatrix();
385 setMatrix(E: ((const Mat *)(const char *)&RHS.Data)->Elts,
386 NumRows: RHS.getMatrixNumRows(), NumCols: RHS.getMatrixNumColumns());
387 break;
388 case ComplexInt:
389 MakeComplexInt();
390 setComplexInt(R: RHS.getComplexIntReal(), I: RHS.getComplexIntImag());
391 break;
392 case ComplexFloat:
393 MakeComplexFloat();
394 setComplexFloat(R: RHS.getComplexFloatReal(), I: RHS.getComplexFloatImag());
395 break;
396 case LValue:
397 MakeLValue();
398 if (RHS.hasLValuePath())
399 setLValue(B: RHS.getLValueBase(), O: RHS.getLValueOffset(), Path: RHS.getLValuePath(),
400 OnePastTheEnd: RHS.isLValueOnePastTheEnd(), IsNullPtr: RHS.isNullPointer());
401 else
402 setLValue(B: RHS.getLValueBase(), O: RHS.getLValueOffset(), NoLValuePath(),
403 IsNullPtr: RHS.isNullPointer());
404 break;
405 case Array:
406 MakeArray(InitElts: RHS.getArrayInitializedElts(), Size: RHS.getArraySize());
407 for (unsigned I = 0, N = RHS.getArrayInitializedElts(); I != N; ++I)
408 getArrayInitializedElt(I) = RHS.getArrayInitializedElt(I);
409 if (RHS.hasArrayFiller())
410 getArrayFiller() = RHS.getArrayFiller();
411 break;
412 case Struct:
413 MakeStruct(B: RHS.getStructNumBases(), M: RHS.getStructNumFields(),
414 V: RHS.getStructNumVirtualBases());
415 for (unsigned I = 0, N = RHS.getStructNumBases(); I != N; ++I)
416 getStructBase(i: I) = RHS.getStructBase(i: I);
417 for (unsigned I = 0, N = RHS.getStructNumFields(); I != N; ++I)
418 getStructField(i: I) = RHS.getStructField(i: I);
419 for (unsigned I = 0, N = RHS.getStructNumVirtualBases(); I != N; ++I)
420 getStructVirtualBase(i: I) = RHS.getStructVirtualBase(i: I);
421 break;
422 case Union:
423 MakeUnion();
424 setUnion(Field: RHS.getUnionField(), Value: RHS.getUnionValue());
425 break;
426 case MemberPointer:
427 MakeMemberPointer(Member: RHS.getMemberPointerDecl(),
428 IsDerivedMember: RHS.isMemberPointerToDerivedMember(),
429 Path: RHS.getMemberPointerPath());
430 break;
431 case AddrLabelDiff:
432 MakeAddrLabelDiff();
433 setAddrLabelDiff(LHSExpr: RHS.getAddrLabelDiffLHS(), RHSExpr: RHS.getAddrLabelDiffRHS());
434 break;
435 case Reflection:
436 MakeReflection(OperandKind: RHS.getReflectionOperandKind(),
437 Operand: RHS.getReflectionOpaqueOperand());
438 break;
439 }
440}
441
442APValue::APValue(APValue &&RHS)
443 : Kind(RHS.Kind), AllowConstexprUnknown(RHS.AllowConstexprUnknown),
444 Data(RHS.Data) {
445 RHS.Kind = None;
446}
447
448APValue &APValue::operator=(const APValue &RHS) {
449 if (this != &RHS)
450 *this = APValue(RHS);
451
452 return *this;
453}
454
455APValue &APValue::operator=(APValue &&RHS) {
456 if (this != &RHS) {
457 if (Kind != None && Kind != Indeterminate)
458 DestroyDataAndMakeUninit();
459 Kind = RHS.Kind;
460 Data = RHS.Data;
461 AllowConstexprUnknown = RHS.AllowConstexprUnknown;
462 RHS.Kind = None;
463 }
464 return *this;
465}
466
467void APValue::DestroyDataAndMakeUninit() {
468 if (Kind == Int)
469 ((APSInt *)(char *)&Data)->~APSInt();
470 else if (Kind == Float)
471 ((APFloat *)(char *)&Data)->~APFloat();
472 else if (Kind == FixedPoint)
473 ((APFixedPoint *)(char *)&Data)->~APFixedPoint();
474 else if (Kind == Vector)
475 ((Vec *)(char *)&Data)->~Vec();
476 else if (Kind == Matrix)
477 ((Mat *)(char *)&Data)->~Mat();
478 else if (Kind == ComplexInt)
479 ((ComplexAPSInt *)(char *)&Data)->~ComplexAPSInt();
480 else if (Kind == ComplexFloat)
481 ((ComplexAPFloat *)(char *)&Data)->~ComplexAPFloat();
482 else if (Kind == LValue)
483 ((LV *)(char *)&Data)->~LV();
484 else if (Kind == Array)
485 ((Arr *)(char *)&Data)->~Arr();
486 else if (Kind == Struct)
487 ((StructData *)(char *)&Data)->~StructData();
488 else if (Kind == Union)
489 ((UnionData *)(char *)&Data)->~UnionData();
490 else if (Kind == MemberPointer)
491 ((MemberPointerData *)(char *)&Data)->~MemberPointerData();
492 else if (Kind == AddrLabelDiff)
493 ((AddrLabelDiffData *)(char *)&Data)->~AddrLabelDiffData();
494 else if (Kind == Reflection)
495 ((ReflectionData *)(char *)&Data)->~ReflectionData();
496 Kind = None;
497 AllowConstexprUnknown = false;
498}
499
500bool APValue::needsCleanup() const {
501 switch (getKind()) {
502 case None:
503 case Indeterminate:
504 case AddrLabelDiff:
505 case Reflection:
506 return false;
507 case Struct:
508 case Union:
509 case Array:
510 case Vector:
511 case Matrix:
512 return true;
513 case Int:
514 return getInt().needsCleanup();
515 case Float:
516 return getFloat().needsCleanup();
517 case FixedPoint:
518 return getFixedPoint().getValue().needsCleanup();
519 case ComplexFloat:
520 assert(getComplexFloatImag().needsCleanup() ==
521 getComplexFloatReal().needsCleanup() &&
522 "In _Complex float types, real and imaginary values always have the "
523 "same size.");
524 return getComplexFloatReal().needsCleanup();
525 case ComplexInt:
526 assert(getComplexIntImag().needsCleanup() ==
527 getComplexIntReal().needsCleanup() &&
528 "In _Complex int types, real and imaginary values must have the "
529 "same size.");
530 return getComplexIntReal().needsCleanup();
531 case LValue:
532 return reinterpret_cast<const LV *>(&Data)->hasPathPtr();
533 case MemberPointer:
534 return reinterpret_cast<const MemberPointerData *>(&Data)->hasPathPtr();
535 }
536 llvm_unreachable("Unknown APValue kind!");
537}
538
539void APValue::swap(APValue &RHS) {
540 std::swap(a&: Kind, b&: RHS.Kind);
541 std::swap(a&: Data, b&: RHS.Data);
542 // We can't use std::swap w/ bit-fields
543 bool tmp = AllowConstexprUnknown;
544 AllowConstexprUnknown = RHS.AllowConstexprUnknown;
545 RHS.AllowConstexprUnknown = tmp;
546}
547
548/// Profile the value of an APInt, excluding its bit-width.
549static void profileIntValue(llvm::FoldingSetNodeID &ID, const llvm::APInt &V) {
550 for (unsigned I = 0, N = V.getBitWidth(); I < N; I += 32)
551 ID.AddInteger(I: (uint32_t)V.extractBitsAsZExtValue(numBits: std::min(a: 32u, b: N - I), bitPosition: I));
552}
553
554/// Unwrap reflected type for profiling
555static void profileTypeReflection(llvm::FoldingSetNodeID &ID, QualType QT) {
556 // TODO(Reflection)
557
558 if (isTypeAliasAsReflectionName(QT)) {
559 if (const auto *TDT = QT->getAs<TypedefType>()) {
560 ID.AddBoolean(B: true);
561 ID.AddPointer(Ptr: TDT->getDecl()->getCanonicalDecl());
562 return;
563 }
564 }
565
566 ID.AddBoolean(B: false);
567 QT.getCanonicalType().Profile(ID);
568}
569
570static void profileReflection(llvm::FoldingSetNodeID &ID, APValue V) {
571 ID.AddInteger(I: static_cast<int>(V.getReflectionOperandKind()));
572 switch (V.getReflectionOperandKind()) {
573 case ReflectionKind::Null:
574 return;
575 case ReflectionKind::Type: {
576 const TypeSourceInfo *Info =
577 static_cast<const TypeSourceInfo *>(V.getReflectionOpaqueOperand());
578 profileTypeReflection(ID, QT: Info->getType());
579 return;
580 }
581 }
582 assert(false && "unknown or unimplemented reflection entities");
583}
584
585void APValue::Profile(llvm::FoldingSetNodeID &ID) const {
586 // Note that our profiling assumes that only APValues of the same type are
587 // ever compared. As a result, we don't consider collisions that could only
588 // happen if the types are different. (For example, structs with different
589 // numbers of members could profile the same.)
590
591 ID.AddInteger(I: Kind);
592
593 switch (Kind) {
594 case None:
595 case Indeterminate:
596 return;
597
598 case AddrLabelDiff:
599 ID.AddPointer(Ptr: getAddrLabelDiffLHS()->getLabel()->getCanonicalDecl());
600 ID.AddPointer(Ptr: getAddrLabelDiffRHS()->getLabel()->getCanonicalDecl());
601 return;
602
603 case Struct:
604 for (unsigned I = 0, N = getStructNumBases(); I != N; ++I)
605 getStructBase(i: I).Profile(ID);
606 for (unsigned I = 0, N = getStructNumFields(); I != N; ++I)
607 getStructField(i: I).Profile(ID);
608 for (unsigned I = 0, N = getStructNumVirtualBases(); I != N; ++I)
609 getStructVirtualBase(i: I).Profile(ID);
610 return;
611
612 case Union:
613 if (!getUnionField()) {
614 ID.AddInteger(I: 0);
615 return;
616 }
617 ID.AddInteger(I: getUnionField()->getFieldIndex() + 1);
618 getUnionValue().Profile(ID);
619 return;
620
621 case Array: {
622 if (getArraySize() == 0)
623 return;
624
625 // The profile should not depend on whether the array is expanded or
626 // not, but we don't want to profile the array filler many times for
627 // a large array. So treat all equal trailing elements as the filler.
628 // Elements are profiled in reverse order to support this, and the
629 // first profiled element is followed by a count. For example:
630 //
631 // ['a', 'c', 'x', 'x', 'x'] is profiled as
632 // [5, 'x', 3, 'c', 'a']
633 llvm::FoldingSetNodeID FillerID;
634 (hasArrayFiller() ? getArrayFiller()
635 : getArrayInitializedElt(I: getArrayInitializedElts() - 1))
636 .Profile(ID&: FillerID);
637 ID.AddNodeID(ID: FillerID);
638 unsigned NumFillers = getArraySize() - getArrayInitializedElts();
639 unsigned N = getArrayInitializedElts();
640
641 // Count the number of elements equal to the last one. This loop ends
642 // by adding an integer indicating the number of such elements, with
643 // N set to the number of elements left to profile.
644 while (true) {
645 if (N == 0) {
646 // All elements are fillers.
647 assert(NumFillers == getArraySize());
648 ID.AddInteger(I: NumFillers);
649 break;
650 }
651
652 // No need to check if the last element is equal to the last
653 // element.
654 if (N != getArraySize()) {
655 llvm::FoldingSetNodeID ElemID;
656 getArrayInitializedElt(I: N - 1).Profile(ID&: ElemID);
657 if (ElemID != FillerID) {
658 ID.AddInteger(I: NumFillers);
659 ID.AddNodeID(ID: ElemID);
660 --N;
661 break;
662 }
663 }
664
665 // This is a filler.
666 ++NumFillers;
667 --N;
668 }
669
670 // Emit the remaining elements.
671 for (; N != 0; --N)
672 getArrayInitializedElt(I: N - 1).Profile(ID);
673 return;
674 }
675
676 case Vector:
677 for (unsigned I = 0, N = getVectorLength(); I != N; ++I)
678 getVectorElt(I).Profile(ID);
679 return;
680
681 case Matrix:
682 for (unsigned R = 0, N = getMatrixNumRows(); R != N; ++R)
683 for (unsigned C = 0, M = getMatrixNumColumns(); C != M; ++C)
684 getMatrixElt(Row: R, Col: C).Profile(ID);
685 return;
686
687 case Int:
688 profileIntValue(ID, V: getInt());
689 return;
690
691 case Float:
692 profileIntValue(ID, V: getFloat().bitcastToAPInt());
693 return;
694
695 case FixedPoint:
696 profileIntValue(ID, V: getFixedPoint().getValue());
697 return;
698
699 case ComplexFloat:
700 profileIntValue(ID, V: getComplexFloatReal().bitcastToAPInt());
701 profileIntValue(ID, V: getComplexFloatImag().bitcastToAPInt());
702 return;
703
704 case ComplexInt:
705 profileIntValue(ID, V: getComplexIntReal());
706 profileIntValue(ID, V: getComplexIntImag());
707 return;
708
709 case LValue:
710 getLValueBase().Profile(ID);
711 ID.AddInteger(I: getLValueOffset().getQuantity());
712 ID.AddInteger(I: (isNullPointer() ? 1 : 0) |
713 (isLValueOnePastTheEnd() ? 2 : 0) |
714 (hasLValuePath() ? 4 : 0));
715 if (hasLValuePath()) {
716 ID.AddInteger(I: getLValuePath().size());
717 // For uniqueness, we only need to profile the entries corresponding
718 // to union members, but we don't have the type here so we don't know
719 // how to interpret the entries.
720 for (LValuePathEntry E : getLValuePath())
721 E.Profile(ID);
722 }
723 return;
724
725 case MemberPointer:
726 ID.AddPointer(Ptr: getMemberPointerDecl());
727 ID.AddInteger(I: isMemberPointerToDerivedMember());
728 for (const CXXRecordDecl *D : getMemberPointerPath())
729 ID.AddPointer(Ptr: D);
730 return;
731 case Reflection:
732 profileReflection(ID, V: *this);
733 return;
734 }
735
736 llvm_unreachable("Unknown APValue kind!");
737}
738
739static double GetApproxValue(const llvm::APFloat &F) {
740 llvm::APFloat V = F;
741 bool ignored;
742 V.convert(ToSemantics: llvm::APFloat::IEEEdouble(), RM: llvm::APFloat::rmNearestTiesToEven,
743 losesInfo: &ignored);
744 return V.convertToDouble();
745}
746
747static bool TryPrintAsStringLiteral(raw_ostream &Out,
748 const PrintingPolicy &Policy,
749 const ArrayType *ATy,
750 ArrayRef<APValue> Inits) {
751 if (Inits.empty())
752 return false;
753
754 QualType Ty = ATy->getElementType();
755 if (!Ty->isAnyCharacterType())
756 return false;
757
758 // Nothing we can do about a sequence that is not null-terminated
759 if (!Inits.back().isInt() || !Inits.back().getInt().isZero())
760 return false;
761
762 Inits = Inits.drop_back();
763
764 llvm::SmallString<40> Buf;
765 Buf.push_back(Elt: '"');
766
767 // Better than printing a two-digit sequence of 10 integers.
768 constexpr size_t MaxN = 36;
769 StringRef Ellipsis;
770 if (Inits.size() > MaxN && !Policy.EntireContentsOfLargeArray) {
771 Ellipsis = "[...]";
772 Inits =
773 Inits.take_front(N: std::min(a: MaxN - Ellipsis.size() / 2, b: Inits.size()));
774 }
775
776 for (auto &Val : Inits) {
777 if (!Val.isInt())
778 return false;
779 int64_t Char64 = Val.getInt().getExtValue();
780 if (!isASCII(c: Char64))
781 return false; // Bye bye, see you in integers.
782 auto Ch = static_cast<unsigned char>(Char64);
783 // The diagnostic message is 'quoted'
784 StringRef Escaped = escapeCStyle<EscapeChar::SingleAndDouble>(Ch);
785 if (Escaped.empty()) {
786 if (!isPrintable(c: Ch))
787 return false;
788 Buf.emplace_back(Args&: Ch);
789 } else {
790 Buf.append(RHS: Escaped);
791 }
792 }
793
794 Buf.append(RHS: Ellipsis);
795 Buf.push_back(Elt: '"');
796
797 if (Ty->isWideCharType())
798 Out << 'L';
799 else if (Ty->isChar8Type())
800 Out << "u8";
801 else if (Ty->isChar16Type())
802 Out << 'u';
803 else if (Ty->isChar32Type())
804 Out << 'U';
805
806 Out << Buf;
807 return true;
808}
809
810void APValue::printPretty(raw_ostream &Out, const ASTContext &Ctx,
811 QualType Ty) const {
812 printPretty(OS&: Out, Policy: Ctx.getPrintingPolicy(), Ty, Ctx: &Ctx);
813}
814
815void APValue::printPretty(raw_ostream &Out, const PrintingPolicy &Policy,
816 QualType Ty, const ASTContext *Ctx) const {
817 // There are no objects of type 'void', but values of this type can be
818 // returned from functions.
819 if (Ty->isVoidType()) {
820 Out << "void()";
821 return;
822 }
823
824 if (const auto *AT = Ty->getAs<AtomicType>())
825 Ty = AT->getValueType();
826
827 switch (getKind()) {
828 case APValue::None:
829 Out << "<out of lifetime>";
830 return;
831 case APValue::Indeterminate:
832 Out << "<uninitialized>";
833 return;
834 case APValue::Int:
835 if (Ty->isBooleanType())
836 Out << (getInt().getBoolValue() ? "true" : "false");
837 else
838 Out << getInt();
839 return;
840 case APValue::Float:
841 Out << GetApproxValue(F: getFloat());
842 return;
843 case APValue::FixedPoint:
844 Out << getFixedPoint();
845 return;
846 case APValue::Vector: {
847 Out << '{';
848 QualType ElemTy = Ty->castAs<VectorType>()->getElementType();
849 getVectorElt(I: 0).printPretty(Out, Policy, Ty: ElemTy, Ctx);
850 for (unsigned i = 1; i != getVectorLength(); ++i) {
851 Out << ", ";
852 getVectorElt(I: i).printPretty(Out, Policy, Ty: ElemTy, Ctx);
853 }
854 Out << '}';
855 return;
856 }
857 case APValue::Matrix: {
858 const auto *MT = Ty->castAs<ConstantMatrixType>();
859 QualType ElemTy = MT->getElementType();
860 Out << '{';
861 for (unsigned R = 0; R < getMatrixNumRows(); ++R) {
862 if (R != 0)
863 Out << ", ";
864 Out << '{';
865 for (unsigned C = 0; C < getMatrixNumColumns(); ++C) {
866 if (C != 0)
867 Out << ", ";
868 getMatrixElt(Row: R, Col: C).printPretty(Out, Policy, Ty: ElemTy, Ctx);
869 }
870 Out << '}';
871 }
872 Out << '}';
873 return;
874 }
875 case APValue::ComplexInt:
876 Out << getComplexIntReal() << "+" << getComplexIntImag() << "i";
877 return;
878 case APValue::ComplexFloat:
879 Out << GetApproxValue(F: getComplexFloatReal()) << "+"
880 << GetApproxValue(F: getComplexFloatImag()) << "i";
881 return;
882 case APValue::LValue: {
883 bool IsReference = Ty->isReferenceType();
884 QualType InnerTy
885 = IsReference ? Ty.getNonReferenceType() : Ty->getPointeeType();
886 if (InnerTy.isNull())
887 InnerTy = Ty;
888
889 LValueBase Base = getLValueBase();
890 if (!Base) {
891 if (isNullPointer()) {
892 Out << (Policy.Nullptr ? "nullptr" : "0");
893 } else if (IsReference) {
894 Out << "*(" << InnerTy.stream(Policy) << "*)"
895 << getLValueOffset().getQuantity();
896 } else {
897 Out << "(" << Ty.stream(Policy) << ")"
898 << getLValueOffset().getQuantity();
899 }
900 return;
901 }
902
903 if (!hasLValuePath()) {
904 // No lvalue path: just print the offset.
905 CharUnits O = getLValueOffset();
906 CharUnits S = Ctx ? Ctx->getTypeSizeInCharsIfKnown(Ty: InnerTy).value_or(
907 u: CharUnits::Zero())
908 : CharUnits::Zero();
909 if (!O.isZero()) {
910 if (IsReference)
911 Out << "*(";
912 if (S.isZero() || !O.isMultipleOf(N: S)) {
913 Out << "(char*)";
914 S = CharUnits::One();
915 }
916 Out << '&';
917 } else if (!IsReference) {
918 Out << '&';
919 }
920
921 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
922 Out << *VD;
923 else if (TypeInfoLValue TI = Base.dyn_cast<TypeInfoLValue>()) {
924 TI.print(Out, Policy);
925 } else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
926 Out << "{*new "
927 << Base.getDynamicAllocType().stream(Policy) << "#"
928 << DA.getIndex() << "}";
929 } else {
930 assert(Base.get<const Expr *>() != nullptr &&
931 "Expecting non-null Expr");
932 Base.get<const Expr*>()->printPretty(OS&: Out, Helper: nullptr, Policy);
933 }
934
935 if (!O.isZero()) {
936 Out << " + " << (O / S);
937 if (IsReference)
938 Out << ')';
939 }
940 return;
941 }
942
943 // We have an lvalue path. Print it out nicely.
944 if (!IsReference)
945 Out << '&';
946 else if (isLValueOnePastTheEnd())
947 Out << "*(&";
948
949 QualType ElemTy = Base.getType().getNonReferenceType();
950 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
951 Out << *VD;
952 } else if (TypeInfoLValue TI = Base.dyn_cast<TypeInfoLValue>()) {
953 TI.print(Out, Policy);
954 } else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
955 Out << "{*new " << Base.getDynamicAllocType().stream(Policy) << "#"
956 << DA.getIndex() << "}";
957 } else {
958 const Expr *E = Base.get<const Expr*>();
959 assert(E != nullptr && "Expecting non-null Expr");
960 E->printPretty(OS&: Out, Helper: nullptr, Policy);
961 }
962
963 ArrayRef<LValuePathEntry> Path = getLValuePath();
964 const CXXRecordDecl *CastToBase = nullptr;
965 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
966 if (ElemTy->isRecordType()) {
967 // The lvalue refers to a class type, so the next path entry is a base
968 // or member.
969 const Decl *BaseOrMember = Path[I].getAsBaseOrMember().getPointer();
970 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: BaseOrMember)) {
971 CastToBase = RD;
972 // Leave ElemTy referring to the most-derived class. The actual type
973 // doesn't matter except for array types.
974 } else {
975 const ValueDecl *VD = cast<ValueDecl>(Val: BaseOrMember);
976 Out << ".";
977 if (CastToBase)
978 Out << *CastToBase << "::";
979 Out << *VD;
980 ElemTy = VD->getType();
981 }
982 } else if (ElemTy->isAnyComplexType()) {
983 // The lvalue refers to a complex type
984 Out << (Path[I].getAsArrayIndex() == 0 ? ".real" : ".imag");
985 ElemTy = ElemTy->castAs<ComplexType>()->getElementType();
986 } else {
987 // The lvalue must refer to an array.
988 Out << '[' << Path[I].getAsArrayIndex() << ']';
989 ElemTy = ElemTy->castAsArrayTypeUnsafe()->getElementType();
990 }
991 }
992
993 // Handle formatting of one-past-the-end lvalues.
994 if (isLValueOnePastTheEnd()) {
995 // FIXME: If CastToBase is non-0, we should prefix the output with
996 // "(CastToBase*)".
997 Out << " + 1";
998 if (IsReference)
999 Out << ')';
1000 }
1001 return;
1002 }
1003 case APValue::Array: {
1004 const ArrayType *AT = Ty->castAsArrayTypeUnsafe();
1005 unsigned N = getArrayInitializedElts();
1006 if (N != 0 && TryPrintAsStringLiteral(Out, Policy, ATy: AT,
1007 Inits: {&getArrayInitializedElt(I: 0), N}))
1008 return;
1009 QualType ElemTy = AT->getElementType();
1010 Out << '{';
1011 unsigned I = 0;
1012 switch (N) {
1013 case 0:
1014 for (; I != N; ++I) {
1015 Out << ", ";
1016 if (I == 10 && !Policy.EntireContentsOfLargeArray) {
1017 Out << "...}";
1018 return;
1019 }
1020 [[fallthrough]];
1021 default:
1022 getArrayInitializedElt(I).printPretty(Out, Policy, Ty: ElemTy, Ctx);
1023 }
1024 }
1025 Out << '}';
1026 return;
1027 }
1028 case APValue::Struct: {
1029 Out << '{';
1030 llvm::ListSeparator Comma;
1031 const auto *RD = Ty->castAsRecordDecl();
1032 if (unsigned N = getStructNumBases()) {
1033 const CXXRecordDecl *CD = cast<CXXRecordDecl>(Val: RD);
1034 CXXRecordDecl::base_class_const_iterator BI = CD->bases_begin();
1035 for (unsigned I = 0; I != N; ++I, ++BI) {
1036 assert(BI != CD->bases_end());
1037 Out << Comma;
1038 getStructBase(i: I).printPretty(Out, Policy, Ty: BI->getType(), Ctx);
1039 }
1040 }
1041 for (const auto *FI : RD->fields()) {
1042 Out << Comma;
1043 if (FI->isUnnamedBitField())
1044 continue;
1045 getStructField(i: FI->getFieldIndex())
1046 .printPretty(Out, Policy, Ty: FI->getType(), Ctx);
1047 }
1048 if (unsigned N = getStructNumVirtualBases()) {
1049 const CXXRecordDecl *CD = cast<CXXRecordDecl>(Val: RD);
1050 CXXRecordDecl::base_class_const_iterator BI = CD->vbases_begin();
1051 for (unsigned I = 0; I != N; ++I, ++BI) {
1052 assert(BI != CD->vbases_end());
1053 Out << Comma;
1054 getStructVirtualBase(i: I).printPretty(Out, Policy, Ty: BI->getType(), Ctx);
1055 }
1056 }
1057 Out << '}';
1058 return;
1059 }
1060 case APValue::Union:
1061 Out << '{';
1062 if (const FieldDecl *FD = getUnionField()) {
1063 Out << "." << *FD << " = ";
1064 getUnionValue().printPretty(Out, Policy, Ty: FD->getType(), Ctx);
1065 }
1066 Out << '}';
1067 return;
1068 case APValue::MemberPointer:
1069 // FIXME: This is not enough to unambiguously identify the member in a
1070 // multiple-inheritance scenario.
1071 if (const ValueDecl *VD = getMemberPointerDecl()) {
1072 Out << '&' << *cast<CXXRecordDecl>(Val: VD->getDeclContext()) << "::" << *VD;
1073 return;
1074 }
1075 Out << "0";
1076 return;
1077 case APValue::AddrLabelDiff:
1078 Out << "&&" << getAddrLabelDiffLHS()->getLabel()->getName();
1079 Out << " - ";
1080 Out << "&&" << getAddrLabelDiffRHS()->getLabel()->getName();
1081 return;
1082 case APValue::Reflection:
1083 switch (getReflectionOperandKind()) {
1084 case ReflectionKind::Null:
1085 Out << "std::meta::info{}";
1086 break;
1087 case ReflectionKind::Type: {
1088 const auto *TInfo =
1089 static_cast<const TypeSourceInfo *>(getReflectionOpaqueOperand());
1090 Out << "^^" << TInfo->getType().stream(Policy);
1091 break;
1092 }
1093 }
1094 return;
1095 }
1096 llvm_unreachable("Unknown APValue kind!");
1097}
1098
1099std::string APValue::getAsString(const ASTContext &Ctx, QualType Ty) const {
1100 std::string Result;
1101 llvm::raw_string_ostream Out(Result);
1102 printPretty(Out, Ctx, Ty);
1103 return Result;
1104}
1105
1106bool APValue::toIntegralConstant(APSInt &Result, QualType SrcTy,
1107 const ASTContext &Ctx) const {
1108 if (isInt()) {
1109 Result = getInt();
1110 return true;
1111 }
1112
1113 if (isLValue() && isNullPointer()) {
1114 Result = Ctx.MakeIntValue(Value: Ctx.getTargetNullPointerValue(QT: SrcTy), Type: SrcTy);
1115 return true;
1116 }
1117
1118 if (isLValue() && !getLValueBase()) {
1119 Result = Ctx.MakeIntValue(Value: getLValueOffset().getQuantity(), Type: SrcTy);
1120 return true;
1121 }
1122
1123 return false;
1124}
1125
1126const APValue::LValueBase APValue::getLValueBase() const {
1127 assert(isLValue() && "Invalid accessor");
1128 return ((const LV *)(const void *)&Data)->Base;
1129}
1130
1131bool APValue::isLValueOnePastTheEnd() const {
1132 assert(isLValue() && "Invalid accessor");
1133 return ((const LV *)(const void *)&Data)->IsOnePastTheEnd;
1134}
1135
1136CharUnits &APValue::getLValueOffset() {
1137 assert(isLValue() && "Invalid accessor");
1138 return ((LV *)(void *)&Data)->Offset;
1139}
1140
1141bool APValue::hasLValuePath() const {
1142 assert(isLValue() && "Invalid accessor");
1143 return ((const LV *)(const char *)&Data)->hasPath();
1144}
1145
1146ArrayRef<APValue::LValuePathEntry> APValue::getLValuePath() const {
1147 assert(isLValue() && hasLValuePath() && "Invalid accessor");
1148 const LV &LVal = *((const LV *)(const char *)&Data);
1149 return {LVal.getPath(), LVal.PathLength};
1150}
1151
1152unsigned APValue::getLValueCallIndex() const {
1153 assert(isLValue() && "Invalid accessor");
1154 return ((const LV *)(const char *)&Data)->Base.getCallIndex();
1155}
1156
1157unsigned APValue::getLValueVersion() const {
1158 assert(isLValue() && "Invalid accessor");
1159 return ((const LV *)(const char *)&Data)->Base.getVersion();
1160}
1161
1162bool APValue::isNullPointer() const {
1163 assert(isLValue() && "Invalid usage");
1164 return ((const LV *)(const char *)&Data)->IsNullPtr;
1165}
1166
1167void APValue::setLValue(LValueBase B, CharUnits O, NoLValuePath,
1168 bool IsNullPtr) {
1169 assert(isLValue() && "Invalid accessor");
1170 LV &LVal = *((LV *)(char *)&Data);
1171 LVal.Base = B;
1172 LVal.IsOnePastTheEnd = false;
1173 LVal.Offset = O;
1174 LVal.resizePath(Length: (unsigned)-1);
1175 LVal.IsNullPtr = IsNullPtr;
1176}
1177
1178MutableArrayRef<APValue::LValuePathEntry>
1179APValue::setLValueUninit(LValueBase B, CharUnits O, unsigned Size,
1180 bool IsOnePastTheEnd, bool IsNullPtr) {
1181 assert(isLValue() && "Invalid accessor");
1182 LV &LVal = *((LV *)(char *)&Data);
1183 LVal.Base = B;
1184 LVal.IsOnePastTheEnd = IsOnePastTheEnd;
1185 LVal.Offset = O;
1186 LVal.IsNullPtr = IsNullPtr;
1187 LVal.resizePath(Length: Size);
1188 return {LVal.getPath(), Size};
1189}
1190
1191void APValue::setLValue(LValueBase B, CharUnits O,
1192 ArrayRef<LValuePathEntry> Path, bool IsOnePastTheEnd,
1193 bool IsNullPtr) {
1194 MutableArrayRef<APValue::LValuePathEntry> InternalPath =
1195 setLValueUninit(B, O, Size: Path.size(), IsOnePastTheEnd, IsNullPtr);
1196 if (Path.size()) {
1197 memcpy(dest: InternalPath.data(), src: Path.data(),
1198 n: Path.size() * sizeof(LValuePathEntry));
1199 }
1200}
1201
1202void APValue::setUnion(const FieldDecl *Field, const APValue &Value) {
1203 assert(isUnion() && "Invalid accessor");
1204 ((UnionData *)(char *)&Data)->Field =
1205 Field ? Field->getCanonicalDecl() : nullptr;
1206 *((UnionData *)(char *)&Data)->Value = Value;
1207}
1208
1209const ValueDecl *APValue::getMemberPointerDecl() const {
1210 assert(isMemberPointer() && "Invalid accessor");
1211 const MemberPointerData &MPD =
1212 *((const MemberPointerData *)(const char *)&Data);
1213 return MPD.MemberAndIsDerivedMember.getPointer();
1214}
1215
1216bool APValue::isMemberPointerToDerivedMember() const {
1217 assert(isMemberPointer() && "Invalid accessor");
1218 const MemberPointerData &MPD =
1219 *((const MemberPointerData *)(const char *)&Data);
1220 return MPD.MemberAndIsDerivedMember.getInt();
1221}
1222
1223ArrayRef<const CXXRecordDecl*> APValue::getMemberPointerPath() const {
1224 assert(isMemberPointer() && "Invalid accessor");
1225 const MemberPointerData &MPD =
1226 *((const MemberPointerData *)(const char *)&Data);
1227 return {MPD.getPath(), MPD.PathLength};
1228}
1229
1230void APValue::MakeLValue() {
1231 assert(isAbsent() && "Bad state change");
1232 static_assert(sizeof(LV) <= DataSize, "LV too big");
1233 new ((void *)(char *)&Data) LV();
1234 Kind = LValue;
1235}
1236
1237void APValue::MakeArray(unsigned InitElts, unsigned Size) {
1238 assert(isAbsent() && "Bad state change");
1239 new ((void *)(char *)&Data) Arr(InitElts, Size);
1240 Kind = Array;
1241}
1242
1243MutableArrayRef<const CXXRecordDecl *>
1244APValue::setMemberPointerUninit(const ValueDecl *Member, bool IsDerivedMember,
1245 unsigned Size) {
1246 assert(isAbsent() && "Bad state change");
1247 MemberPointerData *MPD = new ((void *)(char *)&Data) MemberPointerData;
1248 Kind = MemberPointer;
1249 MPD->MemberAndIsDerivedMember.setPointer(
1250 Member ? cast<ValueDecl>(Val: Member->getCanonicalDecl()) : nullptr);
1251 MPD->MemberAndIsDerivedMember.setInt(IsDerivedMember);
1252 MPD->resizePath(Length: Size);
1253 return {MPD->getPath(), MPD->PathLength};
1254}
1255
1256void APValue::MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember,
1257 ArrayRef<const CXXRecordDecl *> Path) {
1258 MutableArrayRef<const CXXRecordDecl *> InternalPath =
1259 setMemberPointerUninit(Member, IsDerivedMember, Size: Path.size());
1260 for (unsigned I = 0; I != Path.size(); ++I)
1261 InternalPath[I] = Path[I]->getCanonicalDecl();
1262}
1263
1264LinkageInfo LinkageComputer::getLVForValue(const APValue &V,
1265 LVComputationKind computation) {
1266 LinkageInfo LV = LinkageInfo::external();
1267
1268 auto MergeLV = [&](LinkageInfo MergeLV) { LV.merge(other: MergeLV); };
1269 V.visit(Visitor: [&](const APValue &Value) {
1270 switch (Value.getKind()) {
1271 case APValue::AddrLabelDiff:
1272 // Even for an inline function, it's not reasonable to treat a difference
1273 // between the addresses of labels as an external value.
1274 LV = LinkageInfo::internal();
1275 return false;
1276
1277 case APValue::LValue:
1278 if (!Value.getLValueBase()) {
1279 // Null or absolute address: this is external.
1280 } else if (const auto *VD =
1281 Value.getLValueBase().dyn_cast<const ValueDecl *>()) {
1282 MergeLV(getLVForDecl(D: VD, computation));
1283 } else if (const auto TI =
1284 Value.getLValueBase().dyn_cast<TypeInfoLValue>()) {
1285 MergeLV(getLVForType(T: *TI.getType(), computation));
1286 } else if (const Expr *E =
1287 Value.getLValueBase().dyn_cast<const Expr *>()) {
1288 // Almost all expression bases are internal. The exception is
1289 // lifetime-extended temporaries.
1290 // FIXME: These should be modeled as having the
1291 // LifetimeExtendedTemporaryDecl itself as the base.
1292 // FIXME: If we permit Objective-C object literals in template
1293 // arguments, they should not imply internal linkage.
1294 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
1295 if (!MTE || MTE->getStorageDuration() == SD_FullExpression)
1296 LV = LinkageInfo::internal();
1297 else
1298 MergeLV(getLVForDecl(D: MTE->getExtendingDecl(), computation));
1299 } else {
1300 assert(Value.getLValueBase().is<DynamicAllocLValue>() &&
1301 "unexpected LValueBase kind");
1302 LV = LinkageInfo::internal();
1303 }
1304 // The lvalue path doesn't matter: pointers to all subobjects always have
1305 // the same visibility as pointers to the complete object.
1306 return LV.getLinkage() != Linkage::Internal;
1307
1308 case APValue::MemberPointer:
1309 if (const NamedDecl *D = Value.getMemberPointerDecl())
1310 MergeLV(getLVForDecl(D, computation));
1311 // Note that we could have a base-to-derived conversion here to a member
1312 // of a derived class with less linkage/visibility. That's covered by the
1313 // linkage and visibility of the value's type.
1314 return LV.getLinkage() != Linkage::Internal;
1315
1316 default:
1317 return true;
1318 }
1319 });
1320
1321 return LV;
1322}
1323