xref: /freebsd/contrib/llvm-project/clang/lib/AST/VTableBuilder.cpp (revision af23369a6deaaeb612ab266eb88b8bb8d560c322)
1 //===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
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 contains code dealing with generation of the layout of virtual tables.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/VTableBuilder.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTDiagnostic.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "llvm/ADT/SetOperations.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <algorithm>
25 #include <cstdio>
26 
27 using namespace clang;
28 
29 #define DUMP_OVERRIDERS 0
30 
31 namespace {
32 
33 /// BaseOffset - Represents an offset from a derived class to a direct or
34 /// indirect base class.
35 struct BaseOffset {
36   /// DerivedClass - The derived class.
37   const CXXRecordDecl *DerivedClass;
38 
39   /// VirtualBase - If the path from the derived class to the base class
40   /// involves virtual base classes, this holds the declaration of the last
41   /// virtual base in this path (i.e. closest to the base class).
42   const CXXRecordDecl *VirtualBase;
43 
44   /// NonVirtualOffset - The offset from the derived class to the base class.
45   /// (Or the offset from the virtual base class to the base class, if the
46   /// path from the derived class to the base class involves a virtual base
47   /// class.
48   CharUnits NonVirtualOffset;
49 
50   BaseOffset() : DerivedClass(nullptr), VirtualBase(nullptr),
51                  NonVirtualOffset(CharUnits::Zero()) { }
52   BaseOffset(const CXXRecordDecl *DerivedClass,
53              const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
54     : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
55     NonVirtualOffset(NonVirtualOffset) { }
56 
57   bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
58 };
59 
60 /// FinalOverriders - Contains the final overrider member functions for all
61 /// member functions in the base subobjects of a class.
62 class FinalOverriders {
63 public:
64   /// OverriderInfo - Information about a final overrider.
65   struct OverriderInfo {
66     /// Method - The method decl of the overrider.
67     const CXXMethodDecl *Method;
68 
69     /// VirtualBase - The virtual base class subobject of this overrider.
70     /// Note that this records the closest derived virtual base class subobject.
71     const CXXRecordDecl *VirtualBase;
72 
73     /// Offset - the base offset of the overrider's parent in the layout class.
74     CharUnits Offset;
75 
76     OverriderInfo() : Method(nullptr), VirtualBase(nullptr),
77                       Offset(CharUnits::Zero()) { }
78   };
79 
80 private:
81   /// MostDerivedClass - The most derived class for which the final overriders
82   /// are stored.
83   const CXXRecordDecl *MostDerivedClass;
84 
85   /// MostDerivedClassOffset - If we're building final overriders for a
86   /// construction vtable, this holds the offset from the layout class to the
87   /// most derived class.
88   const CharUnits MostDerivedClassOffset;
89 
90   /// LayoutClass - The class we're using for layout information. Will be
91   /// different than the most derived class if the final overriders are for a
92   /// construction vtable.
93   const CXXRecordDecl *LayoutClass;
94 
95   ASTContext &Context;
96 
97   /// MostDerivedClassLayout - the AST record layout of the most derived class.
98   const ASTRecordLayout &MostDerivedClassLayout;
99 
100   /// MethodBaseOffsetPairTy - Uniquely identifies a member function
101   /// in a base subobject.
102   typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
103 
104   typedef llvm::DenseMap<MethodBaseOffsetPairTy,
105                          OverriderInfo> OverridersMapTy;
106 
107   /// OverridersMap - The final overriders for all virtual member functions of
108   /// all the base subobjects of the most derived class.
109   OverridersMapTy OverridersMap;
110 
111   /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
112   /// as a record decl and a subobject number) and its offsets in the most
113   /// derived class as well as the layout class.
114   typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
115                          CharUnits> SubobjectOffsetMapTy;
116 
117   typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
118 
119   /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
120   /// given base.
121   void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
122                           CharUnits OffsetInLayoutClass,
123                           SubobjectOffsetMapTy &SubobjectOffsets,
124                           SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
125                           SubobjectCountMapTy &SubobjectCounts);
126 
127   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
128 
129   /// dump - dump the final overriders for a base subobject, and all its direct
130   /// and indirect base subobjects.
131   void dump(raw_ostream &Out, BaseSubobject Base,
132             VisitedVirtualBasesSetTy& VisitedVirtualBases);
133 
134 public:
135   FinalOverriders(const CXXRecordDecl *MostDerivedClass,
136                   CharUnits MostDerivedClassOffset,
137                   const CXXRecordDecl *LayoutClass);
138 
139   /// getOverrider - Get the final overrider for the given method declaration in
140   /// the subobject with the given base offset.
141   OverriderInfo getOverrider(const CXXMethodDecl *MD,
142                              CharUnits BaseOffset) const {
143     assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
144            "Did not find overrider!");
145 
146     return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
147   }
148 
149   /// dump - dump the final overriders.
150   void dump() {
151     VisitedVirtualBasesSetTy VisitedVirtualBases;
152     dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
153          VisitedVirtualBases);
154   }
155 
156 };
157 
158 FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
159                                  CharUnits MostDerivedClassOffset,
160                                  const CXXRecordDecl *LayoutClass)
161   : MostDerivedClass(MostDerivedClass),
162   MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
163   Context(MostDerivedClass->getASTContext()),
164   MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
165 
166   // Compute base offsets.
167   SubobjectOffsetMapTy SubobjectOffsets;
168   SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
169   SubobjectCountMapTy SubobjectCounts;
170   ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
171                      /*IsVirtual=*/false,
172                      MostDerivedClassOffset,
173                      SubobjectOffsets, SubobjectLayoutClassOffsets,
174                      SubobjectCounts);
175 
176   // Get the final overriders.
177   CXXFinalOverriderMap FinalOverriders;
178   MostDerivedClass->getFinalOverriders(FinalOverriders);
179 
180   for (const auto &Overrider : FinalOverriders) {
181     const CXXMethodDecl *MD = Overrider.first;
182     const OverridingMethods &Methods = Overrider.second;
183 
184     for (const auto &M : Methods) {
185       unsigned SubobjectNumber = M.first;
186       assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
187                                                    SubobjectNumber)) &&
188              "Did not find subobject offset!");
189 
190       CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
191                                                             SubobjectNumber)];
192 
193       assert(M.second.size() == 1 && "Final overrider is not unique!");
194       const UniqueVirtualMethod &Method = M.second.front();
195 
196       const CXXRecordDecl *OverriderRD = Method.Method->getParent();
197       assert(SubobjectLayoutClassOffsets.count(
198              std::make_pair(OverriderRD, Method.Subobject))
199              && "Did not find subobject offset!");
200       CharUnits OverriderOffset =
201         SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
202                                                    Method.Subobject)];
203 
204       OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
205       assert(!Overrider.Method && "Overrider should not exist yet!");
206 
207       Overrider.Offset = OverriderOffset;
208       Overrider.Method = Method.Method;
209       Overrider.VirtualBase = Method.InVirtualSubobject;
210     }
211   }
212 
213 #if DUMP_OVERRIDERS
214   // And dump them (for now).
215   dump();
216 #endif
217 }
218 
219 static BaseOffset ComputeBaseOffset(const ASTContext &Context,
220                                     const CXXRecordDecl *DerivedRD,
221                                     const CXXBasePath &Path) {
222   CharUnits NonVirtualOffset = CharUnits::Zero();
223 
224   unsigned NonVirtualStart = 0;
225   const CXXRecordDecl *VirtualBase = nullptr;
226 
227   // First, look for the virtual base class.
228   for (int I = Path.size(), E = 0; I != E; --I) {
229     const CXXBasePathElement &Element = Path[I - 1];
230 
231     if (Element.Base->isVirtual()) {
232       NonVirtualStart = I;
233       QualType VBaseType = Element.Base->getType();
234       VirtualBase = VBaseType->getAsCXXRecordDecl();
235       break;
236     }
237   }
238 
239   // Now compute the non-virtual offset.
240   for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
241     const CXXBasePathElement &Element = Path[I];
242 
243     // Check the base class offset.
244     const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
245 
246     const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
247 
248     NonVirtualOffset += Layout.getBaseClassOffset(Base);
249   }
250 
251   // FIXME: This should probably use CharUnits or something. Maybe we should
252   // even change the base offsets in ASTRecordLayout to be specified in
253   // CharUnits.
254   return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
255 
256 }
257 
258 static BaseOffset ComputeBaseOffset(const ASTContext &Context,
259                                     const CXXRecordDecl *BaseRD,
260                                     const CXXRecordDecl *DerivedRD) {
261   CXXBasePaths Paths(/*FindAmbiguities=*/false,
262                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
263 
264   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
265     llvm_unreachable("Class must be derived from the passed in base class!");
266 
267   return ComputeBaseOffset(Context, DerivedRD, Paths.front());
268 }
269 
270 static BaseOffset
271 ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
272                                   const CXXMethodDecl *DerivedMD,
273                                   const CXXMethodDecl *BaseMD) {
274   const auto *BaseFT = BaseMD->getType()->castAs<FunctionType>();
275   const auto *DerivedFT = DerivedMD->getType()->castAs<FunctionType>();
276 
277   // Canonicalize the return types.
278   CanQualType CanDerivedReturnType =
279       Context.getCanonicalType(DerivedFT->getReturnType());
280   CanQualType CanBaseReturnType =
281       Context.getCanonicalType(BaseFT->getReturnType());
282 
283   assert(CanDerivedReturnType->getTypeClass() ==
284          CanBaseReturnType->getTypeClass() &&
285          "Types must have same type class!");
286 
287   if (CanDerivedReturnType == CanBaseReturnType) {
288     // No adjustment needed.
289     return BaseOffset();
290   }
291 
292   if (isa<ReferenceType>(CanDerivedReturnType)) {
293     CanDerivedReturnType =
294       CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
295     CanBaseReturnType =
296       CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
297   } else if (isa<PointerType>(CanDerivedReturnType)) {
298     CanDerivedReturnType =
299       CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
300     CanBaseReturnType =
301       CanBaseReturnType->getAs<PointerType>()->getPointeeType();
302   } else {
303     llvm_unreachable("Unexpected return type!");
304   }
305 
306   // We need to compare unqualified types here; consider
307   //   const T *Base::foo();
308   //   T *Derived::foo();
309   if (CanDerivedReturnType.getUnqualifiedType() ==
310       CanBaseReturnType.getUnqualifiedType()) {
311     // No adjustment needed.
312     return BaseOffset();
313   }
314 
315   const CXXRecordDecl *DerivedRD =
316     cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
317 
318   const CXXRecordDecl *BaseRD =
319     cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
320 
321   return ComputeBaseOffset(Context, BaseRD, DerivedRD);
322 }
323 
324 void
325 FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
326                               CharUnits OffsetInLayoutClass,
327                               SubobjectOffsetMapTy &SubobjectOffsets,
328                               SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
329                               SubobjectCountMapTy &SubobjectCounts) {
330   const CXXRecordDecl *RD = Base.getBase();
331 
332   unsigned SubobjectNumber = 0;
333   if (!IsVirtual)
334     SubobjectNumber = ++SubobjectCounts[RD];
335 
336   // Set up the subobject to offset mapping.
337   assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
338          && "Subobject offset already exists!");
339   assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
340          && "Subobject offset already exists!");
341 
342   SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
343   SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
344     OffsetInLayoutClass;
345 
346   // Traverse our bases.
347   for (const auto &B : RD->bases()) {
348     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
349 
350     CharUnits BaseOffset;
351     CharUnits BaseOffsetInLayoutClass;
352     if (B.isVirtual()) {
353       // Check if we've visited this virtual base before.
354       if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
355         continue;
356 
357       const ASTRecordLayout &LayoutClassLayout =
358         Context.getASTRecordLayout(LayoutClass);
359 
360       BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
361       BaseOffsetInLayoutClass =
362         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
363     } else {
364       const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
365       CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
366 
367       BaseOffset = Base.getBaseOffset() + Offset;
368       BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
369     }
370 
371     ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
372                        B.isVirtual(), BaseOffsetInLayoutClass,
373                        SubobjectOffsets, SubobjectLayoutClassOffsets,
374                        SubobjectCounts);
375   }
376 }
377 
378 void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
379                            VisitedVirtualBasesSetTy &VisitedVirtualBases) {
380   const CXXRecordDecl *RD = Base.getBase();
381   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
382 
383   for (const auto &B : RD->bases()) {
384     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
385 
386     // Ignore bases that don't have any virtual member functions.
387     if (!BaseDecl->isPolymorphic())
388       continue;
389 
390     CharUnits BaseOffset;
391     if (B.isVirtual()) {
392       if (!VisitedVirtualBases.insert(BaseDecl).second) {
393         // We've visited this base before.
394         continue;
395       }
396 
397       BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
398     } else {
399       BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
400     }
401 
402     dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
403   }
404 
405   Out << "Final overriders for (";
406   RD->printQualifiedName(Out);
407   Out << ", ";
408   Out << Base.getBaseOffset().getQuantity() << ")\n";
409 
410   // Now dump the overriders for this base subobject.
411   for (const auto *MD : RD->methods()) {
412     if (!VTableContextBase::hasVtableSlot(MD))
413       continue;
414     MD = MD->getCanonicalDecl();
415 
416     OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
417 
418     Out << "  ";
419     MD->printQualifiedName(Out);
420     Out << " - (";
421     Overrider.Method->printQualifiedName(Out);
422     Out << ", " << Overrider.Offset.getQuantity() << ')';
423 
424     BaseOffset Offset;
425     if (!Overrider.Method->isPure())
426       Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
427 
428     if (!Offset.isEmpty()) {
429       Out << " [ret-adj: ";
430       if (Offset.VirtualBase) {
431         Offset.VirtualBase->printQualifiedName(Out);
432         Out << " vbase, ";
433       }
434 
435       Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
436     }
437 
438     Out << "\n";
439   }
440 }
441 
442 /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
443 struct VCallOffsetMap {
444 
445   typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
446 
447   /// Offsets - Keeps track of methods and their offsets.
448   // FIXME: This should be a real map and not a vector.
449   SmallVector<MethodAndOffsetPairTy, 16> Offsets;
450 
451   /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
452   /// can share the same vcall offset.
453   static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
454                                          const CXXMethodDecl *RHS);
455 
456 public:
457   /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
458   /// add was successful, or false if there was already a member function with
459   /// the same signature in the map.
460   bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
461 
462   /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
463   /// vtable address point) for the given virtual member function.
464   CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
465 
466   // empty - Return whether the offset map is empty or not.
467   bool empty() const { return Offsets.empty(); }
468 };
469 
470 static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
471                                     const CXXMethodDecl *RHS) {
472   const FunctionProtoType *LT =
473     cast<FunctionProtoType>(LHS->getType().getCanonicalType());
474   const FunctionProtoType *RT =
475     cast<FunctionProtoType>(RHS->getType().getCanonicalType());
476 
477   // Fast-path matches in the canonical types.
478   if (LT == RT) return true;
479 
480   // Force the signatures to match.  We can't rely on the overrides
481   // list here because there isn't necessarily an inheritance
482   // relationship between the two methods.
483   if (LT->getMethodQuals() != RT->getMethodQuals())
484     return false;
485   return LT->getParamTypes() == RT->getParamTypes();
486 }
487 
488 bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
489                                                 const CXXMethodDecl *RHS) {
490   assert(VTableContextBase::hasVtableSlot(LHS) && "LHS must be virtual!");
491   assert(VTableContextBase::hasVtableSlot(RHS) && "RHS must be virtual!");
492 
493   // A destructor can share a vcall offset with another destructor.
494   if (isa<CXXDestructorDecl>(LHS))
495     return isa<CXXDestructorDecl>(RHS);
496 
497   // FIXME: We need to check more things here.
498 
499   // The methods must have the same name.
500   DeclarationName LHSName = LHS->getDeclName();
501   DeclarationName RHSName = RHS->getDeclName();
502   if (LHSName != RHSName)
503     return false;
504 
505   // And the same signatures.
506   return HasSameVirtualSignature(LHS, RHS);
507 }
508 
509 bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
510                                     CharUnits OffsetOffset) {
511   // Check if we can reuse an offset.
512   for (const auto &OffsetPair : Offsets) {
513     if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
514       return false;
515   }
516 
517   // Add the offset.
518   Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
519   return true;
520 }
521 
522 CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
523   // Look for an offset.
524   for (const auto &OffsetPair : Offsets) {
525     if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
526       return OffsetPair.second;
527   }
528 
529   llvm_unreachable("Should always find a vcall offset offset!");
530 }
531 
532 /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
533 class VCallAndVBaseOffsetBuilder {
534 public:
535   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
536     VBaseOffsetOffsetsMapTy;
537 
538 private:
539   const ItaniumVTableContext &VTables;
540 
541   /// MostDerivedClass - The most derived class for which we're building vcall
542   /// and vbase offsets.
543   const CXXRecordDecl *MostDerivedClass;
544 
545   /// LayoutClass - The class we're using for layout information. Will be
546   /// different than the most derived class if we're building a construction
547   /// vtable.
548   const CXXRecordDecl *LayoutClass;
549 
550   /// Context - The ASTContext which we will use for layout information.
551   ASTContext &Context;
552 
553   /// Components - vcall and vbase offset components
554   typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
555   VTableComponentVectorTy Components;
556 
557   /// VisitedVirtualBases - Visited virtual bases.
558   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
559 
560   /// VCallOffsets - Keeps track of vcall offsets.
561   VCallOffsetMap VCallOffsets;
562 
563 
564   /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
565   /// relative to the address point.
566   VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
567 
568   /// FinalOverriders - The final overriders of the most derived class.
569   /// (Can be null when we're not building a vtable of the most derived class).
570   const FinalOverriders *Overriders;
571 
572   /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
573   /// given base subobject.
574   void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
575                                CharUnits RealBaseOffset);
576 
577   /// AddVCallOffsets - Add vcall offsets for the given base subobject.
578   void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
579 
580   /// AddVBaseOffsets - Add vbase offsets for the given class.
581   void AddVBaseOffsets(const CXXRecordDecl *Base,
582                        CharUnits OffsetInLayoutClass);
583 
584   /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
585   /// chars, relative to the vtable address point.
586   CharUnits getCurrentOffsetOffset() const;
587 
588 public:
589   VCallAndVBaseOffsetBuilder(const ItaniumVTableContext &VTables,
590                              const CXXRecordDecl *MostDerivedClass,
591                              const CXXRecordDecl *LayoutClass,
592                              const FinalOverriders *Overriders,
593                              BaseSubobject Base, bool BaseIsVirtual,
594                              CharUnits OffsetInLayoutClass)
595       : VTables(VTables), MostDerivedClass(MostDerivedClass),
596         LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
597         Overriders(Overriders) {
598 
599     // Add vcall and vbase offsets.
600     AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
601   }
602 
603   /// Methods for iterating over the components.
604   typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
605   const_iterator components_begin() const { return Components.rbegin(); }
606   const_iterator components_end() const { return Components.rend(); }
607 
608   const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
609   const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
610     return VBaseOffsetOffsets;
611   }
612 };
613 
614 void
615 VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
616                                                     bool BaseIsVirtual,
617                                                     CharUnits RealBaseOffset) {
618   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
619 
620   // Itanium C++ ABI 2.5.2:
621   //   ..in classes sharing a virtual table with a primary base class, the vcall
622   //   and vbase offsets added by the derived class all come before the vcall
623   //   and vbase offsets required by the base class, so that the latter may be
624   //   laid out as required by the base class without regard to additions from
625   //   the derived class(es).
626 
627   // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
628   // emit them for the primary base first).
629   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
630     bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
631 
632     CharUnits PrimaryBaseOffset;
633 
634     // Get the base offset of the primary base.
635     if (PrimaryBaseIsVirtual) {
636       assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
637              "Primary vbase should have a zero offset!");
638 
639       const ASTRecordLayout &MostDerivedClassLayout =
640         Context.getASTRecordLayout(MostDerivedClass);
641 
642       PrimaryBaseOffset =
643         MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
644     } else {
645       assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
646              "Primary base should have a zero offset!");
647 
648       PrimaryBaseOffset = Base.getBaseOffset();
649     }
650 
651     AddVCallAndVBaseOffsets(
652       BaseSubobject(PrimaryBase,PrimaryBaseOffset),
653       PrimaryBaseIsVirtual, RealBaseOffset);
654   }
655 
656   AddVBaseOffsets(Base.getBase(), RealBaseOffset);
657 
658   // We only want to add vcall offsets for virtual bases.
659   if (BaseIsVirtual)
660     AddVCallOffsets(Base, RealBaseOffset);
661 }
662 
663 CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
664   // OffsetIndex is the index of this vcall or vbase offset, relative to the
665   // vtable address point. (We subtract 3 to account for the information just
666   // above the address point, the RTTI info, the offset to top, and the
667   // vcall offset itself).
668   int64_t OffsetIndex = -(int64_t)(3 + Components.size());
669 
670   // Under the relative ABI, the offset widths are 32-bit ints instead of
671   // pointer widths.
672   CharUnits OffsetWidth = Context.toCharUnitsFromBits(
673       VTables.isRelativeLayout() ? 32
674                                  : Context.getTargetInfo().getPointerWidth(0));
675   CharUnits OffsetOffset = OffsetWidth * OffsetIndex;
676 
677   return OffsetOffset;
678 }
679 
680 void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
681                                                  CharUnits VBaseOffset) {
682   const CXXRecordDecl *RD = Base.getBase();
683   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
684 
685   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
686 
687   // Handle the primary base first.
688   // We only want to add vcall offsets if the base is non-virtual; a virtual
689   // primary base will have its vcall and vbase offsets emitted already.
690   if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
691     // Get the base offset of the primary base.
692     assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
693            "Primary base should have a zero offset!");
694 
695     AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
696                     VBaseOffset);
697   }
698 
699   // Add the vcall offsets.
700   for (const auto *MD : RD->methods()) {
701     if (!VTableContextBase::hasVtableSlot(MD))
702       continue;
703     MD = MD->getCanonicalDecl();
704 
705     CharUnits OffsetOffset = getCurrentOffsetOffset();
706 
707     // Don't add a vcall offset if we already have one for this member function
708     // signature.
709     if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
710       continue;
711 
712     CharUnits Offset = CharUnits::Zero();
713 
714     if (Overriders) {
715       // Get the final overrider.
716       FinalOverriders::OverriderInfo Overrider =
717         Overriders->getOverrider(MD, Base.getBaseOffset());
718 
719       /// The vcall offset is the offset from the virtual base to the object
720       /// where the function was overridden.
721       Offset = Overrider.Offset - VBaseOffset;
722     }
723 
724     Components.push_back(
725       VTableComponent::MakeVCallOffset(Offset));
726   }
727 
728   // And iterate over all non-virtual bases (ignoring the primary base).
729   for (const auto &B : RD->bases()) {
730     if (B.isVirtual())
731       continue;
732 
733     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
734     if (BaseDecl == PrimaryBase)
735       continue;
736 
737     // Get the base offset of this base.
738     CharUnits BaseOffset = Base.getBaseOffset() +
739       Layout.getBaseClassOffset(BaseDecl);
740 
741     AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
742                     VBaseOffset);
743   }
744 }
745 
746 void
747 VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
748                                             CharUnits OffsetInLayoutClass) {
749   const ASTRecordLayout &LayoutClassLayout =
750     Context.getASTRecordLayout(LayoutClass);
751 
752   // Add vbase offsets.
753   for (const auto &B : RD->bases()) {
754     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
755 
756     // Check if this is a virtual base that we haven't visited before.
757     if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) {
758       CharUnits Offset =
759         LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
760 
761       // Add the vbase offset offset.
762       assert(!VBaseOffsetOffsets.count(BaseDecl) &&
763              "vbase offset offset already exists!");
764 
765       CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
766       VBaseOffsetOffsets.insert(
767           std::make_pair(BaseDecl, VBaseOffsetOffset));
768 
769       Components.push_back(
770           VTableComponent::MakeVBaseOffset(Offset));
771     }
772 
773     // Check the base class looking for more vbase offsets.
774     AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
775   }
776 }
777 
778 /// ItaniumVTableBuilder - Class for building vtable layout information.
779 class ItaniumVTableBuilder {
780 public:
781   /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
782   /// primary bases.
783   typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
784     PrimaryBasesSetVectorTy;
785 
786   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
787     VBaseOffsetOffsetsMapTy;
788 
789   typedef VTableLayout::AddressPointsMapTy AddressPointsMapTy;
790 
791   typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
792 
793 private:
794   /// VTables - Global vtable information.
795   ItaniumVTableContext &VTables;
796 
797   /// MostDerivedClass - The most derived class for which we're building this
798   /// vtable.
799   const CXXRecordDecl *MostDerivedClass;
800 
801   /// MostDerivedClassOffset - If we're building a construction vtable, this
802   /// holds the offset from the layout class to the most derived class.
803   const CharUnits MostDerivedClassOffset;
804 
805   /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
806   /// base. (This only makes sense when building a construction vtable).
807   bool MostDerivedClassIsVirtual;
808 
809   /// LayoutClass - The class we're using for layout information. Will be
810   /// different than the most derived class if we're building a construction
811   /// vtable.
812   const CXXRecordDecl *LayoutClass;
813 
814   /// Context - The ASTContext which we will use for layout information.
815   ASTContext &Context;
816 
817   /// FinalOverriders - The final overriders of the most derived class.
818   const FinalOverriders Overriders;
819 
820   /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
821   /// bases in this vtable.
822   llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
823 
824   /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
825   /// the most derived class.
826   VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
827 
828   /// Components - The components of the vtable being built.
829   SmallVector<VTableComponent, 64> Components;
830 
831   /// AddressPoints - Address points for the vtable being built.
832   AddressPointsMapTy AddressPoints;
833 
834   /// MethodInfo - Contains information about a method in a vtable.
835   /// (Used for computing 'this' pointer adjustment thunks.
836   struct MethodInfo {
837     /// BaseOffset - The base offset of this method.
838     const CharUnits BaseOffset;
839 
840     /// BaseOffsetInLayoutClass - The base offset in the layout class of this
841     /// method.
842     const CharUnits BaseOffsetInLayoutClass;
843 
844     /// VTableIndex - The index in the vtable that this method has.
845     /// (For destructors, this is the index of the complete destructor).
846     const uint64_t VTableIndex;
847 
848     MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
849                uint64_t VTableIndex)
850       : BaseOffset(BaseOffset),
851       BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
852       VTableIndex(VTableIndex) { }
853 
854     MethodInfo()
855       : BaseOffset(CharUnits::Zero()),
856       BaseOffsetInLayoutClass(CharUnits::Zero()),
857       VTableIndex(0) { }
858 
859     MethodInfo(MethodInfo const&) = default;
860   };
861 
862   typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
863 
864   /// MethodInfoMap - The information for all methods in the vtable we're
865   /// currently building.
866   MethodInfoMapTy MethodInfoMap;
867 
868   /// MethodVTableIndices - Contains the index (relative to the vtable address
869   /// point) where the function pointer for a virtual function is stored.
870   MethodVTableIndicesTy MethodVTableIndices;
871 
872   typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
873 
874   /// VTableThunks - The thunks by vtable index in the vtable currently being
875   /// built.
876   VTableThunksMapTy VTableThunks;
877 
878   typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
879   typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
880 
881   /// Thunks - A map that contains all the thunks needed for all methods in the
882   /// most derived class for which the vtable is currently being built.
883   ThunksMapTy Thunks;
884 
885   /// AddThunk - Add a thunk for the given method.
886   void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
887 
888   /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
889   /// part of the vtable we're currently building.
890   void ComputeThisAdjustments();
891 
892   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
893 
894   /// PrimaryVirtualBases - All known virtual bases who are a primary base of
895   /// some other base.
896   VisitedVirtualBasesSetTy PrimaryVirtualBases;
897 
898   /// ComputeReturnAdjustment - Compute the return adjustment given a return
899   /// adjustment base offset.
900   ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
901 
902   /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
903   /// the 'this' pointer from the base subobject to the derived subobject.
904   BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
905                                              BaseSubobject Derived) const;
906 
907   /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
908   /// given virtual member function, its offset in the layout class and its
909   /// final overrider.
910   ThisAdjustment
911   ComputeThisAdjustment(const CXXMethodDecl *MD,
912                         CharUnits BaseOffsetInLayoutClass,
913                         FinalOverriders::OverriderInfo Overrider);
914 
915   /// AddMethod - Add a single virtual member function to the vtable
916   /// components vector.
917   void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
918 
919   /// IsOverriderUsed - Returns whether the overrider will ever be used in this
920   /// part of the vtable.
921   ///
922   /// Itanium C++ ABI 2.5.2:
923   ///
924   ///   struct A { virtual void f(); };
925   ///   struct B : virtual public A { int i; };
926   ///   struct C : virtual public A { int j; };
927   ///   struct D : public B, public C {};
928   ///
929   ///   When B and C are declared, A is a primary base in each case, so although
930   ///   vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
931   ///   adjustment is required and no thunk is generated. However, inside D
932   ///   objects, A is no longer a primary base of C, so if we allowed calls to
933   ///   C::f() to use the copy of A's vtable in the C subobject, we would need
934   ///   to adjust this from C* to B::A*, which would require a third-party
935   ///   thunk. Since we require that a call to C::f() first convert to A*,
936   ///   C-in-D's copy of A's vtable is never referenced, so this is not
937   ///   necessary.
938   bool IsOverriderUsed(const CXXMethodDecl *Overrider,
939                        CharUnits BaseOffsetInLayoutClass,
940                        const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
941                        CharUnits FirstBaseOffsetInLayoutClass) const;
942 
943 
944   /// AddMethods - Add the methods of this base subobject and all its
945   /// primary bases to the vtable components vector.
946   void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
947                   const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
948                   CharUnits FirstBaseOffsetInLayoutClass,
949                   PrimaryBasesSetVectorTy &PrimaryBases);
950 
951   // LayoutVTable - Layout the vtable for the given base class, including its
952   // secondary vtables and any vtables for virtual bases.
953   void LayoutVTable();
954 
955   /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
956   /// given base subobject, as well as all its secondary vtables.
957   ///
958   /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
959   /// or a direct or indirect base of a virtual base.
960   ///
961   /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
962   /// in the layout class.
963   void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
964                                         bool BaseIsMorallyVirtual,
965                                         bool BaseIsVirtualInLayoutClass,
966                                         CharUnits OffsetInLayoutClass);
967 
968   /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
969   /// subobject.
970   ///
971   /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
972   /// or a direct or indirect base of a virtual base.
973   void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
974                               CharUnits OffsetInLayoutClass);
975 
976   /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
977   /// class hierarchy.
978   void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
979                                     CharUnits OffsetInLayoutClass,
980                                     VisitedVirtualBasesSetTy &VBases);
981 
982   /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
983   /// given base (excluding any primary bases).
984   void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
985                                     VisitedVirtualBasesSetTy &VBases);
986 
987   /// isBuildingConstructionVTable - Return whether this vtable builder is
988   /// building a construction vtable.
989   bool isBuildingConstructorVTable() const {
990     return MostDerivedClass != LayoutClass;
991   }
992 
993 public:
994   /// Component indices of the first component of each of the vtables in the
995   /// vtable group.
996   SmallVector<size_t, 4> VTableIndices;
997 
998   ItaniumVTableBuilder(ItaniumVTableContext &VTables,
999                        const CXXRecordDecl *MostDerivedClass,
1000                        CharUnits MostDerivedClassOffset,
1001                        bool MostDerivedClassIsVirtual,
1002                        const CXXRecordDecl *LayoutClass)
1003       : VTables(VTables), MostDerivedClass(MostDerivedClass),
1004         MostDerivedClassOffset(MostDerivedClassOffset),
1005         MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
1006         LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
1007         Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
1008     assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
1009 
1010     LayoutVTable();
1011 
1012     if (Context.getLangOpts().DumpVTableLayouts)
1013       dumpLayout(llvm::outs());
1014   }
1015 
1016   uint64_t getNumThunks() const {
1017     return Thunks.size();
1018   }
1019 
1020   ThunksMapTy::const_iterator thunks_begin() const {
1021     return Thunks.begin();
1022   }
1023 
1024   ThunksMapTy::const_iterator thunks_end() const {
1025     return Thunks.end();
1026   }
1027 
1028   const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1029     return VBaseOffsetOffsets;
1030   }
1031 
1032   const AddressPointsMapTy &getAddressPoints() const {
1033     return AddressPoints;
1034   }
1035 
1036   MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1037     return MethodVTableIndices.begin();
1038   }
1039 
1040   MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1041     return MethodVTableIndices.end();
1042   }
1043 
1044   ArrayRef<VTableComponent> vtable_components() const { return Components; }
1045 
1046   AddressPointsMapTy::const_iterator address_points_begin() const {
1047     return AddressPoints.begin();
1048   }
1049 
1050   AddressPointsMapTy::const_iterator address_points_end() const {
1051     return AddressPoints.end();
1052   }
1053 
1054   VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1055     return VTableThunks.begin();
1056   }
1057 
1058   VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1059     return VTableThunks.end();
1060   }
1061 
1062   /// dumpLayout - Dump the vtable layout.
1063   void dumpLayout(raw_ostream&);
1064 };
1065 
1066 void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1067                                     const ThunkInfo &Thunk) {
1068   assert(!isBuildingConstructorVTable() &&
1069          "Can't add thunks for construction vtable");
1070 
1071   SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1072 
1073   // Check if we have this thunk already.
1074   if (llvm::is_contained(ThunksVector, Thunk))
1075     return;
1076 
1077   ThunksVector.push_back(Thunk);
1078 }
1079 
1080 typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1081 
1082 /// Visit all the methods overridden by the given method recursively,
1083 /// in a depth-first pre-order. The Visitor's visitor method returns a bool
1084 /// indicating whether to continue the recursion for the given overridden
1085 /// method (i.e. returning false stops the iteration).
1086 template <class VisitorTy>
1087 static void
1088 visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
1089   assert(VTableContextBase::hasVtableSlot(MD) && "Method is not virtual!");
1090 
1091   for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
1092     if (!Visitor(OverriddenMD))
1093       continue;
1094     visitAllOverriddenMethods(OverriddenMD, Visitor);
1095   }
1096 }
1097 
1098 /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1099 /// the overridden methods that the function decl overrides.
1100 static void
1101 ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1102                             OverriddenMethodsSetTy& OverriddenMethods) {
1103   auto OverriddenMethodsCollector = [&](const CXXMethodDecl *MD) {
1104     // Don't recurse on this method if we've already collected it.
1105     return OverriddenMethods.insert(MD).second;
1106   };
1107   visitAllOverriddenMethods(MD, OverriddenMethodsCollector);
1108 }
1109 
1110 void ItaniumVTableBuilder::ComputeThisAdjustments() {
1111   // Now go through the method info map and see if any of the methods need
1112   // 'this' pointer adjustments.
1113   for (const auto &MI : MethodInfoMap) {
1114     const CXXMethodDecl *MD = MI.first;
1115     const MethodInfo &MethodInfo = MI.second;
1116 
1117     // Ignore adjustments for unused function pointers.
1118     uint64_t VTableIndex = MethodInfo.VTableIndex;
1119     if (Components[VTableIndex].getKind() ==
1120         VTableComponent::CK_UnusedFunctionPointer)
1121       continue;
1122 
1123     // Get the final overrider for this method.
1124     FinalOverriders::OverriderInfo Overrider =
1125       Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1126 
1127     // Check if we need an adjustment at all.
1128     if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1129       // When a return thunk is needed by a derived class that overrides a
1130       // virtual base, gcc uses a virtual 'this' adjustment as well.
1131       // While the thunk itself might be needed by vtables in subclasses or
1132       // in construction vtables, there doesn't seem to be a reason for using
1133       // the thunk in this vtable. Still, we do so to match gcc.
1134       if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1135         continue;
1136     }
1137 
1138     ThisAdjustment ThisAdjustment =
1139       ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1140 
1141     if (ThisAdjustment.isEmpty())
1142       continue;
1143 
1144     // Add it.
1145     VTableThunks[VTableIndex].This = ThisAdjustment;
1146 
1147     if (isa<CXXDestructorDecl>(MD)) {
1148       // Add an adjustment for the deleting destructor as well.
1149       VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1150     }
1151   }
1152 
1153   /// Clear the method info map.
1154   MethodInfoMap.clear();
1155 
1156   if (isBuildingConstructorVTable()) {
1157     // We don't need to store thunk information for construction vtables.
1158     return;
1159   }
1160 
1161   for (const auto &TI : VTableThunks) {
1162     const VTableComponent &Component = Components[TI.first];
1163     const ThunkInfo &Thunk = TI.second;
1164     const CXXMethodDecl *MD;
1165 
1166     switch (Component.getKind()) {
1167     default:
1168       llvm_unreachable("Unexpected vtable component kind!");
1169     case VTableComponent::CK_FunctionPointer:
1170       MD = Component.getFunctionDecl();
1171       break;
1172     case VTableComponent::CK_CompleteDtorPointer:
1173       MD = Component.getDestructorDecl();
1174       break;
1175     case VTableComponent::CK_DeletingDtorPointer:
1176       // We've already added the thunk when we saw the complete dtor pointer.
1177       continue;
1178     }
1179 
1180     if (MD->getParent() == MostDerivedClass)
1181       AddThunk(MD, Thunk);
1182   }
1183 }
1184 
1185 ReturnAdjustment
1186 ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1187   ReturnAdjustment Adjustment;
1188 
1189   if (!Offset.isEmpty()) {
1190     if (Offset.VirtualBase) {
1191       // Get the virtual base offset offset.
1192       if (Offset.DerivedClass == MostDerivedClass) {
1193         // We can get the offset offset directly from our map.
1194         Adjustment.Virtual.Itanium.VBaseOffsetOffset =
1195           VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1196       } else {
1197         Adjustment.Virtual.Itanium.VBaseOffsetOffset =
1198           VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1199                                              Offset.VirtualBase).getQuantity();
1200       }
1201     }
1202 
1203     Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1204   }
1205 
1206   return Adjustment;
1207 }
1208 
1209 BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1210     BaseSubobject Base, BaseSubobject Derived) const {
1211   const CXXRecordDecl *BaseRD = Base.getBase();
1212   const CXXRecordDecl *DerivedRD = Derived.getBase();
1213 
1214   CXXBasePaths Paths(/*FindAmbiguities=*/true,
1215                      /*RecordPaths=*/true, /*DetectVirtual=*/true);
1216 
1217   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
1218     llvm_unreachable("Class must be derived from the passed in base class!");
1219 
1220   // We have to go through all the paths, and see which one leads us to the
1221   // right base subobject.
1222   for (const CXXBasePath &Path : Paths) {
1223     BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, Path);
1224 
1225     CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1226 
1227     if (Offset.VirtualBase) {
1228       // If we have a virtual base class, the non-virtual offset is relative
1229       // to the virtual base class offset.
1230       const ASTRecordLayout &LayoutClassLayout =
1231         Context.getASTRecordLayout(LayoutClass);
1232 
1233       /// Get the virtual base offset, relative to the most derived class
1234       /// layout.
1235       OffsetToBaseSubobject +=
1236         LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1237     } else {
1238       // Otherwise, the non-virtual offset is relative to the derived class
1239       // offset.
1240       OffsetToBaseSubobject += Derived.getBaseOffset();
1241     }
1242 
1243     // Check if this path gives us the right base subobject.
1244     if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1245       // Since we're going from the base class _to_ the derived class, we'll
1246       // invert the non-virtual offset here.
1247       Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1248       return Offset;
1249     }
1250   }
1251 
1252   return BaseOffset();
1253 }
1254 
1255 ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1256     const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1257     FinalOverriders::OverriderInfo Overrider) {
1258   // Ignore adjustments for pure virtual member functions.
1259   if (Overrider.Method->isPure())
1260     return ThisAdjustment();
1261 
1262   BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1263                                         BaseOffsetInLayoutClass);
1264 
1265   BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1266                                        Overrider.Offset);
1267 
1268   // Compute the adjustment offset.
1269   BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1270                                                       OverriderBaseSubobject);
1271   if (Offset.isEmpty())
1272     return ThisAdjustment();
1273 
1274   ThisAdjustment Adjustment;
1275 
1276   if (Offset.VirtualBase) {
1277     // Get the vcall offset map for this virtual base.
1278     VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1279 
1280     if (VCallOffsets.empty()) {
1281       // We don't have vcall offsets for this virtual base, go ahead and
1282       // build them.
1283       VCallAndVBaseOffsetBuilder Builder(
1284           VTables, MostDerivedClass, MostDerivedClass,
1285           /*Overriders=*/nullptr,
1286           BaseSubobject(Offset.VirtualBase, CharUnits::Zero()),
1287           /*BaseIsVirtual=*/true,
1288           /*OffsetInLayoutClass=*/
1289           CharUnits::Zero());
1290 
1291       VCallOffsets = Builder.getVCallOffsets();
1292     }
1293 
1294     Adjustment.Virtual.Itanium.VCallOffsetOffset =
1295       VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1296   }
1297 
1298   // Set the non-virtual part of the adjustment.
1299   Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1300 
1301   return Adjustment;
1302 }
1303 
1304 void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1305                                      ReturnAdjustment ReturnAdjustment) {
1306   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1307     assert(ReturnAdjustment.isEmpty() &&
1308            "Destructor can't have return adjustment!");
1309 
1310     // Add both the complete destructor and the deleting destructor.
1311     Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1312     Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1313   } else {
1314     // Add the return adjustment if necessary.
1315     if (!ReturnAdjustment.isEmpty())
1316       VTableThunks[Components.size()].Return = ReturnAdjustment;
1317 
1318     // Add the function.
1319     Components.push_back(VTableComponent::MakeFunction(MD));
1320   }
1321 }
1322 
1323 /// OverridesIndirectMethodInBase - Return whether the given member function
1324 /// overrides any methods in the set of given bases.
1325 /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1326 /// For example, if we have:
1327 ///
1328 /// struct A { virtual void f(); }
1329 /// struct B : A { virtual void f(); }
1330 /// struct C : B { virtual void f(); }
1331 ///
1332 /// OverridesIndirectMethodInBase will return true if given C::f as the method
1333 /// and { A } as the set of bases.
1334 static bool OverridesIndirectMethodInBases(
1335     const CXXMethodDecl *MD,
1336     ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1337   if (Bases.count(MD->getParent()))
1338     return true;
1339 
1340   for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
1341     // Check "indirect overriders".
1342     if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1343       return true;
1344   }
1345 
1346   return false;
1347 }
1348 
1349 bool ItaniumVTableBuilder::IsOverriderUsed(
1350     const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1351     const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1352     CharUnits FirstBaseOffsetInLayoutClass) const {
1353   // If the base and the first base in the primary base chain have the same
1354   // offsets, then this overrider will be used.
1355   if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1356    return true;
1357 
1358   // We know now that Base (or a direct or indirect base of it) is a primary
1359   // base in part of the class hierarchy, but not a primary base in the most
1360   // derived class.
1361 
1362   // If the overrider is the first base in the primary base chain, we know
1363   // that the overrider will be used.
1364   if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1365     return true;
1366 
1367   ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1368 
1369   const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1370   PrimaryBases.insert(RD);
1371 
1372   // Now traverse the base chain, starting with the first base, until we find
1373   // the base that is no longer a primary base.
1374   while (true) {
1375     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1376     const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1377 
1378     if (!PrimaryBase)
1379       break;
1380 
1381     if (Layout.isPrimaryBaseVirtual()) {
1382       assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1383              "Primary base should always be at offset 0!");
1384 
1385       const ASTRecordLayout &LayoutClassLayout =
1386         Context.getASTRecordLayout(LayoutClass);
1387 
1388       // Now check if this is the primary base that is not a primary base in the
1389       // most derived class.
1390       if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1391           FirstBaseOffsetInLayoutClass) {
1392         // We found it, stop walking the chain.
1393         break;
1394       }
1395     } else {
1396       assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1397              "Primary base should always be at offset 0!");
1398     }
1399 
1400     if (!PrimaryBases.insert(PrimaryBase))
1401       llvm_unreachable("Found a duplicate primary base!");
1402 
1403     RD = PrimaryBase;
1404   }
1405 
1406   // If the final overrider is an override of one of the primary bases,
1407   // then we know that it will be used.
1408   return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1409 }
1410 
1411 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1412 
1413 /// FindNearestOverriddenMethod - Given a method, returns the overridden method
1414 /// from the nearest base. Returns null if no method was found.
1415 /// The Bases are expected to be sorted in a base-to-derived order.
1416 static const CXXMethodDecl *
1417 FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1418                             BasesSetVectorTy &Bases) {
1419   OverriddenMethodsSetTy OverriddenMethods;
1420   ComputeAllOverriddenMethods(MD, OverriddenMethods);
1421 
1422   for (const CXXRecordDecl *PrimaryBase : llvm::reverse(Bases)) {
1423     // Now check the overridden methods.
1424     for (const CXXMethodDecl *OverriddenMD : OverriddenMethods) {
1425       // We found our overridden method.
1426       if (OverriddenMD->getParent() == PrimaryBase)
1427         return OverriddenMD;
1428     }
1429   }
1430 
1431   return nullptr;
1432 }
1433 
1434 void ItaniumVTableBuilder::AddMethods(
1435     BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1436     const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1437     CharUnits FirstBaseOffsetInLayoutClass,
1438     PrimaryBasesSetVectorTy &PrimaryBases) {
1439   // Itanium C++ ABI 2.5.2:
1440   //   The order of the virtual function pointers in a virtual table is the
1441   //   order of declaration of the corresponding member functions in the class.
1442   //
1443   //   There is an entry for any virtual function declared in a class,
1444   //   whether it is a new function or overrides a base class function,
1445   //   unless it overrides a function from the primary base, and conversion
1446   //   between their return types does not require an adjustment.
1447 
1448   const CXXRecordDecl *RD = Base.getBase();
1449   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1450 
1451   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1452     CharUnits PrimaryBaseOffset;
1453     CharUnits PrimaryBaseOffsetInLayoutClass;
1454     if (Layout.isPrimaryBaseVirtual()) {
1455       assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1456              "Primary vbase should have a zero offset!");
1457 
1458       const ASTRecordLayout &MostDerivedClassLayout =
1459         Context.getASTRecordLayout(MostDerivedClass);
1460 
1461       PrimaryBaseOffset =
1462         MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1463 
1464       const ASTRecordLayout &LayoutClassLayout =
1465         Context.getASTRecordLayout(LayoutClass);
1466 
1467       PrimaryBaseOffsetInLayoutClass =
1468         LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1469     } else {
1470       assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1471              "Primary base should have a zero offset!");
1472 
1473       PrimaryBaseOffset = Base.getBaseOffset();
1474       PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1475     }
1476 
1477     AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1478                PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1479                FirstBaseOffsetInLayoutClass, PrimaryBases);
1480 
1481     if (!PrimaryBases.insert(PrimaryBase))
1482       llvm_unreachable("Found a duplicate primary base!");
1483   }
1484 
1485   typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1486   NewVirtualFunctionsTy NewVirtualFunctions;
1487 
1488   llvm::SmallVector<const CXXMethodDecl*, 4> NewImplicitVirtualFunctions;
1489 
1490   // Now go through all virtual member functions and add them.
1491   for (const auto *MD : RD->methods()) {
1492     if (!ItaniumVTableContext::hasVtableSlot(MD))
1493       continue;
1494     MD = MD->getCanonicalDecl();
1495 
1496     // Get the final overrider.
1497     FinalOverriders::OverriderInfo Overrider =
1498       Overriders.getOverrider(MD, Base.getBaseOffset());
1499 
1500     // Check if this virtual member function overrides a method in a primary
1501     // base. If this is the case, and the return type doesn't require adjustment
1502     // then we can just use the member function from the primary base.
1503     if (const CXXMethodDecl *OverriddenMD =
1504           FindNearestOverriddenMethod(MD, PrimaryBases)) {
1505       if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1506                                             OverriddenMD).isEmpty()) {
1507         // Replace the method info of the overridden method with our own
1508         // method.
1509         assert(MethodInfoMap.count(OverriddenMD) &&
1510                "Did not find the overridden method!");
1511         MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1512 
1513         MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1514                               OverriddenMethodInfo.VTableIndex);
1515 
1516         assert(!MethodInfoMap.count(MD) &&
1517                "Should not have method info for this method yet!");
1518 
1519         MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1520         MethodInfoMap.erase(OverriddenMD);
1521 
1522         // If the overridden method exists in a virtual base class or a direct
1523         // or indirect base class of a virtual base class, we need to emit a
1524         // thunk if we ever have a class hierarchy where the base class is not
1525         // a primary base in the complete object.
1526         if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1527           // Compute the this adjustment.
1528           ThisAdjustment ThisAdjustment =
1529             ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1530                                   Overrider);
1531 
1532           if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
1533               Overrider.Method->getParent() == MostDerivedClass) {
1534 
1535             // There's no return adjustment from OverriddenMD and MD,
1536             // but that doesn't mean there isn't one between MD and
1537             // the final overrider.
1538             BaseOffset ReturnAdjustmentOffset =
1539               ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1540             ReturnAdjustment ReturnAdjustment =
1541               ComputeReturnAdjustment(ReturnAdjustmentOffset);
1542 
1543             // This is a virtual thunk for the most derived class, add it.
1544             AddThunk(Overrider.Method,
1545                      ThunkInfo(ThisAdjustment, ReturnAdjustment));
1546           }
1547         }
1548 
1549         continue;
1550       }
1551     }
1552 
1553     if (MD->isImplicit())
1554       NewImplicitVirtualFunctions.push_back(MD);
1555     else
1556       NewVirtualFunctions.push_back(MD);
1557   }
1558 
1559   std::stable_sort(
1560       NewImplicitVirtualFunctions.begin(), NewImplicitVirtualFunctions.end(),
1561       [](const CXXMethodDecl *A, const CXXMethodDecl *B) {
1562         if (A->isCopyAssignmentOperator() != B->isCopyAssignmentOperator())
1563           return A->isCopyAssignmentOperator();
1564         if (A->isMoveAssignmentOperator() != B->isMoveAssignmentOperator())
1565           return A->isMoveAssignmentOperator();
1566         if (isa<CXXDestructorDecl>(A) != isa<CXXDestructorDecl>(B))
1567           return isa<CXXDestructorDecl>(A);
1568         assert(A->getOverloadedOperator() == OO_EqualEqual &&
1569                B->getOverloadedOperator() == OO_EqualEqual &&
1570                "unexpected or duplicate implicit virtual function");
1571         // We rely on Sema to have declared the operator== members in the
1572         // same order as the corresponding operator<=> members.
1573         return false;
1574       });
1575   NewVirtualFunctions.append(NewImplicitVirtualFunctions.begin(),
1576                              NewImplicitVirtualFunctions.end());
1577 
1578   for (const CXXMethodDecl *MD : NewVirtualFunctions) {
1579     // Get the final overrider.
1580     FinalOverriders::OverriderInfo Overrider =
1581       Overriders.getOverrider(MD, Base.getBaseOffset());
1582 
1583     // Insert the method info for this method.
1584     MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1585                           Components.size());
1586 
1587     assert(!MethodInfoMap.count(MD) &&
1588            "Should not have method info for this method yet!");
1589     MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1590 
1591     // Check if this overrider is going to be used.
1592     const CXXMethodDecl *OverriderMD = Overrider.Method;
1593     if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1594                          FirstBaseInPrimaryBaseChain,
1595                          FirstBaseOffsetInLayoutClass)) {
1596       Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1597       continue;
1598     }
1599 
1600     // Check if this overrider needs a return adjustment.
1601     // We don't want to do this for pure virtual member functions.
1602     BaseOffset ReturnAdjustmentOffset;
1603     if (!OverriderMD->isPure()) {
1604       ReturnAdjustmentOffset =
1605         ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1606     }
1607 
1608     ReturnAdjustment ReturnAdjustment =
1609       ComputeReturnAdjustment(ReturnAdjustmentOffset);
1610 
1611     AddMethod(Overrider.Method, ReturnAdjustment);
1612   }
1613 }
1614 
1615 void ItaniumVTableBuilder::LayoutVTable() {
1616   LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1617                                                  CharUnits::Zero()),
1618                                    /*BaseIsMorallyVirtual=*/false,
1619                                    MostDerivedClassIsVirtual,
1620                                    MostDerivedClassOffset);
1621 
1622   VisitedVirtualBasesSetTy VBases;
1623 
1624   // Determine the primary virtual bases.
1625   DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1626                                VBases);
1627   VBases.clear();
1628 
1629   LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1630 
1631   // -fapple-kext adds an extra entry at end of vtbl.
1632   bool IsAppleKext = Context.getLangOpts().AppleKext;
1633   if (IsAppleKext)
1634     Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1635 }
1636 
1637 void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1638     BaseSubobject Base, bool BaseIsMorallyVirtual,
1639     bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
1640   assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1641 
1642   unsigned VTableIndex = Components.size();
1643   VTableIndices.push_back(VTableIndex);
1644 
1645   // Add vcall and vbase offsets for this vtable.
1646   VCallAndVBaseOffsetBuilder Builder(
1647       VTables, MostDerivedClass, LayoutClass, &Overriders, Base,
1648       BaseIsVirtualInLayoutClass, OffsetInLayoutClass);
1649   Components.append(Builder.components_begin(), Builder.components_end());
1650 
1651   // Check if we need to add these vcall offsets.
1652   if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1653     VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1654 
1655     if (VCallOffsets.empty())
1656       VCallOffsets = Builder.getVCallOffsets();
1657   }
1658 
1659   // If we're laying out the most derived class we want to keep track of the
1660   // virtual base class offset offsets.
1661   if (Base.getBase() == MostDerivedClass)
1662     VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1663 
1664   // Add the offset to top.
1665   CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1666   Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1667 
1668   // Next, add the RTTI.
1669   Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1670 
1671   uint64_t AddressPoint = Components.size();
1672 
1673   // Now go through all virtual member functions and add them.
1674   PrimaryBasesSetVectorTy PrimaryBases;
1675   AddMethods(Base, OffsetInLayoutClass,
1676              Base.getBase(), OffsetInLayoutClass,
1677              PrimaryBases);
1678 
1679   const CXXRecordDecl *RD = Base.getBase();
1680   if (RD == MostDerivedClass) {
1681     assert(MethodVTableIndices.empty());
1682     for (const auto &I : MethodInfoMap) {
1683       const CXXMethodDecl *MD = I.first;
1684       const MethodInfo &MI = I.second;
1685       if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1686         MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1687             = MI.VTableIndex - AddressPoint;
1688         MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1689             = MI.VTableIndex + 1 - AddressPoint;
1690       } else {
1691         MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1692       }
1693     }
1694   }
1695 
1696   // Compute 'this' pointer adjustments.
1697   ComputeThisAdjustments();
1698 
1699   // Add all address points.
1700   while (true) {
1701     AddressPoints.insert(
1702         std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
1703                        VTableLayout::AddressPointLocation{
1704                            unsigned(VTableIndices.size() - 1),
1705                            unsigned(AddressPoint - VTableIndex)}));
1706 
1707     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1708     const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1709 
1710     if (!PrimaryBase)
1711       break;
1712 
1713     if (Layout.isPrimaryBaseVirtual()) {
1714       // Check if this virtual primary base is a primary base in the layout
1715       // class. If it's not, we don't want to add it.
1716       const ASTRecordLayout &LayoutClassLayout =
1717         Context.getASTRecordLayout(LayoutClass);
1718 
1719       if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1720           OffsetInLayoutClass) {
1721         // We don't want to add this class (or any of its primary bases).
1722         break;
1723       }
1724     }
1725 
1726     RD = PrimaryBase;
1727   }
1728 
1729   // Layout secondary vtables.
1730   LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1731 }
1732 
1733 void
1734 ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1735                                              bool BaseIsMorallyVirtual,
1736                                              CharUnits OffsetInLayoutClass) {
1737   // Itanium C++ ABI 2.5.2:
1738   //   Following the primary virtual table of a derived class are secondary
1739   //   virtual tables for each of its proper base classes, except any primary
1740   //   base(s) with which it shares its primary virtual table.
1741 
1742   const CXXRecordDecl *RD = Base.getBase();
1743   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1744   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1745 
1746   for (const auto &B : RD->bases()) {
1747     // Ignore virtual bases, we'll emit them later.
1748     if (B.isVirtual())
1749       continue;
1750 
1751     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1752 
1753     // Ignore bases that don't have a vtable.
1754     if (!BaseDecl->isDynamicClass())
1755       continue;
1756 
1757     if (isBuildingConstructorVTable()) {
1758       // Itanium C++ ABI 2.6.4:
1759       //   Some of the base class subobjects may not need construction virtual
1760       //   tables, which will therefore not be present in the construction
1761       //   virtual table group, even though the subobject virtual tables are
1762       //   present in the main virtual table group for the complete object.
1763       if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1764         continue;
1765     }
1766 
1767     // Get the base offset of this base.
1768     CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1769     CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1770 
1771     CharUnits BaseOffsetInLayoutClass =
1772       OffsetInLayoutClass + RelativeBaseOffset;
1773 
1774     // Don't emit a secondary vtable for a primary base. We might however want
1775     // to emit secondary vtables for other bases of this base.
1776     if (BaseDecl == PrimaryBase) {
1777       LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1778                              BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1779       continue;
1780     }
1781 
1782     // Layout the primary vtable (and any secondary vtables) for this base.
1783     LayoutPrimaryAndSecondaryVTables(
1784       BaseSubobject(BaseDecl, BaseOffset),
1785       BaseIsMorallyVirtual,
1786       /*BaseIsVirtualInLayoutClass=*/false,
1787       BaseOffsetInLayoutClass);
1788   }
1789 }
1790 
1791 void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1792     const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1793     VisitedVirtualBasesSetTy &VBases) {
1794   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1795 
1796   // Check if this base has a primary base.
1797   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1798 
1799     // Check if it's virtual.
1800     if (Layout.isPrimaryBaseVirtual()) {
1801       bool IsPrimaryVirtualBase = true;
1802 
1803       if (isBuildingConstructorVTable()) {
1804         // Check if the base is actually a primary base in the class we use for
1805         // layout.
1806         const ASTRecordLayout &LayoutClassLayout =
1807           Context.getASTRecordLayout(LayoutClass);
1808 
1809         CharUnits PrimaryBaseOffsetInLayoutClass =
1810           LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1811 
1812         // We know that the base is not a primary base in the layout class if
1813         // the base offsets are different.
1814         if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1815           IsPrimaryVirtualBase = false;
1816       }
1817 
1818       if (IsPrimaryVirtualBase)
1819         PrimaryVirtualBases.insert(PrimaryBase);
1820     }
1821   }
1822 
1823   // Traverse bases, looking for more primary virtual bases.
1824   for (const auto &B : RD->bases()) {
1825     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1826 
1827     CharUnits BaseOffsetInLayoutClass;
1828 
1829     if (B.isVirtual()) {
1830       if (!VBases.insert(BaseDecl).second)
1831         continue;
1832 
1833       const ASTRecordLayout &LayoutClassLayout =
1834         Context.getASTRecordLayout(LayoutClass);
1835 
1836       BaseOffsetInLayoutClass =
1837         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1838     } else {
1839       BaseOffsetInLayoutClass =
1840         OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1841     }
1842 
1843     DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1844   }
1845 }
1846 
1847 void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1848     const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
1849   // Itanium C++ ABI 2.5.2:
1850   //   Then come the virtual base virtual tables, also in inheritance graph
1851   //   order, and again excluding primary bases (which share virtual tables with
1852   //   the classes for which they are primary).
1853   for (const auto &B : RD->bases()) {
1854     const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1855 
1856     // Check if this base needs a vtable. (If it's virtual, not a primary base
1857     // of some other class, and we haven't visited it before).
1858     if (B.isVirtual() && BaseDecl->isDynamicClass() &&
1859         !PrimaryVirtualBases.count(BaseDecl) &&
1860         VBases.insert(BaseDecl).second) {
1861       const ASTRecordLayout &MostDerivedClassLayout =
1862         Context.getASTRecordLayout(MostDerivedClass);
1863       CharUnits BaseOffset =
1864         MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1865 
1866       const ASTRecordLayout &LayoutClassLayout =
1867         Context.getASTRecordLayout(LayoutClass);
1868       CharUnits BaseOffsetInLayoutClass =
1869         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1870 
1871       LayoutPrimaryAndSecondaryVTables(
1872         BaseSubobject(BaseDecl, BaseOffset),
1873         /*BaseIsMorallyVirtual=*/true,
1874         /*BaseIsVirtualInLayoutClass=*/true,
1875         BaseOffsetInLayoutClass);
1876     }
1877 
1878     // We only need to check the base for virtual base vtables if it actually
1879     // has virtual bases.
1880     if (BaseDecl->getNumVBases())
1881       LayoutVTablesForVirtualBases(BaseDecl, VBases);
1882   }
1883 }
1884 
1885 /// dumpLayout - Dump the vtable layout.
1886 void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
1887   // FIXME: write more tests that actually use the dumpLayout output to prevent
1888   // ItaniumVTableBuilder regressions.
1889 
1890   if (isBuildingConstructorVTable()) {
1891     Out << "Construction vtable for ('";
1892     MostDerivedClass->printQualifiedName(Out);
1893     Out << "', ";
1894     Out << MostDerivedClassOffset.getQuantity() << ") in '";
1895     LayoutClass->printQualifiedName(Out);
1896   } else {
1897     Out << "Vtable for '";
1898     MostDerivedClass->printQualifiedName(Out);
1899   }
1900   Out << "' (" << Components.size() << " entries).\n";
1901 
1902   // Iterate through the address points and insert them into a new map where
1903   // they are keyed by the index and not the base object.
1904   // Since an address point can be shared by multiple subobjects, we use an
1905   // STL multimap.
1906   std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1907   for (const auto &AP : AddressPoints) {
1908     const BaseSubobject &Base = AP.first;
1909     uint64_t Index =
1910         VTableIndices[AP.second.VTableIndex] + AP.second.AddressPointIndex;
1911 
1912     AddressPointsByIndex.insert(std::make_pair(Index, Base));
1913   }
1914 
1915   for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1916     uint64_t Index = I;
1917 
1918     Out << llvm::format("%4d | ", I);
1919 
1920     const VTableComponent &Component = Components[I];
1921 
1922     // Dump the component.
1923     switch (Component.getKind()) {
1924 
1925     case VTableComponent::CK_VCallOffset:
1926       Out << "vcall_offset ("
1927           << Component.getVCallOffset().getQuantity()
1928           << ")";
1929       break;
1930 
1931     case VTableComponent::CK_VBaseOffset:
1932       Out << "vbase_offset ("
1933           << Component.getVBaseOffset().getQuantity()
1934           << ")";
1935       break;
1936 
1937     case VTableComponent::CK_OffsetToTop:
1938       Out << "offset_to_top ("
1939           << Component.getOffsetToTop().getQuantity()
1940           << ")";
1941       break;
1942 
1943     case VTableComponent::CK_RTTI:
1944       Component.getRTTIDecl()->printQualifiedName(Out);
1945       Out << " RTTI";
1946       break;
1947 
1948     case VTableComponent::CK_FunctionPointer: {
1949       const CXXMethodDecl *MD = Component.getFunctionDecl();
1950 
1951       std::string Str =
1952         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1953                                     MD);
1954       Out << Str;
1955       if (MD->isPure())
1956         Out << " [pure]";
1957 
1958       if (MD->isDeleted())
1959         Out << " [deleted]";
1960 
1961       ThunkInfo Thunk = VTableThunks.lookup(I);
1962       if (!Thunk.isEmpty()) {
1963         // If this function pointer has a return adjustment, dump it.
1964         if (!Thunk.Return.isEmpty()) {
1965           Out << "\n       [return adjustment: ";
1966           Out << Thunk.Return.NonVirtual << " non-virtual";
1967 
1968           if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1969             Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
1970             Out << " vbase offset offset";
1971           }
1972 
1973           Out << ']';
1974         }
1975 
1976         // If this function pointer has a 'this' pointer adjustment, dump it.
1977         if (!Thunk.This.isEmpty()) {
1978           Out << "\n       [this adjustment: ";
1979           Out << Thunk.This.NonVirtual << " non-virtual";
1980 
1981           if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
1982             Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
1983             Out << " vcall offset offset";
1984           }
1985 
1986           Out << ']';
1987         }
1988       }
1989 
1990       break;
1991     }
1992 
1993     case VTableComponent::CK_CompleteDtorPointer:
1994     case VTableComponent::CK_DeletingDtorPointer: {
1995       bool IsComplete =
1996         Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
1997 
1998       const CXXDestructorDecl *DD = Component.getDestructorDecl();
1999 
2000       DD->printQualifiedName(Out);
2001       if (IsComplete)
2002         Out << "() [complete]";
2003       else
2004         Out << "() [deleting]";
2005 
2006       if (DD->isPure())
2007         Out << " [pure]";
2008 
2009       ThunkInfo Thunk = VTableThunks.lookup(I);
2010       if (!Thunk.isEmpty()) {
2011         // If this destructor has a 'this' pointer adjustment, dump it.
2012         if (!Thunk.This.isEmpty()) {
2013           Out << "\n       [this adjustment: ";
2014           Out << Thunk.This.NonVirtual << " non-virtual";
2015 
2016           if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2017             Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2018             Out << " vcall offset offset";
2019           }
2020 
2021           Out << ']';
2022         }
2023       }
2024 
2025       break;
2026     }
2027 
2028     case VTableComponent::CK_UnusedFunctionPointer: {
2029       const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2030 
2031       std::string Str =
2032         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2033                                     MD);
2034       Out << "[unused] " << Str;
2035       if (MD->isPure())
2036         Out << " [pure]";
2037     }
2038 
2039     }
2040 
2041     Out << '\n';
2042 
2043     // Dump the next address point.
2044     uint64_t NextIndex = Index + 1;
2045     if (AddressPointsByIndex.count(NextIndex)) {
2046       if (AddressPointsByIndex.count(NextIndex) == 1) {
2047         const BaseSubobject &Base =
2048           AddressPointsByIndex.find(NextIndex)->second;
2049 
2050         Out << "       -- (";
2051         Base.getBase()->printQualifiedName(Out);
2052         Out << ", " << Base.getBaseOffset().getQuantity();
2053         Out << ") vtable address --\n";
2054       } else {
2055         CharUnits BaseOffset =
2056           AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2057 
2058         // We store the class names in a set to get a stable order.
2059         std::set<std::string> ClassNames;
2060         for (const auto &I :
2061              llvm::make_range(AddressPointsByIndex.equal_range(NextIndex))) {
2062           assert(I.second.getBaseOffset() == BaseOffset &&
2063                  "Invalid base offset!");
2064           const CXXRecordDecl *RD = I.second.getBase();
2065           ClassNames.insert(RD->getQualifiedNameAsString());
2066         }
2067 
2068         for (const std::string &Name : ClassNames) {
2069           Out << "       -- (" << Name;
2070           Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2071         }
2072       }
2073     }
2074   }
2075 
2076   Out << '\n';
2077 
2078   if (isBuildingConstructorVTable())
2079     return;
2080 
2081   if (MostDerivedClass->getNumVBases()) {
2082     // We store the virtual base class names and their offsets in a map to get
2083     // a stable order.
2084 
2085     std::map<std::string, CharUnits> ClassNamesAndOffsets;
2086     for (const auto &I : VBaseOffsetOffsets) {
2087       std::string ClassName = I.first->getQualifiedNameAsString();
2088       CharUnits OffsetOffset = I.second;
2089       ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
2090     }
2091 
2092     Out << "Virtual base offset offsets for '";
2093     MostDerivedClass->printQualifiedName(Out);
2094     Out << "' (";
2095     Out << ClassNamesAndOffsets.size();
2096     Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2097 
2098     for (const auto &I : ClassNamesAndOffsets)
2099       Out << "   " << I.first << " | " << I.second.getQuantity() << '\n';
2100 
2101     Out << "\n";
2102   }
2103 
2104   if (!Thunks.empty()) {
2105     // We store the method names in a map to get a stable order.
2106     std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2107 
2108     for (const auto &I : Thunks) {
2109       const CXXMethodDecl *MD = I.first;
2110       std::string MethodName =
2111         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2112                                     MD);
2113 
2114       MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2115     }
2116 
2117     for (const auto &I : MethodNamesAndDecls) {
2118       const std::string &MethodName = I.first;
2119       const CXXMethodDecl *MD = I.second;
2120 
2121       ThunkInfoVectorTy ThunksVector = Thunks[MD];
2122       llvm::sort(ThunksVector, [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
2123         assert(LHS.Method == nullptr && RHS.Method == nullptr);
2124         return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
2125       });
2126 
2127       Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2128       Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2129 
2130       for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2131         const ThunkInfo &Thunk = ThunksVector[I];
2132 
2133         Out << llvm::format("%4d | ", I);
2134 
2135         // If this function pointer has a return pointer adjustment, dump it.
2136         if (!Thunk.Return.isEmpty()) {
2137           Out << "return adjustment: " << Thunk.Return.NonVirtual;
2138           Out << " non-virtual";
2139           if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2140             Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
2141             Out << " vbase offset offset";
2142           }
2143 
2144           if (!Thunk.This.isEmpty())
2145             Out << "\n       ";
2146         }
2147 
2148         // If this function pointer has a 'this' pointer adjustment, dump it.
2149         if (!Thunk.This.isEmpty()) {
2150           Out << "this adjustment: ";
2151           Out << Thunk.This.NonVirtual << " non-virtual";
2152 
2153           if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2154             Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2155             Out << " vcall offset offset";
2156           }
2157         }
2158 
2159         Out << '\n';
2160       }
2161 
2162       Out << '\n';
2163     }
2164   }
2165 
2166   // Compute the vtable indices for all the member functions.
2167   // Store them in a map keyed by the index so we'll get a sorted table.
2168   std::map<uint64_t, std::string> IndicesMap;
2169 
2170   for (const auto *MD : MostDerivedClass->methods()) {
2171     // We only want virtual member functions.
2172     if (!ItaniumVTableContext::hasVtableSlot(MD))
2173       continue;
2174     MD = MD->getCanonicalDecl();
2175 
2176     std::string MethodName =
2177       PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2178                                   MD);
2179 
2180     if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2181       GlobalDecl GD(DD, Dtor_Complete);
2182       assert(MethodVTableIndices.count(GD));
2183       uint64_t VTableIndex = MethodVTableIndices[GD];
2184       IndicesMap[VTableIndex] = MethodName + " [complete]";
2185       IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
2186     } else {
2187       assert(MethodVTableIndices.count(MD));
2188       IndicesMap[MethodVTableIndices[MD]] = MethodName;
2189     }
2190   }
2191 
2192   // Print the vtable indices for all the member functions.
2193   if (!IndicesMap.empty()) {
2194     Out << "VTable indices for '";
2195     MostDerivedClass->printQualifiedName(Out);
2196     Out << "' (" << IndicesMap.size() << " entries).\n";
2197 
2198     for (const auto &I : IndicesMap) {
2199       uint64_t VTableIndex = I.first;
2200       const std::string &MethodName = I.second;
2201 
2202       Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
2203           << '\n';
2204     }
2205   }
2206 
2207   Out << '\n';
2208 }
2209 }
2210 
2211 static VTableLayout::AddressPointsIndexMapTy
2212 MakeAddressPointIndices(const VTableLayout::AddressPointsMapTy &addressPoints,
2213                         unsigned numVTables) {
2214   VTableLayout::AddressPointsIndexMapTy indexMap(numVTables);
2215 
2216   for (auto it = addressPoints.begin(); it != addressPoints.end(); ++it) {
2217     const auto &addressPointLoc = it->second;
2218     unsigned vtableIndex = addressPointLoc.VTableIndex;
2219     unsigned addressPoint = addressPointLoc.AddressPointIndex;
2220     if (indexMap[vtableIndex]) {
2221       // Multiple BaseSubobjects can map to the same AddressPointLocation, but
2222       // every vtable index should have a unique address point.
2223       assert(indexMap[vtableIndex] == addressPoint &&
2224              "Every vtable index should have a unique address point. Found a "
2225              "vtable that has two different address points.");
2226     } else {
2227       indexMap[vtableIndex] = addressPoint;
2228     }
2229   }
2230 
2231   // Note that by this point, not all the address may be initialized if the
2232   // AddressPoints map is empty. This is ok if the map isn't needed. See
2233   // MicrosoftVTableContext::computeVTableRelatedInformation() which uses an
2234   // emprt map.
2235   return indexMap;
2236 }
2237 
2238 VTableLayout::VTableLayout(ArrayRef<size_t> VTableIndices,
2239                            ArrayRef<VTableComponent> VTableComponents,
2240                            ArrayRef<VTableThunkTy> VTableThunks,
2241                            const AddressPointsMapTy &AddressPoints)
2242     : VTableComponents(VTableComponents), VTableThunks(VTableThunks),
2243       AddressPoints(AddressPoints), AddressPointIndices(MakeAddressPointIndices(
2244                                         AddressPoints, VTableIndices.size())) {
2245   if (VTableIndices.size() <= 1)
2246     assert(VTableIndices.size() == 1 && VTableIndices[0] == 0);
2247   else
2248     this->VTableIndices = OwningArrayRef<size_t>(VTableIndices);
2249 
2250   llvm::sort(this->VTableThunks, [](const VTableLayout::VTableThunkTy &LHS,
2251                                     const VTableLayout::VTableThunkTy &RHS) {
2252     assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2253            "Different thunks should have unique indices!");
2254     return LHS.first < RHS.first;
2255   });
2256 }
2257 
2258 VTableLayout::~VTableLayout() { }
2259 
2260 bool VTableContextBase::hasVtableSlot(const CXXMethodDecl *MD) {
2261   return MD->isVirtual() && !MD->isConsteval();
2262 }
2263 
2264 ItaniumVTableContext::ItaniumVTableContext(
2265     ASTContext &Context, VTableComponentLayout ComponentLayout)
2266     : VTableContextBase(/*MS=*/false), ComponentLayout(ComponentLayout) {}
2267 
2268 ItaniumVTableContext::~ItaniumVTableContext() {}
2269 
2270 uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
2271   GD = GD.getCanonicalDecl();
2272   MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2273   if (I != MethodVTableIndices.end())
2274     return I->second;
2275 
2276   const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2277 
2278   computeVTableRelatedInformation(RD);
2279 
2280   I = MethodVTableIndices.find(GD);
2281   assert(I != MethodVTableIndices.end() && "Did not find index!");
2282   return I->second;
2283 }
2284 
2285 CharUnits
2286 ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2287                                                  const CXXRecordDecl *VBase) {
2288   ClassPairTy ClassPair(RD, VBase);
2289 
2290   VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2291     VirtualBaseClassOffsetOffsets.find(ClassPair);
2292   if (I != VirtualBaseClassOffsetOffsets.end())
2293     return I->second;
2294 
2295   VCallAndVBaseOffsetBuilder Builder(*this, RD, RD, /*Overriders=*/nullptr,
2296                                      BaseSubobject(RD, CharUnits::Zero()),
2297                                      /*BaseIsVirtual=*/false,
2298                                      /*OffsetInLayoutClass=*/CharUnits::Zero());
2299 
2300   for (const auto &I : Builder.getVBaseOffsetOffsets()) {
2301     // Insert all types.
2302     ClassPairTy ClassPair(RD, I.first);
2303 
2304     VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
2305   }
2306 
2307   I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2308   assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2309 
2310   return I->second;
2311 }
2312 
2313 static std::unique_ptr<VTableLayout>
2314 CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
2315   SmallVector<VTableLayout::VTableThunkTy, 1>
2316     VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2317 
2318   return std::make_unique<VTableLayout>(
2319       Builder.VTableIndices, Builder.vtable_components(), VTableThunks,
2320       Builder.getAddressPoints());
2321 }
2322 
2323 void
2324 ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
2325   std::unique_ptr<const VTableLayout> &Entry = VTableLayouts[RD];
2326 
2327   // Check if we've computed this information before.
2328   if (Entry)
2329     return;
2330 
2331   ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2332                                /*MostDerivedClassIsVirtual=*/false, RD);
2333   Entry = CreateVTableLayout(Builder);
2334 
2335   MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2336                              Builder.vtable_indices_end());
2337 
2338   // Add the known thunks.
2339   Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2340 
2341   // If we don't have the vbase information for this class, insert it.
2342   // getVirtualBaseOffsetOffset will compute it separately without computing
2343   // the rest of the vtable related information.
2344   if (!RD->getNumVBases())
2345     return;
2346 
2347   const CXXRecordDecl *VBase =
2348     RD->vbases_begin()->getType()->getAsCXXRecordDecl();
2349 
2350   if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2351     return;
2352 
2353   for (const auto &I : Builder.getVBaseOffsetOffsets()) {
2354     // Insert all types.
2355     ClassPairTy ClassPair(RD, I.first);
2356 
2357     VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
2358   }
2359 }
2360 
2361 std::unique_ptr<VTableLayout>
2362 ItaniumVTableContext::createConstructionVTableLayout(
2363     const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2364     bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2365   ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2366                                MostDerivedClassIsVirtual, LayoutClass);
2367   return CreateVTableLayout(Builder);
2368 }
2369 
2370 namespace {
2371 
2372 // Vtables in the Microsoft ABI are different from the Itanium ABI.
2373 //
2374 // The main differences are:
2375 //  1. Separate vftable and vbtable.
2376 //
2377 //  2. Each subobject with a vfptr gets its own vftable rather than an address
2378 //     point in a single vtable shared between all the subobjects.
2379 //     Each vftable is represented by a separate section and virtual calls
2380 //     must be done using the vftable which has a slot for the function to be
2381 //     called.
2382 //
2383 //  3. Virtual method definitions expect their 'this' parameter to point to the
2384 //     first vfptr whose table provides a compatible overridden method.  In many
2385 //     cases, this permits the original vf-table entry to directly call
2386 //     the method instead of passing through a thunk.
2387 //     See example before VFTableBuilder::ComputeThisOffset below.
2388 //
2389 //     A compatible overridden method is one which does not have a non-trivial
2390 //     covariant-return adjustment.
2391 //
2392 //     The first vfptr is the one with the lowest offset in the complete-object
2393 //     layout of the defining class, and the method definition will subtract
2394 //     that constant offset from the parameter value to get the real 'this'
2395 //     value.  Therefore, if the offset isn't really constant (e.g. if a virtual
2396 //     function defined in a virtual base is overridden in a more derived
2397 //     virtual base and these bases have a reverse order in the complete
2398 //     object), the vf-table may require a this-adjustment thunk.
2399 //
2400 //  4. vftables do not contain new entries for overrides that merely require
2401 //     this-adjustment.  Together with #3, this keeps vf-tables smaller and
2402 //     eliminates the need for this-adjustment thunks in many cases, at the cost
2403 //     of often requiring redundant work to adjust the "this" pointer.
2404 //
2405 //  5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2406 //     Vtordisps are emitted into the class layout if a class has
2407 //      a) a user-defined ctor/dtor
2408 //     and
2409 //      b) a method overriding a method in a virtual base.
2410 //
2411 //  To get a better understanding of this code,
2412 //  you might want to see examples in test/CodeGenCXX/microsoft-abi-vtables-*.cpp
2413 
2414 class VFTableBuilder {
2415 public:
2416   typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2417     MethodVFTableLocationsTy;
2418 
2419   typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
2420     method_locations_range;
2421 
2422 private:
2423   /// VTables - Global vtable information.
2424   MicrosoftVTableContext &VTables;
2425 
2426   /// Context - The ASTContext which we will use for layout information.
2427   ASTContext &Context;
2428 
2429   /// MostDerivedClass - The most derived class for which we're building this
2430   /// vtable.
2431   const CXXRecordDecl *MostDerivedClass;
2432 
2433   const ASTRecordLayout &MostDerivedClassLayout;
2434 
2435   const VPtrInfo &WhichVFPtr;
2436 
2437   /// FinalOverriders - The final overriders of the most derived class.
2438   const FinalOverriders Overriders;
2439 
2440   /// Components - The components of the vftable being built.
2441   SmallVector<VTableComponent, 64> Components;
2442 
2443   MethodVFTableLocationsTy MethodVFTableLocations;
2444 
2445   /// Does this class have an RTTI component?
2446   bool HasRTTIComponent = false;
2447 
2448   /// MethodInfo - Contains information about a method in a vtable.
2449   /// (Used for computing 'this' pointer adjustment thunks.
2450   struct MethodInfo {
2451     /// VBTableIndex - The nonzero index in the vbtable that
2452     /// this method's base has, or zero.
2453     const uint64_t VBTableIndex;
2454 
2455     /// VFTableIndex - The index in the vftable that this method has.
2456     const uint64_t VFTableIndex;
2457 
2458     /// Shadowed - Indicates if this vftable slot is shadowed by
2459     /// a slot for a covariant-return override. If so, it shouldn't be printed
2460     /// or used for vcalls in the most derived class.
2461     bool Shadowed;
2462 
2463     /// UsesExtraSlot - Indicates if this vftable slot was created because
2464     /// any of the overridden slots required a return adjusting thunk.
2465     bool UsesExtraSlot;
2466 
2467     MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex,
2468                bool UsesExtraSlot = false)
2469         : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
2470           Shadowed(false), UsesExtraSlot(UsesExtraSlot) {}
2471 
2472     MethodInfo()
2473         : VBTableIndex(0), VFTableIndex(0), Shadowed(false),
2474           UsesExtraSlot(false) {}
2475   };
2476 
2477   typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2478 
2479   /// MethodInfoMap - The information for all methods in the vftable we're
2480   /// currently building.
2481   MethodInfoMapTy MethodInfoMap;
2482 
2483   typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2484 
2485   /// VTableThunks - The thunks by vftable index in the vftable currently being
2486   /// built.
2487   VTableThunksMapTy VTableThunks;
2488 
2489   typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2490   typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2491 
2492   /// Thunks - A map that contains all the thunks needed for all methods in the
2493   /// most derived class for which the vftable is currently being built.
2494   ThunksMapTy Thunks;
2495 
2496   /// AddThunk - Add a thunk for the given method.
2497   void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2498     SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2499 
2500     // Check if we have this thunk already.
2501     if (llvm::is_contained(ThunksVector, Thunk))
2502       return;
2503 
2504     ThunksVector.push_back(Thunk);
2505   }
2506 
2507   /// ComputeThisOffset - Returns the 'this' argument offset for the given
2508   /// method, relative to the beginning of the MostDerivedClass.
2509   CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
2510 
2511   void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2512                                    CharUnits ThisOffset, ThisAdjustment &TA);
2513 
2514   /// AddMethod - Add a single virtual member function to the vftable
2515   /// components vector.
2516   void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
2517     if (!TI.isEmpty()) {
2518       VTableThunks[Components.size()] = TI;
2519       AddThunk(MD, TI);
2520     }
2521     if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2522       assert(TI.Return.isEmpty() &&
2523              "Destructor can't have return adjustment!");
2524       Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2525     } else {
2526       Components.push_back(VTableComponent::MakeFunction(MD));
2527     }
2528   }
2529 
2530   /// AddMethods - Add the methods of this base subobject and the relevant
2531   /// subbases to the vftable we're currently laying out.
2532   void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2533                   const CXXRecordDecl *LastVBase,
2534                   BasesSetVectorTy &VisitedBases);
2535 
2536   void LayoutVFTable() {
2537     // RTTI data goes before all other entries.
2538     if (HasRTTIComponent)
2539       Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
2540 
2541     BasesSetVectorTy VisitedBases;
2542     AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, nullptr,
2543                VisitedBases);
2544     // Note that it is possible for the vftable to contain only an RTTI
2545     // pointer, if all virtual functions are constewval.
2546     assert(!Components.empty() && "vftable can't be empty");
2547 
2548     assert(MethodVFTableLocations.empty());
2549     for (const auto &I : MethodInfoMap) {
2550       const CXXMethodDecl *MD = I.first;
2551       const MethodInfo &MI = I.second;
2552       assert(MD == MD->getCanonicalDecl());
2553 
2554       // Skip the methods that the MostDerivedClass didn't override
2555       // and the entries shadowed by return adjusting thunks.
2556       if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2557         continue;
2558       MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2559                                 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
2560       if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2561         MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2562       } else {
2563         MethodVFTableLocations[MD] = Loc;
2564       }
2565     }
2566   }
2567 
2568 public:
2569   VFTableBuilder(MicrosoftVTableContext &VTables,
2570                  const CXXRecordDecl *MostDerivedClass, const VPtrInfo &Which)
2571       : VTables(VTables),
2572         Context(MostDerivedClass->getASTContext()),
2573         MostDerivedClass(MostDerivedClass),
2574         MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
2575         WhichVFPtr(Which),
2576         Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2577     // Provide the RTTI component if RTTIData is enabled. If the vftable would
2578     // be available externally, we should not provide the RTTI componenent. It
2579     // is currently impossible to get available externally vftables with either
2580     // dllimport or extern template instantiations, but eventually we may add a
2581     // flag to support additional devirtualization that needs this.
2582     if (Context.getLangOpts().RTTIData)
2583       HasRTTIComponent = true;
2584 
2585     LayoutVFTable();
2586 
2587     if (Context.getLangOpts().DumpVTableLayouts)
2588       dumpLayout(llvm::outs());
2589   }
2590 
2591   uint64_t getNumThunks() const { return Thunks.size(); }
2592 
2593   ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2594 
2595   ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2596 
2597   method_locations_range vtable_locations() const {
2598     return method_locations_range(MethodVFTableLocations.begin(),
2599                                   MethodVFTableLocations.end());
2600   }
2601 
2602   ArrayRef<VTableComponent> vtable_components() const { return Components; }
2603 
2604   VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2605     return VTableThunks.begin();
2606   }
2607 
2608   VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2609     return VTableThunks.end();
2610   }
2611 
2612   void dumpLayout(raw_ostream &);
2613 };
2614 
2615 } // end namespace
2616 
2617 // Let's study one class hierarchy as an example:
2618 //   struct A {
2619 //     virtual void f();
2620 //     int x;
2621 //   };
2622 //
2623 //   struct B : virtual A {
2624 //     virtual void f();
2625 //   };
2626 //
2627 // Record layouts:
2628 //   struct A:
2629 //   0 |   (A vftable pointer)
2630 //   4 |   int x
2631 //
2632 //   struct B:
2633 //   0 |   (B vbtable pointer)
2634 //   4 |   struct A (virtual base)
2635 //   4 |     (A vftable pointer)
2636 //   8 |     int x
2637 //
2638 // Let's assume we have a pointer to the A part of an object of dynamic type B:
2639 //   B b;
2640 //   A *a = (A*)&b;
2641 //   a->f();
2642 //
2643 // In this hierarchy, f() belongs to the vftable of A, so B::f() expects
2644 // "this" parameter to point at the A subobject, which is B+4.
2645 // In the B::f() prologue, it adjusts "this" back to B by subtracting 4,
2646 // performed as a *static* adjustment.
2647 //
2648 // Interesting thing happens when we alter the relative placement of A and B
2649 // subobjects in a class:
2650 //   struct C : virtual B { };
2651 //
2652 //   C c;
2653 //   A *a = (A*)&c;
2654 //   a->f();
2655 //
2656 // Respective record layout is:
2657 //   0 |   (C vbtable pointer)
2658 //   4 |   struct A (virtual base)
2659 //   4 |     (A vftable pointer)
2660 //   8 |     int x
2661 //  12 |   struct B (virtual base)
2662 //  12 |     (B vbtable pointer)
2663 //
2664 // The final overrider of f() in class C is still B::f(), so B+4 should be
2665 // passed as "this" to that code.  However, "a" points at B-8, so the respective
2666 // vftable entry should hold a thunk that adds 12 to the "this" argument before
2667 // performing a tail call to B::f().
2668 //
2669 // With this example in mind, we can now calculate the 'this' argument offset
2670 // for the given method, relative to the beginning of the MostDerivedClass.
2671 CharUnits
2672 VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
2673   BasesSetVectorTy Bases;
2674 
2675   {
2676     // Find the set of least derived bases that define the given method.
2677     OverriddenMethodsSetTy VisitedOverriddenMethods;
2678     auto InitialOverriddenDefinitionCollector = [&](
2679         const CXXMethodDecl *OverriddenMD) {
2680       if (OverriddenMD->size_overridden_methods() == 0)
2681         Bases.insert(OverriddenMD->getParent());
2682       // Don't recurse on this method if we've already collected it.
2683       return VisitedOverriddenMethods.insert(OverriddenMD).second;
2684     };
2685     visitAllOverriddenMethods(Overrider.Method,
2686                               InitialOverriddenDefinitionCollector);
2687   }
2688 
2689   // If there are no overrides then 'this' is located
2690   // in the base that defines the method.
2691   if (Bases.size() == 0)
2692     return Overrider.Offset;
2693 
2694   CXXBasePaths Paths;
2695   Overrider.Method->getParent()->lookupInBases(
2696       [&Bases](const CXXBaseSpecifier *Specifier, CXXBasePath &) {
2697         return Bases.count(Specifier->getType()->getAsCXXRecordDecl());
2698       },
2699       Paths);
2700 
2701   // This will hold the smallest this offset among overridees of MD.
2702   // This implies that an offset of a non-virtual base will dominate an offset
2703   // of a virtual base to potentially reduce the number of thunks required
2704   // in the derived classes that inherit this method.
2705   CharUnits Ret;
2706   bool First = true;
2707 
2708   const ASTRecordLayout &OverriderRDLayout =
2709       Context.getASTRecordLayout(Overrider.Method->getParent());
2710   for (const CXXBasePath &Path : Paths) {
2711     CharUnits ThisOffset = Overrider.Offset;
2712     CharUnits LastVBaseOffset;
2713 
2714     // For each path from the overrider to the parents of the overridden
2715     // methods, traverse the path, calculating the this offset in the most
2716     // derived class.
2717     for (const CXXBasePathElement &Element : Path) {
2718       QualType CurTy = Element.Base->getType();
2719       const CXXRecordDecl *PrevRD = Element.Class,
2720                           *CurRD = CurTy->getAsCXXRecordDecl();
2721       const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2722 
2723       if (Element.Base->isVirtual()) {
2724         // The interesting things begin when you have virtual inheritance.
2725         // The final overrider will use a static adjustment equal to the offset
2726         // of the vbase in the final overrider class.
2727         // For example, if the final overrider is in a vbase B of the most
2728         // derived class and it overrides a method of the B's own vbase A,
2729         // it uses A* as "this".  In its prologue, it can cast A* to B* with
2730         // a static offset.  This offset is used regardless of the actual
2731         // offset of A from B in the most derived class, requiring an
2732         // this-adjusting thunk in the vftable if A and B are laid out
2733         // differently in the most derived class.
2734         LastVBaseOffset = ThisOffset =
2735             Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
2736       } else {
2737         ThisOffset += Layout.getBaseClassOffset(CurRD);
2738       }
2739     }
2740 
2741     if (isa<CXXDestructorDecl>(Overrider.Method)) {
2742       if (LastVBaseOffset.isZero()) {
2743         // If a "Base" class has at least one non-virtual base with a virtual
2744         // destructor, the "Base" virtual destructor will take the address
2745         // of the "Base" subobject as the "this" argument.
2746         ThisOffset = Overrider.Offset;
2747       } else {
2748         // A virtual destructor of a virtual base takes the address of the
2749         // virtual base subobject as the "this" argument.
2750         ThisOffset = LastVBaseOffset;
2751       }
2752     }
2753 
2754     if (Ret > ThisOffset || First) {
2755       First = false;
2756       Ret = ThisOffset;
2757     }
2758   }
2759 
2760   assert(!First && "Method not found in the given subobject?");
2761   return Ret;
2762 }
2763 
2764 // Things are getting even more complex when the "this" adjustment has to
2765 // use a dynamic offset instead of a static one, or even two dynamic offsets.
2766 // This is sometimes required when a virtual call happens in the middle of
2767 // a non-most-derived class construction or destruction.
2768 //
2769 // Let's take a look at the following example:
2770 //   struct A {
2771 //     virtual void f();
2772 //   };
2773 //
2774 //   void foo(A *a) { a->f(); }  // Knows nothing about siblings of A.
2775 //
2776 //   struct B : virtual A {
2777 //     virtual void f();
2778 //     B() {
2779 //       foo(this);
2780 //     }
2781 //   };
2782 //
2783 //   struct C : virtual B {
2784 //     virtual void f();
2785 //   };
2786 //
2787 // Record layouts for these classes are:
2788 //   struct A
2789 //   0 |   (A vftable pointer)
2790 //
2791 //   struct B
2792 //   0 |   (B vbtable pointer)
2793 //   4 |   (vtordisp for vbase A)
2794 //   8 |   struct A (virtual base)
2795 //   8 |     (A vftable pointer)
2796 //
2797 //   struct C
2798 //   0 |   (C vbtable pointer)
2799 //   4 |   (vtordisp for vbase A)
2800 //   8 |   struct A (virtual base)  // A precedes B!
2801 //   8 |     (A vftable pointer)
2802 //  12 |   struct B (virtual base)
2803 //  12 |     (B vbtable pointer)
2804 //
2805 // When one creates an object of type C, the C constructor:
2806 // - initializes all the vbptrs, then
2807 // - calls the A subobject constructor
2808 //   (initializes A's vfptr with an address of A vftable), then
2809 // - calls the B subobject constructor
2810 //   (initializes A's vfptr with an address of B vftable and vtordisp for A),
2811 //   that in turn calls foo(), then
2812 // - initializes A's vfptr with an address of C vftable and zeroes out the
2813 //   vtordisp
2814 //   FIXME: if a structor knows it belongs to MDC, why doesn't it use a vftable
2815 //   without vtordisp thunks?
2816 //   FIXME: how are vtordisp handled in the presence of nooverride/final?
2817 //
2818 // When foo() is called, an object with a layout of class C has a vftable
2819 // referencing B::f() that assumes a B layout, so the "this" adjustments are
2820 // incorrect, unless an extra adjustment is done.  This adjustment is called
2821 // "vtordisp adjustment".  Vtordisp basically holds the difference between the
2822 // actual location of a vbase in the layout class and the location assumed by
2823 // the vftable of the class being constructed/destructed.  Vtordisp is only
2824 // needed if "this" escapes a
2825 // structor (or we can't prove otherwise).
2826 // [i.e. vtordisp is a dynamic adjustment for a static adjustment, which is an
2827 // estimation of a dynamic adjustment]
2828 //
2829 // foo() gets a pointer to the A vbase and doesn't know anything about B or C,
2830 // so it just passes that pointer as "this" in a virtual call.
2831 // If there was no vtordisp, that would just dispatch to B::f().
2832 // However, B::f() assumes B+8 is passed as "this",
2833 // yet the pointer foo() passes along is B-4 (i.e. C+8).
2834 // An extra adjustment is needed, so we emit a thunk into the B vftable.
2835 // This vtordisp thunk subtracts the value of vtordisp
2836 // from the "this" argument (-12) before making a tailcall to B::f().
2837 //
2838 // Let's consider an even more complex example:
2839 //   struct D : virtual B, virtual C {
2840 //     D() {
2841 //       foo(this);
2842 //     }
2843 //   };
2844 //
2845 //   struct D
2846 //   0 |   (D vbtable pointer)
2847 //   4 |   (vtordisp for vbase A)
2848 //   8 |   struct A (virtual base)  // A precedes both B and C!
2849 //   8 |     (A vftable pointer)
2850 //  12 |   struct B (virtual base)  // B precedes C!
2851 //  12 |     (B vbtable pointer)
2852 //  16 |   struct C (virtual base)
2853 //  16 |     (C vbtable pointer)
2854 //
2855 // When D::D() calls foo(), we find ourselves in a thunk that should tailcall
2856 // to C::f(), which assumes C+8 as its "this" parameter.  This time, foo()
2857 // passes along A, which is C-8.  The A vtordisp holds
2858 //   "D.vbptr[index_of_A] - offset_of_A_in_D"
2859 // and we statically know offset_of_A_in_D, so can get a pointer to D.
2860 // When we know it, we can make an extra vbtable lookup to locate the C vbase
2861 // and one extra static adjustment to calculate the expected value of C+8.
2862 void VFTableBuilder::CalculateVtordispAdjustment(
2863     FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2864     ThisAdjustment &TA) {
2865   const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2866       MostDerivedClassLayout.getVBaseOffsetsMap();
2867   const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
2868       VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
2869   assert(VBaseMapEntry != VBaseMap.end());
2870 
2871   // If there's no vtordisp or the final overrider is defined in the same vbase
2872   // as the initial declaration, we don't need any vtordisp adjustment.
2873   if (!VBaseMapEntry->second.hasVtorDisp() ||
2874       Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
2875     return;
2876 
2877   // OK, now we know we need to use a vtordisp thunk.
2878   // The implicit vtordisp field is located right before the vbase.
2879   CharUnits OffsetOfVBaseWithVFPtr = VBaseMapEntry->second.VBaseOffset;
2880   TA.Virtual.Microsoft.VtordispOffset =
2881       (OffsetOfVBaseWithVFPtr - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
2882 
2883   // A simple vtordisp thunk will suffice if the final overrider is defined
2884   // in either the most derived class or its non-virtual base.
2885   if (Overrider.Method->getParent() == MostDerivedClass ||
2886       !Overrider.VirtualBase)
2887     return;
2888 
2889   // Otherwise, we need to do use the dynamic offset of the final overrider
2890   // in order to get "this" adjustment right.
2891   TA.Virtual.Microsoft.VBPtrOffset =
2892       (OffsetOfVBaseWithVFPtr + WhichVFPtr.NonVirtualOffset -
2893        MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2894   TA.Virtual.Microsoft.VBOffsetOffset =
2895       Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
2896       VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
2897 
2898   TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2899 }
2900 
2901 static void GroupNewVirtualOverloads(
2902     const CXXRecordDecl *RD,
2903     SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2904   // Put the virtual methods into VirtualMethods in the proper order:
2905   // 1) Group overloads by declaration name. New groups are added to the
2906   //    vftable in the order of their first declarations in this class
2907   //    (including overrides, non-virtual methods and any other named decl that
2908   //    might be nested within the class).
2909   // 2) In each group, new overloads appear in the reverse order of declaration.
2910   typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2911   SmallVector<MethodGroup, 10> Groups;
2912   typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2913   VisitedGroupIndicesTy VisitedGroupIndices;
2914   for (const auto *D : RD->decls()) {
2915     const auto *ND = dyn_cast<NamedDecl>(D);
2916     if (!ND)
2917       continue;
2918     VisitedGroupIndicesTy::iterator J;
2919     bool Inserted;
2920     std::tie(J, Inserted) = VisitedGroupIndices.insert(
2921         std::make_pair(ND->getDeclName(), Groups.size()));
2922     if (Inserted)
2923       Groups.push_back(MethodGroup());
2924     if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
2925       if (MicrosoftVTableContext::hasVtableSlot(MD))
2926         Groups[J->second].push_back(MD->getCanonicalDecl());
2927   }
2928 
2929   for (const MethodGroup &Group : Groups)
2930     VirtualMethods.append(Group.rbegin(), Group.rend());
2931 }
2932 
2933 static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
2934   for (const auto &B : RD->bases()) {
2935     if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
2936       return true;
2937   }
2938   return false;
2939 }
2940 
2941 void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2942                                 const CXXRecordDecl *LastVBase,
2943                                 BasesSetVectorTy &VisitedBases) {
2944   const CXXRecordDecl *RD = Base.getBase();
2945   if (!RD->isPolymorphic())
2946     return;
2947 
2948   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2949 
2950   // See if this class expands a vftable of the base we look at, which is either
2951   // the one defined by the vfptr base path or the primary base of the current
2952   // class.
2953   const CXXRecordDecl *NextBase = nullptr, *NextLastVBase = LastVBase;
2954   CharUnits NextBaseOffset;
2955   if (BaseDepth < WhichVFPtr.PathToIntroducingObject.size()) {
2956     NextBase = WhichVFPtr.PathToIntroducingObject[BaseDepth];
2957     if (isDirectVBase(NextBase, RD)) {
2958       NextLastVBase = NextBase;
2959       NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2960     } else {
2961       NextBaseOffset =
2962           Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2963     }
2964   } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2965     assert(!Layout.isPrimaryBaseVirtual() &&
2966            "No primary virtual bases in this ABI");
2967     NextBase = PrimaryBase;
2968     NextBaseOffset = Base.getBaseOffset();
2969   }
2970 
2971   if (NextBase) {
2972     AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2973                NextLastVBase, VisitedBases);
2974     if (!VisitedBases.insert(NextBase))
2975       llvm_unreachable("Found a duplicate primary base!");
2976   }
2977 
2978   SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2979   // Put virtual methods in the proper order.
2980   GroupNewVirtualOverloads(RD, VirtualMethods);
2981 
2982   // Now go through all virtual member functions and add them to the current
2983   // vftable. This is done by
2984   //  - replacing overridden methods in their existing slots, as long as they
2985   //    don't require return adjustment; calculating This adjustment if needed.
2986   //  - adding new slots for methods of the current base not present in any
2987   //    sub-bases;
2988   //  - adding new slots for methods that require Return adjustment.
2989   // We keep track of the methods visited in the sub-bases in MethodInfoMap.
2990   for (const CXXMethodDecl *MD : VirtualMethods) {
2991     FinalOverriders::OverriderInfo FinalOverrider =
2992         Overriders.getOverrider(MD, Base.getBaseOffset());
2993     const CXXMethodDecl *FinalOverriderMD = FinalOverrider.Method;
2994     const CXXMethodDecl *OverriddenMD =
2995         FindNearestOverriddenMethod(MD, VisitedBases);
2996 
2997     ThisAdjustment ThisAdjustmentOffset;
2998     bool ReturnAdjustingThunk = false, ForceReturnAdjustmentMangling = false;
2999     CharUnits ThisOffset = ComputeThisOffset(FinalOverrider);
3000     ThisAdjustmentOffset.NonVirtual =
3001         (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
3002     if ((OverriddenMD || FinalOverriderMD != MD) &&
3003         WhichVFPtr.getVBaseWithVPtr())
3004       CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
3005                                   ThisAdjustmentOffset);
3006 
3007     unsigned VBIndex =
3008         LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
3009 
3010     if (OverriddenMD) {
3011       // If MD overrides anything in this vftable, we need to update the
3012       // entries.
3013       MethodInfoMapTy::iterator OverriddenMDIterator =
3014           MethodInfoMap.find(OverriddenMD);
3015 
3016       // If the overridden method went to a different vftable, skip it.
3017       if (OverriddenMDIterator == MethodInfoMap.end())
3018         continue;
3019 
3020       MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
3021 
3022       VBIndex = OverriddenMethodInfo.VBTableIndex;
3023 
3024       // Let's check if the overrider requires any return adjustments.
3025       // We must create a new slot if the MD's return type is not trivially
3026       // convertible to the OverriddenMD's one.
3027       // Once a chain of method overrides adds a return adjusting vftable slot,
3028       // all subsequent overrides will also use an extra method slot.
3029       ReturnAdjustingThunk = !ComputeReturnAdjustmentBaseOffset(
3030                                   Context, MD, OverriddenMD).isEmpty() ||
3031                              OverriddenMethodInfo.UsesExtraSlot;
3032 
3033       if (!ReturnAdjustingThunk) {
3034         // No return adjustment needed - just replace the overridden method info
3035         // with the current info.
3036         MethodInfo MI(VBIndex, OverriddenMethodInfo.VFTableIndex);
3037         MethodInfoMap.erase(OverriddenMDIterator);
3038 
3039         assert(!MethodInfoMap.count(MD) &&
3040                "Should not have method info for this method yet!");
3041         MethodInfoMap.insert(std::make_pair(MD, MI));
3042         continue;
3043       }
3044 
3045       // In case we need a return adjustment, we'll add a new slot for
3046       // the overrider. Mark the overridden method as shadowed by the new slot.
3047       OverriddenMethodInfo.Shadowed = true;
3048 
3049       // Force a special name mangling for a return-adjusting thunk
3050       // unless the method is the final overrider without this adjustment.
3051       ForceReturnAdjustmentMangling =
3052           !(MD == FinalOverriderMD && ThisAdjustmentOffset.isEmpty());
3053     } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
3054                MD->size_overridden_methods()) {
3055       // Skip methods that don't belong to the vftable of the current class,
3056       // e.g. each method that wasn't seen in any of the visited sub-bases
3057       // but overrides multiple methods of other sub-bases.
3058       continue;
3059     }
3060 
3061     // If we got here, MD is a method not seen in any of the sub-bases or
3062     // it requires return adjustment. Insert the method info for this method.
3063     MethodInfo MI(VBIndex,
3064                   HasRTTIComponent ? Components.size() - 1 : Components.size(),
3065                   ReturnAdjustingThunk);
3066 
3067     assert(!MethodInfoMap.count(MD) &&
3068            "Should not have method info for this method yet!");
3069     MethodInfoMap.insert(std::make_pair(MD, MI));
3070 
3071     // Check if this overrider needs a return adjustment.
3072     // We don't want to do this for pure virtual member functions.
3073     BaseOffset ReturnAdjustmentOffset;
3074     ReturnAdjustment ReturnAdjustment;
3075     if (!FinalOverriderMD->isPure()) {
3076       ReturnAdjustmentOffset =
3077           ComputeReturnAdjustmentBaseOffset(Context, FinalOverriderMD, MD);
3078     }
3079     if (!ReturnAdjustmentOffset.isEmpty()) {
3080       ForceReturnAdjustmentMangling = true;
3081       ReturnAdjustment.NonVirtual =
3082           ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
3083       if (ReturnAdjustmentOffset.VirtualBase) {
3084         const ASTRecordLayout &DerivedLayout =
3085             Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
3086         ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
3087             DerivedLayout.getVBPtrOffset().getQuantity();
3088         ReturnAdjustment.Virtual.Microsoft.VBIndex =
3089             VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
3090                                     ReturnAdjustmentOffset.VirtualBase);
3091       }
3092     }
3093 
3094     AddMethod(FinalOverriderMD,
3095               ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
3096                         ForceReturnAdjustmentMangling ? MD : nullptr));
3097   }
3098 }
3099 
3100 static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
3101   for (const CXXRecordDecl *Elem : llvm::reverse(Path)) {
3102     Out << "'";
3103     Elem->printQualifiedName(Out);
3104     Out << "' in ";
3105   }
3106 }
3107 
3108 static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
3109                                          bool ContinueFirstLine) {
3110   const ReturnAdjustment &R = TI.Return;
3111   bool Multiline = false;
3112   const char *LinePrefix = "\n       ";
3113   if (!R.isEmpty() || TI.Method) {
3114     if (!ContinueFirstLine)
3115       Out << LinePrefix;
3116     Out << "[return adjustment (to type '"
3117         << TI.Method->getReturnType().getCanonicalType() << "'): ";
3118     if (R.Virtual.Microsoft.VBPtrOffset)
3119       Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
3120     if (R.Virtual.Microsoft.VBIndex)
3121       Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
3122     Out << R.NonVirtual << " non-virtual]";
3123     Multiline = true;
3124   }
3125 
3126   const ThisAdjustment &T = TI.This;
3127   if (!T.isEmpty()) {
3128     if (Multiline || !ContinueFirstLine)
3129       Out << LinePrefix;
3130     Out << "[this adjustment: ";
3131     if (!TI.This.Virtual.isEmpty()) {
3132       assert(T.Virtual.Microsoft.VtordispOffset < 0);
3133       Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
3134       if (T.Virtual.Microsoft.VBPtrOffset) {
3135         Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
3136             << " to the left,";
3137         assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
3138         Out << LinePrefix << " vboffset at "
3139             << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
3140       }
3141     }
3142     Out << T.NonVirtual << " non-virtual]";
3143   }
3144 }
3145 
3146 void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3147   Out << "VFTable for ";
3148   PrintBasePath(WhichVFPtr.PathToIntroducingObject, Out);
3149   Out << "'";
3150   MostDerivedClass->printQualifiedName(Out);
3151   Out << "' (" << Components.size()
3152       << (Components.size() == 1 ? " entry" : " entries") << ").\n";
3153 
3154   for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3155     Out << llvm::format("%4d | ", I);
3156 
3157     const VTableComponent &Component = Components[I];
3158 
3159     // Dump the component.
3160     switch (Component.getKind()) {
3161     case VTableComponent::CK_RTTI:
3162       Component.getRTTIDecl()->printQualifiedName(Out);
3163       Out << " RTTI";
3164       break;
3165 
3166     case VTableComponent::CK_FunctionPointer: {
3167       const CXXMethodDecl *MD = Component.getFunctionDecl();
3168 
3169       // FIXME: Figure out how to print the real thunk type, since they can
3170       // differ in the return type.
3171       std::string Str = PredefinedExpr::ComputeName(
3172           PredefinedExpr::PrettyFunctionNoVirtual, MD);
3173       Out << Str;
3174       if (MD->isPure())
3175         Out << " [pure]";
3176 
3177       if (MD->isDeleted())
3178         Out << " [deleted]";
3179 
3180       ThunkInfo Thunk = VTableThunks.lookup(I);
3181       if (!Thunk.isEmpty())
3182         dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
3183 
3184       break;
3185     }
3186 
3187     case VTableComponent::CK_DeletingDtorPointer: {
3188       const CXXDestructorDecl *DD = Component.getDestructorDecl();
3189 
3190       DD->printQualifiedName(Out);
3191       Out << "() [scalar deleting]";
3192 
3193       if (DD->isPure())
3194         Out << " [pure]";
3195 
3196       ThunkInfo Thunk = VTableThunks.lookup(I);
3197       if (!Thunk.isEmpty()) {
3198         assert(Thunk.Return.isEmpty() &&
3199                "No return adjustment needed for destructors!");
3200         dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
3201       }
3202 
3203       break;
3204     }
3205 
3206     default:
3207       DiagnosticsEngine &Diags = Context.getDiagnostics();
3208       unsigned DiagID = Diags.getCustomDiagID(
3209           DiagnosticsEngine::Error,
3210           "Unexpected vftable component type %0 for component number %1");
3211       Diags.Report(MostDerivedClass->getLocation(), DiagID)
3212           << I << Component.getKind();
3213     }
3214 
3215     Out << '\n';
3216   }
3217 
3218   Out << '\n';
3219 
3220   if (!Thunks.empty()) {
3221     // We store the method names in a map to get a stable order.
3222     std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3223 
3224     for (const auto &I : Thunks) {
3225       const CXXMethodDecl *MD = I.first;
3226       std::string MethodName = PredefinedExpr::ComputeName(
3227           PredefinedExpr::PrettyFunctionNoVirtual, MD);
3228 
3229       MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3230     }
3231 
3232     for (const auto &MethodNameAndDecl : MethodNamesAndDecls) {
3233       const std::string &MethodName = MethodNameAndDecl.first;
3234       const CXXMethodDecl *MD = MethodNameAndDecl.second;
3235 
3236       ThunkInfoVectorTy ThunksVector = Thunks[MD];
3237       llvm::stable_sort(ThunksVector, [](const ThunkInfo &LHS,
3238                                          const ThunkInfo &RHS) {
3239         // Keep different thunks with the same adjustments in the order they
3240         // were put into the vector.
3241         return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
3242       });
3243 
3244       Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3245       Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3246 
3247       for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3248         const ThunkInfo &Thunk = ThunksVector[I];
3249 
3250         Out << llvm::format("%4d | ", I);
3251         dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
3252         Out << '\n';
3253       }
3254 
3255       Out << '\n';
3256     }
3257   }
3258 
3259   Out.flush();
3260 }
3261 
3262 static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
3263                           ArrayRef<const CXXRecordDecl *> B) {
3264   for (const CXXRecordDecl *Decl : B) {
3265     if (A.count(Decl))
3266       return true;
3267   }
3268   return false;
3269 }
3270 
3271 static bool rebucketPaths(VPtrInfoVector &Paths);
3272 
3273 /// Produces MSVC-compatible vbtable data.  The symbols produced by this
3274 /// algorithm match those produced by MSVC 2012 and newer, which is different
3275 /// from MSVC 2010.
3276 ///
3277 /// MSVC 2012 appears to minimize the vbtable names using the following
3278 /// algorithm.  First, walk the class hierarchy in the usual order, depth first,
3279 /// left to right, to find all of the subobjects which contain a vbptr field.
3280 /// Visiting each class node yields a list of inheritance paths to vbptrs.  Each
3281 /// record with a vbptr creates an initially empty path.
3282 ///
3283 /// To combine paths from child nodes, the paths are compared to check for
3284 /// ambiguity.  Paths are "ambiguous" if multiple paths have the same set of
3285 /// components in the same order.  Each group of ambiguous paths is extended by
3286 /// appending the class of the base from which it came.  If the current class
3287 /// node produced an ambiguous path, its path is extended with the current class.
3288 /// After extending paths, MSVC again checks for ambiguity, and extends any
3289 /// ambiguous path which wasn't already extended.  Because each node yields an
3290 /// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3291 /// to produce an unambiguous set of paths.
3292 ///
3293 /// TODO: Presumably vftables use the same algorithm.
3294 void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3295                                                 const CXXRecordDecl *RD,
3296                                                 VPtrInfoVector &Paths) {
3297   assert(Paths.empty());
3298   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3299 
3300   // Base case: this subobject has its own vptr.
3301   if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
3302     Paths.push_back(std::make_unique<VPtrInfo>(RD));
3303 
3304   // Recursive case: get all the vbtables from our bases and remove anything
3305   // that shares a virtual base.
3306   llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
3307   for (const auto &B : RD->bases()) {
3308     const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
3309     if (B.isVirtual() && VBasesSeen.count(Base))
3310       continue;
3311 
3312     if (!Base->isDynamicClass())
3313       continue;
3314 
3315     const VPtrInfoVector &BasePaths =
3316         ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3317 
3318     for (const std::unique_ptr<VPtrInfo> &BaseInfo : BasePaths) {
3319       // Don't include the path if it goes through a virtual base that we've
3320       // already included.
3321       if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
3322         continue;
3323 
3324       // Copy the path and adjust it as necessary.
3325       auto P = std::make_unique<VPtrInfo>(*BaseInfo);
3326 
3327       // We mangle Base into the path if the path would've been ambiguous and it
3328       // wasn't already extended with Base.
3329       if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3330         P->NextBaseToMangle = Base;
3331 
3332       // Keep track of which vtable the derived class is going to extend with
3333       // new methods or bases.  We append to either the vftable of our primary
3334       // base, or the first non-virtual base that has a vbtable.
3335       if (P->ObjectWithVPtr == Base &&
3336           Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
3337                                : Layout.getPrimaryBase()))
3338         P->ObjectWithVPtr = RD;
3339 
3340       // Keep track of the full adjustment from the MDC to this vtable.  The
3341       // adjustment is captured by an optional vbase and a non-virtual offset.
3342       if (B.isVirtual())
3343         P->ContainingVBases.push_back(Base);
3344       else if (P->ContainingVBases.empty())
3345         P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3346 
3347       // Update the full offset in the MDC.
3348       P->FullOffsetInMDC = P->NonVirtualOffset;
3349       if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3350         P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3351 
3352       Paths.push_back(std::move(P));
3353     }
3354 
3355     if (B.isVirtual())
3356       VBasesSeen.insert(Base);
3357 
3358     // After visiting any direct base, we've transitively visited all of its
3359     // morally virtual bases.
3360     for (const auto &VB : Base->vbases())
3361       VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
3362   }
3363 
3364   // Sort the paths into buckets, and if any of them are ambiguous, extend all
3365   // paths in ambiguous buckets.
3366   bool Changed = true;
3367   while (Changed)
3368     Changed = rebucketPaths(Paths);
3369 }
3370 
3371 static bool extendPath(VPtrInfo &P) {
3372   if (P.NextBaseToMangle) {
3373     P.MangledPath.push_back(P.NextBaseToMangle);
3374     P.NextBaseToMangle = nullptr;// Prevent the path from being extended twice.
3375     return true;
3376   }
3377   return false;
3378 }
3379 
3380 static bool rebucketPaths(VPtrInfoVector &Paths) {
3381   // What we're essentially doing here is bucketing together ambiguous paths.
3382   // Any bucket with more than one path in it gets extended by NextBase, which
3383   // is usually the direct base of the inherited the vbptr.  This code uses a
3384   // sorted vector to implement a multiset to form the buckets.  Note that the
3385   // ordering is based on pointers, but it doesn't change our output order.  The
3386   // current algorithm is designed to match MSVC 2012's names.
3387   llvm::SmallVector<std::reference_wrapper<VPtrInfo>, 2> PathsSorted(
3388       llvm::make_pointee_range(Paths));
3389   llvm::sort(PathsSorted, [](const VPtrInfo &LHS, const VPtrInfo &RHS) {
3390     return LHS.MangledPath < RHS.MangledPath;
3391   });
3392   bool Changed = false;
3393   for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3394     // Scan forward to find the end of the bucket.
3395     size_t BucketStart = I;
3396     do {
3397       ++I;
3398     } while (I != E &&
3399              PathsSorted[BucketStart].get().MangledPath ==
3400                  PathsSorted[I].get().MangledPath);
3401 
3402     // If this bucket has multiple paths, extend them all.
3403     if (I - BucketStart > 1) {
3404       for (size_t II = BucketStart; II != I; ++II)
3405         Changed |= extendPath(PathsSorted[II]);
3406       assert(Changed && "no paths were extended to fix ambiguity");
3407     }
3408   }
3409   return Changed;
3410 }
3411 
3412 MicrosoftVTableContext::~MicrosoftVTableContext() {}
3413 
3414 namespace {
3415 typedef llvm::SetVector<BaseSubobject, std::vector<BaseSubobject>,
3416                         llvm::DenseSet<BaseSubobject>> FullPathTy;
3417 }
3418 
3419 // This recursive function finds all paths from a subobject centered at
3420 // (RD, Offset) to the subobject located at IntroducingObject.
3421 static void findPathsToSubobject(ASTContext &Context,
3422                                  const ASTRecordLayout &MostDerivedLayout,
3423                                  const CXXRecordDecl *RD, CharUnits Offset,
3424                                  BaseSubobject IntroducingObject,
3425                                  FullPathTy &FullPath,
3426                                  std::list<FullPathTy> &Paths) {
3427   if (BaseSubobject(RD, Offset) == IntroducingObject) {
3428     Paths.push_back(FullPath);
3429     return;
3430   }
3431 
3432   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3433 
3434   for (const CXXBaseSpecifier &BS : RD->bases()) {
3435     const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
3436     CharUnits NewOffset = BS.isVirtual()
3437                               ? MostDerivedLayout.getVBaseClassOffset(Base)
3438                               : Offset + Layout.getBaseClassOffset(Base);
3439     FullPath.insert(BaseSubobject(Base, NewOffset));
3440     findPathsToSubobject(Context, MostDerivedLayout, Base, NewOffset,
3441                          IntroducingObject, FullPath, Paths);
3442     FullPath.pop_back();
3443   }
3444 }
3445 
3446 // Return the paths which are not subsets of other paths.
3447 static void removeRedundantPaths(std::list<FullPathTy> &FullPaths) {
3448   FullPaths.remove_if([&](const FullPathTy &SpecificPath) {
3449     for (const FullPathTy &OtherPath : FullPaths) {
3450       if (&SpecificPath == &OtherPath)
3451         continue;
3452       if (llvm::all_of(SpecificPath, [&](const BaseSubobject &BSO) {
3453             return OtherPath.contains(BSO);
3454           })) {
3455         return true;
3456       }
3457     }
3458     return false;
3459   });
3460 }
3461 
3462 static CharUnits getOffsetOfFullPath(ASTContext &Context,
3463                                      const CXXRecordDecl *RD,
3464                                      const FullPathTy &FullPath) {
3465   const ASTRecordLayout &MostDerivedLayout =
3466       Context.getASTRecordLayout(RD);
3467   CharUnits Offset = CharUnits::fromQuantity(-1);
3468   for (const BaseSubobject &BSO : FullPath) {
3469     const CXXRecordDecl *Base = BSO.getBase();
3470     // The first entry in the path is always the most derived record, skip it.
3471     if (Base == RD) {
3472       assert(Offset.getQuantity() == -1);
3473       Offset = CharUnits::Zero();
3474       continue;
3475     }
3476     assert(Offset.getQuantity() != -1);
3477     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3478     // While we know which base has to be traversed, we don't know if that base
3479     // was a virtual base.
3480     const CXXBaseSpecifier *BaseBS = std::find_if(
3481         RD->bases_begin(), RD->bases_end(), [&](const CXXBaseSpecifier &BS) {
3482           return BS.getType()->getAsCXXRecordDecl() == Base;
3483         });
3484     Offset = BaseBS->isVirtual() ? MostDerivedLayout.getVBaseClassOffset(Base)
3485                                  : Offset + Layout.getBaseClassOffset(Base);
3486     RD = Base;
3487   }
3488   return Offset;
3489 }
3490 
3491 // We want to select the path which introduces the most covariant overrides.  If
3492 // two paths introduce overrides which the other path doesn't contain, issue a
3493 // diagnostic.
3494 static const FullPathTy *selectBestPath(ASTContext &Context,
3495                                         const CXXRecordDecl *RD,
3496                                         const VPtrInfo &Info,
3497                                         std::list<FullPathTy> &FullPaths) {
3498   // Handle some easy cases first.
3499   if (FullPaths.empty())
3500     return nullptr;
3501   if (FullPaths.size() == 1)
3502     return &FullPaths.front();
3503 
3504   const FullPathTy *BestPath = nullptr;
3505   typedef std::set<const CXXMethodDecl *> OverriderSetTy;
3506   OverriderSetTy LastOverrides;
3507   for (const FullPathTy &SpecificPath : FullPaths) {
3508     assert(!SpecificPath.empty());
3509     OverriderSetTy CurrentOverrides;
3510     const CXXRecordDecl *TopLevelRD = SpecificPath.begin()->getBase();
3511     // Find the distance from the start of the path to the subobject with the
3512     // VPtr.
3513     CharUnits BaseOffset =
3514         getOffsetOfFullPath(Context, TopLevelRD, SpecificPath);
3515     FinalOverriders Overriders(TopLevelRD, CharUnits::Zero(), TopLevelRD);
3516     for (const CXXMethodDecl *MD : Info.IntroducingObject->methods()) {
3517       if (!MicrosoftVTableContext::hasVtableSlot(MD))
3518         continue;
3519       FinalOverriders::OverriderInfo OI =
3520           Overriders.getOverrider(MD->getCanonicalDecl(), BaseOffset);
3521       const CXXMethodDecl *OverridingMethod = OI.Method;
3522       // Only overriders which have a return adjustment introduce problematic
3523       // thunks.
3524       if (ComputeReturnAdjustmentBaseOffset(Context, OverridingMethod, MD)
3525               .isEmpty())
3526         continue;
3527       // It's possible that the overrider isn't in this path.  If so, skip it
3528       // because this path didn't introduce it.
3529       const CXXRecordDecl *OverridingParent = OverridingMethod->getParent();
3530       if (llvm::none_of(SpecificPath, [&](const BaseSubobject &BSO) {
3531             return BSO.getBase() == OverridingParent;
3532           }))
3533         continue;
3534       CurrentOverrides.insert(OverridingMethod);
3535     }
3536     OverriderSetTy NewOverrides =
3537         llvm::set_difference(CurrentOverrides, LastOverrides);
3538     if (NewOverrides.empty())
3539       continue;
3540     OverriderSetTy MissingOverrides =
3541         llvm::set_difference(LastOverrides, CurrentOverrides);
3542     if (MissingOverrides.empty()) {
3543       // This path is a strict improvement over the last path, let's use it.
3544       BestPath = &SpecificPath;
3545       std::swap(CurrentOverrides, LastOverrides);
3546     } else {
3547       // This path introduces an overrider with a conflicting covariant thunk.
3548       DiagnosticsEngine &Diags = Context.getDiagnostics();
3549       const CXXMethodDecl *CovariantMD = *NewOverrides.begin();
3550       const CXXMethodDecl *ConflictMD = *MissingOverrides.begin();
3551       Diags.Report(RD->getLocation(), diag::err_vftable_ambiguous_component)
3552           << RD;
3553       Diags.Report(CovariantMD->getLocation(), diag::note_covariant_thunk)
3554           << CovariantMD;
3555       Diags.Report(ConflictMD->getLocation(), diag::note_covariant_thunk)
3556           << ConflictMD;
3557     }
3558   }
3559   // Go with the path that introduced the most covariant overrides.  If there is
3560   // no such path, pick the first path.
3561   return BestPath ? BestPath : &FullPaths.front();
3562 }
3563 
3564 static void computeFullPathsForVFTables(ASTContext &Context,
3565                                         const CXXRecordDecl *RD,
3566                                         VPtrInfoVector &Paths) {
3567   const ASTRecordLayout &MostDerivedLayout = Context.getASTRecordLayout(RD);
3568   FullPathTy FullPath;
3569   std::list<FullPathTy> FullPaths;
3570   for (const std::unique_ptr<VPtrInfo>& Info : Paths) {
3571     findPathsToSubobject(
3572         Context, MostDerivedLayout, RD, CharUnits::Zero(),
3573         BaseSubobject(Info->IntroducingObject, Info->FullOffsetInMDC), FullPath,
3574         FullPaths);
3575     FullPath.clear();
3576     removeRedundantPaths(FullPaths);
3577     Info->PathToIntroducingObject.clear();
3578     if (const FullPathTy *BestPath =
3579             selectBestPath(Context, RD, *Info, FullPaths))
3580       for (const BaseSubobject &BSO : *BestPath)
3581         Info->PathToIntroducingObject.push_back(BSO.getBase());
3582     FullPaths.clear();
3583   }
3584 }
3585 
3586 static bool vfptrIsEarlierInMDC(const ASTRecordLayout &Layout,
3587                                 const MethodVFTableLocation &LHS,
3588                                 const MethodVFTableLocation &RHS) {
3589   CharUnits L = LHS.VFPtrOffset;
3590   CharUnits R = RHS.VFPtrOffset;
3591   if (LHS.VBase)
3592     L += Layout.getVBaseClassOffset(LHS.VBase);
3593   if (RHS.VBase)
3594     R += Layout.getVBaseClassOffset(RHS.VBase);
3595   return L < R;
3596 }
3597 
3598 void MicrosoftVTableContext::computeVTableRelatedInformation(
3599     const CXXRecordDecl *RD) {
3600   assert(RD->isDynamicClass());
3601 
3602   // Check if we've computed this information before.
3603   if (VFPtrLocations.count(RD))
3604     return;
3605 
3606   const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3607 
3608   {
3609     auto VFPtrs = std::make_unique<VPtrInfoVector>();
3610     computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3611     computeFullPathsForVFTables(Context, RD, *VFPtrs);
3612     VFPtrLocations[RD] = std::move(VFPtrs);
3613   }
3614 
3615   MethodVFTableLocationsTy NewMethodLocations;
3616   for (const std::unique_ptr<VPtrInfo> &VFPtr : *VFPtrLocations[RD]) {
3617     VFTableBuilder Builder(*this, RD, *VFPtr);
3618 
3619     VFTableIdTy id(RD, VFPtr->FullOffsetInMDC);
3620     assert(VFTableLayouts.count(id) == 0);
3621     SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3622         Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
3623     VFTableLayouts[id] = std::make_unique<VTableLayout>(
3624         ArrayRef<size_t>{0}, Builder.vtable_components(), VTableThunks,
3625         EmptyAddressPointsMap);
3626     Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3627 
3628     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3629     for (const auto &Loc : Builder.vtable_locations()) {
3630       auto Insert = NewMethodLocations.insert(Loc);
3631       if (!Insert.second) {
3632         const MethodVFTableLocation &NewLoc = Loc.second;
3633         MethodVFTableLocation &OldLoc = Insert.first->second;
3634         if (vfptrIsEarlierInMDC(Layout, NewLoc, OldLoc))
3635           OldLoc = NewLoc;
3636       }
3637     }
3638   }
3639 
3640   MethodVFTableLocations.insert(NewMethodLocations.begin(),
3641                                 NewMethodLocations.end());
3642   if (Context.getLangOpts().DumpVTableLayouts)
3643     dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
3644 }
3645 
3646 void MicrosoftVTableContext::dumpMethodLocations(
3647     const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3648     raw_ostream &Out) {
3649   // Compute the vtable indices for all the member functions.
3650   // Store them in a map keyed by the location so we'll get a sorted table.
3651   std::map<MethodVFTableLocation, std::string> IndicesMap;
3652   bool HasNonzeroOffset = false;
3653 
3654   for (const auto &I : NewMethods) {
3655     const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I.first.getDecl());
3656     assert(hasVtableSlot(MD));
3657 
3658     std::string MethodName = PredefinedExpr::ComputeName(
3659         PredefinedExpr::PrettyFunctionNoVirtual, MD);
3660 
3661     if (isa<CXXDestructorDecl>(MD)) {
3662       IndicesMap[I.second] = MethodName + " [scalar deleting]";
3663     } else {
3664       IndicesMap[I.second] = MethodName;
3665     }
3666 
3667     if (!I.second.VFPtrOffset.isZero() || I.second.VBTableIndex != 0)
3668       HasNonzeroOffset = true;
3669   }
3670 
3671   // Print the vtable indices for all the member functions.
3672   if (!IndicesMap.empty()) {
3673     Out << "VFTable indices for ";
3674     Out << "'";
3675     RD->printQualifiedName(Out);
3676     Out << "' (" << IndicesMap.size()
3677         << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
3678 
3679     CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3680     uint64_t LastVBIndex = 0;
3681     for (const auto &I : IndicesMap) {
3682       CharUnits VFPtrOffset = I.first.VFPtrOffset;
3683       uint64_t VBIndex = I.first.VBTableIndex;
3684       if (HasNonzeroOffset &&
3685           (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3686         assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3687         Out << " -- accessible via ";
3688         if (VBIndex)
3689           Out << "vbtable index " << VBIndex << ", ";
3690         Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3691         LastVFPtrOffset = VFPtrOffset;
3692         LastVBIndex = VBIndex;
3693       }
3694 
3695       uint64_t VTableIndex = I.first.Index;
3696       const std::string &MethodName = I.second;
3697       Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3698     }
3699     Out << '\n';
3700   }
3701 
3702   Out.flush();
3703 }
3704 
3705 const VirtualBaseInfo &MicrosoftVTableContext::computeVBTableRelatedInformation(
3706     const CXXRecordDecl *RD) {
3707   VirtualBaseInfo *VBI;
3708 
3709   {
3710     // Get or create a VBI for RD.  Don't hold a reference to the DenseMap cell,
3711     // as it may be modified and rehashed under us.
3712     std::unique_ptr<VirtualBaseInfo> &Entry = VBaseInfo[RD];
3713     if (Entry)
3714       return *Entry;
3715     Entry = std::make_unique<VirtualBaseInfo>();
3716     VBI = Entry.get();
3717   }
3718 
3719   computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
3720 
3721   // First, see if the Derived class shared the vbptr with a non-virtual base.
3722   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3723   if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
3724     // If the Derived class shares the vbptr with a non-virtual base, the shared
3725     // virtual bases come first so that the layout is the same.
3726     const VirtualBaseInfo &BaseInfo =
3727         computeVBTableRelatedInformation(VBPtrBase);
3728     VBI->VBTableIndices.insert(BaseInfo.VBTableIndices.begin(),
3729                                BaseInfo.VBTableIndices.end());
3730   }
3731 
3732   // New vbases are added to the end of the vbtable.
3733   // Skip the self entry and vbases visited in the non-virtual base, if any.
3734   unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
3735   for (const auto &VB : RD->vbases()) {
3736     const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
3737     if (!VBI->VBTableIndices.count(CurVBase))
3738       VBI->VBTableIndices[CurVBase] = VBTableIndex++;
3739   }
3740 
3741   return *VBI;
3742 }
3743 
3744 unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3745                                                  const CXXRecordDecl *VBase) {
3746   const VirtualBaseInfo &VBInfo = computeVBTableRelatedInformation(Derived);
3747   assert(VBInfo.VBTableIndices.count(VBase));
3748   return VBInfo.VBTableIndices.find(VBase)->second;
3749 }
3750 
3751 const VPtrInfoVector &
3752 MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
3753   return computeVBTableRelatedInformation(RD).VBPtrPaths;
3754 }
3755 
3756 const VPtrInfoVector &
3757 MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
3758   computeVTableRelatedInformation(RD);
3759 
3760   assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
3761   return *VFPtrLocations[RD];
3762 }
3763 
3764 const VTableLayout &
3765 MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3766                                          CharUnits VFPtrOffset) {
3767   computeVTableRelatedInformation(RD);
3768 
3769   VFTableIdTy id(RD, VFPtrOffset);
3770   assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3771   return *VFTableLayouts[id];
3772 }
3773 
3774 MethodVFTableLocation
3775 MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
3776   assert(hasVtableSlot(cast<CXXMethodDecl>(GD.getDecl())) &&
3777          "Only use this method for virtual methods or dtors");
3778   if (isa<CXXDestructorDecl>(GD.getDecl()))
3779     assert(GD.getDtorType() == Dtor_Deleting);
3780 
3781   GD = GD.getCanonicalDecl();
3782 
3783   MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3784   if (I != MethodVFTableLocations.end())
3785     return I->second;
3786 
3787   const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3788 
3789   computeVTableRelatedInformation(RD);
3790 
3791   I = MethodVFTableLocations.find(GD);
3792   assert(I != MethodVFTableLocations.end() && "Did not find index!");
3793   return I->second;
3794 }
3795