blob: e0b737cd515698e513027f8a06b21694668c978e [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 Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000995 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
Peter Collingbourne24018462011-09-26 01:57:12 +0000996
997 LayoutVTable();
998
David Blaikie4e4d0842012-03-11 07:00:24 +0000999 if (Context.getLangOpts().DumpVTableLayouts)
Peter Collingbourne24018462011-09-26 01:57:12 +00001000 dumpLayout(llvm::errs());
1001 }
1002
1003 uint64_t getNumThunks() const {
1004 return Thunks.size();
1005 }
1006
1007 ThunksMapTy::const_iterator thunks_begin() const {
1008 return Thunks.begin();
1009 }
1010
1011 ThunksMapTy::const_iterator thunks_end() const {
1012 return Thunks.end();
1013 }
1014
1015 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1016 return VBaseOffsetOffsets;
1017 }
1018
1019 const AddressPointsMapTy &getAddressPoints() const {
1020 return AddressPoints;
1021 }
1022
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00001023 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1024 return MethodVTableIndices.begin();
1025 }
1026
1027 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1028 return MethodVTableIndices.end();
1029 }
1030
Peter Collingbourne24018462011-09-26 01:57:12 +00001031 /// getNumVTableComponents - Return the number of components in the vtable
1032 /// currently built.
1033 uint64_t getNumVTableComponents() const {
1034 return Components.size();
1035 }
1036
1037 const VTableComponent *vtable_component_begin() const {
1038 return Components.begin();
1039 }
1040
1041 const VTableComponent *vtable_component_end() const {
1042 return Components.end();
1043 }
1044
1045 AddressPointsMapTy::const_iterator address_points_begin() const {
1046 return AddressPoints.begin();
1047 }
1048
1049 AddressPointsMapTy::const_iterator address_points_end() const {
1050 return AddressPoints.end();
1051 }
1052
1053 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1054 return VTableThunks.begin();
1055 }
1056
1057 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1058 return VTableThunks.end();
1059 }
1060
1061 /// dumpLayout - Dump the vtable layout.
1062 void dumpLayout(raw_ostream&);
1063};
1064
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 Iskhodzhanov2cb17a02013-10-09 09:23:58 +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 return false;
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 Iskhodzhanov2cb17a02013-10-09 09:23:58 +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 Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002253
2254struct VTableThunksComparator {
2255 bool operator()(const VTableLayout::VTableThunkTy &LHS,
2256 const VTableLayout::VTableThunkTy &RHS) {
2257 if (LHS.first == RHS.first) {
2258 assert(LHS.second == RHS.second &&
2259 "Different thunks should have unique indices!");
2260 }
2261 return LHS.first < RHS.first;
2262 }
2263};
Peter Collingbourne24018462011-09-26 01:57:12 +00002264}
2265
2266VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2267 const VTableComponent *VTableComponents,
2268 uint64_t NumVTableThunks,
2269 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002270 const AddressPointsMapTy &AddressPoints,
2271 bool IsMicrosoftABI)
Peter Collingbourne24018462011-09-26 01:57:12 +00002272 : NumVTableComponents(NumVTableComponents),
2273 VTableComponents(new VTableComponent[NumVTableComponents]),
2274 NumVTableThunks(NumVTableThunks),
2275 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002276 AddressPoints(AddressPoints),
2277 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002278 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002279 this->VTableComponents.get());
2280 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2281 this->VTableThunks.get());
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002282 std::sort(this->VTableThunks.get(),
2283 this->VTableThunks.get() + NumVTableThunks,
2284 VTableThunksComparator());
Peter Collingbourne24018462011-09-26 01:57:12 +00002285}
2286
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002287VTableLayout::~VTableLayout() { }
Peter Collingbourne24018462011-09-26 01:57:12 +00002288
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002289VTableContext::VTableContext(ASTContext &Context)
Eli Friedman0a598fd2013-06-27 20:48:08 +00002290 : IsMicrosoftABI(Context.getTargetInfo().getCXXABI().isMicrosoft()) {
John McCallb8b2c9d2013-01-25 22:30:49 +00002291}
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002292
Peter Collingbourne24018462011-09-26 01:57:12 +00002293VTableContext::~VTableContext() {
2294 llvm::DeleteContainerSeconds(VTableLayouts);
2295}
2296
Peter Collingbourne24018462011-09-26 01:57:12 +00002297uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2298 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2299 if (I != MethodVTableIndices.end())
2300 return I->second;
2301
2302 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2303
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002304 computeVTableRelatedInformation(RD);
Peter Collingbourne24018462011-09-26 01:57:12 +00002305
2306 I = MethodVTableIndices.find(GD);
2307 assert(I != MethodVTableIndices.end() && "Did not find index!");
2308 return I->second;
2309}
2310
2311CharUnits
2312VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2313 const CXXRecordDecl *VBase) {
2314 ClassPairTy ClassPair(RD, VBase);
2315
2316 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2317 VirtualBaseClassOffsetOffsets.find(ClassPair);
2318 if (I != VirtualBaseClassOffsetOffsets.end())
2319 return I->second;
2320
2321 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2322 BaseSubobject(RD, CharUnits::Zero()),
2323 /*BaseIsVirtual=*/false,
2324 /*OffsetInLayoutClass=*/CharUnits::Zero());
2325
2326 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2327 Builder.getVBaseOffsetOffsets().begin(),
2328 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2329 // Insert all types.
2330 ClassPairTy ClassPair(RD, I->first);
2331
2332 VirtualBaseClassOffsetOffsets.insert(
2333 std::make_pair(ClassPair, I->second));
2334 }
2335
2336 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2337 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2338
2339 return I->second;
2340}
2341
2342static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2343 SmallVector<VTableLayout::VTableThunkTy, 1>
2344 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbourne24018462011-09-26 01:57:12 +00002345
2346 return new VTableLayout(Builder.getNumVTableComponents(),
2347 Builder.vtable_component_begin(),
2348 VTableThunks.size(),
2349 VTableThunks.data(),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002350 Builder.getAddressPoints(),
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002351 /*IsMicrosoftABI=*/false);
Peter Collingbourne24018462011-09-26 01:57:12 +00002352}
2353
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002354void VTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00002355 assert(!IsMicrosoftABI && "Shouldn't be called in this ABI!");
2356
Peter Collingbourne24018462011-09-26 01:57:12 +00002357 const VTableLayout *&Entry = VTableLayouts[RD];
2358
2359 // Check if we've computed this information before.
2360 if (Entry)
2361 return;
2362
2363 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2364 /*MostDerivedClassIsVirtual=*/0, RD);
2365 Entry = CreateVTableLayout(Builder);
2366
Timur Iskhodzhanov2aae5ba2013-06-05 14:05:50 +00002367 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2368 Builder.vtable_indices_end());
2369
Peter Collingbourne24018462011-09-26 01:57:12 +00002370 // Add the known thunks.
2371 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2372
2373 // If we don't have the vbase information for this class, insert it.
2374 // getVirtualBaseOffsetOffset will compute it separately without computing
2375 // the rest of the vtable related information.
2376 if (!RD->getNumVBases())
2377 return;
2378
Timur Iskhodzhanov432d4882013-07-02 16:00:40 +00002379 const CXXRecordDecl *VBase =
2380 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbourne24018462011-09-26 01:57:12 +00002381
2382 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2383 return;
2384
2385 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2386 Builder.getVBaseOffsetOffsets().begin(),
2387 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2388 // Insert all types.
2389 ClassPairTy ClassPair(RD, I->first);
2390
2391 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2392 }
2393}
2394
Peter Collingbourne24018462011-09-26 01:57:12 +00002395VTableLayout *VTableContext::createConstructionVTableLayout(
2396 const CXXRecordDecl *MostDerivedClass,
2397 CharUnits MostDerivedClassOffset,
2398 bool MostDerivedClassIsVirtual,
2399 const CXXRecordDecl *LayoutClass) {
2400 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2401 MostDerivedClassIsVirtual, LayoutClass);
2402 return CreateVTableLayout(Builder);
2403}
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002404
2405unsigned clang::GetVBTableIndex(const CXXRecordDecl *Derived,
2406 const CXXRecordDecl *VBase) {
2407 unsigned VBTableIndex = 1; // Start with one to skip the self entry.
2408 for (CXXRecordDecl::base_class_const_iterator I = Derived->vbases_begin(),
2409 E = Derived->vbases_end(); I != E; ++I) {
2410 if (I->getType()->getAsCXXRecordDecl() == VBase)
2411 return VBTableIndex;
2412 ++VBTableIndex;
2413 }
2414 llvm_unreachable("VBase must be a vbase of Derived");
2415}
2416
2417namespace {
2418
2419// Vtables in the Microsoft ABI are different from the Itanium ABI.
2420//
2421// The main differences are:
2422// 1. Separate vftable and vbtable.
2423//
2424// 2. Each subobject with a vfptr gets its own vftable rather than an address
2425// point in a single vtable shared between all the subobjects.
2426// Each vftable is represented by a separate section and virtual calls
2427// must be done using the vftable which has a slot for the function to be
2428// called.
2429//
2430// 3. Virtual method definitions expect their 'this' parameter to point to the
2431// first vfptr whose table provides a compatible overridden method. In many
2432// cases, this permits the original vf-table entry to directly call
2433// the method instead of passing through a thunk.
2434//
2435// A compatible overridden method is one which does not have a non-trivial
2436// covariant-return adjustment.
2437//
2438// The first vfptr is the one with the lowest offset in the complete-object
2439// layout of the defining class, and the method definition will subtract
2440// that constant offset from the parameter value to get the real 'this'
2441// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2442// function defined in a virtual base is overridden in a more derived
2443// virtual base and these bases have a reverse order in the complete
2444// object), the vf-table may require a this-adjustment thunk.
2445//
2446// 4. vftables do not contain new entries for overrides that merely require
2447// this-adjustment. Together with #3, this keeps vf-tables smaller and
2448// eliminates the need for this-adjustment thunks in many cases, at the cost
2449// of often requiring redundant work to adjust the "this" pointer.
2450//
2451// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2452// Vtordisps are emitted into the class layout if a class has
2453// a) a user-defined ctor/dtor
2454// and
2455// b) a method overriding a method in a virtual base.
2456
2457class VFTableBuilder {
2458public:
2459 typedef MicrosoftVFTableContext::MethodVFTableLocation MethodVFTableLocation;
2460
2461 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2462 MethodVFTableLocationsTy;
2463
2464private:
2465 /// Context - The ASTContext which we will use for layout information.
2466 ASTContext &Context;
2467
2468 /// MostDerivedClass - The most derived class for which we're building this
2469 /// vtable.
2470 const CXXRecordDecl *MostDerivedClass;
2471
2472 const ASTRecordLayout &MostDerivedClassLayout;
2473
2474 VFPtrInfo WhichVFPtr;
2475
2476 /// FinalOverriders - The final overriders of the most derived class.
2477 const FinalOverriders Overriders;
2478
2479 /// Components - The components of the vftable being built.
2480 SmallVector<VTableComponent, 64> Components;
2481
2482 MethodVFTableLocationsTy MethodVFTableLocations;
2483
2484 /// MethodInfo - Contains information about a method in a vtable.
2485 /// (Used for computing 'this' pointer adjustment thunks.
2486 struct MethodInfo {
2487 /// VBTableIndex - The nonzero index in the vbtable that
2488 /// this method's base has, or zero.
2489 const uint64_t VBTableIndex;
2490
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002491 /// VBase - If nonnull, holds the last vbase which contains the vfptr that
2492 /// the method definition is adjusted to.
2493 const CXXRecordDecl *VBase;
2494
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002495 /// VFTableIndex - The index in the vftable that this method has.
2496 const uint64_t VFTableIndex;
2497
2498 /// Shadowed - Indicates if this vftable slot is shadowed by
2499 /// a slot for a covariant-return override. If so, it shouldn't be printed
2500 /// or used for vcalls in the most derived class.
2501 bool Shadowed;
2502
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002503 MethodInfo(uint64_t VBTableIndex, const CXXRecordDecl *VBase,
2504 uint64_t VFTableIndex)
2505 : VBTableIndex(VBTableIndex), VBase(VBase), VFTableIndex(VFTableIndex),
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002506 Shadowed(false) {}
2507
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002508 MethodInfo()
2509 : VBTableIndex(0), VBase(0), VFTableIndex(0), Shadowed(false) {}
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002510 };
2511
2512 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2513
2514 /// MethodInfoMap - The information for all methods in the vftable we're
2515 /// currently building.
2516 MethodInfoMapTy MethodInfoMap;
2517
2518 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2519
2520 /// VTableThunks - The thunks by vftable index in the vftable currently being
2521 /// built.
2522 VTableThunksMapTy VTableThunks;
2523
2524 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2525 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2526
2527 /// Thunks - A map that contains all the thunks needed for all methods in the
2528 /// most derived class for which the vftable is currently being built.
2529 ThunksMapTy Thunks;
2530
2531 /// AddThunk - Add a thunk for the given method.
2532 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2533 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2534
2535 // Check if we have this thunk already.
2536 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2537 ThunksVector.end())
2538 return;
2539
2540 ThunksVector.push_back(Thunk);
2541 }
2542
2543 /// ComputeThisOffset - Returns the 'this' argument offset for the given
2544 /// method in the given subobject, relative to the beginning of the
2545 /// MostDerivedClass.
2546 CharUnits ComputeThisOffset(const CXXMethodDecl *MD,
2547 BaseSubobject Base,
2548 FinalOverriders::OverriderInfo Overrider);
2549
2550 /// AddMethod - Add a single virtual member function to the vftable
2551 /// components vector.
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002552 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002553 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002554 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002555 "Destructor can't have return adjustment!");
2556 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2557 } else {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002558 if (!TI.isEmpty())
2559 VTableThunks[Components.size()] = TI;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002560 Components.push_back(VTableComponent::MakeFunction(MD));
2561 }
2562 }
2563
2564 /// AddMethods - Add the methods of this base subobject and the relevant
2565 /// subbases to the vftable we're currently laying out.
2566 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2567 const CXXRecordDecl *LastVBase,
2568 BasesSetVectorTy &VisitedBases);
2569
2570 void LayoutVFTable() {
2571 // FIXME: add support for RTTI when we have proper LLVM support for symbols
2572 // pointing to the middle of a section.
2573
2574 BasesSetVectorTy VisitedBases;
2575 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, 0,
2576 VisitedBases);
2577
2578 assert(MethodVFTableLocations.empty());
2579 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2580 E = MethodInfoMap.end(); I != E; ++I) {
2581 const CXXMethodDecl *MD = I->first;
2582 const MethodInfo &MI = I->second;
2583 // Skip the methods that the MostDerivedClass didn't override
2584 // and the entries shadowed by return adjusting thunks.
2585 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2586 continue;
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002587 MethodVFTableLocation Loc(MI.VBTableIndex, MI.VBase,
2588 WhichVFPtr.VFPtrOffset, MI.VFTableIndex);
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002589 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2590 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2591 } else {
2592 MethodVFTableLocations[MD] = Loc;
2593 }
2594 }
2595 }
2596
2597 void ErrorUnsupported(StringRef Feature, SourceLocation Location) {
2598 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2599 unsigned DiagID = Diags.getCustomDiagID(
2600 DiagnosticsEngine::Error, "v-table layout for %0 is not supported yet");
2601 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2602 }
2603
2604public:
2605 VFTableBuilder(const CXXRecordDecl *MostDerivedClass, VFPtrInfo Which)
2606 : Context(MostDerivedClass->getASTContext()),
2607 MostDerivedClass(MostDerivedClass),
2608 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
2609 WhichVFPtr(Which),
2610 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2611 LayoutVFTable();
2612
2613 if (Context.getLangOpts().DumpVTableLayouts)
2614 dumpLayout(llvm::errs());
2615 }
2616
2617 uint64_t getNumThunks() const { return Thunks.size(); }
2618
2619 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2620
2621 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2622
2623 MethodVFTableLocationsTy::const_iterator vtable_indices_begin() const {
2624 return MethodVFTableLocations.begin();
2625 }
2626
2627 MethodVFTableLocationsTy::const_iterator vtable_indices_end() const {
2628 return MethodVFTableLocations.end();
2629 }
2630
2631 uint64_t getNumVTableComponents() const { return Components.size(); }
2632
2633 const VTableComponent *vtable_component_begin() const {
2634 return Components.begin();
2635 }
2636
2637 const VTableComponent *vtable_component_end() const {
2638 return Components.end();
2639 }
2640
2641 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2642 return VTableThunks.begin();
2643 }
2644
2645 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2646 return VTableThunks.end();
2647 }
2648
2649 void dumpLayout(raw_ostream &);
2650};
2651
2652/// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2653/// that define the given method.
2654struct InitialOverriddenDefinitionCollector {
2655 BasesSetVectorTy Bases;
2656 OverriddenMethodsSetTy VisitedOverriddenMethods;
2657
2658 bool visit(const CXXMethodDecl *OverriddenMD) {
2659 if (OverriddenMD->size_overridden_methods() == 0)
2660 Bases.insert(OverriddenMD->getParent());
2661 // Don't recurse on this method if we've already collected it.
2662 return VisitedOverriddenMethods.insert(OverriddenMD);
2663 }
2664};
2665
2666static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2667 CXXBasePath &Path, void *BasesSet) {
2668 BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2669 return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2670}
2671
2672CharUnits
2673VFTableBuilder::ComputeThisOffset(const CXXMethodDecl *MD,
2674 BaseSubobject Base,
2675 FinalOverriders::OverriderInfo Overrider) {
2676 // Complete object virtual destructors are always emitted in the most derived
2677 // class, thus don't have this offset.
2678 if (isa<CXXDestructorDecl>(MD))
2679 return CharUnits();
2680
2681 InitialOverriddenDefinitionCollector Collector;
2682 visitAllOverriddenMethods(MD, Collector);
2683
2684 CXXBasePaths Paths;
2685 Base.getBase()->lookupInBases(BaseInSet, &Collector.Bases, Paths);
2686
2687 // This will hold the smallest this offset among overridees of MD.
2688 // This implies that an offset of a non-virtual base will dominate an offset
2689 // of a virtual base to potentially reduce the number of thunks required
2690 // in the derived classes that inherit this method.
2691 CharUnits Ret;
2692 bool First = true;
2693
2694 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2695 I != E; ++I) {
2696 const CXXBasePath &Path = (*I);
2697 CharUnits ThisOffset = Base.getBaseOffset();
2698
2699 // For each path from the overrider to the parents of the overridden methods,
2700 // traverse the path, calculating the this offset in the most derived class.
2701 for (int J = 0, F = Path.size(); J != F; ++J) {
2702 const CXXBasePathElement &Element = Path[J];
2703 QualType CurTy = Element.Base->getType();
2704 const CXXRecordDecl *PrevRD = Element.Class,
2705 *CurRD = CurTy->getAsCXXRecordDecl();
2706 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2707
2708 if (Element.Base->isVirtual()) {
2709 if (Overrider.Method->getParent() == PrevRD) {
2710 // This one's interesting. If the final overrider is in a vbase B of the
2711 // most derived class and it overrides a method of the B's own vbase A,
2712 // it uses A* as "this". In its prologue, it can cast A* to B* with
2713 // a static offset. This offset is used regardless of the actual
2714 // offset of A from B in the most derived class, requiring an
2715 // this-adjusting thunk in the vftable if A and B are laid out
2716 // differently in the most derived class.
2717 ThisOffset += Layout.getVBaseClassOffset(CurRD);
2718 } else {
2719 ThisOffset = MostDerivedClassLayout.getVBaseClassOffset(CurRD);
2720 }
2721 } else {
2722 ThisOffset += Layout.getBaseClassOffset(CurRD);
2723 }
2724 }
2725
2726 if (Ret > ThisOffset || First) {
2727 First = false;
2728 Ret = ThisOffset;
2729 }
2730 }
2731
2732 assert(!First && "Method not found in the given subobject?");
2733 return Ret;
2734}
2735
2736static const CXXMethodDecl*
2737FindDirectlyOverriddenMethodInBases(const CXXMethodDecl *MD,
2738 BasesSetVectorTy &Bases) {
2739 // We can't just iterate over the overridden methods and return the first one
2740 // which has its parent in Bases, e.g. this doesn't work when we have
2741 // multiple subobjects of the same type that have its virtual function
2742 // overridden.
2743 for (int I = Bases.size(), E = 0; I != E; --I) {
2744 const CXXRecordDecl *CurrentBase = Bases[I - 1];
2745
2746 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2747 E = MD->end_overridden_methods(); I != E; ++I) {
2748 const CXXMethodDecl *OverriddenMD = *I;
2749
2750 if (OverriddenMD->getParent() == CurrentBase)
2751 return OverriddenMD;
2752 }
2753 }
2754
2755 return 0;
2756}
2757
Timur Iskhodzhanovcbf8dde2013-10-06 15:31:37 +00002758static void GroupNewVirtualOverloads(
2759 const CXXRecordDecl *RD,
2760 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2761 // Put the virtual methods into VirtualMethods in the proper order:
2762 // 1) Group overloads by declaration name. New groups are added to the
2763 // vftable in the order of their first declarations in this class
2764 // (including overrides).
2765 // 2) In each group, new overloads appear in the reverse order of declaration.
2766 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2767 SmallVector<MethodGroup, 10> Groups;
2768 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2769 VisitedGroupIndicesTy VisitedGroupIndices;
2770 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2771 E = RD->method_end(); I != E; ++I) {
2772 const CXXMethodDecl *MD = *I;
2773 if (!MD->isVirtual())
2774 continue;
2775
2776 VisitedGroupIndicesTy::iterator J;
2777 bool Inserted;
2778 llvm::tie(J, Inserted) = VisitedGroupIndices.insert(
2779 std::make_pair(MD->getDeclName(), Groups.size()));
2780 if (Inserted)
2781 Groups.push_back(MethodGroup(1, MD));
2782 else
2783 Groups[J->second].push_back(MD);
2784 }
2785
2786 for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2787 VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2788}
2789
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002790void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2791 const CXXRecordDecl *LastVBase,
2792 BasesSetVectorTy &VisitedBases) {
2793 const CXXRecordDecl *RD = Base.getBase();
2794 if (!RD->isPolymorphic())
2795 return;
2796
2797 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2798
2799 // See if this class expands a vftable of the base we look at, which is either
2800 // the one defined by the vfptr base path or the primary base of the current class.
2801 const CXXRecordDecl *NextBase = 0, *NextLastVBase = LastVBase;
2802 CharUnits NextBaseOffset;
2803 if (BaseDepth < WhichVFPtr.PathToBaseWithVFPtr.size()) {
2804 NextBase = WhichVFPtr.PathToBaseWithVFPtr[BaseDepth];
2805 if (Layout.getVBaseOffsetsMap().count(NextBase)) {
2806 NextLastVBase = NextBase;
2807 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2808 } else {
2809 NextBaseOffset =
2810 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2811 }
2812 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2813 assert(!Layout.isPrimaryBaseVirtual() &&
2814 "No primary virtual bases in this ABI");
2815 NextBase = PrimaryBase;
2816 NextBaseOffset = Base.getBaseOffset();
2817 }
2818
2819 if (NextBase) {
2820 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2821 NextLastVBase, VisitedBases);
2822 if (!VisitedBases.insert(NextBase))
2823 llvm_unreachable("Found a duplicate primary base!");
2824 }
2825
Timur Iskhodzhanovcbf8dde2013-10-06 15:31:37 +00002826 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2827 // Put virtual methods in the proper order.
2828 GroupNewVirtualOverloads(RD, VirtualMethods);
2829
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002830 // Now go through all virtual member functions and add them to the current
2831 // vftable. This is done by
2832 // - replacing overridden methods in their existing slots, as long as they
2833 // don't require return adjustment; calculating This adjustment if needed.
2834 // - adding new slots for methods of the current base not present in any
2835 // sub-bases;
2836 // - adding new slots for methods that require Return adjustment.
2837 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Timur Iskhodzhanovcbf8dde2013-10-06 15:31:37 +00002838 for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
2839 const CXXMethodDecl *MD = VirtualMethods[I];
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002840
2841 FinalOverriders::OverriderInfo Overrider =
2842 Overriders.getOverrider(MD, Base.getBaseOffset());
2843 ThisAdjustment ThisAdjustmentOffset;
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002844 bool ForceThunk = false;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002845
2846 // Check if this virtual member function overrides
2847 // a method in one of the visited bases.
2848 if (const CXXMethodDecl *OverriddenMD =
2849 FindDirectlyOverriddenMethodInBases(MD, VisitedBases)) {
2850 MethodInfoMapTy::iterator OverriddenMDIterator =
2851 MethodInfoMap.find(OverriddenMD);
2852
2853 // If the overridden method went to a different vftable, skip it.
2854 if (OverriddenMDIterator == MethodInfoMap.end())
2855 continue;
2856
2857 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2858
2859 // Create a this-adjusting thunk if needed.
2860 CharUnits TI = ComputeThisOffset(MD, Base, Overrider);
2861 if (TI != WhichVFPtr.VFPtrFullOffset) {
2862 ThisAdjustmentOffset.NonVirtual =
2863 (TI - WhichVFPtr.VFPtrFullOffset).getQuantity();
2864 VTableThunks[OverriddenMethodInfo.VFTableIndex].This =
2865 ThisAdjustmentOffset;
2866 AddThunk(MD, VTableThunks[OverriddenMethodInfo.VFTableIndex]);
2867 }
2868
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002869 if (MD->getResultType() == OverriddenMD->getResultType()) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002870 // No return adjustment needed - just replace the overridden method info
2871 // with the current info.
2872 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002873 OverriddenMethodInfo.VBase,
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002874 OverriddenMethodInfo.VFTableIndex);
2875 MethodInfoMap.erase(OverriddenMDIterator);
2876
2877 assert(!MethodInfoMap.count(MD) &&
2878 "Should not have method info for this method yet!");
2879 MethodInfoMap.insert(std::make_pair(MD, MI));
2880 continue;
2881 } else {
2882 // In case we need a return adjustment, we'll add a new slot for
2883 // the overrider and put a return-adjusting thunk where the overridden
2884 // method was in the vftable.
2885 // For now, just mark the overriden method as shadowed by a new slot.
2886 OverriddenMethodInfo.Shadowed = true;
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002887 ForceThunk = true;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002888
2889 // Also apply this adjustment to the shadowed slots.
2890 if (!ThisAdjustmentOffset.isEmpty()) {
2891 // FIXME: this is O(N^2), can be O(N).
2892 const CXXMethodDecl *SubOverride = OverriddenMD;
2893 while ((SubOverride =
2894 FindDirectlyOverriddenMethodInBases(SubOverride, VisitedBases))) {
2895 MethodInfoMapTy::iterator SubOverrideIterator =
2896 MethodInfoMap.find(SubOverride);
2897 if (SubOverrideIterator == MethodInfoMap.end())
2898 break;
2899 MethodInfo &SubOverrideMI = SubOverrideIterator->second;
2900 assert(SubOverrideMI.Shadowed);
2901 VTableThunks[SubOverrideMI.VFTableIndex].This =
2902 ThisAdjustmentOffset;
2903 AddThunk(MD, VTableThunks[SubOverrideMI.VFTableIndex]);
2904 }
2905 }
2906 }
2907 } else if (Base.getBaseOffset() != WhichVFPtr.VFPtrFullOffset ||
2908 MD->size_overridden_methods()) {
2909 // Skip methods that don't belong to the vftable of the current class,
2910 // e.g. each method that wasn't seen in any of the visited sub-bases
2911 // but overrides multiple methods of other sub-bases.
2912 continue;
2913 }
2914
2915 // If we got here, MD is a method not seen in any of the sub-bases or
2916 // it requires return adjustment. Insert the method info for this method.
2917 unsigned VBIndex =
2918 LastVBase ? GetVBTableIndex(MostDerivedClass, LastVBase) : 0;
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002919 MethodInfo MI(VBIndex, LastVBase, Components.size());
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002920
2921 assert(!MethodInfoMap.count(MD) &&
2922 "Should not have method info for this method yet!");
2923 MethodInfoMap.insert(std::make_pair(MD, MI));
2924
2925 const CXXMethodDecl *OverriderMD = Overrider.Method;
2926
2927 // Check if this overrider needs a return adjustment.
2928 // We don't want to do this for pure virtual member functions.
2929 BaseOffset ReturnAdjustmentOffset;
2930 ReturnAdjustment ReturnAdjustment;
2931 if (!OverriderMD->isPure()) {
2932 ReturnAdjustmentOffset =
2933 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
2934 }
2935 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002936 ForceThunk = true;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002937 ReturnAdjustment.NonVirtual =
2938 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
2939 if (ReturnAdjustmentOffset.VirtualBase) {
2940 // FIXME: We might want to create a VBIndex alias for VBaseOffsetOffset
2941 // in the ReturnAdjustment struct.
2942 ReturnAdjustment.VBaseOffsetOffset =
2943 GetVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
2944 ReturnAdjustmentOffset.VirtualBase);
2945 }
2946 }
2947
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002948 AddMethod(OverriderMD, ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
2949 ForceThunk ? MD : 0));
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002950 }
2951}
2952
2953void PrintBasePath(const VFPtrInfo::BasePath &Path, raw_ostream &Out) {
2954 for (VFPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
2955 E = Path.rend(); I != E; ++I) {
2956 Out << "'" << (*I)->getQualifiedNameAsString() << "' in ";
2957 }
2958}
2959
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00002960struct MicrosoftThunkInfoStableSortComparator {
2961 bool operator() (const ThunkInfo &LHS, const ThunkInfo &RHS) {
2962 if (LHS.This != RHS.This)
2963 return LHS.This < RHS.This;
2964
2965 if (LHS.Return != RHS.Return)
2966 return LHS.Return < RHS.Return;
2967
2968 // Keep different thunks with the same adjustments in the order they
2969 // were put into the vector.
2970 return false;
2971 }
2972};
2973
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00002974void VFTableBuilder::dumpLayout(raw_ostream &Out) {
2975 Out << "VFTable for ";
2976 PrintBasePath(WhichVFPtr.PathToBaseWithVFPtr, Out);
2977 Out << "'" << MostDerivedClass->getQualifiedNameAsString();
2978 Out << "' (" << Components.size() << " entries).\n";
2979
2980 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
2981 Out << llvm::format("%4d | ", I);
2982
2983 const VTableComponent &Component = Components[I];
2984
2985 // Dump the component.
2986 switch (Component.getKind()) {
2987 case VTableComponent::CK_RTTI:
2988 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
2989 break;
2990
2991 case VTableComponent::CK_FunctionPointer: {
2992 const CXXMethodDecl *MD = Component.getFunctionDecl();
2993
2994 std::string Str = PredefinedExpr::ComputeName(
2995 PredefinedExpr::PrettyFunctionNoVirtual, MD);
2996 Out << Str;
2997 if (MD->isPure())
2998 Out << " [pure]";
2999
3000 if (MD->isDeleted()) {
3001 ErrorUnsupported("deleted methods", MD->getLocation());
3002 Out << " [deleted]";
3003 }
3004
3005 ThunkInfo Thunk = VTableThunks.lookup(I);
3006 if (!Thunk.isEmpty()) {
3007 // If this function pointer has a return adjustment, dump it.
3008 if (!Thunk.Return.isEmpty()) {
3009 Out << "\n [return adjustment: ";
3010 if (Thunk.Return.VBaseOffsetOffset)
3011 Out << "vbase #" << Thunk.Return.VBaseOffsetOffset << ", ";
3012 Out << Thunk.Return.NonVirtual << " non-virtual]";
3013 }
3014
3015 // If this function pointer has a 'this' pointer adjustment, dump it.
3016 if (!Thunk.This.isEmpty()) {
3017 assert(!Thunk.This.VCallOffsetOffset &&
3018 "No virtual this adjustment in this ABI");
3019 Out << "\n [this adjustment: " << Thunk.This.NonVirtual
3020 << " non-virtual]";
3021 }
3022 }
3023
3024 break;
3025 }
3026
3027 case VTableComponent::CK_DeletingDtorPointer: {
3028 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3029
3030 Out << DD->getQualifiedNameAsString();
3031 Out << "() [scalar deleting]";
3032
3033 if (DD->isPure())
3034 Out << " [pure]";
3035
3036 ThunkInfo Thunk = VTableThunks.lookup(I);
3037 if (!Thunk.isEmpty()) {
3038 assert(Thunk.Return.isEmpty() &&
3039 "No return adjustment needed for destructors!");
3040 // If this destructor has a 'this' pointer adjustment, dump it.
3041 if (!Thunk.This.isEmpty()) {
3042 assert(!Thunk.This.VCallOffsetOffset &&
3043 "No virtual this adjustment in this ABI");
3044 Out << "\n [this adjustment: " << Thunk.This.NonVirtual
3045 << " non-virtual]";
3046 }
3047 }
3048
3049 break;
3050 }
3051
3052 default:
3053 DiagnosticsEngine &Diags = Context.getDiagnostics();
3054 unsigned DiagID = Diags.getCustomDiagID(
3055 DiagnosticsEngine::Error,
3056 "Unexpected vftable component type %0 for component number %1");
3057 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3058 << I << Component.getKind();
3059 }
3060
3061 Out << '\n';
3062 }
3063
3064 Out << '\n';
3065
3066 if (!Thunks.empty()) {
3067 // We store the method names in a map to get a stable order.
3068 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3069
3070 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3071 I != E; ++I) {
3072 const CXXMethodDecl *MD = I->first;
3073 std::string MethodName = PredefinedExpr::ComputeName(
3074 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3075
3076 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3077 }
3078
3079 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3080 I = MethodNamesAndDecls.begin(),
3081 E = MethodNamesAndDecls.end();
3082 I != E; ++I) {
3083 const std::string &MethodName = I->first;
3084 const CXXMethodDecl *MD = I->second;
3085
3086 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +00003087 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
3088 MicrosoftThunkInfoStableSortComparator());
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003089
3090 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3091 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3092
3093 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3094 const ThunkInfo &Thunk = ThunksVector[I];
3095
3096 Out << llvm::format("%4d | ", I);
3097
3098 // If this function pointer has a return pointer adjustment, dump it.
3099 if (!Thunk.Return.isEmpty()) {
3100 Out << "return adjustment: ";
3101 if (Thunk.Return.VBaseOffsetOffset)
3102 Out << "vbase #" << Thunk.Return.VBaseOffsetOffset << ", ";
3103 Out << Thunk.Return.NonVirtual << " non-virtual";
3104
3105 if (!Thunk.This.isEmpty())
3106 Out << "\n ";
3107 }
3108
3109 // If this function pointer has a 'this' pointer adjustment, dump it.
3110 if (!Thunk.This.isEmpty()) {
3111 assert(!Thunk.This.VCallOffsetOffset &&
3112 "No virtual this adjustment in this ABI");
3113 Out << "this adjustment: ";
3114 Out << Thunk.This.NonVirtual << " non-virtual";
3115 }
3116
3117 Out << '\n';
3118 }
3119
3120 Out << '\n';
3121 }
3122 }
3123}
3124}
3125
3126static void EnumerateVFPtrs(
3127 ASTContext &Context, const CXXRecordDecl *MostDerivedClass,
3128 const ASTRecordLayout &MostDerivedClassLayout,
3129 BaseSubobject Base, const CXXRecordDecl *LastVBase,
3130 const VFPtrInfo::BasePath &PathFromCompleteClass,
3131 BasesSetVectorTy &VisitedVBases,
3132 MicrosoftVFTableContext::VFPtrListTy &Result) {
3133 const CXXRecordDecl *CurrentClass = Base.getBase();
3134 CharUnits OffsetInCompleteClass = Base.getBaseOffset();
3135 const ASTRecordLayout &CurrentClassLayout =
3136 Context.getASTRecordLayout(CurrentClass);
3137
3138 if (CurrentClassLayout.hasOwnVFPtr()) {
3139 if (LastVBase) {
3140 uint64_t VBIndex = GetVBTableIndex(MostDerivedClass, LastVBase);
3141 assert(VBIndex > 0 && "vbases must have vbindex!");
3142 CharUnits VFPtrOffset =
3143 OffsetInCompleteClass -
3144 MostDerivedClassLayout.getVBaseClassOffset(LastVBase);
3145 Result.push_back(VFPtrInfo(VBIndex, LastVBase, VFPtrOffset,
3146 PathFromCompleteClass, OffsetInCompleteClass));
3147 } else {
3148 Result.push_back(VFPtrInfo(OffsetInCompleteClass, PathFromCompleteClass));
3149 }
3150 }
3151
3152 for (CXXRecordDecl::base_class_const_iterator I = CurrentClass->bases_begin(),
3153 E = CurrentClass->bases_end(); I != E; ++I) {
3154 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
3155
3156 CharUnits NextBaseOffset;
3157 const CXXRecordDecl *NextLastVBase;
3158 if (I->isVirtual()) {
3159 if (VisitedVBases.count(BaseDecl))
3160 continue;
3161 VisitedVBases.insert(BaseDecl);
3162 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
3163 NextLastVBase = BaseDecl;
3164 } else {
3165 NextBaseOffset = OffsetInCompleteClass +
3166 CurrentClassLayout.getBaseClassOffset(BaseDecl);
3167 NextLastVBase = LastVBase;
3168 }
3169
3170 VFPtrInfo::BasePath NewPath = PathFromCompleteClass;
3171 NewPath.push_back(BaseDecl);
3172 BaseSubobject NextBase(BaseDecl, NextBaseOffset);
3173
3174 EnumerateVFPtrs(Context, MostDerivedClass, MostDerivedClassLayout, NextBase,
3175 NextLastVBase, NewPath, VisitedVBases, Result);
3176 }
3177}
3178
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00003179/// CalculatePathToMangle - Calculate the subset of records that should be used
3180/// to mangle the vftable for the given vfptr.
3181/// Should only be called if a class has multiple vftables.
3182static void
3183CalculatePathToMangle(const CXXRecordDecl *RD, VFPtrInfo &VFPtr) {
3184 // FIXME: In some rare cases this code produces a slightly incorrect mangling.
3185 // It's very likely that the vbtable mangling code can be adjusted to mangle
3186 // both vftables and vbtables correctly.
3187
3188 VFPtrInfo::BasePath &FullPath = VFPtr.PathToBaseWithVFPtr;
3189 if (FullPath.empty()) {
3190 // Mangle the class's own vftable.
3191 assert(RD->getNumVBases() &&
3192 "Something's wrong: if the most derived "
3193 "class has more than one vftable, it can only have its own "
3194 "vftable if it has vbases");
3195 VFPtr.PathToMangle.push_back(RD);
3196 return;
3197 }
3198
3199 unsigned Begin = 0;
3200
3201 // First, skip all the bases before the vbase.
3202 if (VFPtr.LastVBase) {
3203 while (FullPath[Begin] != VFPtr.LastVBase) {
3204 Begin++;
3205 assert(Begin < FullPath.size());
3206 }
3207 }
3208
3209 // Then, put the rest of the base path in the reverse order.
3210 for (unsigned I = FullPath.size(); I != Begin; --I) {
3211 const CXXRecordDecl *CurBase = FullPath[I - 1],
3212 *ItsBase = (I == 1) ? RD : FullPath[I - 2];
3213 bool BaseIsVirtual = false;
3214 for (CXXRecordDecl::base_class_const_iterator J = ItsBase->bases_begin(),
3215 F = ItsBase->bases_end(); J != F; ++J) {
3216 if (J->getType()->getAsCXXRecordDecl() == CurBase) {
3217 BaseIsVirtual = J->isVirtual();
3218 break;
3219 }
3220 }
3221
3222 // Should skip the current base if it is a non-virtual base with no siblings.
3223 if (BaseIsVirtual || ItsBase->getNumBases() != 1)
3224 VFPtr.PathToMangle.push_back(CurBase);
3225 }
3226}
3227
Benjamin Kramer3b142da2013-08-01 11:08:06 +00003228static void EnumerateVFPtrs(ASTContext &Context, const CXXRecordDecl *ForClass,
3229 MicrosoftVFTableContext::VFPtrListTy &Result) {
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003230 Result.clear();
3231 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(ForClass);
3232 BasesSetVectorTy VisitedVBases;
3233 EnumerateVFPtrs(Context, ForClass, ClassLayout,
3234 BaseSubobject(ForClass, CharUnits::Zero()), 0,
3235 VFPtrInfo::BasePath(), VisitedVBases, Result);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +00003236 if (Result.size() > 1) {
3237 for (unsigned I = 0, E = Result.size(); I != E; ++I)
3238 CalculatePathToMangle(ForClass, Result[I]);
3239 }
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003240}
3241
3242void MicrosoftVFTableContext::computeVTableRelatedInformation(
3243 const CXXRecordDecl *RD) {
3244 assert(RD->isDynamicClass());
3245
3246 // Check if we've computed this information before.
3247 if (VFPtrLocations.count(RD))
3248 return;
3249
3250 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3251
3252 VFPtrListTy &VFPtrs = VFPtrLocations[RD];
3253 EnumerateVFPtrs(Context, RD, VFPtrs);
3254
3255 MethodVFTableLocationsTy NewMethodLocations;
3256 for (VFPtrListTy::iterator I = VFPtrs.begin(), E = VFPtrs.end();
3257 I != E; ++I) {
3258 VFTableBuilder Builder(RD, *I);
3259
3260 VFTableIdTy id(RD, I->VFPtrFullOffset);
3261 assert(VFTableLayouts.count(id) == 0);
3262 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3263 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Timur Iskhodzhanov635de282013-07-30 09:46:19 +00003264 VFTableLayouts[id] = new VTableLayout(
3265 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3266 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
3267 NewMethodLocations.insert(Builder.vtable_indices_begin(),
3268 Builder.vtable_indices_end());
3269 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3270 }
3271
3272 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3273 NewMethodLocations.end());
3274 if (Context.getLangOpts().DumpVTableLayouts)
3275 dumpMethodLocations(RD, NewMethodLocations, llvm::errs());
3276}
3277
3278void MicrosoftVFTableContext::dumpMethodLocations(
3279 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3280 raw_ostream &Out) {
3281 // Compute the vtable indices for all the member functions.
3282 // Store them in a map keyed by the location so we'll get a sorted table.
3283 std::map<MethodVFTableLocation, std::string> IndicesMap;
3284 bool HasNonzeroOffset = false;
3285
3286 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3287 E = NewMethods.end(); I != E; ++I) {
3288 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3289 assert(MD->isVirtual());
3290
3291 std::string MethodName = PredefinedExpr::ComputeName(
3292 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3293
3294 if (isa<CXXDestructorDecl>(MD)) {
3295 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3296 } else {
3297 IndicesMap[I->second] = MethodName;
3298 }
3299
3300 if (!I->second.VFTableOffset.isZero() || I->second.VBTableIndex != 0)
3301 HasNonzeroOffset = true;
3302 }
3303
3304 // Print the vtable indices for all the member functions.
3305 if (!IndicesMap.empty()) {
3306 Out << "VFTable indices for ";
3307 Out << "'" << RD->getQualifiedNameAsString();
3308 Out << "' (" << IndicesMap.size() << " entries).\n";
3309
3310 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3311 uint64_t LastVBIndex = 0;
3312 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3313 I = IndicesMap.begin(),
3314 E = IndicesMap.end();
3315 I != E; ++I) {
3316 CharUnits VFPtrOffset = I->first.VFTableOffset;
3317 uint64_t VBIndex = I->first.VBTableIndex;
3318 if (HasNonzeroOffset &&
3319 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3320 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3321 Out << " -- accessible via ";
3322 if (VBIndex)
3323 Out << "vbtable index " << VBIndex << ", ";
3324 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3325 LastVFPtrOffset = VFPtrOffset;
3326 LastVBIndex = VBIndex;
3327 }
3328
3329 uint64_t VTableIndex = I->first.Index;
3330 const std::string &MethodName = I->second;
3331 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3332 }
3333 Out << '\n';
3334 }
3335}
3336
3337const MicrosoftVFTableContext::VFPtrListTy &
3338MicrosoftVFTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
3339 computeVTableRelatedInformation(RD);
3340
3341 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
3342 return VFPtrLocations[RD];
3343}
3344
3345const VTableLayout &
3346MicrosoftVFTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3347 CharUnits VFPtrOffset) {
3348 computeVTableRelatedInformation(RD);
3349
3350 VFTableIdTy id(RD, VFPtrOffset);
3351 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3352 return *VFTableLayouts[id];
3353}
3354
3355const MicrosoftVFTableContext::MethodVFTableLocation &
3356MicrosoftVFTableContext::getMethodVFTableLocation(GlobalDecl GD) {
3357 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3358 "Only use this method for virtual methods or dtors");
3359 if (isa<CXXDestructorDecl>(GD.getDecl()))
3360 assert(GD.getDtorType() == Dtor_Deleting);
3361
3362 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3363 if (I != MethodVFTableLocations.end())
3364 return I->second;
3365
3366 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3367
3368 computeVTableRelatedInformation(RD);
3369
3370 I = MethodVFTableLocations.find(GD);
3371 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3372 return I->second;
3373}