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