xref: /llvm-project/clang/lib/AST/APValue.cpp (revision 53122ce2b39f5fb52c7a5933cc4cf32aad43568f)
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 "clang/AST/ASTContext.h"
15 #include "clang/AST/CharUnits.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/Type.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
21 using namespace clang;
22 
23 /// The identity of a type_info object depends on the canonical unqualified
24 /// type only.
25 TypeInfoLValue::TypeInfoLValue(const Type *T)
26     : T(T->getCanonicalTypeUnqualified().getTypePtr()) {}
27 
28 void TypeInfoLValue::print(llvm::raw_ostream &Out,
29                            const PrintingPolicy &Policy) const {
30   Out << "typeid(";
31   QualType(getType(), 0).print(Out, Policy);
32   Out << ")";
33 }
34 
35 static_assert(
36     1 << llvm::PointerLikeTypeTraits<TypeInfoLValue>::NumLowBitsAvailable <=
37         alignof(Type),
38     "Type is insufficiently aligned");
39 
40 APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I, unsigned V)
41     : Ptr(P ? cast<ValueDecl>(P->getCanonicalDecl()) : nullptr), Local{I, V} {}
42 APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
43     : Ptr(P), Local{I, V} {}
44 
45 APValue::LValueBase APValue::LValueBase::getDynamicAlloc(DynamicAllocLValue LV,
46                                                          QualType Type) {
47   LValueBase Base;
48   Base.Ptr = LV;
49   Base.DynamicAllocType = Type.getAsOpaquePtr();
50   return Base;
51 }
52 
53 APValue::LValueBase APValue::LValueBase::getTypeInfo(TypeInfoLValue LV,
54                                                      QualType TypeInfo) {
55   LValueBase Base;
56   Base.Ptr = LV;
57   Base.TypeInfoType = TypeInfo.getAsOpaquePtr();
58   return Base;
59 }
60 
61 unsigned APValue::LValueBase::getCallIndex() const {
62   return (is<TypeInfoLValue>() || is<DynamicAllocLValue>()) ? 0
63                                                             : Local.CallIndex;
64 }
65 
66 unsigned APValue::LValueBase::getVersion() const {
67   return (is<TypeInfoLValue>() || is<DynamicAllocLValue>()) ? 0 : Local.Version;
68 }
69 
70 QualType APValue::LValueBase::getTypeInfoType() const {
71   assert(is<TypeInfoLValue>() && "not a type_info lvalue");
72   return QualType::getFromOpaquePtr(TypeInfoType);
73 }
74 
75 QualType APValue::LValueBase::getDynamicAllocType() const {
76   assert(is<DynamicAllocLValue>() && "not a dynamic allocation lvalue");
77   return QualType::getFromOpaquePtr(DynamicAllocType);
78 }
79 
80 void APValue::LValueBase::Profile(llvm::FoldingSetNodeID &ID) const {
81   ID.AddPointer(Ptr.getOpaqueValue());
82   if (is<TypeInfoLValue>() || is<DynamicAllocLValue>())
83     return;
84   ID.AddInteger(Local.CallIndex);
85   ID.AddInteger(Local.Version);
86 }
87 
88 namespace clang {
89 bool operator==(const APValue::LValueBase &LHS,
90                 const APValue::LValueBase &RHS) {
91   if (LHS.Ptr != RHS.Ptr)
92     return false;
93   if (LHS.is<TypeInfoLValue>() || LHS.is<DynamicAllocLValue>())
94     return true;
95   return LHS.Local.CallIndex == RHS.Local.CallIndex &&
96          LHS.Local.Version == RHS.Local.Version;
97 }
98 }
99 
100 APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType BaseOrMember) {
101   if (const Decl *D = BaseOrMember.getPointer())
102     BaseOrMember.setPointer(D->getCanonicalDecl());
103   Value = reinterpret_cast<uintptr_t>(BaseOrMember.getOpaqueValue());
104 }
105 
106 void APValue::LValuePathEntry::Profile(llvm::FoldingSetNodeID &ID) const {
107   ID.AddInteger(Value);
108 }
109 
110 namespace {
111   struct LVBase {
112     APValue::LValueBase Base;
113     CharUnits Offset;
114     unsigned PathLength;
115     bool IsNullPtr : 1;
116     bool IsOnePastTheEnd : 1;
117   };
118 }
119 
120 void *APValue::LValueBase::getOpaqueValue() const {
121   return Ptr.getOpaqueValue();
122 }
123 
124 bool APValue::LValueBase::isNull() const {
125   return Ptr.isNull();
126 }
127 
128 APValue::LValueBase::operator bool () const {
129   return static_cast<bool>(Ptr);
130 }
131 
132 clang::APValue::LValueBase
133 llvm::DenseMapInfo<clang::APValue::LValueBase>::getEmptyKey() {
134   clang::APValue::LValueBase B;
135   B.Ptr = DenseMapInfo<const ValueDecl*>::getEmptyKey();
136   return B;
137 }
138 
139 clang::APValue::LValueBase
140 llvm::DenseMapInfo<clang::APValue::LValueBase>::getTombstoneKey() {
141   clang::APValue::LValueBase B;
142   B.Ptr = DenseMapInfo<const ValueDecl*>::getTombstoneKey();
143   return B;
144 }
145 
146 namespace clang {
147 llvm::hash_code hash_value(const APValue::LValueBase &Base) {
148   if (Base.is<TypeInfoLValue>() || Base.is<DynamicAllocLValue>())
149     return llvm::hash_value(Base.getOpaqueValue());
150   return llvm::hash_combine(Base.getOpaqueValue(), Base.getCallIndex(),
151                             Base.getVersion());
152 }
153 }
154 
155 unsigned llvm::DenseMapInfo<clang::APValue::LValueBase>::getHashValue(
156     const clang::APValue::LValueBase &Base) {
157   return hash_value(Base);
158 }
159 
160 bool llvm::DenseMapInfo<clang::APValue::LValueBase>::isEqual(
161     const clang::APValue::LValueBase &LHS,
162     const clang::APValue::LValueBase &RHS) {
163   return LHS == RHS;
164 }
165 
166 struct APValue::LV : LVBase {
167   static const unsigned InlinePathSpace =
168       (DataSize - sizeof(LVBase)) / sizeof(LValuePathEntry);
169 
170   /// Path - The sequence of base classes, fields and array indices to follow to
171   /// walk from Base to the subobject. When performing GCC-style folding, there
172   /// may not be such a path.
173   union {
174     LValuePathEntry Path[InlinePathSpace];
175     LValuePathEntry *PathPtr;
176   };
177 
178   LV() { PathLength = (unsigned)-1; }
179   ~LV() { resizePath(0); }
180 
181   void resizePath(unsigned Length) {
182     if (Length == PathLength)
183       return;
184     if (hasPathPtr())
185       delete [] PathPtr;
186     PathLength = Length;
187     if (hasPathPtr())
188       PathPtr = new LValuePathEntry[Length];
189   }
190 
191   bool hasPath() const { return PathLength != (unsigned)-1; }
192   bool hasPathPtr() const { return hasPath() && PathLength > InlinePathSpace; }
193 
194   LValuePathEntry *getPath() { return hasPathPtr() ? PathPtr : Path; }
195   const LValuePathEntry *getPath() const {
196     return hasPathPtr() ? PathPtr : Path;
197   }
198 };
199 
200 namespace {
201   struct MemberPointerBase {
202     llvm::PointerIntPair<const ValueDecl*, 1, bool> MemberAndIsDerivedMember;
203     unsigned PathLength;
204   };
205 }
206 
207 struct APValue::MemberPointerData : MemberPointerBase {
208   static const unsigned InlinePathSpace =
209       (DataSize - sizeof(MemberPointerBase)) / sizeof(const CXXRecordDecl*);
210   typedef const CXXRecordDecl *PathElem;
211   union {
212     PathElem Path[InlinePathSpace];
213     PathElem *PathPtr;
214   };
215 
216   MemberPointerData() { PathLength = 0; }
217   ~MemberPointerData() { resizePath(0); }
218 
219   void resizePath(unsigned Length) {
220     if (Length == PathLength)
221       return;
222     if (hasPathPtr())
223       delete [] PathPtr;
224     PathLength = Length;
225     if (hasPathPtr())
226       PathPtr = new PathElem[Length];
227   }
228 
229   bool hasPathPtr() const { return PathLength > InlinePathSpace; }
230 
231   PathElem *getPath() { return hasPathPtr() ? PathPtr : Path; }
232   const PathElem *getPath() const {
233     return hasPathPtr() ? PathPtr : Path;
234   }
235 };
236 
237 // FIXME: Reduce the malloc traffic here.
238 
239 APValue::Arr::Arr(unsigned NumElts, unsigned Size) :
240   Elts(new APValue[NumElts + (NumElts != Size ? 1 : 0)]),
241   NumElts(NumElts), ArrSize(Size) {}
242 APValue::Arr::~Arr() { delete [] Elts; }
243 
244 APValue::StructData::StructData(unsigned NumBases, unsigned NumFields) :
245   Elts(new APValue[NumBases+NumFields]),
246   NumBases(NumBases), NumFields(NumFields) {}
247 APValue::StructData::~StructData() {
248   delete [] Elts;
249 }
250 
251 APValue::UnionData::UnionData() : Field(nullptr), Value(new APValue) {}
252 APValue::UnionData::~UnionData () {
253   delete Value;
254 }
255 
256 APValue::APValue(const APValue &RHS) : Kind(None) {
257   switch (RHS.getKind()) {
258   case None:
259   case Indeterminate:
260     Kind = RHS.getKind();
261     break;
262   case Int:
263     MakeInt();
264     setInt(RHS.getInt());
265     break;
266   case Float:
267     MakeFloat();
268     setFloat(RHS.getFloat());
269     break;
270   case FixedPoint: {
271     APFixedPoint FXCopy = RHS.getFixedPoint();
272     MakeFixedPoint(std::move(FXCopy));
273     break;
274   }
275   case Vector:
276     MakeVector();
277     setVector(((const Vec *)(const char *)RHS.Data.buffer)->Elts,
278               RHS.getVectorLength());
279     break;
280   case ComplexInt:
281     MakeComplexInt();
282     setComplexInt(RHS.getComplexIntReal(), RHS.getComplexIntImag());
283     break;
284   case ComplexFloat:
285     MakeComplexFloat();
286     setComplexFloat(RHS.getComplexFloatReal(), RHS.getComplexFloatImag());
287     break;
288   case LValue:
289     MakeLValue();
290     if (RHS.hasLValuePath())
291       setLValue(RHS.getLValueBase(), RHS.getLValueOffset(), RHS.getLValuePath(),
292                 RHS.isLValueOnePastTheEnd(), RHS.isNullPointer());
293     else
294       setLValue(RHS.getLValueBase(), RHS.getLValueOffset(), NoLValuePath(),
295                 RHS.isNullPointer());
296     break;
297   case Array:
298     MakeArray(RHS.getArrayInitializedElts(), RHS.getArraySize());
299     for (unsigned I = 0, N = RHS.getArrayInitializedElts(); I != N; ++I)
300       getArrayInitializedElt(I) = RHS.getArrayInitializedElt(I);
301     if (RHS.hasArrayFiller())
302       getArrayFiller() = RHS.getArrayFiller();
303     break;
304   case Struct:
305     MakeStruct(RHS.getStructNumBases(), RHS.getStructNumFields());
306     for (unsigned I = 0, N = RHS.getStructNumBases(); I != N; ++I)
307       getStructBase(I) = RHS.getStructBase(I);
308     for (unsigned I = 0, N = RHS.getStructNumFields(); I != N; ++I)
309       getStructField(I) = RHS.getStructField(I);
310     break;
311   case Union:
312     MakeUnion();
313     setUnion(RHS.getUnionField(), RHS.getUnionValue());
314     break;
315   case MemberPointer:
316     MakeMemberPointer(RHS.getMemberPointerDecl(),
317                       RHS.isMemberPointerToDerivedMember(),
318                       RHS.getMemberPointerPath());
319     break;
320   case AddrLabelDiff:
321     MakeAddrLabelDiff();
322     setAddrLabelDiff(RHS.getAddrLabelDiffLHS(), RHS.getAddrLabelDiffRHS());
323     break;
324   }
325 }
326 
327 APValue::APValue(APValue &&RHS) : Kind(RHS.Kind), Data(RHS.Data) {
328   RHS.Kind = None;
329 }
330 
331 APValue &APValue::operator=(const APValue &RHS) {
332   if (this != &RHS)
333     *this = APValue(RHS);
334   return *this;
335 }
336 
337 APValue &APValue::operator=(APValue &&RHS) {
338   if (Kind != None && Kind != Indeterminate)
339     DestroyDataAndMakeUninit();
340   Kind = RHS.Kind;
341   Data = RHS.Data;
342   RHS.Kind = None;
343   return *this;
344 }
345 
346 void APValue::DestroyDataAndMakeUninit() {
347   if (Kind == Int)
348     ((APSInt*)(char*)Data.buffer)->~APSInt();
349   else if (Kind == Float)
350     ((APFloat*)(char*)Data.buffer)->~APFloat();
351   else if (Kind == FixedPoint)
352     ((APFixedPoint *)(char *)Data.buffer)->~APFixedPoint();
353   else if (Kind == Vector)
354     ((Vec*)(char*)Data.buffer)->~Vec();
355   else if (Kind == ComplexInt)
356     ((ComplexAPSInt*)(char*)Data.buffer)->~ComplexAPSInt();
357   else if (Kind == ComplexFloat)
358     ((ComplexAPFloat*)(char*)Data.buffer)->~ComplexAPFloat();
359   else if (Kind == LValue)
360     ((LV*)(char*)Data.buffer)->~LV();
361   else if (Kind == Array)
362     ((Arr*)(char*)Data.buffer)->~Arr();
363   else if (Kind == Struct)
364     ((StructData*)(char*)Data.buffer)->~StructData();
365   else if (Kind == Union)
366     ((UnionData*)(char*)Data.buffer)->~UnionData();
367   else if (Kind == MemberPointer)
368     ((MemberPointerData*)(char*)Data.buffer)->~MemberPointerData();
369   else if (Kind == AddrLabelDiff)
370     ((AddrLabelDiffData*)(char*)Data.buffer)->~AddrLabelDiffData();
371   Kind = None;
372 }
373 
374 bool APValue::needsCleanup() const {
375   switch (getKind()) {
376   case None:
377   case Indeterminate:
378   case AddrLabelDiff:
379     return false;
380   case Struct:
381   case Union:
382   case Array:
383   case Vector:
384     return true;
385   case Int:
386     return getInt().needsCleanup();
387   case Float:
388     return getFloat().needsCleanup();
389   case FixedPoint:
390     return getFixedPoint().getValue().needsCleanup();
391   case ComplexFloat:
392     assert(getComplexFloatImag().needsCleanup() ==
393                getComplexFloatReal().needsCleanup() &&
394            "In _Complex float types, real and imaginary values always have the "
395            "same size.");
396     return getComplexFloatReal().needsCleanup();
397   case ComplexInt:
398     assert(getComplexIntImag().needsCleanup() ==
399                getComplexIntReal().needsCleanup() &&
400            "In _Complex int types, real and imaginary values must have the "
401            "same size.");
402     return getComplexIntReal().needsCleanup();
403   case LValue:
404     return reinterpret_cast<const LV *>(Data.buffer)->hasPathPtr();
405   case MemberPointer:
406     return reinterpret_cast<const MemberPointerData *>(Data.buffer)
407         ->hasPathPtr();
408   }
409   llvm_unreachable("Unknown APValue kind!");
410 }
411 
412 void APValue::swap(APValue &RHS) {
413   std::swap(Kind, RHS.Kind);
414   std::swap(Data, RHS.Data);
415 }
416 
417 void APValue::Profile(llvm::FoldingSetNodeID &ID) const {
418   ID.AddInteger(Kind);
419 
420   switch (Kind) {
421   case None:
422   case Indeterminate:
423     return;
424 
425   case AddrLabelDiff:
426     ID.AddPointer(getAddrLabelDiffLHS()->getLabel()->getCanonicalDecl());
427     ID.AddPointer(getAddrLabelDiffRHS()->getLabel()->getCanonicalDecl());
428     return;
429 
430   case Struct:
431     ID.AddInteger(getStructNumBases());
432     for (unsigned I = 0, N = getStructNumBases(); I != N; ++I)
433       getStructBase(I).Profile(ID);
434     ID.AddInteger(getStructNumFields());
435     for (unsigned I = 0, N = getStructNumFields(); I != N; ++I)
436       getStructField(I).Profile(ID);
437     return;
438 
439   case Union:
440     if (!getUnionField()) {
441       ID.AddPointer(nullptr);
442       return;
443     }
444     ID.AddPointer(getUnionField()->getCanonicalDecl());
445     getUnionValue().Profile(ID);
446     return;
447 
448   case Array: {
449     ID.AddInteger(getArraySize());
450     if (getArraySize() == 0)
451       return;
452 
453     // The profile should not depend on whether the array is expanded or
454     // not, but we don't want to profile the array filler many times for
455     // a large array. So treat all equal trailing elements as the filler.
456     // Elements are profiled in reverse order to support this, and the
457     // first profiled element is followed by a count. For example:
458     //
459     //   ['a', 'c', 'x', 'x', 'x'] is profiled as
460     //   [5, 'x', 3, 'c', 'a']
461     llvm::FoldingSetNodeID FillerID;
462     (hasArrayFiller() ? getArrayFiller()
463                       : getArrayInitializedElt(getArrayInitializedElts() - 1))
464         .Profile(FillerID);
465     ID.AddNodeID(FillerID);
466     unsigned NumFillers = getArraySize() - getArrayInitializedElts();
467     unsigned N = getArrayInitializedElts();
468 
469     // Count the number of elements equal to the last one. This loop ends
470     // by adding an integer indicating the number of such elements, with
471     // N set to the number of elements left to profile.
472     while (true) {
473       if (N == 0) {
474         // All elements are fillers.
475         assert(NumFillers == getArraySize());
476         ID.AddInteger(NumFillers);
477         break;
478       }
479 
480       // No need to check if the last element is equal to the last
481       // element.
482       if (N != getArraySize()) {
483         llvm::FoldingSetNodeID ElemID;
484         getArrayInitializedElt(N - 1).Profile(ElemID);
485         if (ElemID != FillerID) {
486           ID.AddInteger(NumFillers);
487           ID.AddNodeID(ElemID);
488           --N;
489           break;
490         }
491       }
492 
493       // This is a filler.
494       ++NumFillers;
495       --N;
496     }
497 
498     // Emit the remaining elements.
499     for (; N != 0; --N)
500       getArrayInitializedElt(N - 1).Profile(ID);
501     return;
502   }
503 
504   case Vector:
505     ID.AddInteger(getVectorLength());
506     for (unsigned I = 0, N = getVectorLength(); I != N; ++I)
507       getVectorElt(I).Profile(ID);
508     return;
509 
510   case Int:
511     // We don't need to include the sign bit; it's implied by the type.
512     getInt().APInt::Profile(ID);
513     return;
514 
515   case Float:
516     getFloat().Profile(ID);
517     return;
518 
519   case FixedPoint:
520     // We don't need to include the fixed-point semantics; they're
521     // implied by the type.
522     getFixedPoint().getValue().APInt::Profile(ID);
523     return;
524 
525   case ComplexFloat:
526     getComplexFloatReal().Profile(ID);
527     getComplexFloatImag().Profile(ID);
528     return;
529 
530   case ComplexInt:
531     getComplexIntReal().APInt::Profile(ID);
532     getComplexIntImag().APInt::Profile(ID);
533     return;
534 
535   case LValue:
536     getLValueBase().Profile(ID);
537     ID.AddInteger(getLValueOffset().getQuantity());
538     ID.AddInteger(isNullPointer());
539     ID.AddInteger(isLValueOnePastTheEnd());
540     // For uniqueness, we only need to profile the entries corresponding
541     // to union members, but we don't have the type here so we don't know
542     // how to interpret the entries.
543     for (LValuePathEntry E : getLValuePath())
544       E.Profile(ID);
545     return;
546 
547   case MemberPointer:
548     ID.AddPointer(getMemberPointerDecl());
549     ID.AddInteger(isMemberPointerToDerivedMember());
550     for (const CXXRecordDecl *D : getMemberPointerPath())
551       ID.AddPointer(D);
552     return;
553   }
554 
555   llvm_unreachable("Unknown APValue kind!");
556 }
557 
558 static double GetApproxValue(const llvm::APFloat &F) {
559   llvm::APFloat V = F;
560   bool ignored;
561   V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
562             &ignored);
563   return V.convertToDouble();
564 }
565 
566 void APValue::printPretty(raw_ostream &Out, const ASTContext &Ctx,
567                           QualType Ty) const {
568   // There are no objects of type 'void', but values of this type can be
569   // returned from functions.
570   if (Ty->isVoidType()) {
571     Out << "void()";
572     return;
573   }
574 
575   switch (getKind()) {
576   case APValue::None:
577     Out << "<out of lifetime>";
578     return;
579   case APValue::Indeterminate:
580     Out << "<uninitialized>";
581     return;
582   case APValue::Int:
583     if (Ty->isBooleanType())
584       Out << (getInt().getBoolValue() ? "true" : "false");
585     else
586       Out << getInt();
587     return;
588   case APValue::Float:
589     Out << GetApproxValue(getFloat());
590     return;
591   case APValue::FixedPoint:
592     Out << getFixedPoint();
593     return;
594   case APValue::Vector: {
595     Out << '{';
596     QualType ElemTy = Ty->castAs<VectorType>()->getElementType();
597     getVectorElt(0).printPretty(Out, Ctx, ElemTy);
598     for (unsigned i = 1; i != getVectorLength(); ++i) {
599       Out << ", ";
600       getVectorElt(i).printPretty(Out, Ctx, ElemTy);
601     }
602     Out << '}';
603     return;
604   }
605   case APValue::ComplexInt:
606     Out << getComplexIntReal() << "+" << getComplexIntImag() << "i";
607     return;
608   case APValue::ComplexFloat:
609     Out << GetApproxValue(getComplexFloatReal()) << "+"
610         << GetApproxValue(getComplexFloatImag()) << "i";
611     return;
612   case APValue::LValue: {
613     bool IsReference = Ty->isReferenceType();
614     QualType InnerTy
615       = IsReference ? Ty.getNonReferenceType() : Ty->getPointeeType();
616     if (InnerTy.isNull())
617       InnerTy = Ty;
618 
619     LValueBase Base = getLValueBase();
620     if (!Base) {
621       if (isNullPointer()) {
622         Out << (Ctx.getLangOpts().CPlusPlus11 ? "nullptr" : "0");
623       } else if (IsReference) {
624         Out << "*(" << InnerTy.stream(Ctx.getPrintingPolicy()) << "*)"
625             << getLValueOffset().getQuantity();
626       } else {
627         Out << "(" << Ty.stream(Ctx.getPrintingPolicy()) << ")"
628             << getLValueOffset().getQuantity();
629       }
630       return;
631     }
632 
633     if (!hasLValuePath()) {
634       // No lvalue path: just print the offset.
635       CharUnits O = getLValueOffset();
636       CharUnits S = Ctx.getTypeSizeInChars(InnerTy);
637       if (!O.isZero()) {
638         if (IsReference)
639           Out << "*(";
640         if (O % S) {
641           Out << "(char*)";
642           S = CharUnits::One();
643         }
644         Out << '&';
645       } else if (!IsReference) {
646         Out << '&';
647       }
648 
649       if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
650         Out << *VD;
651       else if (TypeInfoLValue TI = Base.dyn_cast<TypeInfoLValue>()) {
652         TI.print(Out, Ctx.getPrintingPolicy());
653       } else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
654         Out << "{*new "
655             << Base.getDynamicAllocType().stream(Ctx.getPrintingPolicy()) << "#"
656             << DA.getIndex() << "}";
657       } else {
658         assert(Base.get<const Expr *>() != nullptr &&
659                "Expecting non-null Expr");
660         Base.get<const Expr*>()->printPretty(Out, nullptr,
661                                              Ctx.getPrintingPolicy());
662       }
663 
664       if (!O.isZero()) {
665         Out << " + " << (O / S);
666         if (IsReference)
667           Out << ')';
668       }
669       return;
670     }
671 
672     // We have an lvalue path. Print it out nicely.
673     if (!IsReference)
674       Out << '&';
675     else if (isLValueOnePastTheEnd())
676       Out << "*(&";
677 
678     QualType ElemTy;
679     if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
680       Out << *VD;
681       ElemTy = VD->getType();
682     } else if (TypeInfoLValue TI = Base.dyn_cast<TypeInfoLValue>()) {
683       TI.print(Out, Ctx.getPrintingPolicy());
684       ElemTy = Base.getTypeInfoType();
685     } else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
686       Out << "{*new "
687           << Base.getDynamicAllocType().stream(Ctx.getPrintingPolicy()) << "#"
688           << DA.getIndex() << "}";
689       ElemTy = Base.getDynamicAllocType();
690     } else {
691       const Expr *E = Base.get<const Expr*>();
692       assert(E != nullptr && "Expecting non-null Expr");
693       E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
694       // FIXME: This is wrong if E is a MaterializeTemporaryExpr with an lvalue
695       // adjustment.
696       ElemTy = E->getType();
697     }
698 
699     ArrayRef<LValuePathEntry> Path = getLValuePath();
700     const CXXRecordDecl *CastToBase = nullptr;
701     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
702       if (ElemTy->getAs<RecordType>()) {
703         // The lvalue refers to a class type, so the next path entry is a base
704         // or member.
705         const Decl *BaseOrMember = Path[I].getAsBaseOrMember().getPointer();
706         if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(BaseOrMember)) {
707           CastToBase = RD;
708           ElemTy = Ctx.getRecordType(RD);
709         } else {
710           const ValueDecl *VD = cast<ValueDecl>(BaseOrMember);
711           Out << ".";
712           if (CastToBase)
713             Out << *CastToBase << "::";
714           Out << *VD;
715           ElemTy = VD->getType();
716         }
717       } else {
718         // The lvalue must refer to an array.
719         Out << '[' << Path[I].getAsArrayIndex() << ']';
720         ElemTy = Ctx.getAsArrayType(ElemTy)->getElementType();
721       }
722     }
723 
724     // Handle formatting of one-past-the-end lvalues.
725     if (isLValueOnePastTheEnd()) {
726       // FIXME: If CastToBase is non-0, we should prefix the output with
727       // "(CastToBase*)".
728       Out << " + 1";
729       if (IsReference)
730         Out << ')';
731     }
732     return;
733   }
734   case APValue::Array: {
735     const ArrayType *AT = Ctx.getAsArrayType(Ty);
736     QualType ElemTy = AT->getElementType();
737     Out << '{';
738     if (unsigned N = getArrayInitializedElts()) {
739       getArrayInitializedElt(0).printPretty(Out, Ctx, ElemTy);
740       for (unsigned I = 1; I != N; ++I) {
741         Out << ", ";
742         if (I == 10) {
743           // Avoid printing out the entire contents of large arrays.
744           Out << "...";
745           break;
746         }
747         getArrayInitializedElt(I).printPretty(Out, Ctx, ElemTy);
748       }
749     }
750     Out << '}';
751     return;
752   }
753   case APValue::Struct: {
754     Out << '{';
755     const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
756     bool First = true;
757     if (unsigned N = getStructNumBases()) {
758       const CXXRecordDecl *CD = cast<CXXRecordDecl>(RD);
759       CXXRecordDecl::base_class_const_iterator BI = CD->bases_begin();
760       for (unsigned I = 0; I != N; ++I, ++BI) {
761         assert(BI != CD->bases_end());
762         if (!First)
763           Out << ", ";
764         getStructBase(I).printPretty(Out, Ctx, BI->getType());
765         First = false;
766       }
767     }
768     for (const auto *FI : RD->fields()) {
769       if (!First)
770         Out << ", ";
771       if (FI->isUnnamedBitfield()) continue;
772       getStructField(FI->getFieldIndex()).
773         printPretty(Out, Ctx, FI->getType());
774       First = false;
775     }
776     Out << '}';
777     return;
778   }
779   case APValue::Union:
780     Out << '{';
781     if (const FieldDecl *FD = getUnionField()) {
782       Out << "." << *FD << " = ";
783       getUnionValue().printPretty(Out, Ctx, FD->getType());
784     }
785     Out << '}';
786     return;
787   case APValue::MemberPointer:
788     // FIXME: This is not enough to unambiguously identify the member in a
789     // multiple-inheritance scenario.
790     if (const ValueDecl *VD = getMemberPointerDecl()) {
791       Out << '&' << *cast<CXXRecordDecl>(VD->getDeclContext()) << "::" << *VD;
792       return;
793     }
794     Out << "0";
795     return;
796   case APValue::AddrLabelDiff:
797     Out << "&&" << getAddrLabelDiffLHS()->getLabel()->getName();
798     Out << " - ";
799     Out << "&&" << getAddrLabelDiffRHS()->getLabel()->getName();
800     return;
801   }
802   llvm_unreachable("Unknown APValue kind!");
803 }
804 
805 std::string APValue::getAsString(const ASTContext &Ctx, QualType Ty) const {
806   std::string Result;
807   llvm::raw_string_ostream Out(Result);
808   printPretty(Out, Ctx, Ty);
809   Out.flush();
810   return Result;
811 }
812 
813 bool APValue::toIntegralConstant(APSInt &Result, QualType SrcTy,
814                                  const ASTContext &Ctx) const {
815   if (isInt()) {
816     Result = getInt();
817     return true;
818   }
819 
820   if (isLValue() && isNullPointer()) {
821     Result = Ctx.MakeIntValue(Ctx.getTargetNullPointerValue(SrcTy), SrcTy);
822     return true;
823   }
824 
825   if (isLValue() && !getLValueBase()) {
826     Result = Ctx.MakeIntValue(getLValueOffset().getQuantity(), SrcTy);
827     return true;
828   }
829 
830   return false;
831 }
832 
833 const APValue::LValueBase APValue::getLValueBase() const {
834   assert(isLValue() && "Invalid accessor");
835   return ((const LV*)(const void*)Data.buffer)->Base;
836 }
837 
838 bool APValue::isLValueOnePastTheEnd() const {
839   assert(isLValue() && "Invalid accessor");
840   return ((const LV*)(const void*)Data.buffer)->IsOnePastTheEnd;
841 }
842 
843 CharUnits &APValue::getLValueOffset() {
844   assert(isLValue() && "Invalid accessor");
845   return ((LV*)(void*)Data.buffer)->Offset;
846 }
847 
848 bool APValue::hasLValuePath() const {
849   assert(isLValue() && "Invalid accessor");
850   return ((const LV*)(const char*)Data.buffer)->hasPath();
851 }
852 
853 ArrayRef<APValue::LValuePathEntry> APValue::getLValuePath() const {
854   assert(isLValue() && hasLValuePath() && "Invalid accessor");
855   const LV &LVal = *((const LV*)(const char*)Data.buffer);
856   return llvm::makeArrayRef(LVal.getPath(), LVal.PathLength);
857 }
858 
859 unsigned APValue::getLValueCallIndex() const {
860   assert(isLValue() && "Invalid accessor");
861   return ((const LV*)(const char*)Data.buffer)->Base.getCallIndex();
862 }
863 
864 unsigned APValue::getLValueVersion() const {
865   assert(isLValue() && "Invalid accessor");
866   return ((const LV*)(const char*)Data.buffer)->Base.getVersion();
867 }
868 
869 bool APValue::isNullPointer() const {
870   assert(isLValue() && "Invalid usage");
871   return ((const LV*)(const char*)Data.buffer)->IsNullPtr;
872 }
873 
874 void APValue::setLValue(LValueBase B, const CharUnits &O, NoLValuePath,
875                         bool IsNullPtr) {
876   assert(isLValue() && "Invalid accessor");
877   LV &LVal = *((LV*)(char*)Data.buffer);
878   LVal.Base = B;
879   LVal.IsOnePastTheEnd = false;
880   LVal.Offset = O;
881   LVal.resizePath((unsigned)-1);
882   LVal.IsNullPtr = IsNullPtr;
883 }
884 
885 void APValue::setLValue(LValueBase B, const CharUnits &O,
886                         ArrayRef<LValuePathEntry> Path, bool IsOnePastTheEnd,
887                         bool IsNullPtr) {
888   assert(isLValue() && "Invalid accessor");
889   LV &LVal = *((LV*)(char*)Data.buffer);
890   LVal.Base = B;
891   LVal.IsOnePastTheEnd = IsOnePastTheEnd;
892   LVal.Offset = O;
893   LVal.resizePath(Path.size());
894   memcpy(LVal.getPath(), Path.data(), Path.size() * sizeof(LValuePathEntry));
895   LVal.IsNullPtr = IsNullPtr;
896 }
897 
898 const ValueDecl *APValue::getMemberPointerDecl() const {
899   assert(isMemberPointer() && "Invalid accessor");
900   const MemberPointerData &MPD =
901       *((const MemberPointerData *)(const char *)Data.buffer);
902   return MPD.MemberAndIsDerivedMember.getPointer();
903 }
904 
905 bool APValue::isMemberPointerToDerivedMember() const {
906   assert(isMemberPointer() && "Invalid accessor");
907   const MemberPointerData &MPD =
908       *((const MemberPointerData *)(const char *)Data.buffer);
909   return MPD.MemberAndIsDerivedMember.getInt();
910 }
911 
912 ArrayRef<const CXXRecordDecl*> APValue::getMemberPointerPath() const {
913   assert(isMemberPointer() && "Invalid accessor");
914   const MemberPointerData &MPD =
915       *((const MemberPointerData *)(const char *)Data.buffer);
916   return llvm::makeArrayRef(MPD.getPath(), MPD.PathLength);
917 }
918 
919 void APValue::MakeLValue() {
920   assert(isAbsent() && "Bad state change");
921   static_assert(sizeof(LV) <= DataSize, "LV too big");
922   new ((void*)(char*)Data.buffer) LV();
923   Kind = LValue;
924 }
925 
926 void APValue::MakeArray(unsigned InitElts, unsigned Size) {
927   assert(isAbsent() && "Bad state change");
928   new ((void*)(char*)Data.buffer) Arr(InitElts, Size);
929   Kind = Array;
930 }
931 
932 void APValue::MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember,
933                                 ArrayRef<const CXXRecordDecl*> Path) {
934   assert(isAbsent() && "Bad state change");
935   MemberPointerData *MPD = new ((void*)(char*)Data.buffer) MemberPointerData;
936   Kind = MemberPointer;
937   MPD->MemberAndIsDerivedMember.setPointer(
938       Member ? cast<ValueDecl>(Member->getCanonicalDecl()) : nullptr);
939   MPD->MemberAndIsDerivedMember.setInt(IsDerivedMember);
940   MPD->resizePath(Path.size());
941   for (unsigned I = 0; I != Path.size(); ++I)
942     MPD->getPath()[I] = Path[I]->getCanonicalDecl();
943 }
944