blob: 013ebe23ec9188135fb057ed811da43e0386878c [file] [log] [blame]
Peter Collingbournecfd23562011-09-26 01:57:12 +00001//===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Peter Collingbournecfd23562011-09-26 01:57:12 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with generation of the layout of virtual tables.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/VTableBuilder.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000014#include "clang/AST/ASTContext.h"
David Majnemer70e6a002015-05-01 21:35:45 +000015#include "clang/AST/ASTDiagnostic.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/Basic/TargetInfo.h"
David Majnemerab130922015-05-04 18:47:54 +000019#include "llvm/ADT/SetOperations.h"
Reid Kleckner5f080942014-01-03 23:42:00 +000020#include "llvm/ADT/SmallPtrSet.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000021#include "llvm/Support/Format.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000022#include "llvm/Support/raw_ostream.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000023#include <algorithm>
24#include <cstdio>
25
26using namespace clang;
27
28#define DUMP_OVERRIDERS 0
29
30namespace {
31
32/// BaseOffset - Represents an offset from a derived class to a direct or
33/// indirect base class.
34struct BaseOffset {
35 /// DerivedClass - The derived class.
36 const CXXRecordDecl *DerivedClass;
Fangrui Song6907ce22018-07-30 19:24:48 +000037
Peter Collingbournecfd23562011-09-26 01:57:12 +000038 /// VirtualBase - If the path from the derived class to the base class
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +000039 /// involves virtual base classes, this holds the declaration of the last
40 /// virtual base in this path (i.e. closest to the base class).
Peter Collingbournecfd23562011-09-26 01:57:12 +000041 const CXXRecordDecl *VirtualBase;
42
43 /// NonVirtualOffset - The offset from the derived class to the base class.
Fangrui Song6907ce22018-07-30 19:24:48 +000044 /// (Or the offset from the virtual base class to the base class, if the
Peter Collingbournecfd23562011-09-26 01:57:12 +000045 /// path from the derived class to the base class involves a virtual base
46 /// class.
47 CharUnits NonVirtualOffset;
Craig Topper36250ad2014-05-12 05:36:57 +000048
49 BaseOffset() : DerivedClass(nullptr), VirtualBase(nullptr),
50 NonVirtualOffset(CharUnits::Zero()) { }
Peter Collingbournecfd23562011-09-26 01:57:12 +000051 BaseOffset(const CXXRecordDecl *DerivedClass,
52 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
Fangrui Song6907ce22018-07-30 19:24:48 +000053 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
Peter Collingbournecfd23562011-09-26 01:57:12 +000054 NonVirtualOffset(NonVirtualOffset) { }
55
56 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
57};
58
59/// FinalOverriders - Contains the final overrider member functions for all
60/// member functions in the base subobjects of a class.
61class FinalOverriders {
62public:
63 /// OverriderInfo - Information about a final overrider.
64 struct OverriderInfo {
65 /// Method - The method decl of the overrider.
66 const CXXMethodDecl *Method;
67
Timur Iskhodzhanov7d19fc12014-11-17 15:11:05 +000068 /// VirtualBase - The virtual base class subobject of this overrider.
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +000069 /// Note that this records the closest derived virtual base class subobject.
70 const CXXRecordDecl *VirtualBase;
71
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000072 /// Offset - the base offset of the overrider's parent in the layout class.
Peter Collingbournecfd23562011-09-26 01:57:12 +000073 CharUnits Offset;
Craig Topper36250ad2014-05-12 05:36:57 +000074
75 OverriderInfo() : Method(nullptr), VirtualBase(nullptr),
76 Offset(CharUnits::Zero()) { }
Peter Collingbournecfd23562011-09-26 01:57:12 +000077 };
78
79private:
80 /// MostDerivedClass - The most derived class for which the final overriders
81 /// are stored.
82 const CXXRecordDecl *MostDerivedClass;
Fangrui Song6907ce22018-07-30 19:24:48 +000083
84 /// MostDerivedClassOffset - If we're building final overriders for a
Peter Collingbournecfd23562011-09-26 01:57:12 +000085 /// construction vtable, this holds the offset from the layout class to the
86 /// most derived class.
87 const CharUnits MostDerivedClassOffset;
88
Fangrui Song6907ce22018-07-30 19:24:48 +000089 /// LayoutClass - The class we're using for layout information. Will be
Peter Collingbournecfd23562011-09-26 01:57:12 +000090 /// different than the most derived class if the final overriders are for a
Fangrui Song6907ce22018-07-30 19:24:48 +000091 /// construction vtable.
92 const CXXRecordDecl *LayoutClass;
Peter Collingbournecfd23562011-09-26 01:57:12 +000093
94 ASTContext &Context;
Fangrui Song6907ce22018-07-30 19:24:48 +000095
Peter Collingbournecfd23562011-09-26 01:57:12 +000096 /// MostDerivedClassLayout - the AST record layout of the most derived class.
97 const ASTRecordLayout &MostDerivedClassLayout;
98
99 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
100 /// in a base subobject.
101 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
102
103 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
104 OverriderInfo> OverridersMapTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000105
106 /// OverridersMap - The final overriders for all virtual member functions of
Peter Collingbournecfd23562011-09-26 01:57:12 +0000107 /// all the base subobjects of the most derived class.
108 OverridersMapTy OverridersMap;
Fangrui Song6907ce22018-07-30 19:24:48 +0000109
Peter Collingbournecfd23562011-09-26 01:57:12 +0000110 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
111 /// as a record decl and a subobject number) and its offsets in the most
112 /// derived class as well as the layout class.
Fangrui Song6907ce22018-07-30 19:24:48 +0000113 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000114 CharUnits> SubobjectOffsetMapTy;
115
116 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000117
Peter Collingbournecfd23562011-09-26 01:57:12 +0000118 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
119 /// given base.
120 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
121 CharUnits OffsetInLayoutClass,
122 SubobjectOffsetMapTy &SubobjectOffsets,
123 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
124 SubobjectCountMapTy &SubobjectCounts);
125
126 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000127
Peter Collingbournecfd23562011-09-26 01:57:12 +0000128 /// dump - dump the final overriders for a base subobject, and all its direct
129 /// and indirect base subobjects.
130 void dump(raw_ostream &Out, BaseSubobject Base,
131 VisitedVirtualBasesSetTy& VisitedVirtualBases);
Fangrui Song6907ce22018-07-30 19:24:48 +0000132
Peter Collingbournecfd23562011-09-26 01:57:12 +0000133public:
134 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
135 CharUnits MostDerivedClassOffset,
136 const CXXRecordDecl *LayoutClass);
137
138 /// getOverrider - Get the final overrider for the given method declaration in
Fangrui Song6907ce22018-07-30 19:24:48 +0000139 /// the subobject with the given base offset.
140 OverriderInfo getOverrider(const CXXMethodDecl *MD,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000141 CharUnits BaseOffset) const {
Fangrui Song6907ce22018-07-30 19:24:48 +0000142 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000143 "Did not find overrider!");
Fangrui Song6907ce22018-07-30 19:24:48 +0000144
Peter Collingbournecfd23562011-09-26 01:57:12 +0000145 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
146 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000147
Peter Collingbournecfd23562011-09-26 01:57:12 +0000148 /// dump - dump the final overriders.
149 void dump() {
150 VisitedVirtualBasesSetTy VisitedVirtualBases;
Fangrui Song6907ce22018-07-30 19:24:48 +0000151 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000152 VisitedVirtualBases);
153 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000154
Peter Collingbournecfd23562011-09-26 01:57:12 +0000155};
156
Peter Collingbournecfd23562011-09-26 01:57:12 +0000157FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
158 CharUnits MostDerivedClassOffset,
159 const CXXRecordDecl *LayoutClass)
Fangrui Song6907ce22018-07-30 19:24:48 +0000160 : MostDerivedClass(MostDerivedClass),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000161 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
162 Context(MostDerivedClass->getASTContext()),
163 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
164
165 // Compute base offsets.
166 SubobjectOffsetMapTy SubobjectOffsets;
167 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
168 SubobjectCountMapTy SubobjectCounts;
Fangrui Song6907ce22018-07-30 19:24:48 +0000169 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000170 /*IsVirtual=*/false,
Fangrui Song6907ce22018-07-30 19:24:48 +0000171 MostDerivedClassOffset,
172 SubobjectOffsets, SubobjectLayoutClassOffsets,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000173 SubobjectCounts);
174
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000175 // Get the final overriders.
Peter Collingbournecfd23562011-09-26 01:57:12 +0000176 CXXFinalOverriderMap FinalOverriders;
177 MostDerivedClass->getFinalOverriders(FinalOverriders);
178
Benjamin Kramera37e7652015-07-25 17:10:49 +0000179 for (const auto &Overrider : FinalOverriders) {
180 const CXXMethodDecl *MD = Overrider.first;
181 const OverridingMethods &Methods = Overrider.second;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000182
Benjamin Kramera37e7652015-07-25 17:10:49 +0000183 for (const auto &M : Methods) {
184 unsigned SubobjectNumber = M.first;
Fangrui Song6907ce22018-07-30 19:24:48 +0000185 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000186 SubobjectNumber)) &&
187 "Did not find subobject offset!");
Fangrui Song6907ce22018-07-30 19:24:48 +0000188
Peter Collingbournecfd23562011-09-26 01:57:12 +0000189 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
190 SubobjectNumber)];
191
Benjamin Kramera37e7652015-07-25 17:10:49 +0000192 assert(M.second.size() == 1 && "Final overrider is not unique!");
193 const UniqueVirtualMethod &Method = M.second.front();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000194
195 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
196 assert(SubobjectLayoutClassOffsets.count(
197 std::make_pair(OverriderRD, Method.Subobject))
198 && "Did not find subobject offset!");
199 CharUnits OverriderOffset =
Fangrui Song6907ce22018-07-30 19:24:48 +0000200 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000201 Method.Subobject)];
202
203 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
204 assert(!Overrider.Method && "Overrider should not exist yet!");
Fangrui Song6907ce22018-07-30 19:24:48 +0000205
Peter Collingbournecfd23562011-09-26 01:57:12 +0000206 Overrider.Offset = OverriderOffset;
207 Overrider.Method = Method.Method;
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +0000208 Overrider.VirtualBase = Method.InVirtualSubobject;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000209 }
210 }
211
212#if DUMP_OVERRIDERS
213 // And dump them (for now).
214 dump();
215#endif
216}
217
David Majnemerab130922015-05-04 18:47:54 +0000218static BaseOffset ComputeBaseOffset(const ASTContext &Context,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000219 const CXXRecordDecl *DerivedRD,
220 const CXXBasePath &Path) {
221 CharUnits NonVirtualOffset = CharUnits::Zero();
222
223 unsigned NonVirtualStart = 0;
Craig Topper36250ad2014-05-12 05:36:57 +0000224 const CXXRecordDecl *VirtualBase = nullptr;
225
Peter Collingbournecfd23562011-09-26 01:57:12 +0000226 // First, look for the virtual base class.
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000227 for (int I = Path.size(), E = 0; I != E; --I) {
228 const CXXBasePathElement &Element = Path[I - 1];
229
Peter Collingbournecfd23562011-09-26 01:57:12 +0000230 if (Element.Base->isVirtual()) {
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000231 NonVirtualStart = I;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000232 QualType VBaseType = Element.Base->getType();
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000233 VirtualBase = VBaseType->getAsCXXRecordDecl();
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000234 break;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000235 }
236 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000237
Peter Collingbournecfd23562011-09-26 01:57:12 +0000238 // Now compute the non-virtual offset.
239 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
240 const CXXBasePathElement &Element = Path[I];
Fangrui Song6907ce22018-07-30 19:24:48 +0000241
Peter Collingbournecfd23562011-09-26 01:57:12 +0000242 // Check the base class offset.
243 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
244
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000245 const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000246
247 NonVirtualOffset += Layout.getBaseClassOffset(Base);
248 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000249
Peter Collingbournecfd23562011-09-26 01:57:12 +0000250 // FIXME: This should probably use CharUnits or something. Maybe we should
Fangrui Song6907ce22018-07-30 19:24:48 +0000251 // even change the base offsets in ASTRecordLayout to be specified in
Peter Collingbournecfd23562011-09-26 01:57:12 +0000252 // CharUnits.
253 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000254
Peter Collingbournecfd23562011-09-26 01:57:12 +0000255}
256
David Majnemerab130922015-05-04 18:47:54 +0000257static BaseOffset ComputeBaseOffset(const ASTContext &Context,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000258 const CXXRecordDecl *BaseRD,
259 const CXXRecordDecl *DerivedRD) {
260 CXXBasePaths Paths(/*FindAmbiguities=*/false,
261 /*RecordPaths=*/true, /*DetectVirtual=*/false);
Benjamin Kramer325d7452013-02-03 18:55:34 +0000262
263 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000264 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +0000265
266 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
267}
268
269static BaseOffset
Fangrui Song6907ce22018-07-30 19:24:48 +0000270ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000271 const CXXMethodDecl *DerivedMD,
272 const CXXMethodDecl *BaseMD) {
Simon Pilgrim54b29142020-01-12 22:08:56 +0000273 const auto *BaseFT = BaseMD->getType()->castAs<FunctionType>();
274 const auto *DerivedFT = DerivedMD->getType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +0000275
Peter Collingbournecfd23562011-09-26 01:57:12 +0000276 // Canonicalize the return types.
Alp Toker314cc812014-01-25 16:55:45 +0000277 CanQualType CanDerivedReturnType =
278 Context.getCanonicalType(DerivedFT->getReturnType());
279 CanQualType CanBaseReturnType =
280 Context.getCanonicalType(BaseFT->getReturnType());
281
Fangrui Song6907ce22018-07-30 19:24:48 +0000282 assert(CanDerivedReturnType->getTypeClass() ==
283 CanBaseReturnType->getTypeClass() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000284 "Types must have same type class!");
Fangrui Song6907ce22018-07-30 19:24:48 +0000285
Peter Collingbournecfd23562011-09-26 01:57:12 +0000286 if (CanDerivedReturnType == CanBaseReturnType) {
287 // No adjustment needed.
288 return BaseOffset();
289 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000290
Peter Collingbournecfd23562011-09-26 01:57:12 +0000291 if (isa<ReferenceType>(CanDerivedReturnType)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000292 CanDerivedReturnType =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000293 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000294 CanBaseReturnType =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000295 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
296 } else if (isa<PointerType>(CanDerivedReturnType)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000297 CanDerivedReturnType =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000298 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000299 CanBaseReturnType =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000300 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
301 } else {
302 llvm_unreachable("Unexpected return type!");
303 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000304
Peter Collingbournecfd23562011-09-26 01:57:12 +0000305 // We need to compare unqualified types here; consider
306 // const T *Base::foo();
307 // T *Derived::foo();
Fangrui Song6907ce22018-07-30 19:24:48 +0000308 if (CanDerivedReturnType.getUnqualifiedType() ==
Peter Collingbournecfd23562011-09-26 01:57:12 +0000309 CanBaseReturnType.getUnqualifiedType()) {
310 // No adjustment needed.
311 return BaseOffset();
312 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000313
314 const CXXRecordDecl *DerivedRD =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000315 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +0000316
317 const CXXRecordDecl *BaseRD =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000318 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
319
320 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
321}
322
Fangrui Song6907ce22018-07-30 19:24:48 +0000323void
Peter Collingbournecfd23562011-09-26 01:57:12 +0000324FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
325 CharUnits OffsetInLayoutClass,
326 SubobjectOffsetMapTy &SubobjectOffsets,
327 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
328 SubobjectCountMapTy &SubobjectCounts) {
329 const CXXRecordDecl *RD = Base.getBase();
Fangrui Song6907ce22018-07-30 19:24:48 +0000330
Peter Collingbournecfd23562011-09-26 01:57:12 +0000331 unsigned SubobjectNumber = 0;
332 if (!IsVirtual)
333 SubobjectNumber = ++SubobjectCounts[RD];
334
335 // Set up the subobject to offset mapping.
336 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
337 && "Subobject offset already exists!");
Fangrui Song6907ce22018-07-30 19:24:48 +0000338 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000339 && "Subobject offset already exists!");
340
341 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
342 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
343 OffsetInLayoutClass;
Fangrui Song6907ce22018-07-30 19:24:48 +0000344
Peter Collingbournecfd23562011-09-26 01:57:12 +0000345 // Traverse our bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000346 for (const auto &B : RD->bases()) {
347 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000348
349 CharUnits BaseOffset;
350 CharUnits BaseOffsetInLayoutClass;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000351 if (B.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000352 // Check if we've visited this virtual base before.
353 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
354 continue;
355
356 const ASTRecordLayout &LayoutClassLayout =
357 Context.getASTRecordLayout(LayoutClass);
358
359 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +0000360 BaseOffsetInLayoutClass =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000361 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
362 } else {
363 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
364 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +0000365
Peter Collingbournecfd23562011-09-26 01:57:12 +0000366 BaseOffset = Base.getBaseOffset() + Offset;
367 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
368 }
369
Fangrui Song6907ce22018-07-30 19:24:48 +0000370 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
371 B.isVirtual(), BaseOffsetInLayoutClass,
372 SubobjectOffsets, SubobjectLayoutClassOffsets,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000373 SubobjectCounts);
374 }
375}
376
377void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
378 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
379 const CXXRecordDecl *RD = Base.getBase();
380 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
381
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000382 for (const auto &B : RD->bases()) {
383 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +0000384
Peter Collingbournecfd23562011-09-26 01:57:12 +0000385 // Ignore bases that don't have any virtual member functions.
386 if (!BaseDecl->isPolymorphic())
387 continue;
388
389 CharUnits BaseOffset;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000390 if (B.isVirtual()) {
David Blaikie82e95a32014-11-19 07:49:47 +0000391 if (!VisitedVirtualBases.insert(BaseDecl).second) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000392 // We've visited this base before.
393 continue;
394 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000395
Peter Collingbournecfd23562011-09-26 01:57:12 +0000396 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
397 } else {
398 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
399 }
400
401 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
402 }
403
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000404 Out << "Final overriders for (";
405 RD->printQualifiedName(Out);
406 Out << ", ";
Peter Collingbournecfd23562011-09-26 01:57:12 +0000407 Out << Base.getBaseOffset().getQuantity() << ")\n";
408
409 // Now dump the overriders for this base subobject.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000410 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000411 if (!MD->isVirtual())
412 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +0000413 MD = MD->getCanonicalDecl();
NAKAMURA Takumi073f2b42015-02-25 10:50:06 +0000414
Peter Collingbournecfd23562011-09-26 01:57:12 +0000415 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
416
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000417 Out << " ";
418 MD->printQualifiedName(Out);
419 Out << " - (";
420 Overrider.Method->printQualifiedName(Out);
Timur Iskhodzhanovbe5a3d82013-06-05 06:40:07 +0000421 Out << ", " << Overrider.Offset.getQuantity() << ')';
Peter Collingbournecfd23562011-09-26 01:57:12 +0000422
423 BaseOffset Offset;
424 if (!Overrider.Method->isPure())
425 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
426
427 if (!Offset.isEmpty()) {
428 Out << " [ret-adj: ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000429 if (Offset.VirtualBase) {
430 Offset.VirtualBase->printQualifiedName(Out);
431 Out << " vbase, ";
432 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000433
Peter Collingbournecfd23562011-09-26 01:57:12 +0000434 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
435 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000436
Peter Collingbournecfd23562011-09-26 01:57:12 +0000437 Out << "\n";
Fangrui Song6907ce22018-07-30 19:24:48 +0000438 }
Peter Collingbournecfd23562011-09-26 01:57:12 +0000439}
440
441/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
442struct VCallOffsetMap {
Fangrui Song6907ce22018-07-30 19:24:48 +0000443
Peter Collingbournecfd23562011-09-26 01:57:12 +0000444 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000445
Peter Collingbournecfd23562011-09-26 01:57:12 +0000446 /// Offsets - Keeps track of methods and their offsets.
447 // FIXME: This should be a real map and not a vector.
448 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
449
450 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
451 /// can share the same vcall offset.
452 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
453 const CXXMethodDecl *RHS);
454
455public:
456 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
457 /// add was successful, or false if there was already a member function with
458 /// the same signature in the map.
459 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000460
Peter Collingbournecfd23562011-09-26 01:57:12 +0000461 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
462 /// vtable address point) for the given virtual member function.
463 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
Fangrui Song6907ce22018-07-30 19:24:48 +0000464
Peter Collingbournecfd23562011-09-26 01:57:12 +0000465 // empty - Return whether the offset map is empty or not.
466 bool empty() const { return Offsets.empty(); }
467};
468
469static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
470 const CXXMethodDecl *RHS) {
John McCallb6c4a7e2012-03-21 06:57:19 +0000471 const FunctionProtoType *LT =
472 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
473 const FunctionProtoType *RT =
474 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000475
476 // Fast-path matches in the canonical types.
477 if (LT == RT) return true;
478
479 // Force the signatures to match. We can't rely on the overrides
480 // list here because there isn't necessarily an inheritance
481 // relationship between the two methods.
Anastasia Stulovac61eaa52019-01-28 11:37:49 +0000482 if (LT->getMethodQuals() != RT->getMethodQuals())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000483 return false;
Benjamin Kramera37e7652015-07-25 17:10:49 +0000484 return LT->getParamTypes() == RT->getParamTypes();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000485}
486
487bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
488 const CXXMethodDecl *RHS) {
489 assert(LHS->isVirtual() && "LHS must be virtual!");
490 assert(RHS->isVirtual() && "LHS must be virtual!");
Fangrui Song6907ce22018-07-30 19:24:48 +0000491
Peter Collingbournecfd23562011-09-26 01:57:12 +0000492 // A destructor can share a vcall offset with another destructor.
493 if (isa<CXXDestructorDecl>(LHS))
494 return isa<CXXDestructorDecl>(RHS);
495
496 // FIXME: We need to check more things here.
Fangrui Song6907ce22018-07-30 19:24:48 +0000497
Peter Collingbournecfd23562011-09-26 01:57:12 +0000498 // The methods must have the same name.
499 DeclarationName LHSName = LHS->getDeclName();
500 DeclarationName RHSName = RHS->getDeclName();
501 if (LHSName != RHSName)
502 return false;
503
504 // And the same signatures.
505 return HasSameVirtualSignature(LHS, RHS);
506}
507
Fangrui Song6907ce22018-07-30 19:24:48 +0000508bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000509 CharUnits OffsetOffset) {
510 // Check if we can reuse an offset.
Benjamin Kramera37e7652015-07-25 17:10:49 +0000511 for (const auto &OffsetPair : Offsets) {
512 if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000513 return false;
514 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000515
Peter Collingbournecfd23562011-09-26 01:57:12 +0000516 // Add the offset.
517 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
518 return true;
519}
520
521CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
522 // Look for an offset.
Benjamin Kramera37e7652015-07-25 17:10:49 +0000523 for (const auto &OffsetPair : Offsets) {
524 if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
525 return OffsetPair.second;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000526 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000527
Peter Collingbournecfd23562011-09-26 01:57:12 +0000528 llvm_unreachable("Should always find a vcall offset offset!");
529}
530
531/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
532class VCallAndVBaseOffsetBuilder {
533public:
Fangrui Song6907ce22018-07-30 19:24:48 +0000534 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
Peter Collingbournecfd23562011-09-26 01:57:12 +0000535 VBaseOffsetOffsetsMapTy;
536
537private:
Leonard Chan71568a92020-06-11 11:17:08 -0700538 const ItaniumVTableContext &VTables;
539
Peter Collingbournecfd23562011-09-26 01:57:12 +0000540 /// MostDerivedClass - The most derived class for which we're building vcall
541 /// and vbase offsets.
542 const CXXRecordDecl *MostDerivedClass;
Fangrui Song6907ce22018-07-30 19:24:48 +0000543
544 /// LayoutClass - The class we're using for layout information. Will be
Peter Collingbournecfd23562011-09-26 01:57:12 +0000545 /// different than the most derived class if we're building a construction
546 /// vtable.
547 const CXXRecordDecl *LayoutClass;
Fangrui Song6907ce22018-07-30 19:24:48 +0000548
Peter Collingbournecfd23562011-09-26 01:57:12 +0000549 /// Context - The ASTContext which we will use for layout information.
550 ASTContext &Context;
551
552 /// Components - vcall and vbase offset components
553 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
554 VTableComponentVectorTy Components;
Fangrui Song6907ce22018-07-30 19:24:48 +0000555
Peter Collingbournecfd23562011-09-26 01:57:12 +0000556 /// VisitedVirtualBases - Visited virtual bases.
557 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Fangrui Song6907ce22018-07-30 19:24:48 +0000558
Peter Collingbournecfd23562011-09-26 01:57:12 +0000559 /// VCallOffsets - Keeps track of vcall offsets.
560 VCallOffsetMap VCallOffsets;
561
562
563 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
564 /// relative to the address point.
565 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
Fangrui Song6907ce22018-07-30 19:24:48 +0000566
Peter Collingbournecfd23562011-09-26 01:57:12 +0000567 /// FinalOverriders - The final overriders of the most derived class.
568 /// (Can be null when we're not building a vtable of the most derived class).
569 const FinalOverriders *Overriders;
570
571 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
572 /// given base subobject.
573 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
574 CharUnits RealBaseOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000575
Peter Collingbournecfd23562011-09-26 01:57:12 +0000576 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
577 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000578
Peter Collingbournecfd23562011-09-26 01:57:12 +0000579 /// AddVBaseOffsets - Add vbase offsets for the given class.
Fangrui Song6907ce22018-07-30 19:24:48 +0000580 void AddVBaseOffsets(const CXXRecordDecl *Base,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000581 CharUnits OffsetInLayoutClass);
Fangrui Song6907ce22018-07-30 19:24:48 +0000582
Peter Collingbournecfd23562011-09-26 01:57:12 +0000583 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
584 /// chars, relative to the vtable address point.
585 CharUnits getCurrentOffsetOffset() const;
Fangrui Song6907ce22018-07-30 19:24:48 +0000586
Peter Collingbournecfd23562011-09-26 01:57:12 +0000587public:
Leonard Chan71568a92020-06-11 11:17:08 -0700588 VCallAndVBaseOffsetBuilder(const ItaniumVTableContext &VTables,
589 const CXXRecordDecl *MostDerivedClass,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000590 const CXXRecordDecl *LayoutClass,
591 const FinalOverriders *Overriders,
592 BaseSubobject Base, bool BaseIsVirtual,
593 CharUnits OffsetInLayoutClass)
Leonard Chan71568a92020-06-11 11:17:08 -0700594 : VTables(VTables), MostDerivedClass(MostDerivedClass),
595 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
596 Overriders(Overriders) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000597
Peter Collingbournecfd23562011-09-26 01:57:12 +0000598 // Add vcall and vbase offsets.
599 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
600 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000601
Peter Collingbournecfd23562011-09-26 01:57:12 +0000602 /// Methods for iterating over the components.
603 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
604 const_iterator components_begin() const { return Components.rbegin(); }
605 const_iterator components_end() const { return Components.rend(); }
Fangrui Song6907ce22018-07-30 19:24:48 +0000606
Peter Collingbournecfd23562011-09-26 01:57:12 +0000607 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
608 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
609 return VBaseOffsetOffsets;
610 }
611};
Fangrui Song6907ce22018-07-30 19:24:48 +0000612
613void
Peter Collingbournecfd23562011-09-26 01:57:12 +0000614VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
615 bool BaseIsVirtual,
616 CharUnits RealBaseOffset) {
617 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
Fangrui Song6907ce22018-07-30 19:24:48 +0000618
Peter Collingbournecfd23562011-09-26 01:57:12 +0000619 // Itanium C++ ABI 2.5.2:
620 // ..in classes sharing a virtual table with a primary base class, the vcall
621 // and vbase offsets added by the derived class all come before the vcall
622 // and vbase offsets required by the base class, so that the latter may be
623 // laid out as required by the base class without regard to additions from
624 // the derived class(es).
625
626 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
627 // emit them for the primary base first).
628 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
629 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
630
631 CharUnits PrimaryBaseOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +0000632
Peter Collingbournecfd23562011-09-26 01:57:12 +0000633 // Get the base offset of the primary base.
634 if (PrimaryBaseIsVirtual) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000635 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000636 "Primary vbase should have a zero offset!");
Fangrui Song6907ce22018-07-30 19:24:48 +0000637
Peter Collingbournecfd23562011-09-26 01:57:12 +0000638 const ASTRecordLayout &MostDerivedClassLayout =
639 Context.getASTRecordLayout(MostDerivedClass);
Fangrui Song6907ce22018-07-30 19:24:48 +0000640
641 PrimaryBaseOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000642 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
643 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000644 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000645 "Primary base should have a zero offset!");
646
647 PrimaryBaseOffset = Base.getBaseOffset();
648 }
649
650 AddVCallAndVBaseOffsets(
651 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
652 PrimaryBaseIsVirtual, RealBaseOffset);
653 }
654
655 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
656
657 // We only want to add vcall offsets for virtual bases.
658 if (BaseIsVirtual)
659 AddVCallOffsets(Base, RealBaseOffset);
660}
661
662CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
Fangrui Song6907ce22018-07-30 19:24:48 +0000663 // OffsetIndex is the index of this vcall or vbase offset, relative to the
Peter Collingbournecfd23562011-09-26 01:57:12 +0000664 // vtable address point. (We subtract 3 to account for the information just
665 // above the address point, the RTTI info, the offset to top, and the
666 // vcall offset itself).
667 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000668
Leonard Chan71568a92020-06-11 11:17:08 -0700669 // Under the relative ABI, the offset widths are 32-bit ints instead of
670 // pointer widths.
671 CharUnits OffsetWidth = Context.toCharUnitsFromBits(
672 VTables.isRelativeLayout() ? 32
673 : Context.getTargetInfo().getPointerWidth(0));
674 CharUnits OffsetOffset = OffsetWidth * OffsetIndex;
675
Peter Collingbournecfd23562011-09-26 01:57:12 +0000676 return OffsetOffset;
677}
678
Fangrui Song6907ce22018-07-30 19:24:48 +0000679void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000680 CharUnits VBaseOffset) {
681 const CXXRecordDecl *RD = Base.getBase();
682 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
683
684 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
685
686 // Handle the primary base first.
687 // We only want to add vcall offsets if the base is non-virtual; a virtual
688 // primary base will have its vcall and vbase offsets emitted already.
689 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
690 // Get the base offset of the primary base.
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000691 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000692 "Primary base should have a zero offset!");
693
694 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
695 VBaseOffset);
696 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000697
Peter Collingbournecfd23562011-09-26 01:57:12 +0000698 // Add the vcall offsets.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000699 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000700 if (!MD->isVirtual())
701 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +0000702 MD = MD->getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000703
704 CharUnits OffsetOffset = getCurrentOffsetOffset();
Fangrui Song6907ce22018-07-30 19:24:48 +0000705
Peter Collingbournecfd23562011-09-26 01:57:12 +0000706 // Don't add a vcall offset if we already have one for this member function
707 // signature.
708 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
709 continue;
710
711 CharUnits Offset = CharUnits::Zero();
712
713 if (Overriders) {
714 // Get the final overrider.
Fangrui Song6907ce22018-07-30 19:24:48 +0000715 FinalOverriders::OverriderInfo Overrider =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000716 Overriders->getOverrider(MD, Base.getBaseOffset());
Fangrui Song6907ce22018-07-30 19:24:48 +0000717
718 /// The vcall offset is the offset from the virtual base to the object
Peter Collingbournecfd23562011-09-26 01:57:12 +0000719 /// where the function was overridden.
720 Offset = Overrider.Offset - VBaseOffset;
721 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000722
Peter Collingbournecfd23562011-09-26 01:57:12 +0000723 Components.push_back(
724 VTableComponent::MakeVCallOffset(Offset));
725 }
726
727 // And iterate over all non-virtual bases (ignoring the primary base).
Fangrui Song6907ce22018-07-30 19:24:48 +0000728 for (const auto &B : RD->bases()) {
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000729 if (B.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000730 continue;
731
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000732 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000733 if (BaseDecl == PrimaryBase)
734 continue;
735
736 // Get the base offset of this base.
Fangrui Song6907ce22018-07-30 19:24:48 +0000737 CharUnits BaseOffset = Base.getBaseOffset() +
Peter Collingbournecfd23562011-09-26 01:57:12 +0000738 Layout.getBaseClassOffset(BaseDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +0000739
740 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000741 VBaseOffset);
742 }
743}
744
Fangrui Song6907ce22018-07-30 19:24:48 +0000745void
Peter Collingbournecfd23562011-09-26 01:57:12 +0000746VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
747 CharUnits OffsetInLayoutClass) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000748 const ASTRecordLayout &LayoutClassLayout =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000749 Context.getASTRecordLayout(LayoutClass);
750
751 // Add vbase offsets.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000752 for (const auto &B : RD->bases()) {
753 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000754
755 // Check if this is a virtual base that we haven't visited before.
David Blaikie82e95a32014-11-19 07:49:47 +0000756 if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000757 CharUnits Offset =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000758 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
759
760 // Add the vbase offset offset.
761 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
762 "vbase offset offset already exists!");
763
764 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
765 VBaseOffsetOffsets.insert(
766 std::make_pair(BaseDecl, VBaseOffsetOffset));
767
768 Components.push_back(
769 VTableComponent::MakeVBaseOffset(Offset));
770 }
771
772 // Check the base class looking for more vbase offsets.
773 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
774 }
775}
776
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000777/// ItaniumVTableBuilder - Class for building vtable layout information.
778class ItaniumVTableBuilder {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000779public:
Fangrui Song6907ce22018-07-30 19:24:48 +0000780 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
Peter Collingbournecfd23562011-09-26 01:57:12 +0000781 /// primary bases.
Fangrui Song6907ce22018-07-30 19:24:48 +0000782 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
Peter Collingbournecfd23562011-09-26 01:57:12 +0000783 PrimaryBasesSetVectorTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000784
785 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
Peter Collingbournecfd23562011-09-26 01:57:12 +0000786 VBaseOffsetOffsetsMapTy;
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000787
788 typedef VTableLayout::AddressPointsMapTy AddressPointsMapTy;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000789
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000790 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
791
Peter Collingbournecfd23562011-09-26 01:57:12 +0000792private:
793 /// VTables - Global vtable information.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000794 ItaniumVTableContext &VTables;
Fangrui Song6907ce22018-07-30 19:24:48 +0000795
Peter Collingbournecfd23562011-09-26 01:57:12 +0000796 /// MostDerivedClass - The most derived class for which we're building this
797 /// vtable.
798 const CXXRecordDecl *MostDerivedClass;
799
800 /// MostDerivedClassOffset - If we're building a construction vtable, this
801 /// holds the offset from the layout class to the most derived class.
802 const CharUnits MostDerivedClassOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +0000803
804 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
Peter Collingbournecfd23562011-09-26 01:57:12 +0000805 /// base. (This only makes sense when building a construction vtable).
806 bool MostDerivedClassIsVirtual;
Fangrui Song6907ce22018-07-30 19:24:48 +0000807
808 /// LayoutClass - The class we're using for layout information. Will be
Peter Collingbournecfd23562011-09-26 01:57:12 +0000809 /// different than the most derived class if we're building a construction
810 /// vtable.
811 const CXXRecordDecl *LayoutClass;
Fangrui Song6907ce22018-07-30 19:24:48 +0000812
Peter Collingbournecfd23562011-09-26 01:57:12 +0000813 /// Context - The ASTContext which we will use for layout information.
814 ASTContext &Context;
Fangrui Song6907ce22018-07-30 19:24:48 +0000815
Peter Collingbournecfd23562011-09-26 01:57:12 +0000816 /// FinalOverriders - The final overriders of the most derived class.
817 const FinalOverriders Overriders;
818
819 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
820 /// bases in this vtable.
821 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
822
823 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
824 /// the most derived class.
825 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000826
Peter Collingbournecfd23562011-09-26 01:57:12 +0000827 /// Components - The components of the vtable being built.
828 SmallVector<VTableComponent, 64> Components;
829
830 /// AddressPoints - Address points for the vtable being built.
831 AddressPointsMapTy AddressPoints;
832
833 /// MethodInfo - Contains information about a method in a vtable.
834 /// (Used for computing 'this' pointer adjustment thunks.
835 struct MethodInfo {
836 /// BaseOffset - The base offset of this method.
837 const CharUnits BaseOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +0000838
Peter Collingbournecfd23562011-09-26 01:57:12 +0000839 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
840 /// method.
841 const CharUnits BaseOffsetInLayoutClass;
Fangrui Song6907ce22018-07-30 19:24:48 +0000842
Peter Collingbournecfd23562011-09-26 01:57:12 +0000843 /// VTableIndex - The index in the vtable that this method has.
844 /// (For destructors, this is the index of the complete destructor).
845 const uint64_t VTableIndex;
Fangrui Song6907ce22018-07-30 19:24:48 +0000846
847 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000848 uint64_t VTableIndex)
Fangrui Song6907ce22018-07-30 19:24:48 +0000849 : BaseOffset(BaseOffset),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000850 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
851 VTableIndex(VTableIndex) { }
Fangrui Song6907ce22018-07-30 19:24:48 +0000852
853 MethodInfo()
854 : BaseOffset(CharUnits::Zero()),
855 BaseOffsetInLayoutClass(CharUnits::Zero()),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000856 VTableIndex(0) { }
Serge Gueltonbe885392019-01-20 21:19:56 +0000857
858 MethodInfo(MethodInfo const&) = default;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000859 };
Fangrui Song6907ce22018-07-30 19:24:48 +0000860
Peter Collingbournecfd23562011-09-26 01:57:12 +0000861 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000862
Peter Collingbournecfd23562011-09-26 01:57:12 +0000863 /// MethodInfoMap - The information for all methods in the vtable we're
864 /// currently building.
865 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000866
867 /// MethodVTableIndices - Contains the index (relative to the vtable address
868 /// point) where the function pointer for a virtual function is stored.
869 MethodVTableIndicesTy MethodVTableIndices;
870
Peter Collingbournecfd23562011-09-26 01:57:12 +0000871 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000872
873 /// VTableThunks - The thunks by vtable index in the vtable currently being
Peter Collingbournecfd23562011-09-26 01:57:12 +0000874 /// built.
875 VTableThunksMapTy VTableThunks;
876
877 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
878 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000879
Peter Collingbournecfd23562011-09-26 01:57:12 +0000880 /// Thunks - A map that contains all the thunks needed for all methods in the
881 /// most derived class for which the vtable is currently being built.
882 ThunksMapTy Thunks;
Fangrui Song6907ce22018-07-30 19:24:48 +0000883
Peter Collingbournecfd23562011-09-26 01:57:12 +0000884 /// AddThunk - Add a thunk for the given method.
885 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
Fangrui Song6907ce22018-07-30 19:24:48 +0000886
Peter Collingbournecfd23562011-09-26 01:57:12 +0000887 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
888 /// part of the vtable we're currently building.
889 void ComputeThisAdjustments();
Fangrui Song6907ce22018-07-30 19:24:48 +0000890
Peter Collingbournecfd23562011-09-26 01:57:12 +0000891 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
892
893 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
894 /// some other base.
895 VisitedVirtualBasesSetTy PrimaryVirtualBases;
896
897 /// ComputeReturnAdjustment - Compute the return adjustment given a return
898 /// adjustment base offset.
899 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000900
Peter Collingbournecfd23562011-09-26 01:57:12 +0000901 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
902 /// the 'this' pointer from the base subobject to the derived subobject.
903 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
904 BaseSubobject Derived) const;
905
906 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
907 /// given virtual member function, its offset in the layout class and its
908 /// final overrider.
Fangrui Song6907ce22018-07-30 19:24:48 +0000909 ThisAdjustment
910 ComputeThisAdjustment(const CXXMethodDecl *MD,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000911 CharUnits BaseOffsetInLayoutClass,
912 FinalOverriders::OverriderInfo Overrider);
913
914 /// AddMethod - Add a single virtual member function to the vtable
915 /// components vector.
916 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
917
918 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
Fangrui Song6907ce22018-07-30 19:24:48 +0000919 /// part of the vtable.
Peter Collingbournecfd23562011-09-26 01:57:12 +0000920 ///
921 /// Itanium C++ ABI 2.5.2:
922 ///
923 /// struct A { virtual void f(); };
924 /// struct B : virtual public A { int i; };
925 /// struct C : virtual public A { int j; };
926 /// struct D : public B, public C {};
927 ///
928 /// When B and C are declared, A is a primary base in each case, so although
929 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
930 /// adjustment is required and no thunk is generated. However, inside D
931 /// objects, A is no longer a primary base of C, so if we allowed calls to
932 /// C::f() to use the copy of A's vtable in the C subobject, we would need
Fangrui Song6907ce22018-07-30 19:24:48 +0000933 /// to adjust this from C* to B::A*, which would require a third-party
934 /// thunk. Since we require that a call to C::f() first convert to A*,
935 /// C-in-D's copy of A's vtable is never referenced, so this is not
Peter Collingbournecfd23562011-09-26 01:57:12 +0000936 /// necessary.
937 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
938 CharUnits BaseOffsetInLayoutClass,
939 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
940 CharUnits FirstBaseOffsetInLayoutClass) const;
941
Fangrui Song6907ce22018-07-30 19:24:48 +0000942
Peter Collingbournecfd23562011-09-26 01:57:12 +0000943 /// AddMethods - Add the methods of this base subobject and all its
944 /// primary bases to the vtable components vector.
945 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
946 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
947 CharUnits FirstBaseOffsetInLayoutClass,
948 PrimaryBasesSetVectorTy &PrimaryBases);
949
950 // LayoutVTable - Layout the vtable for the given base class, including its
951 // secondary vtables and any vtables for virtual bases.
952 void LayoutVTable();
953
954 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
955 /// given base subobject, as well as all its secondary vtables.
956 ///
957 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
958 /// or a direct or indirect base of a virtual base.
959 ///
960 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
Fangrui Song6907ce22018-07-30 19:24:48 +0000961 /// in the layout class.
Peter Collingbournecfd23562011-09-26 01:57:12 +0000962 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
963 bool BaseIsMorallyVirtual,
964 bool BaseIsVirtualInLayoutClass,
965 CharUnits OffsetInLayoutClass);
Fangrui Song6907ce22018-07-30 19:24:48 +0000966
Peter Collingbournecfd23562011-09-26 01:57:12 +0000967 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
968 /// subobject.
969 ///
970 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
971 /// or a direct or indirect base of a virtual base.
972 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
973 CharUnits OffsetInLayoutClass);
974
975 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
976 /// class hierarchy.
Fangrui Song6907ce22018-07-30 19:24:48 +0000977 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000978 CharUnits OffsetInLayoutClass,
979 VisitedVirtualBasesSetTy &VBases);
980
981 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
982 /// given base (excluding any primary bases).
Fangrui Song6907ce22018-07-30 19:24:48 +0000983 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000984 VisitedVirtualBasesSetTy &VBases);
985
986 /// isBuildingConstructionVTable - Return whether this vtable builder is
987 /// building a construction vtable.
Fangrui Song6907ce22018-07-30 19:24:48 +0000988 bool isBuildingConstructorVTable() const {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000989 return MostDerivedClass != LayoutClass;
990 }
991
992public:
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000993 /// Component indices of the first component of each of the vtables in the
994 /// vtable group.
995 SmallVector<size_t, 4> VTableIndices;
996
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000997 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
998 const CXXRecordDecl *MostDerivedClass,
999 CharUnits MostDerivedClassOffset,
1000 bool MostDerivedClassIsVirtual,
1001 const CXXRecordDecl *LayoutClass)
1002 : VTables(VTables), MostDerivedClass(MostDerivedClass),
1003 MostDerivedClassOffset(MostDerivedClassOffset),
1004 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
1005 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
1006 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00001007 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
Peter Collingbournecfd23562011-09-26 01:57:12 +00001008
1009 LayoutVTable();
1010
David Blaikiebbafb8a2012-03-11 07:00:24 +00001011 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00001012 dumpLayout(llvm::outs());
Peter Collingbournecfd23562011-09-26 01:57:12 +00001013 }
1014
1015 uint64_t getNumThunks() const {
1016 return Thunks.size();
1017 }
1018
1019 ThunksMapTy::const_iterator thunks_begin() const {
1020 return Thunks.begin();
1021 }
1022
1023 ThunksMapTy::const_iterator thunks_end() const {
1024 return Thunks.end();
1025 }
1026
1027 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1028 return VBaseOffsetOffsets;
1029 }
1030
1031 const AddressPointsMapTy &getAddressPoints() const {
1032 return AddressPoints;
1033 }
1034
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001035 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1036 return MethodVTableIndices.begin();
1037 }
1038
1039 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1040 return MethodVTableIndices.end();
1041 }
1042
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001043 ArrayRef<VTableComponent> vtable_components() const { return Components; }
Peter Collingbournecfd23562011-09-26 01:57:12 +00001044
Peter Collingbournecfd23562011-09-26 01:57:12 +00001045 AddressPointsMapTy::const_iterator address_points_begin() const {
1046 return AddressPoints.begin();
1047 }
1048
1049 AddressPointsMapTy::const_iterator address_points_end() const {
1050 return AddressPoints.end();
1051 }
1052
1053 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1054 return VTableThunks.begin();
1055 }
1056
1057 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1058 return VTableThunks.end();
1059 }
1060
1061 /// dumpLayout - Dump the vtable layout.
1062 void dumpLayout(raw_ostream&);
1063};
1064
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001065void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1066 const ThunkInfo &Thunk) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001067 assert(!isBuildingConstructorVTable() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001068 "Can't add thunks for construction vtable");
1069
Craig Topper5603df42013-07-05 19:34:19 +00001070 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1071
Peter Collingbournecfd23562011-09-26 01:57:12 +00001072 // Check if we have this thunk already.
Fangrui Song75e74e02019-03-31 08:48:19 +00001073 if (llvm::find(ThunksVector, Thunk) != ThunksVector.end())
Peter Collingbournecfd23562011-09-26 01:57:12 +00001074 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001075
Peter Collingbournecfd23562011-09-26 01:57:12 +00001076 ThunksVector.push_back(Thunk);
1077}
1078
1079typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1080
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001081/// Visit all the methods overridden by the given method recursively,
1082/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1083/// indicating whether to continue the recursion for the given overridden
1084/// method (i.e. returning false stops the iteration).
1085template <class VisitorTy>
1086static void
1087visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001088 assert(MD->isVirtual() && "Method is not virtual!");
1089
Benjamin Krameracfa3392017-12-17 23:52:45 +00001090 for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00001091 if (!Visitor(OverriddenMD))
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001092 continue;
1093 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001094 }
1095}
1096
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001097/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1098/// the overridden methods that the function decl overrides.
1099static void
1100ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1101 OverriddenMethodsSetTy& OverriddenMethods) {
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00001102 auto OverriddenMethodsCollector = [&](const CXXMethodDecl *MD) {
1103 // Don't recurse on this method if we've already collected it.
1104 return OverriddenMethods.insert(MD).second;
1105 };
1106 visitAllOverriddenMethods(MD, OverriddenMethodsCollector);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001107}
1108
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001109void ItaniumVTableBuilder::ComputeThisAdjustments() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001110 // Now go through the method info map and see if any of the methods need
1111 // 'this' pointer adjustments.
Benjamin Kramera37e7652015-07-25 17:10:49 +00001112 for (const auto &MI : MethodInfoMap) {
1113 const CXXMethodDecl *MD = MI.first;
1114 const MethodInfo &MethodInfo = MI.second;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001115
1116 // Ignore adjustments for unused function pointers.
1117 uint64_t VTableIndex = MethodInfo.VTableIndex;
Fangrui Song6907ce22018-07-30 19:24:48 +00001118 if (Components[VTableIndex].getKind() ==
Peter Collingbournecfd23562011-09-26 01:57:12 +00001119 VTableComponent::CK_UnusedFunctionPointer)
1120 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001121
Peter Collingbournecfd23562011-09-26 01:57:12 +00001122 // Get the final overrider for this method.
1123 FinalOverriders::OverriderInfo Overrider =
1124 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +00001125
Peter Collingbournecfd23562011-09-26 01:57:12 +00001126 // Check if we need an adjustment at all.
1127 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1128 // When a return thunk is needed by a derived class that overrides a
Fangrui Song6907ce22018-07-30 19:24:48 +00001129 // virtual base, gcc uses a virtual 'this' adjustment as well.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001130 // While the thunk itself might be needed by vtables in subclasses or
1131 // in construction vtables, there doesn't seem to be a reason for using
1132 // the thunk in this vtable. Still, we do so to match gcc.
1133 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1134 continue;
1135 }
1136
1137 ThisAdjustment ThisAdjustment =
1138 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1139
1140 if (ThisAdjustment.isEmpty())
1141 continue;
1142
1143 // Add it.
1144 VTableThunks[VTableIndex].This = ThisAdjustment;
1145
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001146 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001147 // Add an adjustment for the deleting destructor as well.
1148 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1149 }
1150 }
1151
1152 /// Clear the method info map.
1153 MethodInfoMap.clear();
Fangrui Song6907ce22018-07-30 19:24:48 +00001154
Peter Collingbournecfd23562011-09-26 01:57:12 +00001155 if (isBuildingConstructorVTable()) {
1156 // We don't need to store thunk information for construction vtables.
1157 return;
1158 }
1159
Benjamin Kramera37e7652015-07-25 17:10:49 +00001160 for (const auto &TI : VTableThunks) {
1161 const VTableComponent &Component = Components[TI.first];
1162 const ThunkInfo &Thunk = TI.second;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001163 const CXXMethodDecl *MD;
Fangrui Song6907ce22018-07-30 19:24:48 +00001164
Peter Collingbournecfd23562011-09-26 01:57:12 +00001165 switch (Component.getKind()) {
1166 default:
1167 llvm_unreachable("Unexpected vtable component kind!");
1168 case VTableComponent::CK_FunctionPointer:
1169 MD = Component.getFunctionDecl();
1170 break;
1171 case VTableComponent::CK_CompleteDtorPointer:
1172 MD = Component.getDestructorDecl();
1173 break;
1174 case VTableComponent::CK_DeletingDtorPointer:
1175 // We've already added the thunk when we saw the complete dtor pointer.
1176 continue;
1177 }
1178
1179 if (MD->getParent() == MostDerivedClass)
1180 AddThunk(MD, Thunk);
1181 }
1182}
1183
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001184ReturnAdjustment
1185ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001186 ReturnAdjustment Adjustment;
Fangrui Song6907ce22018-07-30 19:24:48 +00001187
Peter Collingbournecfd23562011-09-26 01:57:12 +00001188 if (!Offset.isEmpty()) {
1189 if (Offset.VirtualBase) {
1190 // Get the virtual base offset offset.
1191 if (Offset.DerivedClass == MostDerivedClass) {
1192 // We can get the offset offset directly from our map.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001193 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001194 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1195 } else {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001196 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001197 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1198 Offset.VirtualBase).getQuantity();
1199 }
1200 }
1201
1202 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1203 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001204
Peter Collingbournecfd23562011-09-26 01:57:12 +00001205 return Adjustment;
1206}
1207
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001208BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1209 BaseSubobject Base, BaseSubobject Derived) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001210 const CXXRecordDecl *BaseRD = Base.getBase();
1211 const CXXRecordDecl *DerivedRD = Derived.getBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00001212
Peter Collingbournecfd23562011-09-26 01:57:12 +00001213 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1214 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1215
Benjamin Kramer325d7452013-02-03 18:55:34 +00001216 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +00001217 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +00001218
1219 // We have to go through all the paths, and see which one leads us to the
1220 // right base subobject.
Benjamin Kramera37e7652015-07-25 17:10:49 +00001221 for (const CXXBasePath &Path : Paths) {
1222 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, Path);
1223
Peter Collingbournecfd23562011-09-26 01:57:12 +00001224 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +00001225
Peter Collingbournecfd23562011-09-26 01:57:12 +00001226 if (Offset.VirtualBase) {
1227 // If we have a virtual base class, the non-virtual offset is relative
1228 // to the virtual base class offset.
1229 const ASTRecordLayout &LayoutClassLayout =
1230 Context.getASTRecordLayout(LayoutClass);
Fangrui Song6907ce22018-07-30 19:24:48 +00001231
1232 /// Get the virtual base offset, relative to the most derived class
Peter Collingbournecfd23562011-09-26 01:57:12 +00001233 /// layout.
Fangrui Song6907ce22018-07-30 19:24:48 +00001234 OffsetToBaseSubobject +=
Peter Collingbournecfd23562011-09-26 01:57:12 +00001235 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1236 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +00001237 // Otherwise, the non-virtual offset is relative to the derived class
Peter Collingbournecfd23562011-09-26 01:57:12 +00001238 // offset.
1239 OffsetToBaseSubobject += Derived.getBaseOffset();
1240 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001241
Peter Collingbournecfd23562011-09-26 01:57:12 +00001242 // Check if this path gives us the right base subobject.
1243 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1244 // Since we're going from the base class _to_ the derived class, we'll
1245 // invert the non-virtual offset here.
1246 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1247 return Offset;
Fangrui Song6907ce22018-07-30 19:24:48 +00001248 }
Peter Collingbournecfd23562011-09-26 01:57:12 +00001249 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001250
Peter Collingbournecfd23562011-09-26 01:57:12 +00001251 return BaseOffset();
1252}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001253
1254ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1255 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1256 FinalOverriders::OverriderInfo Overrider) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001257 // Ignore adjustments for pure virtual member functions.
1258 if (Overrider.Method->isPure())
1259 return ThisAdjustment();
Fangrui Song6907ce22018-07-30 19:24:48 +00001260
1261 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
Peter Collingbournecfd23562011-09-26 01:57:12 +00001262 BaseOffsetInLayoutClass);
Fangrui Song6907ce22018-07-30 19:24:48 +00001263
Peter Collingbournecfd23562011-09-26 01:57:12 +00001264 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1265 Overrider.Offset);
Fangrui Song6907ce22018-07-30 19:24:48 +00001266
Peter Collingbournecfd23562011-09-26 01:57:12 +00001267 // Compute the adjustment offset.
1268 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1269 OverriderBaseSubobject);
1270 if (Offset.isEmpty())
1271 return ThisAdjustment();
1272
1273 ThisAdjustment Adjustment;
Fangrui Song6907ce22018-07-30 19:24:48 +00001274
Peter Collingbournecfd23562011-09-26 01:57:12 +00001275 if (Offset.VirtualBase) {
1276 // Get the vcall offset map for this virtual base.
1277 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1278
1279 if (VCallOffsets.empty()) {
1280 // We don't have vcall offsets for this virtual base, go ahead and
1281 // build them.
Leonard Chan71568a92020-06-11 11:17:08 -07001282 VCallAndVBaseOffsetBuilder Builder(
1283 VTables, MostDerivedClass, MostDerivedClass,
1284 /*Overriders=*/nullptr,
1285 BaseSubobject(Offset.VirtualBase, CharUnits::Zero()),
1286 /*BaseIsVirtual=*/true,
1287 /*OffsetInLayoutClass=*/
1288 CharUnits::Zero());
Fangrui Song6907ce22018-07-30 19:24:48 +00001289
Peter Collingbournecfd23562011-09-26 01:57:12 +00001290 VCallOffsets = Builder.getVCallOffsets();
1291 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001292
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001293 Adjustment.Virtual.Itanium.VCallOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001294 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1295 }
1296
1297 // Set the non-virtual part of the adjustment.
1298 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
Fangrui Song6907ce22018-07-30 19:24:48 +00001299
Peter Collingbournecfd23562011-09-26 01:57:12 +00001300 return Adjustment;
1301}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001302
1303void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1304 ReturnAdjustment ReturnAdjustment) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001305 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001306 assert(ReturnAdjustment.isEmpty() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001307 "Destructor can't have return adjustment!");
1308
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001309 // Add both the complete destructor and the deleting destructor.
1310 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1311 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbournecfd23562011-09-26 01:57:12 +00001312 } else {
1313 // Add the return adjustment if necessary.
1314 if (!ReturnAdjustment.isEmpty())
1315 VTableThunks[Components.size()].Return = ReturnAdjustment;
1316
1317 // Add the function.
1318 Components.push_back(VTableComponent::MakeFunction(MD));
1319 }
1320}
1321
1322/// OverridesIndirectMethodInBase - Return whether the given member function
Fangrui Song6907ce22018-07-30 19:24:48 +00001323/// overrides any methods in the set of given bases.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001324/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1325/// For example, if we have:
1326///
1327/// struct A { virtual void f(); }
1328/// struct B : A { virtual void f(); }
1329/// struct C : B { virtual void f(); }
1330///
Fangrui Song6907ce22018-07-30 19:24:48 +00001331/// OverridesIndirectMethodInBase will return true if given C::f as the method
Peter Collingbournecfd23562011-09-26 01:57:12 +00001332/// and { A } as the set of bases.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001333static bool OverridesIndirectMethodInBases(
1334 const CXXMethodDecl *MD,
1335 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001336 if (Bases.count(MD->getParent()))
1337 return true;
Benjamin Krameracfa3392017-12-17 23:52:45 +00001338
1339 for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001340 // Check "indirect overriders".
1341 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1342 return true;
1343 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001344
Peter Collingbournecfd23562011-09-26 01:57:12 +00001345 return false;
1346}
1347
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001348bool ItaniumVTableBuilder::IsOverriderUsed(
1349 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1350 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1351 CharUnits FirstBaseOffsetInLayoutClass) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001352 // If the base and the first base in the primary base chain have the same
1353 // offsets, then this overrider will be used.
1354 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1355 return true;
1356
1357 // We know now that Base (or a direct or indirect base of it) is a primary
Fangrui Song6907ce22018-07-30 19:24:48 +00001358 // base in part of the class hierarchy, but not a primary base in the most
Peter Collingbournecfd23562011-09-26 01:57:12 +00001359 // derived class.
Fangrui Song6907ce22018-07-30 19:24:48 +00001360
Peter Collingbournecfd23562011-09-26 01:57:12 +00001361 // If the overrider is the first base in the primary base chain, we know
1362 // that the overrider will be used.
1363 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1364 return true;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001365
1366 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001367
1368 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1369 PrimaryBases.insert(RD);
1370
1371 // Now traverse the base chain, starting with the first base, until we find
1372 // the base that is no longer a primary base.
1373 while (true) {
1374 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1375 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00001376
Peter Collingbournecfd23562011-09-26 01:57:12 +00001377 if (!PrimaryBase)
1378 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001379
Peter Collingbournecfd23562011-09-26 01:57:12 +00001380 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001381 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001382 "Primary base should always be at offset 0!");
1383
1384 const ASTRecordLayout &LayoutClassLayout =
1385 Context.getASTRecordLayout(LayoutClass);
1386
1387 // Now check if this is the primary base that is not a primary base in the
1388 // most derived class.
1389 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1390 FirstBaseOffsetInLayoutClass) {
1391 // We found it, stop walking the chain.
1392 break;
1393 }
1394 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001395 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001396 "Primary base should always be at offset 0!");
1397 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001398
Peter Collingbournecfd23562011-09-26 01:57:12 +00001399 if (!PrimaryBases.insert(PrimaryBase))
1400 llvm_unreachable("Found a duplicate primary base!");
1401
1402 RD = PrimaryBase;
1403 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001404
Peter Collingbournecfd23562011-09-26 01:57:12 +00001405 // If the final overrider is an override of one of the primary bases,
1406 // then we know that it will be used.
1407 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1408}
1409
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001410typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1411
Peter Collingbournecfd23562011-09-26 01:57:12 +00001412/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1413/// from the nearest base. Returns null if no method was found.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001414/// The Bases are expected to be sorted in a base-to-derived order.
1415static const CXXMethodDecl *
Peter Collingbournecfd23562011-09-26 01:57:12 +00001416FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001417 BasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001418 OverriddenMethodsSetTy OverriddenMethods;
1419 ComputeAllOverriddenMethods(MD, OverriddenMethods);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001420
Benjamin Kramera37e7652015-07-25 17:10:49 +00001421 for (const CXXRecordDecl *PrimaryBase :
1422 llvm::make_range(Bases.rbegin(), Bases.rend())) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001423 // Now check the overridden methods.
Benjamin Kramera37e7652015-07-25 17:10:49 +00001424 for (const CXXMethodDecl *OverriddenMD : OverriddenMethods) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001425 // We found our overridden method.
1426 if (OverriddenMD->getParent() == PrimaryBase)
1427 return OverriddenMD;
1428 }
1429 }
Craig Topper36250ad2014-05-12 05:36:57 +00001430
1431 return nullptr;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001432}
Peter Collingbournecfd23562011-09-26 01:57:12 +00001433
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001434void ItaniumVTableBuilder::AddMethods(
1435 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1436 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1437 CharUnits FirstBaseOffsetInLayoutClass,
1438 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001439 // 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
Peter Collingbournecfd23562011-09-26 01:57:12 +00001448 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()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001455 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001456 "Primary vbase should have a zero offset!");
Fangrui Song6907ce22018-07-30 19:24:48 +00001457
Peter Collingbournecfd23562011-09-26 01:57:12 +00001458 const ASTRecordLayout &MostDerivedClassLayout =
1459 Context.getASTRecordLayout(MostDerivedClass);
Fangrui Song6907ce22018-07-30 19:24:48 +00001460
1461 PrimaryBaseOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001462 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
Fangrui Song6907ce22018-07-30 19:24:48 +00001463
Peter Collingbournecfd23562011-09-26 01:57:12 +00001464 const ASTRecordLayout &LayoutClassLayout =
1465 Context.getASTRecordLayout(LayoutClass);
1466
1467 PrimaryBaseOffsetInLayoutClass =
1468 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1469 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001470 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001471 "Primary base should have a zero offset!");
1472
1473 PrimaryBaseOffset = Base.getBaseOffset();
1474 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1475 }
1476
1477 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
Fangrui Song6907ce22018-07-30 19:24:48 +00001478 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001479 FirstBaseOffsetInLayoutClass, PrimaryBases);
Fangrui Song6907ce22018-07-30 19:24:48 +00001480
Peter Collingbournecfd23562011-09-26 01:57:12 +00001481 if (!PrimaryBases.insert(PrimaryBase))
1482 llvm_unreachable("Found a duplicate primary base!");
1483 }
1484
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001485 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1486 NewVirtualFunctionsTy NewVirtualFunctions;
1487
Richard Smith6e73fee2020-01-21 15:52:15 -08001488 llvm::SmallVector<const CXXMethodDecl*, 4> NewImplicitVirtualFunctions;
1489
Peter Collingbournecfd23562011-09-26 01:57:12 +00001490 // Now go through all virtual member functions and add them.
Aaron Ballman2b124d12014-03-13 16:36:16 +00001491 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001492 if (!MD->isVirtual())
1493 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +00001494 MD = MD->getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001495
1496 // Get the final overrider.
Fangrui Song6907ce22018-07-30 19:24:48 +00001497 FinalOverriders::OverriderInfo Overrider =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001498 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.
Fangrui Song6907ce22018-07-30 19:24:48 +00001503 if (const CXXMethodDecl *OverriddenMD =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001504 FindNearestOverriddenMethod(MD, PrimaryBases)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001505 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001506 OverriddenMD).isEmpty()) {
1507 // Replace the method info of the overridden method with our own
1508 // method.
Fangrui Song6907ce22018-07-30 19:24:48 +00001509 assert(MethodInfoMap.count(OverriddenMD) &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001510 "Did not find the overridden method!");
1511 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
Fangrui Song6907ce22018-07-30 19:24:48 +00001512
Peter Collingbournecfd23562011-09-26 01:57:12 +00001513 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1514 OverriddenMethodInfo.VTableIndex);
1515
1516 assert(!MethodInfoMap.count(MD) &&
1517 "Should not have method info for this method yet!");
Fangrui Song6907ce22018-07-30 19:24:48 +00001518
Peter Collingbournecfd23562011-09-26 01:57:12 +00001519 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1520 MethodInfoMap.erase(OverriddenMD);
Fangrui Song6907ce22018-07-30 19:24:48 +00001521
Peter Collingbournecfd23562011-09-26 01:57:12 +00001522 // 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
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001532 if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001533 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);
Fangrui Song6907ce22018-07-30 19:24:48 +00001540 ReturnAdjustment ReturnAdjustment =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001541 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1542
1543 // This is a virtual thunk for the most derived class, add it.
Fangrui Song6907ce22018-07-30 19:24:48 +00001544 AddThunk(Overrider.Method,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001545 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1546 }
1547 }
1548
1549 continue;
1550 }
1551 }
1552
Richard Smith6e73fee2020-01-21 15:52:15 -08001553 if (MD->isImplicit())
1554 NewImplicitVirtualFunctions.push_back(MD);
1555 else
1556 NewVirtualFunctions.push_back(MD);
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001557 }
1558
Richard Smith6e73fee2020-01-21 15:52:15 -08001559 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());
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001577
Benjamin Kramera37e7652015-07-25 17:10:49 +00001578 for (const CXXMethodDecl *MD : NewVirtualFunctions) {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001579 // Get the final overrider.
1580 FinalOverriders::OverriderInfo Overrider =
1581 Overriders.getOverrider(MD, Base.getBaseOffset());
1582
Peter Collingbournecfd23562011-09-26 01:57:12 +00001583 // 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,
Fangrui Song6907ce22018-07-30 19:24:48 +00001594 FirstBaseInPrimaryBaseChain,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001595 FirstBaseOffsetInLayoutClass)) {
1596 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1597 continue;
1598 }
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001599
Peter Collingbournecfd23562011-09-26 01:57:12 +00001600 // 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()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001604 ReturnAdjustmentOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001605 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1606 }
1607
Fangrui Song6907ce22018-07-30 19:24:48 +00001608 ReturnAdjustment ReturnAdjustment =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001609 ComputeReturnAdjustment(ReturnAdjustmentOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +00001610
Peter Collingbournecfd23562011-09-26 01:57:12 +00001611 AddMethod(Overrider.Method, ReturnAdjustment);
1612 }
1613}
1614
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001615void ItaniumVTableBuilder::LayoutVTable() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001616 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1617 CharUnits::Zero()),
1618 /*BaseIsMorallyVirtual=*/false,
1619 MostDerivedClassIsVirtual,
1620 MostDerivedClassOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +00001621
Peter Collingbournecfd23562011-09-26 01:57:12 +00001622 VisitedVirtualBasesSetTy VBases;
Fangrui Song6907ce22018-07-30 19:24:48 +00001623
Peter Collingbournecfd23562011-09-26 01:57:12 +00001624 // Determine the primary virtual bases.
Fangrui Song6907ce22018-07-30 19:24:48 +00001625 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001626 VBases);
1627 VBases.clear();
Fangrui Song6907ce22018-07-30 19:24:48 +00001628
Peter Collingbournecfd23562011-09-26 01:57:12 +00001629 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1630
1631 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001632 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001633 if (IsAppleKext)
1634 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1635}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001636
1637void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1638 BaseSubobject Base, bool BaseIsMorallyVirtual,
1639 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001640 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1641
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001642 unsigned VTableIndex = Components.size();
1643 VTableIndices.push_back(VTableIndex);
1644
Peter Collingbournecfd23562011-09-26 01:57:12 +00001645 // Add vcall and vbase offsets for this vtable.
Leonard Chan71568a92020-06-11 11:17:08 -07001646 VCallAndVBaseOffsetBuilder Builder(
1647 VTables, MostDerivedClass, LayoutClass, &Overriders, Base,
1648 BaseIsVirtualInLayoutClass, OffsetInLayoutClass);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001649 Components.append(Builder.components_begin(), Builder.components_end());
Fangrui Song6907ce22018-07-30 19:24:48 +00001650
Peter Collingbournecfd23562011-09-26 01:57:12 +00001651 // Check if we need to add these vcall offsets.
1652 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1653 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
Fangrui Song6907ce22018-07-30 19:24:48 +00001654
Peter Collingbournecfd23562011-09-26 01:57:12 +00001655 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
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001664 // Add the offset to top.
1665 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1666 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001667
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001668 // Next, add the RTTI.
1669 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001670
Peter Collingbournecfd23562011-09-26 01:57:12 +00001671 uint64_t AddressPoint = Components.size();
1672
1673 // Now go through all virtual member functions and add them.
1674 PrimaryBasesSetVectorTy PrimaryBases;
1675 AddMethods(Base, OffsetInLayoutClass,
Fangrui Song6907ce22018-07-30 19:24:48 +00001676 Base.getBase(), OffsetInLayoutClass,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001677 PrimaryBases);
1678
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001679 const CXXRecordDecl *RD = Base.getBase();
1680 if (RD == MostDerivedClass) {
1681 assert(MethodVTableIndices.empty());
Benjamin Kramera37e7652015-07-25 17:10:49 +00001682 for (const auto &I : MethodInfoMap) {
1683 const CXXMethodDecl *MD = I.first;
1684 const MethodInfo &MI = I.second;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001685 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001686 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1687 = MI.VTableIndex - AddressPoint;
1688 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1689 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001690 } else {
1691 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1692 }
1693 }
1694 }
1695
Peter Collingbournecfd23562011-09-26 01:57:12 +00001696 // Compute 'this' pointer adjustments.
1697 ComputeThisAdjustments();
1698
1699 // Add all address points.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001700 while (true) {
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001701 AddressPoints.insert(
1702 std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
1703 VTableLayout::AddressPointLocation{
1704 unsigned(VTableIndices.size() - 1),
1705 unsigned(AddressPoint - VTableIndex)}));
Peter Collingbournecfd23562011-09-26 01:57:12 +00001706
1707 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1708 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00001709
Peter Collingbournecfd23562011-09-26 01:57:12 +00001710 if (!PrimaryBase)
1711 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001712
Peter Collingbournecfd23562011-09-26 01:57:12 +00001713 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
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001733void
1734ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1735 bool BaseIsMorallyVirtual,
1736 CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001737 // Itanium C++ ABI 2.5.2:
Fangrui Song6907ce22018-07-30 19:24:48 +00001738 // Following the primary virtual table of a derived class are secondary
Peter Collingbournecfd23562011-09-26 01:57:12 +00001739 // 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();
Fangrui Song6907ce22018-07-30 19:24:48 +00001745
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001746 for (const auto &B : RD->bases()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001747 // Ignore virtual bases, we'll emit them later.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001748 if (B.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +00001749 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001750
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001751 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001752
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;
Fangrui Song6907ce22018-07-30 19:24:48 +00001770
1771 CharUnits BaseOffsetInLayoutClass =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001772 OffsetInLayoutClass + RelativeBaseOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +00001773
1774 // Don't emit a secondary vtable for a primary base. We might however want
Peter Collingbournecfd23562011-09-26 01:57:12 +00001775 // 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
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001791void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1792 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1793 VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001794 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Fangrui Song6907ce22018-07-30 19:24:48 +00001795
Peter Collingbournecfd23562011-09-26 01:57:12 +00001796 // 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);
Fangrui Song6907ce22018-07-30 19:24:48 +00001811
1812 // We know that the base is not a primary base in the layout class if
Peter Collingbournecfd23562011-09-26 01:57:12 +00001813 // the base offsets are different.
1814 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1815 IsPrimaryVirtualBase = false;
1816 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001817
Peter Collingbournecfd23562011-09-26 01:57:12 +00001818 if (IsPrimaryVirtualBase)
1819 PrimaryVirtualBases.insert(PrimaryBase);
1820 }
1821 }
1822
1823 // Traverse bases, looking for more primary virtual bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001824 for (const auto &B : RD->bases()) {
1825 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001826
1827 CharUnits BaseOffsetInLayoutClass;
Fangrui Song6907ce22018-07-30 19:24:48 +00001828
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001829 if (B.isVirtual()) {
David Blaikie82e95a32014-11-19 07:49:47 +00001830 if (!VBases.insert(BaseDecl).second)
Peter Collingbournecfd23562011-09-26 01:57:12 +00001831 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001832
Peter Collingbournecfd23562011-09-26 01:57:12 +00001833 const ASTRecordLayout &LayoutClassLayout =
1834 Context.getASTRecordLayout(LayoutClass);
1835
Fangrui Song6907ce22018-07-30 19:24:48 +00001836 BaseOffsetInLayoutClass =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001837 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1838 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +00001839 BaseOffsetInLayoutClass =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001840 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1841 }
1842
1843 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1844 }
1845}
1846
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001847void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1848 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001849 // 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).
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001853 for (const auto &B : RD->bases()) {
1854 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001855
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).
David Blaikie82e95a32014-11-19 07:49:47 +00001858 if (B.isVirtual() && BaseDecl->isDynamicClass() &&
1859 !PrimaryVirtualBases.count(BaseDecl) &&
1860 VBases.insert(BaseDecl).second) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001861 const ASTRecordLayout &MostDerivedClassLayout =
1862 Context.getASTRecordLayout(MostDerivedClass);
Fangrui Song6907ce22018-07-30 19:24:48 +00001863 CharUnits BaseOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001864 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001865
Peter Collingbournecfd23562011-09-26 01:57:12 +00001866 const ASTRecordLayout &LayoutClassLayout =
1867 Context.getASTRecordLayout(LayoutClass);
Fangrui Song6907ce22018-07-30 19:24:48 +00001868 CharUnits BaseOffsetInLayoutClass =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001869 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1870
1871 LayoutPrimaryAndSecondaryVTables(
1872 BaseSubobject(BaseDecl, BaseOffset),
1873 /*BaseIsMorallyVirtual=*/true,
1874 /*BaseIsVirtualInLayoutClass=*/true,
1875 BaseOffsetInLayoutClass);
1876 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001877
Peter Collingbournecfd23562011-09-26 01:57:12 +00001878 // 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.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001886void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00001887 // FIXME: write more tests that actually use the dumpLayout output to prevent
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001888 // ItaniumVTableBuilder regressions.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001889
1890 if (isBuildingConstructorVTable()) {
1891 Out << "Construction vtable for ('";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001892 MostDerivedClass->printQualifiedName(Out);
1893 Out << "', ";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001894 Out << MostDerivedClassOffset.getQuantity() << ") in '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001895 LayoutClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001896 } else {
1897 Out << "Vtable for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001898 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001899 }
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;
Benjamin Kramera37e7652015-07-25 17:10:49 +00001907 for (const auto &AP : AddressPoints) {
1908 const BaseSubobject &Base = AP.first;
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001909 uint64_t Index =
1910 VTableIndices[AP.second.VTableIndex] + AP.second.AddressPointIndex;
Benjamin Kramera37e7652015-07-25 17:10:49 +00001911
Peter Collingbournecfd23562011-09-26 01:57:12 +00001912 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1913 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001914
Peter Collingbournecfd23562011-09-26 01:57:12 +00001915 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 ("
Fangrui Song6907ce22018-07-30 19:24:48 +00001927 << Component.getVCallOffset().getQuantity()
Peter Collingbournecfd23562011-09-26 01:57:12 +00001928 << ")";
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;
Fangrui Song6907ce22018-07-30 19:24:48 +00001942
Peter Collingbournecfd23562011-09-26 01:57:12 +00001943 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001944 Component.getRTTIDecl()->printQualifiedName(Out);
1945 Out << " RTTI";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001946 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001947
Peter Collingbournecfd23562011-09-26 01:57:12 +00001948 case VTableComponent::CK_FunctionPointer: {
1949 const CXXMethodDecl *MD = Component.getFunctionDecl();
1950
Fangrui Song6907ce22018-07-30 19:24:48 +00001951 std::string Str =
1952 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001953 MD);
1954 Out << Str;
1955 if (MD->isPure())
1956 Out << " [pure]";
1957
David Blaikie596d2ca2012-10-16 20:25:33 +00001958 if (MD->isDeleted())
1959 Out << " [deleted]";
1960
Peter Collingbournecfd23562011-09-26 01:57:12 +00001961 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";
Fangrui Song6907ce22018-07-30 19:24:48 +00001967
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001968 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1969 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001970 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";
Fangrui Song6907ce22018-07-30 19:24:48 +00001980
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001981 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
1982 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001983 Out << " vcall offset offset";
1984 }
1985
1986 Out << ']';
Fangrui Song6907ce22018-07-30 19:24:48 +00001987 }
Peter Collingbournecfd23562011-09-26 01:57:12 +00001988 }
1989
1990 break;
1991 }
1992
Fangrui Song6907ce22018-07-30 19:24:48 +00001993 case VTableComponent::CK_CompleteDtorPointer:
Peter Collingbournecfd23562011-09-26 01:57:12 +00001994 case VTableComponent::CK_DeletingDtorPointer: {
Fangrui Song6907ce22018-07-30 19:24:48 +00001995 bool IsComplete =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001996 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
Fangrui Song6907ce22018-07-30 19:24:48 +00001997
Peter Collingbournecfd23562011-09-26 01:57:12 +00001998 const CXXDestructorDecl *DD = Component.getDestructorDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001999
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002000 DD->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002001 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";
Fangrui Song6907ce22018-07-30 19:24:48 +00002015
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002016 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2017 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002018 Out << " vcall offset offset";
2019 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002020
Peter Collingbournecfd23562011-09-26 01:57:12 +00002021 Out << ']';
Fangrui Song6907ce22018-07-30 19:24:48 +00002022 }
2023 }
Peter Collingbournecfd23562011-09-26 01:57:12 +00002024
2025 break;
2026 }
2027
2028 case VTableComponent::CK_UnusedFunctionPointer: {
2029 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2030
Fangrui Song6907ce22018-07-30 19:24:48 +00002031 std::string Str =
2032 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
Peter Collingbournecfd23562011-09-26 01:57:12 +00002033 MD);
2034 Out << "[unused] " << Str;
2035 if (MD->isPure())
2036 Out << " [pure]";
2037 }
2038
2039 }
2040
2041 Out << '\n';
Fangrui Song6907ce22018-07-30 19:24:48 +00002042
Peter Collingbournecfd23562011-09-26 01:57:12 +00002043 // Dump the next address point.
2044 uint64_t NextIndex = Index + 1;
2045 if (AddressPointsByIndex.count(NextIndex)) {
2046 if (AddressPointsByIndex.count(NextIndex) == 1) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002047 const BaseSubobject &Base =
Peter Collingbournecfd23562011-09-26 01:57:12 +00002048 AddressPointsByIndex.find(NextIndex)->second;
Fangrui Song6907ce22018-07-30 19:24:48 +00002049
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002050 Out << " -- (";
2051 Base.getBase()->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002052 Out << ", " << Base.getBaseOffset().getQuantity();
2053 Out << ") vtable address --\n";
2054 } else {
2055 CharUnits BaseOffset =
2056 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
Fangrui Song6907ce22018-07-30 19:24:48 +00002057
Peter Collingbournecfd23562011-09-26 01:57:12 +00002058 // We store the class names in a set to get a stable order.
2059 std::set<std::string> ClassNames;
Benjamin Kramera37e7652015-07-25 17:10:49 +00002060 for (const auto &I :
2061 llvm::make_range(AddressPointsByIndex.equal_range(NextIndex))) {
2062 assert(I.second.getBaseOffset() == BaseOffset &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00002063 "Invalid base offset!");
Benjamin Kramera37e7652015-07-25 17:10:49 +00002064 const CXXRecordDecl *RD = I.second.getBase();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002065 ClassNames.insert(RD->getQualifiedNameAsString());
2066 }
Benjamin Kramera37e7652015-07-25 17:10:49 +00002067
2068 for (const std::string &Name : ClassNames) {
2069 Out << " -- (" << Name;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002070 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2071 }
2072 }
2073 }
2074 }
2075
2076 Out << '\n';
Fangrui Song6907ce22018-07-30 19:24:48 +00002077
Peter Collingbournecfd23562011-09-26 01:57:12 +00002078 if (isBuildingConstructorVTable())
2079 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002080
Peter Collingbournecfd23562011-09-26 01:57:12 +00002081 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;
Benjamin Kramera37e7652015-07-25 17:10:49 +00002086 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));
Peter Collingbournecfd23562011-09-26 01:57:12 +00002090 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002091
Peter Collingbournecfd23562011-09-26 01:57:12 +00002092 Out << "Virtual base offset offsets for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002093 MostDerivedClass->printQualifiedName(Out);
2094 Out << "' (";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002095 Out << ClassNamesAndOffsets.size();
2096 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2097
Benjamin Kramera37e7652015-07-25 17:10:49 +00002098 for (const auto &I : ClassNamesAndOffsets)
2099 Out << " " << I.first << " | " << I.second.getQuantity() << '\n';
Peter Collingbournecfd23562011-09-26 01:57:12 +00002100
2101 Out << "\n";
2102 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002103
Peter Collingbournecfd23562011-09-26 01:57:12 +00002104 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;
Benjamin Kramera37e7652015-07-25 17:10:49 +00002107
2108 for (const auto &I : Thunks) {
2109 const CXXMethodDecl *MD = I.first;
Fangrui Song6907ce22018-07-30 19:24:48 +00002110 std::string MethodName =
Peter Collingbournecfd23562011-09-26 01:57:12 +00002111 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2112 MD);
Fangrui Song6907ce22018-07-30 19:24:48 +00002113
Peter Collingbournecfd23562011-09-26 01:57:12 +00002114 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2115 }
2116
Benjamin Kramera37e7652015-07-25 17:10:49 +00002117 for (const auto &I : MethodNamesAndDecls) {
2118 const std::string &MethodName = I.first;
2119 const CXXMethodDecl *MD = I.second;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002120
2121 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Fangrui Song55fab262018-09-26 22:16:28 +00002122 llvm::sort(ThunksVector, [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
Craig Topper36250ad2014-05-12 05:36:57 +00002123 assert(LHS.Method == nullptr && RHS.Method == nullptr);
Benjamin Kramera741b8c2014-03-03 20:26:46 +00002124 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002125 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002126
2127 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2128 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00002129
Peter Collingbournecfd23562011-09-26 01:57:12 +00002130 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2131 const ThunkInfo &Thunk = ThunksVector[I];
2132
2133 Out << llvm::format("%4d | ", I);
Fangrui Song6907ce22018-07-30 19:24:48 +00002134
Peter Collingbournecfd23562011-09-26 01:57:12 +00002135 // If this function pointer has a return pointer adjustment, dump it.
2136 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00002137 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002138 Out << " non-virtual";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002139 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2140 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002141 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";
Fangrui Song6907ce22018-07-30 19:24:48 +00002152
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002153 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2154 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002155 Out << " vcall offset offset";
2156 }
2157 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002158
Peter Collingbournecfd23562011-09-26 01:57:12 +00002159 Out << '\n';
2160 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002161
Peter Collingbournecfd23562011-09-26 01:57:12 +00002162 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
Aaron Ballman2b124d12014-03-13 16:36:16 +00002170 for (const auto *MD : MostDerivedClass->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002171 // We only want virtual member functions.
2172 if (!MD->isVirtual())
2173 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +00002174 MD = MD->getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002175
2176 std::string MethodName =
2177 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2178 MD);
2179
2180 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002181 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]";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002186 } else {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002187 assert(MethodVTableIndices.count(MD));
2188 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002189 }
2190 }
2191
2192 // Print the vtable indices for all the member functions.
2193 if (!IndicesMap.empty()) {
2194 Out << "VTable indices for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002195 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002196 Out << "' (" << IndicesMap.size() << " entries).\n";
2197
Benjamin Kramera37e7652015-07-25 17:10:49 +00002198 for (const auto &I : IndicesMap) {
2199 uint64_t VTableIndex = I.first;
2200 const std::string &MethodName = I.second;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002201
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002202 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer5291e682012-03-10 02:06:27 +00002203 << '\n';
Peter Collingbournecfd23562011-09-26 01:57:12 +00002204 }
2205 }
2206
2207 Out << '\n';
2208}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002209}
Peter Collingbournecfd23562011-09-26 01:57:12 +00002210
Leonard Chan71568a92020-06-11 11:17:08 -07002211static VTableLayout::AddressPointsIndexMapTy
2212MakeAddressPointIndices(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
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00002238VTableLayout::VTableLayout(ArrayRef<size_t> VTableIndices,
2239 ArrayRef<VTableComponent> VTableComponents,
2240 ArrayRef<VTableThunkTy> VTableThunks,
2241 const AddressPointsMapTy &AddressPoints)
2242 : VTableComponents(VTableComponents), VTableThunks(VTableThunks),
Leonard Chan71568a92020-06-11 11:17:08 -07002243 AddressPoints(AddressPoints), AddressPointIndices(MakeAddressPointIndices(
2244 AddressPoints, VTableIndices.size())) {
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00002245 if (VTableIndices.size() <= 1)
2246 assert(VTableIndices.size() == 1 && VTableIndices[0] == 0);
2247 else
2248 this->VTableIndices = OwningArrayRef<size_t>(VTableIndices);
2249
Fangrui Song1d38c132018-09-30 21:41:11 +00002250 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 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002256}
2257
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002258VTableLayout::~VTableLayout() { }
Peter Collingbournecfd23562011-09-26 01:57:12 +00002259
Leonard Chan71568a92020-06-11 11:17:08 -07002260ItaniumVTableContext::ItaniumVTableContext(
2261 ASTContext &Context, VTableComponentLayout ComponentLayout)
2262 : VTableContextBase(/*MS=*/false), ComponentLayout(ComponentLayout) {}
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002263
Justin Lebar072f9ba2016-10-10 16:26:24 +00002264ItaniumVTableContext::~ItaniumVTableContext() {}
Peter Collingbournecfd23562011-09-26 01:57:12 +00002265
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002266uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
Reid Kleckner138ab492018-05-17 18:12:18 +00002267 GD = GD.getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002268 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2269 if (I != MethodVTableIndices.end())
2270 return I->second;
Fangrui Song6907ce22018-07-30 19:24:48 +00002271
Peter Collingbournecfd23562011-09-26 01:57:12 +00002272 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2273
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002274 computeVTableRelatedInformation(RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002275
2276 I = MethodVTableIndices.find(GD);
2277 assert(I != MethodVTableIndices.end() && "Did not find index!");
2278 return I->second;
2279}
2280
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002281CharUnits
2282ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2283 const CXXRecordDecl *VBase) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002284 ClassPairTy ClassPair(RD, VBase);
Fangrui Song6907ce22018-07-30 19:24:48 +00002285
2286 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
Peter Collingbournecfd23562011-09-26 01:57:12 +00002287 VirtualBaseClassOffsetOffsets.find(ClassPair);
2288 if (I != VirtualBaseClassOffsetOffsets.end())
2289 return I->second;
Craig Topper36250ad2014-05-12 05:36:57 +00002290
Leonard Chan71568a92020-06-11 11:17:08 -07002291 VCallAndVBaseOffsetBuilder Builder(*this, RD, RD, /*Overriders=*/nullptr,
Peter Collingbournecfd23562011-09-26 01:57:12 +00002292 BaseSubobject(RD, CharUnits::Zero()),
2293 /*BaseIsVirtual=*/false,
2294 /*OffsetInLayoutClass=*/CharUnits::Zero());
2295
Benjamin Kramera37e7652015-07-25 17:10:49 +00002296 for (const auto &I : Builder.getVBaseOffsetOffsets()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002297 // Insert all types.
Benjamin Kramera37e7652015-07-25 17:10:49 +00002298 ClassPairTy ClassPair(RD, I.first);
2299
2300 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
Peter Collingbournecfd23562011-09-26 01:57:12 +00002301 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002302
Peter Collingbournecfd23562011-09-26 01:57:12 +00002303 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2304 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
Fangrui Song6907ce22018-07-30 19:24:48 +00002305
Peter Collingbournecfd23562011-09-26 01:57:12 +00002306 return I->second;
2307}
2308
Justin Lebar072f9ba2016-10-10 16:26:24 +00002309static std::unique_ptr<VTableLayout>
2310CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002311 SmallVector<VTableLayout::VTableThunkTy, 1>
2312 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002313
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002314 return std::make_unique<VTableLayout>(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00002315 Builder.VTableIndices, Builder.vtable_components(), VTableThunks,
2316 Builder.getAddressPoints());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002317}
2318
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002319void
2320ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Justin Lebar072f9ba2016-10-10 16:26:24 +00002321 std::unique_ptr<const VTableLayout> &Entry = VTableLayouts[RD];
Peter Collingbournecfd23562011-09-26 01:57:12 +00002322
2323 // Check if we've computed this information before.
2324 if (Entry)
2325 return;
2326
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002327 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2328 /*MostDerivedClassIsVirtual=*/0, RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002329 Entry = CreateVTableLayout(Builder);
2330
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002331 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2332 Builder.vtable_indices_end());
2333
Peter Collingbournecfd23562011-09-26 01:57:12 +00002334 // Add the known thunks.
2335 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2336
2337 // If we don't have the vbase information for this class, insert it.
2338 // getVirtualBaseOffsetOffset will compute it separately without computing
2339 // the rest of the vtable related information.
2340 if (!RD->getNumVBases())
2341 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002342
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00002343 const CXXRecordDecl *VBase =
2344 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002345
Peter Collingbournecfd23562011-09-26 01:57:12 +00002346 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2347 return;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002348
Benjamin Kramera37e7652015-07-25 17:10:49 +00002349 for (const auto &I : Builder.getVBaseOffsetOffsets()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002350 // Insert all types.
Benjamin Kramera37e7652015-07-25 17:10:49 +00002351 ClassPairTy ClassPair(RD, I.first);
2352
2353 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
Peter Collingbournecfd23562011-09-26 01:57:12 +00002354 }
2355}
2356
Justin Lebar072f9ba2016-10-10 16:26:24 +00002357std::unique_ptr<VTableLayout>
2358ItaniumVTableContext::createConstructionVTableLayout(
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002359 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2360 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2361 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2362 MostDerivedClassIsVirtual, LayoutClass);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002363 return CreateVTableLayout(Builder);
2364}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002365
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002366namespace {
2367
2368// Vtables in the Microsoft ABI are different from the Itanium ABI.
2369//
2370// The main differences are:
2371// 1. Separate vftable and vbtable.
2372//
2373// 2. Each subobject with a vfptr gets its own vftable rather than an address
2374// point in a single vtable shared between all the subobjects.
2375// Each vftable is represented by a separate section and virtual calls
2376// must be done using the vftable which has a slot for the function to be
2377// called.
2378//
2379// 3. Virtual method definitions expect their 'this' parameter to point to the
2380// first vfptr whose table provides a compatible overridden method. In many
2381// cases, this permits the original vf-table entry to directly call
2382// the method instead of passing through a thunk.
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002383// See example before VFTableBuilder::ComputeThisOffset below.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002384//
2385// A compatible overridden method is one which does not have a non-trivial
2386// covariant-return adjustment.
2387//
2388// The first vfptr is the one with the lowest offset in the complete-object
2389// layout of the defining class, and the method definition will subtract
2390// that constant offset from the parameter value to get the real 'this'
2391// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2392// function defined in a virtual base is overridden in a more derived
2393// virtual base and these bases have a reverse order in the complete
2394// object), the vf-table may require a this-adjustment thunk.
2395//
2396// 4. vftables do not contain new entries for overrides that merely require
2397// this-adjustment. Together with #3, this keeps vf-tables smaller and
2398// eliminates the need for this-adjustment thunks in many cases, at the cost
2399// of often requiring redundant work to adjust the "this" pointer.
2400//
2401// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2402// Vtordisps are emitted into the class layout if a class has
2403// a) a user-defined ctor/dtor
2404// and
2405// b) a method overriding a method in a virtual base.
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002406//
2407// To get a better understanding of this code,
2408// you might want to see examples in test/CodeGenCXX/microsoft-abi-vtables-*.cpp
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002409
2410class VFTableBuilder {
2411public:
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002412 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2413 MethodVFTableLocationsTy;
2414
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00002415 typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
2416 method_locations_range;
2417
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002418private:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002419 /// VTables - Global vtable information.
2420 MicrosoftVTableContext &VTables;
2421
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002422 /// Context - The ASTContext which we will use for layout information.
2423 ASTContext &Context;
2424
2425 /// MostDerivedClass - The most derived class for which we're building this
2426 /// vtable.
2427 const CXXRecordDecl *MostDerivedClass;
2428
2429 const ASTRecordLayout &MostDerivedClassLayout;
2430
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002431 const VPtrInfo &WhichVFPtr;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002432
2433 /// FinalOverriders - The final overriders of the most derived class.
2434 const FinalOverriders Overriders;
2435
2436 /// Components - The components of the vftable being built.
2437 SmallVector<VTableComponent, 64> Components;
2438
2439 MethodVFTableLocationsTy MethodVFTableLocations;
2440
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002441 /// Does this class have an RTTI component?
David Majnemer2d8b2002016-02-11 17:49:28 +00002442 bool HasRTTIComponent = false;
David Majnemer3c7228e2014-07-01 21:10:07 +00002443
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002444 /// MethodInfo - Contains information about a method in a vtable.
2445 /// (Used for computing 'this' pointer adjustment thunks.
2446 struct MethodInfo {
2447 /// VBTableIndex - The nonzero index in the vbtable that
2448 /// this method's base has, or zero.
2449 const uint64_t VBTableIndex;
2450
2451 /// VFTableIndex - The index in the vftable that this method has.
2452 const uint64_t VFTableIndex;
2453
2454 /// Shadowed - Indicates if this vftable slot is shadowed by
2455 /// a slot for a covariant-return override. If so, it shouldn't be printed
2456 /// or used for vcalls in the most derived class.
2457 bool Shadowed;
2458
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00002459 /// UsesExtraSlot - Indicates if this vftable slot was created because
2460 /// any of the overridden slots required a return adjusting thunk.
2461 bool UsesExtraSlot;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002462
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00002463 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex,
2464 bool UsesExtraSlot = false)
2465 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
2466 Shadowed(false), UsesExtraSlot(UsesExtraSlot) {}
2467
2468 MethodInfo()
2469 : VBTableIndex(0), VFTableIndex(0), Shadowed(false),
2470 UsesExtraSlot(false) {}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002471 };
2472
2473 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2474
2475 /// MethodInfoMap - The information for all methods in the vftable we're
2476 /// currently building.
2477 MethodInfoMapTy MethodInfoMap;
2478
2479 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2480
2481 /// VTableThunks - The thunks by vftable index in the vftable currently being
2482 /// built.
2483 VTableThunksMapTy VTableThunks;
2484
2485 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2486 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2487
2488 /// Thunks - A map that contains all the thunks needed for all methods in the
2489 /// most derived class for which the vftable is currently being built.
2490 ThunksMapTy Thunks;
2491
2492 /// AddThunk - Add a thunk for the given method.
2493 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2494 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2495
2496 // Check if we have this thunk already.
Fangrui Song75e74e02019-03-31 08:48:19 +00002497 if (llvm::find(ThunksVector, Thunk) != ThunksVector.end())
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002498 return;
2499
2500 ThunksVector.push_back(Thunk);
2501 }
2502
2503 /// ComputeThisOffset - Returns the 'this' argument offset for the given
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002504 /// method, relative to the beginning of the MostDerivedClass.
2505 CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002506
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002507 void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2508 CharUnits ThisOffset, ThisAdjustment &TA);
2509
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002510 /// AddMethod - Add a single virtual member function to the vftable
2511 /// components vector.
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002512 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002513 if (!TI.isEmpty()) {
2514 VTableThunks[Components.size()] = TI;
2515 AddThunk(MD, TI);
2516 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002517 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002518 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002519 "Destructor can't have return adjustment!");
2520 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2521 } else {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002522 Components.push_back(VTableComponent::MakeFunction(MD));
2523 }
2524 }
2525
2526 /// AddMethods - Add the methods of this base subobject and the relevant
2527 /// subbases to the vftable we're currently laying out.
2528 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2529 const CXXRecordDecl *LastVBase,
2530 BasesSetVectorTy &VisitedBases);
2531
2532 void LayoutVFTable() {
David Majnemer6e9ae782014-09-22 20:39:37 +00002533 // RTTI data goes before all other entries.
2534 if (HasRTTIComponent)
2535 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002536
2537 BasesSetVectorTy VisitedBases;
Craig Topper36250ad2014-05-12 05:36:57 +00002538 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, nullptr,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002539 VisitedBases);
David Majnemera9b7e662014-09-26 08:07:55 +00002540 assert((HasRTTIComponent ? Components.size() - 1 : Components.size()) &&
2541 "vftable can't be empty");
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002542
2543 assert(MethodVFTableLocations.empty());
Benjamin Kramera37e7652015-07-25 17:10:49 +00002544 for (const auto &I : MethodInfoMap) {
2545 const CXXMethodDecl *MD = I.first;
2546 const MethodInfo &MI = I.second;
Reid Kleckner138ab492018-05-17 18:12:18 +00002547 assert(MD == MD->getCanonicalDecl());
2548
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002549 // Skip the methods that the MostDerivedClass didn't override
2550 // and the entries shadowed by return adjusting thunks.
2551 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2552 continue;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002553 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2554 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002555 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2556 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2557 } else {
2558 MethodVFTableLocations[MD] = Loc;
2559 }
2560 }
2561 }
2562
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002563public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002564 VFTableBuilder(MicrosoftVTableContext &VTables,
Justin Lebar562914e2016-10-10 16:26:29 +00002565 const CXXRecordDecl *MostDerivedClass, const VPtrInfo &Which)
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002566 : VTables(VTables),
2567 Context(MostDerivedClass->getASTContext()),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002568 MostDerivedClass(MostDerivedClass),
2569 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
Justin Lebar562914e2016-10-10 16:26:29 +00002570 WhichVFPtr(Which),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002571 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
Reid Klecknerad1e22b2016-06-29 18:29:21 +00002572 // Provide the RTTI component if RTTIData is enabled. If the vftable would
2573 // be available externally, we should not provide the RTTI componenent. It
2574 // is currently impossible to get available externally vftables with either
2575 // dllimport or extern template instantiations, but eventually we may add a
2576 // flag to support additional devirtualization that needs this.
David Majnemer2d8b2002016-02-11 17:49:28 +00002577 if (Context.getLangOpts().RTTIData)
Reid Klecknerad1e22b2016-06-29 18:29:21 +00002578 HasRTTIComponent = true;
David Majnemerd905da42014-07-01 20:30:31 +00002579
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002580 LayoutVFTable();
2581
2582 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00002583 dumpLayout(llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002584 }
2585
2586 uint64_t getNumThunks() const { return Thunks.size(); }
2587
2588 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2589
2590 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2591
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00002592 method_locations_range vtable_locations() const {
2593 return method_locations_range(MethodVFTableLocations.begin(),
2594 MethodVFTableLocations.end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002595 }
2596
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00002597 ArrayRef<VTableComponent> vtable_components() const { return Components; }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002598
2599 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2600 return VTableThunks.begin();
2601 }
2602
2603 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2604 return VTableThunks.end();
2605 }
2606
2607 void dumpLayout(raw_ostream &);
2608};
2609
Benjamin Kramerd5748c72015-03-23 12:31:05 +00002610} // end namespace
2611
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002612// Let's study one class hierarchy as an example:
2613// struct A {
2614// virtual void f();
2615// int x;
2616// };
2617//
2618// struct B : virtual A {
2619// virtual void f();
2620// };
2621//
2622// Record layouts:
2623// struct A:
Timur Iskhodzhanov4d280022014-11-14 14:16:34 +00002624// 0 | (A vftable pointer)
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002625// 4 | int x
2626//
2627// struct B:
Timur Iskhodzhanov4d280022014-11-14 14:16:34 +00002628// 0 | (B vbtable pointer)
2629// 4 | struct A (virtual base)
2630// 4 | (A vftable pointer)
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002631// 8 | int x
2632//
2633// Let's assume we have a pointer to the A part of an object of dynamic type B:
2634// B b;
2635// A *a = (A*)&b;
2636// a->f();
2637//
2638// In this hierarchy, f() belongs to the vftable of A, so B::f() expects
2639// "this" parameter to point at the A subobject, which is B+4.
2640// In the B::f() prologue, it adjusts "this" back to B by subtracting 4,
Nico Webercda5c7c2014-11-29 23:57:35 +00002641// performed as a *static* adjustment.
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002642//
2643// Interesting thing happens when we alter the relative placement of A and B
2644// subobjects in a class:
2645// struct C : virtual B { };
2646//
2647// C c;
2648// A *a = (A*)&c;
2649// a->f();
2650//
2651// Respective record layout is:
2652// 0 | (C vbtable pointer)
2653// 4 | struct A (virtual base)
2654// 4 | (A vftable pointer)
2655// 8 | int x
2656// 12 | struct B (virtual base)
2657// 12 | (B vbtable pointer)
2658//
2659// The final overrider of f() in class C is still B::f(), so B+4 should be
2660// passed as "this" to that code. However, "a" points at B-8, so the respective
2661// vftable entry should hold a thunk that adds 12 to the "this" argument before
2662// performing a tail call to B::f().
2663//
2664// With this example in mind, we can now calculate the 'this' argument offset
2665// for the given method, relative to the beginning of the MostDerivedClass.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002666CharUnits
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002667VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00002668 BasesSetVectorTy Bases;
2669
2670 {
2671 // Find the set of least derived bases that define the given method.
2672 OverriddenMethodsSetTy VisitedOverriddenMethods;
2673 auto InitialOverriddenDefinitionCollector = [&](
2674 const CXXMethodDecl *OverriddenMD) {
2675 if (OverriddenMD->size_overridden_methods() == 0)
2676 Bases.insert(OverriddenMD->getParent());
2677 // Don't recurse on this method if we've already collected it.
2678 return VisitedOverriddenMethods.insert(OverriddenMD).second;
2679 };
2680 visitAllOverriddenMethods(Overrider.Method,
2681 InitialOverriddenDefinitionCollector);
2682 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002683
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002684 // If there are no overrides then 'this' is located
2685 // in the base that defines the method.
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00002686 if (Bases.size() == 0)
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002687 return Overrider.Offset;
2688
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002689 CXXBasePaths Paths;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002690 Overrider.Method->getParent()->lookupInBases(
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00002691 [&Bases](const CXXBaseSpecifier *Specifier, CXXBasePath &) {
2692 return Bases.count(Specifier->getType()->getAsCXXRecordDecl());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002693 },
2694 Paths);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002695
2696 // This will hold the smallest this offset among overridees of MD.
2697 // This implies that an offset of a non-virtual base will dominate an offset
2698 // of a virtual base to potentially reduce the number of thunks required
2699 // in the derived classes that inherit this method.
2700 CharUnits Ret;
2701 bool First = true;
2702
Timur Iskhodzhanoved11ae32014-04-17 22:01:48 +00002703 const ASTRecordLayout &OverriderRDLayout =
2704 Context.getASTRecordLayout(Overrider.Method->getParent());
Benjamin Kramera37e7652015-07-25 17:10:49 +00002705 for (const CXXBasePath &Path : Paths) {
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002706 CharUnits ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002707 CharUnits LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002708
Nico Weberd73258a2015-05-16 23:49:53 +00002709 // For each path from the overrider to the parents of the overridden
2710 // methods, traverse the path, calculating the this offset in the most
2711 // derived class.
Benjamin Kramera37e7652015-07-25 17:10:49 +00002712 for (const CXXBasePathElement &Element : Path) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002713 QualType CurTy = Element.Base->getType();
2714 const CXXRecordDecl *PrevRD = Element.Class,
2715 *CurRD = CurTy->getAsCXXRecordDecl();
2716 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2717
2718 if (Element.Base->isVirtual()) {
Timur Iskhodzhanoved11ae32014-04-17 22:01:48 +00002719 // The interesting things begin when you have virtual inheritance.
2720 // The final overrider will use a static adjustment equal to the offset
2721 // of the vbase in the final overrider class.
2722 // For example, if the final overrider is in a vbase B of the most
2723 // derived class and it overrides a method of the B's own vbase A,
2724 // it uses A* as "this". In its prologue, it can cast A* to B* with
2725 // a static offset. This offset is used regardless of the actual
2726 // offset of A from B in the most derived class, requiring an
2727 // this-adjusting thunk in the vftable if A and B are laid out
2728 // differently in the most derived class.
2729 LastVBaseOffset = ThisOffset =
2730 Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002731 } else {
2732 ThisOffset += Layout.getBaseClassOffset(CurRD);
2733 }
2734 }
2735
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002736 if (isa<CXXDestructorDecl>(Overrider.Method)) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002737 if (LastVBaseOffset.isZero()) {
2738 // If a "Base" class has at least one non-virtual base with a virtual
2739 // destructor, the "Base" virtual destructor will take the address
2740 // of the "Base" subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002741 ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002742 } else {
2743 // A virtual destructor of a virtual base takes the address of the
2744 // virtual base subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002745 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002746 }
2747 }
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +00002748
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002749 if (Ret > ThisOffset || First) {
2750 First = false;
2751 Ret = ThisOffset;
2752 }
2753 }
2754
2755 assert(!First && "Method not found in the given subobject?");
2756 return Ret;
2757}
2758
Timur Iskhodzhanov7d19fc12014-11-17 15:11:05 +00002759// Things are getting even more complex when the "this" adjustment has to
2760// use a dynamic offset instead of a static one, or even two dynamic offsets.
2761// This is sometimes required when a virtual call happens in the middle of
2762// a non-most-derived class construction or destruction.
2763//
2764// Let's take a look at the following example:
2765// struct A {
2766// virtual void f();
2767// };
2768//
2769// void foo(A *a) { a->f(); } // Knows nothing about siblings of A.
2770//
2771// struct B : virtual A {
2772// virtual void f();
2773// B() {
2774// foo(this);
2775// }
2776// };
2777//
2778// struct C : virtual B {
2779// virtual void f();
2780// };
2781//
2782// Record layouts for these classes are:
2783// struct A
2784// 0 | (A vftable pointer)
2785//
2786// struct B
2787// 0 | (B vbtable pointer)
2788// 4 | (vtordisp for vbase A)
2789// 8 | struct A (virtual base)
2790// 8 | (A vftable pointer)
2791//
2792// struct C
2793// 0 | (C vbtable pointer)
2794// 4 | (vtordisp for vbase A)
2795// 8 | struct A (virtual base) // A precedes B!
2796// 8 | (A vftable pointer)
2797// 12 | struct B (virtual base)
2798// 12 | (B vbtable pointer)
2799//
2800// When one creates an object of type C, the C constructor:
2801// - initializes all the vbptrs, then
2802// - calls the A subobject constructor
2803// (initializes A's vfptr with an address of A vftable), then
2804// - calls the B subobject constructor
2805// (initializes A's vfptr with an address of B vftable and vtordisp for A),
2806// that in turn calls foo(), then
2807// - initializes A's vfptr with an address of C vftable and zeroes out the
2808// vtordisp
2809// FIXME: if a structor knows it belongs to MDC, why doesn't it use a vftable
2810// without vtordisp thunks?
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002811// FIXME: how are vtordisp handled in the presence of nooverride/final?
Timur Iskhodzhanov7d19fc12014-11-17 15:11:05 +00002812//
2813// When foo() is called, an object with a layout of class C has a vftable
2814// referencing B::f() that assumes a B layout, so the "this" adjustments are
2815// incorrect, unless an extra adjustment is done. This adjustment is called
2816// "vtordisp adjustment". Vtordisp basically holds the difference between the
2817// actual location of a vbase in the layout class and the location assumed by
2818// the vftable of the class being constructed/destructed. Vtordisp is only
2819// needed if "this" escapes a
2820// structor (or we can't prove otherwise).
2821// [i.e. vtordisp is a dynamic adjustment for a static adjustment, which is an
2822// estimation of a dynamic adjustment]
2823//
2824// foo() gets a pointer to the A vbase and doesn't know anything about B or C,
2825// so it just passes that pointer as "this" in a virtual call.
2826// If there was no vtordisp, that would just dispatch to B::f().
2827// However, B::f() assumes B+8 is passed as "this",
2828// yet the pointer foo() passes along is B-4 (i.e. C+8).
2829// An extra adjustment is needed, so we emit a thunk into the B vftable.
2830// This vtordisp thunk subtracts the value of vtordisp
2831// from the "this" argument (-12) before making a tailcall to B::f().
2832//
2833// Let's consider an even more complex example:
2834// struct D : virtual B, virtual C {
2835// D() {
2836// foo(this);
2837// }
2838// };
2839//
2840// struct D
2841// 0 | (D vbtable pointer)
2842// 4 | (vtordisp for vbase A)
2843// 8 | struct A (virtual base) // A precedes both B and C!
2844// 8 | (A vftable pointer)
2845// 12 | struct B (virtual base) // B precedes C!
2846// 12 | (B vbtable pointer)
2847// 16 | struct C (virtual base)
2848// 16 | (C vbtable pointer)
2849//
2850// When D::D() calls foo(), we find ourselves in a thunk that should tailcall
2851// to C::f(), which assumes C+8 as its "this" parameter. This time, foo()
2852// passes along A, which is C-8. The A vtordisp holds
2853// "D.vbptr[index_of_A] - offset_of_A_in_D"
2854// and we statically know offset_of_A_in_D, so can get a pointer to D.
2855// When we know it, we can make an extra vbtable lookup to locate the C vbase
2856// and one extra static adjustment to calculate the expected value of C+8.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002857void VFTableBuilder::CalculateVtordispAdjustment(
2858 FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2859 ThisAdjustment &TA) {
2860 const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2861 MostDerivedClassLayout.getVBaseOffsetsMap();
2862 const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002863 VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002864 assert(VBaseMapEntry != VBaseMap.end());
2865
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002866 // If there's no vtordisp or the final overrider is defined in the same vbase
2867 // as the initial declaration, we don't need any vtordisp adjustment.
2868 if (!VBaseMapEntry->second.hasVtorDisp() ||
2869 Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
Timur Iskhodzhanov057fa3a2014-04-17 11:01:41 +00002870 return;
2871
2872 // OK, now we know we need to use a vtordisp thunk.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002873 // The implicit vtordisp field is located right before the vbase.
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002874 CharUnits OffsetOfVBaseWithVFPtr = VBaseMapEntry->second.VBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002875 TA.Virtual.Microsoft.VtordispOffset =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002876 (OffsetOfVBaseWithVFPtr - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002877
Timur Iskhodzhanov057fa3a2014-04-17 11:01:41 +00002878 // A simple vtordisp thunk will suffice if the final overrider is defined
2879 // in either the most derived class or its non-virtual base.
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002880 if (Overrider.Method->getParent() == MostDerivedClass ||
2881 !Overrider.VirtualBase)
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002882 return;
2883
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002884 // Otherwise, we need to do use the dynamic offset of the final overrider
2885 // in order to get "this" adjustment right.
2886 TA.Virtual.Microsoft.VBPtrOffset =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002887 (OffsetOfVBaseWithVFPtr + WhichVFPtr.NonVirtualOffset -
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002888 MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2889 TA.Virtual.Microsoft.VBOffsetOffset =
2890 Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002891 VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002892
2893 TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2894}
2895
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002896static void GroupNewVirtualOverloads(
2897 const CXXRecordDecl *RD,
2898 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2899 // Put the virtual methods into VirtualMethods in the proper order:
2900 // 1) Group overloads by declaration name. New groups are added to the
2901 // vftable in the order of their first declarations in this class
David Majnemer70effde2015-11-19 00:03:54 +00002902 // (including overrides, non-virtual methods and any other named decl that
2903 // might be nested within the class).
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002904 // 2) In each group, new overloads appear in the reverse order of declaration.
2905 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2906 SmallVector<MethodGroup, 10> Groups;
2907 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2908 VisitedGroupIndicesTy VisitedGroupIndices;
David Majnemer70effde2015-11-19 00:03:54 +00002909 for (const auto *D : RD->decls()) {
2910 const auto *ND = dyn_cast<NamedDecl>(D);
2911 if (!ND)
2912 continue;
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002913 VisitedGroupIndicesTy::iterator J;
2914 bool Inserted;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002915 std::tie(J, Inserted) = VisitedGroupIndices.insert(
David Majnemer70effde2015-11-19 00:03:54 +00002916 std::make_pair(ND->getDeclName(), Groups.size()));
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002917 if (Inserted)
Reid Kleckner6701de22014-02-19 22:06:10 +00002918 Groups.push_back(MethodGroup());
David Majnemer70effde2015-11-19 00:03:54 +00002919 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
2920 if (MD->isVirtual())
2921 Groups[J->second].push_back(MD->getCanonicalDecl());
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002922 }
2923
Benjamin Kramera37e7652015-07-25 17:10:49 +00002924 for (const MethodGroup &Group : Groups)
2925 VirtualMethods.append(Group.rbegin(), Group.rend());
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002926}
2927
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002928static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
2929 for (const auto &B : RD->bases()) {
2930 if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
2931 return true;
2932 }
2933 return false;
2934}
2935
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002936void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2937 const CXXRecordDecl *LastVBase,
2938 BasesSetVectorTy &VisitedBases) {
2939 const CXXRecordDecl *RD = Base.getBase();
2940 if (!RD->isPolymorphic())
2941 return;
2942
2943 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2944
2945 // See if this class expands a vftable of the base we look at, which is either
Nico Weberd73258a2015-05-16 23:49:53 +00002946 // the one defined by the vfptr base path or the primary base of the current
2947 // class.
Craig Topper36250ad2014-05-12 05:36:57 +00002948 const CXXRecordDecl *NextBase = nullptr, *NextLastVBase = LastVBase;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002949 CharUnits NextBaseOffset;
Reid Kleckner8ad06d62016-07-20 14:40:25 +00002950 if (BaseDepth < WhichVFPtr.PathToIntroducingObject.size()) {
2951 NextBase = WhichVFPtr.PathToIntroducingObject[BaseDepth];
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002952 if (isDirectVBase(NextBase, RD)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002953 NextLastVBase = NextBase;
2954 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2955 } else {
2956 NextBaseOffset =
2957 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2958 }
2959 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2960 assert(!Layout.isPrimaryBaseVirtual() &&
2961 "No primary virtual bases in this ABI");
2962 NextBase = PrimaryBase;
2963 NextBaseOffset = Base.getBaseOffset();
2964 }
2965
2966 if (NextBase) {
2967 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2968 NextLastVBase, VisitedBases);
2969 if (!VisitedBases.insert(NextBase))
2970 llvm_unreachable("Found a duplicate primary base!");
2971 }
2972
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002973 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2974 // Put virtual methods in the proper order.
2975 GroupNewVirtualOverloads(RD, VirtualMethods);
2976
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002977 // Now go through all virtual member functions and add them to the current
2978 // vftable. This is done by
2979 // - replacing overridden methods in their existing slots, as long as they
2980 // don't require return adjustment; calculating This adjustment if needed.
2981 // - adding new slots for methods of the current base not present in any
2982 // sub-bases;
2983 // - adding new slots for methods that require Return adjustment.
2984 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Benjamin Kramera37e7652015-07-25 17:10:49 +00002985 for (const CXXMethodDecl *MD : VirtualMethods) {
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002986 FinalOverriders::OverriderInfo FinalOverrider =
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002987 Overriders.getOverrider(MD, Base.getBaseOffset());
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002988 const CXXMethodDecl *FinalOverriderMD = FinalOverrider.Method;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002989 const CXXMethodDecl *OverriddenMD =
2990 FindNearestOverriddenMethod(MD, VisitedBases);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002991
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002992 ThisAdjustment ThisAdjustmentOffset;
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00002993 bool ReturnAdjustingThunk = false, ForceReturnAdjustmentMangling = false;
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002994 CharUnits ThisOffset = ComputeThisOffset(FinalOverrider);
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002995 ThisAdjustmentOffset.NonVirtual =
2996 (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002997 if ((OverriddenMD || FinalOverriderMD != MD) &&
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002998 WhichVFPtr.getVBaseWithVPtr())
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002999 CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
3000 ThisAdjustmentOffset);
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003001
Reid Klecknerdd6fc832017-08-29 17:40:04 +00003002 unsigned VBIndex =
3003 LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
3004
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003005 if (OverriddenMD) {
Nico Weberd73258a2015-05-16 23:49:53 +00003006 // If MD overrides anything in this vftable, we need to update the
3007 // entries.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003008 MethodInfoMapTy::iterator OverriddenMDIterator =
3009 MethodInfoMap.find(OverriddenMD);
3010
3011 // If the overridden method went to a different vftable, skip it.
3012 if (OverriddenMDIterator == MethodInfoMap.end())
3013 continue;
3014
3015 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
3016
Reid Klecknerdd6fc832017-08-29 17:40:04 +00003017 VBIndex = OverriddenMethodInfo.VBTableIndex;
3018
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003019 // Let's check if the overrider requires any return adjustments.
3020 // We must create a new slot if the MD's return type is not trivially
3021 // convertible to the OverriddenMD's one.
3022 // Once a chain of method overrides adds a return adjusting vftable slot,
3023 // all subsequent overrides will also use an extra method slot.
3024 ReturnAdjustingThunk = !ComputeReturnAdjustmentBaseOffset(
3025 Context, MD, OverriddenMD).isEmpty() ||
3026 OverriddenMethodInfo.UsesExtraSlot;
3027
3028 if (!ReturnAdjustingThunk) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003029 // No return adjustment needed - just replace the overridden method info
3030 // with the current info.
Reid Klecknerdd6fc832017-08-29 17:40:04 +00003031 MethodInfo MI(VBIndex, OverriddenMethodInfo.VFTableIndex);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003032 MethodInfoMap.erase(OverriddenMDIterator);
3033
3034 assert(!MethodInfoMap.count(MD) &&
3035 "Should not have method info for this method yet!");
3036 MethodInfoMap.insert(std::make_pair(MD, MI));
3037 continue;
Reid Kleckner31a9f742013-12-27 20:29:16 +00003038 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003039
Reid Kleckner31a9f742013-12-27 20:29:16 +00003040 // In case we need a return adjustment, we'll add a new slot for
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003041 // the overrider. Mark the overridden method as shadowed by the new slot.
Reid Kleckner31a9f742013-12-27 20:29:16 +00003042 OverriddenMethodInfo.Shadowed = true;
Reid Kleckner31a9f742013-12-27 20:29:16 +00003043
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003044 // Force a special name mangling for a return-adjusting thunk
3045 // unless the method is the final overrider without this adjustment.
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003046 ForceReturnAdjustmentMangling =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003047 !(MD == FinalOverriderMD && ThisAdjustmentOffset.isEmpty());
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003048 } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003049 MD->size_overridden_methods()) {
3050 // Skip methods that don't belong to the vftable of the current class,
3051 // e.g. each method that wasn't seen in any of the visited sub-bases
3052 // but overrides multiple methods of other sub-bases.
3053 continue;
3054 }
3055
3056 // If we got here, MD is a method not seen in any of the sub-bases or
3057 // it requires return adjustment. Insert the method info for this method.
David Majnemer3c7228e2014-07-01 21:10:07 +00003058 MethodInfo MI(VBIndex,
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003059 HasRTTIComponent ? Components.size() - 1 : Components.size(),
3060 ReturnAdjustingThunk);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003061
3062 assert(!MethodInfoMap.count(MD) &&
3063 "Should not have method info for this method yet!");
3064 MethodInfoMap.insert(std::make_pair(MD, MI));
3065
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003066 // Check if this overrider needs a return adjustment.
3067 // We don't want to do this for pure virtual member functions.
3068 BaseOffset ReturnAdjustmentOffset;
3069 ReturnAdjustment ReturnAdjustment;
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003070 if (!FinalOverriderMD->isPure()) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003071 ReturnAdjustmentOffset =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003072 ComputeReturnAdjustmentBaseOffset(Context, FinalOverriderMD, MD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003073 }
3074 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003075 ForceReturnAdjustmentMangling = true;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003076 ReturnAdjustment.NonVirtual =
3077 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
3078 if (ReturnAdjustmentOffset.VirtualBase) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003079 const ASTRecordLayout &DerivedLayout =
3080 Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
3081 ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
3082 DerivedLayout.getVBPtrOffset().getQuantity();
3083 ReturnAdjustment.Virtual.Microsoft.VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003084 VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
3085 ReturnAdjustmentOffset.VirtualBase);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003086 }
3087 }
3088
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003089 AddMethod(FinalOverriderMD,
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003090 ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
3091 ForceReturnAdjustmentMangling ? MD : nullptr));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003092 }
3093}
3094
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003095static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
Benjamin Kramera37e7652015-07-25 17:10:49 +00003096 for (const CXXRecordDecl *Elem :
3097 llvm::make_range(Path.rbegin(), Path.rend())) {
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003098 Out << "'";
Benjamin Kramera37e7652015-07-25 17:10:49 +00003099 Elem->printQualifiedName(Out);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003100 Out << "' in ";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003101 }
3102}
3103
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003104static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
3105 bool ContinueFirstLine) {
3106 const ReturnAdjustment &R = TI.Return;
3107 bool Multiline = false;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003108 const char *LinePrefix = "\n ";
3109 if (!R.isEmpty() || TI.Method) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003110 if (!ContinueFirstLine)
3111 Out << LinePrefix;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003112 Out << "[return adjustment (to type '"
3113 << TI.Method->getReturnType().getCanonicalType().getAsString()
3114 << "'): ";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003115 if (R.Virtual.Microsoft.VBPtrOffset)
3116 Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
3117 if (R.Virtual.Microsoft.VBIndex)
3118 Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
3119 Out << R.NonVirtual << " non-virtual]";
3120 Multiline = true;
3121 }
3122
3123 const ThisAdjustment &T = TI.This;
3124 if (!T.isEmpty()) {
3125 if (Multiline || !ContinueFirstLine)
3126 Out << LinePrefix;
3127 Out << "[this adjustment: ";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003128 if (!TI.This.Virtual.isEmpty()) {
3129 assert(T.Virtual.Microsoft.VtordispOffset < 0);
3130 Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
3131 if (T.Virtual.Microsoft.VBPtrOffset) {
3132 Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003133 << " to the left,";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003134 assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
3135 Out << LinePrefix << " vboffset at "
3136 << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
3137 }
3138 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003139 Out << T.NonVirtual << " non-virtual]";
3140 }
3141}
3142
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003143void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3144 Out << "VFTable for ";
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003145 PrintBasePath(WhichVFPtr.PathToIntroducingObject, Out);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003146 Out << "'";
3147 MostDerivedClass->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003148 Out << "' (" << Components.size()
3149 << (Components.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003150
3151 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3152 Out << llvm::format("%4d | ", I);
3153
3154 const VTableComponent &Component = Components[I];
3155
3156 // Dump the component.
3157 switch (Component.getKind()) {
3158 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003159 Component.getRTTIDecl()->printQualifiedName(Out);
3160 Out << " RTTI";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003161 break;
3162
3163 case VTableComponent::CK_FunctionPointer: {
3164 const CXXMethodDecl *MD = Component.getFunctionDecl();
3165
Reid Kleckner604c8b42013-12-27 19:43:59 +00003166 // FIXME: Figure out how to print the real thunk type, since they can
3167 // differ in the return type.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003168 std::string Str = PredefinedExpr::ComputeName(
3169 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3170 Out << Str;
3171 if (MD->isPure())
3172 Out << " [pure]";
3173
David Majnemerd59becb2014-09-12 04:38:08 +00003174 if (MD->isDeleted())
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003175 Out << " [deleted]";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003176
3177 ThunkInfo Thunk = VTableThunks.lookup(I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003178 if (!Thunk.isEmpty())
3179 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003180
3181 break;
3182 }
3183
3184 case VTableComponent::CK_DeletingDtorPointer: {
3185 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3186
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003187 DD->printQualifiedName(Out);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003188 Out << "() [scalar deleting]";
3189
3190 if (DD->isPure())
3191 Out << " [pure]";
3192
3193 ThunkInfo Thunk = VTableThunks.lookup(I);
3194 if (!Thunk.isEmpty()) {
3195 assert(Thunk.Return.isEmpty() &&
3196 "No return adjustment needed for destructors!");
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003197 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003198 }
3199
3200 break;
3201 }
3202
3203 default:
3204 DiagnosticsEngine &Diags = Context.getDiagnostics();
3205 unsigned DiagID = Diags.getCustomDiagID(
3206 DiagnosticsEngine::Error,
3207 "Unexpected vftable component type %0 for component number %1");
3208 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3209 << I << Component.getKind();
3210 }
3211
3212 Out << '\n';
3213 }
3214
3215 Out << '\n';
3216
3217 if (!Thunks.empty()) {
3218 // We store the method names in a map to get a stable order.
3219 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3220
Benjamin Kramera37e7652015-07-25 17:10:49 +00003221 for (const auto &I : Thunks) {
3222 const CXXMethodDecl *MD = I.first;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003223 std::string MethodName = PredefinedExpr::ComputeName(
3224 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3225
3226 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3227 }
3228
Benjamin Kramera37e7652015-07-25 17:10:49 +00003229 for (const auto &MethodNameAndDecl : MethodNamesAndDecls) {
3230 const std::string &MethodName = MethodNameAndDecl.first;
3231 const CXXMethodDecl *MD = MethodNameAndDecl.second;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003232
3233 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Fangrui Song899d1392019-04-24 14:43:05 +00003234 llvm::stable_sort(ThunksVector, [](const ThunkInfo &LHS,
3235 const ThunkInfo &RHS) {
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003236 // Keep different thunks with the same adjustments in the order they
3237 // were put into the vector.
Benjamin Kramera741b8c2014-03-03 20:26:46 +00003238 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003239 });
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003240
3241 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3242 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3243
3244 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3245 const ThunkInfo &Thunk = ThunksVector[I];
3246
3247 Out << llvm::format("%4d | ", I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003248 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003249 Out << '\n';
3250 }
3251
3252 Out << '\n';
3253 }
3254 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003255
3256 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003257}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003258
Reid Kleckner5f080942014-01-03 23:42:00 +00003259static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
Craig Topper3cb91b22014-08-27 06:28:16 +00003260 ArrayRef<const CXXRecordDecl *> B) {
Benjamin Kramera37e7652015-07-25 17:10:49 +00003261 for (const CXXRecordDecl *Decl : B) {
3262 if (A.count(Decl))
Reid Kleckner5f080942014-01-03 23:42:00 +00003263 return true;
3264 }
3265 return false;
3266}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003267
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003268static bool rebucketPaths(VPtrInfoVector &Paths);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003269
Reid Kleckner5f080942014-01-03 23:42:00 +00003270/// Produces MSVC-compatible vbtable data. The symbols produced by this
3271/// algorithm match those produced by MSVC 2012 and newer, which is different
3272/// from MSVC 2010.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003273///
3274/// MSVC 2012 appears to minimize the vbtable names using the following
3275/// algorithm. First, walk the class hierarchy in the usual order, depth first,
3276/// left to right, to find all of the subobjects which contain a vbptr field.
3277/// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3278/// record with a vbptr creates an initially empty path.
3279///
3280/// To combine paths from child nodes, the paths are compared to check for
3281/// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3282/// components in the same order. Each group of ambiguous paths is extended by
3283/// appending the class of the base from which it came. If the current class
3284/// node produced an ambiguous path, its path is extended with the current class.
3285/// After extending paths, MSVC again checks for ambiguity, and extends any
3286/// ambiguous path which wasn't already extended. Because each node yields an
3287/// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3288/// to produce an unambiguous set of paths.
3289///
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003290/// TODO: Presumably vftables use the same algorithm.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003291void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3292 const CXXRecordDecl *RD,
3293 VPtrInfoVector &Paths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003294 assert(Paths.empty());
3295 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003296
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003297 // Base case: this subobject has its own vptr.
3298 if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003299 Paths.push_back(std::make_unique<VPtrInfo>(RD));
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003300
Reid Kleckner5f080942014-01-03 23:42:00 +00003301 // Recursive case: get all the vbtables from our bases and remove anything
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003302 // that shares a virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003303 llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003304 for (const auto &B : RD->bases()) {
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003305 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
3306 if (B.isVirtual() && VBasesSeen.count(Base))
Reid Kleckner5f080942014-01-03 23:42:00 +00003307 continue;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003308
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003309 if (!Base->isDynamicClass())
3310 continue;
Reid Kleckner5f080942014-01-03 23:42:00 +00003311
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003312 const VPtrInfoVector &BasePaths =
3313 ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3314
Justin Lebar562914e2016-10-10 16:26:29 +00003315 for (const std::unique_ptr<VPtrInfo> &BaseInfo : BasePaths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003316 // Don't include the path if it goes through a virtual base that we've
3317 // already included.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003318 if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
Reid Kleckner5f080942014-01-03 23:42:00 +00003319 continue;
3320
3321 // Copy the path and adjust it as necessary.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003322 auto P = std::make_unique<VPtrInfo>(*BaseInfo);
Reid Kleckner5f080942014-01-03 23:42:00 +00003323
3324 // We mangle Base into the path if the path would've been ambiguous and it
3325 // wasn't already extended with Base.
3326 if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3327 P->NextBaseToMangle = Base;
3328
Reid Klecknerfd385402014-04-17 22:47:52 +00003329 // Keep track of which vtable the derived class is going to extend with
3330 // new methods or bases. We append to either the vftable of our primary
3331 // base, or the first non-virtual base that has a vbtable.
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003332 if (P->ObjectWithVPtr == Base &&
Reid Klecknerfd385402014-04-17 22:47:52 +00003333 Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003334 : Layout.getPrimaryBase()))
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003335 P->ObjectWithVPtr = RD;
Reid Klecknerfd385402014-04-17 22:47:52 +00003336
3337 // Keep track of the full adjustment from the MDC to this vtable. The
3338 // adjustment is captured by an optional vbase and a non-virtual offset.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003339 if (B.isVirtual())
Reid Kleckner5f080942014-01-03 23:42:00 +00003340 P->ContainingVBases.push_back(Base);
3341 else if (P->ContainingVBases.empty())
3342 P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3343
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003344 // Update the full offset in the MDC.
3345 P->FullOffsetInMDC = P->NonVirtualOffset;
3346 if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3347 P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3348
Justin Lebar562914e2016-10-10 16:26:29 +00003349 Paths.push_back(std::move(P));
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003350 }
3351
Timur Iskhodzhanov9ae7d3b2014-03-31 11:01:51 +00003352 if (B.isVirtual())
3353 VBasesSeen.insert(Base);
3354
Reid Kleckner5f080942014-01-03 23:42:00 +00003355 // After visiting any direct base, we've transitively visited all of its
3356 // morally virtual bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003357 for (const auto &VB : Base->vbases())
3358 VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003359 }
3360
Reid Kleckner5f080942014-01-03 23:42:00 +00003361 // Sort the paths into buckets, and if any of them are ambiguous, extend all
3362 // paths in ambiguous buckets.
3363 bool Changed = true;
3364 while (Changed)
3365 Changed = rebucketPaths(Paths);
3366}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003367
Justin Lebar562914e2016-10-10 16:26:29 +00003368static bool extendPath(VPtrInfo &P) {
3369 if (P.NextBaseToMangle) {
3370 P.MangledPath.push_back(P.NextBaseToMangle);
3371 P.NextBaseToMangle = nullptr;// Prevent the path from being extended twice.
Reid Kleckner5f080942014-01-03 23:42:00 +00003372 return true;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003373 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003374 return false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003375}
3376
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003377static bool rebucketPaths(VPtrInfoVector &Paths) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003378 // What we're essentially doing here is bucketing together ambiguous paths.
3379 // Any bucket with more than one path in it gets extended by NextBase, which
3380 // is usually the direct base of the inherited the vbptr. This code uses a
3381 // sorted vector to implement a multiset to form the buckets. Note that the
3382 // ordering is based on pointers, but it doesn't change our output order. The
3383 // current algorithm is designed to match MSVC 2012's names.
Justin Lebar76d4def2016-10-10 19:26:22 +00003384 llvm::SmallVector<std::reference_wrapper<VPtrInfo>, 2> PathsSorted;
3385 PathsSorted.reserve(Paths.size());
3386 for (auto& P : Paths)
3387 PathsSorted.push_back(*P);
Fangrui Song55fab262018-09-26 22:16:28 +00003388 llvm::sort(PathsSorted, [](const VPtrInfo &LHS, const VPtrInfo &RHS) {
Justin Lebar562914e2016-10-10 16:26:29 +00003389 return LHS.MangledPath < RHS.MangledPath;
Benjamin Kramer15ae7832014-03-07 21:35:40 +00003390 });
Reid Kleckner5f080942014-01-03 23:42:00 +00003391 bool Changed = false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003392 for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3393 // Scan forward to find the end of the bucket.
3394 size_t BucketStart = I;
3395 do {
3396 ++I;
Justin Lebar562914e2016-10-10 16:26:29 +00003397 } while (I != E &&
3398 PathsSorted[BucketStart].get().MangledPath ==
3399 PathsSorted[I].get().MangledPath);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003400
3401 // If this bucket has multiple paths, extend them all.
3402 if (I - BucketStart > 1) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003403 for (size_t II = BucketStart; II != I; ++II)
Reid Kleckner5f080942014-01-03 23:42:00 +00003404 Changed |= extendPath(PathsSorted[II]);
3405 assert(Changed && "no paths were extended to fix ambiguity");
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003406 }
3407 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003408 return Changed;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003409}
3410
Justin Lebar03b06202016-10-10 16:26:36 +00003411MicrosoftVTableContext::~MicrosoftVTableContext() {}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003412
David Majnemerab130922015-05-04 18:47:54 +00003413namespace {
3414typedef llvm::SetVector<BaseSubobject, std::vector<BaseSubobject>,
3415 llvm::DenseSet<BaseSubobject>> FullPathTy;
3416}
3417
3418// This recursive function finds all paths from a subobject centered at
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003419// (RD, Offset) to the subobject located at IntroducingObject.
David Majnemerab130922015-05-04 18:47:54 +00003420static void findPathsToSubobject(ASTContext &Context,
3421 const ASTRecordLayout &MostDerivedLayout,
3422 const CXXRecordDecl *RD, CharUnits Offset,
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003423 BaseSubobject IntroducingObject,
David Majnemerab130922015-05-04 18:47:54 +00003424 FullPathTy &FullPath,
3425 std::list<FullPathTy> &Paths) {
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003426 if (BaseSubobject(RD, Offset) == IntroducingObject) {
David Majnemerab130922015-05-04 18:47:54 +00003427 Paths.push_back(FullPath);
3428 return;
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003429 }
3430
3431 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3432
David Majnemerab130922015-05-04 18:47:54 +00003433 for (const CXXBaseSpecifier &BS : RD->bases()) {
David Majnemeread97572015-05-01 21:35:41 +00003434 const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
David Majnemerab130922015-05-04 18:47:54 +00003435 CharUnits NewOffset = BS.isVirtual()
3436 ? MostDerivedLayout.getVBaseClassOffset(Base)
3437 : Offset + Layout.getBaseClassOffset(Base);
3438 FullPath.insert(BaseSubobject(Base, NewOffset));
3439 findPathsToSubobject(Context, MostDerivedLayout, Base, NewOffset,
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003440 IntroducingObject, FullPath, Paths);
David Majnemerab130922015-05-04 18:47:54 +00003441 FullPath.pop_back();
3442 }
3443}
David Majnemerd950f152015-04-30 17:15:48 +00003444
David Majnemerab130922015-05-04 18:47:54 +00003445// Return the paths which are not subsets of other paths.
3446static void removeRedundantPaths(std::list<FullPathTy> &FullPaths) {
3447 FullPaths.remove_if([&](const FullPathTy &SpecificPath) {
3448 for (const FullPathTy &OtherPath : FullPaths) {
3449 if (&SpecificPath == &OtherPath)
David Majnemer70e6a002015-05-01 21:35:45 +00003450 continue;
Fangrui Song3117b172018-10-20 17:53:42 +00003451 if (llvm::all_of(SpecificPath, [&](const BaseSubobject &BSO) {
3452 return OtherPath.count(BSO) != 0;
3453 })) {
David Majnemerab130922015-05-04 18:47:54 +00003454 return true;
David Majnemer70e6a002015-05-01 21:35:45 +00003455 }
David Majnemerd950f152015-04-30 17:15:48 +00003456 }
David Majnemerab130922015-05-04 18:47:54 +00003457 return false;
3458 });
3459}
3460
3461static CharUnits getOffsetOfFullPath(ASTContext &Context,
3462 const CXXRecordDecl *RD,
3463 const FullPathTy &FullPath) {
3464 const ASTRecordLayout &MostDerivedLayout =
3465 Context.getASTRecordLayout(RD);
3466 CharUnits Offset = CharUnits::fromQuantity(-1);
3467 for (const BaseSubobject &BSO : FullPath) {
3468 const CXXRecordDecl *Base = BSO.getBase();
3469 // The first entry in the path is always the most derived record, skip it.
3470 if (Base == RD) {
3471 assert(Offset.getQuantity() == -1);
3472 Offset = CharUnits::Zero();
3473 continue;
3474 }
3475 assert(Offset.getQuantity() != -1);
3476 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3477 // While we know which base has to be traversed, we don't know if that base
3478 // was a virtual base.
3479 const CXXBaseSpecifier *BaseBS = std::find_if(
3480 RD->bases_begin(), RD->bases_end(), [&](const CXXBaseSpecifier &BS) {
3481 return BS.getType()->getAsCXXRecordDecl() == Base;
3482 });
3483 Offset = BaseBS->isVirtual() ? MostDerivedLayout.getVBaseClassOffset(Base)
3484 : Offset + Layout.getBaseClassOffset(Base);
3485 RD = Base;
David Majnemerd950f152015-04-30 17:15:48 +00003486 }
David Majnemerab130922015-05-04 18:47:54 +00003487 return Offset;
3488}
David Majnemeread97572015-05-01 21:35:41 +00003489
David Majnemerab130922015-05-04 18:47:54 +00003490// We want to select the path which introduces the most covariant overrides. If
3491// two paths introduce overrides which the other path doesn't contain, issue a
3492// diagnostic.
3493static const FullPathTy *selectBestPath(ASTContext &Context,
Justin Lebar562914e2016-10-10 16:26:29 +00003494 const CXXRecordDecl *RD,
3495 const VPtrInfo &Info,
David Majnemerab130922015-05-04 18:47:54 +00003496 std::list<FullPathTy> &FullPaths) {
David Majnemere48630f2015-05-05 01:39:20 +00003497 // Handle some easy cases first.
3498 if (FullPaths.empty())
3499 return nullptr;
3500 if (FullPaths.size() == 1)
3501 return &FullPaths.front();
3502
David Majnemerab130922015-05-04 18:47:54 +00003503 const FullPathTy *BestPath = nullptr;
3504 typedef std::set<const CXXMethodDecl *> OverriderSetTy;
3505 OverriderSetTy LastOverrides;
3506 for (const FullPathTy &SpecificPath : FullPaths) {
David Majnemere48630f2015-05-05 01:39:20 +00003507 assert(!SpecificPath.empty());
David Majnemerab130922015-05-04 18:47:54 +00003508 OverriderSetTy CurrentOverrides;
3509 const CXXRecordDecl *TopLevelRD = SpecificPath.begin()->getBase();
3510 // Find the distance from the start of the path to the subobject with the
3511 // VPtr.
3512 CharUnits BaseOffset =
3513 getOffsetOfFullPath(Context, TopLevelRD, SpecificPath);
3514 FinalOverriders Overriders(TopLevelRD, CharUnits::Zero(), TopLevelRD);
Justin Lebar562914e2016-10-10 16:26:29 +00003515 for (const CXXMethodDecl *MD : Info.IntroducingObject->methods()) {
David Majnemerab130922015-05-04 18:47:54 +00003516 if (!MD->isVirtual())
3517 continue;
3518 FinalOverriders::OverriderInfo OI =
3519 Overriders.getOverrider(MD->getCanonicalDecl(), BaseOffset);
David Majnemere48630f2015-05-05 01:39:20 +00003520 const CXXMethodDecl *OverridingMethod = OI.Method;
David Majnemerab130922015-05-04 18:47:54 +00003521 // Only overriders which have a return adjustment introduce problematic
3522 // thunks.
David Majnemere48630f2015-05-05 01:39:20 +00003523 if (ComputeReturnAdjustmentBaseOffset(Context, OverridingMethod, MD)
3524 .isEmpty())
David Majnemerab130922015-05-04 18:47:54 +00003525 continue;
3526 // It's possible that the overrider isn't in this path. If so, skip it
3527 // because this path didn't introduce it.
David Majnemere48630f2015-05-05 01:39:20 +00003528 const CXXRecordDecl *OverridingParent = OverridingMethod->getParent();
Fangrui Song3117b172018-10-20 17:53:42 +00003529 if (llvm::none_of(SpecificPath, [&](const BaseSubobject &BSO) {
3530 return BSO.getBase() == OverridingParent;
3531 }))
David Majnemerab130922015-05-04 18:47:54 +00003532 continue;
David Majnemere48630f2015-05-05 01:39:20 +00003533 CurrentOverrides.insert(OverridingMethod);
David Majnemerab130922015-05-04 18:47:54 +00003534 }
3535 OverriderSetTy NewOverrides =
3536 llvm::set_difference(CurrentOverrides, LastOverrides);
3537 if (NewOverrides.empty())
3538 continue;
3539 OverriderSetTy MissingOverrides =
3540 llvm::set_difference(LastOverrides, CurrentOverrides);
3541 if (MissingOverrides.empty()) {
3542 // This path is a strict improvement over the last path, let's use it.
3543 BestPath = &SpecificPath;
3544 std::swap(CurrentOverrides, LastOverrides);
3545 } else {
3546 // This path introduces an overrider with a conflicting covariant thunk.
3547 DiagnosticsEngine &Diags = Context.getDiagnostics();
3548 const CXXMethodDecl *CovariantMD = *NewOverrides.begin();
3549 const CXXMethodDecl *ConflictMD = *MissingOverrides.begin();
3550 Diags.Report(RD->getLocation(), diag::err_vftable_ambiguous_component)
3551 << RD;
3552 Diags.Report(CovariantMD->getLocation(), diag::note_covariant_thunk)
3553 << CovariantMD;
3554 Diags.Report(ConflictMD->getLocation(), diag::note_covariant_thunk)
3555 << ConflictMD;
3556 }
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003557 }
David Majnemere48630f2015-05-05 01:39:20 +00003558 // Go with the path that introduced the most covariant overrides. If there is
3559 // no such path, pick the first path.
3560 return BestPath ? BestPath : &FullPaths.front();
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003561}
3562
3563static void computeFullPathsForVFTables(ASTContext &Context,
3564 const CXXRecordDecl *RD,
3565 VPtrInfoVector &Paths) {
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003566 const ASTRecordLayout &MostDerivedLayout = Context.getASTRecordLayout(RD);
David Majnemerab130922015-05-04 18:47:54 +00003567 FullPathTy FullPath;
3568 std::list<FullPathTy> FullPaths;
Justin Lebar562914e2016-10-10 16:26:29 +00003569 for (const std::unique_ptr<VPtrInfo>& Info : Paths) {
David Majnemerab130922015-05-04 18:47:54 +00003570 findPathsToSubobject(
3571 Context, MostDerivedLayout, RD, CharUnits::Zero(),
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003572 BaseSubobject(Info->IntroducingObject, Info->FullOffsetInMDC), FullPath,
David Majnemerab130922015-05-04 18:47:54 +00003573 FullPaths);
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003574 FullPath.clear();
David Majnemerab130922015-05-04 18:47:54 +00003575 removeRedundantPaths(FullPaths);
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003576 Info->PathToIntroducingObject.clear();
David Majnemerab130922015-05-04 18:47:54 +00003577 if (const FullPathTy *BestPath =
Justin Lebar562914e2016-10-10 16:26:29 +00003578 selectBestPath(Context, RD, *Info, FullPaths))
David Majnemerab130922015-05-04 18:47:54 +00003579 for (const BaseSubobject &BSO : *BestPath)
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003580 Info->PathToIntroducingObject.push_back(BSO.getBase());
David Majnemerab130922015-05-04 18:47:54 +00003581 FullPaths.clear();
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003582 }
3583}
3584
Reid Klecknercbec0262018-04-02 20:00:39 +00003585static bool vfptrIsEarlierInMDC(const ASTRecordLayout &Layout,
3586 const MethodVFTableLocation &LHS,
3587 const MethodVFTableLocation &RHS) {
Reid Klecknereed88202018-03-28 18:23:35 +00003588 CharUnits L = LHS.VFPtrOffset;
3589 CharUnits R = RHS.VFPtrOffset;
3590 if (LHS.VBase)
3591 L += Layout.getVBaseClassOffset(LHS.VBase);
3592 if (RHS.VBase)
3593 R += Layout.getVBaseClassOffset(RHS.VBase);
3594 return L < R;
3595}
3596
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003597void MicrosoftVTableContext::computeVTableRelatedInformation(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003598 const CXXRecordDecl *RD) {
3599 assert(RD->isDynamicClass());
3600
3601 // Check if we've computed this information before.
3602 if (VFPtrLocations.count(RD))
3603 return;
3604
3605 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3606
Justin Lebar562914e2016-10-10 16:26:29 +00003607 {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003608 auto VFPtrs = std::make_unique<VPtrInfoVector>();
Reid Klecknercbec0262018-04-02 20:00:39 +00003609 computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3610 computeFullPathsForVFTables(Context, RD, *VFPtrs);
Justin Lebar562914e2016-10-10 16:26:29 +00003611 VFPtrLocations[RD] = std::move(VFPtrs);
3612 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003613
3614 MethodVFTableLocationsTy NewMethodLocations;
Reid Klecknercbec0262018-04-02 20:00:39 +00003615 for (const std::unique_ptr<VPtrInfo> &VFPtr : *VFPtrLocations[RD]) {
Justin Lebar562914e2016-10-10 16:26:29 +00003616 VFTableBuilder Builder(*this, RD, *VFPtr);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003617
Benjamin Kramera37e7652015-07-25 17:10:49 +00003618 VFTableIdTy id(RD, VFPtr->FullOffsetInMDC);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003619 assert(VFTableLayouts.count(id) == 0);
3620 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3621 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003622 VFTableLayouts[id] = std::make_unique<VTableLayout>(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00003623 ArrayRef<size_t>{0}, Builder.vtable_components(), VTableThunks,
3624 EmptyAddressPointsMap);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003625 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00003626
Reid Klecknereed88202018-03-28 18:23:35 +00003627 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003628 for (const auto &Loc : Builder.vtable_locations()) {
Reid Klecknereed88202018-03-28 18:23:35 +00003629 auto Insert = NewMethodLocations.insert(Loc);
3630 if (!Insert.second) {
3631 const MethodVFTableLocation &NewLoc = Loc.second;
3632 MethodVFTableLocation &OldLoc = Insert.first->second;
3633 if (vfptrIsEarlierInMDC(Layout, NewLoc, OldLoc))
3634 OldLoc = NewLoc;
3635 }
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00003636 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003637 }
3638
3639 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3640 NewMethodLocations.end());
3641 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00003642 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003643}
3644
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003645void MicrosoftVTableContext::dumpMethodLocations(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003646 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3647 raw_ostream &Out) {
3648 // Compute the vtable indices for all the member functions.
3649 // Store them in a map keyed by the location so we'll get a sorted table.
3650 std::map<MethodVFTableLocation, std::string> IndicesMap;
3651 bool HasNonzeroOffset = false;
3652
Benjamin Kramera37e7652015-07-25 17:10:49 +00003653 for (const auto &I : NewMethods) {
3654 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I.first.getDecl());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003655 assert(MD->isVirtual());
3656
3657 std::string MethodName = PredefinedExpr::ComputeName(
3658 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3659
3660 if (isa<CXXDestructorDecl>(MD)) {
Benjamin Kramera37e7652015-07-25 17:10:49 +00003661 IndicesMap[I.second] = MethodName + " [scalar deleting]";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003662 } else {
Benjamin Kramera37e7652015-07-25 17:10:49 +00003663 IndicesMap[I.second] = MethodName;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003664 }
3665
Benjamin Kramera37e7652015-07-25 17:10:49 +00003666 if (!I.second.VFPtrOffset.isZero() || I.second.VBTableIndex != 0)
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003667 HasNonzeroOffset = true;
3668 }
3669
3670 // Print the vtable indices for all the member functions.
3671 if (!IndicesMap.empty()) {
3672 Out << "VFTable indices for ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003673 Out << "'";
3674 RD->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003675 Out << "' (" << IndicesMap.size()
3676 << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003677
3678 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3679 uint64_t LastVBIndex = 0;
Benjamin Kramera37e7652015-07-25 17:10:49 +00003680 for (const auto &I : IndicesMap) {
3681 CharUnits VFPtrOffset = I.first.VFPtrOffset;
3682 uint64_t VBIndex = I.first.VBTableIndex;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003683 if (HasNonzeroOffset &&
3684 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3685 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3686 Out << " -- accessible via ";
3687 if (VBIndex)
3688 Out << "vbtable index " << VBIndex << ", ";
3689 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3690 LastVFPtrOffset = VFPtrOffset;
3691 LastVBIndex = VBIndex;
3692 }
3693
Benjamin Kramera37e7652015-07-25 17:10:49 +00003694 uint64_t VTableIndex = I.first.Index;
3695 const std::string &MethodName = I.second;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003696 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3697 }
3698 Out << '\n';
3699 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003700
3701 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003702}
3703
Justin Lebar03b06202016-10-10 16:26:36 +00003704const VirtualBaseInfo &MicrosoftVTableContext::computeVBTableRelatedInformation(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003705 const CXXRecordDecl *RD) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003706 VirtualBaseInfo *VBI;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003707
Reid Kleckner5f080942014-01-03 23:42:00 +00003708 {
3709 // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
3710 // as it may be modified and rehashed under us.
Justin Lebar03b06202016-10-10 16:26:36 +00003711 std::unique_ptr<VirtualBaseInfo> &Entry = VBaseInfo[RD];
Reid Kleckner5f080942014-01-03 23:42:00 +00003712 if (Entry)
Justin Lebar03b06202016-10-10 16:26:36 +00003713 return *Entry;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003714 Entry = std::make_unique<VirtualBaseInfo>();
Justin Lebar03b06202016-10-10 16:26:36 +00003715 VBI = Entry.get();
Reid Kleckner5f080942014-01-03 23:42:00 +00003716 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003717
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003718 computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003719
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003720 // First, see if the Derived class shared the vbptr with a non-virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003721 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003722 if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003723 // If the Derived class shares the vbptr with a non-virtual base, the shared
3724 // virtual bases come first so that the layout is the same.
Justin Lebar03b06202016-10-10 16:26:36 +00003725 const VirtualBaseInfo &BaseInfo =
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003726 computeVBTableRelatedInformation(VBPtrBase);
Justin Lebar03b06202016-10-10 16:26:36 +00003727 VBI->VBTableIndices.insert(BaseInfo.VBTableIndices.begin(),
3728 BaseInfo.VBTableIndices.end());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003729 }
3730
3731 // New vbases are added to the end of the vbtable.
3732 // Skip the self entry and vbases visited in the non-virtual base, if any.
Reid Kleckner5f080942014-01-03 23:42:00 +00003733 unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003734 for (const auto &VB : RD->vbases()) {
3735 const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
Reid Kleckner5f080942014-01-03 23:42:00 +00003736 if (!VBI->VBTableIndices.count(CurVBase))
3737 VBI->VBTableIndices[CurVBase] = VBTableIndex++;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003738 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003739
Justin Lebar03b06202016-10-10 16:26:36 +00003740 return *VBI;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003741}
3742
3743unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3744 const CXXRecordDecl *VBase) {
Justin Lebar03b06202016-10-10 16:26:36 +00003745 const VirtualBaseInfo &VBInfo = computeVBTableRelatedInformation(Derived);
3746 assert(VBInfo.VBTableIndices.count(VBase));
3747 return VBInfo.VBTableIndices.find(VBase)->second;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003748}
3749
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003750const VPtrInfoVector &
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003751MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
Justin Lebar03b06202016-10-10 16:26:36 +00003752 return computeVBTableRelatedInformation(RD).VBPtrPaths;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003753}
3754
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003755const VPtrInfoVector &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003756MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003757 computeVTableRelatedInformation(RD);
3758
3759 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
Reid Klecknercbec0262018-04-02 20:00:39 +00003760 return *VFPtrLocations[RD];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003761}
3762
3763const VTableLayout &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003764MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3765 CharUnits VFPtrOffset) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003766 computeVTableRelatedInformation(RD);
3767
3768 VFTableIdTy id(RD, VFPtrOffset);
3769 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3770 return *VFTableLayouts[id];
3771}
3772
Reid Klecknercbec0262018-04-02 20:00:39 +00003773MethodVFTableLocation
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003774MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003775 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3776 "Only use this method for virtual methods or dtors");
3777 if (isa<CXXDestructorDecl>(GD.getDecl()))
3778 assert(GD.getDtorType() == Dtor_Deleting);
3779
Reid Kleckner138ab492018-05-17 18:12:18 +00003780 GD = GD.getCanonicalDecl();
3781
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003782 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3783 if (I != MethodVFTableLocations.end())
3784 return I->second;
3785
3786 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3787
3788 computeVTableRelatedInformation(RD);
3789
3790 I = MethodVFTableLocations.find(GD);
3791 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3792 return I->second;
3793}