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