blob: 30319554528608844c83e73a0fcf47cc454dd421 [file] [log] [blame]
Peter Collingbourne24018462011-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 Kramerd4f51982012-07-04 18:45:14 +000015#include "clang/AST/ASTContext.h"
Peter Collingbourne24018462011-09-26 01:57:12 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/Basic/TargetInfo.h"
19#include "llvm/Support/Format.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000020#include "llvm/Support/raw_ostream.h"
Peter Collingbourne24018462011-09-26 01:57:12 +000021#include <algorithm>
22#include <cstdio>
23
24using namespace clang;
25
26#define DUMP_OVERRIDERS 0
27
28namespace {
29
30/// BaseOffset - Represents an offset from a derived class to a direct or
31/// indirect base class.
32struct BaseOffset {
33 /// DerivedClass - The derived class.
34 const CXXRecordDecl *DerivedClass;
35
36 /// VirtualBase - If the path from the derived class to the base class
Timur Iskhodzhanov2fca8022013-05-08 08:09:21 +000037 /// involves virtual base classes, this holds the declaration of the last
38 /// virtual base in this path (i.e. closest to the base class).
Peter Collingbourne24018462011-09-26 01:57:12 +000039 const CXXRecordDecl *VirtualBase;
40
41 /// NonVirtualOffset - The offset from the derived class to the base class.
42 /// (Or the offset from the virtual base class to the base class, if the
43 /// path from the derived class to the base class involves a virtual base
44 /// class.
45 CharUnits NonVirtualOffset;
46
47 BaseOffset() : DerivedClass(0), VirtualBase(0),
48 NonVirtualOffset(CharUnits::Zero()) { }
49 BaseOffset(const CXXRecordDecl *DerivedClass,
50 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
51 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
52 NonVirtualOffset(NonVirtualOffset) { }
53
54 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
55};
56
57/// FinalOverriders - Contains the final overrider member functions for all
58/// member functions in the base subobjects of a class.
59class FinalOverriders {
60public:
61 /// OverriderInfo - Information about a final overrider.
62 struct OverriderInfo {
63 /// Method - The method decl of the overrider.
64 const CXXMethodDecl *Method;
65
Timur Iskhodzhanov635de282013-07-30 09:46:19 +000066 /// Offset - the base offset of the overrider's parent in the layout class.
Peter Collingbourne24018462011-09-26 01:57:12 +000067 CharUnits Offset;
68
69 OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
70 };
71
72private:
73 /// MostDerivedClass - The most derived class for which the final overriders
74 /// are stored.
75 const CXXRecordDecl *MostDerivedClass;
76
77 /// MostDerivedClassOffset - If we're building final overriders for a
78 /// construction vtable, this holds the offset from the layout class to the
79 /// most derived class.
80 const CharUnits MostDerivedClassOffset;
81
82 /// LayoutClass - The class we're using for layout information. Will be
83 /// different than the most derived class if the final overriders are for a
84 /// construction vtable.
85 const CXXRecordDecl *LayoutClass;
86
87 ASTContext &Context;
88
89 /// MostDerivedClassLayout - the AST record layout of the most derived class.
90 const ASTRecordLayout &MostDerivedClassLayout;
91
92 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
93 /// in a base subobject.
94 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
95
96 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
97 OverriderInfo> OverridersMapTy;
98
99 /// OverridersMap - The final overriders for all virtual member functions of
100 /// all the base subobjects of the most derived class.
101 OverridersMapTy OverridersMap;
102
103 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
104 /// as a record decl and a subobject number) and its offsets in the most
105 /// derived class as well as the layout class.
106 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
107 CharUnits> SubobjectOffsetMapTy;
108
109 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
110
111 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
112 /// given base.
113 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
114 CharUnits OffsetInLayoutClass,
115 SubobjectOffsetMapTy &SubobjectOffsets,
116 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
117 SubobjectCountMapTy &SubobjectCounts);
118
119 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
120
121 /// dump - dump the final overriders for a base subobject, and all its direct
122 /// and indirect base subobjects.
123 void dump(raw_ostream &Out, BaseSubobject Base,
124 VisitedVirtualBasesSetTy& VisitedVirtualBases);
125
126public:
127 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
128 CharUnits MostDerivedClassOffset,
129 const CXXRecordDecl *LayoutClass);
130
131 /// getOverrider - Get the final overrider for the given method declaration in
132 /// the subobject with the given base offset.
133 OverriderInfo getOverrider(const CXXMethodDecl *MD,
134 CharUnits BaseOffset) const {
135 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
136 "Did not find overrider!");
137
138 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
139 }
140
141 /// dump - dump the final overriders.
142 void dump() {
143 VisitedVirtualBasesSetTy VisitedVirtualBases;
144 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
145 VisitedVirtualBases);
146 }
147
148};
149
Peter Collingbourne24018462011-09-26 01:57:12 +0000150FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
151 CharUnits MostDerivedClassOffset,
152 const CXXRecordDecl *LayoutClass)
153 : MostDerivedClass(MostDerivedClass),
154 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
155 Context(MostDerivedClass->getASTContext()),
156 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
157
158 // Compute base offsets.
159 SubobjectOffsetMapTy SubobjectOffsets;
160 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
161 SubobjectCountMapTy SubobjectCounts;
162 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
163 /*IsVirtual=*/false,
164 MostDerivedClassOffset,
165 SubobjectOffsets, SubobjectLayoutClassOffsets,
166 SubobjectCounts);
167
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000168 // Get the final overriders.
Peter Collingbourne24018462011-09-26 01:57:12 +0000169 CXXFinalOverriderMap FinalOverriders;
170 MostDerivedClass->getFinalOverriders(FinalOverriders);
171
172 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
173 E = FinalOverriders.end(); I != E; ++I) {
174 const CXXMethodDecl *MD = I->first;
175 const OverridingMethods& Methods = I->second;
176
177 for (OverridingMethods::const_iterator I = Methods.begin(),
178 E = Methods.end(); I != E; ++I) {
179 unsigned SubobjectNumber = I->first;
180 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
181 SubobjectNumber)) &&
182 "Did not find subobject offset!");
183
184 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
185 SubobjectNumber)];
186
187 assert(I->second.size() == 1 && "Final overrider is not unique!");
188 const UniqueVirtualMethod &Method = I->second.front();
189
190 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
191 assert(SubobjectLayoutClassOffsets.count(
192 std::make_pair(OverriderRD, Method.Subobject))
193 && "Did not find subobject offset!");
194 CharUnits OverriderOffset =
195 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
196 Method.Subobject)];
197
198 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
199 assert(!Overrider.Method && "Overrider should not exist yet!");
200
201 Overrider.Offset = OverriderOffset;
202 Overrider.Method = Method.Method;
203 }
204 }
205
206#if DUMP_OVERRIDERS
207 // And dump them (for now).
208 dump();
209#endif
210}
211
212static BaseOffset ComputeBaseOffset(ASTContext &Context,
213 const CXXRecordDecl *DerivedRD,
214 const CXXBasePath &Path) {
215 CharUnits NonVirtualOffset = CharUnits::Zero();
216
217 unsigned NonVirtualStart = 0;
218 const CXXRecordDecl *VirtualBase = 0;
219
220 // First, look for the virtual base class.
Timur Iskhodzhanov2fca8022013-05-08 08:09:21 +0000221 for (int I = Path.size(), E = 0; I != E; --I) {
222 const CXXBasePathElement &Element = Path[I - 1];
223
Peter Collingbourne24018462011-09-26 01:57:12 +0000224 if (Element.Base->isVirtual()) {
Timur Iskhodzhanov2fca8022013-05-08 08:09:21 +0000225 NonVirtualStart = I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000226 QualType VBaseType = Element.Base->getType();
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000227 VirtualBase = VBaseType->getAsCXXRecordDecl();
Timur Iskhodzhanov2fca8022013-05-08 08:09:21 +0000228 break;
Peter Collingbourne24018462011-09-26 01:57:12 +0000229 }
230 }
231
232 // Now compute the non-virtual offset.
233 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
234 const CXXBasePathElement &Element = Path[I];
235
236 // Check the base class offset.
237 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
238
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000239 const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +0000240
241 NonVirtualOffset += Layout.getBaseClassOffset(Base);
242 }
243
244 // FIXME: This should probably use CharUnits or something. Maybe we should
245 // even change the base offsets in ASTRecordLayout to be specified in
246 // CharUnits.
247 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
248
249}
250
251static BaseOffset ComputeBaseOffset(ASTContext &Context,
252 const CXXRecordDecl *BaseRD,
253 const CXXRecordDecl *DerivedRD) {
254 CXXBasePaths Paths(/*FindAmbiguities=*/false,
255 /*RecordPaths=*/true, /*DetectVirtual=*/false);
Benjamin Kramer922cec22013-02-03 18:55:34 +0000256
257 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbourne24018462011-09-26 01:57:12 +0000258 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbourne24018462011-09-26 01:57:12 +0000259
260 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
261}
262
263static BaseOffset
264ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
265 const CXXMethodDecl *DerivedMD,
266 const CXXMethodDecl *BaseMD) {
267 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
268 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
269
270 // Canonicalize the return types.
271 CanQualType CanDerivedReturnType =
272 Context.getCanonicalType(DerivedFT->getResultType());
273 CanQualType CanBaseReturnType =
274 Context.getCanonicalType(BaseFT->getResultType());
275
276 assert(CanDerivedReturnType->getTypeClass() ==
277 CanBaseReturnType->getTypeClass() &&
278 "Types must have same type class!");
279
280 if (CanDerivedReturnType == CanBaseReturnType) {
281 // No adjustment needed.
282 return BaseOffset();
283 }
284
285 if (isa<ReferenceType>(CanDerivedReturnType)) {
286 CanDerivedReturnType =
287 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
288 CanBaseReturnType =
289 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
290 } else if (isa<PointerType>(CanDerivedReturnType)) {
291 CanDerivedReturnType =
292 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
293 CanBaseReturnType =
294 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
295 } else {
296 llvm_unreachable("Unexpected return type!");
297 }
298
299 // We need to compare unqualified types here; consider
300 // const T *Base::foo();
301 // T *Derived::foo();
302 if (CanDerivedReturnType.getUnqualifiedType() ==
303 CanBaseReturnType.getUnqualifiedType()) {
304 // No adjustment needed.
305 return BaseOffset();
306 }
307
308 const CXXRecordDecl *DerivedRD =
309 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
310
311 const CXXRecordDecl *BaseRD =
312 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
313
314 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
315}
316
317void
318FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
319 CharUnits OffsetInLayoutClass,
320 SubobjectOffsetMapTy &SubobjectOffsets,
321 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
322 SubobjectCountMapTy &SubobjectCounts) {
323 const CXXRecordDecl *RD = Base.getBase();
324
325 unsigned SubobjectNumber = 0;
326 if (!IsVirtual)
327 SubobjectNumber = ++SubobjectCounts[RD];
328
329 // Set up the subobject to offset mapping.
330 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
331 && "Subobject offset already exists!");
332 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
333 && "Subobject offset already exists!");
334
335 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
336 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
337 OffsetInLayoutClass;
338
339 // Traverse our bases.
340 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
341 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000342 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +0000343
344 CharUnits BaseOffset;
345 CharUnits BaseOffsetInLayoutClass;
346 if (I->isVirtual()) {
347 // Check if we've visited this virtual base before.
348 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
349 continue;
350
351 const ASTRecordLayout &LayoutClassLayout =
352 Context.getASTRecordLayout(LayoutClass);
353
354 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
355 BaseOffsetInLayoutClass =
356 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
357 } else {
358 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
359 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
360
361 BaseOffset = Base.getBaseOffset() + Offset;
362 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
363 }
364
365 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
366 I->isVirtual(), BaseOffsetInLayoutClass,
367 SubobjectOffsets, SubobjectLayoutClassOffsets,
368 SubobjectCounts);
369 }
370}
371
372void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
373 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
374 const CXXRecordDecl *RD = Base.getBase();
375 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
376
377 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
378 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000379 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +0000380
381 // Ignore bases that don't have any virtual member functions.
382 if (!BaseDecl->isPolymorphic())
383 continue;
384
385 CharUnits BaseOffset;
386 if (I->isVirtual()) {
387 if (!VisitedVirtualBases.insert(BaseDecl)) {
388 // We've visited this base before.
389 continue;
390 }
391
392 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
393 } else {
394 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
395 }
396
397 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
398 }
399
400 Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
401 Out << Base.getBaseOffset().getQuantity() << ")\n";
402
403 // Now dump the overriders for this base subobject.
404 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
405 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000406 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000407
408 if (!MD->isVirtual())
409 continue;
410
411 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
412
413 Out << " " << MD->getQualifiedNameAsString() << " - (";
414 Out << Overrider.Method->getQualifiedNameAsString();
Timur Iskhodzhanovc65ee8f2013-06-05 06:40:07 +0000415 Out << ", " << Overrider.Offset.getQuantity() << ')';
Peter Collingbourne24018462011-09-26 01:57:12 +0000416
417 BaseOffset Offset;
418 if (!Overrider.Method->isPure())
419 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
420
421 if (!Offset.isEmpty()) {
422 Out << " [ret-adj: ";
423 if (Offset.VirtualBase)
424 Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
425
426 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
427 }
428
429 Out << "\n";
430 }
431}
432
433/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
434struct VCallOffsetMap {
435
436 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
437
438 /// Offsets - Keeps track of methods and their offsets.
439 // FIXME: This should be a real map and not a vector.
440 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
441
442 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
443 /// can share the same vcall offset.
444 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
445 const CXXMethodDecl *RHS);
446
447public:
448 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
449 /// add was successful, or false if there was already a member function with
450 /// the same signature in the map.
451 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
452
453 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
454 /// vtable address point) for the given virtual member function.
455 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
456
457 // empty - Return whether the offset map is empty or not.
458 bool empty() const { return Offsets.empty(); }
459};
460
461static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
462 const CXXMethodDecl *RHS) {
John McCall260a3e42012-03-21 06:57:19 +0000463 const FunctionProtoType *LT =
464 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
465 const FunctionProtoType *RT =
466 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbourne24018462011-09-26 01:57:12 +0000467
468 // Fast-path matches in the canonical types.
469 if (LT == RT) return true;
470
471 // Force the signatures to match. We can't rely on the overrides
472 // list here because there isn't necessarily an inheritance
473 // relationship between the two methods.
John McCall260a3e42012-03-21 06:57:19 +0000474 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Peter Collingbourne24018462011-09-26 01:57:12 +0000475 LT->getNumArgs() != RT->getNumArgs())
476 return false;
477 for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
478 if (LT->getArgType(I) != RT->getArgType(I))
479 return false;
480 return true;
481}
482
483bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
484 const CXXMethodDecl *RHS) {
485 assert(LHS->isVirtual() && "LHS must be virtual!");
486 assert(RHS->isVirtual() && "LHS must be virtual!");
487
488 // A destructor can share a vcall offset with another destructor.
489 if (isa<CXXDestructorDecl>(LHS))
490 return isa<CXXDestructorDecl>(RHS);
491
492 // FIXME: We need to check more things here.
493
494 // The methods must have the same name.
495 DeclarationName LHSName = LHS->getDeclName();
496 DeclarationName RHSName = RHS->getDeclName();
497 if (LHSName != RHSName)
498 return false;
499
500 // And the same signatures.
501 return HasSameVirtualSignature(LHS, RHS);
502}
503
504bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
505 CharUnits OffsetOffset) {
506 // Check if we can reuse an offset.
507 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
508 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
509 return false;
510 }
511
512 // Add the offset.
513 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
514 return true;
515}
516
517CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
518 // Look for an offset.
519 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
520 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
521 return Offsets[I].second;
522 }
523
524 llvm_unreachable("Should always find a vcall offset offset!");
525}
526
527/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
528class VCallAndVBaseOffsetBuilder {
529public:
530 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
531 VBaseOffsetOffsetsMapTy;
532
533private:
534 /// MostDerivedClass - The most derived class for which we're building vcall
535 /// and vbase offsets.
536 const CXXRecordDecl *MostDerivedClass;
537
538 /// LayoutClass - The class we're using for layout information. Will be
539 /// different than the most derived class if we're building a construction
540 /// vtable.
541 const CXXRecordDecl *LayoutClass;
542
543 /// Context - The ASTContext which we will use for layout information.
544 ASTContext &Context;
545
546 /// Components - vcall and vbase offset components
547 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
548 VTableComponentVectorTy Components;
549
550 /// VisitedVirtualBases - Visited virtual bases.
551 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
552
553 /// VCallOffsets - Keeps track of vcall offsets.
554 VCallOffsetMap VCallOffsets;
555
556
557 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
558 /// relative to the address point.
559 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
560
561 /// FinalOverriders - The final overriders of the most derived class.
562 /// (Can be null when we're not building a vtable of the most derived class).
563 const FinalOverriders *Overriders;
564
565 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
566 /// given base subobject.
567 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
568 CharUnits RealBaseOffset);
569
570 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
571 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
572
573 /// AddVBaseOffsets - Add vbase offsets for the given class.
574 void AddVBaseOffsets(const CXXRecordDecl *Base,
575 CharUnits OffsetInLayoutClass);
576
577 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
578 /// chars, relative to the vtable address point.
579 CharUnits getCurrentOffsetOffset() const;
580
581public:
582 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
583 const CXXRecordDecl *LayoutClass,
584 const FinalOverriders *Overriders,
585 BaseSubobject Base, bool BaseIsVirtual,
586 CharUnits OffsetInLayoutClass)
587 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
588 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
589
590 // Add vcall and vbase offsets.
591 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
592 }
593
594 /// Methods for iterating over the components.
595 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
596 const_iterator components_begin() const { return Components.rbegin(); }
597 const_iterator components_end() const { return Components.rend(); }
598
599 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
600 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
601 return VBaseOffsetOffsets;
602 }
603};
604
605void
606VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
607 bool BaseIsVirtual,
608 CharUnits RealBaseOffset) {
609 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
610
611 // Itanium C++ ABI 2.5.2:
612 // ..in classes sharing a virtual table with a primary base class, the vcall
613 // and vbase offsets added by the derived class all come before the vcall
614 // and vbase offsets required by the base class, so that the latter may be
615 // laid out as required by the base class without regard to additions from
616 // the derived class(es).
617
618 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
619 // emit them for the primary base first).
620 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
621 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
622
623 CharUnits PrimaryBaseOffset;
624
625 // Get the base offset of the primary base.
626 if (PrimaryBaseIsVirtual) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000627 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000628 "Primary vbase should have a zero offset!");
629
630 const ASTRecordLayout &MostDerivedClassLayout =
631 Context.getASTRecordLayout(MostDerivedClass);
632
633 PrimaryBaseOffset =
634 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
635 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000636 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000637 "Primary base should have a zero offset!");
638
639 PrimaryBaseOffset = Base.getBaseOffset();
640 }
641
642 AddVCallAndVBaseOffsets(
643 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
644 PrimaryBaseIsVirtual, RealBaseOffset);
645 }
646
647 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
648
649 // We only want to add vcall offsets for virtual bases.
650 if (BaseIsVirtual)
651 AddVCallOffsets(Base, RealBaseOffset);
652}
653
654CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
655 // OffsetIndex is the index of this vcall or vbase offset, relative to the
656 // vtable address point. (We subtract 3 to account for the information just
657 // above the address point, the RTTI info, the offset to top, and the
658 // vcall offset itself).
659 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
660
661 CharUnits PointerWidth =
662 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
663 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
664 return OffsetOffset;
665}
666
667void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
668 CharUnits VBaseOffset) {
669 const CXXRecordDecl *RD = Base.getBase();
670 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
671
672 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
673
674 // Handle the primary base first.
675 // We only want to add vcall offsets if the base is non-virtual; a virtual
676 // primary base will have its vcall and vbase offsets emitted already.
677 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
678 // Get the base offset of the primary base.
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000679 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000680 "Primary base should have a zero offset!");
681
682 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
683 VBaseOffset);
684 }
685
686 // Add the vcall offsets.
687 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
688 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000689 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000690
691 if (!MD->isVirtual())
692 continue;
693
694 CharUnits OffsetOffset = getCurrentOffsetOffset();
695
696 // Don't add a vcall offset if we already have one for this member function
697 // signature.
698 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
699 continue;
700
701 CharUnits Offset = CharUnits::Zero();
702
703 if (Overriders) {
704 // Get the final overrider.
705 FinalOverriders::OverriderInfo Overrider =
706 Overriders->getOverrider(MD, Base.getBaseOffset());
707
708 /// The vcall offset is the offset from the virtual base to the object
709 /// where the function was overridden.
710 Offset = Overrider.Offset - VBaseOffset;
711 }
712
713 Components.push_back(
714 VTableComponent::MakeVCallOffset(Offset));
715 }
716
717 // And iterate over all non-virtual bases (ignoring the primary base).
718 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
719 E = RD->bases_end(); I != E; ++I) {
720
721 if (I->isVirtual())
722 continue;
723
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000724 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +0000725 if (BaseDecl == PrimaryBase)
726 continue;
727
728 // Get the base offset of this base.
729 CharUnits BaseOffset = Base.getBaseOffset() +
730 Layout.getBaseClassOffset(BaseDecl);
731
732 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
733 VBaseOffset);
734 }
735}
736
737void
738VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
739 CharUnits OffsetInLayoutClass) {
740 const ASTRecordLayout &LayoutClassLayout =
741 Context.getASTRecordLayout(LayoutClass);
742
743 // Add vbase offsets.
744 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
745 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +0000746 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +0000747
748 // Check if this is a virtual base that we haven't visited before.
749 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
750 CharUnits Offset =
751 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
752
753 // Add the vbase offset offset.
754 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
755 "vbase offset offset already exists!");
756
757 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
758 VBaseOffsetOffsets.insert(
759 std::make_pair(BaseDecl, VBaseOffsetOffset));
760
761 Components.push_back(
762 VTableComponent::MakeVBaseOffset(Offset));
763 }
764
765 // Check the base class looking for more vbase offsets.
766 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
767 }
768}
769
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +0000770/// ItaniumVTableBuilder - Class for building vtable layout information.
771class ItaniumVTableBuilder {
Peter Collingbourne24018462011-09-26 01:57:12 +0000772public:
773 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
774 /// primary bases.
775 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
776 PrimaryBasesSetVectorTy;
777
778 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
779 VBaseOffsetOffsetsMapTy;
780
781 typedef llvm::DenseMap<BaseSubobject, uint64_t>
782 AddressPointsMapTy;
783
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +0000784 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
785
Peter Collingbourne24018462011-09-26 01:57:12 +0000786private:
787 /// VTables - Global vtable information.
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +0000788 ItaniumVTableContext &VTables;
Peter Collingbourne24018462011-09-26 01:57:12 +0000789
790 /// MostDerivedClass - The most derived class for which we're building this
791 /// vtable.
792 const CXXRecordDecl *MostDerivedClass;
793
794 /// MostDerivedClassOffset - If we're building a construction vtable, this
795 /// holds the offset from the layout class to the most derived class.
796 const CharUnits MostDerivedClassOffset;
797
798 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
799 /// base. (This only makes sense when building a construction vtable).
800 bool MostDerivedClassIsVirtual;
801
802 /// LayoutClass - The class we're using for layout information. Will be
803 /// different than the most derived class if we're building a construction
804 /// vtable.
805 const CXXRecordDecl *LayoutClass;
806
807 /// Context - The ASTContext which we will use for layout information.
808 ASTContext &Context;
809
810 /// FinalOverriders - The final overriders of the most derived class.
811 const FinalOverriders Overriders;
812
813 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
814 /// bases in this vtable.
815 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
816
817 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
818 /// the most derived class.
819 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
820
821 /// Components - The components of the vtable being built.
822 SmallVector<VTableComponent, 64> Components;
823
824 /// AddressPoints - Address points for the vtable being built.
825 AddressPointsMapTy AddressPoints;
826
827 /// MethodInfo - Contains information about a method in a vtable.
828 /// (Used for computing 'this' pointer adjustment thunks.
829 struct MethodInfo {
830 /// BaseOffset - The base offset of this method.
831 const CharUnits BaseOffset;
832
833 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
834 /// method.
835 const CharUnits BaseOffsetInLayoutClass;
836
837 /// VTableIndex - The index in the vtable that this method has.
838 /// (For destructors, this is the index of the complete destructor).
839 const uint64_t VTableIndex;
840
841 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
842 uint64_t VTableIndex)
843 : BaseOffset(BaseOffset),
844 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
845 VTableIndex(VTableIndex) { }
846
847 MethodInfo()
848 : BaseOffset(CharUnits::Zero()),
849 BaseOffsetInLayoutClass(CharUnits::Zero()),
850 VTableIndex(0) { }
851 };
852
853 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
854
855 /// MethodInfoMap - The information for all methods in the vtable we're
856 /// currently building.
857 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +0000858
859 /// MethodVTableIndices - Contains the index (relative to the vtable address
860 /// point) where the function pointer for a virtual function is stored.
861 MethodVTableIndicesTy MethodVTableIndices;
862
Peter Collingbourne24018462011-09-26 01:57:12 +0000863 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
864
865 /// VTableThunks - The thunks by vtable index in the vtable currently being
866 /// built.
867 VTableThunksMapTy VTableThunks;
868
869 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
870 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
871
872 /// Thunks - A map that contains all the thunks needed for all methods in the
873 /// most derived class for which the vtable is currently being built.
874 ThunksMapTy Thunks;
875
876 /// AddThunk - Add a thunk for the given method.
877 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
878
879 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
880 /// part of the vtable we're currently building.
881 void ComputeThisAdjustments();
882
883 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
884
885 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
886 /// some other base.
887 VisitedVirtualBasesSetTy PrimaryVirtualBases;
888
889 /// ComputeReturnAdjustment - Compute the return adjustment given a return
890 /// adjustment base offset.
891 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
892
893 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
894 /// the 'this' pointer from the base subobject to the derived subobject.
895 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
896 BaseSubobject Derived) const;
897
898 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
899 /// given virtual member function, its offset in the layout class and its
900 /// final overrider.
901 ThisAdjustment
902 ComputeThisAdjustment(const CXXMethodDecl *MD,
903 CharUnits BaseOffsetInLayoutClass,
904 FinalOverriders::OverriderInfo Overrider);
905
906 /// AddMethod - Add a single virtual member function to the vtable
907 /// components vector.
908 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
909
910 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
911 /// part of the vtable.
912 ///
913 /// Itanium C++ ABI 2.5.2:
914 ///
915 /// struct A { virtual void f(); };
916 /// struct B : virtual public A { int i; };
917 /// struct C : virtual public A { int j; };
918 /// struct D : public B, public C {};
919 ///
920 /// When B and C are declared, A is a primary base in each case, so although
921 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
922 /// adjustment is required and no thunk is generated. However, inside D
923 /// objects, A is no longer a primary base of C, so if we allowed calls to
924 /// C::f() to use the copy of A's vtable in the C subobject, we would need
925 /// to adjust this from C* to B::A*, which would require a third-party
926 /// thunk. Since we require that a call to C::f() first convert to A*,
927 /// C-in-D's copy of A's vtable is never referenced, so this is not
928 /// necessary.
929 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
930 CharUnits BaseOffsetInLayoutClass,
931 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
932 CharUnits FirstBaseOffsetInLayoutClass) const;
933
934
935 /// AddMethods - Add the methods of this base subobject and all its
936 /// primary bases to the vtable components vector.
937 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
938 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
939 CharUnits FirstBaseOffsetInLayoutClass,
940 PrimaryBasesSetVectorTy &PrimaryBases);
941
942 // LayoutVTable - Layout the vtable for the given base class, including its
943 // secondary vtables and any vtables for virtual bases.
944 void LayoutVTable();
945
946 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
947 /// given base subobject, as well as all its secondary vtables.
948 ///
949 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
950 /// or a direct or indirect base of a virtual base.
951 ///
952 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
953 /// in the layout class.
954 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
955 bool BaseIsMorallyVirtual,
956 bool BaseIsVirtualInLayoutClass,
957 CharUnits OffsetInLayoutClass);
958
959 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
960 /// subobject.
961 ///
962 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
963 /// or a direct or indirect base of a virtual base.
964 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
965 CharUnits OffsetInLayoutClass);
966
967 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
968 /// class hierarchy.
969 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
970 CharUnits OffsetInLayoutClass,
971 VisitedVirtualBasesSetTy &VBases);
972
973 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
974 /// given base (excluding any primary bases).
975 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
976 VisitedVirtualBasesSetTy &VBases);
977
978 /// isBuildingConstructionVTable - Return whether this vtable builder is
979 /// building a construction vtable.
980 bool isBuildingConstructorVTable() const {
981 return MostDerivedClass != LayoutClass;
982 }
983
984public:
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +0000985 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
986 const CXXRecordDecl *MostDerivedClass,
987 CharUnits MostDerivedClassOffset,
988 bool MostDerivedClassIsVirtual,
989 const CXXRecordDecl *LayoutClass)
990 : VTables(VTables), MostDerivedClass(MostDerivedClass),
991 MostDerivedClassOffset(MostDerivedClassOffset),
992 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
993 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
994 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000995 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
Peter Collingbourne24018462011-09-26 01:57:12 +0000996
997 LayoutVTable();
998
David Blaikie4e4d0842012-03-11 07:00:24 +0000999 if (Context.getLangOpts().DumpVTableLayouts)
Peter Collingbourne24018462011-09-26 01:57:12 +00001000 dumpLayout(llvm::errs());
1001 }
1002
1003 uint64_t getNumThunks() const {
1004 return Thunks.size();
1005 }
1006
1007 ThunksMapTy::const_iterator thunks_begin() const {
1008 return Thunks.begin();
1009 }
1010
1011 ThunksMapTy::const_iterator thunks_end() const {
1012 return Thunks.end();
1013 }
1014
1015 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1016 return VBaseOffsetOffsets;
1017 }
1018
1019 const AddressPointsMapTy &getAddressPoints() const {
1020 return AddressPoints;
1021 }
1022
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001023 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1024 return MethodVTableIndices.begin();
1025 }
1026
1027 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1028 return MethodVTableIndices.end();
1029 }
1030
Peter Collingbourne24018462011-09-26 01:57:12 +00001031 /// getNumVTableComponents - Return the number of components in the vtable
1032 /// currently built.
1033 uint64_t getNumVTableComponents() const {
1034 return Components.size();
1035 }
1036
1037 const VTableComponent *vtable_component_begin() const {
1038 return Components.begin();
1039 }
1040
1041 const VTableComponent *vtable_component_end() const {
1042 return Components.end();
1043 }
1044
1045 AddressPointsMapTy::const_iterator address_points_begin() const {
1046 return AddressPoints.begin();
1047 }
1048
1049 AddressPointsMapTy::const_iterator address_points_end() const {
1050 return AddressPoints.end();
1051 }
1052
1053 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1054 return VTableThunks.begin();
1055 }
1056
1057 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1058 return VTableThunks.end();
1059 }
1060
1061 /// dumpLayout - Dump the vtable layout.
1062 void dumpLayout(raw_ostream&);
1063};
1064
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001065void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1066 const ThunkInfo &Thunk) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001067 assert(!isBuildingConstructorVTable() &&
1068 "Can't add thunks for construction vtable");
1069
Craig Topper6b9240e2013-07-05 19:34:19 +00001070 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1071
Peter Collingbourne24018462011-09-26 01:57:12 +00001072 // Check if we have this thunk already.
1073 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1074 ThunksVector.end())
1075 return;
1076
1077 ThunksVector.push_back(Thunk);
1078}
1079
1080typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1081
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001082/// Visit all the methods overridden by the given method recursively,
1083/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1084/// indicating whether to continue the recursion for the given overridden
1085/// method (i.e. returning false stops the iteration).
1086template <class VisitorTy>
1087static void
1088visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001089 assert(MD->isVirtual() && "Method is not virtual!");
1090
1091 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1092 E = MD->end_overridden_methods(); I != E; ++I) {
1093 const CXXMethodDecl *OverriddenMD = *I;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001094 if (!Visitor.visit(OverriddenMD))
1095 continue;
1096 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbourne24018462011-09-26 01:57:12 +00001097 }
1098}
1099
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001100namespace {
1101 struct OverriddenMethodsCollector {
1102 OverriddenMethodsSetTy *Methods;
1103
1104 bool visit(const CXXMethodDecl *MD) {
1105 // Don't recurse on this method if we've already collected it.
1106 return Methods->insert(MD);
1107 }
1108 };
1109}
1110
1111/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1112/// the overridden methods that the function decl overrides.
1113static void
1114ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1115 OverriddenMethodsSetTy& OverriddenMethods) {
1116 OverriddenMethodsCollector Collector = { &OverriddenMethods };
1117 visitAllOverriddenMethods(MD, Collector);
1118}
1119
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001120void ItaniumVTableBuilder::ComputeThisAdjustments() {
Peter Collingbourne24018462011-09-26 01:57:12 +00001121 // Now go through the method info map and see if any of the methods need
1122 // 'this' pointer adjustments.
1123 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1124 E = MethodInfoMap.end(); I != E; ++I) {
1125 const CXXMethodDecl *MD = I->first;
1126 const MethodInfo &MethodInfo = I->second;
1127
1128 // Ignore adjustments for unused function pointers.
1129 uint64_t VTableIndex = MethodInfo.VTableIndex;
1130 if (Components[VTableIndex].getKind() ==
1131 VTableComponent::CK_UnusedFunctionPointer)
1132 continue;
1133
1134 // Get the final overrider for this method.
1135 FinalOverriders::OverriderInfo Overrider =
1136 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1137
1138 // Check if we need an adjustment at all.
1139 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1140 // When a return thunk is needed by a derived class that overrides a
1141 // virtual base, gcc uses a virtual 'this' adjustment as well.
1142 // While the thunk itself might be needed by vtables in subclasses or
1143 // in construction vtables, there doesn't seem to be a reason for using
1144 // the thunk in this vtable. Still, we do so to match gcc.
1145 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1146 continue;
1147 }
1148
1149 ThisAdjustment ThisAdjustment =
1150 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1151
1152 if (ThisAdjustment.isEmpty())
1153 continue;
1154
1155 // Add it.
1156 VTableThunks[VTableIndex].This = ThisAdjustment;
1157
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001158 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001159 // Add an adjustment for the deleting destructor as well.
1160 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1161 }
1162 }
1163
1164 /// Clear the method info map.
1165 MethodInfoMap.clear();
1166
1167 if (isBuildingConstructorVTable()) {
1168 // We don't need to store thunk information for construction vtables.
1169 return;
1170 }
1171
1172 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1173 E = VTableThunks.end(); I != E; ++I) {
1174 const VTableComponent &Component = Components[I->first];
1175 const ThunkInfo &Thunk = I->second;
1176 const CXXMethodDecl *MD;
1177
1178 switch (Component.getKind()) {
1179 default:
1180 llvm_unreachable("Unexpected vtable component kind!");
1181 case VTableComponent::CK_FunctionPointer:
1182 MD = Component.getFunctionDecl();
1183 break;
1184 case VTableComponent::CK_CompleteDtorPointer:
1185 MD = Component.getDestructorDecl();
1186 break;
1187 case VTableComponent::CK_DeletingDtorPointer:
1188 // We've already added the thunk when we saw the complete dtor pointer.
1189 continue;
1190 }
1191
1192 if (MD->getParent() == MostDerivedClass)
1193 AddThunk(MD, Thunk);
1194 }
1195}
1196
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001197ReturnAdjustment
1198ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001199 ReturnAdjustment Adjustment;
1200
1201 if (!Offset.isEmpty()) {
1202 if (Offset.VirtualBase) {
1203 // Get the virtual base offset offset.
1204 if (Offset.DerivedClass == MostDerivedClass) {
1205 // We can get the offset offset directly from our map.
1206 Adjustment.VBaseOffsetOffset =
1207 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1208 } else {
1209 Adjustment.VBaseOffsetOffset =
1210 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1211 Offset.VirtualBase).getQuantity();
1212 }
1213 }
1214
1215 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1216 }
1217
1218 return Adjustment;
1219}
1220
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001221BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1222 BaseSubobject Base, BaseSubobject Derived) const {
Peter Collingbourne24018462011-09-26 01:57:12 +00001223 const CXXRecordDecl *BaseRD = Base.getBase();
1224 const CXXRecordDecl *DerivedRD = Derived.getBase();
1225
1226 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1227 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1228
Benjamin Kramer922cec22013-02-03 18:55:34 +00001229 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbourne24018462011-09-26 01:57:12 +00001230 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbourne24018462011-09-26 01:57:12 +00001231
1232 // We have to go through all the paths, and see which one leads us to the
1233 // right base subobject.
1234 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1235 I != E; ++I) {
1236 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1237
1238 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1239
1240 if (Offset.VirtualBase) {
1241 // If we have a virtual base class, the non-virtual offset is relative
1242 // to the virtual base class offset.
1243 const ASTRecordLayout &LayoutClassLayout =
1244 Context.getASTRecordLayout(LayoutClass);
1245
1246 /// Get the virtual base offset, relative to the most derived class
1247 /// layout.
1248 OffsetToBaseSubobject +=
1249 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1250 } else {
1251 // Otherwise, the non-virtual offset is relative to the derived class
1252 // offset.
1253 OffsetToBaseSubobject += Derived.getBaseOffset();
1254 }
1255
1256 // Check if this path gives us the right base subobject.
1257 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1258 // Since we're going from the base class _to_ the derived class, we'll
1259 // invert the non-virtual offset here.
1260 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1261 return Offset;
1262 }
1263 }
1264
1265 return BaseOffset();
1266}
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001267
1268ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1269 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1270 FinalOverriders::OverriderInfo Overrider) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001271 // Ignore adjustments for pure virtual member functions.
1272 if (Overrider.Method->isPure())
1273 return ThisAdjustment();
1274
1275 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1276 BaseOffsetInLayoutClass);
1277
1278 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1279 Overrider.Offset);
1280
1281 // Compute the adjustment offset.
1282 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1283 OverriderBaseSubobject);
1284 if (Offset.isEmpty())
1285 return ThisAdjustment();
1286
1287 ThisAdjustment Adjustment;
1288
1289 if (Offset.VirtualBase) {
1290 // Get the vcall offset map for this virtual base.
1291 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1292
1293 if (VCallOffsets.empty()) {
1294 // We don't have vcall offsets for this virtual base, go ahead and
1295 // build them.
1296 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1297 /*FinalOverriders=*/0,
1298 BaseSubobject(Offset.VirtualBase,
1299 CharUnits::Zero()),
1300 /*BaseIsVirtual=*/true,
1301 /*OffsetInLayoutClass=*/
1302 CharUnits::Zero());
1303
1304 VCallOffsets = Builder.getVCallOffsets();
1305 }
1306
1307 Adjustment.VCallOffsetOffset =
1308 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1309 }
1310
1311 // Set the non-virtual part of the adjustment.
1312 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1313
1314 return Adjustment;
1315}
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001316
1317void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1318 ReturnAdjustment ReturnAdjustment) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001319 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1320 assert(ReturnAdjustment.isEmpty() &&
1321 "Destructor can't have return adjustment!");
1322
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001323 // Add both the complete destructor and the deleting destructor.
1324 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1325 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbourne24018462011-09-26 01:57:12 +00001326 } else {
1327 // Add the return adjustment if necessary.
1328 if (!ReturnAdjustment.isEmpty())
1329 VTableThunks[Components.size()].Return = ReturnAdjustment;
1330
1331 // Add the function.
1332 Components.push_back(VTableComponent::MakeFunction(MD));
1333 }
1334}
1335
1336/// OverridesIndirectMethodInBase - Return whether the given member function
1337/// overrides any methods in the set of given bases.
1338/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1339/// For example, if we have:
1340///
1341/// struct A { virtual void f(); }
1342/// struct B : A { virtual void f(); }
1343/// struct C : B { virtual void f(); }
1344///
1345/// OverridesIndirectMethodInBase will return true if given C::f as the method
1346/// and { A } as the set of bases.
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001347static bool OverridesIndirectMethodInBases(
1348 const CXXMethodDecl *MD,
1349 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001350 if (Bases.count(MD->getParent()))
1351 return true;
1352
1353 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1354 E = MD->end_overridden_methods(); I != E; ++I) {
1355 const CXXMethodDecl *OverriddenMD = *I;
1356
1357 // Check "indirect overriders".
1358 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1359 return true;
1360 }
1361
1362 return false;
1363}
1364
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001365bool ItaniumVTableBuilder::IsOverriderUsed(
1366 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1367 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1368 CharUnits FirstBaseOffsetInLayoutClass) const {
Peter Collingbourne24018462011-09-26 01:57:12 +00001369 // If the base and the first base in the primary base chain have the same
1370 // offsets, then this overrider will be used.
1371 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1372 return true;
1373
1374 // We know now that Base (or a direct or indirect base of it) is a primary
1375 // base in part of the class hierarchy, but not a primary base in the most
1376 // derived class.
1377
1378 // If the overrider is the first base in the primary base chain, we know
1379 // that the overrider will be used.
1380 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1381 return true;
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001382
1383 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Peter Collingbourne24018462011-09-26 01:57:12 +00001384
1385 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1386 PrimaryBases.insert(RD);
1387
1388 // Now traverse the base chain, starting with the first base, until we find
1389 // the base that is no longer a primary base.
1390 while (true) {
1391 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1392 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1393
1394 if (!PrimaryBase)
1395 break;
1396
1397 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001398 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001399 "Primary base should always be at offset 0!");
1400
1401 const ASTRecordLayout &LayoutClassLayout =
1402 Context.getASTRecordLayout(LayoutClass);
1403
1404 // Now check if this is the primary base that is not a primary base in the
1405 // most derived class.
1406 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1407 FirstBaseOffsetInLayoutClass) {
1408 // We found it, stop walking the chain.
1409 break;
1410 }
1411 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001412 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001413 "Primary base should always be at offset 0!");
1414 }
1415
1416 if (!PrimaryBases.insert(PrimaryBase))
1417 llvm_unreachable("Found a duplicate primary base!");
1418
1419 RD = PrimaryBase;
1420 }
1421
1422 // If the final overrider is an override of one of the primary bases,
1423 // then we know that it will be used.
1424 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1425}
1426
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001427typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1428
Peter Collingbourne24018462011-09-26 01:57:12 +00001429/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1430/// from the nearest base. Returns null if no method was found.
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001431/// The Bases are expected to be sorted in a base-to-derived order.
1432static const CXXMethodDecl *
Peter Collingbourne24018462011-09-26 01:57:12 +00001433FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001434 BasesSetVectorTy &Bases) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001435 OverriddenMethodsSetTy OverriddenMethods;
1436 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1437
1438 for (int I = Bases.size(), E = 0; I != E; --I) {
1439 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1440
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001441 // Now check the overridden methods.
Peter Collingbourne24018462011-09-26 01:57:12 +00001442 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1443 E = OverriddenMethods.end(); I != E; ++I) {
1444 const CXXMethodDecl *OverriddenMD = *I;
1445
1446 // We found our overridden method.
1447 if (OverriddenMD->getParent() == PrimaryBase)
1448 return OverriddenMD;
1449 }
1450 }
1451
1452 return 0;
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001453}
Peter Collingbourne24018462011-09-26 01:57:12 +00001454
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001455void ItaniumVTableBuilder::AddMethods(
1456 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1457 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1458 CharUnits FirstBaseOffsetInLayoutClass,
1459 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001460 // Itanium C++ ABI 2.5.2:
1461 // The order of the virtual function pointers in a virtual table is the
1462 // order of declaration of the corresponding member functions in the class.
1463 //
1464 // There is an entry for any virtual function declared in a class,
1465 // whether it is a new function or overrides a base class function,
1466 // unless it overrides a function from the primary base, and conversion
1467 // between their return types does not require an adjustment.
1468
Peter Collingbourne24018462011-09-26 01:57:12 +00001469 const CXXRecordDecl *RD = Base.getBase();
1470 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1471
1472 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1473 CharUnits PrimaryBaseOffset;
1474 CharUnits PrimaryBaseOffsetInLayoutClass;
1475 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001476 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001477 "Primary vbase should have a zero offset!");
1478
1479 const ASTRecordLayout &MostDerivedClassLayout =
1480 Context.getASTRecordLayout(MostDerivedClass);
1481
1482 PrimaryBaseOffset =
1483 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1484
1485 const ASTRecordLayout &LayoutClassLayout =
1486 Context.getASTRecordLayout(LayoutClass);
1487
1488 PrimaryBaseOffsetInLayoutClass =
1489 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1490 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001491 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001492 "Primary base should have a zero offset!");
1493
1494 PrimaryBaseOffset = Base.getBaseOffset();
1495 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1496 }
1497
1498 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1499 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1500 FirstBaseOffsetInLayoutClass, PrimaryBases);
1501
1502 if (!PrimaryBases.insert(PrimaryBase))
1503 llvm_unreachable("Found a duplicate primary base!");
1504 }
1505
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001506 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1507
1508 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1509 NewVirtualFunctionsTy NewVirtualFunctions;
1510
Peter Collingbourne24018462011-09-26 01:57:12 +00001511 // Now go through all virtual member functions and add them.
1512 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1513 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001514 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +00001515
1516 if (!MD->isVirtual())
1517 continue;
1518
1519 // Get the final overrider.
1520 FinalOverriders::OverriderInfo Overrider =
1521 Overriders.getOverrider(MD, Base.getBaseOffset());
1522
1523 // Check if this virtual member function overrides a method in a primary
1524 // base. If this is the case, and the return type doesn't require adjustment
1525 // then we can just use the member function from the primary base.
1526 if (const CXXMethodDecl *OverriddenMD =
1527 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1528 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1529 OverriddenMD).isEmpty()) {
1530 // Replace the method info of the overridden method with our own
1531 // method.
1532 assert(MethodInfoMap.count(OverriddenMD) &&
1533 "Did not find the overridden method!");
1534 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1535
1536 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1537 OverriddenMethodInfo.VTableIndex);
1538
1539 assert(!MethodInfoMap.count(MD) &&
1540 "Should not have method info for this method yet!");
1541
1542 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1543 MethodInfoMap.erase(OverriddenMD);
1544
1545 // If the overridden method exists in a virtual base class or a direct
1546 // or indirect base class of a virtual base class, we need to emit a
1547 // thunk if we ever have a class hierarchy where the base class is not
1548 // a primary base in the complete object.
1549 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1550 // Compute the this adjustment.
1551 ThisAdjustment ThisAdjustment =
1552 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1553 Overrider);
1554
1555 if (ThisAdjustment.VCallOffsetOffset &&
1556 Overrider.Method->getParent() == MostDerivedClass) {
1557
1558 // There's no return adjustment from OverriddenMD and MD,
1559 // but that doesn't mean there isn't one between MD and
1560 // the final overrider.
1561 BaseOffset ReturnAdjustmentOffset =
1562 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1563 ReturnAdjustment ReturnAdjustment =
1564 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1565
1566 // This is a virtual thunk for the most derived class, add it.
1567 AddThunk(Overrider.Method,
1568 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1569 }
1570 }
1571
1572 continue;
1573 }
1574 }
1575
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001576 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1577 if (MD->isImplicit()) {
1578 // Itanium C++ ABI 2.5.2:
1579 // If a class has an implicitly-defined virtual destructor,
1580 // its entries come after the declared virtual function pointers.
1581
1582 assert(!ImplicitVirtualDtor &&
1583 "Did already see an implicit virtual dtor!");
1584 ImplicitVirtualDtor = DD;
1585 continue;
1586 }
1587 }
1588
1589 NewVirtualFunctions.push_back(MD);
1590 }
1591
1592 if (ImplicitVirtualDtor)
1593 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1594
1595 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1596 E = NewVirtualFunctions.end(); I != E; ++I) {
1597 const CXXMethodDecl *MD = *I;
1598
1599 // Get the final overrider.
1600 FinalOverriders::OverriderInfo Overrider =
1601 Overriders.getOverrider(MD, Base.getBaseOffset());
1602
Peter Collingbourne24018462011-09-26 01:57:12 +00001603 // Insert the method info for this method.
1604 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1605 Components.size());
1606
1607 assert(!MethodInfoMap.count(MD) &&
1608 "Should not have method info for this method yet!");
1609 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1610
1611 // Check if this overrider is going to be used.
1612 const CXXMethodDecl *OverriderMD = Overrider.Method;
1613 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1614 FirstBaseInPrimaryBaseChain,
1615 FirstBaseOffsetInLayoutClass)) {
1616 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1617 continue;
1618 }
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001619
Peter Collingbourne24018462011-09-26 01:57:12 +00001620 // Check if this overrider needs a return adjustment.
1621 // We don't want to do this for pure virtual member functions.
1622 BaseOffset ReturnAdjustmentOffset;
1623 if (!OverriderMD->isPure()) {
1624 ReturnAdjustmentOffset =
1625 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1626 }
1627
1628 ReturnAdjustment ReturnAdjustment =
1629 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1630
1631 AddMethod(Overrider.Method, ReturnAdjustment);
1632 }
1633}
1634
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001635void ItaniumVTableBuilder::LayoutVTable() {
Peter Collingbourne24018462011-09-26 01:57:12 +00001636 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1637 CharUnits::Zero()),
1638 /*BaseIsMorallyVirtual=*/false,
1639 MostDerivedClassIsVirtual,
1640 MostDerivedClassOffset);
1641
1642 VisitedVirtualBasesSetTy VBases;
1643
1644 // Determine the primary virtual bases.
1645 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1646 VBases);
1647 VBases.clear();
1648
1649 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1650
1651 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikie4e4d0842012-03-11 07:00:24 +00001652 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbourne24018462011-09-26 01:57:12 +00001653 if (IsAppleKext)
1654 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1655}
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001656
1657void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1658 BaseSubobject Base, bool BaseIsMorallyVirtual,
1659 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001660 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1661
1662 // Add vcall and vbase offsets for this vtable.
1663 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1664 Base, BaseIsVirtualInLayoutClass,
1665 OffsetInLayoutClass);
1666 Components.append(Builder.components_begin(), Builder.components_end());
1667
1668 // Check if we need to add these vcall offsets.
1669 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1670 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1671
1672 if (VCallOffsets.empty())
1673 VCallOffsets = Builder.getVCallOffsets();
1674 }
1675
1676 // If we're laying out the most derived class we want to keep track of the
1677 // virtual base class offset offsets.
1678 if (Base.getBase() == MostDerivedClass)
1679 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1680
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001681 // Add the offset to top.
1682 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1683 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001684
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001685 // Next, add the RTTI.
1686 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001687
Peter Collingbourne24018462011-09-26 01:57:12 +00001688 uint64_t AddressPoint = Components.size();
1689
1690 // Now go through all virtual member functions and add them.
1691 PrimaryBasesSetVectorTy PrimaryBases;
1692 AddMethods(Base, OffsetInLayoutClass,
1693 Base.getBase(), OffsetInLayoutClass,
1694 PrimaryBases);
1695
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001696 const CXXRecordDecl *RD = Base.getBase();
1697 if (RD == MostDerivedClass) {
1698 assert(MethodVTableIndices.empty());
1699 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1700 E = MethodInfoMap.end(); I != E; ++I) {
1701 const CXXMethodDecl *MD = I->first;
1702 const MethodInfo &MI = I->second;
1703 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001704 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1705 = MI.VTableIndex - AddressPoint;
1706 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1707 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001708 } else {
1709 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1710 }
1711 }
1712 }
1713
Peter Collingbourne24018462011-09-26 01:57:12 +00001714 // Compute 'this' pointer adjustments.
1715 ComputeThisAdjustments();
1716
1717 // Add all address points.
Peter Collingbourne24018462011-09-26 01:57:12 +00001718 while (true) {
1719 AddressPoints.insert(std::make_pair(
1720 BaseSubobject(RD, OffsetInLayoutClass),
1721 AddressPoint));
1722
1723 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1724 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1725
1726 if (!PrimaryBase)
1727 break;
1728
1729 if (Layout.isPrimaryBaseVirtual()) {
1730 // Check if this virtual primary base is a primary base in the layout
1731 // class. If it's not, we don't want to add it.
1732 const ASTRecordLayout &LayoutClassLayout =
1733 Context.getASTRecordLayout(LayoutClass);
1734
1735 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1736 OffsetInLayoutClass) {
1737 // We don't want to add this class (or any of its primary bases).
1738 break;
1739 }
1740 }
1741
1742 RD = PrimaryBase;
1743 }
1744
1745 // Layout secondary vtables.
1746 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1747}
1748
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001749void
1750ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1751 bool BaseIsMorallyVirtual,
1752 CharUnits OffsetInLayoutClass) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001753 // Itanium C++ ABI 2.5.2:
1754 // Following the primary virtual table of a derived class are secondary
1755 // virtual tables for each of its proper base classes, except any primary
1756 // base(s) with which it shares its primary virtual table.
1757
1758 const CXXRecordDecl *RD = Base.getBase();
1759 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1760 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1761
1762 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1763 E = RD->bases_end(); I != E; ++I) {
1764 // Ignore virtual bases, we'll emit them later.
1765 if (I->isVirtual())
1766 continue;
1767
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001768 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001769
1770 // Ignore bases that don't have a vtable.
1771 if (!BaseDecl->isDynamicClass())
1772 continue;
1773
1774 if (isBuildingConstructorVTable()) {
1775 // Itanium C++ ABI 2.6.4:
1776 // Some of the base class subobjects may not need construction virtual
1777 // tables, which will therefore not be present in the construction
1778 // virtual table group, even though the subobject virtual tables are
1779 // present in the main virtual table group for the complete object.
1780 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1781 continue;
1782 }
1783
1784 // Get the base offset of this base.
1785 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1786 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1787
1788 CharUnits BaseOffsetInLayoutClass =
1789 OffsetInLayoutClass + RelativeBaseOffset;
1790
1791 // Don't emit a secondary vtable for a primary base. We might however want
1792 // to emit secondary vtables for other bases of this base.
1793 if (BaseDecl == PrimaryBase) {
1794 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1795 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1796 continue;
1797 }
1798
1799 // Layout the primary vtable (and any secondary vtables) for this base.
1800 LayoutPrimaryAndSecondaryVTables(
1801 BaseSubobject(BaseDecl, BaseOffset),
1802 BaseIsMorallyVirtual,
1803 /*BaseIsVirtualInLayoutClass=*/false,
1804 BaseOffsetInLayoutClass);
1805 }
1806}
1807
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001808void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1809 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1810 VisitedVirtualBasesSetTy &VBases) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001811 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1812
1813 // Check if this base has a primary base.
1814 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1815
1816 // Check if it's virtual.
1817 if (Layout.isPrimaryBaseVirtual()) {
1818 bool IsPrimaryVirtualBase = true;
1819
1820 if (isBuildingConstructorVTable()) {
1821 // Check if the base is actually a primary base in the class we use for
1822 // layout.
1823 const ASTRecordLayout &LayoutClassLayout =
1824 Context.getASTRecordLayout(LayoutClass);
1825
1826 CharUnits PrimaryBaseOffsetInLayoutClass =
1827 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1828
1829 // We know that the base is not a primary base in the layout class if
1830 // the base offsets are different.
1831 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1832 IsPrimaryVirtualBase = false;
1833 }
1834
1835 if (IsPrimaryVirtualBase)
1836 PrimaryVirtualBases.insert(PrimaryBase);
1837 }
1838 }
1839
1840 // Traverse bases, looking for more primary virtual bases.
1841 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1842 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001843 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001844
1845 CharUnits BaseOffsetInLayoutClass;
1846
1847 if (I->isVirtual()) {
1848 if (!VBases.insert(BaseDecl))
1849 continue;
1850
1851 const ASTRecordLayout &LayoutClassLayout =
1852 Context.getASTRecordLayout(LayoutClass);
1853
1854 BaseOffsetInLayoutClass =
1855 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1856 } else {
1857 BaseOffsetInLayoutClass =
1858 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1859 }
1860
1861 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1862 }
1863}
1864
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001865void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1866 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001867 // Itanium C++ ABI 2.5.2:
1868 // Then come the virtual base virtual tables, also in inheritance graph
1869 // order, and again excluding primary bases (which share virtual tables with
1870 // the classes for which they are primary).
1871 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1872 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001873 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001874
1875 // Check if this base needs a vtable. (If it's virtual, not a primary base
1876 // of some other class, and we haven't visited it before).
1877 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1878 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1879 const ASTRecordLayout &MostDerivedClassLayout =
1880 Context.getASTRecordLayout(MostDerivedClass);
1881 CharUnits BaseOffset =
1882 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1883
1884 const ASTRecordLayout &LayoutClassLayout =
1885 Context.getASTRecordLayout(LayoutClass);
1886 CharUnits BaseOffsetInLayoutClass =
1887 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1888
1889 LayoutPrimaryAndSecondaryVTables(
1890 BaseSubobject(BaseDecl, BaseOffset),
1891 /*BaseIsMorallyVirtual=*/true,
1892 /*BaseIsVirtualInLayoutClass=*/true,
1893 BaseOffsetInLayoutClass);
1894 }
1895
1896 // We only need to check the base for virtual base vtables if it actually
1897 // has virtual bases.
1898 if (BaseDecl->getNumVBases())
1899 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1900 }
1901}
1902
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00001903struct ItaniumThunkInfoComparator {
1904 bool operator() (const ThunkInfo &LHS, const ThunkInfo &RHS) {
1905 assert(LHS.Method == 0);
1906 assert(RHS.Method == 0);
1907
1908 if (LHS.This != RHS.This)
1909 return LHS.This < RHS.This;
1910
1911 if (LHS.Return != RHS.Return)
1912 return LHS.Return < RHS.Return;
1913
1914 return false;
1915 }
1916};
1917
Peter Collingbourne24018462011-09-26 01:57:12 +00001918/// dumpLayout - Dump the vtable layout.
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001919void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
Timur Iskhodzhanov15a0de92013-06-28 15:42:28 +00001920 // FIXME: write more tests that actually use the dumpLayout output to prevent
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00001921 // ItaniumVTableBuilder regressions.
Peter Collingbourne24018462011-09-26 01:57:12 +00001922
1923 if (isBuildingConstructorVTable()) {
1924 Out << "Construction vtable for ('";
1925 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1926 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1927 Out << LayoutClass->getQualifiedNameAsString();
1928 } else {
1929 Out << "Vtable for '";
1930 Out << MostDerivedClass->getQualifiedNameAsString();
1931 }
1932 Out << "' (" << Components.size() << " entries).\n";
1933
1934 // Iterate through the address points and insert them into a new map where
1935 // they are keyed by the index and not the base object.
1936 // Since an address point can be shared by multiple subobjects, we use an
1937 // STL multimap.
1938 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1939 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1940 E = AddressPoints.end(); I != E; ++I) {
1941 const BaseSubobject& Base = I->first;
1942 uint64_t Index = I->second;
1943
1944 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1945 }
1946
1947 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1948 uint64_t Index = I;
1949
1950 Out << llvm::format("%4d | ", I);
1951
1952 const VTableComponent &Component = Components[I];
1953
1954 // Dump the component.
1955 switch (Component.getKind()) {
1956
1957 case VTableComponent::CK_VCallOffset:
1958 Out << "vcall_offset ("
1959 << Component.getVCallOffset().getQuantity()
1960 << ")";
1961 break;
1962
1963 case VTableComponent::CK_VBaseOffset:
1964 Out << "vbase_offset ("
1965 << Component.getVBaseOffset().getQuantity()
1966 << ")";
1967 break;
1968
1969 case VTableComponent::CK_OffsetToTop:
1970 Out << "offset_to_top ("
1971 << Component.getOffsetToTop().getQuantity()
1972 << ")";
1973 break;
1974
1975 case VTableComponent::CK_RTTI:
1976 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1977 break;
1978
1979 case VTableComponent::CK_FunctionPointer: {
1980 const CXXMethodDecl *MD = Component.getFunctionDecl();
1981
1982 std::string Str =
1983 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1984 MD);
1985 Out << Str;
1986 if (MD->isPure())
1987 Out << " [pure]";
1988
David Blaikied954ab42012-10-16 20:25:33 +00001989 if (MD->isDeleted())
1990 Out << " [deleted]";
1991
Peter Collingbourne24018462011-09-26 01:57:12 +00001992 ThunkInfo Thunk = VTableThunks.lookup(I);
1993 if (!Thunk.isEmpty()) {
1994 // If this function pointer has a return adjustment, dump it.
1995 if (!Thunk.Return.isEmpty()) {
1996 Out << "\n [return adjustment: ";
1997 Out << Thunk.Return.NonVirtual << " non-virtual";
1998
1999 if (Thunk.Return.VBaseOffsetOffset) {
2000 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2001 Out << " vbase offset offset";
2002 }
2003
2004 Out << ']';
2005 }
2006
2007 // If this function pointer has a 'this' pointer adjustment, dump it.
2008 if (!Thunk.This.isEmpty()) {
2009 Out << "\n [this adjustment: ";
2010 Out << Thunk.This.NonVirtual << " non-virtual";
2011
2012 if (Thunk.This.VCallOffsetOffset) {
2013 Out << ", " << Thunk.This.VCallOffsetOffset;
2014 Out << " vcall offset offset";
2015 }
2016
2017 Out << ']';
2018 }
2019 }
2020
2021 break;
2022 }
2023
2024 case VTableComponent::CK_CompleteDtorPointer:
2025 case VTableComponent::CK_DeletingDtorPointer: {
2026 bool IsComplete =
2027 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2028
2029 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2030
2031 Out << DD->getQualifiedNameAsString();
2032 if (IsComplete)
2033 Out << "() [complete]";
2034 else
2035 Out << "() [deleting]";
2036
2037 if (DD->isPure())
2038 Out << " [pure]";
2039
2040 ThunkInfo Thunk = VTableThunks.lookup(I);
2041 if (!Thunk.isEmpty()) {
2042 // If this destructor has a 'this' pointer adjustment, dump it.
2043 if (!Thunk.This.isEmpty()) {
2044 Out << "\n [this adjustment: ";
2045 Out << Thunk.This.NonVirtual << " non-virtual";
2046
2047 if (Thunk.This.VCallOffsetOffset) {
2048 Out << ", " << Thunk.This.VCallOffsetOffset;
2049 Out << " vcall offset offset";
2050 }
2051
2052 Out << ']';
2053 }
2054 }
2055
2056 break;
2057 }
2058
2059 case VTableComponent::CK_UnusedFunctionPointer: {
2060 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2061
2062 std::string Str =
2063 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2064 MD);
2065 Out << "[unused] " << Str;
2066 if (MD->isPure())
2067 Out << " [pure]";
2068 }
2069
2070 }
2071
2072 Out << '\n';
2073
2074 // Dump the next address point.
2075 uint64_t NextIndex = Index + 1;
2076 if (AddressPointsByIndex.count(NextIndex)) {
2077 if (AddressPointsByIndex.count(NextIndex) == 1) {
2078 const BaseSubobject &Base =
2079 AddressPointsByIndex.find(NextIndex)->second;
2080
2081 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
2082 Out << ", " << Base.getBaseOffset().getQuantity();
2083 Out << ") vtable address --\n";
2084 } else {
2085 CharUnits BaseOffset =
2086 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2087
2088 // We store the class names in a set to get a stable order.
2089 std::set<std::string> ClassNames;
2090 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2091 AddressPointsByIndex.lower_bound(NextIndex), E =
2092 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2093 assert(I->second.getBaseOffset() == BaseOffset &&
2094 "Invalid base offset!");
2095 const CXXRecordDecl *RD = I->second.getBase();
2096 ClassNames.insert(RD->getQualifiedNameAsString());
2097 }
2098
2099 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2100 E = ClassNames.end(); I != E; ++I) {
2101 Out << " -- (" << *I;
2102 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2103 }
2104 }
2105 }
2106 }
2107
2108 Out << '\n';
2109
2110 if (isBuildingConstructorVTable())
2111 return;
2112
2113 if (MostDerivedClass->getNumVBases()) {
2114 // We store the virtual base class names and their offsets in a map to get
2115 // a stable order.
2116
2117 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2118 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2119 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2120 std::string ClassName = I->first->getQualifiedNameAsString();
2121 CharUnits OffsetOffset = I->second;
2122 ClassNamesAndOffsets.insert(
2123 std::make_pair(ClassName, OffsetOffset));
2124 }
2125
2126 Out << "Virtual base offset offsets for '";
2127 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2128 Out << ClassNamesAndOffsets.size();
2129 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2130
2131 for (std::map<std::string, CharUnits>::const_iterator I =
2132 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2133 I != E; ++I)
2134 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2135
2136 Out << "\n";
2137 }
2138
2139 if (!Thunks.empty()) {
2140 // We store the method names in a map to get a stable order.
2141 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2142
2143 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2144 I != E; ++I) {
2145 const CXXMethodDecl *MD = I->first;
2146 std::string MethodName =
2147 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2148 MD);
2149
2150 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2151 }
2152
2153 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2154 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2155 I != E; ++I) {
2156 const std::string &MethodName = I->first;
2157 const CXXMethodDecl *MD = I->second;
2158
2159 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002160 std::sort(ThunksVector.begin(), ThunksVector.end(),
2161 ItaniumThunkInfoComparator());
Peter Collingbourne24018462011-09-26 01:57:12 +00002162
2163 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2164 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2165
2166 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2167 const ThunkInfo &Thunk = ThunksVector[I];
2168
2169 Out << llvm::format("%4d | ", I);
2170
2171 // If this function pointer has a return pointer adjustment, dump it.
2172 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov15a0de92013-06-28 15:42:28 +00002173 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbourne24018462011-09-26 01:57:12 +00002174 Out << " non-virtual";
2175 if (Thunk.Return.VBaseOffsetOffset) {
2176 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2177 Out << " vbase offset offset";
2178 }
2179
2180 if (!Thunk.This.isEmpty())
2181 Out << "\n ";
2182 }
2183
2184 // If this function pointer has a 'this' pointer adjustment, dump it.
2185 if (!Thunk.This.isEmpty()) {
2186 Out << "this adjustment: ";
2187 Out << Thunk.This.NonVirtual << " non-virtual";
2188
2189 if (Thunk.This.VCallOffsetOffset) {
2190 Out << ", " << Thunk.This.VCallOffsetOffset;
2191 Out << " vcall offset offset";
2192 }
2193 }
2194
2195 Out << '\n';
2196 }
2197
2198 Out << '\n';
2199 }
2200 }
2201
2202 // Compute the vtable indices for all the member functions.
2203 // Store them in a map keyed by the index so we'll get a sorted table.
2204 std::map<uint64_t, std::string> IndicesMap;
2205
2206 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2207 e = MostDerivedClass->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002208 const CXXMethodDecl *MD = *i;
Peter Collingbourne24018462011-09-26 01:57:12 +00002209
2210 // We only want virtual member functions.
2211 if (!MD->isVirtual())
2212 continue;
2213
2214 std::string MethodName =
2215 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2216 MD);
2217
2218 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002219 GlobalDecl GD(DD, Dtor_Complete);
2220 assert(MethodVTableIndices.count(GD));
2221 uint64_t VTableIndex = MethodVTableIndices[GD];
2222 IndicesMap[VTableIndex] = MethodName + " [complete]";
2223 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Peter Collingbourne24018462011-09-26 01:57:12 +00002224 } else {
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002225 assert(MethodVTableIndices.count(MD));
2226 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbourne24018462011-09-26 01:57:12 +00002227 }
2228 }
2229
2230 // Print the vtable indices for all the member functions.
2231 if (!IndicesMap.empty()) {
2232 Out << "VTable indices for '";
2233 Out << MostDerivedClass->getQualifiedNameAsString();
2234 Out << "' (" << IndicesMap.size() << " entries).\n";
2235
2236 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2237 E = IndicesMap.end(); I != E; ++I) {
2238 uint64_t VTableIndex = I->first;
2239 const std::string &MethodName = I->second;
2240
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002241 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer79a55012012-03-10 02:06:27 +00002242 << '\n';
Peter Collingbourne24018462011-09-26 01:57:12 +00002243 }
2244 }
2245
2246 Out << '\n';
2247}
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002248
2249struct VTableThunksComparator {
2250 bool operator()(const VTableLayout::VTableThunkTy &LHS,
2251 const VTableLayout::VTableThunkTy &RHS) {
2252 if (LHS.first == RHS.first) {
2253 assert(LHS.second == RHS.second &&
2254 "Different thunks should have unique indices!");
2255 }
2256 return LHS.first < RHS.first;
2257 }
2258};
Peter Collingbourne24018462011-09-26 01:57:12 +00002259}
2260
2261VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2262 const VTableComponent *VTableComponents,
2263 uint64_t NumVTableThunks,
2264 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002265 const AddressPointsMapTy &AddressPoints,
2266 bool IsMicrosoftABI)
Peter Collingbourne24018462011-09-26 01:57:12 +00002267 : NumVTableComponents(NumVTableComponents),
2268 VTableComponents(new VTableComponent[NumVTableComponents]),
2269 NumVTableThunks(NumVTableThunks),
2270 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002271 AddressPoints(AddressPoints),
2272 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002273 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002274 this->VTableComponents.get());
2275 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2276 this->VTableThunks.get());
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002277 std::sort(this->VTableThunks.get(),
2278 this->VTableThunks.get() + NumVTableThunks,
2279 VTableThunksComparator());
Peter Collingbourne24018462011-09-26 01:57:12 +00002280}
2281
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002282VTableLayout::~VTableLayout() { }
Peter Collingbourne24018462011-09-26 01:57:12 +00002283
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00002284ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
Eli Friedman0a598fd2013-06-27 20:48:08 +00002285 : IsMicrosoftABI(Context.getTargetInfo().getCXXABI().isMicrosoft()) {
John McCallb8b2c9d2013-01-25 22:30:49 +00002286}
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002287
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00002288ItaniumVTableContext::~ItaniumVTableContext() {
Peter Collingbourne24018462011-09-26 01:57:12 +00002289 llvm::DeleteContainerSeconds(VTableLayouts);
2290}
2291
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00002292uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002293 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2294 if (I != MethodVTableIndices.end())
2295 return I->second;
2296
2297 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2298
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002299 computeVTableRelatedInformation(RD);
Peter Collingbourne24018462011-09-26 01:57:12 +00002300
2301 I = MethodVTableIndices.find(GD);
2302 assert(I != MethodVTableIndices.end() && "Did not find index!");
2303 return I->second;
2304}
2305
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00002306CharUnits
2307ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2308 const CXXRecordDecl *VBase) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002309 ClassPairTy ClassPair(RD, VBase);
2310
2311 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2312 VirtualBaseClassOffsetOffsets.find(ClassPair);
2313 if (I != VirtualBaseClassOffsetOffsets.end())
2314 return I->second;
2315
2316 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2317 BaseSubobject(RD, CharUnits::Zero()),
2318 /*BaseIsVirtual=*/false,
2319 /*OffsetInLayoutClass=*/CharUnits::Zero());
2320
2321 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2322 Builder.getVBaseOffsetOffsets().begin(),
2323 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2324 // Insert all types.
2325 ClassPairTy ClassPair(RD, I->first);
2326
2327 VirtualBaseClassOffsetOffsets.insert(
2328 std::make_pair(ClassPair, I->second));
2329 }
2330
2331 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2332 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2333
2334 return I->second;
2335}
2336
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00002337static VTableLayout *CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002338 SmallVector<VTableLayout::VTableThunkTy, 1>
2339 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbourne24018462011-09-26 01:57:12 +00002340
2341 return new VTableLayout(Builder.getNumVTableComponents(),
2342 Builder.vtable_component_begin(),
2343 VTableThunks.size(),
2344 VTableThunks.data(),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002345 Builder.getAddressPoints(),
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002346 /*IsMicrosoftABI=*/false);
Peter Collingbourne24018462011-09-26 01:57:12 +00002347}
2348
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00002349void
2350ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002351 assert(!IsMicrosoftABI && "Shouldn't be called in this ABI!");
2352
Peter Collingbourne24018462011-09-26 01:57:12 +00002353 const VTableLayout *&Entry = VTableLayouts[RD];
2354
2355 // Check if we've computed this information before.
2356 if (Entry)
2357 return;
2358
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00002359 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2360 /*MostDerivedClassIsVirtual=*/0, RD);
Peter Collingbourne24018462011-09-26 01:57:12 +00002361 Entry = CreateVTableLayout(Builder);
2362
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002363 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2364 Builder.vtable_indices_end());
2365
Peter Collingbourne24018462011-09-26 01:57:12 +00002366 // Add the known thunks.
2367 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2368
2369 // If we don't have the vbase information for this class, insert it.
2370 // getVirtualBaseOffsetOffset will compute it separately without computing
2371 // the rest of the vtable related information.
2372 if (!RD->getNumVBases())
2373 return;
2374
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00002375 const CXXRecordDecl *VBase =
2376 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00002377
2378 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2379 return;
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00002380
2381 for (ItaniumVTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator
2382 I = Builder.getVBaseOffsetOffsets().begin(),
2383 E = Builder.getVBaseOffsetOffsets().end();
2384 I != E; ++I) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002385 // Insert all types.
2386 ClassPairTy ClassPair(RD, I->first);
2387
2388 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2389 }
2390}
2391
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +00002392VTableLayout *ItaniumVTableContext::createConstructionVTableLayout(
2393 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2394 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2395 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2396 MostDerivedClassIsVirtual, LayoutClass);
Peter Collingbourne24018462011-09-26 01:57:12 +00002397 return CreateVTableLayout(Builder);
2398}
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002399
2400unsigned clang::GetVBTableIndex(const CXXRecordDecl *Derived,
2401 const CXXRecordDecl *VBase) {
2402 unsigned VBTableIndex = 1; // Start with one to skip the self entry.
2403 for (CXXRecordDecl::base_class_const_iterator I = Derived->vbases_begin(),
2404 E = Derived->vbases_end(); I != E; ++I) {
2405 if (I->getType()->getAsCXXRecordDecl() == VBase)
2406 return VBTableIndex;
2407 ++VBTableIndex;
2408 }
2409 llvm_unreachable("VBase must be a vbase of Derived");
2410}
2411
2412namespace {
2413
2414// Vtables in the Microsoft ABI are different from the Itanium ABI.
2415//
2416// The main differences are:
2417// 1. Separate vftable and vbtable.
2418//
2419// 2. Each subobject with a vfptr gets its own vftable rather than an address
2420// point in a single vtable shared between all the subobjects.
2421// Each vftable is represented by a separate section and virtual calls
2422// must be done using the vftable which has a slot for the function to be
2423// called.
2424//
2425// 3. Virtual method definitions expect their 'this' parameter to point to the
2426// first vfptr whose table provides a compatible overridden method. In many
2427// cases, this permits the original vf-table entry to directly call
2428// the method instead of passing through a thunk.
2429//
2430// A compatible overridden method is one which does not have a non-trivial
2431// covariant-return adjustment.
2432//
2433// The first vfptr is the one with the lowest offset in the complete-object
2434// layout of the defining class, and the method definition will subtract
2435// that constant offset from the parameter value to get the real 'this'
2436// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2437// function defined in a virtual base is overridden in a more derived
2438// virtual base and these bases have a reverse order in the complete
2439// object), the vf-table may require a this-adjustment thunk.
2440//
2441// 4. vftables do not contain new entries for overrides that merely require
2442// this-adjustment. Together with #3, this keeps vf-tables smaller and
2443// eliminates the need for this-adjustment thunks in many cases, at the cost
2444// of often requiring redundant work to adjust the "this" pointer.
2445//
2446// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2447// Vtordisps are emitted into the class layout if a class has
2448// a) a user-defined ctor/dtor
2449// and
2450// b) a method overriding a method in a virtual base.
2451
2452class VFTableBuilder {
2453public:
2454 typedef MicrosoftVFTableContext::MethodVFTableLocation MethodVFTableLocation;
2455
2456 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2457 MethodVFTableLocationsTy;
2458
2459private:
2460 /// Context - The ASTContext which we will use for layout information.
2461 ASTContext &Context;
2462
2463 /// MostDerivedClass - The most derived class for which we're building this
2464 /// vtable.
2465 const CXXRecordDecl *MostDerivedClass;
2466
2467 const ASTRecordLayout &MostDerivedClassLayout;
2468
2469 VFPtrInfo WhichVFPtr;
2470
2471 /// FinalOverriders - The final overriders of the most derived class.
2472 const FinalOverriders Overriders;
2473
2474 /// Components - The components of the vftable being built.
2475 SmallVector<VTableComponent, 64> Components;
2476
2477 MethodVFTableLocationsTy MethodVFTableLocations;
2478
2479 /// MethodInfo - Contains information about a method in a vtable.
2480 /// (Used for computing 'this' pointer adjustment thunks.
2481 struct MethodInfo {
2482 /// VBTableIndex - The nonzero index in the vbtable that
2483 /// this method's base has, or zero.
2484 const uint64_t VBTableIndex;
2485
2486 /// VFTableIndex - The index in the vftable that this method has.
2487 const uint64_t VFTableIndex;
2488
2489 /// Shadowed - Indicates if this vftable slot is shadowed by
2490 /// a slot for a covariant-return override. If so, it shouldn't be printed
2491 /// or used for vcalls in the most derived class.
2492 bool Shadowed;
2493
Timur Iskhodzhanove39c0f32013-10-22 14:50:20 +00002494 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex)
2495 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002496 Shadowed(false) {}
2497
Timur Iskhodzhanove39c0f32013-10-22 14:50:20 +00002498 MethodInfo() : VBTableIndex(0), VFTableIndex(0), Shadowed(false) {}
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002499 };
2500
2501 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2502
2503 /// MethodInfoMap - The information for all methods in the vftable we're
2504 /// currently building.
2505 MethodInfoMapTy MethodInfoMap;
2506
2507 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2508
2509 /// VTableThunks - The thunks by vftable index in the vftable currently being
2510 /// built.
2511 VTableThunksMapTy VTableThunks;
2512
2513 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2514 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2515
2516 /// Thunks - A map that contains all the thunks needed for all methods in the
2517 /// most derived class for which the vftable is currently being built.
2518 ThunksMapTy Thunks;
2519
2520 /// AddThunk - Add a thunk for the given method.
2521 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2522 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2523
2524 // Check if we have this thunk already.
2525 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2526 ThunksVector.end())
2527 return;
2528
2529 ThunksVector.push_back(Thunk);
2530 }
2531
2532 /// ComputeThisOffset - Returns the 'this' argument offset for the given
2533 /// method in the given subobject, relative to the beginning of the
2534 /// MostDerivedClass.
2535 CharUnits ComputeThisOffset(const CXXMethodDecl *MD,
2536 BaseSubobject Base,
2537 FinalOverriders::OverriderInfo Overrider);
2538
2539 /// AddMethod - Add a single virtual member function to the vftable
2540 /// components vector.
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002541 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002542 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002543 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002544 "Destructor can't have return adjustment!");
2545 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2546 } else {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002547 if (!TI.isEmpty())
2548 VTableThunks[Components.size()] = TI;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002549 Components.push_back(VTableComponent::MakeFunction(MD));
2550 }
2551 }
2552
2553 /// AddMethods - Add the methods of this base subobject and the relevant
2554 /// subbases to the vftable we're currently laying out.
2555 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2556 const CXXRecordDecl *LastVBase,
2557 BasesSetVectorTy &VisitedBases);
2558
2559 void LayoutVFTable() {
2560 // FIXME: add support for RTTI when we have proper LLVM support for symbols
2561 // pointing to the middle of a section.
2562
2563 BasesSetVectorTy VisitedBases;
2564 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, 0,
2565 VisitedBases);
2566
2567 assert(MethodVFTableLocations.empty());
2568 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2569 E = MethodInfoMap.end(); I != E; ++I) {
2570 const CXXMethodDecl *MD = I->first;
2571 const MethodInfo &MI = I->second;
2572 // Skip the methods that the MostDerivedClass didn't override
2573 // and the entries shadowed by return adjusting thunks.
2574 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2575 continue;
Timur Iskhodzhanove39c0f32013-10-22 14:50:20 +00002576 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.LastVBase,
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002577 WhichVFPtr.VFPtrOffset, MI.VFTableIndex);
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002578 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2579 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2580 } else {
2581 MethodVFTableLocations[MD] = Loc;
2582 }
2583 }
2584 }
2585
2586 void ErrorUnsupported(StringRef Feature, SourceLocation Location) {
2587 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2588 unsigned DiagID = Diags.getCustomDiagID(
2589 DiagnosticsEngine::Error, "v-table layout for %0 is not supported yet");
2590 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2591 }
2592
2593public:
2594 VFTableBuilder(const CXXRecordDecl *MostDerivedClass, VFPtrInfo Which)
2595 : Context(MostDerivedClass->getASTContext()),
2596 MostDerivedClass(MostDerivedClass),
2597 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
2598 WhichVFPtr(Which),
2599 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2600 LayoutVFTable();
2601
2602 if (Context.getLangOpts().DumpVTableLayouts)
2603 dumpLayout(llvm::errs());
2604 }
2605
2606 uint64_t getNumThunks() const { return Thunks.size(); }
2607
2608 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2609
2610 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2611
2612 MethodVFTableLocationsTy::const_iterator vtable_indices_begin() const {
2613 return MethodVFTableLocations.begin();
2614 }
2615
2616 MethodVFTableLocationsTy::const_iterator vtable_indices_end() const {
2617 return MethodVFTableLocations.end();
2618 }
2619
2620 uint64_t getNumVTableComponents() const { return Components.size(); }
2621
2622 const VTableComponent *vtable_component_begin() const {
2623 return Components.begin();
2624 }
2625
2626 const VTableComponent *vtable_component_end() const {
2627 return Components.end();
2628 }
2629
2630 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2631 return VTableThunks.begin();
2632 }
2633
2634 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2635 return VTableThunks.end();
2636 }
2637
2638 void dumpLayout(raw_ostream &);
2639};
2640
2641/// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2642/// that define the given method.
2643struct InitialOverriddenDefinitionCollector {
2644 BasesSetVectorTy Bases;
2645 OverriddenMethodsSetTy VisitedOverriddenMethods;
2646
2647 bool visit(const CXXMethodDecl *OverriddenMD) {
2648 if (OverriddenMD->size_overridden_methods() == 0)
2649 Bases.insert(OverriddenMD->getParent());
2650 // Don't recurse on this method if we've already collected it.
2651 return VisitedOverriddenMethods.insert(OverriddenMD);
2652 }
2653};
2654
2655static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2656 CXXBasePath &Path, void *BasesSet) {
2657 BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2658 return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2659}
2660
2661CharUnits
2662VFTableBuilder::ComputeThisOffset(const CXXMethodDecl *MD,
2663 BaseSubobject Base,
2664 FinalOverriders::OverriderInfo Overrider) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002665 InitialOverriddenDefinitionCollector Collector;
2666 visitAllOverriddenMethods(MD, Collector);
2667
2668 CXXBasePaths Paths;
2669 Base.getBase()->lookupInBases(BaseInSet, &Collector.Bases, Paths);
2670
2671 // This will hold the smallest this offset among overridees of MD.
2672 // This implies that an offset of a non-virtual base will dominate an offset
2673 // of a virtual base to potentially reduce the number of thunks required
2674 // in the derived classes that inherit this method.
2675 CharUnits Ret;
2676 bool First = true;
2677
2678 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2679 I != E; ++I) {
2680 const CXXBasePath &Path = (*I);
2681 CharUnits ThisOffset = Base.getBaseOffset();
Timur Iskhodzhanov82552742013-10-16 18:24:06 +00002682 bool SeenVBase = false;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002683
2684 // For each path from the overrider to the parents of the overridden methods,
2685 // traverse the path, calculating the this offset in the most derived class.
2686 for (int J = 0, F = Path.size(); J != F; ++J) {
2687 const CXXBasePathElement &Element = Path[J];
2688 QualType CurTy = Element.Base->getType();
2689 const CXXRecordDecl *PrevRD = Element.Class,
2690 *CurRD = CurTy->getAsCXXRecordDecl();
2691 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2692
2693 if (Element.Base->isVirtual()) {
Timur Iskhodzhanov82552742013-10-16 18:24:06 +00002694 SeenVBase = true;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002695 if (Overrider.Method->getParent() == PrevRD) {
2696 // This one's interesting. If the final overrider is in a vbase B of the
2697 // most derived class and it overrides a method of the B's own vbase A,
2698 // it uses A* as "this". In its prologue, it can cast A* to B* with
2699 // a static offset. This offset is used regardless of the actual
2700 // offset of A from B in the most derived class, requiring an
2701 // this-adjusting thunk in the vftable if A and B are laid out
2702 // differently in the most derived class.
2703 ThisOffset += Layout.getVBaseClassOffset(CurRD);
2704 } else {
2705 ThisOffset = MostDerivedClassLayout.getVBaseClassOffset(CurRD);
2706 }
Timur Iskhodzhanov82552742013-10-16 18:24:06 +00002707
2708 // A virtual destructor of a virtual base takes the address of the
2709 // virtual base subobject as the "this" argument.
2710 if (isa<CXXDestructorDecl>(MD))
2711 break;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002712 } else {
2713 ThisOffset += Layout.getBaseClassOffset(CurRD);
2714 }
2715 }
2716
Timur Iskhodzhanov82552742013-10-16 18:24:06 +00002717 // If a "Base" class has at least one non-virtual base with a virtual
2718 // destructor, the "Base" virtual destructor will take the address of the
2719 // "Base" subobject as the "this" argument.
2720 if (!SeenVBase && isa<CXXDestructorDecl>(MD))
2721 return Base.getBaseOffset();
2722
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002723 if (Ret > ThisOffset || First) {
2724 First = false;
2725 Ret = ThisOffset;
2726 }
2727 }
2728
2729 assert(!First && "Method not found in the given subobject?");
2730 return Ret;
2731}
2732
Timur Iskhodzhanovcbf8dde2013-10-06 15:31:37 +00002733static void GroupNewVirtualOverloads(
2734 const CXXRecordDecl *RD,
2735 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2736 // Put the virtual methods into VirtualMethods in the proper order:
2737 // 1) Group overloads by declaration name. New groups are added to the
2738 // vftable in the order of their first declarations in this class
2739 // (including overrides).
2740 // 2) In each group, new overloads appear in the reverse order of declaration.
2741 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2742 SmallVector<MethodGroup, 10> Groups;
2743 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2744 VisitedGroupIndicesTy VisitedGroupIndices;
2745 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2746 E = RD->method_end(); I != E; ++I) {
2747 const CXXMethodDecl *MD = *I;
2748 if (!MD->isVirtual())
2749 continue;
2750
2751 VisitedGroupIndicesTy::iterator J;
2752 bool Inserted;
2753 llvm::tie(J, Inserted) = VisitedGroupIndices.insert(
2754 std::make_pair(MD->getDeclName(), Groups.size()));
2755 if (Inserted)
2756 Groups.push_back(MethodGroup(1, MD));
2757 else
2758 Groups[J->second].push_back(MD);
2759 }
2760
2761 for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2762 VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2763}
2764
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002765void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2766 const CXXRecordDecl *LastVBase,
2767 BasesSetVectorTy &VisitedBases) {
2768 const CXXRecordDecl *RD = Base.getBase();
2769 if (!RD->isPolymorphic())
2770 return;
2771
2772 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2773
2774 // See if this class expands a vftable of the base we look at, which is either
2775 // the one defined by the vfptr base path or the primary base of the current class.
2776 const CXXRecordDecl *NextBase = 0, *NextLastVBase = LastVBase;
2777 CharUnits NextBaseOffset;
2778 if (BaseDepth < WhichVFPtr.PathToBaseWithVFPtr.size()) {
2779 NextBase = WhichVFPtr.PathToBaseWithVFPtr[BaseDepth];
2780 if (Layout.getVBaseOffsetsMap().count(NextBase)) {
2781 NextLastVBase = NextBase;
2782 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2783 } else {
2784 NextBaseOffset =
2785 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2786 }
2787 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2788 assert(!Layout.isPrimaryBaseVirtual() &&
2789 "No primary virtual bases in this ABI");
2790 NextBase = PrimaryBase;
2791 NextBaseOffset = Base.getBaseOffset();
2792 }
2793
2794 if (NextBase) {
2795 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2796 NextLastVBase, VisitedBases);
2797 if (!VisitedBases.insert(NextBase))
2798 llvm_unreachable("Found a duplicate primary base!");
2799 }
2800
Timur Iskhodzhanovcbf8dde2013-10-06 15:31:37 +00002801 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2802 // Put virtual methods in the proper order.
2803 GroupNewVirtualOverloads(RD, VirtualMethods);
2804
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002805 // Now go through all virtual member functions and add them to the current
2806 // vftable. This is done by
2807 // - replacing overridden methods in their existing slots, as long as they
2808 // don't require return adjustment; calculating This adjustment if needed.
2809 // - adding new slots for methods of the current base not present in any
2810 // sub-bases;
2811 // - adding new slots for methods that require Return adjustment.
2812 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Timur Iskhodzhanovcbf8dde2013-10-06 15:31:37 +00002813 for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
2814 const CXXMethodDecl *MD = VirtualMethods[I];
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002815
2816 FinalOverriders::OverriderInfo Overrider =
2817 Overriders.getOverrider(MD, Base.getBaseOffset());
2818 ThisAdjustment ThisAdjustmentOffset;
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002819 bool ForceThunk = false;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002820
2821 // Check if this virtual member function overrides
2822 // a method in one of the visited bases.
2823 if (const CXXMethodDecl *OverriddenMD =
Timur Iskhodzhanovd647efb2013-10-29 14:13:45 +00002824 FindNearestOverriddenMethod(MD, VisitedBases)) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002825 MethodInfoMapTy::iterator OverriddenMDIterator =
2826 MethodInfoMap.find(OverriddenMD);
2827
2828 // If the overridden method went to a different vftable, skip it.
2829 if (OverriddenMDIterator == MethodInfoMap.end())
2830 continue;
2831
2832 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2833
2834 // Create a this-adjusting thunk if needed.
2835 CharUnits TI = ComputeThisOffset(MD, Base, Overrider);
2836 if (TI != WhichVFPtr.VFPtrFullOffset) {
2837 ThisAdjustmentOffset.NonVirtual =
2838 (TI - WhichVFPtr.VFPtrFullOffset).getQuantity();
2839 VTableThunks[OverriddenMethodInfo.VFTableIndex].This =
2840 ThisAdjustmentOffset;
2841 AddThunk(MD, VTableThunks[OverriddenMethodInfo.VFTableIndex]);
2842 }
2843
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002844 if (MD->getResultType() == OverriddenMD->getResultType()) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002845 // No return adjustment needed - just replace the overridden method info
2846 // with the current info.
2847 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
2848 OverriddenMethodInfo.VFTableIndex);
2849 MethodInfoMap.erase(OverriddenMDIterator);
2850
2851 assert(!MethodInfoMap.count(MD) &&
2852 "Should not have method info for this method yet!");
2853 MethodInfoMap.insert(std::make_pair(MD, MI));
2854 continue;
2855 } else {
2856 // In case we need a return adjustment, we'll add a new slot for
2857 // the overrider and put a return-adjusting thunk where the overridden
2858 // method was in the vftable.
2859 // For now, just mark the overriden method as shadowed by a new slot.
2860 OverriddenMethodInfo.Shadowed = true;
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002861 ForceThunk = true;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002862
2863 // Also apply this adjustment to the shadowed slots.
2864 if (!ThisAdjustmentOffset.isEmpty()) {
2865 // FIXME: this is O(N^2), can be O(N).
2866 const CXXMethodDecl *SubOverride = OverriddenMD;
2867 while ((SubOverride =
Timur Iskhodzhanovd647efb2013-10-29 14:13:45 +00002868 FindNearestOverriddenMethod(SubOverride, VisitedBases))) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002869 MethodInfoMapTy::iterator SubOverrideIterator =
2870 MethodInfoMap.find(SubOverride);
2871 if (SubOverrideIterator == MethodInfoMap.end())
2872 break;
2873 MethodInfo &SubOverrideMI = SubOverrideIterator->second;
2874 assert(SubOverrideMI.Shadowed);
2875 VTableThunks[SubOverrideMI.VFTableIndex].This =
2876 ThisAdjustmentOffset;
2877 AddThunk(MD, VTableThunks[SubOverrideMI.VFTableIndex]);
2878 }
2879 }
2880 }
2881 } else if (Base.getBaseOffset() != WhichVFPtr.VFPtrFullOffset ||
2882 MD->size_overridden_methods()) {
2883 // Skip methods that don't belong to the vftable of the current class,
2884 // e.g. each method that wasn't seen in any of the visited sub-bases
2885 // but overrides multiple methods of other sub-bases.
2886 continue;
2887 }
2888
2889 // If we got here, MD is a method not seen in any of the sub-bases or
2890 // it requires return adjustment. Insert the method info for this method.
2891 unsigned VBIndex =
2892 LastVBase ? GetVBTableIndex(MostDerivedClass, LastVBase) : 0;
Timur Iskhodzhanove39c0f32013-10-22 14:50:20 +00002893 MethodInfo MI(VBIndex, Components.size());
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002894
2895 assert(!MethodInfoMap.count(MD) &&
2896 "Should not have method info for this method yet!");
2897 MethodInfoMap.insert(std::make_pair(MD, MI));
2898
2899 const CXXMethodDecl *OverriderMD = Overrider.Method;
2900
2901 // Check if this overrider needs a return adjustment.
2902 // We don't want to do this for pure virtual member functions.
2903 BaseOffset ReturnAdjustmentOffset;
2904 ReturnAdjustment ReturnAdjustment;
2905 if (!OverriderMD->isPure()) {
2906 ReturnAdjustmentOffset =
2907 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
2908 }
2909 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002910 ForceThunk = true;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002911 ReturnAdjustment.NonVirtual =
2912 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
2913 if (ReturnAdjustmentOffset.VirtualBase) {
2914 // FIXME: We might want to create a VBIndex alias for VBaseOffsetOffset
2915 // in the ReturnAdjustment struct.
2916 ReturnAdjustment.VBaseOffsetOffset =
2917 GetVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
2918 ReturnAdjustmentOffset.VirtualBase);
2919 }
2920 }
2921
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002922 AddMethod(OverriderMD, ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
2923 ForceThunk ? MD : 0));
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002924 }
2925}
2926
2927void PrintBasePath(const VFPtrInfo::BasePath &Path, raw_ostream &Out) {
2928 for (VFPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
2929 E = Path.rend(); I != E; ++I) {
2930 Out << "'" << (*I)->getQualifiedNameAsString() << "' in ";
2931 }
2932}
2933
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002934struct MicrosoftThunkInfoStableSortComparator {
2935 bool operator() (const ThunkInfo &LHS, const ThunkInfo &RHS) {
2936 if (LHS.This != RHS.This)
2937 return LHS.This < RHS.This;
2938
2939 if (LHS.Return != RHS.Return)
2940 return LHS.Return < RHS.Return;
2941
2942 // Keep different thunks with the same adjustments in the order they
2943 // were put into the vector.
2944 return false;
2945 }
2946};
2947
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002948void VFTableBuilder::dumpLayout(raw_ostream &Out) {
2949 Out << "VFTable for ";
2950 PrintBasePath(WhichVFPtr.PathToBaseWithVFPtr, Out);
2951 Out << "'" << MostDerivedClass->getQualifiedNameAsString();
2952 Out << "' (" << Components.size() << " entries).\n";
2953
2954 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
2955 Out << llvm::format("%4d | ", I);
2956
2957 const VTableComponent &Component = Components[I];
2958
2959 // Dump the component.
2960 switch (Component.getKind()) {
2961 case VTableComponent::CK_RTTI:
2962 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
2963 break;
2964
2965 case VTableComponent::CK_FunctionPointer: {
2966 const CXXMethodDecl *MD = Component.getFunctionDecl();
2967
2968 std::string Str = PredefinedExpr::ComputeName(
2969 PredefinedExpr::PrettyFunctionNoVirtual, MD);
2970 Out << Str;
2971 if (MD->isPure())
2972 Out << " [pure]";
2973
2974 if (MD->isDeleted()) {
2975 ErrorUnsupported("deleted methods", MD->getLocation());
2976 Out << " [deleted]";
2977 }
2978
2979 ThunkInfo Thunk = VTableThunks.lookup(I);
2980 if (!Thunk.isEmpty()) {
2981 // If this function pointer has a return adjustment, dump it.
2982 if (!Thunk.Return.isEmpty()) {
2983 Out << "\n [return adjustment: ";
2984 if (Thunk.Return.VBaseOffsetOffset)
2985 Out << "vbase #" << Thunk.Return.VBaseOffsetOffset << ", ";
2986 Out << Thunk.Return.NonVirtual << " non-virtual]";
2987 }
2988
2989 // If this function pointer has a 'this' pointer adjustment, dump it.
2990 if (!Thunk.This.isEmpty()) {
2991 assert(!Thunk.This.VCallOffsetOffset &&
2992 "No virtual this adjustment in this ABI");
2993 Out << "\n [this adjustment: " << Thunk.This.NonVirtual
2994 << " non-virtual]";
2995 }
2996 }
2997
2998 break;
2999 }
3000
3001 case VTableComponent::CK_DeletingDtorPointer: {
3002 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3003
3004 Out << DD->getQualifiedNameAsString();
3005 Out << "() [scalar deleting]";
3006
3007 if (DD->isPure())
3008 Out << " [pure]";
3009
3010 ThunkInfo Thunk = VTableThunks.lookup(I);
3011 if (!Thunk.isEmpty()) {
3012 assert(Thunk.Return.isEmpty() &&
3013 "No return adjustment needed for destructors!");
3014 // If this destructor has a 'this' pointer adjustment, dump it.
3015 if (!Thunk.This.isEmpty()) {
3016 assert(!Thunk.This.VCallOffsetOffset &&
3017 "No virtual this adjustment in this ABI");
3018 Out << "\n [this adjustment: " << Thunk.This.NonVirtual
3019 << " non-virtual]";
3020 }
3021 }
3022
3023 break;
3024 }
3025
3026 default:
3027 DiagnosticsEngine &Diags = Context.getDiagnostics();
3028 unsigned DiagID = Diags.getCustomDiagID(
3029 DiagnosticsEngine::Error,
3030 "Unexpected vftable component type %0 for component number %1");
3031 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3032 << I << Component.getKind();
3033 }
3034
3035 Out << '\n';
3036 }
3037
3038 Out << '\n';
3039
3040 if (!Thunks.empty()) {
3041 // We store the method names in a map to get a stable order.
3042 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3043
3044 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3045 I != E; ++I) {
3046 const CXXMethodDecl *MD = I->first;
3047 std::string MethodName = PredefinedExpr::ComputeName(
3048 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3049
3050 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3051 }
3052
3053 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3054 I = MethodNamesAndDecls.begin(),
3055 E = MethodNamesAndDecls.end();
3056 I != E; ++I) {
3057 const std::string &MethodName = I->first;
3058 const CXXMethodDecl *MD = I->second;
3059
3060 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00003061 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
3062 MicrosoftThunkInfoStableSortComparator());
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003063
3064 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3065 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3066
3067 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3068 const ThunkInfo &Thunk = ThunksVector[I];
3069
3070 Out << llvm::format("%4d | ", I);
3071
3072 // If this function pointer has a return pointer adjustment, dump it.
3073 if (!Thunk.Return.isEmpty()) {
3074 Out << "return adjustment: ";
3075 if (Thunk.Return.VBaseOffsetOffset)
3076 Out << "vbase #" << Thunk.Return.VBaseOffsetOffset << ", ";
3077 Out << Thunk.Return.NonVirtual << " non-virtual";
3078
3079 if (!Thunk.This.isEmpty())
3080 Out << "\n ";
3081 }
3082
3083 // If this function pointer has a 'this' pointer adjustment, dump it.
3084 if (!Thunk.This.isEmpty()) {
3085 assert(!Thunk.This.VCallOffsetOffset &&
3086 "No virtual this adjustment in this ABI");
3087 Out << "this adjustment: ";
3088 Out << Thunk.This.NonVirtual << " non-virtual";
3089 }
3090
3091 Out << '\n';
3092 }
3093
3094 Out << '\n';
3095 }
3096 }
3097}
3098}
3099
3100static void EnumerateVFPtrs(
3101 ASTContext &Context, const CXXRecordDecl *MostDerivedClass,
3102 const ASTRecordLayout &MostDerivedClassLayout,
3103 BaseSubobject Base, const CXXRecordDecl *LastVBase,
3104 const VFPtrInfo::BasePath &PathFromCompleteClass,
3105 BasesSetVectorTy &VisitedVBases,
3106 MicrosoftVFTableContext::VFPtrListTy &Result) {
3107 const CXXRecordDecl *CurrentClass = Base.getBase();
3108 CharUnits OffsetInCompleteClass = Base.getBaseOffset();
3109 const ASTRecordLayout &CurrentClassLayout =
3110 Context.getASTRecordLayout(CurrentClass);
3111
3112 if (CurrentClassLayout.hasOwnVFPtr()) {
3113 if (LastVBase) {
3114 uint64_t VBIndex = GetVBTableIndex(MostDerivedClass, LastVBase);
3115 assert(VBIndex > 0 && "vbases must have vbindex!");
3116 CharUnits VFPtrOffset =
3117 OffsetInCompleteClass -
3118 MostDerivedClassLayout.getVBaseClassOffset(LastVBase);
3119 Result.push_back(VFPtrInfo(VBIndex, LastVBase, VFPtrOffset,
3120 PathFromCompleteClass, OffsetInCompleteClass));
3121 } else {
3122 Result.push_back(VFPtrInfo(OffsetInCompleteClass, PathFromCompleteClass));
3123 }
3124 }
3125
3126 for (CXXRecordDecl::base_class_const_iterator I = CurrentClass->bases_begin(),
3127 E = CurrentClass->bases_end(); I != E; ++I) {
3128 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
3129
3130 CharUnits NextBaseOffset;
3131 const CXXRecordDecl *NextLastVBase;
3132 if (I->isVirtual()) {
Benjamin Kramer7dcff5b2013-10-14 15:16:10 +00003133 if (!VisitedVBases.insert(BaseDecl))
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003134 continue;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003135 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
3136 NextLastVBase = BaseDecl;
3137 } else {
3138 NextBaseOffset = OffsetInCompleteClass +
3139 CurrentClassLayout.getBaseClassOffset(BaseDecl);
3140 NextLastVBase = LastVBase;
3141 }
3142
3143 VFPtrInfo::BasePath NewPath = PathFromCompleteClass;
3144 NewPath.push_back(BaseDecl);
3145 BaseSubobject NextBase(BaseDecl, NextBaseOffset);
3146
3147 EnumerateVFPtrs(Context, MostDerivedClass, MostDerivedClassLayout, NextBase,
3148 NextLastVBase, NewPath, VisitedVBases, Result);
3149 }
3150}
3151
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00003152/// CalculatePathToMangle - Calculate the subset of records that should be used
3153/// to mangle the vftable for the given vfptr.
3154/// Should only be called if a class has multiple vftables.
3155static void
3156CalculatePathToMangle(const CXXRecordDecl *RD, VFPtrInfo &VFPtr) {
3157 // FIXME: In some rare cases this code produces a slightly incorrect mangling.
3158 // It's very likely that the vbtable mangling code can be adjusted to mangle
3159 // both vftables and vbtables correctly.
3160
3161 VFPtrInfo::BasePath &FullPath = VFPtr.PathToBaseWithVFPtr;
3162 if (FullPath.empty()) {
3163 // Mangle the class's own vftable.
3164 assert(RD->getNumVBases() &&
3165 "Something's wrong: if the most derived "
3166 "class has more than one vftable, it can only have its own "
3167 "vftable if it has vbases");
3168 VFPtr.PathToMangle.push_back(RD);
3169 return;
3170 }
3171
3172 unsigned Begin = 0;
3173
3174 // First, skip all the bases before the vbase.
3175 if (VFPtr.LastVBase) {
3176 while (FullPath[Begin] != VFPtr.LastVBase) {
3177 Begin++;
3178 assert(Begin < FullPath.size());
3179 }
3180 }
3181
3182 // Then, put the rest of the base path in the reverse order.
3183 for (unsigned I = FullPath.size(); I != Begin; --I) {
3184 const CXXRecordDecl *CurBase = FullPath[I - 1],
3185 *ItsBase = (I == 1) ? RD : FullPath[I - 2];
3186 bool BaseIsVirtual = false;
3187 for (CXXRecordDecl::base_class_const_iterator J = ItsBase->bases_begin(),
3188 F = ItsBase->bases_end(); J != F; ++J) {
3189 if (J->getType()->getAsCXXRecordDecl() == CurBase) {
3190 BaseIsVirtual = J->isVirtual();
3191 break;
3192 }
3193 }
3194
3195 // Should skip the current base if it is a non-virtual base with no siblings.
3196 if (BaseIsVirtual || ItsBase->getNumBases() != 1)
3197 VFPtr.PathToMangle.push_back(CurBase);
3198 }
3199}
3200
Benjamin Kramer3b142da2013-08-01 11:08:06 +00003201static void EnumerateVFPtrs(ASTContext &Context, const CXXRecordDecl *ForClass,
3202 MicrosoftVFTableContext::VFPtrListTy &Result) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003203 Result.clear();
3204 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(ForClass);
3205 BasesSetVectorTy VisitedVBases;
3206 EnumerateVFPtrs(Context, ForClass, ClassLayout,
3207 BaseSubobject(ForClass, CharUnits::Zero()), 0,
3208 VFPtrInfo::BasePath(), VisitedVBases, Result);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00003209 if (Result.size() > 1) {
3210 for (unsigned I = 0, E = Result.size(); I != E; ++I)
3211 CalculatePathToMangle(ForClass, Result[I]);
3212 }
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003213}
3214
3215void MicrosoftVFTableContext::computeVTableRelatedInformation(
3216 const CXXRecordDecl *RD) {
3217 assert(RD->isDynamicClass());
3218
3219 // Check if we've computed this information before.
3220 if (VFPtrLocations.count(RD))
3221 return;
3222
3223 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3224
3225 VFPtrListTy &VFPtrs = VFPtrLocations[RD];
3226 EnumerateVFPtrs(Context, RD, VFPtrs);
3227
3228 MethodVFTableLocationsTy NewMethodLocations;
3229 for (VFPtrListTy::iterator I = VFPtrs.begin(), E = VFPtrs.end();
3230 I != E; ++I) {
3231 VFTableBuilder Builder(RD, *I);
3232
3233 VFTableIdTy id(RD, I->VFPtrFullOffset);
3234 assert(VFTableLayouts.count(id) == 0);
3235 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3236 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003237 VFTableLayouts[id] = new VTableLayout(
3238 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3239 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
3240 NewMethodLocations.insert(Builder.vtable_indices_begin(),
3241 Builder.vtable_indices_end());
3242 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3243 }
3244
3245 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3246 NewMethodLocations.end());
3247 if (Context.getLangOpts().DumpVTableLayouts)
3248 dumpMethodLocations(RD, NewMethodLocations, llvm::errs());
3249}
3250
3251void MicrosoftVFTableContext::dumpMethodLocations(
3252 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3253 raw_ostream &Out) {
3254 // Compute the vtable indices for all the member functions.
3255 // Store them in a map keyed by the location so we'll get a sorted table.
3256 std::map<MethodVFTableLocation, std::string> IndicesMap;
3257 bool HasNonzeroOffset = false;
3258
3259 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3260 E = NewMethods.end(); I != E; ++I) {
3261 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3262 assert(MD->isVirtual());
3263
3264 std::string MethodName = PredefinedExpr::ComputeName(
3265 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3266
3267 if (isa<CXXDestructorDecl>(MD)) {
3268 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3269 } else {
3270 IndicesMap[I->second] = MethodName;
3271 }
3272
3273 if (!I->second.VFTableOffset.isZero() || I->second.VBTableIndex != 0)
3274 HasNonzeroOffset = true;
3275 }
3276
3277 // Print the vtable indices for all the member functions.
3278 if (!IndicesMap.empty()) {
3279 Out << "VFTable indices for ";
3280 Out << "'" << RD->getQualifiedNameAsString();
3281 Out << "' (" << IndicesMap.size() << " entries).\n";
3282
3283 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3284 uint64_t LastVBIndex = 0;
3285 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3286 I = IndicesMap.begin(),
3287 E = IndicesMap.end();
3288 I != E; ++I) {
3289 CharUnits VFPtrOffset = I->first.VFTableOffset;
3290 uint64_t VBIndex = I->first.VBTableIndex;
3291 if (HasNonzeroOffset &&
3292 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3293 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3294 Out << " -- accessible via ";
3295 if (VBIndex)
3296 Out << "vbtable index " << VBIndex << ", ";
3297 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3298 LastVFPtrOffset = VFPtrOffset;
3299 LastVBIndex = VBIndex;
3300 }
3301
3302 uint64_t VTableIndex = I->first.Index;
3303 const std::string &MethodName = I->second;
3304 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3305 }
3306 Out << '\n';
3307 }
3308}
3309
3310const MicrosoftVFTableContext::VFPtrListTy &
3311MicrosoftVFTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
3312 computeVTableRelatedInformation(RD);
3313
3314 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
3315 return VFPtrLocations[RD];
3316}
3317
3318const VTableLayout &
3319MicrosoftVFTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3320 CharUnits VFPtrOffset) {
3321 computeVTableRelatedInformation(RD);
3322
3323 VFTableIdTy id(RD, VFPtrOffset);
3324 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3325 return *VFTableLayouts[id];
3326}
3327
3328const MicrosoftVFTableContext::MethodVFTableLocation &
3329MicrosoftVFTableContext::getMethodVFTableLocation(GlobalDecl GD) {
3330 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3331 "Only use this method for virtual methods or dtors");
3332 if (isa<CXXDestructorDecl>(GD.getDecl()))
3333 assert(GD.getDtorType() == Dtor_Deleting);
3334
3335 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3336 if (I != MethodVFTableLocations.end())
3337 return I->second;
3338
3339 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3340
3341 computeVTableRelatedInformation(RD);
3342
3343 I = MethodVFTableLocations.find(GD);
3344 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3345 return I->second;
3346}