blob: 3a7282b42eeaf0cfba09fba9e2bcf8112c444ac8 [file] [log] [blame]
Peter Collingbournecfd23562011-09-26 01:57:12 +00001//===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with generation of the layout of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/VTableBuilder.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000015#include "clang/AST/ASTContext.h"
David Majnemer70e6a002015-05-01 21:35:45 +000016#include "clang/AST/ASTDiagnostic.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000017#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/RecordLayout.h"
19#include "clang/Basic/TargetInfo.h"
David Majnemerab130922015-05-04 18:47:54 +000020#include "llvm/ADT/SetOperations.h"
Reid Kleckner5f080942014-01-03 23:42:00 +000021#include "llvm/ADT/SmallPtrSet.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000022#include "llvm/Support/Format.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000023#include "llvm/Support/raw_ostream.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000024#include <algorithm>
25#include <cstdio>
26
27using namespace clang;
28
29#define DUMP_OVERRIDERS 0
30
31namespace {
32
33/// BaseOffset - Represents an offset from a derived class to a direct or
34/// indirect base class.
35struct BaseOffset {
36 /// DerivedClass - The derived class.
37 const CXXRecordDecl *DerivedClass;
38
39 /// VirtualBase - If the path from the derived class to the base class
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +000040 /// involves virtual base classes, this holds the declaration of the last
41 /// virtual base in this path (i.e. closest to the base class).
Peter Collingbournecfd23562011-09-26 01:57:12 +000042 const CXXRecordDecl *VirtualBase;
43
44 /// NonVirtualOffset - The offset from the derived class to the base class.
45 /// (Or the offset from the virtual base class to the base class, if the
46 /// path from the derived class to the base class involves a virtual base
47 /// class.
48 CharUnits NonVirtualOffset;
Craig Topper36250ad2014-05-12 05:36:57 +000049
50 BaseOffset() : DerivedClass(nullptr), VirtualBase(nullptr),
51 NonVirtualOffset(CharUnits::Zero()) { }
Peter Collingbournecfd23562011-09-26 01:57:12 +000052 BaseOffset(const CXXRecordDecl *DerivedClass,
53 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
54 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
55 NonVirtualOffset(NonVirtualOffset) { }
56
57 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
58};
59
60/// FinalOverriders - Contains the final overrider member functions for all
61/// member functions in the base subobjects of a class.
62class FinalOverriders {
63public:
64 /// OverriderInfo - Information about a final overrider.
65 struct OverriderInfo {
66 /// Method - The method decl of the overrider.
67 const CXXMethodDecl *Method;
68
Timur Iskhodzhanov7d19fc12014-11-17 15:11:05 +000069 /// VirtualBase - The virtual base class subobject of this overrider.
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +000070 /// Note that this records the closest derived virtual base class subobject.
71 const CXXRecordDecl *VirtualBase;
72
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000073 /// Offset - the base offset of the overrider's parent in the layout class.
Peter Collingbournecfd23562011-09-26 01:57:12 +000074 CharUnits Offset;
Craig Topper36250ad2014-05-12 05:36:57 +000075
76 OverriderInfo() : Method(nullptr), VirtualBase(nullptr),
77 Offset(CharUnits::Zero()) { }
Peter Collingbournecfd23562011-09-26 01:57:12 +000078 };
79
80private:
81 /// MostDerivedClass - The most derived class for which the final overriders
82 /// are stored.
83 const CXXRecordDecl *MostDerivedClass;
84
85 /// MostDerivedClassOffset - If we're building final overriders for a
86 /// construction vtable, this holds the offset from the layout class to the
87 /// most derived class.
88 const CharUnits MostDerivedClassOffset;
89
90 /// LayoutClass - The class we're using for layout information. Will be
91 /// different than the most derived class if the final overriders are for a
92 /// construction vtable.
93 const CXXRecordDecl *LayoutClass;
94
95 ASTContext &Context;
96
97 /// MostDerivedClassLayout - the AST record layout of the most derived class.
98 const ASTRecordLayout &MostDerivedClassLayout;
99
100 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
101 /// in a base subobject.
102 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
103
104 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
105 OverriderInfo> OverridersMapTy;
106
107 /// OverridersMap - The final overriders for all virtual member functions of
108 /// all the base subobjects of the most derived class.
109 OverridersMapTy OverridersMap;
110
111 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
112 /// as a record decl and a subobject number) and its offsets in the most
113 /// derived class as well as the layout class.
114 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
115 CharUnits> SubobjectOffsetMapTy;
116
117 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
118
119 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
120 /// given base.
121 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
122 CharUnits OffsetInLayoutClass,
123 SubobjectOffsetMapTy &SubobjectOffsets,
124 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
125 SubobjectCountMapTy &SubobjectCounts);
126
127 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
128
129 /// dump - dump the final overriders for a base subobject, and all its direct
130 /// and indirect base subobjects.
131 void dump(raw_ostream &Out, BaseSubobject Base,
132 VisitedVirtualBasesSetTy& VisitedVirtualBases);
133
134public:
135 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
136 CharUnits MostDerivedClassOffset,
137 const CXXRecordDecl *LayoutClass);
138
139 /// getOverrider - Get the final overrider for the given method declaration in
140 /// the subobject with the given base offset.
141 OverriderInfo getOverrider(const CXXMethodDecl *MD,
142 CharUnits BaseOffset) const {
143 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
144 "Did not find overrider!");
145
146 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
147 }
148
149 /// dump - dump the final overriders.
150 void dump() {
151 VisitedVirtualBasesSetTy VisitedVirtualBases;
152 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
153 VisitedVirtualBases);
154 }
155
156};
157
Peter Collingbournecfd23562011-09-26 01:57:12 +0000158FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
159 CharUnits MostDerivedClassOffset,
160 const CXXRecordDecl *LayoutClass)
161 : MostDerivedClass(MostDerivedClass),
162 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
163 Context(MostDerivedClass->getASTContext()),
164 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
165
166 // Compute base offsets.
167 SubobjectOffsetMapTy SubobjectOffsets;
168 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
169 SubobjectCountMapTy SubobjectCounts;
170 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
171 /*IsVirtual=*/false,
172 MostDerivedClassOffset,
173 SubobjectOffsets, SubobjectLayoutClassOffsets,
174 SubobjectCounts);
175
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000176 // Get the final overriders.
Peter Collingbournecfd23562011-09-26 01:57:12 +0000177 CXXFinalOverriderMap FinalOverriders;
178 MostDerivedClass->getFinalOverriders(FinalOverriders);
179
180 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
181 E = FinalOverriders.end(); I != E; ++I) {
182 const CXXMethodDecl *MD = I->first;
183 const OverridingMethods& Methods = I->second;
184
185 for (OverridingMethods::const_iterator I = Methods.begin(),
186 E = Methods.end(); I != E; ++I) {
187 unsigned SubobjectNumber = I->first;
188 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
189 SubobjectNumber)) &&
190 "Did not find subobject offset!");
191
192 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
193 SubobjectNumber)];
194
195 assert(I->second.size() == 1 && "Final overrider is not unique!");
196 const UniqueVirtualMethod &Method = I->second.front();
197
198 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
199 assert(SubobjectLayoutClassOffsets.count(
200 std::make_pair(OverriderRD, Method.Subobject))
201 && "Did not find subobject offset!");
202 CharUnits OverriderOffset =
203 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
204 Method.Subobject)];
205
206 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
207 assert(!Overrider.Method && "Overrider should not exist yet!");
208
209 Overrider.Offset = OverriderOffset;
210 Overrider.Method = Method.Method;
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +0000211 Overrider.VirtualBase = Method.InVirtualSubobject;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000212 }
213 }
214
215#if DUMP_OVERRIDERS
216 // And dump them (for now).
217 dump();
218#endif
219}
220
David Majnemerab130922015-05-04 18:47:54 +0000221static BaseOffset ComputeBaseOffset(const ASTContext &Context,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000222 const CXXRecordDecl *DerivedRD,
223 const CXXBasePath &Path) {
224 CharUnits NonVirtualOffset = CharUnits::Zero();
225
226 unsigned NonVirtualStart = 0;
Craig Topper36250ad2014-05-12 05:36:57 +0000227 const CXXRecordDecl *VirtualBase = nullptr;
228
Peter Collingbournecfd23562011-09-26 01:57:12 +0000229 // First, look for the virtual base class.
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000230 for (int I = Path.size(), E = 0; I != E; --I) {
231 const CXXBasePathElement &Element = Path[I - 1];
232
Peter Collingbournecfd23562011-09-26 01:57:12 +0000233 if (Element.Base->isVirtual()) {
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000234 NonVirtualStart = I;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000235 QualType VBaseType = Element.Base->getType();
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000236 VirtualBase = VBaseType->getAsCXXRecordDecl();
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000237 break;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000238 }
239 }
240
241 // Now compute the non-virtual offset.
242 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
243 const CXXBasePathElement &Element = Path[I];
244
245 // Check the base class offset.
246 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
247
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000248 const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000249
250 NonVirtualOffset += Layout.getBaseClassOffset(Base);
251 }
252
253 // FIXME: This should probably use CharUnits or something. Maybe we should
254 // even change the base offsets in ASTRecordLayout to be specified in
255 // CharUnits.
256 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
257
258}
259
David Majnemerab130922015-05-04 18:47:54 +0000260static BaseOffset ComputeBaseOffset(const ASTContext &Context,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000261 const CXXRecordDecl *BaseRD,
262 const CXXRecordDecl *DerivedRD) {
263 CXXBasePaths Paths(/*FindAmbiguities=*/false,
264 /*RecordPaths=*/true, /*DetectVirtual=*/false);
Benjamin Kramer325d7452013-02-03 18:55:34 +0000265
266 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000267 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +0000268
269 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
270}
271
272static BaseOffset
273ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
274 const CXXMethodDecl *DerivedMD,
275 const CXXMethodDecl *BaseMD) {
276 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
277 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
278
279 // Canonicalize the return types.
Alp Toker314cc812014-01-25 16:55:45 +0000280 CanQualType CanDerivedReturnType =
281 Context.getCanonicalType(DerivedFT->getReturnType());
282 CanQualType CanBaseReturnType =
283 Context.getCanonicalType(BaseFT->getReturnType());
284
Peter Collingbournecfd23562011-09-26 01:57:12 +0000285 assert(CanDerivedReturnType->getTypeClass() ==
286 CanBaseReturnType->getTypeClass() &&
287 "Types must have same type class!");
288
289 if (CanDerivedReturnType == CanBaseReturnType) {
290 // No adjustment needed.
291 return BaseOffset();
292 }
293
294 if (isa<ReferenceType>(CanDerivedReturnType)) {
295 CanDerivedReturnType =
296 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
297 CanBaseReturnType =
298 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
299 } else if (isa<PointerType>(CanDerivedReturnType)) {
300 CanDerivedReturnType =
301 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
302 CanBaseReturnType =
303 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
304 } else {
305 llvm_unreachable("Unexpected return type!");
306 }
307
308 // We need to compare unqualified types here; consider
309 // const T *Base::foo();
310 // T *Derived::foo();
311 if (CanDerivedReturnType.getUnqualifiedType() ==
312 CanBaseReturnType.getUnqualifiedType()) {
313 // No adjustment needed.
314 return BaseOffset();
315 }
316
317 const CXXRecordDecl *DerivedRD =
318 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
319
320 const CXXRecordDecl *BaseRD =
321 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
322
323 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
324}
325
326void
327FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
328 CharUnits OffsetInLayoutClass,
329 SubobjectOffsetMapTy &SubobjectOffsets,
330 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
331 SubobjectCountMapTy &SubobjectCounts) {
332 const CXXRecordDecl *RD = Base.getBase();
333
334 unsigned SubobjectNumber = 0;
335 if (!IsVirtual)
336 SubobjectNumber = ++SubobjectCounts[RD];
337
338 // Set up the subobject to offset mapping.
339 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
340 && "Subobject offset already exists!");
341 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
342 && "Subobject offset already exists!");
343
344 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
345 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
346 OffsetInLayoutClass;
347
348 // Traverse our bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000349 for (const auto &B : RD->bases()) {
350 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000351
352 CharUnits BaseOffset;
353 CharUnits BaseOffsetInLayoutClass;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000354 if (B.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000355 // Check if we've visited this virtual base before.
356 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
357 continue;
358
359 const ASTRecordLayout &LayoutClassLayout =
360 Context.getASTRecordLayout(LayoutClass);
361
362 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
363 BaseOffsetInLayoutClass =
364 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
365 } else {
366 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
367 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
368
369 BaseOffset = Base.getBaseOffset() + Offset;
370 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
371 }
372
373 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000374 B.isVirtual(), BaseOffsetInLayoutClass,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000375 SubobjectOffsets, SubobjectLayoutClassOffsets,
376 SubobjectCounts);
377 }
378}
379
380void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
381 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
382 const CXXRecordDecl *RD = Base.getBase();
383 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
384
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000385 for (const auto &B : RD->bases()) {
386 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000387
388 // Ignore bases that don't have any virtual member functions.
389 if (!BaseDecl->isPolymorphic())
390 continue;
391
392 CharUnits BaseOffset;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000393 if (B.isVirtual()) {
David Blaikie82e95a32014-11-19 07:49:47 +0000394 if (!VisitedVirtualBases.insert(BaseDecl).second) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000395 // We've visited this base before.
396 continue;
397 }
398
399 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
400 } else {
401 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
402 }
403
404 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
405 }
406
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000407 Out << "Final overriders for (";
408 RD->printQualifiedName(Out);
409 Out << ", ";
Peter Collingbournecfd23562011-09-26 01:57:12 +0000410 Out << Base.getBaseOffset().getQuantity() << ")\n";
411
412 // Now dump the overriders for this base subobject.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000413 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000414 if (!MD->isVirtual())
415 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +0000416 MD = MD->getCanonicalDecl();
NAKAMURA Takumi073f2b42015-02-25 10:50:06 +0000417
Peter Collingbournecfd23562011-09-26 01:57:12 +0000418 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
419
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000420 Out << " ";
421 MD->printQualifiedName(Out);
422 Out << " - (";
423 Overrider.Method->printQualifiedName(Out);
Timur Iskhodzhanovbe5a3d82013-06-05 06:40:07 +0000424 Out << ", " << Overrider.Offset.getQuantity() << ')';
Peter Collingbournecfd23562011-09-26 01:57:12 +0000425
426 BaseOffset Offset;
427 if (!Overrider.Method->isPure())
428 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
429
430 if (!Offset.isEmpty()) {
431 Out << " [ret-adj: ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000432 if (Offset.VirtualBase) {
433 Offset.VirtualBase->printQualifiedName(Out);
434 Out << " vbase, ";
435 }
Peter Collingbournecfd23562011-09-26 01:57:12 +0000436
437 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
438 }
439
440 Out << "\n";
441 }
442}
443
444/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
445struct VCallOffsetMap {
446
447 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
448
449 /// Offsets - Keeps track of methods and their offsets.
450 // FIXME: This should be a real map and not a vector.
451 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
452
453 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
454 /// can share the same vcall offset.
455 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
456 const CXXMethodDecl *RHS);
457
458public:
459 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
460 /// add was successful, or false if there was already a member function with
461 /// the same signature in the map.
462 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
463
464 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
465 /// vtable address point) for the given virtual member function.
466 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
467
468 // empty - Return whether the offset map is empty or not.
469 bool empty() const { return Offsets.empty(); }
470};
471
472static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
473 const CXXMethodDecl *RHS) {
John McCallb6c4a7e2012-03-21 06:57:19 +0000474 const FunctionProtoType *LT =
475 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
476 const FunctionProtoType *RT =
477 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000478
479 // Fast-path matches in the canonical types.
480 if (LT == RT) return true;
481
482 // Force the signatures to match. We can't rely on the overrides
483 // list here because there isn't necessarily an inheritance
484 // relationship between the two methods.
John McCallb6c4a7e2012-03-21 06:57:19 +0000485 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000486 LT->getNumParams() != RT->getNumParams())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000487 return false;
Alp Toker9cacbab2014-01-20 20:26:09 +0000488 for (unsigned I = 0, E = LT->getNumParams(); I != E; ++I)
489 if (LT->getParamType(I) != RT->getParamType(I))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000490 return false;
491 return true;
492}
493
494bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
495 const CXXMethodDecl *RHS) {
496 assert(LHS->isVirtual() && "LHS must be virtual!");
497 assert(RHS->isVirtual() && "LHS must be virtual!");
498
499 // A destructor can share a vcall offset with another destructor.
500 if (isa<CXXDestructorDecl>(LHS))
501 return isa<CXXDestructorDecl>(RHS);
502
503 // FIXME: We need to check more things here.
504
505 // The methods must have the same name.
506 DeclarationName LHSName = LHS->getDeclName();
507 DeclarationName RHSName = RHS->getDeclName();
508 if (LHSName != RHSName)
509 return false;
510
511 // And the same signatures.
512 return HasSameVirtualSignature(LHS, RHS);
513}
514
515bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
516 CharUnits OffsetOffset) {
517 // Check if we can reuse an offset.
518 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
519 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
520 return false;
521 }
522
523 // Add the offset.
524 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
525 return true;
526}
527
528CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
529 // Look for an offset.
530 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
531 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
532 return Offsets[I].second;
533 }
534
535 llvm_unreachable("Should always find a vcall offset offset!");
536}
537
538/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
539class VCallAndVBaseOffsetBuilder {
540public:
541 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
542 VBaseOffsetOffsetsMapTy;
543
544private:
545 /// MostDerivedClass - The most derived class for which we're building vcall
546 /// and vbase offsets.
547 const CXXRecordDecl *MostDerivedClass;
548
549 /// LayoutClass - The class we're using for layout information. Will be
550 /// different than the most derived class if we're building a construction
551 /// vtable.
552 const CXXRecordDecl *LayoutClass;
553
554 /// Context - The ASTContext which we will use for layout information.
555 ASTContext &Context;
556
557 /// Components - vcall and vbase offset components
558 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
559 VTableComponentVectorTy Components;
560
561 /// VisitedVirtualBases - Visited virtual bases.
562 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
563
564 /// VCallOffsets - Keeps track of vcall offsets.
565 VCallOffsetMap VCallOffsets;
566
567
568 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
569 /// relative to the address point.
570 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
571
572 /// FinalOverriders - The final overriders of the most derived class.
573 /// (Can be null when we're not building a vtable of the most derived class).
574 const FinalOverriders *Overriders;
575
576 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
577 /// given base subobject.
578 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
579 CharUnits RealBaseOffset);
580
581 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
582 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
583
584 /// AddVBaseOffsets - Add vbase offsets for the given class.
585 void AddVBaseOffsets(const CXXRecordDecl *Base,
586 CharUnits OffsetInLayoutClass);
587
588 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
589 /// chars, relative to the vtable address point.
590 CharUnits getCurrentOffsetOffset() const;
591
592public:
593 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
594 const CXXRecordDecl *LayoutClass,
595 const FinalOverriders *Overriders,
596 BaseSubobject Base, bool BaseIsVirtual,
597 CharUnits OffsetInLayoutClass)
598 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
599 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
600
601 // Add vcall and vbase offsets.
602 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
603 }
604
605 /// Methods for iterating over the components.
606 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
607 const_iterator components_begin() const { return Components.rbegin(); }
608 const_iterator components_end() const { return Components.rend(); }
609
610 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
611 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
612 return VBaseOffsetOffsets;
613 }
614};
615
616void
617VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
618 bool BaseIsVirtual,
619 CharUnits RealBaseOffset) {
620 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
621
622 // Itanium C++ ABI 2.5.2:
623 // ..in classes sharing a virtual table with a primary base class, the vcall
624 // and vbase offsets added by the derived class all come before the vcall
625 // and vbase offsets required by the base class, so that the latter may be
626 // laid out as required by the base class without regard to additions from
627 // the derived class(es).
628
629 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
630 // emit them for the primary base first).
631 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
632 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
633
634 CharUnits PrimaryBaseOffset;
635
636 // Get the base offset of the primary base.
637 if (PrimaryBaseIsVirtual) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000638 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000639 "Primary vbase should have a zero offset!");
640
641 const ASTRecordLayout &MostDerivedClassLayout =
642 Context.getASTRecordLayout(MostDerivedClass);
643
644 PrimaryBaseOffset =
645 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
646 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000647 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000648 "Primary base should have a zero offset!");
649
650 PrimaryBaseOffset = Base.getBaseOffset();
651 }
652
653 AddVCallAndVBaseOffsets(
654 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
655 PrimaryBaseIsVirtual, RealBaseOffset);
656 }
657
658 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
659
660 // We only want to add vcall offsets for virtual bases.
661 if (BaseIsVirtual)
662 AddVCallOffsets(Base, RealBaseOffset);
663}
664
665CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
666 // OffsetIndex is the index of this vcall or vbase offset, relative to the
667 // vtable address point. (We subtract 3 to account for the information just
668 // above the address point, the RTTI info, the offset to top, and the
669 // vcall offset itself).
670 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
671
672 CharUnits PointerWidth =
673 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
674 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
675 return OffsetOffset;
676}
677
678void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
679 CharUnits VBaseOffset) {
680 const CXXRecordDecl *RD = Base.getBase();
681 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
682
683 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
684
685 // Handle the primary base first.
686 // We only want to add vcall offsets if the base is non-virtual; a virtual
687 // primary base will have its vcall and vbase offsets emitted already.
688 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
689 // Get the base offset of the primary base.
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000690 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000691 "Primary base should have a zero offset!");
692
693 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
694 VBaseOffset);
695 }
696
697 // Add the vcall offsets.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000698 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000699 if (!MD->isVirtual())
700 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +0000701 MD = MD->getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000702
703 CharUnits OffsetOffset = getCurrentOffsetOffset();
704
705 // Don't add a vcall offset if we already have one for this member function
706 // signature.
707 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
708 continue;
709
710 CharUnits Offset = CharUnits::Zero();
711
712 if (Overriders) {
713 // Get the final overrider.
714 FinalOverriders::OverriderInfo Overrider =
715 Overriders->getOverrider(MD, Base.getBaseOffset());
716
717 /// The vcall offset is the offset from the virtual base to the object
718 /// where the function was overridden.
719 Offset = Overrider.Offset - VBaseOffset;
720 }
721
722 Components.push_back(
723 VTableComponent::MakeVCallOffset(Offset));
724 }
725
726 // And iterate over all non-virtual bases (ignoring the primary base).
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000727 for (const auto &B : RD->bases()) {
728 if (B.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000729 continue;
730
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000731 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000732 if (BaseDecl == PrimaryBase)
733 continue;
734
735 // Get the base offset of this base.
736 CharUnits BaseOffset = Base.getBaseOffset() +
737 Layout.getBaseClassOffset(BaseDecl);
738
739 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
740 VBaseOffset);
741 }
742}
743
744void
745VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
746 CharUnits OffsetInLayoutClass) {
747 const ASTRecordLayout &LayoutClassLayout =
748 Context.getASTRecordLayout(LayoutClass);
749
750 // Add vbase offsets.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000751 for (const auto &B : RD->bases()) {
752 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000753
754 // Check if this is a virtual base that we haven't visited before.
David Blaikie82e95a32014-11-19 07:49:47 +0000755 if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000756 CharUnits Offset =
757 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
758
759 // Add the vbase offset offset.
760 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
761 "vbase offset offset already exists!");
762
763 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
764 VBaseOffsetOffsets.insert(
765 std::make_pair(BaseDecl, VBaseOffsetOffset));
766
767 Components.push_back(
768 VTableComponent::MakeVBaseOffset(Offset));
769 }
770
771 // Check the base class looking for more vbase offsets.
772 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
773 }
774}
775
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000776/// ItaniumVTableBuilder - Class for building vtable layout information.
777class ItaniumVTableBuilder {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000778public:
779 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
780 /// primary bases.
781 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
782 PrimaryBasesSetVectorTy;
783
784 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
785 VBaseOffsetOffsetsMapTy;
786
787 typedef llvm::DenseMap<BaseSubobject, uint64_t>
788 AddressPointsMapTy;
789
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000790 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
791
Peter Collingbournecfd23562011-09-26 01:57:12 +0000792private:
793 /// VTables - Global vtable information.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000794 ItaniumVTableContext &VTables;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000795
796 /// MostDerivedClass - The most derived class for which we're building this
797 /// vtable.
798 const CXXRecordDecl *MostDerivedClass;
799
800 /// MostDerivedClassOffset - If we're building a construction vtable, this
801 /// holds the offset from the layout class to the most derived class.
802 const CharUnits MostDerivedClassOffset;
803
804 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
805 /// base. (This only makes sense when building a construction vtable).
806 bool MostDerivedClassIsVirtual;
807
808 /// LayoutClass - The class we're using for layout information. Will be
809 /// different than the most derived class if we're building a construction
810 /// vtable.
811 const CXXRecordDecl *LayoutClass;
812
813 /// Context - The ASTContext which we will use for layout information.
814 ASTContext &Context;
815
816 /// FinalOverriders - The final overriders of the most derived class.
817 const FinalOverriders Overriders;
818
819 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
820 /// bases in this vtable.
821 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
822
823 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
824 /// the most derived class.
825 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
826
827 /// Components - The components of the vtable being built.
828 SmallVector<VTableComponent, 64> Components;
829
830 /// AddressPoints - Address points for the vtable being built.
831 AddressPointsMapTy AddressPoints;
832
833 /// MethodInfo - Contains information about a method in a vtable.
834 /// (Used for computing 'this' pointer adjustment thunks.
835 struct MethodInfo {
836 /// BaseOffset - The base offset of this method.
837 const CharUnits BaseOffset;
838
839 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
840 /// method.
841 const CharUnits BaseOffsetInLayoutClass;
842
843 /// VTableIndex - The index in the vtable that this method has.
844 /// (For destructors, this is the index of the complete destructor).
845 const uint64_t VTableIndex;
846
847 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
848 uint64_t VTableIndex)
849 : BaseOffset(BaseOffset),
850 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
851 VTableIndex(VTableIndex) { }
852
853 MethodInfo()
854 : BaseOffset(CharUnits::Zero()),
855 BaseOffsetInLayoutClass(CharUnits::Zero()),
856 VTableIndex(0) { }
857 };
858
859 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
860
861 /// MethodInfoMap - The information for all methods in the vtable we're
862 /// currently building.
863 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000864
865 /// MethodVTableIndices - Contains the index (relative to the vtable address
866 /// point) where the function pointer for a virtual function is stored.
867 MethodVTableIndicesTy MethodVTableIndices;
868
Peter Collingbournecfd23562011-09-26 01:57:12 +0000869 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
870
871 /// VTableThunks - The thunks by vtable index in the vtable currently being
872 /// built.
873 VTableThunksMapTy VTableThunks;
874
875 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
876 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
877
878 /// Thunks - A map that contains all the thunks needed for all methods in the
879 /// most derived class for which the vtable is currently being built.
880 ThunksMapTy Thunks;
881
882 /// AddThunk - Add a thunk for the given method.
883 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
884
885 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
886 /// part of the vtable we're currently building.
887 void ComputeThisAdjustments();
888
889 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
890
891 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
892 /// some other base.
893 VisitedVirtualBasesSetTy PrimaryVirtualBases;
894
895 /// ComputeReturnAdjustment - Compute the return adjustment given a return
896 /// adjustment base offset.
897 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
898
899 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
900 /// the 'this' pointer from the base subobject to the derived subobject.
901 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
902 BaseSubobject Derived) const;
903
904 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
905 /// given virtual member function, its offset in the layout class and its
906 /// final overrider.
907 ThisAdjustment
908 ComputeThisAdjustment(const CXXMethodDecl *MD,
909 CharUnits BaseOffsetInLayoutClass,
910 FinalOverriders::OverriderInfo Overrider);
911
912 /// AddMethod - Add a single virtual member function to the vtable
913 /// components vector.
914 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
915
916 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
917 /// part of the vtable.
918 ///
919 /// Itanium C++ ABI 2.5.2:
920 ///
921 /// struct A { virtual void f(); };
922 /// struct B : virtual public A { int i; };
923 /// struct C : virtual public A { int j; };
924 /// struct D : public B, public C {};
925 ///
926 /// When B and C are declared, A is a primary base in each case, so although
927 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
928 /// adjustment is required and no thunk is generated. However, inside D
929 /// objects, A is no longer a primary base of C, so if we allowed calls to
930 /// C::f() to use the copy of A's vtable in the C subobject, we would need
931 /// to adjust this from C* to B::A*, which would require a third-party
932 /// thunk. Since we require that a call to C::f() first convert to A*,
933 /// C-in-D's copy of A's vtable is never referenced, so this is not
934 /// necessary.
935 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
936 CharUnits BaseOffsetInLayoutClass,
937 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
938 CharUnits FirstBaseOffsetInLayoutClass) const;
939
940
941 /// AddMethods - Add the methods of this base subobject and all its
942 /// primary bases to the vtable components vector.
943 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
944 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
945 CharUnits FirstBaseOffsetInLayoutClass,
946 PrimaryBasesSetVectorTy &PrimaryBases);
947
948 // LayoutVTable - Layout the vtable for the given base class, including its
949 // secondary vtables and any vtables for virtual bases.
950 void LayoutVTable();
951
952 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
953 /// given base subobject, as well as all its secondary vtables.
954 ///
955 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
956 /// or a direct or indirect base of a virtual base.
957 ///
958 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
959 /// in the layout class.
960 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
961 bool BaseIsMorallyVirtual,
962 bool BaseIsVirtualInLayoutClass,
963 CharUnits OffsetInLayoutClass);
964
965 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
966 /// subobject.
967 ///
968 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
969 /// or a direct or indirect base of a virtual base.
970 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
971 CharUnits OffsetInLayoutClass);
972
973 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
974 /// class hierarchy.
975 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
976 CharUnits OffsetInLayoutClass,
977 VisitedVirtualBasesSetTy &VBases);
978
979 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
980 /// given base (excluding any primary bases).
981 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
982 VisitedVirtualBasesSetTy &VBases);
983
984 /// isBuildingConstructionVTable - Return whether this vtable builder is
985 /// building a construction vtable.
986 bool isBuildingConstructorVTable() const {
987 return MostDerivedClass != LayoutClass;
988 }
989
990public:
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000991 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
992 const CXXRecordDecl *MostDerivedClass,
993 CharUnits MostDerivedClassOffset,
994 bool MostDerivedClassIsVirtual,
995 const CXXRecordDecl *LayoutClass)
996 : VTables(VTables), MostDerivedClass(MostDerivedClass),
997 MostDerivedClassOffset(MostDerivedClassOffset),
998 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
999 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
1000 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00001001 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
Peter Collingbournecfd23562011-09-26 01:57:12 +00001002
1003 LayoutVTable();
1004
David Blaikiebbafb8a2012-03-11 07:00:24 +00001005 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00001006 dumpLayout(llvm::outs());
Peter Collingbournecfd23562011-09-26 01:57:12 +00001007 }
1008
1009 uint64_t getNumThunks() const {
1010 return Thunks.size();
1011 }
1012
1013 ThunksMapTy::const_iterator thunks_begin() const {
1014 return Thunks.begin();
1015 }
1016
1017 ThunksMapTy::const_iterator thunks_end() const {
1018 return Thunks.end();
1019 }
1020
1021 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1022 return VBaseOffsetOffsets;
1023 }
1024
1025 const AddressPointsMapTy &getAddressPoints() const {
1026 return AddressPoints;
1027 }
1028
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001029 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1030 return MethodVTableIndices.begin();
1031 }
1032
1033 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1034 return MethodVTableIndices.end();
1035 }
1036
Peter Collingbournecfd23562011-09-26 01:57:12 +00001037 /// getNumVTableComponents - Return the number of components in the vtable
1038 /// currently built.
1039 uint64_t getNumVTableComponents() const {
1040 return Components.size();
1041 }
1042
1043 const VTableComponent *vtable_component_begin() const {
1044 return Components.begin();
1045 }
1046
1047 const VTableComponent *vtable_component_end() const {
1048 return Components.end();
1049 }
1050
1051 AddressPointsMapTy::const_iterator address_points_begin() const {
1052 return AddressPoints.begin();
1053 }
1054
1055 AddressPointsMapTy::const_iterator address_points_end() const {
1056 return AddressPoints.end();
1057 }
1058
1059 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1060 return VTableThunks.begin();
1061 }
1062
1063 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1064 return VTableThunks.end();
1065 }
1066
1067 /// dumpLayout - Dump the vtable layout.
1068 void dumpLayout(raw_ostream&);
1069};
1070
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001071void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1072 const ThunkInfo &Thunk) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001073 assert(!isBuildingConstructorVTable() &&
1074 "Can't add thunks for construction vtable");
1075
Craig Topper5603df42013-07-05 19:34:19 +00001076 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1077
Peter Collingbournecfd23562011-09-26 01:57:12 +00001078 // Check if we have this thunk already.
1079 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1080 ThunksVector.end())
1081 return;
1082
1083 ThunksVector.push_back(Thunk);
1084}
1085
1086typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1087
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001088/// Visit all the methods overridden by the given method recursively,
1089/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1090/// indicating whether to continue the recursion for the given overridden
1091/// method (i.e. returning false stops the iteration).
1092template <class VisitorTy>
1093static void
1094visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001095 assert(MD->isVirtual() && "Method is not virtual!");
1096
1097 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1098 E = MD->end_overridden_methods(); I != E; ++I) {
1099 const CXXMethodDecl *OverriddenMD = *I;
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00001100 if (!Visitor(OverriddenMD))
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001101 continue;
1102 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001103 }
1104}
1105
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001106/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1107/// the overridden methods that the function decl overrides.
1108static void
1109ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1110 OverriddenMethodsSetTy& OverriddenMethods) {
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00001111 auto OverriddenMethodsCollector = [&](const CXXMethodDecl *MD) {
1112 // Don't recurse on this method if we've already collected it.
1113 return OverriddenMethods.insert(MD).second;
1114 };
1115 visitAllOverriddenMethods(MD, OverriddenMethodsCollector);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001116}
1117
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001118void ItaniumVTableBuilder::ComputeThisAdjustments() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001119 // Now go through the method info map and see if any of the methods need
1120 // 'this' pointer adjustments.
1121 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1122 E = MethodInfoMap.end(); I != E; ++I) {
1123 const CXXMethodDecl *MD = I->first;
1124 const MethodInfo &MethodInfo = I->second;
1125
1126 // Ignore adjustments for unused function pointers.
1127 uint64_t VTableIndex = MethodInfo.VTableIndex;
1128 if (Components[VTableIndex].getKind() ==
1129 VTableComponent::CK_UnusedFunctionPointer)
1130 continue;
1131
1132 // Get the final overrider for this method.
1133 FinalOverriders::OverriderInfo Overrider =
1134 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1135
1136 // Check if we need an adjustment at all.
1137 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1138 // When a return thunk is needed by a derived class that overrides a
1139 // virtual base, gcc uses a virtual 'this' adjustment as well.
1140 // While the thunk itself might be needed by vtables in subclasses or
1141 // in construction vtables, there doesn't seem to be a reason for using
1142 // the thunk in this vtable. Still, we do so to match gcc.
1143 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1144 continue;
1145 }
1146
1147 ThisAdjustment ThisAdjustment =
1148 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1149
1150 if (ThisAdjustment.isEmpty())
1151 continue;
1152
1153 // Add it.
1154 VTableThunks[VTableIndex].This = ThisAdjustment;
1155
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001156 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001157 // Add an adjustment for the deleting destructor as well.
1158 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1159 }
1160 }
1161
1162 /// Clear the method info map.
1163 MethodInfoMap.clear();
1164
1165 if (isBuildingConstructorVTable()) {
1166 // We don't need to store thunk information for construction vtables.
1167 return;
1168 }
1169
1170 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1171 E = VTableThunks.end(); I != E; ++I) {
1172 const VTableComponent &Component = Components[I->first];
1173 const ThunkInfo &Thunk = I->second;
1174 const CXXMethodDecl *MD;
1175
1176 switch (Component.getKind()) {
1177 default:
1178 llvm_unreachable("Unexpected vtable component kind!");
1179 case VTableComponent::CK_FunctionPointer:
1180 MD = Component.getFunctionDecl();
1181 break;
1182 case VTableComponent::CK_CompleteDtorPointer:
1183 MD = Component.getDestructorDecl();
1184 break;
1185 case VTableComponent::CK_DeletingDtorPointer:
1186 // We've already added the thunk when we saw the complete dtor pointer.
1187 continue;
1188 }
1189
1190 if (MD->getParent() == MostDerivedClass)
1191 AddThunk(MD, Thunk);
1192 }
1193}
1194
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001195ReturnAdjustment
1196ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001197 ReturnAdjustment Adjustment;
1198
1199 if (!Offset.isEmpty()) {
1200 if (Offset.VirtualBase) {
1201 // Get the virtual base offset offset.
1202 if (Offset.DerivedClass == MostDerivedClass) {
1203 // We can get the offset offset directly from our map.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001204 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001205 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1206 } else {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001207 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001208 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1209 Offset.VirtualBase).getQuantity();
1210 }
1211 }
1212
1213 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1214 }
1215
1216 return Adjustment;
1217}
1218
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001219BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1220 BaseSubobject Base, BaseSubobject Derived) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001221 const CXXRecordDecl *BaseRD = Base.getBase();
1222 const CXXRecordDecl *DerivedRD = Derived.getBase();
1223
1224 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1225 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1226
Benjamin Kramer325d7452013-02-03 18:55:34 +00001227 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +00001228 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +00001229
1230 // We have to go through all the paths, and see which one leads us to the
1231 // right base subobject.
1232 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1233 I != E; ++I) {
1234 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1235
1236 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1237
1238 if (Offset.VirtualBase) {
1239 // If we have a virtual base class, the non-virtual offset is relative
1240 // to the virtual base class offset.
1241 const ASTRecordLayout &LayoutClassLayout =
1242 Context.getASTRecordLayout(LayoutClass);
1243
1244 /// Get the virtual base offset, relative to the most derived class
1245 /// layout.
1246 OffsetToBaseSubobject +=
1247 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1248 } else {
1249 // Otherwise, the non-virtual offset is relative to the derived class
1250 // offset.
1251 OffsetToBaseSubobject += Derived.getBaseOffset();
1252 }
1253
1254 // Check if this path gives us the right base subobject.
1255 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1256 // Since we're going from the base class _to_ the derived class, we'll
1257 // invert the non-virtual offset here.
1258 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1259 return Offset;
1260 }
1261 }
1262
1263 return BaseOffset();
1264}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001265
1266ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1267 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1268 FinalOverriders::OverriderInfo Overrider) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001269 // Ignore adjustments for pure virtual member functions.
1270 if (Overrider.Method->isPure())
1271 return ThisAdjustment();
1272
1273 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1274 BaseOffsetInLayoutClass);
1275
1276 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1277 Overrider.Offset);
1278
1279 // Compute the adjustment offset.
1280 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1281 OverriderBaseSubobject);
1282 if (Offset.isEmpty())
1283 return ThisAdjustment();
1284
1285 ThisAdjustment Adjustment;
1286
1287 if (Offset.VirtualBase) {
1288 // Get the vcall offset map for this virtual base.
1289 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1290
1291 if (VCallOffsets.empty()) {
1292 // We don't have vcall offsets for this virtual base, go ahead and
1293 // build them.
1294 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
Craig Topper36250ad2014-05-12 05:36:57 +00001295 /*FinalOverriders=*/nullptr,
Peter Collingbournecfd23562011-09-26 01:57:12 +00001296 BaseSubobject(Offset.VirtualBase,
1297 CharUnits::Zero()),
1298 /*BaseIsVirtual=*/true,
1299 /*OffsetInLayoutClass=*/
1300 CharUnits::Zero());
1301
1302 VCallOffsets = Builder.getVCallOffsets();
1303 }
1304
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001305 Adjustment.Virtual.Itanium.VCallOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001306 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1307 }
1308
1309 // Set the non-virtual part of the adjustment.
1310 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1311
1312 return Adjustment;
1313}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001314
1315void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1316 ReturnAdjustment ReturnAdjustment) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001317 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1318 assert(ReturnAdjustment.isEmpty() &&
1319 "Destructor can't have return adjustment!");
1320
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001321 // Add both the complete destructor and the deleting destructor.
1322 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1323 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbournecfd23562011-09-26 01:57:12 +00001324 } else {
1325 // Add the return adjustment if necessary.
1326 if (!ReturnAdjustment.isEmpty())
1327 VTableThunks[Components.size()].Return = ReturnAdjustment;
1328
1329 // Add the function.
1330 Components.push_back(VTableComponent::MakeFunction(MD));
1331 }
1332}
1333
1334/// OverridesIndirectMethodInBase - Return whether the given member function
1335/// overrides any methods in the set of given bases.
1336/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1337/// For example, if we have:
1338///
1339/// struct A { virtual void f(); }
1340/// struct B : A { virtual void f(); }
1341/// struct C : B { virtual void f(); }
1342///
1343/// OverridesIndirectMethodInBase will return true if given C::f as the method
1344/// and { A } as the set of bases.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001345static bool OverridesIndirectMethodInBases(
1346 const CXXMethodDecl *MD,
1347 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001348 if (Bases.count(MD->getParent()))
1349 return true;
1350
1351 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1352 E = MD->end_overridden_methods(); I != E; ++I) {
1353 const CXXMethodDecl *OverriddenMD = *I;
1354
1355 // Check "indirect overriders".
1356 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1357 return true;
1358 }
1359
1360 return false;
1361}
1362
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001363bool ItaniumVTableBuilder::IsOverriderUsed(
1364 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1365 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1366 CharUnits FirstBaseOffsetInLayoutClass) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001367 // If the base and the first base in the primary base chain have the same
1368 // offsets, then this overrider will be used.
1369 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1370 return true;
1371
1372 // We know now that Base (or a direct or indirect base of it) is a primary
1373 // base in part of the class hierarchy, but not a primary base in the most
1374 // derived class.
1375
1376 // If the overrider is the first base in the primary base chain, we know
1377 // that the overrider will be used.
1378 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1379 return true;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001380
1381 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001382
1383 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1384 PrimaryBases.insert(RD);
1385
1386 // Now traverse the base chain, starting with the first base, until we find
1387 // the base that is no longer a primary base.
1388 while (true) {
1389 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1390 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1391
1392 if (!PrimaryBase)
1393 break;
1394
1395 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001396 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001397 "Primary base should always be at offset 0!");
1398
1399 const ASTRecordLayout &LayoutClassLayout =
1400 Context.getASTRecordLayout(LayoutClass);
1401
1402 // Now check if this is the primary base that is not a primary base in the
1403 // most derived class.
1404 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1405 FirstBaseOffsetInLayoutClass) {
1406 // We found it, stop walking the chain.
1407 break;
1408 }
1409 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001410 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001411 "Primary base should always be at offset 0!");
1412 }
1413
1414 if (!PrimaryBases.insert(PrimaryBase))
1415 llvm_unreachable("Found a duplicate primary base!");
1416
1417 RD = PrimaryBase;
1418 }
1419
1420 // If the final overrider is an override of one of the primary bases,
1421 // then we know that it will be used.
1422 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1423}
1424
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001425typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1426
Peter Collingbournecfd23562011-09-26 01:57:12 +00001427/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1428/// from the nearest base. Returns null if no method was found.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001429/// The Bases are expected to be sorted in a base-to-derived order.
1430static const CXXMethodDecl *
Peter Collingbournecfd23562011-09-26 01:57:12 +00001431FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001432 BasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001433 OverriddenMethodsSetTy OverriddenMethods;
1434 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1435
1436 for (int I = Bases.size(), E = 0; I != E; --I) {
1437 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1438
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001439 // Now check the overridden methods.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001440 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1441 E = OverriddenMethods.end(); I != E; ++I) {
1442 const CXXMethodDecl *OverriddenMD = *I;
1443
1444 // We found our overridden method.
1445 if (OverriddenMD->getParent() == PrimaryBase)
1446 return OverriddenMD;
1447 }
1448 }
Craig Topper36250ad2014-05-12 05:36:57 +00001449
1450 return nullptr;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001451}
Peter Collingbournecfd23562011-09-26 01:57:12 +00001452
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001453void ItaniumVTableBuilder::AddMethods(
1454 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1455 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1456 CharUnits FirstBaseOffsetInLayoutClass,
1457 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001458 // Itanium C++ ABI 2.5.2:
1459 // The order of the virtual function pointers in a virtual table is the
1460 // order of declaration of the corresponding member functions in the class.
1461 //
1462 // There is an entry for any virtual function declared in a class,
1463 // whether it is a new function or overrides a base class function,
1464 // unless it overrides a function from the primary base, and conversion
1465 // between their return types does not require an adjustment.
1466
Peter Collingbournecfd23562011-09-26 01:57:12 +00001467 const CXXRecordDecl *RD = Base.getBase();
1468 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1469
1470 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1471 CharUnits PrimaryBaseOffset;
1472 CharUnits PrimaryBaseOffsetInLayoutClass;
1473 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001474 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001475 "Primary vbase should have a zero offset!");
1476
1477 const ASTRecordLayout &MostDerivedClassLayout =
1478 Context.getASTRecordLayout(MostDerivedClass);
1479
1480 PrimaryBaseOffset =
1481 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1482
1483 const ASTRecordLayout &LayoutClassLayout =
1484 Context.getASTRecordLayout(LayoutClass);
1485
1486 PrimaryBaseOffsetInLayoutClass =
1487 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1488 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001489 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001490 "Primary base should have a zero offset!");
1491
1492 PrimaryBaseOffset = Base.getBaseOffset();
1493 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1494 }
1495
1496 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1497 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1498 FirstBaseOffsetInLayoutClass, PrimaryBases);
1499
1500 if (!PrimaryBases.insert(PrimaryBase))
1501 llvm_unreachable("Found a duplicate primary base!");
1502 }
1503
Craig Topper36250ad2014-05-12 05:36:57 +00001504 const CXXDestructorDecl *ImplicitVirtualDtor = nullptr;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001505
1506 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1507 NewVirtualFunctionsTy NewVirtualFunctions;
1508
Peter Collingbournecfd23562011-09-26 01:57:12 +00001509 // Now go through all virtual member functions and add them.
Aaron Ballman2b124d12014-03-13 16:36:16 +00001510 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001511 if (!MD->isVirtual())
1512 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +00001513 MD = MD->getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001514
1515 // Get the final overrider.
1516 FinalOverriders::OverriderInfo Overrider =
1517 Overriders.getOverrider(MD, Base.getBaseOffset());
1518
1519 // Check if this virtual member function overrides a method in a primary
1520 // base. If this is the case, and the return type doesn't require adjustment
1521 // then we can just use the member function from the primary base.
1522 if (const CXXMethodDecl *OverriddenMD =
1523 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1524 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1525 OverriddenMD).isEmpty()) {
1526 // Replace the method info of the overridden method with our own
1527 // method.
1528 assert(MethodInfoMap.count(OverriddenMD) &&
1529 "Did not find the overridden method!");
1530 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1531
1532 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1533 OverriddenMethodInfo.VTableIndex);
1534
1535 assert(!MethodInfoMap.count(MD) &&
1536 "Should not have method info for this method yet!");
1537
1538 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1539 MethodInfoMap.erase(OverriddenMD);
1540
1541 // If the overridden method exists in a virtual base class or a direct
1542 // or indirect base class of a virtual base class, we need to emit a
1543 // thunk if we ever have a class hierarchy where the base class is not
1544 // a primary base in the complete object.
1545 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1546 // Compute the this adjustment.
1547 ThisAdjustment ThisAdjustment =
1548 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1549 Overrider);
1550
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001551 if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001552 Overrider.Method->getParent() == MostDerivedClass) {
1553
1554 // There's no return adjustment from OverriddenMD and MD,
1555 // but that doesn't mean there isn't one between MD and
1556 // the final overrider.
1557 BaseOffset ReturnAdjustmentOffset =
1558 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1559 ReturnAdjustment ReturnAdjustment =
1560 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1561
1562 // This is a virtual thunk for the most derived class, add it.
1563 AddThunk(Overrider.Method,
1564 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1565 }
1566 }
1567
1568 continue;
1569 }
1570 }
1571
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001572 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1573 if (MD->isImplicit()) {
1574 // Itanium C++ ABI 2.5.2:
1575 // If a class has an implicitly-defined virtual destructor,
1576 // its entries come after the declared virtual function pointers.
1577
1578 assert(!ImplicitVirtualDtor &&
1579 "Did already see an implicit virtual dtor!");
1580 ImplicitVirtualDtor = DD;
1581 continue;
1582 }
1583 }
1584
1585 NewVirtualFunctions.push_back(MD);
1586 }
1587
1588 if (ImplicitVirtualDtor)
1589 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1590
1591 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1592 E = NewVirtualFunctions.end(); I != E; ++I) {
1593 const CXXMethodDecl *MD = *I;
1594
1595 // Get the final overrider.
1596 FinalOverriders::OverriderInfo Overrider =
1597 Overriders.getOverrider(MD, Base.getBaseOffset());
1598
Peter Collingbournecfd23562011-09-26 01:57:12 +00001599 // Insert the method info for this method.
1600 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1601 Components.size());
1602
1603 assert(!MethodInfoMap.count(MD) &&
1604 "Should not have method info for this method yet!");
1605 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1606
1607 // Check if this overrider is going to be used.
1608 const CXXMethodDecl *OverriderMD = Overrider.Method;
1609 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1610 FirstBaseInPrimaryBaseChain,
1611 FirstBaseOffsetInLayoutClass)) {
1612 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1613 continue;
1614 }
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001615
Peter Collingbournecfd23562011-09-26 01:57:12 +00001616 // Check if this overrider needs a return adjustment.
1617 // We don't want to do this for pure virtual member functions.
1618 BaseOffset ReturnAdjustmentOffset;
1619 if (!OverriderMD->isPure()) {
1620 ReturnAdjustmentOffset =
1621 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1622 }
1623
1624 ReturnAdjustment ReturnAdjustment =
1625 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1626
1627 AddMethod(Overrider.Method, ReturnAdjustment);
1628 }
1629}
1630
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001631void ItaniumVTableBuilder::LayoutVTable() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001632 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1633 CharUnits::Zero()),
1634 /*BaseIsMorallyVirtual=*/false,
1635 MostDerivedClassIsVirtual,
1636 MostDerivedClassOffset);
1637
1638 VisitedVirtualBasesSetTy VBases;
1639
1640 // Determine the primary virtual bases.
1641 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1642 VBases);
1643 VBases.clear();
1644
1645 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1646
1647 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001648 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001649 if (IsAppleKext)
1650 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1651}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001652
1653void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1654 BaseSubobject Base, bool BaseIsMorallyVirtual,
1655 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001656 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1657
1658 // Add vcall and vbase offsets for this vtable.
1659 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1660 Base, BaseIsVirtualInLayoutClass,
1661 OffsetInLayoutClass);
1662 Components.append(Builder.components_begin(), Builder.components_end());
1663
1664 // Check if we need to add these vcall offsets.
1665 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1666 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1667
1668 if (VCallOffsets.empty())
1669 VCallOffsets = Builder.getVCallOffsets();
1670 }
1671
1672 // If we're laying out the most derived class we want to keep track of the
1673 // virtual base class offset offsets.
1674 if (Base.getBase() == MostDerivedClass)
1675 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1676
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001677 // Add the offset to top.
1678 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1679 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001680
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001681 // Next, add the RTTI.
1682 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001683
Peter Collingbournecfd23562011-09-26 01:57:12 +00001684 uint64_t AddressPoint = Components.size();
1685
1686 // Now go through all virtual member functions and add them.
1687 PrimaryBasesSetVectorTy PrimaryBases;
1688 AddMethods(Base, OffsetInLayoutClass,
1689 Base.getBase(), OffsetInLayoutClass,
1690 PrimaryBases);
1691
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001692 const CXXRecordDecl *RD = Base.getBase();
1693 if (RD == MostDerivedClass) {
1694 assert(MethodVTableIndices.empty());
1695 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1696 E = MethodInfoMap.end(); I != E; ++I) {
1697 const CXXMethodDecl *MD = I->first;
1698 const MethodInfo &MI = I->second;
1699 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001700 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1701 = MI.VTableIndex - AddressPoint;
1702 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1703 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001704 } else {
1705 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1706 }
1707 }
1708 }
1709
Peter Collingbournecfd23562011-09-26 01:57:12 +00001710 // Compute 'this' pointer adjustments.
1711 ComputeThisAdjustments();
1712
1713 // Add all address points.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001714 while (true) {
1715 AddressPoints.insert(std::make_pair(
1716 BaseSubobject(RD, OffsetInLayoutClass),
1717 AddressPoint));
1718
1719 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1720 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1721
1722 if (!PrimaryBase)
1723 break;
1724
1725 if (Layout.isPrimaryBaseVirtual()) {
1726 // Check if this virtual primary base is a primary base in the layout
1727 // class. If it's not, we don't want to add it.
1728 const ASTRecordLayout &LayoutClassLayout =
1729 Context.getASTRecordLayout(LayoutClass);
1730
1731 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1732 OffsetInLayoutClass) {
1733 // We don't want to add this class (or any of its primary bases).
1734 break;
1735 }
1736 }
1737
1738 RD = PrimaryBase;
1739 }
1740
1741 // Layout secondary vtables.
1742 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1743}
1744
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001745void
1746ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1747 bool BaseIsMorallyVirtual,
1748 CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001749 // Itanium C++ ABI 2.5.2:
1750 // Following the primary virtual table of a derived class are secondary
1751 // virtual tables for each of its proper base classes, except any primary
1752 // base(s) with which it shares its primary virtual table.
1753
1754 const CXXRecordDecl *RD = Base.getBase();
1755 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1756 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1757
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001758 for (const auto &B : RD->bases()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001759 // Ignore virtual bases, we'll emit them later.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001760 if (B.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +00001761 continue;
1762
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001763 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001764
1765 // Ignore bases that don't have a vtable.
1766 if (!BaseDecl->isDynamicClass())
1767 continue;
1768
1769 if (isBuildingConstructorVTable()) {
1770 // Itanium C++ ABI 2.6.4:
1771 // Some of the base class subobjects may not need construction virtual
1772 // tables, which will therefore not be present in the construction
1773 // virtual table group, even though the subobject virtual tables are
1774 // present in the main virtual table group for the complete object.
1775 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1776 continue;
1777 }
1778
1779 // Get the base offset of this base.
1780 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1781 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1782
1783 CharUnits BaseOffsetInLayoutClass =
1784 OffsetInLayoutClass + RelativeBaseOffset;
1785
1786 // Don't emit a secondary vtable for a primary base. We might however want
1787 // to emit secondary vtables for other bases of this base.
1788 if (BaseDecl == PrimaryBase) {
1789 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1790 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1791 continue;
1792 }
1793
1794 // Layout the primary vtable (and any secondary vtables) for this base.
1795 LayoutPrimaryAndSecondaryVTables(
1796 BaseSubobject(BaseDecl, BaseOffset),
1797 BaseIsMorallyVirtual,
1798 /*BaseIsVirtualInLayoutClass=*/false,
1799 BaseOffsetInLayoutClass);
1800 }
1801}
1802
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001803void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1804 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1805 VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001806 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1807
1808 // Check if this base has a primary base.
1809 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1810
1811 // Check if it's virtual.
1812 if (Layout.isPrimaryBaseVirtual()) {
1813 bool IsPrimaryVirtualBase = true;
1814
1815 if (isBuildingConstructorVTable()) {
1816 // Check if the base is actually a primary base in the class we use for
1817 // layout.
1818 const ASTRecordLayout &LayoutClassLayout =
1819 Context.getASTRecordLayout(LayoutClass);
1820
1821 CharUnits PrimaryBaseOffsetInLayoutClass =
1822 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1823
1824 // We know that the base is not a primary base in the layout class if
1825 // the base offsets are different.
1826 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1827 IsPrimaryVirtualBase = false;
1828 }
1829
1830 if (IsPrimaryVirtualBase)
1831 PrimaryVirtualBases.insert(PrimaryBase);
1832 }
1833 }
1834
1835 // Traverse bases, looking for more primary virtual bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001836 for (const auto &B : RD->bases()) {
1837 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001838
1839 CharUnits BaseOffsetInLayoutClass;
1840
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001841 if (B.isVirtual()) {
David Blaikie82e95a32014-11-19 07:49:47 +00001842 if (!VBases.insert(BaseDecl).second)
Peter Collingbournecfd23562011-09-26 01:57:12 +00001843 continue;
1844
1845 const ASTRecordLayout &LayoutClassLayout =
1846 Context.getASTRecordLayout(LayoutClass);
1847
1848 BaseOffsetInLayoutClass =
1849 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1850 } else {
1851 BaseOffsetInLayoutClass =
1852 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1853 }
1854
1855 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1856 }
1857}
1858
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001859void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1860 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001861 // Itanium C++ ABI 2.5.2:
1862 // Then come the virtual base virtual tables, also in inheritance graph
1863 // order, and again excluding primary bases (which share virtual tables with
1864 // the classes for which they are primary).
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001865 for (const auto &B : RD->bases()) {
1866 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001867
1868 // Check if this base needs a vtable. (If it's virtual, not a primary base
1869 // of some other class, and we haven't visited it before).
David Blaikie82e95a32014-11-19 07:49:47 +00001870 if (B.isVirtual() && BaseDecl->isDynamicClass() &&
1871 !PrimaryVirtualBases.count(BaseDecl) &&
1872 VBases.insert(BaseDecl).second) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001873 const ASTRecordLayout &MostDerivedClassLayout =
1874 Context.getASTRecordLayout(MostDerivedClass);
1875 CharUnits BaseOffset =
1876 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1877
1878 const ASTRecordLayout &LayoutClassLayout =
1879 Context.getASTRecordLayout(LayoutClass);
1880 CharUnits BaseOffsetInLayoutClass =
1881 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1882
1883 LayoutPrimaryAndSecondaryVTables(
1884 BaseSubobject(BaseDecl, BaseOffset),
1885 /*BaseIsMorallyVirtual=*/true,
1886 /*BaseIsVirtualInLayoutClass=*/true,
1887 BaseOffsetInLayoutClass);
1888 }
1889
1890 // We only need to check the base for virtual base vtables if it actually
1891 // has virtual bases.
1892 if (BaseDecl->getNumVBases())
1893 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1894 }
1895}
1896
1897/// dumpLayout - Dump the vtable layout.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001898void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00001899 // FIXME: write more tests that actually use the dumpLayout output to prevent
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001900 // ItaniumVTableBuilder regressions.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001901
1902 if (isBuildingConstructorVTable()) {
1903 Out << "Construction vtable for ('";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001904 MostDerivedClass->printQualifiedName(Out);
1905 Out << "', ";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001906 Out << MostDerivedClassOffset.getQuantity() << ") in '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001907 LayoutClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001908 } else {
1909 Out << "Vtable for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001910 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001911 }
1912 Out << "' (" << Components.size() << " entries).\n";
1913
1914 // Iterate through the address points and insert them into a new map where
1915 // they are keyed by the index and not the base object.
1916 // Since an address point can be shared by multiple subobjects, we use an
1917 // STL multimap.
1918 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1919 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1920 E = AddressPoints.end(); I != E; ++I) {
1921 const BaseSubobject& Base = I->first;
1922 uint64_t Index = I->second;
1923
1924 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1925 }
1926
1927 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1928 uint64_t Index = I;
1929
1930 Out << llvm::format("%4d | ", I);
1931
1932 const VTableComponent &Component = Components[I];
1933
1934 // Dump the component.
1935 switch (Component.getKind()) {
1936
1937 case VTableComponent::CK_VCallOffset:
1938 Out << "vcall_offset ("
1939 << Component.getVCallOffset().getQuantity()
1940 << ")";
1941 break;
1942
1943 case VTableComponent::CK_VBaseOffset:
1944 Out << "vbase_offset ("
1945 << Component.getVBaseOffset().getQuantity()
1946 << ")";
1947 break;
1948
1949 case VTableComponent::CK_OffsetToTop:
1950 Out << "offset_to_top ("
1951 << Component.getOffsetToTop().getQuantity()
1952 << ")";
1953 break;
1954
1955 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001956 Component.getRTTIDecl()->printQualifiedName(Out);
1957 Out << " RTTI";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001958 break;
1959
1960 case VTableComponent::CK_FunctionPointer: {
1961 const CXXMethodDecl *MD = Component.getFunctionDecl();
1962
1963 std::string Str =
1964 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1965 MD);
1966 Out << Str;
1967 if (MD->isPure())
1968 Out << " [pure]";
1969
David Blaikie596d2ca2012-10-16 20:25:33 +00001970 if (MD->isDeleted())
1971 Out << " [deleted]";
1972
Peter Collingbournecfd23562011-09-26 01:57:12 +00001973 ThunkInfo Thunk = VTableThunks.lookup(I);
1974 if (!Thunk.isEmpty()) {
1975 // If this function pointer has a return adjustment, dump it.
1976 if (!Thunk.Return.isEmpty()) {
1977 Out << "\n [return adjustment: ";
1978 Out << Thunk.Return.NonVirtual << " non-virtual";
1979
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001980 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1981 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001982 Out << " vbase offset offset";
1983 }
1984
1985 Out << ']';
1986 }
1987
1988 // If this function pointer has a 'this' pointer adjustment, dump it.
1989 if (!Thunk.This.isEmpty()) {
1990 Out << "\n [this adjustment: ";
1991 Out << Thunk.This.NonVirtual << " non-virtual";
1992
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001993 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
1994 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001995 Out << " vcall offset offset";
1996 }
1997
1998 Out << ']';
1999 }
2000 }
2001
2002 break;
2003 }
2004
2005 case VTableComponent::CK_CompleteDtorPointer:
2006 case VTableComponent::CK_DeletingDtorPointer: {
2007 bool IsComplete =
2008 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2009
2010 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2011
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002012 DD->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002013 if (IsComplete)
2014 Out << "() [complete]";
2015 else
2016 Out << "() [deleting]";
2017
2018 if (DD->isPure())
2019 Out << " [pure]";
2020
2021 ThunkInfo Thunk = VTableThunks.lookup(I);
2022 if (!Thunk.isEmpty()) {
2023 // If this destructor has a 'this' pointer adjustment, dump it.
2024 if (!Thunk.This.isEmpty()) {
2025 Out << "\n [this adjustment: ";
2026 Out << Thunk.This.NonVirtual << " non-virtual";
2027
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002028 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2029 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002030 Out << " vcall offset offset";
2031 }
2032
2033 Out << ']';
2034 }
2035 }
2036
2037 break;
2038 }
2039
2040 case VTableComponent::CK_UnusedFunctionPointer: {
2041 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2042
2043 std::string Str =
2044 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2045 MD);
2046 Out << "[unused] " << Str;
2047 if (MD->isPure())
2048 Out << " [pure]";
2049 }
2050
2051 }
2052
2053 Out << '\n';
2054
2055 // Dump the next address point.
2056 uint64_t NextIndex = Index + 1;
2057 if (AddressPointsByIndex.count(NextIndex)) {
2058 if (AddressPointsByIndex.count(NextIndex) == 1) {
2059 const BaseSubobject &Base =
2060 AddressPointsByIndex.find(NextIndex)->second;
2061
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002062 Out << " -- (";
2063 Base.getBase()->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002064 Out << ", " << Base.getBaseOffset().getQuantity();
2065 Out << ") vtable address --\n";
2066 } else {
2067 CharUnits BaseOffset =
2068 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2069
2070 // We store the class names in a set to get a stable order.
2071 std::set<std::string> ClassNames;
2072 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2073 AddressPointsByIndex.lower_bound(NextIndex), E =
2074 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2075 assert(I->second.getBaseOffset() == BaseOffset &&
2076 "Invalid base offset!");
2077 const CXXRecordDecl *RD = I->second.getBase();
2078 ClassNames.insert(RD->getQualifiedNameAsString());
2079 }
2080
2081 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2082 E = ClassNames.end(); I != E; ++I) {
2083 Out << " -- (" << *I;
2084 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2085 }
2086 }
2087 }
2088 }
2089
2090 Out << '\n';
2091
2092 if (isBuildingConstructorVTable())
2093 return;
2094
2095 if (MostDerivedClass->getNumVBases()) {
2096 // We store the virtual base class names and their offsets in a map to get
2097 // a stable order.
2098
2099 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2100 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2101 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2102 std::string ClassName = I->first->getQualifiedNameAsString();
2103 CharUnits OffsetOffset = I->second;
2104 ClassNamesAndOffsets.insert(
2105 std::make_pair(ClassName, OffsetOffset));
2106 }
2107
2108 Out << "Virtual base offset offsets for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002109 MostDerivedClass->printQualifiedName(Out);
2110 Out << "' (";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002111 Out << ClassNamesAndOffsets.size();
2112 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2113
2114 for (std::map<std::string, CharUnits>::const_iterator I =
2115 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2116 I != E; ++I)
2117 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2118
2119 Out << "\n";
2120 }
2121
2122 if (!Thunks.empty()) {
2123 // We store the method names in a map to get a stable order.
2124 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2125
2126 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2127 I != E; ++I) {
2128 const CXXMethodDecl *MD = I->first;
2129 std::string MethodName =
2130 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2131 MD);
2132
2133 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2134 }
2135
2136 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2137 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2138 I != E; ++I) {
2139 const std::string &MethodName = I->first;
2140 const CXXMethodDecl *MD = I->second;
2141
2142 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002143 std::sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002144 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
Craig Topper36250ad2014-05-12 05:36:57 +00002145 assert(LHS.Method == nullptr && RHS.Method == nullptr);
Benjamin Kramera741b8c2014-03-03 20:26:46 +00002146 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002147 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002148
2149 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2150 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2151
2152 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2153 const ThunkInfo &Thunk = ThunksVector[I];
2154
2155 Out << llvm::format("%4d | ", I);
2156
2157 // If this function pointer has a return pointer adjustment, dump it.
2158 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00002159 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002160 Out << " non-virtual";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002161 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2162 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002163 Out << " vbase offset offset";
2164 }
2165
2166 if (!Thunk.This.isEmpty())
2167 Out << "\n ";
2168 }
2169
2170 // If this function pointer has a 'this' pointer adjustment, dump it.
2171 if (!Thunk.This.isEmpty()) {
2172 Out << "this adjustment: ";
2173 Out << Thunk.This.NonVirtual << " non-virtual";
2174
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002175 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2176 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002177 Out << " vcall offset offset";
2178 }
2179 }
2180
2181 Out << '\n';
2182 }
2183
2184 Out << '\n';
2185 }
2186 }
2187
2188 // Compute the vtable indices for all the member functions.
2189 // Store them in a map keyed by the index so we'll get a sorted table.
2190 std::map<uint64_t, std::string> IndicesMap;
2191
Aaron Ballman2b124d12014-03-13 16:36:16 +00002192 for (const auto *MD : MostDerivedClass->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002193 // We only want virtual member functions.
2194 if (!MD->isVirtual())
2195 continue;
Reid Kleckner1cbd9aa2015-02-25 19:17:48 +00002196 MD = MD->getCanonicalDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002197
2198 std::string MethodName =
2199 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2200 MD);
2201
2202 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002203 GlobalDecl GD(DD, Dtor_Complete);
2204 assert(MethodVTableIndices.count(GD));
2205 uint64_t VTableIndex = MethodVTableIndices[GD];
2206 IndicesMap[VTableIndex] = MethodName + " [complete]";
2207 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002208 } else {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002209 assert(MethodVTableIndices.count(MD));
2210 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002211 }
2212 }
2213
2214 // Print the vtable indices for all the member functions.
2215 if (!IndicesMap.empty()) {
2216 Out << "VTable indices for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002217 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002218 Out << "' (" << IndicesMap.size() << " entries).\n";
2219
2220 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2221 E = IndicesMap.end(); I != E; ++I) {
2222 uint64_t VTableIndex = I->first;
2223 const std::string &MethodName = I->second;
2224
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002225 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer5291e682012-03-10 02:06:27 +00002226 << '\n';
Peter Collingbournecfd23562011-09-26 01:57:12 +00002227 }
2228 }
2229
2230 Out << '\n';
2231}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002232}
Peter Collingbournecfd23562011-09-26 01:57:12 +00002233
2234VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2235 const VTableComponent *VTableComponents,
2236 uint64_t NumVTableThunks,
2237 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002238 const AddressPointsMapTy &AddressPoints,
2239 bool IsMicrosoftABI)
Peter Collingbournecfd23562011-09-26 01:57:12 +00002240 : NumVTableComponents(NumVTableComponents),
2241 VTableComponents(new VTableComponent[NumVTableComponents]),
2242 NumVTableThunks(NumVTableThunks),
2243 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002244 AddressPoints(AddressPoints),
2245 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002246 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramere2980632012-04-14 14:13:43 +00002247 this->VTableComponents.get());
2248 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2249 this->VTableThunks.get());
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002250 std::sort(this->VTableThunks.get(),
2251 this->VTableThunks.get() + NumVTableThunks,
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002252 [](const VTableLayout::VTableThunkTy &LHS,
2253 const VTableLayout::VTableThunkTy &RHS) {
2254 assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2255 "Different thunks should have unique indices!");
2256 return LHS.first < RHS.first;
2257 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002258}
2259
Benjamin Kramere2980632012-04-14 14:13:43 +00002260VTableLayout::~VTableLayout() { }
Peter Collingbournecfd23562011-09-26 01:57:12 +00002261
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002262ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
Reid Klecknerb60a3d52013-12-20 23:58:52 +00002263 : VTableContextBase(/*MS=*/false) {}
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002264
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002265ItaniumVTableContext::~ItaniumVTableContext() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002266 llvm::DeleteContainerSeconds(VTableLayouts);
2267}
2268
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002269uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002270 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2271 if (I != MethodVTableIndices.end())
2272 return I->second;
2273
2274 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2275
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002276 computeVTableRelatedInformation(RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002277
2278 I = MethodVTableIndices.find(GD);
2279 assert(I != MethodVTableIndices.end() && "Did not find index!");
2280 return I->second;
2281}
2282
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002283CharUnits
2284ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2285 const CXXRecordDecl *VBase) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002286 ClassPairTy ClassPair(RD, VBase);
2287
2288 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2289 VirtualBaseClassOffsetOffsets.find(ClassPair);
2290 if (I != VirtualBaseClassOffsetOffsets.end())
2291 return I->second;
Craig Topper36250ad2014-05-12 05:36:57 +00002292
2293 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/nullptr,
Peter Collingbournecfd23562011-09-26 01:57:12 +00002294 BaseSubobject(RD, CharUnits::Zero()),
2295 /*BaseIsVirtual=*/false,
2296 /*OffsetInLayoutClass=*/CharUnits::Zero());
2297
2298 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2299 Builder.getVBaseOffsetOffsets().begin(),
2300 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2301 // Insert all types.
2302 ClassPairTy ClassPair(RD, I->first);
2303
2304 VirtualBaseClassOffsetOffsets.insert(
2305 std::make_pair(ClassPair, I->second));
2306 }
2307
2308 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2309 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2310
2311 return I->second;
2312}
2313
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002314static VTableLayout *CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002315 SmallVector<VTableLayout::VTableThunkTy, 1>
2316 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002317
2318 return new VTableLayout(Builder.getNumVTableComponents(),
2319 Builder.vtable_component_begin(),
2320 VTableThunks.size(),
2321 VTableThunks.data(),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002322 Builder.getAddressPoints(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002323 /*IsMicrosoftABI=*/false);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002324}
2325
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002326void
2327ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002328 const VTableLayout *&Entry = VTableLayouts[RD];
2329
2330 // Check if we've computed this information before.
2331 if (Entry)
2332 return;
2333
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002334 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2335 /*MostDerivedClassIsVirtual=*/0, RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002336 Entry = CreateVTableLayout(Builder);
2337
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002338 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2339 Builder.vtable_indices_end());
2340
Peter Collingbournecfd23562011-09-26 01:57:12 +00002341 // Add the known thunks.
2342 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2343
2344 // If we don't have the vbase information for this class, insert it.
2345 // getVirtualBaseOffsetOffset will compute it separately without computing
2346 // the rest of the vtable related information.
2347 if (!RD->getNumVBases())
2348 return;
2349
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00002350 const CXXRecordDecl *VBase =
2351 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002352
2353 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2354 return;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002355
2356 for (ItaniumVTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator
2357 I = Builder.getVBaseOffsetOffsets().begin(),
2358 E = Builder.getVBaseOffsetOffsets().end();
2359 I != E; ++I) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002360 // Insert all types.
2361 ClassPairTy ClassPair(RD, I->first);
2362
2363 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2364 }
2365}
2366
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002367VTableLayout *ItaniumVTableContext::createConstructionVTableLayout(
2368 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2369 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2370 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2371 MostDerivedClassIsVirtual, LayoutClass);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002372 return CreateVTableLayout(Builder);
2373}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002374
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002375namespace {
2376
2377// Vtables in the Microsoft ABI are different from the Itanium ABI.
2378//
2379// The main differences are:
2380// 1. Separate vftable and vbtable.
2381//
2382// 2. Each subobject with a vfptr gets its own vftable rather than an address
2383// point in a single vtable shared between all the subobjects.
2384// Each vftable is represented by a separate section and virtual calls
2385// must be done using the vftable which has a slot for the function to be
2386// called.
2387//
2388// 3. Virtual method definitions expect their 'this' parameter to point to the
2389// first vfptr whose table provides a compatible overridden method. In many
2390// cases, this permits the original vf-table entry to directly call
2391// the method instead of passing through a thunk.
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002392// See example before VFTableBuilder::ComputeThisOffset below.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002393//
2394// A compatible overridden method is one which does not have a non-trivial
2395// covariant-return adjustment.
2396//
2397// The first vfptr is the one with the lowest offset in the complete-object
2398// layout of the defining class, and the method definition will subtract
2399// that constant offset from the parameter value to get the real 'this'
2400// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2401// function defined in a virtual base is overridden in a more derived
2402// virtual base and these bases have a reverse order in the complete
2403// object), the vf-table may require a this-adjustment thunk.
2404//
2405// 4. vftables do not contain new entries for overrides that merely require
2406// this-adjustment. Together with #3, this keeps vf-tables smaller and
2407// eliminates the need for this-adjustment thunks in many cases, at the cost
2408// of often requiring redundant work to adjust the "this" pointer.
2409//
2410// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2411// Vtordisps are emitted into the class layout if a class has
2412// a) a user-defined ctor/dtor
2413// and
2414// b) a method overriding a method in a virtual base.
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002415//
2416// To get a better understanding of this code,
2417// you might want to see examples in test/CodeGenCXX/microsoft-abi-vtables-*.cpp
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002418
2419class VFTableBuilder {
2420public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002421 typedef MicrosoftVTableContext::MethodVFTableLocation MethodVFTableLocation;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002422
2423 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2424 MethodVFTableLocationsTy;
2425
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00002426 typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
2427 method_locations_range;
2428
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002429private:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002430 /// VTables - Global vtable information.
2431 MicrosoftVTableContext &VTables;
2432
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002433 /// Context - The ASTContext which we will use for layout information.
2434 ASTContext &Context;
2435
2436 /// MostDerivedClass - The most derived class for which we're building this
2437 /// vtable.
2438 const CXXRecordDecl *MostDerivedClass;
2439
2440 const ASTRecordLayout &MostDerivedClassLayout;
2441
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002442 const VPtrInfo &WhichVFPtr;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002443
2444 /// FinalOverriders - The final overriders of the most derived class.
2445 const FinalOverriders Overriders;
2446
2447 /// Components - The components of the vftable being built.
2448 SmallVector<VTableComponent, 64> Components;
2449
2450 MethodVFTableLocationsTy MethodVFTableLocations;
2451
David Majnemer3c7228e2014-07-01 21:10:07 +00002452 /// \brief Does this class have an RTTI component?
2453 bool HasRTTIComponent;
2454
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002455 /// MethodInfo - Contains information about a method in a vtable.
2456 /// (Used for computing 'this' pointer adjustment thunks.
2457 struct MethodInfo {
2458 /// VBTableIndex - The nonzero index in the vbtable that
2459 /// this method's base has, or zero.
2460 const uint64_t VBTableIndex;
2461
2462 /// VFTableIndex - The index in the vftable that this method has.
2463 const uint64_t VFTableIndex;
2464
2465 /// Shadowed - Indicates if this vftable slot is shadowed by
2466 /// a slot for a covariant-return override. If so, it shouldn't be printed
2467 /// or used for vcalls in the most derived class.
2468 bool Shadowed;
2469
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00002470 /// UsesExtraSlot - Indicates if this vftable slot was created because
2471 /// any of the overridden slots required a return adjusting thunk.
2472 bool UsesExtraSlot;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002473
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00002474 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex,
2475 bool UsesExtraSlot = false)
2476 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
2477 Shadowed(false), UsesExtraSlot(UsesExtraSlot) {}
2478
2479 MethodInfo()
2480 : VBTableIndex(0), VFTableIndex(0), Shadowed(false),
2481 UsesExtraSlot(false) {}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002482 };
2483
2484 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2485
2486 /// MethodInfoMap - The information for all methods in the vftable we're
2487 /// currently building.
2488 MethodInfoMapTy MethodInfoMap;
2489
2490 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2491
2492 /// VTableThunks - The thunks by vftable index in the vftable currently being
2493 /// built.
2494 VTableThunksMapTy VTableThunks;
2495
2496 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2497 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2498
2499 /// Thunks - A map that contains all the thunks needed for all methods in the
2500 /// most derived class for which the vftable is currently being built.
2501 ThunksMapTy Thunks;
2502
2503 /// AddThunk - Add a thunk for the given method.
2504 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2505 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2506
2507 // Check if we have this thunk already.
2508 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2509 ThunksVector.end())
2510 return;
2511
2512 ThunksVector.push_back(Thunk);
2513 }
2514
2515 /// ComputeThisOffset - Returns the 'this' argument offset for the given
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002516 /// method, relative to the beginning of the MostDerivedClass.
2517 CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002518
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002519 void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2520 CharUnits ThisOffset, ThisAdjustment &TA);
2521
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002522 /// AddMethod - Add a single virtual member function to the vftable
2523 /// components vector.
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002524 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002525 if (!TI.isEmpty()) {
2526 VTableThunks[Components.size()] = TI;
2527 AddThunk(MD, TI);
2528 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002529 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002530 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002531 "Destructor can't have return adjustment!");
2532 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2533 } else {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002534 Components.push_back(VTableComponent::MakeFunction(MD));
2535 }
2536 }
2537
2538 /// AddMethods - Add the methods of this base subobject and the relevant
2539 /// subbases to the vftable we're currently laying out.
2540 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2541 const CXXRecordDecl *LastVBase,
2542 BasesSetVectorTy &VisitedBases);
2543
2544 void LayoutVFTable() {
David Majnemer6e9ae782014-09-22 20:39:37 +00002545 // RTTI data goes before all other entries.
2546 if (HasRTTIComponent)
2547 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002548
2549 BasesSetVectorTy VisitedBases;
Craig Topper36250ad2014-05-12 05:36:57 +00002550 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, nullptr,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002551 VisitedBases);
David Majnemera9b7e662014-09-26 08:07:55 +00002552 assert((HasRTTIComponent ? Components.size() - 1 : Components.size()) &&
2553 "vftable can't be empty");
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002554
2555 assert(MethodVFTableLocations.empty());
2556 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2557 E = MethodInfoMap.end(); I != E; ++I) {
2558 const CXXMethodDecl *MD = I->first;
2559 const MethodInfo &MI = I->second;
2560 // Skip the methods that the MostDerivedClass didn't override
2561 // and the entries shadowed by return adjusting thunks.
2562 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2563 continue;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002564 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2565 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002566 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2567 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2568 } else {
2569 MethodVFTableLocations[MD] = Loc;
2570 }
2571 }
2572 }
2573
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002574public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002575 VFTableBuilder(MicrosoftVTableContext &VTables,
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002576 const CXXRecordDecl *MostDerivedClass, const VPtrInfo *Which)
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002577 : VTables(VTables),
2578 Context(MostDerivedClass->getASTContext()),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002579 MostDerivedClass(MostDerivedClass),
2580 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002581 WhichVFPtr(*Which),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002582 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
David Majnemerd905da42014-07-01 20:30:31 +00002583 // Only include the RTTI component if we know that we will provide a
2584 // definition of the vftable.
David Majnemerf6072342014-07-01 22:24:56 +00002585 HasRTTIComponent = Context.getLangOpts().RTTIData &&
David Majnemera03849b2015-03-18 22:04:43 +00002586 !MostDerivedClass->hasAttr<DLLImportAttr>() &&
2587 MostDerivedClass->getTemplateSpecializationKind() !=
2588 TSK_ExplicitInstantiationDeclaration;
David Majnemerd905da42014-07-01 20:30:31 +00002589
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002590 LayoutVFTable();
2591
2592 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00002593 dumpLayout(llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002594 }
2595
2596 uint64_t getNumThunks() const { return Thunks.size(); }
2597
2598 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2599
2600 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2601
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00002602 method_locations_range vtable_locations() const {
2603 return method_locations_range(MethodVFTableLocations.begin(),
2604 MethodVFTableLocations.end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002605 }
2606
2607 uint64_t getNumVTableComponents() const { return Components.size(); }
2608
2609 const VTableComponent *vtable_component_begin() const {
2610 return Components.begin();
2611 }
2612
2613 const VTableComponent *vtable_component_end() const {
2614 return Components.end();
2615 }
2616
2617 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2618 return VTableThunks.begin();
2619 }
2620
2621 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2622 return VTableThunks.end();
2623 }
2624
2625 void dumpLayout(raw_ostream &);
2626};
2627
Benjamin Kramerd5748c72015-03-23 12:31:05 +00002628} // end namespace
2629
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002630// Let's study one class hierarchy as an example:
2631// struct A {
2632// virtual void f();
2633// int x;
2634// };
2635//
2636// struct B : virtual A {
2637// virtual void f();
2638// };
2639//
2640// Record layouts:
2641// struct A:
Timur Iskhodzhanov4d280022014-11-14 14:16:34 +00002642// 0 | (A vftable pointer)
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002643// 4 | int x
2644//
2645// struct B:
Timur Iskhodzhanov4d280022014-11-14 14:16:34 +00002646// 0 | (B vbtable pointer)
2647// 4 | struct A (virtual base)
2648// 4 | (A vftable pointer)
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002649// 8 | int x
2650//
2651// Let's assume we have a pointer to the A part of an object of dynamic type B:
2652// B b;
2653// A *a = (A*)&b;
2654// a->f();
2655//
2656// In this hierarchy, f() belongs to the vftable of A, so B::f() expects
2657// "this" parameter to point at the A subobject, which is B+4.
2658// In the B::f() prologue, it adjusts "this" back to B by subtracting 4,
Nico Webercda5c7c2014-11-29 23:57:35 +00002659// performed as a *static* adjustment.
Timur Iskhodzhanov46a18ef2014-11-14 14:10:15 +00002660//
2661// Interesting thing happens when we alter the relative placement of A and B
2662// subobjects in a class:
2663// struct C : virtual B { };
2664//
2665// C c;
2666// A *a = (A*)&c;
2667// a->f();
2668//
2669// Respective record layout is:
2670// 0 | (C vbtable pointer)
2671// 4 | struct A (virtual base)
2672// 4 | (A vftable pointer)
2673// 8 | int x
2674// 12 | struct B (virtual base)
2675// 12 | (B vbtable pointer)
2676//
2677// The final overrider of f() in class C is still B::f(), so B+4 should be
2678// passed as "this" to that code. However, "a" points at B-8, so the respective
2679// vftable entry should hold a thunk that adds 12 to the "this" argument before
2680// performing a tail call to B::f().
2681//
2682// With this example in mind, we can now calculate the 'this' argument offset
2683// for the given method, relative to the beginning of the MostDerivedClass.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002684CharUnits
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002685VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00002686 BasesSetVectorTy Bases;
2687
2688 {
2689 // Find the set of least derived bases that define the given method.
2690 OverriddenMethodsSetTy VisitedOverriddenMethods;
2691 auto InitialOverriddenDefinitionCollector = [&](
2692 const CXXMethodDecl *OverriddenMD) {
2693 if (OverriddenMD->size_overridden_methods() == 0)
2694 Bases.insert(OverriddenMD->getParent());
2695 // Don't recurse on this method if we've already collected it.
2696 return VisitedOverriddenMethods.insert(OverriddenMD).second;
2697 };
2698 visitAllOverriddenMethods(Overrider.Method,
2699 InitialOverriddenDefinitionCollector);
2700 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002701
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002702 // If there are no overrides then 'this' is located
2703 // in the base that defines the method.
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00002704 if (Bases.size() == 0)
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002705 return Overrider.Offset;
2706
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002707 CXXBasePaths Paths;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002708 Overrider.Method->getParent()->lookupInBases(
Benjamin Kramer0cfa68e2015-07-25 16:31:30 +00002709 [&Bases](const CXXBaseSpecifier *Specifier, CXXBasePath &) {
2710 return Bases.count(Specifier->getType()->getAsCXXRecordDecl());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00002711 },
2712 Paths);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002713
2714 // This will hold the smallest this offset among overridees of MD.
2715 // This implies that an offset of a non-virtual base will dominate an offset
2716 // of a virtual base to potentially reduce the number of thunks required
2717 // in the derived classes that inherit this method.
2718 CharUnits Ret;
2719 bool First = true;
2720
Timur Iskhodzhanoved11ae32014-04-17 22:01:48 +00002721 const ASTRecordLayout &OverriderRDLayout =
2722 Context.getASTRecordLayout(Overrider.Method->getParent());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002723 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2724 I != E; ++I) {
2725 const CXXBasePath &Path = (*I);
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002726 CharUnits ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002727 CharUnits LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002728
Nico Weberd73258a2015-05-16 23:49:53 +00002729 // For each path from the overrider to the parents of the overridden
2730 // methods, traverse the path, calculating the this offset in the most
2731 // derived class.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002732 for (int J = 0, F = Path.size(); J != F; ++J) {
2733 const CXXBasePathElement &Element = Path[J];
2734 QualType CurTy = Element.Base->getType();
2735 const CXXRecordDecl *PrevRD = Element.Class,
2736 *CurRD = CurTy->getAsCXXRecordDecl();
2737 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2738
2739 if (Element.Base->isVirtual()) {
Timur Iskhodzhanoved11ae32014-04-17 22:01:48 +00002740 // The interesting things begin when you have virtual inheritance.
2741 // The final overrider will use a static adjustment equal to the offset
2742 // of the vbase in the final overrider class.
2743 // For example, if the final overrider is in a vbase B of the most
2744 // derived class and it overrides a method of the B's own vbase A,
2745 // it uses A* as "this". In its prologue, it can cast A* to B* with
2746 // a static offset. This offset is used regardless of the actual
2747 // offset of A from B in the most derived class, requiring an
2748 // this-adjusting thunk in the vftable if A and B are laid out
2749 // differently in the most derived class.
2750 LastVBaseOffset = ThisOffset =
2751 Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002752 } else {
2753 ThisOffset += Layout.getBaseClassOffset(CurRD);
2754 }
2755 }
2756
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002757 if (isa<CXXDestructorDecl>(Overrider.Method)) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002758 if (LastVBaseOffset.isZero()) {
2759 // If a "Base" class has at least one non-virtual base with a virtual
2760 // destructor, the "Base" virtual destructor will take the address
2761 // of the "Base" subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002762 ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002763 } else {
2764 // A virtual destructor of a virtual base takes the address of the
2765 // virtual base subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002766 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002767 }
2768 }
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +00002769
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002770 if (Ret > ThisOffset || First) {
2771 First = false;
2772 Ret = ThisOffset;
2773 }
2774 }
2775
2776 assert(!First && "Method not found in the given subobject?");
2777 return Ret;
2778}
2779
Timur Iskhodzhanov7d19fc12014-11-17 15:11:05 +00002780// Things are getting even more complex when the "this" adjustment has to
2781// use a dynamic offset instead of a static one, or even two dynamic offsets.
2782// This is sometimes required when a virtual call happens in the middle of
2783// a non-most-derived class construction or destruction.
2784//
2785// Let's take a look at the following example:
2786// struct A {
2787// virtual void f();
2788// };
2789//
2790// void foo(A *a) { a->f(); } // Knows nothing about siblings of A.
2791//
2792// struct B : virtual A {
2793// virtual void f();
2794// B() {
2795// foo(this);
2796// }
2797// };
2798//
2799// struct C : virtual B {
2800// virtual void f();
2801// };
2802//
2803// Record layouts for these classes are:
2804// struct A
2805// 0 | (A vftable pointer)
2806//
2807// struct B
2808// 0 | (B vbtable pointer)
2809// 4 | (vtordisp for vbase A)
2810// 8 | struct A (virtual base)
2811// 8 | (A vftable pointer)
2812//
2813// struct C
2814// 0 | (C vbtable pointer)
2815// 4 | (vtordisp for vbase A)
2816// 8 | struct A (virtual base) // A precedes B!
2817// 8 | (A vftable pointer)
2818// 12 | struct B (virtual base)
2819// 12 | (B vbtable pointer)
2820//
2821// When one creates an object of type C, the C constructor:
2822// - initializes all the vbptrs, then
2823// - calls the A subobject constructor
2824// (initializes A's vfptr with an address of A vftable), then
2825// - calls the B subobject constructor
2826// (initializes A's vfptr with an address of B vftable and vtordisp for A),
2827// that in turn calls foo(), then
2828// - initializes A's vfptr with an address of C vftable and zeroes out the
2829// vtordisp
2830// FIXME: if a structor knows it belongs to MDC, why doesn't it use a vftable
2831// without vtordisp thunks?
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002832// FIXME: how are vtordisp handled in the presence of nooverride/final?
Timur Iskhodzhanov7d19fc12014-11-17 15:11:05 +00002833//
2834// When foo() is called, an object with a layout of class C has a vftable
2835// referencing B::f() that assumes a B layout, so the "this" adjustments are
2836// incorrect, unless an extra adjustment is done. This adjustment is called
2837// "vtordisp adjustment". Vtordisp basically holds the difference between the
2838// actual location of a vbase in the layout class and the location assumed by
2839// the vftable of the class being constructed/destructed. Vtordisp is only
2840// needed if "this" escapes a
2841// structor (or we can't prove otherwise).
2842// [i.e. vtordisp is a dynamic adjustment for a static adjustment, which is an
2843// estimation of a dynamic adjustment]
2844//
2845// foo() gets a pointer to the A vbase and doesn't know anything about B or C,
2846// so it just passes that pointer as "this" in a virtual call.
2847// If there was no vtordisp, that would just dispatch to B::f().
2848// However, B::f() assumes B+8 is passed as "this",
2849// yet the pointer foo() passes along is B-4 (i.e. C+8).
2850// An extra adjustment is needed, so we emit a thunk into the B vftable.
2851// This vtordisp thunk subtracts the value of vtordisp
2852// from the "this" argument (-12) before making a tailcall to B::f().
2853//
2854// Let's consider an even more complex example:
2855// struct D : virtual B, virtual C {
2856// D() {
2857// foo(this);
2858// }
2859// };
2860//
2861// struct D
2862// 0 | (D vbtable pointer)
2863// 4 | (vtordisp for vbase A)
2864// 8 | struct A (virtual base) // A precedes both B and C!
2865// 8 | (A vftable pointer)
2866// 12 | struct B (virtual base) // B precedes C!
2867// 12 | (B vbtable pointer)
2868// 16 | struct C (virtual base)
2869// 16 | (C vbtable pointer)
2870//
2871// When D::D() calls foo(), we find ourselves in a thunk that should tailcall
2872// to C::f(), which assumes C+8 as its "this" parameter. This time, foo()
2873// passes along A, which is C-8. The A vtordisp holds
2874// "D.vbptr[index_of_A] - offset_of_A_in_D"
2875// and we statically know offset_of_A_in_D, so can get a pointer to D.
2876// When we know it, we can make an extra vbtable lookup to locate the C vbase
2877// and one extra static adjustment to calculate the expected value of C+8.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002878void VFTableBuilder::CalculateVtordispAdjustment(
2879 FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2880 ThisAdjustment &TA) {
2881 const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2882 MostDerivedClassLayout.getVBaseOffsetsMap();
2883 const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002884 VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002885 assert(VBaseMapEntry != VBaseMap.end());
2886
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002887 // If there's no vtordisp or the final overrider is defined in the same vbase
2888 // as the initial declaration, we don't need any vtordisp adjustment.
2889 if (!VBaseMapEntry->second.hasVtorDisp() ||
2890 Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
Timur Iskhodzhanov057fa3a2014-04-17 11:01:41 +00002891 return;
2892
2893 // OK, now we know we need to use a vtordisp thunk.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002894 // The implicit vtordisp field is located right before the vbase.
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002895 CharUnits OffsetOfVBaseWithVFPtr = VBaseMapEntry->second.VBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002896 TA.Virtual.Microsoft.VtordispOffset =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002897 (OffsetOfVBaseWithVFPtr - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002898
Timur Iskhodzhanov057fa3a2014-04-17 11:01:41 +00002899 // A simple vtordisp thunk will suffice if the final overrider is defined
2900 // in either the most derived class or its non-virtual base.
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002901 if (Overrider.Method->getParent() == MostDerivedClass ||
2902 !Overrider.VirtualBase)
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002903 return;
2904
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002905 // Otherwise, we need to do use the dynamic offset of the final overrider
2906 // in order to get "this" adjustment right.
2907 TA.Virtual.Microsoft.VBPtrOffset =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00002908 (OffsetOfVBaseWithVFPtr + WhichVFPtr.NonVirtualOffset -
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002909 MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2910 TA.Virtual.Microsoft.VBOffsetOffset =
2911 Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
Timur Iskhodzhanov6b128502014-04-22 17:32:02 +00002912 VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002913
2914 TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2915}
2916
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002917static void GroupNewVirtualOverloads(
2918 const CXXRecordDecl *RD,
2919 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2920 // Put the virtual methods into VirtualMethods in the proper order:
2921 // 1) Group overloads by declaration name. New groups are added to the
2922 // vftable in the order of their first declarations in this class
Reid Kleckner6701de22014-02-19 22:06:10 +00002923 // (including overrides and non-virtual methods).
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002924 // 2) In each group, new overloads appear in the reverse order of declaration.
2925 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2926 SmallVector<MethodGroup, 10> Groups;
2927 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2928 VisitedGroupIndicesTy VisitedGroupIndices;
Aaron Ballman2b124d12014-03-13 16:36:16 +00002929 for (const auto *MD : RD->methods()) {
Reid Kleckner240ef572015-02-25 02:16:02 +00002930 MD = MD->getCanonicalDecl();
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002931 VisitedGroupIndicesTy::iterator J;
2932 bool Inserted;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002933 std::tie(J, Inserted) = VisitedGroupIndices.insert(
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002934 std::make_pair(MD->getDeclName(), Groups.size()));
2935 if (Inserted)
Reid Kleckner6701de22014-02-19 22:06:10 +00002936 Groups.push_back(MethodGroup());
Aaron Ballman2b124d12014-03-13 16:36:16 +00002937 if (MD->isVirtual())
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002938 Groups[J->second].push_back(MD);
2939 }
2940
2941 for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2942 VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2943}
2944
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002945static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
2946 for (const auto &B : RD->bases()) {
2947 if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
2948 return true;
2949 }
2950 return false;
2951}
2952
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002953void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2954 const CXXRecordDecl *LastVBase,
2955 BasesSetVectorTy &VisitedBases) {
2956 const CXXRecordDecl *RD = Base.getBase();
2957 if (!RD->isPolymorphic())
2958 return;
2959
2960 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2961
2962 // See if this class expands a vftable of the base we look at, which is either
Nico Weberd73258a2015-05-16 23:49:53 +00002963 // the one defined by the vfptr base path or the primary base of the current
2964 // class.
Craig Topper36250ad2014-05-12 05:36:57 +00002965 const CXXRecordDecl *NextBase = nullptr, *NextLastVBase = LastVBase;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002966 CharUnits NextBaseOffset;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002967 if (BaseDepth < WhichVFPtr.PathToBaseWithVPtr.size()) {
2968 NextBase = WhichVFPtr.PathToBaseWithVPtr[BaseDepth];
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002969 if (isDirectVBase(NextBase, RD)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002970 NextLastVBase = NextBase;
2971 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2972 } else {
2973 NextBaseOffset =
2974 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2975 }
2976 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2977 assert(!Layout.isPrimaryBaseVirtual() &&
2978 "No primary virtual bases in this ABI");
2979 NextBase = PrimaryBase;
2980 NextBaseOffset = Base.getBaseOffset();
2981 }
2982
2983 if (NextBase) {
2984 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2985 NextLastVBase, VisitedBases);
2986 if (!VisitedBases.insert(NextBase))
2987 llvm_unreachable("Found a duplicate primary base!");
2988 }
2989
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002990 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2991 // Put virtual methods in the proper order.
2992 GroupNewVirtualOverloads(RD, VirtualMethods);
2993
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002994 // Now go through all virtual member functions and add them to the current
2995 // vftable. This is done by
2996 // - replacing overridden methods in their existing slots, as long as they
2997 // don't require return adjustment; calculating This adjustment if needed.
2998 // - adding new slots for methods of the current base not present in any
2999 // sub-bases;
3000 // - adding new slots for methods that require Return adjustment.
3001 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00003002 for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
3003 const CXXMethodDecl *MD = VirtualMethods[I];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003004
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003005 FinalOverriders::OverriderInfo FinalOverrider =
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003006 Overriders.getOverrider(MD, Base.getBaseOffset());
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003007 const CXXMethodDecl *FinalOverriderMD = FinalOverrider.Method;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003008 const CXXMethodDecl *OverriddenMD =
3009 FindNearestOverriddenMethod(MD, VisitedBases);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003010
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003011 ThisAdjustment ThisAdjustmentOffset;
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003012 bool ReturnAdjustingThunk = false, ForceReturnAdjustmentMangling = false;
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003013 CharUnits ThisOffset = ComputeThisOffset(FinalOverrider);
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003014 ThisAdjustmentOffset.NonVirtual =
3015 (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003016 if ((OverriddenMD || FinalOverriderMD != MD) &&
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003017 WhichVFPtr.getVBaseWithVPtr())
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003018 CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
3019 ThisAdjustmentOffset);
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003020
3021 if (OverriddenMD) {
Nico Weberd73258a2015-05-16 23:49:53 +00003022 // If MD overrides anything in this vftable, we need to update the
3023 // entries.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003024 MethodInfoMapTy::iterator OverriddenMDIterator =
3025 MethodInfoMap.find(OverriddenMD);
3026
3027 // If the overridden method went to a different vftable, skip it.
3028 if (OverriddenMDIterator == MethodInfoMap.end())
3029 continue;
3030
3031 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
3032
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003033 // Let's check if the overrider requires any return adjustments.
3034 // We must create a new slot if the MD's return type is not trivially
3035 // convertible to the OverriddenMD's one.
3036 // Once a chain of method overrides adds a return adjusting vftable slot,
3037 // all subsequent overrides will also use an extra method slot.
3038 ReturnAdjustingThunk = !ComputeReturnAdjustmentBaseOffset(
3039 Context, MD, OverriddenMD).isEmpty() ||
3040 OverriddenMethodInfo.UsesExtraSlot;
3041
3042 if (!ReturnAdjustingThunk) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003043 // No return adjustment needed - just replace the overridden method info
3044 // with the current info.
3045 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
3046 OverriddenMethodInfo.VFTableIndex);
3047 MethodInfoMap.erase(OverriddenMDIterator);
3048
3049 assert(!MethodInfoMap.count(MD) &&
3050 "Should not have method info for this method yet!");
3051 MethodInfoMap.insert(std::make_pair(MD, MI));
3052 continue;
Reid Kleckner31a9f742013-12-27 20:29:16 +00003053 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003054
Reid Kleckner31a9f742013-12-27 20:29:16 +00003055 // In case we need a return adjustment, we'll add a new slot for
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003056 // the overrider. Mark the overriden method as shadowed by the new slot.
Reid Kleckner31a9f742013-12-27 20:29:16 +00003057 OverriddenMethodInfo.Shadowed = true;
Reid Kleckner31a9f742013-12-27 20:29:16 +00003058
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003059 // Force a special name mangling for a return-adjusting thunk
3060 // unless the method is the final overrider without this adjustment.
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003061 ForceReturnAdjustmentMangling =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003062 !(MD == FinalOverriderMD && ThisAdjustmentOffset.isEmpty());
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003063 } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003064 MD->size_overridden_methods()) {
3065 // Skip methods that don't belong to the vftable of the current class,
3066 // e.g. each method that wasn't seen in any of the visited sub-bases
3067 // but overrides multiple methods of other sub-bases.
3068 continue;
3069 }
3070
3071 // If we got here, MD is a method not seen in any of the sub-bases or
3072 // it requires return adjustment. Insert the method info for this method.
3073 unsigned VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003074 LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
David Majnemer3c7228e2014-07-01 21:10:07 +00003075 MethodInfo MI(VBIndex,
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003076 HasRTTIComponent ? Components.size() - 1 : Components.size(),
3077 ReturnAdjustingThunk);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003078
3079 assert(!MethodInfoMap.count(MD) &&
3080 "Should not have method info for this method yet!");
3081 MethodInfoMap.insert(std::make_pair(MD, MI));
3082
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003083 // Check if this overrider needs a return adjustment.
3084 // We don't want to do this for pure virtual member functions.
3085 BaseOffset ReturnAdjustmentOffset;
3086 ReturnAdjustment ReturnAdjustment;
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003087 if (!FinalOverriderMD->isPure()) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003088 ReturnAdjustmentOffset =
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003089 ComputeReturnAdjustmentBaseOffset(Context, FinalOverriderMD, MD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003090 }
3091 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003092 ForceReturnAdjustmentMangling = true;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003093 ReturnAdjustment.NonVirtual =
3094 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
3095 if (ReturnAdjustmentOffset.VirtualBase) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003096 const ASTRecordLayout &DerivedLayout =
3097 Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
3098 ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
3099 DerivedLayout.getVBPtrOffset().getQuantity();
3100 ReturnAdjustment.Virtual.Microsoft.VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003101 VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
3102 ReturnAdjustmentOffset.VirtualBase);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003103 }
3104 }
3105
Timur Iskhodzhanov70814602014-11-17 15:53:50 +00003106 AddMethod(FinalOverriderMD,
Timur Iskhodzhanov16055e72014-08-10 11:40:51 +00003107 ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
3108 ForceReturnAdjustmentMangling ? MD : nullptr));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003109 }
3110}
3111
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003112static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
3113 for (VPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003114 E = Path.rend(); I != E; ++I) {
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003115 Out << "'";
3116 (*I)->printQualifiedName(Out);
3117 Out << "' in ";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003118 }
3119}
3120
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003121static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
3122 bool ContinueFirstLine) {
3123 const ReturnAdjustment &R = TI.Return;
3124 bool Multiline = false;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003125 const char *LinePrefix = "\n ";
3126 if (!R.isEmpty() || TI.Method) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003127 if (!ContinueFirstLine)
3128 Out << LinePrefix;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003129 Out << "[return adjustment (to type '"
3130 << TI.Method->getReturnType().getCanonicalType().getAsString()
3131 << "'): ";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003132 if (R.Virtual.Microsoft.VBPtrOffset)
3133 Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
3134 if (R.Virtual.Microsoft.VBIndex)
3135 Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
3136 Out << R.NonVirtual << " non-virtual]";
3137 Multiline = true;
3138 }
3139
3140 const ThisAdjustment &T = TI.This;
3141 if (!T.isEmpty()) {
3142 if (Multiline || !ContinueFirstLine)
3143 Out << LinePrefix;
3144 Out << "[this adjustment: ";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003145 if (!TI.This.Virtual.isEmpty()) {
3146 assert(T.Virtual.Microsoft.VtordispOffset < 0);
3147 Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
3148 if (T.Virtual.Microsoft.VBPtrOffset) {
3149 Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00003150 << " to the left,";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003151 assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
3152 Out << LinePrefix << " vboffset at "
3153 << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
3154 }
3155 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003156 Out << T.NonVirtual << " non-virtual]";
3157 }
3158}
3159
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003160void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3161 Out << "VFTable for ";
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003162 PrintBasePath(WhichVFPtr.PathToBaseWithVPtr, Out);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003163 Out << "'";
3164 MostDerivedClass->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003165 Out << "' (" << Components.size()
3166 << (Components.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003167
3168 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3169 Out << llvm::format("%4d | ", I);
3170
3171 const VTableComponent &Component = Components[I];
3172
3173 // Dump the component.
3174 switch (Component.getKind()) {
3175 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003176 Component.getRTTIDecl()->printQualifiedName(Out);
3177 Out << " RTTI";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003178 break;
3179
3180 case VTableComponent::CK_FunctionPointer: {
3181 const CXXMethodDecl *MD = Component.getFunctionDecl();
3182
Reid Kleckner604c8b42013-12-27 19:43:59 +00003183 // FIXME: Figure out how to print the real thunk type, since they can
3184 // differ in the return type.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003185 std::string Str = PredefinedExpr::ComputeName(
3186 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3187 Out << Str;
3188 if (MD->isPure())
3189 Out << " [pure]";
3190
David Majnemerd59becb2014-09-12 04:38:08 +00003191 if (MD->isDeleted())
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003192 Out << " [deleted]";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003193
3194 ThunkInfo Thunk = VTableThunks.lookup(I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003195 if (!Thunk.isEmpty())
3196 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003197
3198 break;
3199 }
3200
3201 case VTableComponent::CK_DeletingDtorPointer: {
3202 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3203
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003204 DD->printQualifiedName(Out);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003205 Out << "() [scalar deleting]";
3206
3207 if (DD->isPure())
3208 Out << " [pure]";
3209
3210 ThunkInfo Thunk = VTableThunks.lookup(I);
3211 if (!Thunk.isEmpty()) {
3212 assert(Thunk.Return.isEmpty() &&
3213 "No return adjustment needed for destructors!");
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003214 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003215 }
3216
3217 break;
3218 }
3219
3220 default:
3221 DiagnosticsEngine &Diags = Context.getDiagnostics();
3222 unsigned DiagID = Diags.getCustomDiagID(
3223 DiagnosticsEngine::Error,
3224 "Unexpected vftable component type %0 for component number %1");
3225 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3226 << I << Component.getKind();
3227 }
3228
3229 Out << '\n';
3230 }
3231
3232 Out << '\n';
3233
3234 if (!Thunks.empty()) {
3235 // We store the method names in a map to get a stable order.
3236 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3237
3238 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3239 I != E; ++I) {
3240 const CXXMethodDecl *MD = I->first;
3241 std::string MethodName = PredefinedExpr::ComputeName(
3242 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3243
3244 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3245 }
3246
3247 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3248 I = MethodNamesAndDecls.begin(),
3249 E = MethodNamesAndDecls.end();
3250 I != E; ++I) {
3251 const std::string &MethodName = I->first;
3252 const CXXMethodDecl *MD = I->second;
3253
3254 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00003255 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003256 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
3257 // Keep different thunks with the same adjustments in the order they
3258 // were put into the vector.
Benjamin Kramera741b8c2014-03-03 20:26:46 +00003259 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003260 });
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003261
3262 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3263 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3264
3265 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3266 const ThunkInfo &Thunk = ThunksVector[I];
3267
3268 Out << llvm::format("%4d | ", I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003269 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003270 Out << '\n';
3271 }
3272
3273 Out << '\n';
3274 }
3275 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003276
3277 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003278}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003279
Reid Kleckner5f080942014-01-03 23:42:00 +00003280static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
Craig Topper3cb91b22014-08-27 06:28:16 +00003281 ArrayRef<const CXXRecordDecl *> B) {
Craig Topper00bbdcf2014-06-28 23:22:23 +00003282 for (ArrayRef<const CXXRecordDecl *>::iterator I = B.begin(), E = B.end();
Reid Kleckner5f080942014-01-03 23:42:00 +00003283 I != E; ++I) {
3284 if (A.count(*I))
3285 return true;
3286 }
3287 return false;
3288}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003289
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003290static bool rebucketPaths(VPtrInfoVector &Paths);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003291
Reid Kleckner5f080942014-01-03 23:42:00 +00003292/// Produces MSVC-compatible vbtable data. The symbols produced by this
3293/// algorithm match those produced by MSVC 2012 and newer, which is different
3294/// from MSVC 2010.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003295///
3296/// MSVC 2012 appears to minimize the vbtable names using the following
3297/// algorithm. First, walk the class hierarchy in the usual order, depth first,
3298/// left to right, to find all of the subobjects which contain a vbptr field.
3299/// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3300/// record with a vbptr creates an initially empty path.
3301///
3302/// To combine paths from child nodes, the paths are compared to check for
3303/// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3304/// components in the same order. Each group of ambiguous paths is extended by
3305/// appending the class of the base from which it came. If the current class
3306/// node produced an ambiguous path, its path is extended with the current class.
3307/// After extending paths, MSVC again checks for ambiguity, and extends any
3308/// ambiguous path which wasn't already extended. Because each node yields an
3309/// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3310/// to produce an unambiguous set of paths.
3311///
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003312/// TODO: Presumably vftables use the same algorithm.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003313void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3314 const CXXRecordDecl *RD,
3315 VPtrInfoVector &Paths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003316 assert(Paths.empty());
3317 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003318
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003319 // Base case: this subobject has its own vptr.
3320 if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
3321 Paths.push_back(new VPtrInfo(RD));
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003322
Reid Kleckner5f080942014-01-03 23:42:00 +00003323 // Recursive case: get all the vbtables from our bases and remove anything
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003324 // that shares a virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003325 llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003326 for (const auto &B : RD->bases()) {
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003327 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
3328 if (B.isVirtual() && VBasesSeen.count(Base))
Reid Kleckner5f080942014-01-03 23:42:00 +00003329 continue;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003330
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003331 if (!Base->isDynamicClass())
3332 continue;
Reid Kleckner5f080942014-01-03 23:42:00 +00003333
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003334 const VPtrInfoVector &BasePaths =
3335 ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3336
Reid Klecknerfd385402014-04-17 22:47:52 +00003337 for (VPtrInfo *BaseInfo : BasePaths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003338 // Don't include the path if it goes through a virtual base that we've
3339 // already included.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003340 if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
Reid Kleckner5f080942014-01-03 23:42:00 +00003341 continue;
3342
3343 // Copy the path and adjust it as necessary.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003344 VPtrInfo *P = new VPtrInfo(*BaseInfo);
Reid Kleckner5f080942014-01-03 23:42:00 +00003345
3346 // We mangle Base into the path if the path would've been ambiguous and it
3347 // wasn't already extended with Base.
3348 if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3349 P->NextBaseToMangle = Base;
3350
Reid Klecknerfd385402014-04-17 22:47:52 +00003351 // Keep track of which vtable the derived class is going to extend with
3352 // new methods or bases. We append to either the vftable of our primary
3353 // base, or the first non-virtual base that has a vbtable.
3354 if (P->ReusingBase == Base &&
3355 Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003356 : Layout.getPrimaryBase()))
Reid Kleckner5f080942014-01-03 23:42:00 +00003357 P->ReusingBase = RD;
Reid Klecknerfd385402014-04-17 22:47:52 +00003358
3359 // Keep track of the full adjustment from the MDC to this vtable. The
3360 // adjustment is captured by an optional vbase and a non-virtual offset.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003361 if (B.isVirtual())
Reid Kleckner5f080942014-01-03 23:42:00 +00003362 P->ContainingVBases.push_back(Base);
3363 else if (P->ContainingVBases.empty())
3364 P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3365
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003366 // Update the full offset in the MDC.
3367 P->FullOffsetInMDC = P->NonVirtualOffset;
3368 if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3369 P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3370
Reid Kleckner5f080942014-01-03 23:42:00 +00003371 Paths.push_back(P);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003372 }
3373
Timur Iskhodzhanov9ae7d3b2014-03-31 11:01:51 +00003374 if (B.isVirtual())
3375 VBasesSeen.insert(Base);
3376
Reid Kleckner5f080942014-01-03 23:42:00 +00003377 // After visiting any direct base, we've transitively visited all of its
3378 // morally virtual bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003379 for (const auto &VB : Base->vbases())
3380 VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003381 }
3382
Reid Kleckner5f080942014-01-03 23:42:00 +00003383 // Sort the paths into buckets, and if any of them are ambiguous, extend all
3384 // paths in ambiguous buckets.
3385 bool Changed = true;
3386 while (Changed)
3387 Changed = rebucketPaths(Paths);
3388}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003389
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003390static bool extendPath(VPtrInfo *P) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003391 if (P->NextBaseToMangle) {
3392 P->MangledPath.push_back(P->NextBaseToMangle);
Craig Topper36250ad2014-05-12 05:36:57 +00003393 P->NextBaseToMangle = nullptr;// Prevent the path from being extended twice.
Reid Kleckner5f080942014-01-03 23:42:00 +00003394 return true;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003395 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003396 return false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003397}
3398
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003399static bool rebucketPaths(VPtrInfoVector &Paths) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003400 // What we're essentially doing here is bucketing together ambiguous paths.
3401 // Any bucket with more than one path in it gets extended by NextBase, which
3402 // is usually the direct base of the inherited the vbptr. This code uses a
3403 // sorted vector to implement a multiset to form the buckets. Note that the
3404 // ordering is based on pointers, but it doesn't change our output order. The
3405 // current algorithm is designed to match MSVC 2012's names.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003406 VPtrInfoVector PathsSorted(Paths);
Benjamin Kramer15ae7832014-03-07 21:35:40 +00003407 std::sort(PathsSorted.begin(), PathsSorted.end(),
3408 [](const VPtrInfo *LHS, const VPtrInfo *RHS) {
3409 return LHS->MangledPath < RHS->MangledPath;
3410 });
Reid Kleckner5f080942014-01-03 23:42:00 +00003411 bool Changed = false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003412 for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3413 // Scan forward to find the end of the bucket.
3414 size_t BucketStart = I;
3415 do {
3416 ++I;
Reid Kleckner5f080942014-01-03 23:42:00 +00003417 } while (I != E && PathsSorted[BucketStart]->MangledPath ==
3418 PathsSorted[I]->MangledPath);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003419
3420 // If this bucket has multiple paths, extend them all.
3421 if (I - BucketStart > 1) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003422 for (size_t II = BucketStart; II != I; ++II)
Reid Kleckner5f080942014-01-03 23:42:00 +00003423 Changed |= extendPath(PathsSorted[II]);
3424 assert(Changed && "no paths were extended to fix ambiguity");
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003425 }
3426 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003427 return Changed;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003428}
3429
3430MicrosoftVTableContext::~MicrosoftVTableContext() {
Nico Weberd19e6a72014-04-24 19:52:12 +00003431 for (auto &P : VFPtrLocations)
3432 llvm::DeleteContainerPointers(*P.second);
Reid Kleckner33311282014-02-28 23:26:22 +00003433 llvm::DeleteContainerSeconds(VFPtrLocations);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003434 llvm::DeleteContainerSeconds(VFTableLayouts);
3435 llvm::DeleteContainerSeconds(VBaseInfo);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003436}
3437
David Majnemerab130922015-05-04 18:47:54 +00003438namespace {
3439typedef llvm::SetVector<BaseSubobject, std::vector<BaseSubobject>,
3440 llvm::DenseSet<BaseSubobject>> FullPathTy;
3441}
3442
3443// This recursive function finds all paths from a subobject centered at
3444// (RD, Offset) to the subobject located at BaseWithVPtr.
3445static void findPathsToSubobject(ASTContext &Context,
3446 const ASTRecordLayout &MostDerivedLayout,
3447 const CXXRecordDecl *RD, CharUnits Offset,
3448 BaseSubobject BaseWithVPtr,
3449 FullPathTy &FullPath,
3450 std::list<FullPathTy> &Paths) {
3451 if (BaseSubobject(RD, Offset) == BaseWithVPtr) {
3452 Paths.push_back(FullPath);
3453 return;
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003454 }
3455
3456 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3457
David Majnemerab130922015-05-04 18:47:54 +00003458 for (const CXXBaseSpecifier &BS : RD->bases()) {
David Majnemeread97572015-05-01 21:35:41 +00003459 const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
David Majnemerab130922015-05-04 18:47:54 +00003460 CharUnits NewOffset = BS.isVirtual()
3461 ? MostDerivedLayout.getVBaseClassOffset(Base)
3462 : Offset + Layout.getBaseClassOffset(Base);
3463 FullPath.insert(BaseSubobject(Base, NewOffset));
3464 findPathsToSubobject(Context, MostDerivedLayout, Base, NewOffset,
3465 BaseWithVPtr, FullPath, Paths);
3466 FullPath.pop_back();
3467 }
3468}
David Majnemerd950f152015-04-30 17:15:48 +00003469
David Majnemerab130922015-05-04 18:47:54 +00003470// Return the paths which are not subsets of other paths.
3471static void removeRedundantPaths(std::list<FullPathTy> &FullPaths) {
3472 FullPaths.remove_if([&](const FullPathTy &SpecificPath) {
3473 for (const FullPathTy &OtherPath : FullPaths) {
3474 if (&SpecificPath == &OtherPath)
David Majnemer70e6a002015-05-01 21:35:45 +00003475 continue;
David Majnemerab130922015-05-04 18:47:54 +00003476 if (std::all_of(SpecificPath.begin(), SpecificPath.end(),
3477 [&](const BaseSubobject &BSO) {
3478 return OtherPath.count(BSO) != 0;
3479 })) {
3480 return true;
David Majnemer70e6a002015-05-01 21:35:45 +00003481 }
David Majnemerd950f152015-04-30 17:15:48 +00003482 }
David Majnemerab130922015-05-04 18:47:54 +00003483 return false;
3484 });
3485}
3486
3487static CharUnits getOffsetOfFullPath(ASTContext &Context,
3488 const CXXRecordDecl *RD,
3489 const FullPathTy &FullPath) {
3490 const ASTRecordLayout &MostDerivedLayout =
3491 Context.getASTRecordLayout(RD);
3492 CharUnits Offset = CharUnits::fromQuantity(-1);
3493 for (const BaseSubobject &BSO : FullPath) {
3494 const CXXRecordDecl *Base = BSO.getBase();
3495 // The first entry in the path is always the most derived record, skip it.
3496 if (Base == RD) {
3497 assert(Offset.getQuantity() == -1);
3498 Offset = CharUnits::Zero();
3499 continue;
3500 }
3501 assert(Offset.getQuantity() != -1);
3502 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3503 // While we know which base has to be traversed, we don't know if that base
3504 // was a virtual base.
3505 const CXXBaseSpecifier *BaseBS = std::find_if(
3506 RD->bases_begin(), RD->bases_end(), [&](const CXXBaseSpecifier &BS) {
3507 return BS.getType()->getAsCXXRecordDecl() == Base;
3508 });
3509 Offset = BaseBS->isVirtual() ? MostDerivedLayout.getVBaseClassOffset(Base)
3510 : Offset + Layout.getBaseClassOffset(Base);
3511 RD = Base;
David Majnemerd950f152015-04-30 17:15:48 +00003512 }
David Majnemerab130922015-05-04 18:47:54 +00003513 return Offset;
3514}
David Majnemeread97572015-05-01 21:35:41 +00003515
David Majnemerab130922015-05-04 18:47:54 +00003516// We want to select the path which introduces the most covariant overrides. If
3517// two paths introduce overrides which the other path doesn't contain, issue a
3518// diagnostic.
3519static const FullPathTy *selectBestPath(ASTContext &Context,
3520 const CXXRecordDecl *RD, VPtrInfo *Info,
3521 std::list<FullPathTy> &FullPaths) {
David Majnemere48630f2015-05-05 01:39:20 +00003522 // Handle some easy cases first.
3523 if (FullPaths.empty())
3524 return nullptr;
3525 if (FullPaths.size() == 1)
3526 return &FullPaths.front();
3527
David Majnemerab130922015-05-04 18:47:54 +00003528 const FullPathTy *BestPath = nullptr;
3529 typedef std::set<const CXXMethodDecl *> OverriderSetTy;
3530 OverriderSetTy LastOverrides;
3531 for (const FullPathTy &SpecificPath : FullPaths) {
David Majnemere48630f2015-05-05 01:39:20 +00003532 assert(!SpecificPath.empty());
David Majnemerab130922015-05-04 18:47:54 +00003533 OverriderSetTy CurrentOverrides;
3534 const CXXRecordDecl *TopLevelRD = SpecificPath.begin()->getBase();
3535 // Find the distance from the start of the path to the subobject with the
3536 // VPtr.
3537 CharUnits BaseOffset =
3538 getOffsetOfFullPath(Context, TopLevelRD, SpecificPath);
3539 FinalOverriders Overriders(TopLevelRD, CharUnits::Zero(), TopLevelRD);
3540 for (const CXXMethodDecl *MD : Info->BaseWithVPtr->methods()) {
3541 if (!MD->isVirtual())
3542 continue;
3543 FinalOverriders::OverriderInfo OI =
3544 Overriders.getOverrider(MD->getCanonicalDecl(), BaseOffset);
David Majnemere48630f2015-05-05 01:39:20 +00003545 const CXXMethodDecl *OverridingMethod = OI.Method;
David Majnemerab130922015-05-04 18:47:54 +00003546 // Only overriders which have a return adjustment introduce problematic
3547 // thunks.
David Majnemere48630f2015-05-05 01:39:20 +00003548 if (ComputeReturnAdjustmentBaseOffset(Context, OverridingMethod, MD)
3549 .isEmpty())
David Majnemerab130922015-05-04 18:47:54 +00003550 continue;
3551 // It's possible that the overrider isn't in this path. If so, skip it
3552 // because this path didn't introduce it.
David Majnemere48630f2015-05-05 01:39:20 +00003553 const CXXRecordDecl *OverridingParent = OverridingMethod->getParent();
David Majnemerab130922015-05-04 18:47:54 +00003554 if (std::none_of(SpecificPath.begin(), SpecificPath.end(),
3555 [&](const BaseSubobject &BSO) {
3556 return BSO.getBase() == OverridingParent;
3557 }))
3558 continue;
David Majnemere48630f2015-05-05 01:39:20 +00003559 CurrentOverrides.insert(OverridingMethod);
David Majnemerab130922015-05-04 18:47:54 +00003560 }
3561 OverriderSetTy NewOverrides =
3562 llvm::set_difference(CurrentOverrides, LastOverrides);
3563 if (NewOverrides.empty())
3564 continue;
3565 OverriderSetTy MissingOverrides =
3566 llvm::set_difference(LastOverrides, CurrentOverrides);
3567 if (MissingOverrides.empty()) {
3568 // This path is a strict improvement over the last path, let's use it.
3569 BestPath = &SpecificPath;
3570 std::swap(CurrentOverrides, LastOverrides);
3571 } else {
3572 // This path introduces an overrider with a conflicting covariant thunk.
3573 DiagnosticsEngine &Diags = Context.getDiagnostics();
3574 const CXXMethodDecl *CovariantMD = *NewOverrides.begin();
3575 const CXXMethodDecl *ConflictMD = *MissingOverrides.begin();
3576 Diags.Report(RD->getLocation(), diag::err_vftable_ambiguous_component)
3577 << RD;
3578 Diags.Report(CovariantMD->getLocation(), diag::note_covariant_thunk)
3579 << CovariantMD;
3580 Diags.Report(ConflictMD->getLocation(), diag::note_covariant_thunk)
3581 << ConflictMD;
3582 }
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003583 }
David Majnemere48630f2015-05-05 01:39:20 +00003584 // Go with the path that introduced the most covariant overrides. If there is
3585 // no such path, pick the first path.
3586 return BestPath ? BestPath : &FullPaths.front();
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003587}
3588
3589static void computeFullPathsForVFTables(ASTContext &Context,
3590 const CXXRecordDecl *RD,
3591 VPtrInfoVector &Paths) {
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003592 const ASTRecordLayout &MostDerivedLayout = Context.getASTRecordLayout(RD);
David Majnemerab130922015-05-04 18:47:54 +00003593 FullPathTy FullPath;
3594 std::list<FullPathTy> FullPaths;
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003595 for (VPtrInfo *Info : Paths) {
David Majnemerab130922015-05-04 18:47:54 +00003596 findPathsToSubobject(
3597 Context, MostDerivedLayout, RD, CharUnits::Zero(),
3598 BaseSubobject(Info->BaseWithVPtr, Info->FullOffsetInMDC), FullPath,
3599 FullPaths);
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003600 FullPath.clear();
David Majnemerab130922015-05-04 18:47:54 +00003601 removeRedundantPaths(FullPaths);
3602 Info->PathToBaseWithVPtr.clear();
3603 if (const FullPathTy *BestPath =
3604 selectBestPath(Context, RD, Info, FullPaths))
3605 for (const BaseSubobject &BSO : *BestPath)
3606 Info->PathToBaseWithVPtr.push_back(BSO.getBase());
3607 FullPaths.clear();
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003608 }
3609}
3610
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003611void MicrosoftVTableContext::computeVTableRelatedInformation(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003612 const CXXRecordDecl *RD) {
3613 assert(RD->isDynamicClass());
3614
3615 // Check if we've computed this information before.
3616 if (VFPtrLocations.count(RD))
3617 return;
3618
3619 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3620
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003621 VPtrInfoVector *VFPtrs = new VPtrInfoVector();
3622 computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
Reid Kleckner15fdcf12014-09-22 23:14:46 +00003623 computeFullPathsForVFTables(Context, RD, *VFPtrs);
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003624 VFPtrLocations[RD] = VFPtrs;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003625
3626 MethodVFTableLocationsTy NewMethodLocations;
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003627 for (VPtrInfoVector::iterator I = VFPtrs->begin(), E = VFPtrs->end();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003628 I != E; ++I) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003629 VFTableBuilder Builder(*this, RD, *I);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003630
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003631 VFTableIdTy id(RD, (*I)->FullOffsetInMDC);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003632 assert(VFTableLayouts.count(id) == 0);
3633 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3634 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003635 VFTableLayouts[id] = new VTableLayout(
3636 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3637 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003638 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00003639
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003640 for (const auto &Loc : Builder.vtable_locations()) {
3641 GlobalDecl GD = Loc.first;
3642 MethodVFTableLocation NewLoc = Loc.second;
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00003643 auto M = NewMethodLocations.find(GD);
3644 if (M == NewMethodLocations.end() || NewLoc < M->second)
3645 NewMethodLocations[GD] = NewLoc;
3646 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003647 }
3648
3649 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3650 NewMethodLocations.end());
3651 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00003652 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003653}
3654
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003655void MicrosoftVTableContext::dumpMethodLocations(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003656 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3657 raw_ostream &Out) {
3658 // Compute the vtable indices for all the member functions.
3659 // Store them in a map keyed by the location so we'll get a sorted table.
3660 std::map<MethodVFTableLocation, std::string> IndicesMap;
3661 bool HasNonzeroOffset = false;
3662
3663 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3664 E = NewMethods.end(); I != E; ++I) {
3665 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3666 assert(MD->isVirtual());
3667
3668 std::string MethodName = PredefinedExpr::ComputeName(
3669 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3670
3671 if (isa<CXXDestructorDecl>(MD)) {
3672 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3673 } else {
3674 IndicesMap[I->second] = MethodName;
3675 }
3676
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003677 if (!I->second.VFPtrOffset.isZero() || I->second.VBTableIndex != 0)
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003678 HasNonzeroOffset = true;
3679 }
3680
3681 // Print the vtable indices for all the member functions.
3682 if (!IndicesMap.empty()) {
3683 Out << "VFTable indices for ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003684 Out << "'";
3685 RD->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003686 Out << "' (" << IndicesMap.size()
3687 << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003688
3689 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3690 uint64_t LastVBIndex = 0;
3691 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3692 I = IndicesMap.begin(),
3693 E = IndicesMap.end();
3694 I != E; ++I) {
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003695 CharUnits VFPtrOffset = I->first.VFPtrOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003696 uint64_t VBIndex = I->first.VBTableIndex;
3697 if (HasNonzeroOffset &&
3698 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3699 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3700 Out << " -- accessible via ";
3701 if (VBIndex)
3702 Out << "vbtable index " << VBIndex << ", ";
3703 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3704 LastVFPtrOffset = VFPtrOffset;
3705 LastVBIndex = VBIndex;
3706 }
3707
3708 uint64_t VTableIndex = I->first.Index;
3709 const std::string &MethodName = I->second;
3710 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3711 }
3712 Out << '\n';
3713 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003714
3715 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003716}
3717
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003718const VirtualBaseInfo *MicrosoftVTableContext::computeVBTableRelatedInformation(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003719 const CXXRecordDecl *RD) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003720 VirtualBaseInfo *VBI;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003721
Reid Kleckner5f080942014-01-03 23:42:00 +00003722 {
3723 // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
3724 // as it may be modified and rehashed under us.
3725 VirtualBaseInfo *&Entry = VBaseInfo[RD];
3726 if (Entry)
3727 return Entry;
3728 Entry = VBI = new VirtualBaseInfo();
3729 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003730
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003731 computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003732
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003733 // First, see if the Derived class shared the vbptr with a non-virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003734 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003735 if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003736 // If the Derived class shares the vbptr with a non-virtual base, the shared
3737 // virtual bases come first so that the layout is the same.
3738 const VirtualBaseInfo *BaseInfo =
3739 computeVBTableRelatedInformation(VBPtrBase);
Reid Kleckner5f080942014-01-03 23:42:00 +00003740 VBI->VBTableIndices.insert(BaseInfo->VBTableIndices.begin(),
3741 BaseInfo->VBTableIndices.end());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003742 }
3743
3744 // New vbases are added to the end of the vbtable.
3745 // Skip the self entry and vbases visited in the non-virtual base, if any.
Reid Kleckner5f080942014-01-03 23:42:00 +00003746 unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003747 for (const auto &VB : RD->vbases()) {
3748 const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
Reid Kleckner5f080942014-01-03 23:42:00 +00003749 if (!VBI->VBTableIndices.count(CurVBase))
3750 VBI->VBTableIndices[CurVBase] = VBTableIndex++;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003751 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003752
Reid Kleckner5f080942014-01-03 23:42:00 +00003753 return VBI;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003754}
3755
3756unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3757 const CXXRecordDecl *VBase) {
3758 const VirtualBaseInfo *VBInfo = computeVBTableRelatedInformation(Derived);
3759 assert(VBInfo->VBTableIndices.count(VBase));
3760 return VBInfo->VBTableIndices.find(VBase)->second;
3761}
3762
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003763const VPtrInfoVector &
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003764MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003765 return computeVBTableRelatedInformation(RD)->VBPtrPaths;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003766}
3767
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003768const VPtrInfoVector &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003769MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003770 computeVTableRelatedInformation(RD);
3771
3772 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003773 return *VFPtrLocations[RD];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003774}
3775
3776const VTableLayout &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003777MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3778 CharUnits VFPtrOffset) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003779 computeVTableRelatedInformation(RD);
3780
3781 VFTableIdTy id(RD, VFPtrOffset);
3782 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3783 return *VFTableLayouts[id];
3784}
3785
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003786const MicrosoftVTableContext::MethodVFTableLocation &
3787MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003788 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3789 "Only use this method for virtual methods or dtors");
3790 if (isa<CXXDestructorDecl>(GD.getDecl()))
3791 assert(GD.getDtorType() == Dtor_Deleting);
3792
3793 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3794 if (I != MethodVFTableLocations.end())
3795 return I->second;
3796
3797 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3798
3799 computeVTableRelatedInformation(RD);
3800
3801 I = MethodVFTableLocations.find(GD);
3802 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3803 return I->second;
3804}