blob: fbc5e3dd93a2845386a8c70a21b12f91b9502dcf [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
770/// VTableBuilder - Class for building vtable layout information.
Timur Iskhodzhanov635de282013-07-30 09:46:19 +0000771// FIXME: rename to ItaniumVTableBuilder.
Peter Collingbourne24018462011-09-26 01:57:12 +0000772class VTableBuilder {
773public:
774 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
775 /// primary bases.
776 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
777 PrimaryBasesSetVectorTy;
778
779 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
780 VBaseOffsetOffsetsMapTy;
781
782 typedef llvm::DenseMap<BaseSubobject, uint64_t>
783 AddressPointsMapTy;
784
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +0000785 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
786
Peter Collingbourne24018462011-09-26 01:57:12 +0000787private:
788 /// VTables - Global vtable information.
789 VTableContext &VTables;
790
791 /// MostDerivedClass - The most derived class for which we're building this
792 /// vtable.
793 const CXXRecordDecl *MostDerivedClass;
794
795 /// MostDerivedClassOffset - If we're building a construction vtable, this
796 /// holds the offset from the layout class to the most derived class.
797 const CharUnits MostDerivedClassOffset;
798
799 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
800 /// base. (This only makes sense when building a construction vtable).
801 bool MostDerivedClassIsVirtual;
802
803 /// LayoutClass - The class we're using for layout information. Will be
804 /// different than the most derived class if we're building a construction
805 /// vtable.
806 const CXXRecordDecl *LayoutClass;
807
808 /// Context - The ASTContext which we will use for layout information.
809 ASTContext &Context;
810
811 /// FinalOverriders - The final overriders of the most derived class.
812 const FinalOverriders Overriders;
813
814 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
815 /// bases in this vtable.
816 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
817
818 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
819 /// the most derived class.
820 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
821
822 /// Components - The components of the vtable being built.
823 SmallVector<VTableComponent, 64> Components;
824
825 /// AddressPoints - Address points for the vtable being built.
826 AddressPointsMapTy AddressPoints;
827
828 /// MethodInfo - Contains information about a method in a vtable.
829 /// (Used for computing 'this' pointer adjustment thunks.
830 struct MethodInfo {
831 /// BaseOffset - The base offset of this method.
832 const CharUnits BaseOffset;
833
834 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
835 /// method.
836 const CharUnits BaseOffsetInLayoutClass;
837
838 /// VTableIndex - The index in the vtable that this method has.
839 /// (For destructors, this is the index of the complete destructor).
840 const uint64_t VTableIndex;
841
842 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
843 uint64_t VTableIndex)
844 : BaseOffset(BaseOffset),
845 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
846 VTableIndex(VTableIndex) { }
847
848 MethodInfo()
849 : BaseOffset(CharUnits::Zero()),
850 BaseOffsetInLayoutClass(CharUnits::Zero()),
851 VTableIndex(0) { }
852 };
853
854 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
855
856 /// MethodInfoMap - The information for all methods in the vtable we're
857 /// currently building.
858 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +0000859
860 /// MethodVTableIndices - Contains the index (relative to the vtable address
861 /// point) where the function pointer for a virtual function is stored.
862 MethodVTableIndicesTy MethodVTableIndices;
863
Peter Collingbourne24018462011-09-26 01:57:12 +0000864 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
865
866 /// VTableThunks - The thunks by vtable index in the vtable currently being
867 /// built.
868 VTableThunksMapTy VTableThunks;
869
870 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
871 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
872
873 /// Thunks - A map that contains all the thunks needed for all methods in the
874 /// most derived class for which the vtable is currently being built.
875 ThunksMapTy Thunks;
876
877 /// AddThunk - Add a thunk for the given method.
878 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
879
880 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
881 /// part of the vtable we're currently building.
882 void ComputeThisAdjustments();
883
884 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
885
886 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
887 /// some other base.
888 VisitedVirtualBasesSetTy PrimaryVirtualBases;
889
890 /// ComputeReturnAdjustment - Compute the return adjustment given a return
891 /// adjustment base offset.
892 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
893
894 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
895 /// the 'this' pointer from the base subobject to the derived subobject.
896 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
897 BaseSubobject Derived) const;
898
899 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
900 /// given virtual member function, its offset in the layout class and its
901 /// final overrider.
902 ThisAdjustment
903 ComputeThisAdjustment(const CXXMethodDecl *MD,
904 CharUnits BaseOffsetInLayoutClass,
905 FinalOverriders::OverriderInfo Overrider);
906
907 /// AddMethod - Add a single virtual member function to the vtable
908 /// components vector.
909 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
910
911 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
912 /// part of the vtable.
913 ///
914 /// Itanium C++ ABI 2.5.2:
915 ///
916 /// struct A { virtual void f(); };
917 /// struct B : virtual public A { int i; };
918 /// struct C : virtual public A { int j; };
919 /// struct D : public B, public C {};
920 ///
921 /// When B and C are declared, A is a primary base in each case, so although
922 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
923 /// adjustment is required and no thunk is generated. However, inside D
924 /// objects, A is no longer a primary base of C, so if we allowed calls to
925 /// C::f() to use the copy of A's vtable in the C subobject, we would need
926 /// to adjust this from C* to B::A*, which would require a third-party
927 /// thunk. Since we require that a call to C::f() first convert to A*,
928 /// C-in-D's copy of A's vtable is never referenced, so this is not
929 /// necessary.
930 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
931 CharUnits BaseOffsetInLayoutClass,
932 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
933 CharUnits FirstBaseOffsetInLayoutClass) const;
934
935
936 /// AddMethods - Add the methods of this base subobject and all its
937 /// primary bases to the vtable components vector.
938 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
939 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
940 CharUnits FirstBaseOffsetInLayoutClass,
941 PrimaryBasesSetVectorTy &PrimaryBases);
942
943 // LayoutVTable - Layout the vtable for the given base class, including its
944 // secondary vtables and any vtables for virtual bases.
945 void LayoutVTable();
946
947 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
948 /// given base subobject, as well as all its secondary vtables.
949 ///
950 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
951 /// or a direct or indirect base of a virtual base.
952 ///
953 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
954 /// in the layout class.
955 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
956 bool BaseIsMorallyVirtual,
957 bool BaseIsVirtualInLayoutClass,
958 CharUnits OffsetInLayoutClass);
959
960 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
961 /// subobject.
962 ///
963 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
964 /// or a direct or indirect base of a virtual base.
965 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
966 CharUnits OffsetInLayoutClass);
967
968 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
969 /// class hierarchy.
970 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
971 CharUnits OffsetInLayoutClass,
972 VisitedVirtualBasesSetTy &VBases);
973
974 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
975 /// given base (excluding any primary bases).
976 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
977 VisitedVirtualBasesSetTy &VBases);
978
979 /// isBuildingConstructionVTable - Return whether this vtable builder is
980 /// building a construction vtable.
981 bool isBuildingConstructorVTable() const {
982 return MostDerivedClass != LayoutClass;
983 }
984
985public:
986 VTableBuilder(VTableContext &VTables, const CXXRecordDecl *MostDerivedClass,
987 CharUnits MostDerivedClassOffset,
988 bool MostDerivedClassIsVirtual, const
989 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 Iskhodzhanovc3dcfa22013-10-08 19:15:38 +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
1065void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1066 assert(!isBuildingConstructorVTable() &&
1067 "Can't add thunks for construction vtable");
1068
Craig Topper6b9240e2013-07-05 19:34:19 +00001069 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1070
Peter Collingbourne24018462011-09-26 01:57:12 +00001071 // Check if we have this thunk already.
1072 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1073 ThunksVector.end())
1074 return;
1075
1076 ThunksVector.push_back(Thunk);
1077}
1078
1079typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1080
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001081/// Visit all the methods overridden by the given method recursively,
1082/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1083/// indicating whether to continue the recursion for the given overridden
1084/// method (i.e. returning false stops the iteration).
1085template <class VisitorTy>
1086static void
1087visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001088 assert(MD->isVirtual() && "Method is not virtual!");
1089
1090 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1091 E = MD->end_overridden_methods(); I != E; ++I) {
1092 const CXXMethodDecl *OverriddenMD = *I;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001093 if (!Visitor.visit(OverriddenMD))
1094 continue;
1095 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbourne24018462011-09-26 01:57:12 +00001096 }
1097}
1098
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001099namespace {
1100 struct OverriddenMethodsCollector {
1101 OverriddenMethodsSetTy *Methods;
1102
1103 bool visit(const CXXMethodDecl *MD) {
1104 // Don't recurse on this method if we've already collected it.
1105 return Methods->insert(MD);
1106 }
1107 };
1108}
1109
1110/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1111/// the overridden methods that the function decl overrides.
1112static void
1113ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1114 OverriddenMethodsSetTy& OverriddenMethods) {
1115 OverriddenMethodsCollector Collector = { &OverriddenMethods };
1116 visitAllOverriddenMethods(MD, Collector);
1117}
1118
Peter Collingbourne24018462011-09-26 01:57:12 +00001119void VTableBuilder::ComputeThisAdjustments() {
1120 // Now go through the method info map and see if any of the methods need
1121 // 'this' pointer adjustments.
1122 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1123 E = MethodInfoMap.end(); I != E; ++I) {
1124 const CXXMethodDecl *MD = I->first;
1125 const MethodInfo &MethodInfo = I->second;
1126
1127 // Ignore adjustments for unused function pointers.
1128 uint64_t VTableIndex = MethodInfo.VTableIndex;
1129 if (Components[VTableIndex].getKind() ==
1130 VTableComponent::CK_UnusedFunctionPointer)
1131 continue;
1132
1133 // Get the final overrider for this method.
1134 FinalOverriders::OverriderInfo Overrider =
1135 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1136
1137 // Check if we need an adjustment at all.
1138 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1139 // When a return thunk is needed by a derived class that overrides a
1140 // virtual base, gcc uses a virtual 'this' adjustment as well.
1141 // While the thunk itself might be needed by vtables in subclasses or
1142 // in construction vtables, there doesn't seem to be a reason for using
1143 // the thunk in this vtable. Still, we do so to match gcc.
1144 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1145 continue;
1146 }
1147
1148 ThisAdjustment ThisAdjustment =
1149 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1150
1151 if (ThisAdjustment.isEmpty())
1152 continue;
1153
1154 // Add it.
1155 VTableThunks[VTableIndex].This = ThisAdjustment;
1156
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001157 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001158 // Add an adjustment for the deleting destructor as well.
1159 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1160 }
1161 }
1162
1163 /// Clear the method info map.
1164 MethodInfoMap.clear();
1165
1166 if (isBuildingConstructorVTable()) {
1167 // We don't need to store thunk information for construction vtables.
1168 return;
1169 }
1170
1171 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1172 E = VTableThunks.end(); I != E; ++I) {
1173 const VTableComponent &Component = Components[I->first];
1174 const ThunkInfo &Thunk = I->second;
1175 const CXXMethodDecl *MD;
1176
1177 switch (Component.getKind()) {
1178 default:
1179 llvm_unreachable("Unexpected vtable component kind!");
1180 case VTableComponent::CK_FunctionPointer:
1181 MD = Component.getFunctionDecl();
1182 break;
1183 case VTableComponent::CK_CompleteDtorPointer:
1184 MD = Component.getDestructorDecl();
1185 break;
1186 case VTableComponent::CK_DeletingDtorPointer:
1187 // We've already added the thunk when we saw the complete dtor pointer.
1188 continue;
1189 }
1190
1191 if (MD->getParent() == MostDerivedClass)
1192 AddThunk(MD, Thunk);
1193 }
1194}
1195
1196ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1197 ReturnAdjustment Adjustment;
1198
1199 if (!Offset.isEmpty()) {
1200 if (Offset.VirtualBase) {
1201 // Get the virtual base offset offset.
1202 if (Offset.DerivedClass == MostDerivedClass) {
1203 // We can get the offset offset directly from our map.
1204 Adjustment.VBaseOffsetOffset =
1205 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1206 } else {
1207 Adjustment.VBaseOffsetOffset =
1208 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1209 Offset.VirtualBase).getQuantity();
1210 }
1211 }
1212
1213 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1214 }
1215
1216 return Adjustment;
1217}
1218
1219BaseOffset
1220VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1221 BaseSubobject Derived) const {
1222 const CXXRecordDecl *BaseRD = Base.getBase();
1223 const CXXRecordDecl *DerivedRD = Derived.getBase();
1224
1225 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1226 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1227
Benjamin Kramer922cec22013-02-03 18:55:34 +00001228 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbourne24018462011-09-26 01:57:12 +00001229 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbourne24018462011-09-26 01:57:12 +00001230
1231 // We have to go through all the paths, and see which one leads us to the
1232 // right base subobject.
1233 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1234 I != E; ++I) {
1235 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1236
1237 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1238
1239 if (Offset.VirtualBase) {
1240 // If we have a virtual base class, the non-virtual offset is relative
1241 // to the virtual base class offset.
1242 const ASTRecordLayout &LayoutClassLayout =
1243 Context.getASTRecordLayout(LayoutClass);
1244
1245 /// Get the virtual base offset, relative to the most derived class
1246 /// layout.
1247 OffsetToBaseSubobject +=
1248 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1249 } else {
1250 // Otherwise, the non-virtual offset is relative to the derived class
1251 // offset.
1252 OffsetToBaseSubobject += Derived.getBaseOffset();
1253 }
1254
1255 // Check if this path gives us the right base subobject.
1256 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1257 // Since we're going from the base class _to_ the derived class, we'll
1258 // invert the non-virtual offset here.
1259 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1260 return Offset;
1261 }
1262 }
1263
1264 return BaseOffset();
1265}
1266
1267ThisAdjustment
1268VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1269 CharUnits BaseOffsetInLayoutClass,
1270 FinalOverriders::OverriderInfo Overrider) {
1271 // 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}
1316
1317void
1318VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1319 ReturnAdjustment ReturnAdjustment) {
1320 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1321 assert(ReturnAdjustment.isEmpty() &&
1322 "Destructor can't have return adjustment!");
1323
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001324 // Add both the complete destructor and the deleting destructor.
1325 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1326 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbourne24018462011-09-26 01:57:12 +00001327 } else {
1328 // Add the return adjustment if necessary.
1329 if (!ReturnAdjustment.isEmpty())
1330 VTableThunks[Components.size()].Return = ReturnAdjustment;
1331
1332 // Add the function.
1333 Components.push_back(VTableComponent::MakeFunction(MD));
1334 }
1335}
1336
1337/// OverridesIndirectMethodInBase - Return whether the given member function
1338/// overrides any methods in the set of given bases.
1339/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1340/// For example, if we have:
1341///
1342/// struct A { virtual void f(); }
1343/// struct B : A { virtual void f(); }
1344/// struct C : B { virtual void f(); }
1345///
1346/// OverridesIndirectMethodInBase will return true if given C::f as the method
1347/// and { A } as the set of bases.
1348static bool
1349OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1350 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1351 if (Bases.count(MD->getParent()))
1352 return true;
1353
1354 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1355 E = MD->end_overridden_methods(); I != E; ++I) {
1356 const CXXMethodDecl *OverriddenMD = *I;
1357
1358 // Check "indirect overriders".
1359 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1360 return true;
1361 }
1362
1363 return false;
1364}
1365
1366bool
1367VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1368 CharUnits BaseOffsetInLayoutClass,
1369 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1370 CharUnits FirstBaseOffsetInLayoutClass) const {
1371 // If the base and the first base in the primary base chain have the same
1372 // offsets, then this overrider will be used.
1373 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1374 return true;
1375
1376 // We know now that Base (or a direct or indirect base of it) is a primary
1377 // base in part of the class hierarchy, but not a primary base in the most
1378 // derived class.
1379
1380 // If the overrider is the first base in the primary base chain, we know
1381 // that the overrider will be used.
1382 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1383 return true;
1384
1385 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1386
1387 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1388 PrimaryBases.insert(RD);
1389
1390 // Now traverse the base chain, starting with the first base, until we find
1391 // the base that is no longer a primary base.
1392 while (true) {
1393 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1394 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1395
1396 if (!PrimaryBase)
1397 break;
1398
1399 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001400 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001401 "Primary base should always be at offset 0!");
1402
1403 const ASTRecordLayout &LayoutClassLayout =
1404 Context.getASTRecordLayout(LayoutClass);
1405
1406 // Now check if this is the primary base that is not a primary base in the
1407 // most derived class.
1408 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1409 FirstBaseOffsetInLayoutClass) {
1410 // We found it, stop walking the chain.
1411 break;
1412 }
1413 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001414 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001415 "Primary base should always be at offset 0!");
1416 }
1417
1418 if (!PrimaryBases.insert(PrimaryBase))
1419 llvm_unreachable("Found a duplicate primary base!");
1420
1421 RD = PrimaryBase;
1422 }
1423
1424 // If the final overrider is an override of one of the primary bases,
1425 // then we know that it will be used.
1426 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1427}
1428
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001429typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1430
Peter Collingbourne24018462011-09-26 01:57:12 +00001431/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1432/// from the nearest base. Returns null if no method was found.
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001433/// The Bases are expected to be sorted in a base-to-derived order.
1434static const CXXMethodDecl *
Peter Collingbourne24018462011-09-26 01:57:12 +00001435FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001436 BasesSetVectorTy &Bases) {
Peter Collingbourne24018462011-09-26 01:57:12 +00001437 OverriddenMethodsSetTy OverriddenMethods;
1438 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1439
1440 for (int I = Bases.size(), E = 0; I != E; --I) {
1441 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1442
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00001443 // Now check the overridden methods.
Peter Collingbourne24018462011-09-26 01:57:12 +00001444 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1445 E = OverriddenMethods.end(); I != E; ++I) {
1446 const CXXMethodDecl *OverriddenMD = *I;
1447
1448 // We found our overridden method.
1449 if (OverriddenMD->getParent() == PrimaryBase)
1450 return OverriddenMD;
1451 }
1452 }
1453
1454 return 0;
1455}
1456
1457void
1458VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1459 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1460 CharUnits FirstBaseOffsetInLayoutClass,
1461 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001462 // Itanium C++ ABI 2.5.2:
1463 // The order of the virtual function pointers in a virtual table is the
1464 // order of declaration of the corresponding member functions in the class.
1465 //
1466 // There is an entry for any virtual function declared in a class,
1467 // whether it is a new function or overrides a base class function,
1468 // unless it overrides a function from the primary base, and conversion
1469 // between their return types does not require an adjustment.
1470
Peter Collingbourne24018462011-09-26 01:57:12 +00001471 const CXXRecordDecl *RD = Base.getBase();
1472 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1473
1474 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1475 CharUnits PrimaryBaseOffset;
1476 CharUnits PrimaryBaseOffsetInLayoutClass;
1477 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001478 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001479 "Primary vbase should have a zero offset!");
1480
1481 const ASTRecordLayout &MostDerivedClassLayout =
1482 Context.getASTRecordLayout(MostDerivedClass);
1483
1484 PrimaryBaseOffset =
1485 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1486
1487 const ASTRecordLayout &LayoutClassLayout =
1488 Context.getASTRecordLayout(LayoutClass);
1489
1490 PrimaryBaseOffsetInLayoutClass =
1491 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1492 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001493 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001494 "Primary base should have a zero offset!");
1495
1496 PrimaryBaseOffset = Base.getBaseOffset();
1497 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1498 }
1499
1500 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1501 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1502 FirstBaseOffsetInLayoutClass, PrimaryBases);
1503
1504 if (!PrimaryBases.insert(PrimaryBase))
1505 llvm_unreachable("Found a duplicate primary base!");
1506 }
1507
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001508 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1509
1510 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1511 NewVirtualFunctionsTy NewVirtualFunctions;
1512
Peter Collingbourne24018462011-09-26 01:57:12 +00001513 // Now go through all virtual member functions and add them.
1514 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1515 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001516 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +00001517
1518 if (!MD->isVirtual())
1519 continue;
1520
1521 // Get the final overrider.
1522 FinalOverriders::OverriderInfo Overrider =
1523 Overriders.getOverrider(MD, Base.getBaseOffset());
1524
1525 // Check if this virtual member function overrides a method in a primary
1526 // base. If this is the case, and the return type doesn't require adjustment
1527 // then we can just use the member function from the primary base.
1528 if (const CXXMethodDecl *OverriddenMD =
1529 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1530 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1531 OverriddenMD).isEmpty()) {
1532 // Replace the method info of the overridden method with our own
1533 // method.
1534 assert(MethodInfoMap.count(OverriddenMD) &&
1535 "Did not find the overridden method!");
1536 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1537
1538 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1539 OverriddenMethodInfo.VTableIndex);
1540
1541 assert(!MethodInfoMap.count(MD) &&
1542 "Should not have method info for this method yet!");
1543
1544 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1545 MethodInfoMap.erase(OverriddenMD);
1546
1547 // If the overridden method exists in a virtual base class or a direct
1548 // or indirect base class of a virtual base class, we need to emit a
1549 // thunk if we ever have a class hierarchy where the base class is not
1550 // a primary base in the complete object.
1551 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1552 // Compute the this adjustment.
1553 ThisAdjustment ThisAdjustment =
1554 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1555 Overrider);
1556
1557 if (ThisAdjustment.VCallOffsetOffset &&
1558 Overrider.Method->getParent() == MostDerivedClass) {
1559
1560 // There's no return adjustment from OverriddenMD and MD,
1561 // but that doesn't mean there isn't one between MD and
1562 // the final overrider.
1563 BaseOffset ReturnAdjustmentOffset =
1564 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1565 ReturnAdjustment ReturnAdjustment =
1566 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1567
1568 // This is a virtual thunk for the most derived class, add it.
1569 AddThunk(Overrider.Method,
1570 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1571 }
1572 }
1573
1574 continue;
1575 }
1576 }
1577
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001578 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1579 if (MD->isImplicit()) {
1580 // Itanium C++ ABI 2.5.2:
1581 // If a class has an implicitly-defined virtual destructor,
1582 // its entries come after the declared virtual function pointers.
1583
1584 assert(!ImplicitVirtualDtor &&
1585 "Did already see an implicit virtual dtor!");
1586 ImplicitVirtualDtor = DD;
1587 continue;
1588 }
1589 }
1590
1591 NewVirtualFunctions.push_back(MD);
1592 }
1593
1594 if (ImplicitVirtualDtor)
1595 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1596
1597 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1598 E = NewVirtualFunctions.end(); I != E; ++I) {
1599 const CXXMethodDecl *MD = *I;
1600
1601 // Get the final overrider.
1602 FinalOverriders::OverriderInfo Overrider =
1603 Overriders.getOverrider(MD, Base.getBaseOffset());
1604
Peter Collingbourne24018462011-09-26 01:57:12 +00001605 // Insert the method info for this method.
1606 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1607 Components.size());
1608
1609 assert(!MethodInfoMap.count(MD) &&
1610 "Should not have method info for this method yet!");
1611 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1612
1613 // Check if this overrider is going to be used.
1614 const CXXMethodDecl *OverriderMD = Overrider.Method;
1615 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1616 FirstBaseInPrimaryBaseChain,
1617 FirstBaseOffsetInLayoutClass)) {
1618 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1619 continue;
1620 }
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001621
Peter Collingbourne24018462011-09-26 01:57:12 +00001622 // Check if this overrider needs a return adjustment.
1623 // We don't want to do this for pure virtual member functions.
1624 BaseOffset ReturnAdjustmentOffset;
1625 if (!OverriderMD->isPure()) {
1626 ReturnAdjustmentOffset =
1627 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1628 }
1629
1630 ReturnAdjustment ReturnAdjustment =
1631 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1632
1633 AddMethod(Overrider.Method, ReturnAdjustment);
1634 }
1635}
1636
1637void VTableBuilder::LayoutVTable() {
1638 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1639 CharUnits::Zero()),
1640 /*BaseIsMorallyVirtual=*/false,
1641 MostDerivedClassIsVirtual,
1642 MostDerivedClassOffset);
1643
1644 VisitedVirtualBasesSetTy VBases;
1645
1646 // Determine the primary virtual bases.
1647 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1648 VBases);
1649 VBases.clear();
1650
1651 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1652
1653 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikie4e4d0842012-03-11 07:00:24 +00001654 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbourne24018462011-09-26 01:57:12 +00001655 if (IsAppleKext)
1656 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1657}
1658
1659void
1660VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1661 bool BaseIsMorallyVirtual,
1662 bool BaseIsVirtualInLayoutClass,
1663 CharUnits OffsetInLayoutClass) {
1664 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1665
1666 // Add vcall and vbase offsets for this vtable.
1667 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1668 Base, BaseIsVirtualInLayoutClass,
1669 OffsetInLayoutClass);
1670 Components.append(Builder.components_begin(), Builder.components_end());
1671
1672 // Check if we need to add these vcall offsets.
1673 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1674 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1675
1676 if (VCallOffsets.empty())
1677 VCallOffsets = Builder.getVCallOffsets();
1678 }
1679
1680 // If we're laying out the most derived class we want to keep track of the
1681 // virtual base class offset offsets.
1682 if (Base.getBase() == MostDerivedClass)
1683 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1684
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001685 // Add the offset to top.
1686 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1687 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001688
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001689 // Next, add the RTTI.
1690 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001691
Peter Collingbourne24018462011-09-26 01:57:12 +00001692 uint64_t AddressPoint = Components.size();
1693
1694 // Now go through all virtual member functions and add them.
1695 PrimaryBasesSetVectorTy PrimaryBases;
1696 AddMethods(Base, OffsetInLayoutClass,
1697 Base.getBase(), OffsetInLayoutClass,
1698 PrimaryBases);
1699
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001700 const CXXRecordDecl *RD = Base.getBase();
1701 if (RD == MostDerivedClass) {
1702 assert(MethodVTableIndices.empty());
1703 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1704 E = MethodInfoMap.end(); I != E; ++I) {
1705 const CXXMethodDecl *MD = I->first;
1706 const MethodInfo &MI = I->second;
1707 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00001708 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1709 = MI.VTableIndex - AddressPoint;
1710 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1711 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001712 } else {
1713 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1714 }
1715 }
1716 }
1717
Peter Collingbourne24018462011-09-26 01:57:12 +00001718 // Compute 'this' pointer adjustments.
1719 ComputeThisAdjustments();
1720
1721 // Add all address points.
Peter Collingbourne24018462011-09-26 01:57:12 +00001722 while (true) {
1723 AddressPoints.insert(std::make_pair(
1724 BaseSubobject(RD, OffsetInLayoutClass),
1725 AddressPoint));
1726
1727 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1728 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1729
1730 if (!PrimaryBase)
1731 break;
1732
1733 if (Layout.isPrimaryBaseVirtual()) {
1734 // Check if this virtual primary base is a primary base in the layout
1735 // class. If it's not, we don't want to add it.
1736 const ASTRecordLayout &LayoutClassLayout =
1737 Context.getASTRecordLayout(LayoutClass);
1738
1739 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1740 OffsetInLayoutClass) {
1741 // We don't want to add this class (or any of its primary bases).
1742 break;
1743 }
1744 }
1745
1746 RD = PrimaryBase;
1747 }
1748
1749 // Layout secondary vtables.
1750 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1751}
1752
1753void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1754 bool BaseIsMorallyVirtual,
1755 CharUnits OffsetInLayoutClass) {
1756 // Itanium C++ ABI 2.5.2:
1757 // Following the primary virtual table of a derived class are secondary
1758 // virtual tables for each of its proper base classes, except any primary
1759 // base(s) with which it shares its primary virtual table.
1760
1761 const CXXRecordDecl *RD = Base.getBase();
1762 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1763 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1764
1765 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1766 E = RD->bases_end(); I != E; ++I) {
1767 // Ignore virtual bases, we'll emit them later.
1768 if (I->isVirtual())
1769 continue;
1770
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001771 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001772
1773 // Ignore bases that don't have a vtable.
1774 if (!BaseDecl->isDynamicClass())
1775 continue;
1776
1777 if (isBuildingConstructorVTable()) {
1778 // Itanium C++ ABI 2.6.4:
1779 // Some of the base class subobjects may not need construction virtual
1780 // tables, which will therefore not be present in the construction
1781 // virtual table group, even though the subobject virtual tables are
1782 // present in the main virtual table group for the complete object.
1783 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1784 continue;
1785 }
1786
1787 // Get the base offset of this base.
1788 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1789 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1790
1791 CharUnits BaseOffsetInLayoutClass =
1792 OffsetInLayoutClass + RelativeBaseOffset;
1793
1794 // Don't emit a secondary vtable for a primary base. We might however want
1795 // to emit secondary vtables for other bases of this base.
1796 if (BaseDecl == PrimaryBase) {
1797 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1798 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1799 continue;
1800 }
1801
1802 // Layout the primary vtable (and any secondary vtables) for this base.
1803 LayoutPrimaryAndSecondaryVTables(
1804 BaseSubobject(BaseDecl, BaseOffset),
1805 BaseIsMorallyVirtual,
1806 /*BaseIsVirtualInLayoutClass=*/false,
1807 BaseOffsetInLayoutClass);
1808 }
1809}
1810
1811void
1812VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1813 CharUnits OffsetInLayoutClass,
1814 VisitedVirtualBasesSetTy &VBases) {
1815 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1816
1817 // Check if this base has a primary base.
1818 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1819
1820 // Check if it's virtual.
1821 if (Layout.isPrimaryBaseVirtual()) {
1822 bool IsPrimaryVirtualBase = true;
1823
1824 if (isBuildingConstructorVTable()) {
1825 // Check if the base is actually a primary base in the class we use for
1826 // layout.
1827 const ASTRecordLayout &LayoutClassLayout =
1828 Context.getASTRecordLayout(LayoutClass);
1829
1830 CharUnits PrimaryBaseOffsetInLayoutClass =
1831 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1832
1833 // We know that the base is not a primary base in the layout class if
1834 // the base offsets are different.
1835 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1836 IsPrimaryVirtualBase = false;
1837 }
1838
1839 if (IsPrimaryVirtualBase)
1840 PrimaryVirtualBases.insert(PrimaryBase);
1841 }
1842 }
1843
1844 // Traverse bases, looking for more primary virtual bases.
1845 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1846 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001847 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001848
1849 CharUnits BaseOffsetInLayoutClass;
1850
1851 if (I->isVirtual()) {
1852 if (!VBases.insert(BaseDecl))
1853 continue;
1854
1855 const ASTRecordLayout &LayoutClassLayout =
1856 Context.getASTRecordLayout(LayoutClass);
1857
1858 BaseOffsetInLayoutClass =
1859 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1860 } else {
1861 BaseOffsetInLayoutClass =
1862 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1863 }
1864
1865 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1866 }
1867}
1868
1869void
1870VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1871 VisitedVirtualBasesSetTy &VBases) {
1872 // Itanium C++ ABI 2.5.2:
1873 // Then come the virtual base virtual tables, also in inheritance graph
1874 // order, and again excluding primary bases (which share virtual tables with
1875 // the classes for which they are primary).
1876 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1877 E = RD->bases_end(); I != E; ++I) {
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00001878 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00001879
1880 // Check if this base needs a vtable. (If it's virtual, not a primary base
1881 // of some other class, and we haven't visited it before).
1882 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1883 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1884 const ASTRecordLayout &MostDerivedClassLayout =
1885 Context.getASTRecordLayout(MostDerivedClass);
1886 CharUnits BaseOffset =
1887 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1888
1889 const ASTRecordLayout &LayoutClassLayout =
1890 Context.getASTRecordLayout(LayoutClass);
1891 CharUnits BaseOffsetInLayoutClass =
1892 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1893
1894 LayoutPrimaryAndSecondaryVTables(
1895 BaseSubobject(BaseDecl, BaseOffset),
1896 /*BaseIsMorallyVirtual=*/true,
1897 /*BaseIsVirtualInLayoutClass=*/true,
1898 BaseOffsetInLayoutClass);
1899 }
1900
1901 // We only need to check the base for virtual base vtables if it actually
1902 // has virtual bases.
1903 if (BaseDecl->getNumVBases())
1904 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1905 }
1906}
1907
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00001908struct ItaniumThunkInfoComparator {
1909 bool operator() (const ThunkInfo &LHS, const ThunkInfo &RHS) {
1910 assert(LHS.Method == 0);
1911 assert(RHS.Method == 0);
1912
1913 if (LHS.This != RHS.This)
1914 return LHS.This < RHS.This;
1915
1916 if (LHS.Return != RHS.Return)
1917 return LHS.Return < RHS.Return;
1918
1919 llvm_unreachable("Shouldn't observe two equal thunks");
1920 }
1921};
1922
Peter Collingbourne24018462011-09-26 01:57:12 +00001923/// dumpLayout - Dump the vtable layout.
1924void VTableBuilder::dumpLayout(raw_ostream& Out) {
Timur Iskhodzhanov15a0de92013-06-28 15:42:28 +00001925 // FIXME: write more tests that actually use the dumpLayout output to prevent
1926 // VTableBuilder regressions.
Peter Collingbourne24018462011-09-26 01:57:12 +00001927
1928 if (isBuildingConstructorVTable()) {
1929 Out << "Construction vtable for ('";
1930 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1931 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1932 Out << LayoutClass->getQualifiedNameAsString();
1933 } else {
1934 Out << "Vtable for '";
1935 Out << MostDerivedClass->getQualifiedNameAsString();
1936 }
1937 Out << "' (" << Components.size() << " entries).\n";
1938
1939 // Iterate through the address points and insert them into a new map where
1940 // they are keyed by the index and not the base object.
1941 // Since an address point can be shared by multiple subobjects, we use an
1942 // STL multimap.
1943 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1944 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1945 E = AddressPoints.end(); I != E; ++I) {
1946 const BaseSubobject& Base = I->first;
1947 uint64_t Index = I->second;
1948
1949 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1950 }
1951
1952 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1953 uint64_t Index = I;
1954
1955 Out << llvm::format("%4d | ", I);
1956
1957 const VTableComponent &Component = Components[I];
1958
1959 // Dump the component.
1960 switch (Component.getKind()) {
1961
1962 case VTableComponent::CK_VCallOffset:
1963 Out << "vcall_offset ("
1964 << Component.getVCallOffset().getQuantity()
1965 << ")";
1966 break;
1967
1968 case VTableComponent::CK_VBaseOffset:
1969 Out << "vbase_offset ("
1970 << Component.getVBaseOffset().getQuantity()
1971 << ")";
1972 break;
1973
1974 case VTableComponent::CK_OffsetToTop:
1975 Out << "offset_to_top ("
1976 << Component.getOffsetToTop().getQuantity()
1977 << ")";
1978 break;
1979
1980 case VTableComponent::CK_RTTI:
1981 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1982 break;
1983
1984 case VTableComponent::CK_FunctionPointer: {
1985 const CXXMethodDecl *MD = Component.getFunctionDecl();
1986
1987 std::string Str =
1988 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1989 MD);
1990 Out << Str;
1991 if (MD->isPure())
1992 Out << " [pure]";
1993
David Blaikied954ab42012-10-16 20:25:33 +00001994 if (MD->isDeleted())
1995 Out << " [deleted]";
1996
Peter Collingbourne24018462011-09-26 01:57:12 +00001997 ThunkInfo Thunk = VTableThunks.lookup(I);
1998 if (!Thunk.isEmpty()) {
1999 // If this function pointer has a return adjustment, dump it.
2000 if (!Thunk.Return.isEmpty()) {
2001 Out << "\n [return adjustment: ";
2002 Out << Thunk.Return.NonVirtual << " non-virtual";
2003
2004 if (Thunk.Return.VBaseOffsetOffset) {
2005 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2006 Out << " vbase offset offset";
2007 }
2008
2009 Out << ']';
2010 }
2011
2012 // If this function pointer has a 'this' pointer adjustment, dump it.
2013 if (!Thunk.This.isEmpty()) {
2014 Out << "\n [this adjustment: ";
2015 Out << Thunk.This.NonVirtual << " non-virtual";
2016
2017 if (Thunk.This.VCallOffsetOffset) {
2018 Out << ", " << Thunk.This.VCallOffsetOffset;
2019 Out << " vcall offset offset";
2020 }
2021
2022 Out << ']';
2023 }
2024 }
2025
2026 break;
2027 }
2028
2029 case VTableComponent::CK_CompleteDtorPointer:
2030 case VTableComponent::CK_DeletingDtorPointer: {
2031 bool IsComplete =
2032 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2033
2034 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2035
2036 Out << DD->getQualifiedNameAsString();
2037 if (IsComplete)
2038 Out << "() [complete]";
2039 else
2040 Out << "() [deleting]";
2041
2042 if (DD->isPure())
2043 Out << " [pure]";
2044
2045 ThunkInfo Thunk = VTableThunks.lookup(I);
2046 if (!Thunk.isEmpty()) {
2047 // If this destructor has a 'this' pointer adjustment, dump it.
2048 if (!Thunk.This.isEmpty()) {
2049 Out << "\n [this adjustment: ";
2050 Out << Thunk.This.NonVirtual << " non-virtual";
2051
2052 if (Thunk.This.VCallOffsetOffset) {
2053 Out << ", " << Thunk.This.VCallOffsetOffset;
2054 Out << " vcall offset offset";
2055 }
2056
2057 Out << ']';
2058 }
2059 }
2060
2061 break;
2062 }
2063
2064 case VTableComponent::CK_UnusedFunctionPointer: {
2065 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2066
2067 std::string Str =
2068 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2069 MD);
2070 Out << "[unused] " << Str;
2071 if (MD->isPure())
2072 Out << " [pure]";
2073 }
2074
2075 }
2076
2077 Out << '\n';
2078
2079 // Dump the next address point.
2080 uint64_t NextIndex = Index + 1;
2081 if (AddressPointsByIndex.count(NextIndex)) {
2082 if (AddressPointsByIndex.count(NextIndex) == 1) {
2083 const BaseSubobject &Base =
2084 AddressPointsByIndex.find(NextIndex)->second;
2085
2086 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
2087 Out << ", " << Base.getBaseOffset().getQuantity();
2088 Out << ") vtable address --\n";
2089 } else {
2090 CharUnits BaseOffset =
2091 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2092
2093 // We store the class names in a set to get a stable order.
2094 std::set<std::string> ClassNames;
2095 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2096 AddressPointsByIndex.lower_bound(NextIndex), E =
2097 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2098 assert(I->second.getBaseOffset() == BaseOffset &&
2099 "Invalid base offset!");
2100 const CXXRecordDecl *RD = I->second.getBase();
2101 ClassNames.insert(RD->getQualifiedNameAsString());
2102 }
2103
2104 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2105 E = ClassNames.end(); I != E; ++I) {
2106 Out << " -- (" << *I;
2107 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2108 }
2109 }
2110 }
2111 }
2112
2113 Out << '\n';
2114
2115 if (isBuildingConstructorVTable())
2116 return;
2117
2118 if (MostDerivedClass->getNumVBases()) {
2119 // We store the virtual base class names and their offsets in a map to get
2120 // a stable order.
2121
2122 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2123 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2124 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2125 std::string ClassName = I->first->getQualifiedNameAsString();
2126 CharUnits OffsetOffset = I->second;
2127 ClassNamesAndOffsets.insert(
2128 std::make_pair(ClassName, OffsetOffset));
2129 }
2130
2131 Out << "Virtual base offset offsets for '";
2132 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2133 Out << ClassNamesAndOffsets.size();
2134 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2135
2136 for (std::map<std::string, CharUnits>::const_iterator I =
2137 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2138 I != E; ++I)
2139 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2140
2141 Out << "\n";
2142 }
2143
2144 if (!Thunks.empty()) {
2145 // We store the method names in a map to get a stable order.
2146 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2147
2148 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2149 I != E; ++I) {
2150 const CXXMethodDecl *MD = I->first;
2151 std::string MethodName =
2152 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2153 MD);
2154
2155 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2156 }
2157
2158 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2159 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2160 I != E; ++I) {
2161 const std::string &MethodName = I->first;
2162 const CXXMethodDecl *MD = I->second;
2163
2164 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002165 std::sort(ThunksVector.begin(), ThunksVector.end(),
2166 ItaniumThunkInfoComparator());
Peter Collingbourne24018462011-09-26 01:57:12 +00002167
2168 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2169 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2170
2171 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2172 const ThunkInfo &Thunk = ThunksVector[I];
2173
2174 Out << llvm::format("%4d | ", I);
2175
2176 // If this function pointer has a return pointer adjustment, dump it.
2177 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov15a0de92013-06-28 15:42:28 +00002178 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbourne24018462011-09-26 01:57:12 +00002179 Out << " non-virtual";
2180 if (Thunk.Return.VBaseOffsetOffset) {
2181 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2182 Out << " vbase offset offset";
2183 }
2184
2185 if (!Thunk.This.isEmpty())
2186 Out << "\n ";
2187 }
2188
2189 // If this function pointer has a 'this' pointer adjustment, dump it.
2190 if (!Thunk.This.isEmpty()) {
2191 Out << "this adjustment: ";
2192 Out << Thunk.This.NonVirtual << " non-virtual";
2193
2194 if (Thunk.This.VCallOffsetOffset) {
2195 Out << ", " << Thunk.This.VCallOffsetOffset;
2196 Out << " vcall offset offset";
2197 }
2198 }
2199
2200 Out << '\n';
2201 }
2202
2203 Out << '\n';
2204 }
2205 }
2206
2207 // Compute the vtable indices for all the member functions.
2208 // Store them in a map keyed by the index so we'll get a sorted table.
2209 std::map<uint64_t, std::string> IndicesMap;
2210
2211 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2212 e = MostDerivedClass->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002213 const CXXMethodDecl *MD = *i;
Peter Collingbourne24018462011-09-26 01:57:12 +00002214
2215 // We only want virtual member functions.
2216 if (!MD->isVirtual())
2217 continue;
2218
2219 std::string MethodName =
2220 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2221 MD);
2222
2223 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002224 GlobalDecl GD(DD, Dtor_Complete);
2225 assert(MethodVTableIndices.count(GD));
2226 uint64_t VTableIndex = MethodVTableIndices[GD];
2227 IndicesMap[VTableIndex] = MethodName + " [complete]";
2228 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Peter Collingbourne24018462011-09-26 01:57:12 +00002229 } else {
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002230 assert(MethodVTableIndices.count(MD));
2231 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbourne24018462011-09-26 01:57:12 +00002232 }
2233 }
2234
2235 // Print the vtable indices for all the member functions.
2236 if (!IndicesMap.empty()) {
2237 Out << "VTable indices for '";
2238 Out << MostDerivedClass->getQualifiedNameAsString();
2239 Out << "' (" << IndicesMap.size() << " entries).\n";
2240
2241 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2242 E = IndicesMap.end(); I != E; ++I) {
2243 uint64_t VTableIndex = I->first;
2244 const std::string &MethodName = I->second;
2245
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002246 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer79a55012012-03-10 02:06:27 +00002247 << '\n';
Peter Collingbourne24018462011-09-26 01:57:12 +00002248 }
2249 }
2250
2251 Out << '\n';
2252}
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002253
2254struct VTableThunksComparator {
2255 bool operator()(const VTableLayout::VTableThunkTy &LHS,
2256 const VTableLayout::VTableThunkTy &RHS) {
2257 assert(LHS.first != RHS.first &&
2258 "All thunks should have unique indices!");
2259 return LHS.first < RHS.first;
2260 }
2261};
Peter Collingbourne24018462011-09-26 01:57:12 +00002262}
2263
2264VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2265 const VTableComponent *VTableComponents,
2266 uint64_t NumVTableThunks,
2267 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002268 const AddressPointsMapTy &AddressPoints,
2269 bool IsMicrosoftABI)
Peter Collingbourne24018462011-09-26 01:57:12 +00002270 : NumVTableComponents(NumVTableComponents),
2271 VTableComponents(new VTableComponent[NumVTableComponents]),
2272 NumVTableThunks(NumVTableThunks),
2273 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002274 AddressPoints(AddressPoints),
2275 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002276 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002277 this->VTableComponents.get());
2278 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2279 this->VTableThunks.get());
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002280 std::sort(this->VTableThunks.get(),
2281 this->VTableThunks.get() + NumVTableThunks,
2282 VTableThunksComparator());
Peter Collingbourne24018462011-09-26 01:57:12 +00002283}
2284
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002285VTableLayout::~VTableLayout() { }
Peter Collingbourne24018462011-09-26 01:57:12 +00002286
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002287VTableContext::VTableContext(ASTContext &Context)
Eli Friedman0a598fd2013-06-27 20:48:08 +00002288 : IsMicrosoftABI(Context.getTargetInfo().getCXXABI().isMicrosoft()) {
John McCallb8b2c9d2013-01-25 22:30:49 +00002289}
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002290
Peter Collingbourne24018462011-09-26 01:57:12 +00002291VTableContext::~VTableContext() {
2292 llvm::DeleteContainerSeconds(VTableLayouts);
2293}
2294
Peter Collingbourne24018462011-09-26 01:57:12 +00002295uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2296 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2297 if (I != MethodVTableIndices.end())
2298 return I->second;
2299
2300 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2301
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002302 computeVTableRelatedInformation(RD);
Peter Collingbourne24018462011-09-26 01:57:12 +00002303
2304 I = MethodVTableIndices.find(GD);
2305 assert(I != MethodVTableIndices.end() && "Did not find index!");
2306 return I->second;
2307}
2308
2309CharUnits
2310VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2311 const CXXRecordDecl *VBase) {
2312 ClassPairTy ClassPair(RD, VBase);
2313
2314 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2315 VirtualBaseClassOffsetOffsets.find(ClassPair);
2316 if (I != VirtualBaseClassOffsetOffsets.end())
2317 return I->second;
2318
2319 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2320 BaseSubobject(RD, CharUnits::Zero()),
2321 /*BaseIsVirtual=*/false,
2322 /*OffsetInLayoutClass=*/CharUnits::Zero());
2323
2324 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2325 Builder.getVBaseOffsetOffsets().begin(),
2326 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2327 // Insert all types.
2328 ClassPairTy ClassPair(RD, I->first);
2329
2330 VirtualBaseClassOffsetOffsets.insert(
2331 std::make_pair(ClassPair, I->second));
2332 }
2333
2334 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2335 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2336
2337 return I->second;
2338}
2339
2340static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2341 SmallVector<VTableLayout::VTableThunkTy, 1>
2342 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbourne24018462011-09-26 01:57:12 +00002343
2344 return new VTableLayout(Builder.getNumVTableComponents(),
2345 Builder.vtable_component_begin(),
2346 VTableThunks.size(),
2347 VTableThunks.data(),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002348 Builder.getAddressPoints(),
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002349 /*IsMicrosoftABI=*/false);
Peter Collingbourne24018462011-09-26 01:57:12 +00002350}
2351
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002352void VTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002353 assert(!IsMicrosoftABI && "Shouldn't be called in this ABI!");
2354
Peter Collingbourne24018462011-09-26 01:57:12 +00002355 const VTableLayout *&Entry = VTableLayouts[RD];
2356
2357 // Check if we've computed this information before.
2358 if (Entry)
2359 return;
2360
2361 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2362 /*MostDerivedClassIsVirtual=*/0, RD);
2363 Entry = CreateVTableLayout(Builder);
2364
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002365 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2366 Builder.vtable_indices_end());
2367
Peter Collingbourne24018462011-09-26 01:57:12 +00002368 // Add the known thunks.
2369 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2370
2371 // If we don't have the vbase information for this class, insert it.
2372 // getVirtualBaseOffsetOffset will compute it separately without computing
2373 // the rest of the vtable related information.
2374 if (!RD->getNumVBases())
2375 return;
2376
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00002377 const CXXRecordDecl *VBase =
2378 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00002379
2380 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2381 return;
2382
2383 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2384 Builder.getVBaseOffsetOffsets().begin(),
2385 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2386 // Insert all types.
2387 ClassPairTy ClassPair(RD, I->first);
2388
2389 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2390 }
2391}
2392
Peter Collingbourne24018462011-09-26 01:57:12 +00002393VTableLayout *VTableContext::createConstructionVTableLayout(
2394 const CXXRecordDecl *MostDerivedClass,
2395 CharUnits MostDerivedClassOffset,
2396 bool MostDerivedClassIsVirtual,
2397 const CXXRecordDecl *LayoutClass) {
2398 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2399 MostDerivedClassIsVirtual, LayoutClass);
2400 return CreateVTableLayout(Builder);
2401}
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002402
2403unsigned clang::GetVBTableIndex(const CXXRecordDecl *Derived,
2404 const CXXRecordDecl *VBase) {
2405 unsigned VBTableIndex = 1; // Start with one to skip the self entry.
2406 for (CXXRecordDecl::base_class_const_iterator I = Derived->vbases_begin(),
2407 E = Derived->vbases_end(); I != E; ++I) {
2408 if (I->getType()->getAsCXXRecordDecl() == VBase)
2409 return VBTableIndex;
2410 ++VBTableIndex;
2411 }
2412 llvm_unreachable("VBase must be a vbase of Derived");
2413}
2414
2415namespace {
2416
2417// Vtables in the Microsoft ABI are different from the Itanium ABI.
2418//
2419// The main differences are:
2420// 1. Separate vftable and vbtable.
2421//
2422// 2. Each subobject with a vfptr gets its own vftable rather than an address
2423// point in a single vtable shared between all the subobjects.
2424// Each vftable is represented by a separate section and virtual calls
2425// must be done using the vftable which has a slot for the function to be
2426// called.
2427//
2428// 3. Virtual method definitions expect their 'this' parameter to point to the
2429// first vfptr whose table provides a compatible overridden method. In many
2430// cases, this permits the original vf-table entry to directly call
2431// the method instead of passing through a thunk.
2432//
2433// A compatible overridden method is one which does not have a non-trivial
2434// covariant-return adjustment.
2435//
2436// The first vfptr is the one with the lowest offset in the complete-object
2437// layout of the defining class, and the method definition will subtract
2438// that constant offset from the parameter value to get the real 'this'
2439// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2440// function defined in a virtual base is overridden in a more derived
2441// virtual base and these bases have a reverse order in the complete
2442// object), the vf-table may require a this-adjustment thunk.
2443//
2444// 4. vftables do not contain new entries for overrides that merely require
2445// this-adjustment. Together with #3, this keeps vf-tables smaller and
2446// eliminates the need for this-adjustment thunks in many cases, at the cost
2447// of often requiring redundant work to adjust the "this" pointer.
2448//
2449// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2450// Vtordisps are emitted into the class layout if a class has
2451// a) a user-defined ctor/dtor
2452// and
2453// b) a method overriding a method in a virtual base.
2454
2455class VFTableBuilder {
2456public:
2457 typedef MicrosoftVFTableContext::MethodVFTableLocation MethodVFTableLocation;
2458
2459 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2460 MethodVFTableLocationsTy;
2461
2462private:
2463 /// Context - The ASTContext which we will use for layout information.
2464 ASTContext &Context;
2465
2466 /// MostDerivedClass - The most derived class for which we're building this
2467 /// vtable.
2468 const CXXRecordDecl *MostDerivedClass;
2469
2470 const ASTRecordLayout &MostDerivedClassLayout;
2471
2472 VFPtrInfo WhichVFPtr;
2473
2474 /// FinalOverriders - The final overriders of the most derived class.
2475 const FinalOverriders Overriders;
2476
2477 /// Components - The components of the vftable being built.
2478 SmallVector<VTableComponent, 64> Components;
2479
2480 MethodVFTableLocationsTy MethodVFTableLocations;
2481
2482 /// MethodInfo - Contains information about a method in a vtable.
2483 /// (Used for computing 'this' pointer adjustment thunks.
2484 struct MethodInfo {
2485 /// VBTableIndex - The nonzero index in the vbtable that
2486 /// this method's base has, or zero.
2487 const uint64_t VBTableIndex;
2488
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002489 /// VBase - If nonnull, holds the last vbase which contains the vfptr that
2490 /// the method definition is adjusted to.
2491 const CXXRecordDecl *VBase;
2492
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002493 /// VFTableIndex - The index in the vftable that this method has.
2494 const uint64_t VFTableIndex;
2495
2496 /// Shadowed - Indicates if this vftable slot is shadowed by
2497 /// a slot for a covariant-return override. If so, it shouldn't be printed
2498 /// or used for vcalls in the most derived class.
2499 bool Shadowed;
2500
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002501 MethodInfo(uint64_t VBTableIndex, const CXXRecordDecl *VBase,
2502 uint64_t VFTableIndex)
2503 : VBTableIndex(VBTableIndex), VBase(VBase), VFTableIndex(VFTableIndex),
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002504 Shadowed(false) {}
2505
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002506 MethodInfo()
2507 : VBTableIndex(0), VBase(0), VFTableIndex(0), Shadowed(false) {}
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002508 };
2509
2510 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2511
2512 /// MethodInfoMap - The information for all methods in the vftable we're
2513 /// currently building.
2514 MethodInfoMapTy MethodInfoMap;
2515
2516 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2517
2518 /// VTableThunks - The thunks by vftable index in the vftable currently being
2519 /// built.
2520 VTableThunksMapTy VTableThunks;
2521
2522 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2523 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2524
2525 /// Thunks - A map that contains all the thunks needed for all methods in the
2526 /// most derived class for which the vftable is currently being built.
2527 ThunksMapTy Thunks;
2528
2529 /// AddThunk - Add a thunk for the given method.
2530 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2531 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2532
2533 // Check if we have this thunk already.
2534 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2535 ThunksVector.end())
2536 return;
2537
2538 ThunksVector.push_back(Thunk);
2539 }
2540
2541 /// ComputeThisOffset - Returns the 'this' argument offset for the given
2542 /// method in the given subobject, relative to the beginning of the
2543 /// MostDerivedClass.
2544 CharUnits ComputeThisOffset(const CXXMethodDecl *MD,
2545 BaseSubobject Base,
2546 FinalOverriders::OverriderInfo Overrider);
2547
2548 /// AddMethod - Add a single virtual member function to the vftable
2549 /// components vector.
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002550 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002551 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002552 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002553 "Destructor can't have return adjustment!");
2554 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2555 } else {
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002556 if (!TI.isEmpty())
2557 VTableThunks[Components.size()] = TI;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002558 Components.push_back(VTableComponent::MakeFunction(MD));
2559 }
2560 }
2561
2562 /// AddMethods - Add the methods of this base subobject and the relevant
2563 /// subbases to the vftable we're currently laying out.
2564 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2565 const CXXRecordDecl *LastVBase,
2566 BasesSetVectorTy &VisitedBases);
2567
2568 void LayoutVFTable() {
2569 // FIXME: add support for RTTI when we have proper LLVM support for symbols
2570 // pointing to the middle of a section.
2571
2572 BasesSetVectorTy VisitedBases;
2573 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, 0,
2574 VisitedBases);
2575
2576 assert(MethodVFTableLocations.empty());
2577 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2578 E = MethodInfoMap.end(); I != E; ++I) {
2579 const CXXMethodDecl *MD = I->first;
2580 const MethodInfo &MI = I->second;
2581 // Skip the methods that the MostDerivedClass didn't override
2582 // and the entries shadowed by return adjusting thunks.
2583 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2584 continue;
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002585 MethodVFTableLocation Loc(MI.VBTableIndex, MI.VBase,
2586 WhichVFPtr.VFPtrOffset, MI.VFTableIndex);
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002587 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2588 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2589 } else {
2590 MethodVFTableLocations[MD] = Loc;
2591 }
2592 }
2593 }
2594
2595 void ErrorUnsupported(StringRef Feature, SourceLocation Location) {
2596 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2597 unsigned DiagID = Diags.getCustomDiagID(
2598 DiagnosticsEngine::Error, "v-table layout for %0 is not supported yet");
2599 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2600 }
2601
2602public:
2603 VFTableBuilder(const CXXRecordDecl *MostDerivedClass, VFPtrInfo Which)
2604 : Context(MostDerivedClass->getASTContext()),
2605 MostDerivedClass(MostDerivedClass),
2606 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
2607 WhichVFPtr(Which),
2608 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2609 LayoutVFTable();
2610
2611 if (Context.getLangOpts().DumpVTableLayouts)
2612 dumpLayout(llvm::errs());
2613 }
2614
2615 uint64_t getNumThunks() const { return Thunks.size(); }
2616
2617 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2618
2619 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2620
2621 MethodVFTableLocationsTy::const_iterator vtable_indices_begin() const {
2622 return MethodVFTableLocations.begin();
2623 }
2624
2625 MethodVFTableLocationsTy::const_iterator vtable_indices_end() const {
2626 return MethodVFTableLocations.end();
2627 }
2628
2629 uint64_t getNumVTableComponents() const { return Components.size(); }
2630
2631 const VTableComponent *vtable_component_begin() const {
2632 return Components.begin();
2633 }
2634
2635 const VTableComponent *vtable_component_end() const {
2636 return Components.end();
2637 }
2638
2639 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2640 return VTableThunks.begin();
2641 }
2642
2643 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2644 return VTableThunks.end();
2645 }
2646
2647 void dumpLayout(raw_ostream &);
2648};
2649
2650/// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2651/// that define the given method.
2652struct InitialOverriddenDefinitionCollector {
2653 BasesSetVectorTy Bases;
2654 OverriddenMethodsSetTy VisitedOverriddenMethods;
2655
2656 bool visit(const CXXMethodDecl *OverriddenMD) {
2657 if (OverriddenMD->size_overridden_methods() == 0)
2658 Bases.insert(OverriddenMD->getParent());
2659 // Don't recurse on this method if we've already collected it.
2660 return VisitedOverriddenMethods.insert(OverriddenMD);
2661 }
2662};
2663
2664static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2665 CXXBasePath &Path, void *BasesSet) {
2666 BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2667 return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2668}
2669
2670CharUnits
2671VFTableBuilder::ComputeThisOffset(const CXXMethodDecl *MD,
2672 BaseSubobject Base,
2673 FinalOverriders::OverriderInfo Overrider) {
2674 // Complete object virtual destructors are always emitted in the most derived
2675 // class, thus don't have this offset.
2676 if (isa<CXXDestructorDecl>(MD))
2677 return CharUnits();
2678
2679 InitialOverriddenDefinitionCollector Collector;
2680 visitAllOverriddenMethods(MD, Collector);
2681
2682 CXXBasePaths Paths;
2683 Base.getBase()->lookupInBases(BaseInSet, &Collector.Bases, Paths);
2684
2685 // This will hold the smallest this offset among overridees of MD.
2686 // This implies that an offset of a non-virtual base will dominate an offset
2687 // of a virtual base to potentially reduce the number of thunks required
2688 // in the derived classes that inherit this method.
2689 CharUnits Ret;
2690 bool First = true;
2691
2692 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2693 I != E; ++I) {
2694 const CXXBasePath &Path = (*I);
2695 CharUnits ThisOffset = Base.getBaseOffset();
2696
2697 // For each path from the overrider to the parents of the overridden methods,
2698 // traverse the path, calculating the this offset in the most derived class.
2699 for (int J = 0, F = Path.size(); J != F; ++J) {
2700 const CXXBasePathElement &Element = Path[J];
2701 QualType CurTy = Element.Base->getType();
2702 const CXXRecordDecl *PrevRD = Element.Class,
2703 *CurRD = CurTy->getAsCXXRecordDecl();
2704 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2705
2706 if (Element.Base->isVirtual()) {
2707 if (Overrider.Method->getParent() == PrevRD) {
2708 // This one's interesting. If the final overrider is in a vbase B of the
2709 // most derived class and it overrides a method of the B's own vbase A,
2710 // it uses A* as "this". In its prologue, it can cast A* to B* with
2711 // a static offset. This offset is used regardless of the actual
2712 // offset of A from B in the most derived class, requiring an
2713 // this-adjusting thunk in the vftable if A and B are laid out
2714 // differently in the most derived class.
2715 ThisOffset += Layout.getVBaseClassOffset(CurRD);
2716 } else {
2717 ThisOffset = MostDerivedClassLayout.getVBaseClassOffset(CurRD);
2718 }
2719 } else {
2720 ThisOffset += Layout.getBaseClassOffset(CurRD);
2721 }
2722 }
2723
2724 if (Ret > ThisOffset || First) {
2725 First = false;
2726 Ret = ThisOffset;
2727 }
2728 }
2729
2730 assert(!First && "Method not found in the given subobject?");
2731 return Ret;
2732}
2733
2734static const CXXMethodDecl*
2735FindDirectlyOverriddenMethodInBases(const CXXMethodDecl *MD,
2736 BasesSetVectorTy &Bases) {
2737 // We can't just iterate over the overridden methods and return the first one
2738 // which has its parent in Bases, e.g. this doesn't work when we have
2739 // multiple subobjects of the same type that have its virtual function
2740 // overridden.
2741 for (int I = Bases.size(), E = 0; I != E; --I) {
2742 const CXXRecordDecl *CurrentBase = Bases[I - 1];
2743
2744 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2745 E = MD->end_overridden_methods(); I != E; ++I) {
2746 const CXXMethodDecl *OverriddenMD = *I;
2747
2748 if (OverriddenMD->getParent() == CurrentBase)
2749 return OverriddenMD;
2750 }
2751 }
2752
2753 return 0;
2754}
2755
Timur Iskhodzhanovcbf8dde2013-10-06 15:31:37 +00002756static void GroupNewVirtualOverloads(
2757 const CXXRecordDecl *RD,
2758 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2759 // Put the virtual methods into VirtualMethods in the proper order:
2760 // 1) Group overloads by declaration name. New groups are added to the
2761 // vftable in the order of their first declarations in this class
2762 // (including overrides).
2763 // 2) In each group, new overloads appear in the reverse order of declaration.
2764 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2765 SmallVector<MethodGroup, 10> Groups;
2766 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2767 VisitedGroupIndicesTy VisitedGroupIndices;
2768 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2769 E = RD->method_end(); I != E; ++I) {
2770 const CXXMethodDecl *MD = *I;
2771 if (!MD->isVirtual())
2772 continue;
2773
2774 VisitedGroupIndicesTy::iterator J;
2775 bool Inserted;
2776 llvm::tie(J, Inserted) = VisitedGroupIndices.insert(
2777 std::make_pair(MD->getDeclName(), Groups.size()));
2778 if (Inserted)
2779 Groups.push_back(MethodGroup(1, MD));
2780 else
2781 Groups[J->second].push_back(MD);
2782 }
2783
2784 for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2785 VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2786}
2787
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002788void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2789 const CXXRecordDecl *LastVBase,
2790 BasesSetVectorTy &VisitedBases) {
2791 const CXXRecordDecl *RD = Base.getBase();
2792 if (!RD->isPolymorphic())
2793 return;
2794
2795 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2796
2797 // See if this class expands a vftable of the base we look at, which is either
2798 // the one defined by the vfptr base path or the primary base of the current class.
2799 const CXXRecordDecl *NextBase = 0, *NextLastVBase = LastVBase;
2800 CharUnits NextBaseOffset;
2801 if (BaseDepth < WhichVFPtr.PathToBaseWithVFPtr.size()) {
2802 NextBase = WhichVFPtr.PathToBaseWithVFPtr[BaseDepth];
2803 if (Layout.getVBaseOffsetsMap().count(NextBase)) {
2804 NextLastVBase = NextBase;
2805 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2806 } else {
2807 NextBaseOffset =
2808 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2809 }
2810 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2811 assert(!Layout.isPrimaryBaseVirtual() &&
2812 "No primary virtual bases in this ABI");
2813 NextBase = PrimaryBase;
2814 NextBaseOffset = Base.getBaseOffset();
2815 }
2816
2817 if (NextBase) {
2818 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2819 NextLastVBase, VisitedBases);
2820 if (!VisitedBases.insert(NextBase))
2821 llvm_unreachable("Found a duplicate primary base!");
2822 }
2823
Timur Iskhodzhanovcbf8dde2013-10-06 15:31:37 +00002824 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2825 // Put virtual methods in the proper order.
2826 GroupNewVirtualOverloads(RD, VirtualMethods);
2827
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002828 // Now go through all virtual member functions and add them to the current
2829 // vftable. This is done by
2830 // - replacing overridden methods in their existing slots, as long as they
2831 // don't require return adjustment; calculating This adjustment if needed.
2832 // - adding new slots for methods of the current base not present in any
2833 // sub-bases;
2834 // - adding new slots for methods that require Return adjustment.
2835 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Timur Iskhodzhanovcbf8dde2013-10-06 15:31:37 +00002836 for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
2837 const CXXMethodDecl *MD = VirtualMethods[I];
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002838
2839 FinalOverriders::OverriderInfo Overrider =
2840 Overriders.getOverrider(MD, Base.getBaseOffset());
2841 ThisAdjustment ThisAdjustmentOffset;
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002842 bool ForceThunk = false;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002843
2844 // Check if this virtual member function overrides
2845 // a method in one of the visited bases.
2846 if (const CXXMethodDecl *OverriddenMD =
2847 FindDirectlyOverriddenMethodInBases(MD, VisitedBases)) {
2848 MethodInfoMapTy::iterator OverriddenMDIterator =
2849 MethodInfoMap.find(OverriddenMD);
2850
2851 // If the overridden method went to a different vftable, skip it.
2852 if (OverriddenMDIterator == MethodInfoMap.end())
2853 continue;
2854
2855 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2856
2857 // Create a this-adjusting thunk if needed.
2858 CharUnits TI = ComputeThisOffset(MD, Base, Overrider);
2859 if (TI != WhichVFPtr.VFPtrFullOffset) {
2860 ThisAdjustmentOffset.NonVirtual =
2861 (TI - WhichVFPtr.VFPtrFullOffset).getQuantity();
2862 VTableThunks[OverriddenMethodInfo.VFTableIndex].This =
2863 ThisAdjustmentOffset;
2864 AddThunk(MD, VTableThunks[OverriddenMethodInfo.VFTableIndex]);
2865 }
2866
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002867 if (MD->getResultType() == OverriddenMD->getResultType()) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002868 // No return adjustment needed - just replace the overridden method info
2869 // with the current info.
2870 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002871 OverriddenMethodInfo.VBase,
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002872 OverriddenMethodInfo.VFTableIndex);
2873 MethodInfoMap.erase(OverriddenMDIterator);
2874
2875 assert(!MethodInfoMap.count(MD) &&
2876 "Should not have method info for this method yet!");
2877 MethodInfoMap.insert(std::make_pair(MD, MI));
2878 continue;
2879 } else {
2880 // In case we need a return adjustment, we'll add a new slot for
2881 // the overrider and put a return-adjusting thunk where the overridden
2882 // method was in the vftable.
2883 // For now, just mark the overriden method as shadowed by a new slot.
2884 OverriddenMethodInfo.Shadowed = true;
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002885 ForceThunk = true;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002886
2887 // Also apply this adjustment to the shadowed slots.
2888 if (!ThisAdjustmentOffset.isEmpty()) {
2889 // FIXME: this is O(N^2), can be O(N).
2890 const CXXMethodDecl *SubOverride = OverriddenMD;
2891 while ((SubOverride =
2892 FindDirectlyOverriddenMethodInBases(SubOverride, VisitedBases))) {
2893 MethodInfoMapTy::iterator SubOverrideIterator =
2894 MethodInfoMap.find(SubOverride);
2895 if (SubOverrideIterator == MethodInfoMap.end())
2896 break;
2897 MethodInfo &SubOverrideMI = SubOverrideIterator->second;
2898 assert(SubOverrideMI.Shadowed);
2899 VTableThunks[SubOverrideMI.VFTableIndex].This =
2900 ThisAdjustmentOffset;
2901 AddThunk(MD, VTableThunks[SubOverrideMI.VFTableIndex]);
2902 }
2903 }
2904 }
2905 } else if (Base.getBaseOffset() != WhichVFPtr.VFPtrFullOffset ||
2906 MD->size_overridden_methods()) {
2907 // Skip methods that don't belong to the vftable of the current class,
2908 // e.g. each method that wasn't seen in any of the visited sub-bases
2909 // but overrides multiple methods of other sub-bases.
2910 continue;
2911 }
2912
2913 // If we got here, MD is a method not seen in any of the sub-bases or
2914 // it requires return adjustment. Insert the method info for this method.
2915 unsigned VBIndex =
2916 LastVBase ? GetVBTableIndex(MostDerivedClass, LastVBase) : 0;
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002917 MethodInfo MI(VBIndex, LastVBase, Components.size());
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002918
2919 assert(!MethodInfoMap.count(MD) &&
2920 "Should not have method info for this method yet!");
2921 MethodInfoMap.insert(std::make_pair(MD, MI));
2922
2923 const CXXMethodDecl *OverriderMD = Overrider.Method;
2924
2925 // Check if this overrider needs a return adjustment.
2926 // We don't want to do this for pure virtual member functions.
2927 BaseOffset ReturnAdjustmentOffset;
2928 ReturnAdjustment ReturnAdjustment;
2929 if (!OverriderMD->isPure()) {
2930 ReturnAdjustmentOffset =
2931 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
2932 }
2933 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002934 ForceThunk = true;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002935 ReturnAdjustment.NonVirtual =
2936 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
2937 if (ReturnAdjustmentOffset.VirtualBase) {
2938 // FIXME: We might want to create a VBIndex alias for VBaseOffsetOffset
2939 // in the ReturnAdjustment struct.
2940 ReturnAdjustment.VBaseOffsetOffset =
2941 GetVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
2942 ReturnAdjustmentOffset.VirtualBase);
2943 }
2944 }
2945
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002946 AddMethod(OverriderMD, ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
2947 ForceThunk ? MD : 0));
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002948 }
2949}
2950
2951void PrintBasePath(const VFPtrInfo::BasePath &Path, raw_ostream &Out) {
2952 for (VFPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
2953 E = Path.rend(); I != E; ++I) {
2954 Out << "'" << (*I)->getQualifiedNameAsString() << "' in ";
2955 }
2956}
2957
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00002958struct MicrosoftThunkInfoStableSortComparator {
2959 bool operator() (const ThunkInfo &LHS, const ThunkInfo &RHS) {
2960 if (LHS.This != RHS.This)
2961 return LHS.This < RHS.This;
2962
2963 if (LHS.Return != RHS.Return)
2964 return LHS.Return < RHS.Return;
2965
2966 // Keep different thunks with the same adjustments in the order they
2967 // were put into the vector.
2968 return false;
2969 }
2970};
2971
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002972void VFTableBuilder::dumpLayout(raw_ostream &Out) {
2973 Out << "VFTable for ";
2974 PrintBasePath(WhichVFPtr.PathToBaseWithVFPtr, Out);
2975 Out << "'" << MostDerivedClass->getQualifiedNameAsString();
2976 Out << "' (" << Components.size() << " entries).\n";
2977
2978 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
2979 Out << llvm::format("%4d | ", I);
2980
2981 const VTableComponent &Component = Components[I];
2982
2983 // Dump the component.
2984 switch (Component.getKind()) {
2985 case VTableComponent::CK_RTTI:
2986 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
2987 break;
2988
2989 case VTableComponent::CK_FunctionPointer: {
2990 const CXXMethodDecl *MD = Component.getFunctionDecl();
2991
2992 std::string Str = PredefinedExpr::ComputeName(
2993 PredefinedExpr::PrettyFunctionNoVirtual, MD);
2994 Out << Str;
2995 if (MD->isPure())
2996 Out << " [pure]";
2997
2998 if (MD->isDeleted()) {
2999 ErrorUnsupported("deleted methods", MD->getLocation());
3000 Out << " [deleted]";
3001 }
3002
3003 ThunkInfo Thunk = VTableThunks.lookup(I);
3004 if (!Thunk.isEmpty()) {
3005 // If this function pointer has a return adjustment, dump it.
3006 if (!Thunk.Return.isEmpty()) {
3007 Out << "\n [return adjustment: ";
3008 if (Thunk.Return.VBaseOffsetOffset)
3009 Out << "vbase #" << Thunk.Return.VBaseOffsetOffset << ", ";
3010 Out << Thunk.Return.NonVirtual << " non-virtual]";
3011 }
3012
3013 // If this function pointer has a 'this' pointer adjustment, dump it.
3014 if (!Thunk.This.isEmpty()) {
3015 assert(!Thunk.This.VCallOffsetOffset &&
3016 "No virtual this adjustment in this ABI");
3017 Out << "\n [this adjustment: " << Thunk.This.NonVirtual
3018 << " non-virtual]";
3019 }
3020 }
3021
3022 break;
3023 }
3024
3025 case VTableComponent::CK_DeletingDtorPointer: {
3026 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3027
3028 Out << DD->getQualifiedNameAsString();
3029 Out << "() [scalar deleting]";
3030
3031 if (DD->isPure())
3032 Out << " [pure]";
3033
3034 ThunkInfo Thunk = VTableThunks.lookup(I);
3035 if (!Thunk.isEmpty()) {
3036 assert(Thunk.Return.isEmpty() &&
3037 "No return adjustment needed for destructors!");
3038 // If this destructor has a 'this' pointer adjustment, dump it.
3039 if (!Thunk.This.isEmpty()) {
3040 assert(!Thunk.This.VCallOffsetOffset &&
3041 "No virtual this adjustment in this ABI");
3042 Out << "\n [this adjustment: " << Thunk.This.NonVirtual
3043 << " non-virtual]";
3044 }
3045 }
3046
3047 break;
3048 }
3049
3050 default:
3051 DiagnosticsEngine &Diags = Context.getDiagnostics();
3052 unsigned DiagID = Diags.getCustomDiagID(
3053 DiagnosticsEngine::Error,
3054 "Unexpected vftable component type %0 for component number %1");
3055 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3056 << I << Component.getKind();
3057 }
3058
3059 Out << '\n';
3060 }
3061
3062 Out << '\n';
3063
3064 if (!Thunks.empty()) {
3065 // We store the method names in a map to get a stable order.
3066 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3067
3068 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3069 I != E; ++I) {
3070 const CXXMethodDecl *MD = I->first;
3071 std::string MethodName = PredefinedExpr::ComputeName(
3072 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3073
3074 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3075 }
3076
3077 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3078 I = MethodNamesAndDecls.begin(),
3079 E = MethodNamesAndDecls.end();
3080 I != E; ++I) {
3081 const std::string &MethodName = I->first;
3082 const CXXMethodDecl *MD = I->second;
3083
3084 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovc3dcfa22013-10-08 19:15:38 +00003085 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
3086 MicrosoftThunkInfoStableSortComparator());
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003087
3088 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3089 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3090
3091 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3092 const ThunkInfo &Thunk = ThunksVector[I];
3093
3094 Out << llvm::format("%4d | ", I);
3095
3096 // If this function pointer has a return pointer adjustment, dump it.
3097 if (!Thunk.Return.isEmpty()) {
3098 Out << "return adjustment: ";
3099 if (Thunk.Return.VBaseOffsetOffset)
3100 Out << "vbase #" << Thunk.Return.VBaseOffsetOffset << ", ";
3101 Out << Thunk.Return.NonVirtual << " non-virtual";
3102
3103 if (!Thunk.This.isEmpty())
3104 Out << "\n ";
3105 }
3106
3107 // If this function pointer has a 'this' pointer adjustment, dump it.
3108 if (!Thunk.This.isEmpty()) {
3109 assert(!Thunk.This.VCallOffsetOffset &&
3110 "No virtual this adjustment in this ABI");
3111 Out << "this adjustment: ";
3112 Out << Thunk.This.NonVirtual << " non-virtual";
3113 }
3114
3115 Out << '\n';
3116 }
3117
3118 Out << '\n';
3119 }
3120 }
3121}
3122}
3123
3124static void EnumerateVFPtrs(
3125 ASTContext &Context, const CXXRecordDecl *MostDerivedClass,
3126 const ASTRecordLayout &MostDerivedClassLayout,
3127 BaseSubobject Base, const CXXRecordDecl *LastVBase,
3128 const VFPtrInfo::BasePath &PathFromCompleteClass,
3129 BasesSetVectorTy &VisitedVBases,
3130 MicrosoftVFTableContext::VFPtrListTy &Result) {
3131 const CXXRecordDecl *CurrentClass = Base.getBase();
3132 CharUnits OffsetInCompleteClass = Base.getBaseOffset();
3133 const ASTRecordLayout &CurrentClassLayout =
3134 Context.getASTRecordLayout(CurrentClass);
3135
3136 if (CurrentClassLayout.hasOwnVFPtr()) {
3137 if (LastVBase) {
3138 uint64_t VBIndex = GetVBTableIndex(MostDerivedClass, LastVBase);
3139 assert(VBIndex > 0 && "vbases must have vbindex!");
3140 CharUnits VFPtrOffset =
3141 OffsetInCompleteClass -
3142 MostDerivedClassLayout.getVBaseClassOffset(LastVBase);
3143 Result.push_back(VFPtrInfo(VBIndex, LastVBase, VFPtrOffset,
3144 PathFromCompleteClass, OffsetInCompleteClass));
3145 } else {
3146 Result.push_back(VFPtrInfo(OffsetInCompleteClass, PathFromCompleteClass));
3147 }
3148 }
3149
3150 for (CXXRecordDecl::base_class_const_iterator I = CurrentClass->bases_begin(),
3151 E = CurrentClass->bases_end(); I != E; ++I) {
3152 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
3153
3154 CharUnits NextBaseOffset;
3155 const CXXRecordDecl *NextLastVBase;
3156 if (I->isVirtual()) {
3157 if (VisitedVBases.count(BaseDecl))
3158 continue;
3159 VisitedVBases.insert(BaseDecl);
3160 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
3161 NextLastVBase = BaseDecl;
3162 } else {
3163 NextBaseOffset = OffsetInCompleteClass +
3164 CurrentClassLayout.getBaseClassOffset(BaseDecl);
3165 NextLastVBase = LastVBase;
3166 }
3167
3168 VFPtrInfo::BasePath NewPath = PathFromCompleteClass;
3169 NewPath.push_back(BaseDecl);
3170 BaseSubobject NextBase(BaseDecl, NextBaseOffset);
3171
3172 EnumerateVFPtrs(Context, MostDerivedClass, MostDerivedClassLayout, NextBase,
3173 NextLastVBase, NewPath, VisitedVBases, Result);
3174 }
3175}
3176
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00003177/// CalculatePathToMangle - Calculate the subset of records that should be used
3178/// to mangle the vftable for the given vfptr.
3179/// Should only be called if a class has multiple vftables.
3180static void
3181CalculatePathToMangle(const CXXRecordDecl *RD, VFPtrInfo &VFPtr) {
3182 // FIXME: In some rare cases this code produces a slightly incorrect mangling.
3183 // It's very likely that the vbtable mangling code can be adjusted to mangle
3184 // both vftables and vbtables correctly.
3185
3186 VFPtrInfo::BasePath &FullPath = VFPtr.PathToBaseWithVFPtr;
3187 if (FullPath.empty()) {
3188 // Mangle the class's own vftable.
3189 assert(RD->getNumVBases() &&
3190 "Something's wrong: if the most derived "
3191 "class has more than one vftable, it can only have its own "
3192 "vftable if it has vbases");
3193 VFPtr.PathToMangle.push_back(RD);
3194 return;
3195 }
3196
3197 unsigned Begin = 0;
3198
3199 // First, skip all the bases before the vbase.
3200 if (VFPtr.LastVBase) {
3201 while (FullPath[Begin] != VFPtr.LastVBase) {
3202 Begin++;
3203 assert(Begin < FullPath.size());
3204 }
3205 }
3206
3207 // Then, put the rest of the base path in the reverse order.
3208 for (unsigned I = FullPath.size(); I != Begin; --I) {
3209 const CXXRecordDecl *CurBase = FullPath[I - 1],
3210 *ItsBase = (I == 1) ? RD : FullPath[I - 2];
3211 bool BaseIsVirtual = false;
3212 for (CXXRecordDecl::base_class_const_iterator J = ItsBase->bases_begin(),
3213 F = ItsBase->bases_end(); J != F; ++J) {
3214 if (J->getType()->getAsCXXRecordDecl() == CurBase) {
3215 BaseIsVirtual = J->isVirtual();
3216 break;
3217 }
3218 }
3219
3220 // Should skip the current base if it is a non-virtual base with no siblings.
3221 if (BaseIsVirtual || ItsBase->getNumBases() != 1)
3222 VFPtr.PathToMangle.push_back(CurBase);
3223 }
3224}
3225
Benjamin Kramer3b142da2013-08-01 11:08:06 +00003226static void EnumerateVFPtrs(ASTContext &Context, const CXXRecordDecl *ForClass,
3227 MicrosoftVFTableContext::VFPtrListTy &Result) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003228 Result.clear();
3229 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(ForClass);
3230 BasesSetVectorTy VisitedVBases;
3231 EnumerateVFPtrs(Context, ForClass, ClassLayout,
3232 BaseSubobject(ForClass, CharUnits::Zero()), 0,
3233 VFPtrInfo::BasePath(), VisitedVBases, Result);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00003234 if (Result.size() > 1) {
3235 for (unsigned I = 0, E = Result.size(); I != E; ++I)
3236 CalculatePathToMangle(ForClass, Result[I]);
3237 }
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003238}
3239
3240void MicrosoftVFTableContext::computeVTableRelatedInformation(
3241 const CXXRecordDecl *RD) {
3242 assert(RD->isDynamicClass());
3243
3244 // Check if we've computed this information before.
3245 if (VFPtrLocations.count(RD))
3246 return;
3247
3248 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3249
3250 VFPtrListTy &VFPtrs = VFPtrLocations[RD];
3251 EnumerateVFPtrs(Context, RD, VFPtrs);
3252
3253 MethodVFTableLocationsTy NewMethodLocations;
3254 for (VFPtrListTy::iterator I = VFPtrs.begin(), E = VFPtrs.end();
3255 I != E; ++I) {
3256 VFTableBuilder Builder(RD, *I);
3257
3258 VFTableIdTy id(RD, I->VFPtrFullOffset);
3259 assert(VFTableLayouts.count(id) == 0);
3260 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3261 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003262 VFTableLayouts[id] = new VTableLayout(
3263 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3264 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
3265 NewMethodLocations.insert(Builder.vtable_indices_begin(),
3266 Builder.vtable_indices_end());
3267 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3268 }
3269
3270 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3271 NewMethodLocations.end());
3272 if (Context.getLangOpts().DumpVTableLayouts)
3273 dumpMethodLocations(RD, NewMethodLocations, llvm::errs());
3274}
3275
3276void MicrosoftVFTableContext::dumpMethodLocations(
3277 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3278 raw_ostream &Out) {
3279 // Compute the vtable indices for all the member functions.
3280 // Store them in a map keyed by the location so we'll get a sorted table.
3281 std::map<MethodVFTableLocation, std::string> IndicesMap;
3282 bool HasNonzeroOffset = false;
3283
3284 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3285 E = NewMethods.end(); I != E; ++I) {
3286 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3287 assert(MD->isVirtual());
3288
3289 std::string MethodName = PredefinedExpr::ComputeName(
3290 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3291
3292 if (isa<CXXDestructorDecl>(MD)) {
3293 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3294 } else {
3295 IndicesMap[I->second] = MethodName;
3296 }
3297
3298 if (!I->second.VFTableOffset.isZero() || I->second.VBTableIndex != 0)
3299 HasNonzeroOffset = true;
3300 }
3301
3302 // Print the vtable indices for all the member functions.
3303 if (!IndicesMap.empty()) {
3304 Out << "VFTable indices for ";
3305 Out << "'" << RD->getQualifiedNameAsString();
3306 Out << "' (" << IndicesMap.size() << " entries).\n";
3307
3308 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3309 uint64_t LastVBIndex = 0;
3310 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3311 I = IndicesMap.begin(),
3312 E = IndicesMap.end();
3313 I != E; ++I) {
3314 CharUnits VFPtrOffset = I->first.VFTableOffset;
3315 uint64_t VBIndex = I->first.VBTableIndex;
3316 if (HasNonzeroOffset &&
3317 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3318 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3319 Out << " -- accessible via ";
3320 if (VBIndex)
3321 Out << "vbtable index " << VBIndex << ", ";
3322 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3323 LastVFPtrOffset = VFPtrOffset;
3324 LastVBIndex = VBIndex;
3325 }
3326
3327 uint64_t VTableIndex = I->first.Index;
3328 const std::string &MethodName = I->second;
3329 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3330 }
3331 Out << '\n';
3332 }
3333}
3334
3335const MicrosoftVFTableContext::VFPtrListTy &
3336MicrosoftVFTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
3337 computeVTableRelatedInformation(RD);
3338
3339 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
3340 return VFPtrLocations[RD];
3341}
3342
3343const VTableLayout &
3344MicrosoftVFTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3345 CharUnits VFPtrOffset) {
3346 computeVTableRelatedInformation(RD);
3347
3348 VFTableIdTy id(RD, VFPtrOffset);
3349 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3350 return *VFTableLayouts[id];
3351}
3352
3353const MicrosoftVFTableContext::MethodVFTableLocation &
3354MicrosoftVFTableContext::getMethodVFTableLocation(GlobalDecl GD) {
3355 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3356 "Only use this method for virtual methods or dtors");
3357 if (isa<CXXDestructorDecl>(GD.getDecl()))
3358 assert(GD.getDtorType() == Dtor_Deleting);
3359
3360 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3361 if (I != MethodVFTableLocations.end())
3362 return I->second;
3363
3364 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3365
3366 computeVTableRelatedInformation(RD);
3367
3368 I = MethodVFTableLocations.find(GD);
3369 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3370 return I->second;
3371}