blob: 527ee8efc30a88834aebfe6294ac9e4ee1fd8200 [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) {
273 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
274 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<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:
538 /// MostDerivedClass - The most derived class for which we're building vcall
539 /// and vbase offsets.
540 const CXXRecordDecl *MostDerivedClass;
Fangrui Song6907ce22018-07-30 19:24:48 +0000541
542 /// LayoutClass - The class we're using for layout information. Will be
Peter Collingbournecfd23562011-09-26 01:57:12 +0000543 /// different than the most derived class if we're building a construction
544 /// vtable.
545 const CXXRecordDecl *LayoutClass;
Fangrui Song6907ce22018-07-30 19:24:48 +0000546
Peter Collingbournecfd23562011-09-26 01:57:12 +0000547 /// Context - The ASTContext which we will use for layout information.
548 ASTContext &Context;
549
550 /// Components - vcall and vbase offset components
551 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
552 VTableComponentVectorTy Components;
Fangrui Song6907ce22018-07-30 19:24:48 +0000553
Peter Collingbournecfd23562011-09-26 01:57:12 +0000554 /// VisitedVirtualBases - Visited virtual bases.
555 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Fangrui Song6907ce22018-07-30 19:24:48 +0000556
Peter Collingbournecfd23562011-09-26 01:57:12 +0000557 /// VCallOffsets - Keeps track of vcall offsets.
558 VCallOffsetMap VCallOffsets;
559
560
561 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
562 /// relative to the address point.
563 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
Fangrui Song6907ce22018-07-30 19:24:48 +0000564
Peter Collingbournecfd23562011-09-26 01:57:12 +0000565 /// FinalOverriders - The final overriders of the most derived class.
566 /// (Can be null when we're not building a vtable of the most derived class).
567 const FinalOverriders *Overriders;
568
569 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
570 /// given base subobject.
571 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
572 CharUnits RealBaseOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000573
Peter Collingbournecfd23562011-09-26 01:57:12 +0000574 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
575 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000576
Peter Collingbournecfd23562011-09-26 01:57:12 +0000577 /// AddVBaseOffsets - Add vbase offsets for the given class.
Fangrui Song6907ce22018-07-30 19:24:48 +0000578 void AddVBaseOffsets(const CXXRecordDecl *Base,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000579 CharUnits OffsetInLayoutClass);
Fangrui Song6907ce22018-07-30 19:24:48 +0000580
Peter Collingbournecfd23562011-09-26 01:57:12 +0000581 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
582 /// chars, relative to the vtable address point.
583 CharUnits getCurrentOffsetOffset() const;
Fangrui Song6907ce22018-07-30 19:24:48 +0000584
Peter Collingbournecfd23562011-09-26 01:57:12 +0000585public:
586 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
587 const CXXRecordDecl *LayoutClass,
588 const FinalOverriders *Overriders,
589 BaseSubobject Base, bool BaseIsVirtual,
590 CharUnits OffsetInLayoutClass)
Fangrui Song6907ce22018-07-30 19:24:48 +0000591 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000592 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000593
Peter Collingbournecfd23562011-09-26 01:57:12 +0000594 // Add vcall and vbase offsets.
595 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
596 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000597
Peter Collingbournecfd23562011-09-26 01:57:12 +0000598 /// Methods for iterating over the components.
599 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
600 const_iterator components_begin() const { return Components.rbegin(); }
601 const_iterator components_end() const { return Components.rend(); }
Fangrui Song6907ce22018-07-30 19:24:48 +0000602
Peter Collingbournecfd23562011-09-26 01:57:12 +0000603 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
604 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
605 return VBaseOffsetOffsets;
606 }
607};
Fangrui Song6907ce22018-07-30 19:24:48 +0000608
609void
Peter Collingbournecfd23562011-09-26 01:57:12 +0000610VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
611 bool BaseIsVirtual,
612 CharUnits RealBaseOffset) {
613 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
Fangrui Song6907ce22018-07-30 19:24:48 +0000614
Peter Collingbournecfd23562011-09-26 01:57:12 +0000615 // Itanium C++ ABI 2.5.2:
616 // ..in classes sharing a virtual table with a primary base class, the vcall
617 // and vbase offsets added by the derived class all come before the vcall
618 // and vbase offsets required by the base class, so that the latter may be
619 // laid out as required by the base class without regard to additions from
620 // the derived class(es).
621
622 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
623 // emit them for the primary base first).
624 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
625 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
626
627 CharUnits PrimaryBaseOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +0000628
Peter Collingbournecfd23562011-09-26 01:57:12 +0000629 // Get the base offset of the primary base.
630 if (PrimaryBaseIsVirtual) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000631 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000632 "Primary vbase should have a zero offset!");
Fangrui Song6907ce22018-07-30 19:24:48 +0000633
Peter Collingbournecfd23562011-09-26 01:57:12 +0000634 const ASTRecordLayout &MostDerivedClassLayout =
635 Context.getASTRecordLayout(MostDerivedClass);
Fangrui Song6907ce22018-07-30 19:24:48 +0000636
637 PrimaryBaseOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000638 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
639 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000640 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000641 "Primary base should have a zero offset!");
642
643 PrimaryBaseOffset = Base.getBaseOffset();
644 }
645
646 AddVCallAndVBaseOffsets(
647 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
648 PrimaryBaseIsVirtual, RealBaseOffset);
649 }
650
651 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
652
653 // We only want to add vcall offsets for virtual bases.
654 if (BaseIsVirtual)
655 AddVCallOffsets(Base, RealBaseOffset);
656}
657
658CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
Fangrui Song6907ce22018-07-30 19:24:48 +0000659 // OffsetIndex is the index of this vcall or vbase offset, relative to the
Peter Collingbournecfd23562011-09-26 01:57:12 +0000660 // vtable address point. (We subtract 3 to account for the information just
661 // above the address point, the RTTI info, the offset to top, and the
662 // vcall offset itself).
663 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000664
665 CharUnits PointerWidth =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000666 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
667 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
668 return OffsetOffset;
669}
670
Fangrui Song6907ce22018-07-30 19:24:48 +0000671void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000672 CharUnits VBaseOffset) {
673 const CXXRecordDecl *RD = Base.getBase();
674 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
675
676 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
677
678 // Handle the primary base first.
679 // We only want to add vcall offsets if the base is non-virtual; a virtual
680 // primary base will have its vcall and vbase offsets emitted already.
681 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
682 // Get the base offset of the primary base.
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000683 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000684 "Primary base should have a zero offset!");
685
686 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
687 VBaseOffset);
688 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000689
Peter Collingbournecfd23562011-09-26 01:57:12 +0000690 // Add the vcall offsets.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000691 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000692 if (!MD->isVirtual())
693 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +0000694 MD = MD->getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000695
696 CharUnits OffsetOffset = getCurrentOffsetOffset();
Fangrui Song6907ce22018-07-30 19:24:48 +0000697
Peter Collingbournecfd23562011-09-26 01:57:12 +0000698 // Don't add a vcall offset if we already have one for this member function
699 // signature.
700 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
701 continue;
702
703 CharUnits Offset = CharUnits::Zero();
704
705 if (Overriders) {
706 // Get the final overrider.
Fangrui Song6907ce22018-07-30 19:24:48 +0000707 FinalOverriders::OverriderInfo Overrider =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000708 Overriders->getOverrider(MD, Base.getBaseOffset());
Fangrui Song6907ce22018-07-30 19:24:48 +0000709
710 /// The vcall offset is the offset from the virtual base to the object
Peter Collingbournecfd23562011-09-26 01:57:12 +0000711 /// where the function was overridden.
712 Offset = Overrider.Offset - VBaseOffset;
713 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000714
Peter Collingbournecfd23562011-09-26 01:57:12 +0000715 Components.push_back(
716 VTableComponent::MakeVCallOffset(Offset));
717 }
718
719 // And iterate over all non-virtual bases (ignoring the primary base).
Fangrui Song6907ce22018-07-30 19:24:48 +0000720 for (const auto &B : RD->bases()) {
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000721 if (B.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000722 continue;
723
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000724 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000725 if (BaseDecl == PrimaryBase)
726 continue;
727
728 // Get the base offset of this base.
Fangrui Song6907ce22018-07-30 19:24:48 +0000729 CharUnits BaseOffset = Base.getBaseOffset() +
Peter Collingbournecfd23562011-09-26 01:57:12 +0000730 Layout.getBaseClassOffset(BaseDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +0000731
732 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000733 VBaseOffset);
734 }
735}
736
Fangrui Song6907ce22018-07-30 19:24:48 +0000737void
Peter Collingbournecfd23562011-09-26 01:57:12 +0000738VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
739 CharUnits OffsetInLayoutClass) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000740 const ASTRecordLayout &LayoutClassLayout =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000741 Context.getASTRecordLayout(LayoutClass);
742
743 // Add vbase offsets.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000744 for (const auto &B : RD->bases()) {
745 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000746
747 // Check if this is a virtual base that we haven't visited before.
David Blaikie82e95a32014-11-19 07:49:47 +0000748 if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000749 CharUnits Offset =
Peter Collingbournecfd23562011-09-26 01:57:12 +0000750 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
751
752 // Add the vbase offset offset.
753 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
754 "vbase offset offset already exists!");
755
756 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
757 VBaseOffsetOffsets.insert(
758 std::make_pair(BaseDecl, VBaseOffsetOffset));
759
760 Components.push_back(
761 VTableComponent::MakeVBaseOffset(Offset));
762 }
763
764 // Check the base class looking for more vbase offsets.
765 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
766 }
767}
768
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000769/// ItaniumVTableBuilder - Class for building vtable layout information.
770class ItaniumVTableBuilder {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000771public:
Fangrui Song6907ce22018-07-30 19:24:48 +0000772 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
Peter Collingbournecfd23562011-09-26 01:57:12 +0000773 /// primary bases.
Fangrui Song6907ce22018-07-30 19:24:48 +0000774 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
Peter Collingbournecfd23562011-09-26 01:57:12 +0000775 PrimaryBasesSetVectorTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000776
777 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
Peter Collingbournecfd23562011-09-26 01:57:12 +0000778 VBaseOffsetOffsetsMapTy;
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000779
780 typedef VTableLayout::AddressPointsMapTy AddressPointsMapTy;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000781
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000782 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
783
Peter Collingbournecfd23562011-09-26 01:57:12 +0000784private:
785 /// VTables - Global vtable information.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000786 ItaniumVTableContext &VTables;
Fangrui Song6907ce22018-07-30 19:24:48 +0000787
Peter Collingbournecfd23562011-09-26 01:57:12 +0000788 /// MostDerivedClass - The most derived class for which we're building this
789 /// vtable.
790 const CXXRecordDecl *MostDerivedClass;
791
792 /// MostDerivedClassOffset - If we're building a construction vtable, this
793 /// holds the offset from the layout class to the most derived class.
794 const CharUnits MostDerivedClassOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +0000795
796 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
Peter Collingbournecfd23562011-09-26 01:57:12 +0000797 /// base. (This only makes sense when building a construction vtable).
798 bool MostDerivedClassIsVirtual;
Fangrui Song6907ce22018-07-30 19:24:48 +0000799
800 /// LayoutClass - The class we're using for layout information. Will be
Peter Collingbournecfd23562011-09-26 01:57:12 +0000801 /// different than the most derived class if we're building a construction
802 /// vtable.
803 const CXXRecordDecl *LayoutClass;
Fangrui Song6907ce22018-07-30 19:24:48 +0000804
Peter Collingbournecfd23562011-09-26 01:57:12 +0000805 /// Context - The ASTContext which we will use for layout information.
806 ASTContext &Context;
Fangrui Song6907ce22018-07-30 19:24:48 +0000807
Peter Collingbournecfd23562011-09-26 01:57:12 +0000808 /// FinalOverriders - The final overriders of the most derived class.
809 const FinalOverriders Overriders;
810
811 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
812 /// bases in this vtable.
813 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
814
815 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
816 /// the most derived class.
817 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000818
Peter Collingbournecfd23562011-09-26 01:57:12 +0000819 /// Components - The components of the vtable being built.
820 SmallVector<VTableComponent, 64> Components;
821
822 /// AddressPoints - Address points for the vtable being built.
823 AddressPointsMapTy AddressPoints;
824
825 /// MethodInfo - Contains information about a method in a vtable.
826 /// (Used for computing 'this' pointer adjustment thunks.
827 struct MethodInfo {
828 /// BaseOffset - The base offset of this method.
829 const CharUnits BaseOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +0000830
Peter Collingbournecfd23562011-09-26 01:57:12 +0000831 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
832 /// method.
833 const CharUnits BaseOffsetInLayoutClass;
Fangrui Song6907ce22018-07-30 19:24:48 +0000834
Peter Collingbournecfd23562011-09-26 01:57:12 +0000835 /// VTableIndex - The index in the vtable that this method has.
836 /// (For destructors, this is the index of the complete destructor).
837 const uint64_t VTableIndex;
Fangrui Song6907ce22018-07-30 19:24:48 +0000838
839 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000840 uint64_t VTableIndex)
Fangrui Song6907ce22018-07-30 19:24:48 +0000841 : BaseOffset(BaseOffset),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000842 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
843 VTableIndex(VTableIndex) { }
Fangrui Song6907ce22018-07-30 19:24:48 +0000844
845 MethodInfo()
846 : BaseOffset(CharUnits::Zero()),
847 BaseOffsetInLayoutClass(CharUnits::Zero()),
Peter Collingbournecfd23562011-09-26 01:57:12 +0000848 VTableIndex(0) { }
Serge Gueltonbe885392019-01-20 21:19:56 +0000849
850 MethodInfo(MethodInfo const&) = default;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000851 };
Fangrui Song6907ce22018-07-30 19:24:48 +0000852
Peter Collingbournecfd23562011-09-26 01:57:12 +0000853 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000854
Peter Collingbournecfd23562011-09-26 01:57:12 +0000855 /// MethodInfoMap - The information for all methods in the vtable we're
856 /// currently building.
857 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000858
859 /// MethodVTableIndices - Contains the index (relative to the vtable address
860 /// point) where the function pointer for a virtual function is stored.
861 MethodVTableIndicesTy MethodVTableIndices;
862
Peter Collingbournecfd23562011-09-26 01:57:12 +0000863 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000864
865 /// VTableThunks - The thunks by vtable index in the vtable currently being
Peter Collingbournecfd23562011-09-26 01:57:12 +0000866 /// built.
867 VTableThunksMapTy VTableThunks;
868
869 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
870 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000871
Peter Collingbournecfd23562011-09-26 01:57:12 +0000872 /// Thunks - A map that contains all the thunks needed for all methods in the
873 /// most derived class for which the vtable is currently being built.
874 ThunksMapTy Thunks;
Fangrui Song6907ce22018-07-30 19:24:48 +0000875
Peter Collingbournecfd23562011-09-26 01:57:12 +0000876 /// AddThunk - Add a thunk for the given method.
877 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
Fangrui Song6907ce22018-07-30 19:24:48 +0000878
Peter Collingbournecfd23562011-09-26 01:57:12 +0000879 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
880 /// part of the vtable we're currently building.
881 void ComputeThisAdjustments();
Fangrui Song6907ce22018-07-30 19:24:48 +0000882
Peter Collingbournecfd23562011-09-26 01:57:12 +0000883 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
884
885 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
886 /// some other base.
887 VisitedVirtualBasesSetTy PrimaryVirtualBases;
888
889 /// ComputeReturnAdjustment - Compute the return adjustment given a return
890 /// adjustment base offset.
891 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
Fangrui Song6907ce22018-07-30 19:24:48 +0000892
Peter Collingbournecfd23562011-09-26 01:57:12 +0000893 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
894 /// the 'this' pointer from the base subobject to the derived subobject.
895 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
896 BaseSubobject Derived) const;
897
898 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
899 /// given virtual member function, its offset in the layout class and its
900 /// final overrider.
Fangrui Song6907ce22018-07-30 19:24:48 +0000901 ThisAdjustment
902 ComputeThisAdjustment(const CXXMethodDecl *MD,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000903 CharUnits BaseOffsetInLayoutClass,
904 FinalOverriders::OverriderInfo Overrider);
905
906 /// AddMethod - Add a single virtual member function to the vtable
907 /// components vector.
908 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
909
910 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
Fangrui Song6907ce22018-07-30 19:24:48 +0000911 /// part of the vtable.
Peter Collingbournecfd23562011-09-26 01:57:12 +0000912 ///
913 /// Itanium C++ ABI 2.5.2:
914 ///
915 /// struct A { virtual void f(); };
916 /// struct B : virtual public A { int i; };
917 /// struct C : virtual public A { int j; };
918 /// struct D : public B, public C {};
919 ///
920 /// When B and C are declared, A is a primary base in each case, so although
921 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
922 /// adjustment is required and no thunk is generated. However, inside D
923 /// objects, A is no longer a primary base of C, so if we allowed calls to
924 /// C::f() to use the copy of A's vtable in the C subobject, we would need
Fangrui Song6907ce22018-07-30 19:24:48 +0000925 /// to adjust this from C* to B::A*, which would require a third-party
926 /// thunk. Since we require that a call to C::f() first convert to A*,
927 /// C-in-D's copy of A's vtable is never referenced, so this is not
Peter Collingbournecfd23562011-09-26 01:57:12 +0000928 /// necessary.
929 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
930 CharUnits BaseOffsetInLayoutClass,
931 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
932 CharUnits FirstBaseOffsetInLayoutClass) const;
933
Fangrui Song6907ce22018-07-30 19:24:48 +0000934
Peter Collingbournecfd23562011-09-26 01:57:12 +0000935 /// AddMethods - Add the methods of this base subobject and all its
936 /// primary bases to the vtable components vector.
937 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
938 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
939 CharUnits FirstBaseOffsetInLayoutClass,
940 PrimaryBasesSetVectorTy &PrimaryBases);
941
942 // LayoutVTable - Layout the vtable for the given base class, including its
943 // secondary vtables and any vtables for virtual bases.
944 void LayoutVTable();
945
946 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
947 /// given base subobject, as well as all its secondary vtables.
948 ///
949 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
950 /// or a direct or indirect base of a virtual base.
951 ///
952 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
Fangrui Song6907ce22018-07-30 19:24:48 +0000953 /// in the layout class.
Peter Collingbournecfd23562011-09-26 01:57:12 +0000954 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
955 bool BaseIsMorallyVirtual,
956 bool BaseIsVirtualInLayoutClass,
957 CharUnits OffsetInLayoutClass);
Fangrui Song6907ce22018-07-30 19:24:48 +0000958
Peter Collingbournecfd23562011-09-26 01:57:12 +0000959 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
960 /// subobject.
961 ///
962 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
963 /// or a direct or indirect base of a virtual base.
964 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
965 CharUnits OffsetInLayoutClass);
966
967 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
968 /// class hierarchy.
Fangrui Song6907ce22018-07-30 19:24:48 +0000969 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000970 CharUnits OffsetInLayoutClass,
971 VisitedVirtualBasesSetTy &VBases);
972
973 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
974 /// given base (excluding any primary bases).
Fangrui Song6907ce22018-07-30 19:24:48 +0000975 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000976 VisitedVirtualBasesSetTy &VBases);
977
978 /// isBuildingConstructionVTable - Return whether this vtable builder is
979 /// building a construction vtable.
Fangrui Song6907ce22018-07-30 19:24:48 +0000980 bool isBuildingConstructorVTable() const {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000981 return MostDerivedClass != LayoutClass;
982 }
983
984public:
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000985 /// Component indices of the first component of each of the vtables in the
986 /// vtable group.
987 SmallVector<size_t, 4> VTableIndices;
988
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000989 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
990 const CXXRecordDecl *MostDerivedClass,
991 CharUnits MostDerivedClassOffset,
992 bool MostDerivedClassIsVirtual,
993 const CXXRecordDecl *LayoutClass)
994 : VTables(VTables), MostDerivedClass(MostDerivedClass),
995 MostDerivedClassOffset(MostDerivedClassOffset),
996 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
997 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
998 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000999 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
Peter Collingbournecfd23562011-09-26 01:57:12 +00001000
1001 LayoutVTable();
1002
David Blaikiebbafb8a2012-03-11 07:00:24 +00001003 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00001004 dumpLayout(llvm::outs());
Peter Collingbournecfd23562011-09-26 01:57:12 +00001005 }
1006
1007 uint64_t getNumThunks() const {
1008 return Thunks.size();
1009 }
1010
1011 ThunksMapTy::const_iterator thunks_begin() const {
1012 return Thunks.begin();
1013 }
1014
1015 ThunksMapTy::const_iterator thunks_end() const {
1016 return Thunks.end();
1017 }
1018
1019 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1020 return VBaseOffsetOffsets;
1021 }
1022
1023 const AddressPointsMapTy &getAddressPoints() const {
1024 return AddressPoints;
1025 }
1026
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001027 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1028 return MethodVTableIndices.begin();
1029 }
1030
1031 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1032 return MethodVTableIndices.end();
1033 }
1034
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001035 ArrayRef<VTableComponent> vtable_components() const { return Components; }
Peter Collingbournecfd23562011-09-26 01:57:12 +00001036
Peter Collingbournecfd23562011-09-26 01:57:12 +00001037 AddressPointsMapTy::const_iterator address_points_begin() const {
1038 return AddressPoints.begin();
1039 }
1040
1041 AddressPointsMapTy::const_iterator address_points_end() const {
1042 return AddressPoints.end();
1043 }
1044
1045 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1046 return VTableThunks.begin();
1047 }
1048
1049 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1050 return VTableThunks.end();
1051 }
1052
1053 /// dumpLayout - Dump the vtable layout.
1054 void dumpLayout(raw_ostream&);
1055};
1056
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001057void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1058 const ThunkInfo &Thunk) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001059 assert(!isBuildingConstructorVTable() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001060 "Can't add thunks for construction vtable");
1061
Craig Topper5603df42013-07-05 19:34:19 +00001062 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1063
Peter Collingbournecfd23562011-09-26 01:57:12 +00001064 // Check if we have this thunk already.
Fangrui Song6907ce22018-07-30 19:24:48 +00001065 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
Peter Collingbournecfd23562011-09-26 01:57:12 +00001066 ThunksVector.end())
1067 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001068
Peter Collingbournecfd23562011-09-26 01:57:12 +00001069 ThunksVector.push_back(Thunk);
1070}
1071
1072typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1073
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001074/// Visit all the methods overridden by the given method recursively,
1075/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1076/// indicating whether to continue the recursion for the given overridden
1077/// method (i.e. returning false stops the iteration).
1078template <class VisitorTy>
1079static void
1080visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001081 assert(MD->isVirtual() && "Method is not virtual!");
1082
Benjamin Krameracfa3392017-12-17 23:52:45 +00001083 for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00001084 if (!Visitor(OverriddenMD))
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001085 continue;
1086 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001087 }
1088}
1089
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001090/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1091/// the overridden methods that the function decl overrides.
1092static void
1093ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1094 OverriddenMethodsSetTy& OverriddenMethods) {
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00001095 auto OverriddenMethodsCollector = [&](const CXXMethodDecl *MD) {
1096 // Don't recurse on this method if we've already collected it.
1097 return OverriddenMethods.insert(MD).second;
1098 };
1099 visitAllOverriddenMethods(MD, OverriddenMethodsCollector);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001100}
1101
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001102void ItaniumVTableBuilder::ComputeThisAdjustments() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001103 // Now go through the method info map and see if any of the methods need
1104 // 'this' pointer adjustments.
Benjamin Kramera37e7652015-07-25 17:10:49 +00001105 for (const auto &MI : MethodInfoMap) {
1106 const CXXMethodDecl *MD = MI.first;
1107 const MethodInfo &MethodInfo = MI.second;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001108
1109 // Ignore adjustments for unused function pointers.
1110 uint64_t VTableIndex = MethodInfo.VTableIndex;
Fangrui Song6907ce22018-07-30 19:24:48 +00001111 if (Components[VTableIndex].getKind() ==
Peter Collingbournecfd23562011-09-26 01:57:12 +00001112 VTableComponent::CK_UnusedFunctionPointer)
1113 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001114
Peter Collingbournecfd23562011-09-26 01:57:12 +00001115 // Get the final overrider for this method.
1116 FinalOverriders::OverriderInfo Overrider =
1117 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +00001118
Peter Collingbournecfd23562011-09-26 01:57:12 +00001119 // Check if we need an adjustment at all.
1120 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1121 // When a return thunk is needed by a derived class that overrides a
Fangrui Song6907ce22018-07-30 19:24:48 +00001122 // virtual base, gcc uses a virtual 'this' adjustment as well.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001123 // While the thunk itself might be needed by vtables in subclasses or
1124 // in construction vtables, there doesn't seem to be a reason for using
1125 // the thunk in this vtable. Still, we do so to match gcc.
1126 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1127 continue;
1128 }
1129
1130 ThisAdjustment ThisAdjustment =
1131 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1132
1133 if (ThisAdjustment.isEmpty())
1134 continue;
1135
1136 // Add it.
1137 VTableThunks[VTableIndex].This = ThisAdjustment;
1138
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001139 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001140 // Add an adjustment for the deleting destructor as well.
1141 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1142 }
1143 }
1144
1145 /// Clear the method info map.
1146 MethodInfoMap.clear();
Fangrui Song6907ce22018-07-30 19:24:48 +00001147
Peter Collingbournecfd23562011-09-26 01:57:12 +00001148 if (isBuildingConstructorVTable()) {
1149 // We don't need to store thunk information for construction vtables.
1150 return;
1151 }
1152
Benjamin Kramera37e7652015-07-25 17:10:49 +00001153 for (const auto &TI : VTableThunks) {
1154 const VTableComponent &Component = Components[TI.first];
1155 const ThunkInfo &Thunk = TI.second;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001156 const CXXMethodDecl *MD;
Fangrui Song6907ce22018-07-30 19:24:48 +00001157
Peter Collingbournecfd23562011-09-26 01:57:12 +00001158 switch (Component.getKind()) {
1159 default:
1160 llvm_unreachable("Unexpected vtable component kind!");
1161 case VTableComponent::CK_FunctionPointer:
1162 MD = Component.getFunctionDecl();
1163 break;
1164 case VTableComponent::CK_CompleteDtorPointer:
1165 MD = Component.getDestructorDecl();
1166 break;
1167 case VTableComponent::CK_DeletingDtorPointer:
1168 // We've already added the thunk when we saw the complete dtor pointer.
1169 continue;
1170 }
1171
1172 if (MD->getParent() == MostDerivedClass)
1173 AddThunk(MD, Thunk);
1174 }
1175}
1176
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001177ReturnAdjustment
1178ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001179 ReturnAdjustment Adjustment;
Fangrui Song6907ce22018-07-30 19:24:48 +00001180
Peter Collingbournecfd23562011-09-26 01:57:12 +00001181 if (!Offset.isEmpty()) {
1182 if (Offset.VirtualBase) {
1183 // Get the virtual base offset offset.
1184 if (Offset.DerivedClass == MostDerivedClass) {
1185 // We can get the offset offset directly from our map.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001186 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001187 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1188 } else {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001189 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001190 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1191 Offset.VirtualBase).getQuantity();
1192 }
1193 }
1194
1195 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1196 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001197
Peter Collingbournecfd23562011-09-26 01:57:12 +00001198 return Adjustment;
1199}
1200
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001201BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1202 BaseSubobject Base, BaseSubobject Derived) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001203 const CXXRecordDecl *BaseRD = Base.getBase();
1204 const CXXRecordDecl *DerivedRD = Derived.getBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00001205
Peter Collingbournecfd23562011-09-26 01:57:12 +00001206 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1207 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1208
Benjamin Kramer325d7452013-02-03 18:55:34 +00001209 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +00001210 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +00001211
1212 // We have to go through all the paths, and see which one leads us to the
1213 // right base subobject.
Benjamin Kramera37e7652015-07-25 17:10:49 +00001214 for (const CXXBasePath &Path : Paths) {
1215 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, Path);
1216
Peter Collingbournecfd23562011-09-26 01:57:12 +00001217 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +00001218
Peter Collingbournecfd23562011-09-26 01:57:12 +00001219 if (Offset.VirtualBase) {
1220 // If we have a virtual base class, the non-virtual offset is relative
1221 // to the virtual base class offset.
1222 const ASTRecordLayout &LayoutClassLayout =
1223 Context.getASTRecordLayout(LayoutClass);
Fangrui Song6907ce22018-07-30 19:24:48 +00001224
1225 /// Get the virtual base offset, relative to the most derived class
Peter Collingbournecfd23562011-09-26 01:57:12 +00001226 /// layout.
Fangrui Song6907ce22018-07-30 19:24:48 +00001227 OffsetToBaseSubobject +=
Peter Collingbournecfd23562011-09-26 01:57:12 +00001228 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1229 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +00001230 // Otherwise, the non-virtual offset is relative to the derived class
Peter Collingbournecfd23562011-09-26 01:57:12 +00001231 // offset.
1232 OffsetToBaseSubobject += Derived.getBaseOffset();
1233 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001234
Peter Collingbournecfd23562011-09-26 01:57:12 +00001235 // Check if this path gives us the right base subobject.
1236 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1237 // Since we're going from the base class _to_ the derived class, we'll
1238 // invert the non-virtual offset here.
1239 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1240 return Offset;
Fangrui Song6907ce22018-07-30 19:24:48 +00001241 }
Peter Collingbournecfd23562011-09-26 01:57:12 +00001242 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001243
Peter Collingbournecfd23562011-09-26 01:57:12 +00001244 return BaseOffset();
1245}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001246
1247ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1248 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1249 FinalOverriders::OverriderInfo Overrider) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001250 // Ignore adjustments for pure virtual member functions.
1251 if (Overrider.Method->isPure())
1252 return ThisAdjustment();
Fangrui Song6907ce22018-07-30 19:24:48 +00001253
1254 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
Peter Collingbournecfd23562011-09-26 01:57:12 +00001255 BaseOffsetInLayoutClass);
Fangrui Song6907ce22018-07-30 19:24:48 +00001256
Peter Collingbournecfd23562011-09-26 01:57:12 +00001257 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1258 Overrider.Offset);
Fangrui Song6907ce22018-07-30 19:24:48 +00001259
Peter Collingbournecfd23562011-09-26 01:57:12 +00001260 // Compute the adjustment offset.
1261 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1262 OverriderBaseSubobject);
1263 if (Offset.isEmpty())
1264 return ThisAdjustment();
1265
1266 ThisAdjustment Adjustment;
Fangrui Song6907ce22018-07-30 19:24:48 +00001267
Peter Collingbournecfd23562011-09-26 01:57:12 +00001268 if (Offset.VirtualBase) {
1269 // Get the vcall offset map for this virtual base.
1270 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1271
1272 if (VCallOffsets.empty()) {
1273 // We don't have vcall offsets for this virtual base, go ahead and
1274 // build them.
1275 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
Craig Topper36250ad2014-05-12 05:36:57 +00001276 /*FinalOverriders=*/nullptr,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001277 BaseSubobject(Offset.VirtualBase,
1278 CharUnits::Zero()),
1279 /*BaseIsVirtual=*/true,
1280 /*OffsetInLayoutClass=*/
1281 CharUnits::Zero());
Fangrui Song6907ce22018-07-30 19:24:48 +00001282
Peter Collingbournecfd23562011-09-26 01:57:12 +00001283 VCallOffsets = Builder.getVCallOffsets();
1284 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001285
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001286 Adjustment.Virtual.Itanium.VCallOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001287 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1288 }
1289
1290 // Set the non-virtual part of the adjustment.
1291 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
Fangrui Song6907ce22018-07-30 19:24:48 +00001292
Peter Collingbournecfd23562011-09-26 01:57:12 +00001293 return Adjustment;
1294}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001295
1296void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1297 ReturnAdjustment ReturnAdjustment) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001298 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001299 assert(ReturnAdjustment.isEmpty() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001300 "Destructor can't have return adjustment!");
1301
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001302 // Add both the complete destructor and the deleting destructor.
1303 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1304 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbournecfd23562011-09-26 01:57:12 +00001305 } else {
1306 // Add the return adjustment if necessary.
1307 if (!ReturnAdjustment.isEmpty())
1308 VTableThunks[Components.size()].Return = ReturnAdjustment;
1309
1310 // Add the function.
1311 Components.push_back(VTableComponent::MakeFunction(MD));
1312 }
1313}
1314
1315/// OverridesIndirectMethodInBase - Return whether the given member function
Fangrui Song6907ce22018-07-30 19:24:48 +00001316/// overrides any methods in the set of given bases.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001317/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1318/// For example, if we have:
1319///
1320/// struct A { virtual void f(); }
1321/// struct B : A { virtual void f(); }
1322/// struct C : B { virtual void f(); }
1323///
Fangrui Song6907ce22018-07-30 19:24:48 +00001324/// OverridesIndirectMethodInBase will return true if given C::f as the method
Peter Collingbournecfd23562011-09-26 01:57:12 +00001325/// and { A } as the set of bases.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001326static bool OverridesIndirectMethodInBases(
1327 const CXXMethodDecl *MD,
1328 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001329 if (Bases.count(MD->getParent()))
1330 return true;
Benjamin Krameracfa3392017-12-17 23:52:45 +00001331
1332 for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001333 // Check "indirect overriders".
1334 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1335 return true;
1336 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001337
Peter Collingbournecfd23562011-09-26 01:57:12 +00001338 return false;
1339}
1340
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001341bool ItaniumVTableBuilder::IsOverriderUsed(
1342 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1343 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1344 CharUnits FirstBaseOffsetInLayoutClass) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001345 // If the base and the first base in the primary base chain have the same
1346 // offsets, then this overrider will be used.
1347 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1348 return true;
1349
1350 // We know now that Base (or a direct or indirect base of it) is a primary
Fangrui Song6907ce22018-07-30 19:24:48 +00001351 // base in part of the class hierarchy, but not a primary base in the most
Peter Collingbournecfd23562011-09-26 01:57:12 +00001352 // derived class.
Fangrui Song6907ce22018-07-30 19:24:48 +00001353
Peter Collingbournecfd23562011-09-26 01:57:12 +00001354 // If the overrider is the first base in the primary base chain, we know
1355 // that the overrider will be used.
1356 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1357 return true;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001358
1359 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001360
1361 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1362 PrimaryBases.insert(RD);
1363
1364 // Now traverse the base chain, starting with the first base, until we find
1365 // the base that is no longer a primary base.
1366 while (true) {
1367 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1368 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00001369
Peter Collingbournecfd23562011-09-26 01:57:12 +00001370 if (!PrimaryBase)
1371 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001372
Peter Collingbournecfd23562011-09-26 01:57:12 +00001373 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001374 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001375 "Primary base should always be at offset 0!");
1376
1377 const ASTRecordLayout &LayoutClassLayout =
1378 Context.getASTRecordLayout(LayoutClass);
1379
1380 // Now check if this is the primary base that is not a primary base in the
1381 // most derived class.
1382 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1383 FirstBaseOffsetInLayoutClass) {
1384 // We found it, stop walking the chain.
1385 break;
1386 }
1387 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001388 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001389 "Primary base should always be at offset 0!");
1390 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001391
Peter Collingbournecfd23562011-09-26 01:57:12 +00001392 if (!PrimaryBases.insert(PrimaryBase))
1393 llvm_unreachable("Found a duplicate primary base!");
1394
1395 RD = PrimaryBase;
1396 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001397
Peter Collingbournecfd23562011-09-26 01:57:12 +00001398 // If the final overrider is an override of one of the primary bases,
1399 // then we know that it will be used.
1400 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1401}
1402
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001403typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1404
Peter Collingbournecfd23562011-09-26 01:57:12 +00001405/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1406/// from the nearest base. Returns null if no method was found.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001407/// The Bases are expected to be sorted in a base-to-derived order.
1408static const CXXMethodDecl *
Peter Collingbournecfd23562011-09-26 01:57:12 +00001409FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001410 BasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001411 OverriddenMethodsSetTy OverriddenMethods;
1412 ComputeAllOverriddenMethods(MD, OverriddenMethods);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001413
Benjamin Kramera37e7652015-07-25 17:10:49 +00001414 for (const CXXRecordDecl *PrimaryBase :
1415 llvm::make_range(Bases.rbegin(), Bases.rend())) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001416 // Now check the overridden methods.
Benjamin Kramera37e7652015-07-25 17:10:49 +00001417 for (const CXXMethodDecl *OverriddenMD : OverriddenMethods) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001418 // We found our overridden method.
1419 if (OverriddenMD->getParent() == PrimaryBase)
1420 return OverriddenMD;
1421 }
1422 }
Craig Topper36250ad2014-05-12 05:36:57 +00001423
1424 return nullptr;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001425}
Peter Collingbournecfd23562011-09-26 01:57:12 +00001426
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001427void ItaniumVTableBuilder::AddMethods(
1428 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1429 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1430 CharUnits FirstBaseOffsetInLayoutClass,
1431 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001432 // Itanium C++ ABI 2.5.2:
1433 // The order of the virtual function pointers in a virtual table is the
1434 // order of declaration of the corresponding member functions in the class.
1435 //
1436 // There is an entry for any virtual function declared in a class,
1437 // whether it is a new function or overrides a base class function,
1438 // unless it overrides a function from the primary base, and conversion
1439 // between their return types does not require an adjustment.
1440
Peter Collingbournecfd23562011-09-26 01:57:12 +00001441 const CXXRecordDecl *RD = Base.getBase();
1442 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1443
1444 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1445 CharUnits PrimaryBaseOffset;
1446 CharUnits PrimaryBaseOffsetInLayoutClass;
1447 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001448 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001449 "Primary vbase should have a zero offset!");
Fangrui Song6907ce22018-07-30 19:24:48 +00001450
Peter Collingbournecfd23562011-09-26 01:57:12 +00001451 const ASTRecordLayout &MostDerivedClassLayout =
1452 Context.getASTRecordLayout(MostDerivedClass);
Fangrui Song6907ce22018-07-30 19:24:48 +00001453
1454 PrimaryBaseOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001455 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
Fangrui Song6907ce22018-07-30 19:24:48 +00001456
Peter Collingbournecfd23562011-09-26 01:57:12 +00001457 const ASTRecordLayout &LayoutClassLayout =
1458 Context.getASTRecordLayout(LayoutClass);
1459
1460 PrimaryBaseOffsetInLayoutClass =
1461 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1462 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001463 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001464 "Primary base should have a zero offset!");
1465
1466 PrimaryBaseOffset = Base.getBaseOffset();
1467 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1468 }
1469
1470 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
Fangrui Song6907ce22018-07-30 19:24:48 +00001471 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001472 FirstBaseOffsetInLayoutClass, PrimaryBases);
Fangrui Song6907ce22018-07-30 19:24:48 +00001473
Peter Collingbournecfd23562011-09-26 01:57:12 +00001474 if (!PrimaryBases.insert(PrimaryBase))
1475 llvm_unreachable("Found a duplicate primary base!");
1476 }
1477
Craig Topper36250ad2014-05-12 05:36:57 +00001478 const CXXDestructorDecl *ImplicitVirtualDtor = nullptr;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001479
1480 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1481 NewVirtualFunctionsTy NewVirtualFunctions;
1482
Peter Collingbournecfd23562011-09-26 01:57:12 +00001483 // Now go through all virtual member functions and add them.
Aaron Ballman2b124d12014-03-13 16:36:16 +00001484 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001485 if (!MD->isVirtual())
1486 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +00001487 MD = MD->getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001488
1489 // Get the final overrider.
Fangrui Song6907ce22018-07-30 19:24:48 +00001490 FinalOverriders::OverriderInfo Overrider =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001491 Overriders.getOverrider(MD, Base.getBaseOffset());
1492
1493 // Check if this virtual member function overrides a method in a primary
1494 // base. If this is the case, and the return type doesn't require adjustment
1495 // then we can just use the member function from the primary base.
Fangrui Song6907ce22018-07-30 19:24:48 +00001496 if (const CXXMethodDecl *OverriddenMD =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001497 FindNearestOverriddenMethod(MD, PrimaryBases)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001498 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001499 OverriddenMD).isEmpty()) {
1500 // Replace the method info of the overridden method with our own
1501 // method.
Fangrui Song6907ce22018-07-30 19:24:48 +00001502 assert(MethodInfoMap.count(OverriddenMD) &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001503 "Did not find the overridden method!");
1504 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
Fangrui Song6907ce22018-07-30 19:24:48 +00001505
Peter Collingbournecfd23562011-09-26 01:57:12 +00001506 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1507 OverriddenMethodInfo.VTableIndex);
1508
1509 assert(!MethodInfoMap.count(MD) &&
1510 "Should not have method info for this method yet!");
Fangrui Song6907ce22018-07-30 19:24:48 +00001511
Peter Collingbournecfd23562011-09-26 01:57:12 +00001512 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1513 MethodInfoMap.erase(OverriddenMD);
Fangrui Song6907ce22018-07-30 19:24:48 +00001514
Peter Collingbournecfd23562011-09-26 01:57:12 +00001515 // If the overridden method exists in a virtual base class or a direct
1516 // or indirect base class of a virtual base class, we need to emit a
1517 // thunk if we ever have a class hierarchy where the base class is not
1518 // a primary base in the complete object.
1519 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1520 // Compute the this adjustment.
1521 ThisAdjustment ThisAdjustment =
1522 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1523 Overrider);
1524
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001525 if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001526 Overrider.Method->getParent() == MostDerivedClass) {
1527
1528 // There's no return adjustment from OverriddenMD and MD,
1529 // but that doesn't mean there isn't one between MD and
1530 // the final overrider.
1531 BaseOffset ReturnAdjustmentOffset =
1532 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
Fangrui Song6907ce22018-07-30 19:24:48 +00001533 ReturnAdjustment ReturnAdjustment =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001534 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1535
1536 // This is a virtual thunk for the most derived class, add it.
Fangrui Song6907ce22018-07-30 19:24:48 +00001537 AddThunk(Overrider.Method,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001538 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1539 }
1540 }
1541
1542 continue;
1543 }
1544 }
1545
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001546 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1547 if (MD->isImplicit()) {
1548 // Itanium C++ ABI 2.5.2:
1549 // If a class has an implicitly-defined virtual destructor,
1550 // its entries come after the declared virtual function pointers.
1551
1552 assert(!ImplicitVirtualDtor &&
1553 "Did already see an implicit virtual dtor!");
1554 ImplicitVirtualDtor = DD;
1555 continue;
1556 }
1557 }
1558
1559 NewVirtualFunctions.push_back(MD);
1560 }
1561
1562 if (ImplicitVirtualDtor)
1563 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1564
Benjamin Kramera37e7652015-07-25 17:10:49 +00001565 for (const CXXMethodDecl *MD : NewVirtualFunctions) {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001566 // Get the final overrider.
1567 FinalOverriders::OverriderInfo Overrider =
1568 Overriders.getOverrider(MD, Base.getBaseOffset());
1569
Peter Collingbournecfd23562011-09-26 01:57:12 +00001570 // Insert the method info for this method.
1571 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1572 Components.size());
1573
1574 assert(!MethodInfoMap.count(MD) &&
1575 "Should not have method info for this method yet!");
1576 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1577
1578 // Check if this overrider is going to be used.
1579 const CXXMethodDecl *OverriderMD = Overrider.Method;
1580 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
Fangrui Song6907ce22018-07-30 19:24:48 +00001581 FirstBaseInPrimaryBaseChain,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001582 FirstBaseOffsetInLayoutClass)) {
1583 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1584 continue;
1585 }
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001586
Peter Collingbournecfd23562011-09-26 01:57:12 +00001587 // Check if this overrider needs a return adjustment.
1588 // We don't want to do this for pure virtual member functions.
1589 BaseOffset ReturnAdjustmentOffset;
1590 if (!OverriderMD->isPure()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001591 ReturnAdjustmentOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001592 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1593 }
1594
Fangrui Song6907ce22018-07-30 19:24:48 +00001595 ReturnAdjustment ReturnAdjustment =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001596 ComputeReturnAdjustment(ReturnAdjustmentOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +00001597
Peter Collingbournecfd23562011-09-26 01:57:12 +00001598 AddMethod(Overrider.Method, ReturnAdjustment);
1599 }
1600}
1601
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001602void ItaniumVTableBuilder::LayoutVTable() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001603 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1604 CharUnits::Zero()),
1605 /*BaseIsMorallyVirtual=*/false,
1606 MostDerivedClassIsVirtual,
1607 MostDerivedClassOffset);
Fangrui Song6907ce22018-07-30 19:24:48 +00001608
Peter Collingbournecfd23562011-09-26 01:57:12 +00001609 VisitedVirtualBasesSetTy VBases;
Fangrui Song6907ce22018-07-30 19:24:48 +00001610
Peter Collingbournecfd23562011-09-26 01:57:12 +00001611 // Determine the primary virtual bases.
Fangrui Song6907ce22018-07-30 19:24:48 +00001612 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001613 VBases);
1614 VBases.clear();
Fangrui Song6907ce22018-07-30 19:24:48 +00001615
Peter Collingbournecfd23562011-09-26 01:57:12 +00001616 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1617
1618 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001619 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001620 if (IsAppleKext)
1621 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1622}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001623
1624void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1625 BaseSubobject Base, bool BaseIsMorallyVirtual,
1626 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001627 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1628
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001629 unsigned VTableIndex = Components.size();
1630 VTableIndices.push_back(VTableIndex);
1631
Peter Collingbournecfd23562011-09-26 01:57:12 +00001632 // Add vcall and vbase offsets for this vtable.
1633 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
Fangrui Song6907ce22018-07-30 19:24:48 +00001634 Base, BaseIsVirtualInLayoutClass,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001635 OffsetInLayoutClass);
1636 Components.append(Builder.components_begin(), Builder.components_end());
Fangrui Song6907ce22018-07-30 19:24:48 +00001637
Peter Collingbournecfd23562011-09-26 01:57:12 +00001638 // Check if we need to add these vcall offsets.
1639 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1640 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
Fangrui Song6907ce22018-07-30 19:24:48 +00001641
Peter Collingbournecfd23562011-09-26 01:57:12 +00001642 if (VCallOffsets.empty())
1643 VCallOffsets = Builder.getVCallOffsets();
1644 }
1645
1646 // If we're laying out the most derived class we want to keep track of the
1647 // virtual base class offset offsets.
1648 if (Base.getBase() == MostDerivedClass)
1649 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1650
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001651 // Add the offset to top.
1652 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1653 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001654
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001655 // Next, add the RTTI.
1656 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001657
Peter Collingbournecfd23562011-09-26 01:57:12 +00001658 uint64_t AddressPoint = Components.size();
1659
1660 // Now go through all virtual member functions and add them.
1661 PrimaryBasesSetVectorTy PrimaryBases;
1662 AddMethods(Base, OffsetInLayoutClass,
Fangrui Song6907ce22018-07-30 19:24:48 +00001663 Base.getBase(), OffsetInLayoutClass,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001664 PrimaryBases);
1665
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001666 const CXXRecordDecl *RD = Base.getBase();
1667 if (RD == MostDerivedClass) {
1668 assert(MethodVTableIndices.empty());
Benjamin Kramera37e7652015-07-25 17:10:49 +00001669 for (const auto &I : MethodInfoMap) {
1670 const CXXMethodDecl *MD = I.first;
1671 const MethodInfo &MI = I.second;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001672 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001673 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1674 = MI.VTableIndex - AddressPoint;
1675 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1676 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001677 } else {
1678 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1679 }
1680 }
1681 }
1682
Peter Collingbournecfd23562011-09-26 01:57:12 +00001683 // Compute 'this' pointer adjustments.
1684 ComputeThisAdjustments();
1685
1686 // Add all address points.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001687 while (true) {
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001688 AddressPoints.insert(
1689 std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
1690 VTableLayout::AddressPointLocation{
1691 unsigned(VTableIndices.size() - 1),
1692 unsigned(AddressPoint - VTableIndex)}));
Peter Collingbournecfd23562011-09-26 01:57:12 +00001693
1694 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1695 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00001696
Peter Collingbournecfd23562011-09-26 01:57:12 +00001697 if (!PrimaryBase)
1698 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001699
Peter Collingbournecfd23562011-09-26 01:57:12 +00001700 if (Layout.isPrimaryBaseVirtual()) {
1701 // Check if this virtual primary base is a primary base in the layout
1702 // class. If it's not, we don't want to add it.
1703 const ASTRecordLayout &LayoutClassLayout =
1704 Context.getASTRecordLayout(LayoutClass);
1705
1706 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1707 OffsetInLayoutClass) {
1708 // We don't want to add this class (or any of its primary bases).
1709 break;
1710 }
1711 }
1712
1713 RD = PrimaryBase;
1714 }
1715
1716 // Layout secondary vtables.
1717 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1718}
1719
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001720void
1721ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1722 bool BaseIsMorallyVirtual,
1723 CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001724 // Itanium C++ ABI 2.5.2:
Fangrui Song6907ce22018-07-30 19:24:48 +00001725 // Following the primary virtual table of a derived class are secondary
Peter Collingbournecfd23562011-09-26 01:57:12 +00001726 // virtual tables for each of its proper base classes, except any primary
1727 // base(s) with which it shares its primary virtual table.
1728
1729 const CXXRecordDecl *RD = Base.getBase();
1730 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1731 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00001732
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001733 for (const auto &B : RD->bases()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001734 // Ignore virtual bases, we'll emit them later.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001735 if (B.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +00001736 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001737
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001738 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001739
1740 // Ignore bases that don't have a vtable.
1741 if (!BaseDecl->isDynamicClass())
1742 continue;
1743
1744 if (isBuildingConstructorVTable()) {
1745 // Itanium C++ ABI 2.6.4:
1746 // Some of the base class subobjects may not need construction virtual
1747 // tables, which will therefore not be present in the construction
1748 // virtual table group, even though the subobject virtual tables are
1749 // present in the main virtual table group for the complete object.
1750 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1751 continue;
1752 }
1753
1754 // Get the base offset of this base.
1755 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1756 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +00001757
1758 CharUnits BaseOffsetInLayoutClass =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001759 OffsetInLayoutClass + RelativeBaseOffset;
Fangrui Song6907ce22018-07-30 19:24:48 +00001760
1761 // Don't emit a secondary vtable for a primary base. We might however want
Peter Collingbournecfd23562011-09-26 01:57:12 +00001762 // to emit secondary vtables for other bases of this base.
1763 if (BaseDecl == PrimaryBase) {
1764 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1765 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1766 continue;
1767 }
1768
1769 // Layout the primary vtable (and any secondary vtables) for this base.
1770 LayoutPrimaryAndSecondaryVTables(
1771 BaseSubobject(BaseDecl, BaseOffset),
1772 BaseIsMorallyVirtual,
1773 /*BaseIsVirtualInLayoutClass=*/false,
1774 BaseOffsetInLayoutClass);
1775 }
1776}
1777
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001778void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1779 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1780 VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001781 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Fangrui Song6907ce22018-07-30 19:24:48 +00001782
Peter Collingbournecfd23562011-09-26 01:57:12 +00001783 // Check if this base has a primary base.
1784 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1785
1786 // Check if it's virtual.
1787 if (Layout.isPrimaryBaseVirtual()) {
1788 bool IsPrimaryVirtualBase = true;
1789
1790 if (isBuildingConstructorVTable()) {
1791 // Check if the base is actually a primary base in the class we use for
1792 // layout.
1793 const ASTRecordLayout &LayoutClassLayout =
1794 Context.getASTRecordLayout(LayoutClass);
1795
1796 CharUnits PrimaryBaseOffsetInLayoutClass =
1797 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
Fangrui Song6907ce22018-07-30 19:24:48 +00001798
1799 // We know that the base is not a primary base in the layout class if
Peter Collingbournecfd23562011-09-26 01:57:12 +00001800 // the base offsets are different.
1801 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1802 IsPrimaryVirtualBase = false;
1803 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001804
Peter Collingbournecfd23562011-09-26 01:57:12 +00001805 if (IsPrimaryVirtualBase)
1806 PrimaryVirtualBases.insert(PrimaryBase);
1807 }
1808 }
1809
1810 // Traverse bases, looking for more primary virtual bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001811 for (const auto &B : RD->bases()) {
1812 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001813
1814 CharUnits BaseOffsetInLayoutClass;
Fangrui Song6907ce22018-07-30 19:24:48 +00001815
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001816 if (B.isVirtual()) {
David Blaikie82e95a32014-11-19 07:49:47 +00001817 if (!VBases.insert(BaseDecl).second)
Peter Collingbournecfd23562011-09-26 01:57:12 +00001818 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001819
Peter Collingbournecfd23562011-09-26 01:57:12 +00001820 const ASTRecordLayout &LayoutClassLayout =
1821 Context.getASTRecordLayout(LayoutClass);
1822
Fangrui Song6907ce22018-07-30 19:24:48 +00001823 BaseOffsetInLayoutClass =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001824 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1825 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +00001826 BaseOffsetInLayoutClass =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001827 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1828 }
1829
1830 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1831 }
1832}
1833
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001834void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1835 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001836 // Itanium C++ ABI 2.5.2:
1837 // Then come the virtual base virtual tables, also in inheritance graph
1838 // order, and again excluding primary bases (which share virtual tables with
1839 // the classes for which they are primary).
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001840 for (const auto &B : RD->bases()) {
1841 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001842
1843 // Check if this base needs a vtable. (If it's virtual, not a primary base
1844 // of some other class, and we haven't visited it before).
David Blaikie82e95a32014-11-19 07:49:47 +00001845 if (B.isVirtual() && BaseDecl->isDynamicClass() &&
1846 !PrimaryVirtualBases.count(BaseDecl) &&
1847 VBases.insert(BaseDecl).second) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001848 const ASTRecordLayout &MostDerivedClassLayout =
1849 Context.getASTRecordLayout(MostDerivedClass);
Fangrui Song6907ce22018-07-30 19:24:48 +00001850 CharUnits BaseOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001851 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001852
Peter Collingbournecfd23562011-09-26 01:57:12 +00001853 const ASTRecordLayout &LayoutClassLayout =
1854 Context.getASTRecordLayout(LayoutClass);
Fangrui Song6907ce22018-07-30 19:24:48 +00001855 CharUnits BaseOffsetInLayoutClass =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001856 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1857
1858 LayoutPrimaryAndSecondaryVTables(
1859 BaseSubobject(BaseDecl, BaseOffset),
1860 /*BaseIsMorallyVirtual=*/true,
1861 /*BaseIsVirtualInLayoutClass=*/true,
1862 BaseOffsetInLayoutClass);
1863 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001864
Peter Collingbournecfd23562011-09-26 01:57:12 +00001865 // We only need to check the base for virtual base vtables if it actually
1866 // has virtual bases.
1867 if (BaseDecl->getNumVBases())
1868 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1869 }
1870}
1871
1872/// dumpLayout - Dump the vtable layout.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001873void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00001874 // FIXME: write more tests that actually use the dumpLayout output to prevent
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001875 // ItaniumVTableBuilder regressions.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001876
1877 if (isBuildingConstructorVTable()) {
1878 Out << "Construction vtable for ('";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001879 MostDerivedClass->printQualifiedName(Out);
1880 Out << "', ";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001881 Out << MostDerivedClassOffset.getQuantity() << ") in '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001882 LayoutClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001883 } else {
1884 Out << "Vtable for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001885 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001886 }
1887 Out << "' (" << Components.size() << " entries).\n";
1888
1889 // Iterate through the address points and insert them into a new map where
1890 // they are keyed by the index and not the base object.
1891 // Since an address point can be shared by multiple subobjects, we use an
1892 // STL multimap.
1893 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
Benjamin Kramera37e7652015-07-25 17:10:49 +00001894 for (const auto &AP : AddressPoints) {
1895 const BaseSubobject &Base = AP.first;
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001896 uint64_t Index =
1897 VTableIndices[AP.second.VTableIndex] + AP.second.AddressPointIndex;
Benjamin Kramera37e7652015-07-25 17:10:49 +00001898
Peter Collingbournecfd23562011-09-26 01:57:12 +00001899 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1900 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001901
Peter Collingbournecfd23562011-09-26 01:57:12 +00001902 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1903 uint64_t Index = I;
1904
1905 Out << llvm::format("%4d | ", I);
1906
1907 const VTableComponent &Component = Components[I];
1908
1909 // Dump the component.
1910 switch (Component.getKind()) {
1911
1912 case VTableComponent::CK_VCallOffset:
1913 Out << "vcall_offset ("
Fangrui Song6907ce22018-07-30 19:24:48 +00001914 << Component.getVCallOffset().getQuantity()
Peter Collingbournecfd23562011-09-26 01:57:12 +00001915 << ")";
1916 break;
1917
1918 case VTableComponent::CK_VBaseOffset:
1919 Out << "vbase_offset ("
1920 << Component.getVBaseOffset().getQuantity()
1921 << ")";
1922 break;
1923
1924 case VTableComponent::CK_OffsetToTop:
1925 Out << "offset_to_top ("
1926 << Component.getOffsetToTop().getQuantity()
1927 << ")";
1928 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001929
Peter Collingbournecfd23562011-09-26 01:57:12 +00001930 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001931 Component.getRTTIDecl()->printQualifiedName(Out);
1932 Out << " RTTI";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001933 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001934
Peter Collingbournecfd23562011-09-26 01:57:12 +00001935 case VTableComponent::CK_FunctionPointer: {
1936 const CXXMethodDecl *MD = Component.getFunctionDecl();
1937
Fangrui Song6907ce22018-07-30 19:24:48 +00001938 std::string Str =
1939 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001940 MD);
1941 Out << Str;
1942 if (MD->isPure())
1943 Out << " [pure]";
1944
David Blaikie596d2ca2012-10-16 20:25:33 +00001945 if (MD->isDeleted())
1946 Out << " [deleted]";
1947
Peter Collingbournecfd23562011-09-26 01:57:12 +00001948 ThunkInfo Thunk = VTableThunks.lookup(I);
1949 if (!Thunk.isEmpty()) {
1950 // If this function pointer has a return adjustment, dump it.
1951 if (!Thunk.Return.isEmpty()) {
1952 Out << "\n [return adjustment: ";
1953 Out << Thunk.Return.NonVirtual << " non-virtual";
Fangrui Song6907ce22018-07-30 19:24:48 +00001954
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001955 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1956 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001957 Out << " vbase offset offset";
1958 }
1959
1960 Out << ']';
1961 }
1962
1963 // If this function pointer has a 'this' pointer adjustment, dump it.
1964 if (!Thunk.This.isEmpty()) {
1965 Out << "\n [this adjustment: ";
1966 Out << Thunk.This.NonVirtual << " non-virtual";
Fangrui Song6907ce22018-07-30 19:24:48 +00001967
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001968 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
1969 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001970 Out << " vcall offset offset";
1971 }
1972
1973 Out << ']';
Fangrui Song6907ce22018-07-30 19:24:48 +00001974 }
Peter Collingbournecfd23562011-09-26 01:57:12 +00001975 }
1976
1977 break;
1978 }
1979
Fangrui Song6907ce22018-07-30 19:24:48 +00001980 case VTableComponent::CK_CompleteDtorPointer:
Peter Collingbournecfd23562011-09-26 01:57:12 +00001981 case VTableComponent::CK_DeletingDtorPointer: {
Fangrui Song6907ce22018-07-30 19:24:48 +00001982 bool IsComplete =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001983 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
Fangrui Song6907ce22018-07-30 19:24:48 +00001984
Peter Collingbournecfd23562011-09-26 01:57:12 +00001985 const CXXDestructorDecl *DD = Component.getDestructorDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001986
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001987 DD->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001988 if (IsComplete)
1989 Out << "() [complete]";
1990 else
1991 Out << "() [deleting]";
1992
1993 if (DD->isPure())
1994 Out << " [pure]";
1995
1996 ThunkInfo Thunk = VTableThunks.lookup(I);
1997 if (!Thunk.isEmpty()) {
1998 // If this destructor has a 'this' pointer adjustment, dump it.
1999 if (!Thunk.This.isEmpty()) {
2000 Out << "\n [this adjustment: ";
2001 Out << Thunk.This.NonVirtual << " non-virtual";
Fangrui Song6907ce22018-07-30 19:24:48 +00002002
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002003 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2004 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002005 Out << " vcall offset offset";
2006 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002007
Peter Collingbournecfd23562011-09-26 01:57:12 +00002008 Out << ']';
Fangrui Song6907ce22018-07-30 19:24:48 +00002009 }
2010 }
Peter Collingbournecfd23562011-09-26 01:57:12 +00002011
2012 break;
2013 }
2014
2015 case VTableComponent::CK_UnusedFunctionPointer: {
2016 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2017
Fangrui Song6907ce22018-07-30 19:24:48 +00002018 std::string Str =
2019 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
Peter Collingbournecfd23562011-09-26 01:57:12 +00002020 MD);
2021 Out << "[unused] " << Str;
2022 if (MD->isPure())
2023 Out << " [pure]";
2024 }
2025
2026 }
2027
2028 Out << '\n';
Fangrui Song6907ce22018-07-30 19:24:48 +00002029
Peter Collingbournecfd23562011-09-26 01:57:12 +00002030 // Dump the next address point.
2031 uint64_t NextIndex = Index + 1;
2032 if (AddressPointsByIndex.count(NextIndex)) {
2033 if (AddressPointsByIndex.count(NextIndex) == 1) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002034 const BaseSubobject &Base =
Peter Collingbournecfd23562011-09-26 01:57:12 +00002035 AddressPointsByIndex.find(NextIndex)->second;
Fangrui Song6907ce22018-07-30 19:24:48 +00002036
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002037 Out << " -- (";
2038 Base.getBase()->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002039 Out << ", " << Base.getBaseOffset().getQuantity();
2040 Out << ") vtable address --\n";
2041 } else {
2042 CharUnits BaseOffset =
2043 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
Fangrui Song6907ce22018-07-30 19:24:48 +00002044
Peter Collingbournecfd23562011-09-26 01:57:12 +00002045 // We store the class names in a set to get a stable order.
2046 std::set<std::string> ClassNames;
Benjamin Kramera37e7652015-07-25 17:10:49 +00002047 for (const auto &I :
2048 llvm::make_range(AddressPointsByIndex.equal_range(NextIndex))) {
2049 assert(I.second.getBaseOffset() == BaseOffset &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00002050 "Invalid base offset!");
Benjamin Kramera37e7652015-07-25 17:10:49 +00002051 const CXXRecordDecl *RD = I.second.getBase();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002052 ClassNames.insert(RD->getQualifiedNameAsString());
2053 }
Benjamin Kramera37e7652015-07-25 17:10:49 +00002054
2055 for (const std::string &Name : ClassNames) {
2056 Out << " -- (" << Name;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002057 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2058 }
2059 }
2060 }
2061 }
2062
2063 Out << '\n';
Fangrui Song6907ce22018-07-30 19:24:48 +00002064
Peter Collingbournecfd23562011-09-26 01:57:12 +00002065 if (isBuildingConstructorVTable())
2066 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002067
Peter Collingbournecfd23562011-09-26 01:57:12 +00002068 if (MostDerivedClass->getNumVBases()) {
2069 // We store the virtual base class names and their offsets in a map to get
2070 // a stable order.
2071
2072 std::map<std::string, CharUnits> ClassNamesAndOffsets;
Benjamin Kramera37e7652015-07-25 17:10:49 +00002073 for (const auto &I : VBaseOffsetOffsets) {
2074 std::string ClassName = I.first->getQualifiedNameAsString();
2075 CharUnits OffsetOffset = I.second;
2076 ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
Peter Collingbournecfd23562011-09-26 01:57:12 +00002077 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002078
Peter Collingbournecfd23562011-09-26 01:57:12 +00002079 Out << "Virtual base offset offsets for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002080 MostDerivedClass->printQualifiedName(Out);
2081 Out << "' (";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002082 Out << ClassNamesAndOffsets.size();
2083 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2084
Benjamin Kramera37e7652015-07-25 17:10:49 +00002085 for (const auto &I : ClassNamesAndOffsets)
2086 Out << " " << I.first << " | " << I.second.getQuantity() << '\n';
Peter Collingbournecfd23562011-09-26 01:57:12 +00002087
2088 Out << "\n";
2089 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002090
Peter Collingbournecfd23562011-09-26 01:57:12 +00002091 if (!Thunks.empty()) {
2092 // We store the method names in a map to get a stable order.
2093 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
Benjamin Kramera37e7652015-07-25 17:10:49 +00002094
2095 for (const auto &I : Thunks) {
2096 const CXXMethodDecl *MD = I.first;
Fangrui Song6907ce22018-07-30 19:24:48 +00002097 std::string MethodName =
Peter Collingbournecfd23562011-09-26 01:57:12 +00002098 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2099 MD);
Fangrui Song6907ce22018-07-30 19:24:48 +00002100
Peter Collingbournecfd23562011-09-26 01:57:12 +00002101 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2102 }
2103
Benjamin Kramera37e7652015-07-25 17:10:49 +00002104 for (const auto &I : MethodNamesAndDecls) {
2105 const std::string &MethodName = I.first;
2106 const CXXMethodDecl *MD = I.second;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002107
2108 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Fangrui Song55fab262018-09-26 22:16:28 +00002109 llvm::sort(ThunksVector, [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
Craig Topper36250ad2014-05-12 05:36:57 +00002110 assert(LHS.Method == nullptr && RHS.Method == nullptr);
Benjamin Kramera741b8c2014-03-03 20:26:46 +00002111 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002112 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002113
2114 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2115 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00002116
Peter Collingbournecfd23562011-09-26 01:57:12 +00002117 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2118 const ThunkInfo &Thunk = ThunksVector[I];
2119
2120 Out << llvm::format("%4d | ", I);
Fangrui Song6907ce22018-07-30 19:24:48 +00002121
Peter Collingbournecfd23562011-09-26 01:57:12 +00002122 // If this function pointer has a return pointer adjustment, dump it.
2123 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00002124 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002125 Out << " non-virtual";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002126 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2127 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002128 Out << " vbase offset offset";
2129 }
2130
2131 if (!Thunk.This.isEmpty())
2132 Out << "\n ";
2133 }
2134
2135 // If this function pointer has a 'this' pointer adjustment, dump it.
2136 if (!Thunk.This.isEmpty()) {
2137 Out << "this adjustment: ";
2138 Out << Thunk.This.NonVirtual << " non-virtual";
Fangrui Song6907ce22018-07-30 19:24:48 +00002139
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002140 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2141 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002142 Out << " vcall offset offset";
2143 }
2144 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002145
Peter Collingbournecfd23562011-09-26 01:57:12 +00002146 Out << '\n';
2147 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002148
Peter Collingbournecfd23562011-09-26 01:57:12 +00002149 Out << '\n';
2150 }
2151 }
2152
2153 // Compute the vtable indices for all the member functions.
2154 // Store them in a map keyed by the index so we'll get a sorted table.
2155 std::map<uint64_t, std::string> IndicesMap;
2156
Aaron Ballman2b124d12014-03-13 16:36:16 +00002157 for (const auto *MD : MostDerivedClass->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002158 // We only want virtual member functions.
2159 if (!MD->isVirtual())
2160 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +00002161 MD = MD->getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002162
2163 std::string MethodName =
2164 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2165 MD);
2166
2167 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002168 GlobalDecl GD(DD, Dtor_Complete);
2169 assert(MethodVTableIndices.count(GD));
2170 uint64_t VTableIndex = MethodVTableIndices[GD];
2171 IndicesMap[VTableIndex] = MethodName + " [complete]";
2172 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002173 } else {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002174 assert(MethodVTableIndices.count(MD));
2175 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002176 }
2177 }
2178
2179 // Print the vtable indices for all the member functions.
2180 if (!IndicesMap.empty()) {
2181 Out << "VTable indices for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002182 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002183 Out << "' (" << IndicesMap.size() << " entries).\n";
2184
Benjamin Kramera37e7652015-07-25 17:10:49 +00002185 for (const auto &I : IndicesMap) {
2186 uint64_t VTableIndex = I.first;
2187 const std::string &MethodName = I.second;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002188
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002189 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer5291e682012-03-10 02:06:27 +00002190 << '\n';
Peter Collingbournecfd23562011-09-26 01:57:12 +00002191 }
2192 }
2193
2194 Out << '\n';
2195}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002196}
Peter Collingbournecfd23562011-09-26 01:57:12 +00002197
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00002198VTableLayout::VTableLayout(ArrayRef<size_t> VTableIndices,
2199 ArrayRef<VTableComponent> VTableComponents,
2200 ArrayRef<VTableThunkTy> VTableThunks,
2201 const AddressPointsMapTy &AddressPoints)
2202 : VTableComponents(VTableComponents), VTableThunks(VTableThunks),
2203 AddressPoints(AddressPoints) {
2204 if (VTableIndices.size() <= 1)
2205 assert(VTableIndices.size() == 1 && VTableIndices[0] == 0);
2206 else
2207 this->VTableIndices = OwningArrayRef<size_t>(VTableIndices);
2208
Fangrui Song1d38c132018-09-30 21:41:11 +00002209 llvm::sort(this->VTableThunks, [](const VTableLayout::VTableThunkTy &LHS,
2210 const VTableLayout::VTableThunkTy &RHS) {
2211 assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2212 "Different thunks should have unique indices!");
2213 return LHS.first < RHS.first;
2214 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002215}
2216
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002217VTableLayout::~VTableLayout() { }
Peter Collingbournecfd23562011-09-26 01:57:12 +00002218
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002219ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
Reid Klecknerb60a3d52013-12-20 23:58:52 +00002220 : VTableContextBase(/*MS=*/false) {}
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002221
Justin Lebar072f9ba2016-10-10 16:26:24 +00002222ItaniumVTableContext::~ItaniumVTableContext() {}
Peter Collingbournecfd23562011-09-26 01:57:12 +00002223
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002224uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
Reid Kleckner138ab492018-05-17 18:12:18 +00002225 GD = GD.getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002226 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2227 if (I != MethodVTableIndices.end())
2228 return I->second;
Fangrui Song6907ce22018-07-30 19:24:48 +00002229
Peter Collingbournecfd23562011-09-26 01:57:12 +00002230 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2231
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002232 computeVTableRelatedInformation(RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002233
2234 I = MethodVTableIndices.find(GD);
2235 assert(I != MethodVTableIndices.end() && "Did not find index!");
2236 return I->second;
2237}
2238
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002239CharUnits
2240ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2241 const CXXRecordDecl *VBase) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002242 ClassPairTy ClassPair(RD, VBase);
Fangrui Song6907ce22018-07-30 19:24:48 +00002243
2244 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
Peter Collingbournecfd23562011-09-26 01:57:12 +00002245 VirtualBaseClassOffsetOffsets.find(ClassPair);
2246 if (I != VirtualBaseClassOffsetOffsets.end())
2247 return I->second;
Craig Topper36250ad2014-05-12 05:36:57 +00002248
2249 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/nullptr,
Peter Collingbournecfd23562011-09-26 01:57:12 +00002250 BaseSubobject(RD, CharUnits::Zero()),
2251 /*BaseIsVirtual=*/false,
2252 /*OffsetInLayoutClass=*/CharUnits::Zero());
2253
Benjamin Kramera37e7652015-07-25 17:10:49 +00002254 for (const auto &I : Builder.getVBaseOffsetOffsets()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002255 // Insert all types.
Benjamin Kramera37e7652015-07-25 17:10:49 +00002256 ClassPairTy ClassPair(RD, I.first);
2257
2258 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
Peter Collingbournecfd23562011-09-26 01:57:12 +00002259 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002260
Peter Collingbournecfd23562011-09-26 01:57:12 +00002261 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2262 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
Fangrui Song6907ce22018-07-30 19:24:48 +00002263
Peter Collingbournecfd23562011-09-26 01:57:12 +00002264 return I->second;
2265}
2266
Justin Lebar072f9ba2016-10-10 16:26:24 +00002267static std::unique_ptr<VTableLayout>
2268CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002269 SmallVector<VTableLayout::VTableThunkTy, 1>
2270 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002271
Justin Lebar072f9ba2016-10-10 16:26:24 +00002272 return llvm::make_unique<VTableLayout>(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00002273 Builder.VTableIndices, Builder.vtable_components(), VTableThunks,
2274 Builder.getAddressPoints());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002275}
2276
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002277void
2278ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Justin Lebar072f9ba2016-10-10 16:26:24 +00002279 std::unique_ptr<const VTableLayout> &Entry = VTableLayouts[RD];
Peter Collingbournecfd23562011-09-26 01:57:12 +00002280
2281 // Check if we've computed this information before.
2282 if (Entry)
2283 return;
2284
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002285 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2286 /*MostDerivedClassIsVirtual=*/0, RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002287 Entry = CreateVTableLayout(Builder);
2288
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002289 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2290 Builder.vtable_indices_end());
2291
Peter Collingbournecfd23562011-09-26 01:57:12 +00002292 // Add the known thunks.
2293 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2294
2295 // If we don't have the vbase information for this class, insert it.
2296 // getVirtualBaseOffsetOffset will compute it separately without computing
2297 // the rest of the vtable related information.
2298 if (!RD->getNumVBases())
2299 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002300
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00002301 const CXXRecordDecl *VBase =
2302 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002303
Peter Collingbournecfd23562011-09-26 01:57:12 +00002304 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2305 return;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002306
Benjamin Kramera37e7652015-07-25 17:10:49 +00002307 for (const auto &I : Builder.getVBaseOffsetOffsets()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002308 // Insert all types.
Benjamin Kramera37e7652015-07-25 17:10:49 +00002309 ClassPairTy ClassPair(RD, I.first);
2310
2311 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
Peter Collingbournecfd23562011-09-26 01:57:12 +00002312 }
2313}
2314
Justin Lebar072f9ba2016-10-10 16:26:24 +00002315std::unique_ptr<VTableLayout>
2316ItaniumVTableContext::createConstructionVTableLayout(
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002317 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2318 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2319 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2320 MostDerivedClassIsVirtual, LayoutClass);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002321 return CreateVTableLayout(Builder);
2322}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002323
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002324namespace {
2325
2326// Vtables in the Microsoft ABI are different from the Itanium ABI.
2327//
2328// The main differences are:
2329// 1. Separate vftable and vbtable.
2330//
2331// 2. Each subobject with a vfptr gets its own vftable rather than an address
2332// point in a single vtable shared between all the subobjects.
2333// Each vftable is represented by a separate section and virtual calls
2334// must be done using the vftable which has a slot for the function to be
2335// called.
2336//
2337// 3. Virtual method definitions expect their 'this' parameter to point to the
2338// first vfptr whose table provides a compatible overridden method. In many
2339// cases, this permits the original vf-table entry to directly call
2340// the method instead of passing through a thunk.
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002341// See example before VFTableBuilder::ComputeThisOffset below.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002342//
2343// A compatible overridden method is one which does not have a non-trivial
2344// covariant-return adjustment.
2345//
2346// The first vfptr is the one with the lowest offset in the complete-object
2347// layout of the defining class, and the method definition will subtract
2348// that constant offset from the parameter value to get the real 'this'
2349// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2350// function defined in a virtual base is overridden in a more derived
2351// virtual base and these bases have a reverse order in the complete
2352// object), the vf-table may require a this-adjustment thunk.
2353//
2354// 4. vftables do not contain new entries for overrides that merely require
2355// this-adjustment. Together with #3, this keeps vf-tables smaller and
2356// eliminates the need for this-adjustment thunks in many cases, at the cost
2357// of often requiring redundant work to adjust the "this" pointer.
2358//
2359// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2360// Vtordisps are emitted into the class layout if a class has
2361// a) a user-defined ctor/dtor
2362// and
2363// b) a method overriding a method in a virtual base.
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002364//
2365// To get a better understanding of this code,
2366// you might want to see examples in test/CodeGenCXX/microsoft-abi-vtables-*.cpp
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002367
2368class VFTableBuilder {
2369public:
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002370 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2371 MethodVFTableLocationsTy;
2372
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00002373 typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
2374 method_locations_range;
2375
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002376private:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002377 /// VTables - Global vtable information.
2378 MicrosoftVTableContext &VTables;
2379
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002380 /// Context - The ASTContext which we will use for layout information.
2381 ASTContext &Context;
2382
2383 /// MostDerivedClass - The most derived class for which we're building this
2384 /// vtable.
2385 const CXXRecordDecl *MostDerivedClass;
2386
2387 const ASTRecordLayout &MostDerivedClassLayout;
2388
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002389 const VPtrInfo &WhichVFPtr;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002390
2391 /// FinalOverriders - The final overriders of the most derived class.
2392 const FinalOverriders Overriders;
2393
2394 /// Components - The components of the vftable being built.
2395 SmallVector<VTableComponent, 64> Components;
2396
2397 MethodVFTableLocationsTy MethodVFTableLocations;
2398
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002399 /// Does this class have an RTTI component?
David Majnemer2d8b2002016-02-11 17:49:28 +00002400 bool HasRTTIComponent = false;
David Majnemer3c7228e2014-07-01 21:10:07 +00002401
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002402 /// MethodInfo - Contains information about a method in a vtable.
2403 /// (Used for computing 'this' pointer adjustment thunks.
2404 struct MethodInfo {
2405 /// VBTableIndex - The nonzero index in the vbtable that
2406 /// this method's base has, or zero.
2407 const uint64_t VBTableIndex;
2408
2409 /// VFTableIndex - The index in the vftable that this method has.
2410 const uint64_t VFTableIndex;
2411
2412 /// Shadowed - Indicates if this vftable slot is shadowed by
2413 /// a slot for a covariant-return override. If so, it shouldn't be printed
2414 /// or used for vcalls in the most derived class.
2415 bool Shadowed;
2416
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00002417 /// UsesExtraSlot - Indicates if this vftable slot was created because
2418 /// any of the overridden slots required a return adjusting thunk.
2419 bool UsesExtraSlot;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002420
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00002421 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex,
2422 bool UsesExtraSlot = false)
2423 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
2424 Shadowed(false), UsesExtraSlot(UsesExtraSlot) {}
2425
2426 MethodInfo()
2427 : VBTableIndex(0), VFTableIndex(0), Shadowed(false),
2428 UsesExtraSlot(false) {}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002429 };
2430
2431 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2432
2433 /// MethodInfoMap - The information for all methods in the vftable we're
2434 /// currently building.
2435 MethodInfoMapTy MethodInfoMap;
2436
2437 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2438
2439 /// VTableThunks - The thunks by vftable index in the vftable currently being
2440 /// built.
2441 VTableThunksMapTy VTableThunks;
2442
2443 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2444 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2445
2446 /// Thunks - A map that contains all the thunks needed for all methods in the
2447 /// most derived class for which the vftable is currently being built.
2448 ThunksMapTy Thunks;
2449
2450 /// AddThunk - Add a thunk for the given method.
2451 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2452 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2453
2454 // Check if we have this thunk already.
2455 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2456 ThunksVector.end())
2457 return;
2458
2459 ThunksVector.push_back(Thunk);
2460 }
2461
2462 /// ComputeThisOffset - Returns the 'this' argument offset for the given
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002463 /// method, relative to the beginning of the MostDerivedClass.
2464 CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002465
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002466 void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2467 CharUnits ThisOffset, ThisAdjustment &TA);
2468
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002469 /// AddMethod - Add a single virtual member function to the vftable
2470 /// components vector.
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002471 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002472 if (!TI.isEmpty()) {
2473 VTableThunks[Components.size()] = TI;
2474 AddThunk(MD, TI);
2475 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002476 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002477 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002478 "Destructor can't have return adjustment!");
2479 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2480 } else {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002481 Components.push_back(VTableComponent::MakeFunction(MD));
2482 }
2483 }
2484
2485 /// AddMethods - Add the methods of this base subobject and the relevant
2486 /// subbases to the vftable we're currently laying out.
2487 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2488 const CXXRecordDecl *LastVBase,
2489 BasesSetVectorTy &VisitedBases);
2490
2491 void LayoutVFTable() {
David Majnemer6e9ae782014-09-22 20:39:37 +00002492 // RTTI data goes before all other entries.
2493 if (HasRTTIComponent)
2494 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002495
2496 BasesSetVectorTy VisitedBases;
Craig Topper36250ad2014-05-12 05:36:57 +00002497 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, nullptr,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002498 VisitedBases);
David Majnemera9b7e662014-09-26 08:07:55 +00002499 assert((HasRTTIComponent ? Components.size() - 1 : Components.size()) &&
2500 "vftable can't be empty");
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002501
2502 assert(MethodVFTableLocations.empty());
Benjamin Kramera37e7652015-07-25 17:10:49 +00002503 for (const auto &I : MethodInfoMap) {
2504 const CXXMethodDecl *MD = I.first;
2505 const MethodInfo &MI = I.second;
Reid Kleckner138ab492018-05-17 18:12:18 +00002506 assert(MD == MD->getCanonicalDecl());
2507
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002508 // Skip the methods that the MostDerivedClass didn't override
2509 // and the entries shadowed by return adjusting thunks.
2510 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2511 continue;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002512 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2513 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002514 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2515 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2516 } else {
2517 MethodVFTableLocations[MD] = Loc;
2518 }
2519 }
2520 }
2521
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002522public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002523 VFTableBuilder(MicrosoftVTableContext &VTables,
Justin Lebar562914e2016-10-10 16:26:29 +00002524 const CXXRecordDecl *MostDerivedClass, const VPtrInfo &Which)
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002525 : VTables(VTables),
2526 Context(MostDerivedClass->getASTContext()),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002527 MostDerivedClass(MostDerivedClass),
2528 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
Justin Lebar562914e2016-10-10 16:26:29 +00002529 WhichVFPtr(Which),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002530 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
Reid Klecknerad1e22b2016-06-29 18:29:21 +00002531 // Provide the RTTI component if RTTIData is enabled. If the vftable would
2532 // be available externally, we should not provide the RTTI componenent. It
2533 // is currently impossible to get available externally vftables with either
2534 // dllimport or extern template instantiations, but eventually we may add a
2535 // flag to support additional devirtualization that needs this.
David Majnemer2d8b2002016-02-11 17:49:28 +00002536 if (Context.getLangOpts().RTTIData)
Reid Klecknerad1e22b2016-06-29 18:29:21 +00002537 HasRTTIComponent = true;
David Majnemerd905da42014-07-01 20:30:31 +00002538
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002539 LayoutVFTable();
2540
2541 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00002542 dumpLayout(llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002543 }
2544
2545 uint64_t getNumThunks() const { return Thunks.size(); }
2546
2547 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2548
2549 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2550
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00002551 method_locations_range vtable_locations() const {
2552 return method_locations_range(MethodVFTableLocations.begin(),
2553 MethodVFTableLocations.end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002554 }
2555
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00002556 ArrayRef<VTableComponent> vtable_components() const { return Components; }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002557
2558 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2559 return VTableThunks.begin();
2560 }
2561
2562 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2563 return VTableThunks.end();
2564 }
2565
2566 void dumpLayout(raw_ostream &);
2567};
2568
Benjamin Kramerd5748c72015-03-23 12:31:05 +00002569} // end namespace
2570
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002571// Let's study one class hierarchy as an example:
2572// struct A {
2573// virtual void f();
2574// int x;
2575// };
2576//
2577// struct B : virtual A {
2578// virtual void f();
2579// };
2580//
2581// Record layouts:
2582// struct A:
Timur Iskhodzhanov4d280022014-11-14 14:16:34 +00002583// 0 | (A vftable pointer)
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002584// 4 | int x
2585//
2586// struct B:
Timur Iskhodzhanov4d280022014-11-14 14:16:34 +00002587// 0 | (B vbtable pointer)
2588// 4 | struct A (virtual base)
2589// 4 | (A vftable pointer)
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002590// 8 | int x
2591//
2592// Let's assume we have a pointer to the A part of an object of dynamic type B:
2593// B b;
2594// A *a = (A*)&b;
2595// a->f();
2596//
2597// In this hierarchy, f() belongs to the vftable of A, so B::f() expects
2598// "this" parameter to point at the A subobject, which is B+4.
2599// In the B::f() prologue, it adjusts "this" back to B by subtracting 4,
Nico Webercda5c7c2014-11-29 23:57:35 +00002600// performed as a *static* adjustment.
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002601//
2602// Interesting thing happens when we alter the relative placement of A and B
2603// subobjects in a class:
2604// struct C : virtual B { };
2605//
2606// C c;
2607// A *a = (A*)&c;
2608// a->f();
2609//
2610// Respective record layout is:
2611// 0 | (C vbtable pointer)
2612// 4 | struct A (virtual base)
2613// 4 | (A vftable pointer)
2614// 8 | int x
2615// 12 | struct B (virtual base)
2616// 12 | (B vbtable pointer)
2617//
2618// The final overrider of f() in class C is still B::f(), so B+4 should be
2619// passed as "this" to that code. However, "a" points at B-8, so the respective
2620// vftable entry should hold a thunk that adds 12 to the "this" argument before
2621// performing a tail call to B::f().
2622//
2623// With this example in mind, we can now calculate the 'this' argument offset
2624// for the given method, relative to the beginning of the MostDerivedClass.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002625CharUnits
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002626VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00002627 BasesSetVectorTy Bases;
2628
2629 {
2630 // Find the set of least derived bases that define the given method.
2631 OverriddenMethodsSetTy VisitedOverriddenMethods;
2632 auto InitialOverriddenDefinitionCollector = [&](
2633 const CXXMethodDecl *OverriddenMD) {
2634 if (OverriddenMD->size_overridden_methods() == 0)
2635 Bases.insert(OverriddenMD->getParent());
2636 // Don't recurse on this method if we've already collected it.
2637 return VisitedOverriddenMethods.insert(OverriddenMD).second;
2638 };
2639 visitAllOverriddenMethods(Overrider.Method,
2640 InitialOverriddenDefinitionCollector);
2641 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002642
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002643 // If there are no overrides then 'this' is located
2644 // in the base that defines the method.
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00002645 if (Bases.size() == 0)
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002646 return Overrider.Offset;
2647
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002648 CXXBasePaths Paths;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002649 Overrider.Method->getParent()->lookupInBases(
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00002650 [&Bases](const CXXBaseSpecifier *Specifier, CXXBasePath &) {
2651 return Bases.count(Specifier->getType()->getAsCXXRecordDecl());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002652 },
2653 Paths);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002654
2655 // This will hold the smallest this offset among overridees of MD.
2656 // This implies that an offset of a non-virtual base will dominate an offset
2657 // of a virtual base to potentially reduce the number of thunks required
2658 // in the derived classes that inherit this method.
2659 CharUnits Ret;
2660 bool First = true;
2661
Timur Iskhodzhanoved11ae32014-04-17 22:01:48 +00002662 const ASTRecordLayout &OverriderRDLayout =
2663 Context.getASTRecordLayout(Overrider.Method->getParent());
Benjamin Kramera37e7652015-07-25 17:10:49 +00002664 for (const CXXBasePath &Path : Paths) {
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002665 CharUnits ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002666 CharUnits LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002667
Nico Weberd73258a2015-05-16 23:49:53 +00002668 // For each path from the overrider to the parents of the overridden
2669 // methods, traverse the path, calculating the this offset in the most
2670 // derived class.
Benjamin Kramera37e7652015-07-25 17:10:49 +00002671 for (const CXXBasePathElement &Element : Path) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002672 QualType CurTy = Element.Base->getType();
2673 const CXXRecordDecl *PrevRD = Element.Class,
2674 *CurRD = CurTy->getAsCXXRecordDecl();
2675 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2676
2677 if (Element.Base->isVirtual()) {
Timur Iskhodzhanoved11ae32014-04-17 22:01:48 +00002678 // The interesting things begin when you have virtual inheritance.
2679 // The final overrider will use a static adjustment equal to the offset
2680 // of the vbase in the final overrider class.
2681 // For example, if the final overrider is in a vbase B of the most
2682 // derived class and it overrides a method of the B's own vbase A,
2683 // it uses A* as "this". In its prologue, it can cast A* to B* with
2684 // a static offset. This offset is used regardless of the actual
2685 // offset of A from B in the most derived class, requiring an
2686 // this-adjusting thunk in the vftable if A and B are laid out
2687 // differently in the most derived class.
2688 LastVBaseOffset = ThisOffset =
2689 Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002690 } else {
2691 ThisOffset += Layout.getBaseClassOffset(CurRD);
2692 }
2693 }
2694
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002695 if (isa<CXXDestructorDecl>(Overrider.Method)) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002696 if (LastVBaseOffset.isZero()) {
2697 // If a "Base" class has at least one non-virtual base with a virtual
2698 // destructor, the "Base" virtual destructor will take the address
2699 // of the "Base" subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002700 ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002701 } else {
2702 // A virtual destructor of a virtual base takes the address of the
2703 // virtual base subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002704 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002705 }
2706 }
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +00002707
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002708 if (Ret > ThisOffset || First) {
2709 First = false;
2710 Ret = ThisOffset;
2711 }
2712 }
2713
2714 assert(!First && "Method not found in the given subobject?");
2715 return Ret;
2716}
2717
Timur Iskhodzhanov7d19fc12014-11-17 15:11:05 +00002718// Things are getting even more complex when the "this" adjustment has to
2719// use a dynamic offset instead of a static one, or even two dynamic offsets.
2720// This is sometimes required when a virtual call happens in the middle of
2721// a non-most-derived class construction or destruction.
2722//
2723// Let's take a look at the following example:
2724// struct A {
2725// virtual void f();
2726// };
2727//
2728// void foo(A *a) { a->f(); } // Knows nothing about siblings of A.
2729//
2730// struct B : virtual A {
2731// virtual void f();
2732// B() {
2733// foo(this);
2734// }
2735// };
2736//
2737// struct C : virtual B {
2738// virtual void f();
2739// };
2740//
2741// Record layouts for these classes are:
2742// struct A
2743// 0 | (A vftable pointer)
2744//
2745// struct B
2746// 0 | (B vbtable pointer)
2747// 4 | (vtordisp for vbase A)
2748// 8 | struct A (virtual base)
2749// 8 | (A vftable pointer)
2750//
2751// struct C
2752// 0 | (C vbtable pointer)
2753// 4 | (vtordisp for vbase A)
2754// 8 | struct A (virtual base) // A precedes B!
2755// 8 | (A vftable pointer)
2756// 12 | struct B (virtual base)
2757// 12 | (B vbtable pointer)
2758//
2759// When one creates an object of type C, the C constructor:
2760// - initializes all the vbptrs, then
2761// - calls the A subobject constructor
2762// (initializes A's vfptr with an address of A vftable), then
2763// - calls the B subobject constructor
2764// (initializes A's vfptr with an address of B vftable and vtordisp for A),
2765// that in turn calls foo(), then
2766// - initializes A's vfptr with an address of C vftable and zeroes out the
2767// vtordisp
2768// FIXME: if a structor knows it belongs to MDC, why doesn't it use a vftable
2769// without vtordisp thunks?
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002770// FIXME: how are vtordisp handled in the presence of nooverride/final?
Timur Iskhodzhanov7d19fc12014-11-17 15:11:05 +00002771//
2772// When foo() is called, an object with a layout of class C has a vftable
2773// referencing B::f() that assumes a B layout, so the "this" adjustments are
2774// incorrect, unless an extra adjustment is done. This adjustment is called
2775// "vtordisp adjustment". Vtordisp basically holds the difference between the
2776// actual location of a vbase in the layout class and the location assumed by
2777// the vftable of the class being constructed/destructed. Vtordisp is only
2778// needed if "this" escapes a
2779// structor (or we can't prove otherwise).
2780// [i.e. vtordisp is a dynamic adjustment for a static adjustment, which is an
2781// estimation of a dynamic adjustment]
2782//
2783// foo() gets a pointer to the A vbase and doesn't know anything about B or C,
2784// so it just passes that pointer as "this" in a virtual call.
2785// If there was no vtordisp, that would just dispatch to B::f().
2786// However, B::f() assumes B+8 is passed as "this",
2787// yet the pointer foo() passes along is B-4 (i.e. C+8).
2788// An extra adjustment is needed, so we emit a thunk into the B vftable.
2789// This vtordisp thunk subtracts the value of vtordisp
2790// from the "this" argument (-12) before making a tailcall to B::f().
2791//
2792// Let's consider an even more complex example:
2793// struct D : virtual B, virtual C {
2794// D() {
2795// foo(this);
2796// }
2797// };
2798//
2799// struct D
2800// 0 | (D vbtable pointer)
2801// 4 | (vtordisp for vbase A)
2802// 8 | struct A (virtual base) // A precedes both B and C!
2803// 8 | (A vftable pointer)
2804// 12 | struct B (virtual base) // B precedes C!
2805// 12 | (B vbtable pointer)
2806// 16 | struct C (virtual base)
2807// 16 | (C vbtable pointer)
2808//
2809// When D::D() calls foo(), we find ourselves in a thunk that should tailcall
2810// to C::f(), which assumes C+8 as its "this" parameter. This time, foo()
2811// passes along A, which is C-8. The A vtordisp holds
2812// "D.vbptr[index_of_A] - offset_of_A_in_D"
2813// and we statically know offset_of_A_in_D, so can get a pointer to D.
2814// When we know it, we can make an extra vbtable lookup to locate the C vbase
2815// and one extra static adjustment to calculate the expected value of C+8.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002816void VFTableBuilder::CalculateVtordispAdjustment(
2817 FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2818 ThisAdjustment &TA) {
2819 const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2820 MostDerivedClassLayout.getVBaseOffsetsMap();
2821 const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002822 VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002823 assert(VBaseMapEntry != VBaseMap.end());
2824
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002825 // If there's no vtordisp or the final overrider is defined in the same vbase
2826 // as the initial declaration, we don't need any vtordisp adjustment.
2827 if (!VBaseMapEntry->second.hasVtorDisp() ||
2828 Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
Timur Iskhodzhanov057fa3a2014-04-17 11:01:41 +00002829 return;
2830
2831 // OK, now we know we need to use a vtordisp thunk.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002832 // The implicit vtordisp field is located right before the vbase.
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002833 CharUnits OffsetOfVBaseWithVFPtr = VBaseMapEntry->second.VBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002834 TA.Virtual.Microsoft.VtordispOffset =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002835 (OffsetOfVBaseWithVFPtr - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002836
Timur Iskhodzhanov057fa3a2014-04-17 11:01:41 +00002837 // A simple vtordisp thunk will suffice if the final overrider is defined
2838 // in either the most derived class or its non-virtual base.
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002839 if (Overrider.Method->getParent() == MostDerivedClass ||
2840 !Overrider.VirtualBase)
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002841 return;
2842
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002843 // Otherwise, we need to do use the dynamic offset of the final overrider
2844 // in order to get "this" adjustment right.
2845 TA.Virtual.Microsoft.VBPtrOffset =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002846 (OffsetOfVBaseWithVFPtr + WhichVFPtr.NonVirtualOffset -
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002847 MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2848 TA.Virtual.Microsoft.VBOffsetOffset =
2849 Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002850 VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002851
2852 TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2853}
2854
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002855static void GroupNewVirtualOverloads(
2856 const CXXRecordDecl *RD,
2857 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2858 // Put the virtual methods into VirtualMethods in the proper order:
2859 // 1) Group overloads by declaration name. New groups are added to the
2860 // vftable in the order of their first declarations in this class
David Majnemer70effde2015-11-19 00:03:54 +00002861 // (including overrides, non-virtual methods and any other named decl that
2862 // might be nested within the class).
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002863 // 2) In each group, new overloads appear in the reverse order of declaration.
2864 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2865 SmallVector<MethodGroup, 10> Groups;
2866 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2867 VisitedGroupIndicesTy VisitedGroupIndices;
David Majnemer70effde2015-11-19 00:03:54 +00002868 for (const auto *D : RD->decls()) {
2869 const auto *ND = dyn_cast<NamedDecl>(D);
2870 if (!ND)
2871 continue;
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002872 VisitedGroupIndicesTy::iterator J;
2873 bool Inserted;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002874 std::tie(J, Inserted) = VisitedGroupIndices.insert(
David Majnemer70effde2015-11-19 00:03:54 +00002875 std::make_pair(ND->getDeclName(), Groups.size()));
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002876 if (Inserted)
Reid Kleckner6701de22014-02-19 22:06:10 +00002877 Groups.push_back(MethodGroup());
David Majnemer70effde2015-11-19 00:03:54 +00002878 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
2879 if (MD->isVirtual())
2880 Groups[J->second].push_back(MD->getCanonicalDecl());
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002881 }
2882
Benjamin Kramera37e7652015-07-25 17:10:49 +00002883 for (const MethodGroup &Group : Groups)
2884 VirtualMethods.append(Group.rbegin(), Group.rend());
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002885}
2886
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002887static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
2888 for (const auto &B : RD->bases()) {
2889 if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
2890 return true;
2891 }
2892 return false;
2893}
2894
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002895void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2896 const CXXRecordDecl *LastVBase,
2897 BasesSetVectorTy &VisitedBases) {
2898 const CXXRecordDecl *RD = Base.getBase();
2899 if (!RD->isPolymorphic())
2900 return;
2901
2902 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2903
2904 // See if this class expands a vftable of the base we look at, which is either
Nico Weberd73258a2015-05-16 23:49:53 +00002905 // the one defined by the vfptr base path or the primary base of the current
2906 // class.
Craig Topper36250ad2014-05-12 05:36:57 +00002907 const CXXRecordDecl *NextBase = nullptr, *NextLastVBase = LastVBase;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002908 CharUnits NextBaseOffset;
Reid Kleckner8ad06d62016-07-20 14:40:25 +00002909 if (BaseDepth < WhichVFPtr.PathToIntroducingObject.size()) {
2910 NextBase = WhichVFPtr.PathToIntroducingObject[BaseDepth];
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002911 if (isDirectVBase(NextBase, RD)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002912 NextLastVBase = NextBase;
2913 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2914 } else {
2915 NextBaseOffset =
2916 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2917 }
2918 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2919 assert(!Layout.isPrimaryBaseVirtual() &&
2920 "No primary virtual bases in this ABI");
2921 NextBase = PrimaryBase;
2922 NextBaseOffset = Base.getBaseOffset();
2923 }
2924
2925 if (NextBase) {
2926 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2927 NextLastVBase, VisitedBases);
2928 if (!VisitedBases.insert(NextBase))
2929 llvm_unreachable("Found a duplicate primary base!");
2930 }
2931
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002932 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2933 // Put virtual methods in the proper order.
2934 GroupNewVirtualOverloads(RD, VirtualMethods);
2935
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002936 // Now go through all virtual member functions and add them to the current
2937 // vftable. This is done by
2938 // - replacing overridden methods in their existing slots, as long as they
2939 // don't require return adjustment; calculating This adjustment if needed.
2940 // - adding new slots for methods of the current base not present in any
2941 // sub-bases;
2942 // - adding new slots for methods that require Return adjustment.
2943 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Benjamin Kramera37e7652015-07-25 17:10:49 +00002944 for (const CXXMethodDecl *MD : VirtualMethods) {
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002945 FinalOverriders::OverriderInfo FinalOverrider =
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002946 Overriders.getOverrider(MD, Base.getBaseOffset());
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002947 const CXXMethodDecl *FinalOverriderMD = FinalOverrider.Method;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002948 const CXXMethodDecl *OverriddenMD =
2949 FindNearestOverriddenMethod(MD, VisitedBases);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002950
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002951 ThisAdjustment ThisAdjustmentOffset;
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00002952 bool ReturnAdjustingThunk = false, ForceReturnAdjustmentMangling = false;
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002953 CharUnits ThisOffset = ComputeThisOffset(FinalOverrider);
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002954 ThisAdjustmentOffset.NonVirtual =
2955 (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002956 if ((OverriddenMD || FinalOverriderMD != MD) &&
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002957 WhichVFPtr.getVBaseWithVPtr())
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002958 CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
2959 ThisAdjustmentOffset);
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002960
Reid Klecknerdd6fc832017-08-29 17:40:04 +00002961 unsigned VBIndex =
2962 LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
2963
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002964 if (OverriddenMD) {
Nico Weberd73258a2015-05-16 23:49:53 +00002965 // If MD overrides anything in this vftable, we need to update the
2966 // entries.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002967 MethodInfoMapTy::iterator OverriddenMDIterator =
2968 MethodInfoMap.find(OverriddenMD);
2969
2970 // If the overridden method went to a different vftable, skip it.
2971 if (OverriddenMDIterator == MethodInfoMap.end())
2972 continue;
2973
2974 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2975
Reid Klecknerdd6fc832017-08-29 17:40:04 +00002976 VBIndex = OverriddenMethodInfo.VBTableIndex;
2977
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00002978 // Let's check if the overrider requires any return adjustments.
2979 // We must create a new slot if the MD's return type is not trivially
2980 // convertible to the OverriddenMD's one.
2981 // Once a chain of method overrides adds a return adjusting vftable slot,
2982 // all subsequent overrides will also use an extra method slot.
2983 ReturnAdjustingThunk = !ComputeReturnAdjustmentBaseOffset(
2984 Context, MD, OverriddenMD).isEmpty() ||
2985 OverriddenMethodInfo.UsesExtraSlot;
2986
2987 if (!ReturnAdjustingThunk) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002988 // No return adjustment needed - just replace the overridden method info
2989 // with the current info.
Reid Klecknerdd6fc832017-08-29 17:40:04 +00002990 MethodInfo MI(VBIndex, OverriddenMethodInfo.VFTableIndex);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002991 MethodInfoMap.erase(OverriddenMDIterator);
2992
2993 assert(!MethodInfoMap.count(MD) &&
2994 "Should not have method info for this method yet!");
2995 MethodInfoMap.insert(std::make_pair(MD, MI));
2996 continue;
Reid Kleckner31a9f742013-12-27 20:29:16 +00002997 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002998
Reid Kleckner31a9f742013-12-27 20:29:16 +00002999 // In case we need a return adjustment, we'll add a new slot for
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003000 // the overrider. Mark the overridden method as shadowed by the new slot.
Reid Kleckner31a9f742013-12-27 20:29:16 +00003001 OverriddenMethodInfo.Shadowed = true;
Reid Kleckner31a9f742013-12-27 20:29:16 +00003002
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003003 // Force a special name mangling for a return-adjusting thunk
3004 // unless the method is the final overrider without this adjustment.
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003005 ForceReturnAdjustmentMangling =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003006 !(MD == FinalOverriderMD && ThisAdjustmentOffset.isEmpty());
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003007 } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003008 MD->size_overridden_methods()) {
3009 // Skip methods that don't belong to the vftable of the current class,
3010 // e.g. each method that wasn't seen in any of the visited sub-bases
3011 // but overrides multiple methods of other sub-bases.
3012 continue;
3013 }
3014
3015 // If we got here, MD is a method not seen in any of the sub-bases or
3016 // it requires return adjustment. Insert the method info for this method.
David Majnemer3c7228e2014-07-01 21:10:07 +00003017 MethodInfo MI(VBIndex,
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003018 HasRTTIComponent ? Components.size() - 1 : Components.size(),
3019 ReturnAdjustingThunk);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003020
3021 assert(!MethodInfoMap.count(MD) &&
3022 "Should not have method info for this method yet!");
3023 MethodInfoMap.insert(std::make_pair(MD, MI));
3024
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003025 // Check if this overrider needs a return adjustment.
3026 // We don't want to do this for pure virtual member functions.
3027 BaseOffset ReturnAdjustmentOffset;
3028 ReturnAdjustment ReturnAdjustment;
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003029 if (!FinalOverriderMD->isPure()) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003030 ReturnAdjustmentOffset =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003031 ComputeReturnAdjustmentBaseOffset(Context, FinalOverriderMD, MD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003032 }
3033 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003034 ForceReturnAdjustmentMangling = true;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003035 ReturnAdjustment.NonVirtual =
3036 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
3037 if (ReturnAdjustmentOffset.VirtualBase) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003038 const ASTRecordLayout &DerivedLayout =
3039 Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
3040 ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
3041 DerivedLayout.getVBPtrOffset().getQuantity();
3042 ReturnAdjustment.Virtual.Microsoft.VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003043 VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
3044 ReturnAdjustmentOffset.VirtualBase);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003045 }
3046 }
3047
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003048 AddMethod(FinalOverriderMD,
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003049 ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
3050 ForceReturnAdjustmentMangling ? MD : nullptr));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003051 }
3052}
3053
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003054static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
Benjamin Kramera37e7652015-07-25 17:10:49 +00003055 for (const CXXRecordDecl *Elem :
3056 llvm::make_range(Path.rbegin(), Path.rend())) {
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003057 Out << "'";
Benjamin Kramera37e7652015-07-25 17:10:49 +00003058 Elem->printQualifiedName(Out);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003059 Out << "' in ";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003060 }
3061}
3062
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003063static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
3064 bool ContinueFirstLine) {
3065 const ReturnAdjustment &R = TI.Return;
3066 bool Multiline = false;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003067 const char *LinePrefix = "\n ";
3068 if (!R.isEmpty() || TI.Method) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003069 if (!ContinueFirstLine)
3070 Out << LinePrefix;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003071 Out << "[return adjustment (to type '"
3072 << TI.Method->getReturnType().getCanonicalType().getAsString()
3073 << "'): ";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003074 if (R.Virtual.Microsoft.VBPtrOffset)
3075 Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
3076 if (R.Virtual.Microsoft.VBIndex)
3077 Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
3078 Out << R.NonVirtual << " non-virtual]";
3079 Multiline = true;
3080 }
3081
3082 const ThisAdjustment &T = TI.This;
3083 if (!T.isEmpty()) {
3084 if (Multiline || !ContinueFirstLine)
3085 Out << LinePrefix;
3086 Out << "[this adjustment: ";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003087 if (!TI.This.Virtual.isEmpty()) {
3088 assert(T.Virtual.Microsoft.VtordispOffset < 0);
3089 Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
3090 if (T.Virtual.Microsoft.VBPtrOffset) {
3091 Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003092 << " to the left,";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003093 assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
3094 Out << LinePrefix << " vboffset at "
3095 << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
3096 }
3097 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003098 Out << T.NonVirtual << " non-virtual]";
3099 }
3100}
3101
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003102void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3103 Out << "VFTable for ";
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003104 PrintBasePath(WhichVFPtr.PathToIntroducingObject, Out);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003105 Out << "'";
3106 MostDerivedClass->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003107 Out << "' (" << Components.size()
3108 << (Components.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003109
3110 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3111 Out << llvm::format("%4d | ", I);
3112
3113 const VTableComponent &Component = Components[I];
3114
3115 // Dump the component.
3116 switch (Component.getKind()) {
3117 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003118 Component.getRTTIDecl()->printQualifiedName(Out);
3119 Out << " RTTI";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003120 break;
3121
3122 case VTableComponent::CK_FunctionPointer: {
3123 const CXXMethodDecl *MD = Component.getFunctionDecl();
3124
Reid Kleckner604c8b42013-12-27 19:43:59 +00003125 // FIXME: Figure out how to print the real thunk type, since they can
3126 // differ in the return type.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003127 std::string Str = PredefinedExpr::ComputeName(
3128 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3129 Out << Str;
3130 if (MD->isPure())
3131 Out << " [pure]";
3132
David Majnemerd59becb2014-09-12 04:38:08 +00003133 if (MD->isDeleted())
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003134 Out << " [deleted]";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003135
3136 ThunkInfo Thunk = VTableThunks.lookup(I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003137 if (!Thunk.isEmpty())
3138 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003139
3140 break;
3141 }
3142
3143 case VTableComponent::CK_DeletingDtorPointer: {
3144 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3145
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003146 DD->printQualifiedName(Out);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003147 Out << "() [scalar deleting]";
3148
3149 if (DD->isPure())
3150 Out << " [pure]";
3151
3152 ThunkInfo Thunk = VTableThunks.lookup(I);
3153 if (!Thunk.isEmpty()) {
3154 assert(Thunk.Return.isEmpty() &&
3155 "No return adjustment needed for destructors!");
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003156 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003157 }
3158
3159 break;
3160 }
3161
3162 default:
3163 DiagnosticsEngine &Diags = Context.getDiagnostics();
3164 unsigned DiagID = Diags.getCustomDiagID(
3165 DiagnosticsEngine::Error,
3166 "Unexpected vftable component type %0 for component number %1");
3167 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3168 << I << Component.getKind();
3169 }
3170
3171 Out << '\n';
3172 }
3173
3174 Out << '\n';
3175
3176 if (!Thunks.empty()) {
3177 // We store the method names in a map to get a stable order.
3178 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3179
Benjamin Kramera37e7652015-07-25 17:10:49 +00003180 for (const auto &I : Thunks) {
3181 const CXXMethodDecl *MD = I.first;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003182 std::string MethodName = PredefinedExpr::ComputeName(
3183 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3184
3185 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3186 }
3187
Benjamin Kramera37e7652015-07-25 17:10:49 +00003188 for (const auto &MethodNameAndDecl : MethodNamesAndDecls) {
3189 const std::string &MethodName = MethodNameAndDecl.first;
3190 const CXXMethodDecl *MD = MethodNameAndDecl.second;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003191
3192 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00003193 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003194 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
3195 // Keep different thunks with the same adjustments in the order they
3196 // were put into the vector.
Benjamin Kramera741b8c2014-03-03 20:26:46 +00003197 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003198 });
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003199
3200 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3201 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3202
3203 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3204 const ThunkInfo &Thunk = ThunksVector[I];
3205
3206 Out << llvm::format("%4d | ", I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003207 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003208 Out << '\n';
3209 }
3210
3211 Out << '\n';
3212 }
3213 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003214
3215 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003216}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003217
Reid Kleckner5f080942014-01-03 23:42:00 +00003218static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
Craig Topper3cb91b22014-08-27 06:28:16 +00003219 ArrayRef<const CXXRecordDecl *> B) {
Benjamin Kramera37e7652015-07-25 17:10:49 +00003220 for (const CXXRecordDecl *Decl : B) {
3221 if (A.count(Decl))
Reid Kleckner5f080942014-01-03 23:42:00 +00003222 return true;
3223 }
3224 return false;
3225}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003226
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003227static bool rebucketPaths(VPtrInfoVector &Paths);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003228
Reid Kleckner5f080942014-01-03 23:42:00 +00003229/// Produces MSVC-compatible vbtable data. The symbols produced by this
3230/// algorithm match those produced by MSVC 2012 and newer, which is different
3231/// from MSVC 2010.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003232///
3233/// MSVC 2012 appears to minimize the vbtable names using the following
3234/// algorithm. First, walk the class hierarchy in the usual order, depth first,
3235/// left to right, to find all of the subobjects which contain a vbptr field.
3236/// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3237/// record with a vbptr creates an initially empty path.
3238///
3239/// To combine paths from child nodes, the paths are compared to check for
3240/// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3241/// components in the same order. Each group of ambiguous paths is extended by
3242/// appending the class of the base from which it came. If the current class
3243/// node produced an ambiguous path, its path is extended with the current class.
3244/// After extending paths, MSVC again checks for ambiguity, and extends any
3245/// ambiguous path which wasn't already extended. Because each node yields an
3246/// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3247/// to produce an unambiguous set of paths.
3248///
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003249/// TODO: Presumably vftables use the same algorithm.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003250void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3251 const CXXRecordDecl *RD,
3252 VPtrInfoVector &Paths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003253 assert(Paths.empty());
3254 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003255
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003256 // Base case: this subobject has its own vptr.
3257 if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
Justin Lebar562914e2016-10-10 16:26:29 +00003258 Paths.push_back(llvm::make_unique<VPtrInfo>(RD));
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003259
Reid Kleckner5f080942014-01-03 23:42:00 +00003260 // Recursive case: get all the vbtables from our bases and remove anything
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003261 // that shares a virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003262 llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003263 for (const auto &B : RD->bases()) {
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003264 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
3265 if (B.isVirtual() && VBasesSeen.count(Base))
Reid Kleckner5f080942014-01-03 23:42:00 +00003266 continue;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003267
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003268 if (!Base->isDynamicClass())
3269 continue;
Reid Kleckner5f080942014-01-03 23:42:00 +00003270
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003271 const VPtrInfoVector &BasePaths =
3272 ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3273
Justin Lebar562914e2016-10-10 16:26:29 +00003274 for (const std::unique_ptr<VPtrInfo> &BaseInfo : BasePaths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003275 // Don't include the path if it goes through a virtual base that we've
3276 // already included.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003277 if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
Reid Kleckner5f080942014-01-03 23:42:00 +00003278 continue;
3279
3280 // Copy the path and adjust it as necessary.
Justin Lebar562914e2016-10-10 16:26:29 +00003281 auto P = llvm::make_unique<VPtrInfo>(*BaseInfo);
Reid Kleckner5f080942014-01-03 23:42:00 +00003282
3283 // We mangle Base into the path if the path would've been ambiguous and it
3284 // wasn't already extended with Base.
3285 if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3286 P->NextBaseToMangle = Base;
3287
Reid Klecknerfd385402014-04-17 22:47:52 +00003288 // Keep track of which vtable the derived class is going to extend with
3289 // new methods or bases. We append to either the vftable of our primary
3290 // base, or the first non-virtual base that has a vbtable.
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003291 if (P->ObjectWithVPtr == Base &&
Reid Klecknerfd385402014-04-17 22:47:52 +00003292 Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003293 : Layout.getPrimaryBase()))
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003294 P->ObjectWithVPtr = RD;
Reid Klecknerfd385402014-04-17 22:47:52 +00003295
3296 // Keep track of the full adjustment from the MDC to this vtable. The
3297 // adjustment is captured by an optional vbase and a non-virtual offset.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003298 if (B.isVirtual())
Reid Kleckner5f080942014-01-03 23:42:00 +00003299 P->ContainingVBases.push_back(Base);
3300 else if (P->ContainingVBases.empty())
3301 P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3302
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003303 // Update the full offset in the MDC.
3304 P->FullOffsetInMDC = P->NonVirtualOffset;
3305 if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3306 P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3307
Justin Lebar562914e2016-10-10 16:26:29 +00003308 Paths.push_back(std::move(P));
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003309 }
3310
Timur Iskhodzhanov9ae7d3b2014-03-31 11:01:51 +00003311 if (B.isVirtual())
3312 VBasesSeen.insert(Base);
3313
Reid Kleckner5f080942014-01-03 23:42:00 +00003314 // After visiting any direct base, we've transitively visited all of its
3315 // morally virtual bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003316 for (const auto &VB : Base->vbases())
3317 VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003318 }
3319
Reid Kleckner5f080942014-01-03 23:42:00 +00003320 // Sort the paths into buckets, and if any of them are ambiguous, extend all
3321 // paths in ambiguous buckets.
3322 bool Changed = true;
3323 while (Changed)
3324 Changed = rebucketPaths(Paths);
3325}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003326
Justin Lebar562914e2016-10-10 16:26:29 +00003327static bool extendPath(VPtrInfo &P) {
3328 if (P.NextBaseToMangle) {
3329 P.MangledPath.push_back(P.NextBaseToMangle);
3330 P.NextBaseToMangle = nullptr;// Prevent the path from being extended twice.
Reid Kleckner5f080942014-01-03 23:42:00 +00003331 return true;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003332 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003333 return false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003334}
3335
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003336static bool rebucketPaths(VPtrInfoVector &Paths) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003337 // What we're essentially doing here is bucketing together ambiguous paths.
3338 // Any bucket with more than one path in it gets extended by NextBase, which
3339 // is usually the direct base of the inherited the vbptr. This code uses a
3340 // sorted vector to implement a multiset to form the buckets. Note that the
3341 // ordering is based on pointers, but it doesn't change our output order. The
3342 // current algorithm is designed to match MSVC 2012's names.
Justin Lebar76d4def2016-10-10 19:26:22 +00003343 llvm::SmallVector<std::reference_wrapper<VPtrInfo>, 2> PathsSorted;
3344 PathsSorted.reserve(Paths.size());
3345 for (auto& P : Paths)
3346 PathsSorted.push_back(*P);
Fangrui Song55fab262018-09-26 22:16:28 +00003347 llvm::sort(PathsSorted, [](const VPtrInfo &LHS, const VPtrInfo &RHS) {
Justin Lebar562914e2016-10-10 16:26:29 +00003348 return LHS.MangledPath < RHS.MangledPath;
Benjamin Kramer15ae7832014-03-07 21:35:40 +00003349 });
Reid Kleckner5f080942014-01-03 23:42:00 +00003350 bool Changed = false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003351 for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3352 // Scan forward to find the end of the bucket.
3353 size_t BucketStart = I;
3354 do {
3355 ++I;
Justin Lebar562914e2016-10-10 16:26:29 +00003356 } while (I != E &&
3357 PathsSorted[BucketStart].get().MangledPath ==
3358 PathsSorted[I].get().MangledPath);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003359
3360 // If this bucket has multiple paths, extend them all.
3361 if (I - BucketStart > 1) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003362 for (size_t II = BucketStart; II != I; ++II)
Reid Kleckner5f080942014-01-03 23:42:00 +00003363 Changed |= extendPath(PathsSorted[II]);
3364 assert(Changed && "no paths were extended to fix ambiguity");
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003365 }
3366 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003367 return Changed;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003368}
3369
Justin Lebar03b06202016-10-10 16:26:36 +00003370MicrosoftVTableContext::~MicrosoftVTableContext() {}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003371
David Majnemerab130922015-05-04 18:47:54 +00003372namespace {
3373typedef llvm::SetVector<BaseSubobject, std::vector<BaseSubobject>,
3374 llvm::DenseSet<BaseSubobject>> FullPathTy;
3375}
3376
3377// This recursive function finds all paths from a subobject centered at
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003378// (RD, Offset) to the subobject located at IntroducingObject.
David Majnemerab130922015-05-04 18:47:54 +00003379static void findPathsToSubobject(ASTContext &Context,
3380 const ASTRecordLayout &MostDerivedLayout,
3381 const CXXRecordDecl *RD, CharUnits Offset,
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003382 BaseSubobject IntroducingObject,
David Majnemerab130922015-05-04 18:47:54 +00003383 FullPathTy &FullPath,
3384 std::list<FullPathTy> &Paths) {
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003385 if (BaseSubobject(RD, Offset) == IntroducingObject) {
David Majnemerab130922015-05-04 18:47:54 +00003386 Paths.push_back(FullPath);
3387 return;
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003388 }
3389
3390 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3391
David Majnemerab130922015-05-04 18:47:54 +00003392 for (const CXXBaseSpecifier &BS : RD->bases()) {
David Majnemeread97572015-05-01 21:35:41 +00003393 const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
David Majnemerab130922015-05-04 18:47:54 +00003394 CharUnits NewOffset = BS.isVirtual()
3395 ? MostDerivedLayout.getVBaseClassOffset(Base)
3396 : Offset + Layout.getBaseClassOffset(Base);
3397 FullPath.insert(BaseSubobject(Base, NewOffset));
3398 findPathsToSubobject(Context, MostDerivedLayout, Base, NewOffset,
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003399 IntroducingObject, FullPath, Paths);
David Majnemerab130922015-05-04 18:47:54 +00003400 FullPath.pop_back();
3401 }
3402}
David Majnemerd950f152015-04-30 17:15:48 +00003403
David Majnemerab130922015-05-04 18:47:54 +00003404// Return the paths which are not subsets of other paths.
3405static void removeRedundantPaths(std::list<FullPathTy> &FullPaths) {
3406 FullPaths.remove_if([&](const FullPathTy &SpecificPath) {
3407 for (const FullPathTy &OtherPath : FullPaths) {
3408 if (&SpecificPath == &OtherPath)
David Majnemer70e6a002015-05-01 21:35:45 +00003409 continue;
Fangrui Song3117b172018-10-20 17:53:42 +00003410 if (llvm::all_of(SpecificPath, [&](const BaseSubobject &BSO) {
3411 return OtherPath.count(BSO) != 0;
3412 })) {
David Majnemerab130922015-05-04 18:47:54 +00003413 return true;
David Majnemer70e6a002015-05-01 21:35:45 +00003414 }
David Majnemerd950f152015-04-30 17:15:48 +00003415 }
David Majnemerab130922015-05-04 18:47:54 +00003416 return false;
3417 });
3418}
3419
3420static CharUnits getOffsetOfFullPath(ASTContext &Context,
3421 const CXXRecordDecl *RD,
3422 const FullPathTy &FullPath) {
3423 const ASTRecordLayout &MostDerivedLayout =
3424 Context.getASTRecordLayout(RD);
3425 CharUnits Offset = CharUnits::fromQuantity(-1);
3426 for (const BaseSubobject &BSO : FullPath) {
3427 const CXXRecordDecl *Base = BSO.getBase();
3428 // The first entry in the path is always the most derived record, skip it.
3429 if (Base == RD) {
3430 assert(Offset.getQuantity() == -1);
3431 Offset = CharUnits::Zero();
3432 continue;
3433 }
3434 assert(Offset.getQuantity() != -1);
3435 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3436 // While we know which base has to be traversed, we don't know if that base
3437 // was a virtual base.
3438 const CXXBaseSpecifier *BaseBS = std::find_if(
3439 RD->bases_begin(), RD->bases_end(), [&](const CXXBaseSpecifier &BS) {
3440 return BS.getType()->getAsCXXRecordDecl() == Base;
3441 });
3442 Offset = BaseBS->isVirtual() ? MostDerivedLayout.getVBaseClassOffset(Base)
3443 : Offset + Layout.getBaseClassOffset(Base);
3444 RD = Base;
David Majnemerd950f152015-04-30 17:15:48 +00003445 }
David Majnemerab130922015-05-04 18:47:54 +00003446 return Offset;
3447}
David Majnemeread97572015-05-01 21:35:41 +00003448
David Majnemerab130922015-05-04 18:47:54 +00003449// We want to select the path which introduces the most covariant overrides. If
3450// two paths introduce overrides which the other path doesn't contain, issue a
3451// diagnostic.
3452static const FullPathTy *selectBestPath(ASTContext &Context,
Justin Lebar562914e2016-10-10 16:26:29 +00003453 const CXXRecordDecl *RD,
3454 const VPtrInfo &Info,
David Majnemerab130922015-05-04 18:47:54 +00003455 std::list<FullPathTy> &FullPaths) {
David Majnemere48630f2015-05-05 01:39:20 +00003456 // Handle some easy cases first.
3457 if (FullPaths.empty())
3458 return nullptr;
3459 if (FullPaths.size() == 1)
3460 return &FullPaths.front();
3461
David Majnemerab130922015-05-04 18:47:54 +00003462 const FullPathTy *BestPath = nullptr;
3463 typedef std::set<const CXXMethodDecl *> OverriderSetTy;
3464 OverriderSetTy LastOverrides;
3465 for (const FullPathTy &SpecificPath : FullPaths) {
David Majnemere48630f2015-05-05 01:39:20 +00003466 assert(!SpecificPath.empty());
David Majnemerab130922015-05-04 18:47:54 +00003467 OverriderSetTy CurrentOverrides;
3468 const CXXRecordDecl *TopLevelRD = SpecificPath.begin()->getBase();
3469 // Find the distance from the start of the path to the subobject with the
3470 // VPtr.
3471 CharUnits BaseOffset =
3472 getOffsetOfFullPath(Context, TopLevelRD, SpecificPath);
3473 FinalOverriders Overriders(TopLevelRD, CharUnits::Zero(), TopLevelRD);
Justin Lebar562914e2016-10-10 16:26:29 +00003474 for (const CXXMethodDecl *MD : Info.IntroducingObject->methods()) {
David Majnemerab130922015-05-04 18:47:54 +00003475 if (!MD->isVirtual())
3476 continue;
3477 FinalOverriders::OverriderInfo OI =
3478 Overriders.getOverrider(MD->getCanonicalDecl(), BaseOffset);
David Majnemere48630f2015-05-05 01:39:20 +00003479 const CXXMethodDecl *OverridingMethod = OI.Method;
David Majnemerab130922015-05-04 18:47:54 +00003480 // Only overriders which have a return adjustment introduce problematic
3481 // thunks.
David Majnemere48630f2015-05-05 01:39:20 +00003482 if (ComputeReturnAdjustmentBaseOffset(Context, OverridingMethod, MD)
3483 .isEmpty())
David Majnemerab130922015-05-04 18:47:54 +00003484 continue;
3485 // It's possible that the overrider isn't in this path. If so, skip it
3486 // because this path didn't introduce it.
David Majnemere48630f2015-05-05 01:39:20 +00003487 const CXXRecordDecl *OverridingParent = OverridingMethod->getParent();
Fangrui Song3117b172018-10-20 17:53:42 +00003488 if (llvm::none_of(SpecificPath, [&](const BaseSubobject &BSO) {
3489 return BSO.getBase() == OverridingParent;
3490 }))
David Majnemerab130922015-05-04 18:47:54 +00003491 continue;
David Majnemere48630f2015-05-05 01:39:20 +00003492 CurrentOverrides.insert(OverridingMethod);
David Majnemerab130922015-05-04 18:47:54 +00003493 }
3494 OverriderSetTy NewOverrides =
3495 llvm::set_difference(CurrentOverrides, LastOverrides);
3496 if (NewOverrides.empty())
3497 continue;
3498 OverriderSetTy MissingOverrides =
3499 llvm::set_difference(LastOverrides, CurrentOverrides);
3500 if (MissingOverrides.empty()) {
3501 // This path is a strict improvement over the last path, let's use it.
3502 BestPath = &SpecificPath;
3503 std::swap(CurrentOverrides, LastOverrides);
3504 } else {
3505 // This path introduces an overrider with a conflicting covariant thunk.
3506 DiagnosticsEngine &Diags = Context.getDiagnostics();
3507 const CXXMethodDecl *CovariantMD = *NewOverrides.begin();
3508 const CXXMethodDecl *ConflictMD = *MissingOverrides.begin();
3509 Diags.Report(RD->getLocation(), diag::err_vftable_ambiguous_component)
3510 << RD;
3511 Diags.Report(CovariantMD->getLocation(), diag::note_covariant_thunk)
3512 << CovariantMD;
3513 Diags.Report(ConflictMD->getLocation(), diag::note_covariant_thunk)
3514 << ConflictMD;
3515 }
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003516 }
David Majnemere48630f2015-05-05 01:39:20 +00003517 // Go with the path that introduced the most covariant overrides. If there is
3518 // no such path, pick the first path.
3519 return BestPath ? BestPath : &FullPaths.front();
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003520}
3521
3522static void computeFullPathsForVFTables(ASTContext &Context,
3523 const CXXRecordDecl *RD,
3524 VPtrInfoVector &Paths) {
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003525 const ASTRecordLayout &MostDerivedLayout = Context.getASTRecordLayout(RD);
David Majnemerab130922015-05-04 18:47:54 +00003526 FullPathTy FullPath;
3527 std::list<FullPathTy> FullPaths;
Justin Lebar562914e2016-10-10 16:26:29 +00003528 for (const std::unique_ptr<VPtrInfo>& Info : Paths) {
David Majnemerab130922015-05-04 18:47:54 +00003529 findPathsToSubobject(
3530 Context, MostDerivedLayout, RD, CharUnits::Zero(),
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003531 BaseSubobject(Info->IntroducingObject, Info->FullOffsetInMDC), FullPath,
David Majnemerab130922015-05-04 18:47:54 +00003532 FullPaths);
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003533 FullPath.clear();
David Majnemerab130922015-05-04 18:47:54 +00003534 removeRedundantPaths(FullPaths);
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003535 Info->PathToIntroducingObject.clear();
David Majnemerab130922015-05-04 18:47:54 +00003536 if (const FullPathTy *BestPath =
Justin Lebar562914e2016-10-10 16:26:29 +00003537 selectBestPath(Context, RD, *Info, FullPaths))
David Majnemerab130922015-05-04 18:47:54 +00003538 for (const BaseSubobject &BSO : *BestPath)
Reid Kleckner8ad06d62016-07-20 14:40:25 +00003539 Info->PathToIntroducingObject.push_back(BSO.getBase());
David Majnemerab130922015-05-04 18:47:54 +00003540 FullPaths.clear();
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003541 }
3542}
3543
Reid Klecknercbec0262018-04-02 20:00:39 +00003544static bool vfptrIsEarlierInMDC(const ASTRecordLayout &Layout,
3545 const MethodVFTableLocation &LHS,
3546 const MethodVFTableLocation &RHS) {
Reid Klecknereed88202018-03-28 18:23:35 +00003547 CharUnits L = LHS.VFPtrOffset;
3548 CharUnits R = RHS.VFPtrOffset;
3549 if (LHS.VBase)
3550 L += Layout.getVBaseClassOffset(LHS.VBase);
3551 if (RHS.VBase)
3552 R += Layout.getVBaseClassOffset(RHS.VBase);
3553 return L < R;
3554}
3555
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003556void MicrosoftVTableContext::computeVTableRelatedInformation(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003557 const CXXRecordDecl *RD) {
3558 assert(RD->isDynamicClass());
3559
3560 // Check if we've computed this information before.
3561 if (VFPtrLocations.count(RD))
3562 return;
3563
3564 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3565
Justin Lebar562914e2016-10-10 16:26:29 +00003566 {
Reid Klecknercbec0262018-04-02 20:00:39 +00003567 auto VFPtrs = llvm::make_unique<VPtrInfoVector>();
3568 computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3569 computeFullPathsForVFTables(Context, RD, *VFPtrs);
Justin Lebar562914e2016-10-10 16:26:29 +00003570 VFPtrLocations[RD] = std::move(VFPtrs);
3571 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003572
3573 MethodVFTableLocationsTy NewMethodLocations;
Reid Klecknercbec0262018-04-02 20:00:39 +00003574 for (const std::unique_ptr<VPtrInfo> &VFPtr : *VFPtrLocations[RD]) {
Justin Lebar562914e2016-10-10 16:26:29 +00003575 VFTableBuilder Builder(*this, RD, *VFPtr);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003576
Benjamin Kramera37e7652015-07-25 17:10:49 +00003577 VFTableIdTy id(RD, VFPtr->FullOffsetInMDC);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003578 assert(VFTableLayouts.count(id) == 0);
3579 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3580 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Justin Lebare920cfa2016-10-10 16:26:33 +00003581 VFTableLayouts[id] = llvm::make_unique<VTableLayout>(
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00003582 ArrayRef<size_t>{0}, Builder.vtable_components(), VTableThunks,
3583 EmptyAddressPointsMap);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003584 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00003585
Reid Klecknereed88202018-03-28 18:23:35 +00003586 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003587 for (const auto &Loc : Builder.vtable_locations()) {
Reid Klecknereed88202018-03-28 18:23:35 +00003588 auto Insert = NewMethodLocations.insert(Loc);
3589 if (!Insert.second) {
3590 const MethodVFTableLocation &NewLoc = Loc.second;
3591 MethodVFTableLocation &OldLoc = Insert.first->second;
3592 if (vfptrIsEarlierInMDC(Layout, NewLoc, OldLoc))
3593 OldLoc = NewLoc;
3594 }
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00003595 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003596 }
3597
3598 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3599 NewMethodLocations.end());
3600 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00003601 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003602}
3603
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003604void MicrosoftVTableContext::dumpMethodLocations(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003605 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3606 raw_ostream &Out) {
3607 // Compute the vtable indices for all the member functions.
3608 // Store them in a map keyed by the location so we'll get a sorted table.
3609 std::map<MethodVFTableLocation, std::string> IndicesMap;
3610 bool HasNonzeroOffset = false;
3611
Benjamin Kramera37e7652015-07-25 17:10:49 +00003612 for (const auto &I : NewMethods) {
3613 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I.first.getDecl());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003614 assert(MD->isVirtual());
3615
3616 std::string MethodName = PredefinedExpr::ComputeName(
3617 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3618
3619 if (isa<CXXDestructorDecl>(MD)) {
Benjamin Kramera37e7652015-07-25 17:10:49 +00003620 IndicesMap[I.second] = MethodName + " [scalar deleting]";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003621 } else {
Benjamin Kramera37e7652015-07-25 17:10:49 +00003622 IndicesMap[I.second] = MethodName;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003623 }
3624
Benjamin Kramera37e7652015-07-25 17:10:49 +00003625 if (!I.second.VFPtrOffset.isZero() || I.second.VBTableIndex != 0)
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003626 HasNonzeroOffset = true;
3627 }
3628
3629 // Print the vtable indices for all the member functions.
3630 if (!IndicesMap.empty()) {
3631 Out << "VFTable indices for ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003632 Out << "'";
3633 RD->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003634 Out << "' (" << IndicesMap.size()
3635 << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003636
3637 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3638 uint64_t LastVBIndex = 0;
Benjamin Kramera37e7652015-07-25 17:10:49 +00003639 for (const auto &I : IndicesMap) {
3640 CharUnits VFPtrOffset = I.first.VFPtrOffset;
3641 uint64_t VBIndex = I.first.VBTableIndex;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003642 if (HasNonzeroOffset &&
3643 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3644 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3645 Out << " -- accessible via ";
3646 if (VBIndex)
3647 Out << "vbtable index " << VBIndex << ", ";
3648 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3649 LastVFPtrOffset = VFPtrOffset;
3650 LastVBIndex = VBIndex;
3651 }
3652
Benjamin Kramera37e7652015-07-25 17:10:49 +00003653 uint64_t VTableIndex = I.first.Index;
3654 const std::string &MethodName = I.second;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003655 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3656 }
3657 Out << '\n';
3658 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003659
3660 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003661}
3662
Justin Lebar03b06202016-10-10 16:26:36 +00003663const VirtualBaseInfo &MicrosoftVTableContext::computeVBTableRelatedInformation(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003664 const CXXRecordDecl *RD) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003665 VirtualBaseInfo *VBI;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003666
Reid Kleckner5f080942014-01-03 23:42:00 +00003667 {
3668 // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
3669 // as it may be modified and rehashed under us.
Justin Lebar03b06202016-10-10 16:26:36 +00003670 std::unique_ptr<VirtualBaseInfo> &Entry = VBaseInfo[RD];
Reid Kleckner5f080942014-01-03 23:42:00 +00003671 if (Entry)
Justin Lebar03b06202016-10-10 16:26:36 +00003672 return *Entry;
3673 Entry = llvm::make_unique<VirtualBaseInfo>();
3674 VBI = Entry.get();
Reid Kleckner5f080942014-01-03 23:42:00 +00003675 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003676
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003677 computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003678
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003679 // First, see if the Derived class shared the vbptr with a non-virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003680 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003681 if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003682 // If the Derived class shares the vbptr with a non-virtual base, the shared
3683 // virtual bases come first so that the layout is the same.
Justin Lebar03b06202016-10-10 16:26:36 +00003684 const VirtualBaseInfo &BaseInfo =
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003685 computeVBTableRelatedInformation(VBPtrBase);
Justin Lebar03b06202016-10-10 16:26:36 +00003686 VBI->VBTableIndices.insert(BaseInfo.VBTableIndices.begin(),
3687 BaseInfo.VBTableIndices.end());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003688 }
3689
3690 // New vbases are added to the end of the vbtable.
3691 // Skip the self entry and vbases visited in the non-virtual base, if any.
Reid Kleckner5f080942014-01-03 23:42:00 +00003692 unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003693 for (const auto &VB : RD->vbases()) {
3694 const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
Reid Kleckner5f080942014-01-03 23:42:00 +00003695 if (!VBI->VBTableIndices.count(CurVBase))
3696 VBI->VBTableIndices[CurVBase] = VBTableIndex++;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003697 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003698
Justin Lebar03b06202016-10-10 16:26:36 +00003699 return *VBI;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003700}
3701
3702unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3703 const CXXRecordDecl *VBase) {
Justin Lebar03b06202016-10-10 16:26:36 +00003704 const VirtualBaseInfo &VBInfo = computeVBTableRelatedInformation(Derived);
3705 assert(VBInfo.VBTableIndices.count(VBase));
3706 return VBInfo.VBTableIndices.find(VBase)->second;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003707}
3708
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003709const VPtrInfoVector &
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003710MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
Justin Lebar03b06202016-10-10 16:26:36 +00003711 return computeVBTableRelatedInformation(RD).VBPtrPaths;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003712}
3713
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003714const VPtrInfoVector &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003715MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003716 computeVTableRelatedInformation(RD);
3717
3718 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
Reid Klecknercbec0262018-04-02 20:00:39 +00003719 return *VFPtrLocations[RD];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003720}
3721
3722const VTableLayout &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003723MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3724 CharUnits VFPtrOffset) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003725 computeVTableRelatedInformation(RD);
3726
3727 VFTableIdTy id(RD, VFPtrOffset);
3728 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3729 return *VFTableLayouts[id];
3730}
3731
Reid Klecknercbec0262018-04-02 20:00:39 +00003732MethodVFTableLocation
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003733MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003734 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3735 "Only use this method for virtual methods or dtors");
3736 if (isa<CXXDestructorDecl>(GD.getDecl()))
3737 assert(GD.getDtorType() == Dtor_Deleting);
3738
Reid Kleckner138ab492018-05-17 18:12:18 +00003739 GD = GD.getCanonicalDecl();
3740
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003741 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3742 if (I != MethodVFTableLocations.end())
3743 return I->second;
3744
3745 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3746
3747 computeVTableRelatedInformation(RD);
3748
3749 I = MethodVFTableLocations.find(GD);
3750 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3751 return I->second;
3752}