blob: 4f28c77b7585b6041c14a765c9246e319180f002 [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
66 /// Offset - the base offset of the overrider in the layout class.
67 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 Iskhodzhanov2fca8022013-05-08 08:09:21 +0000227 VirtualBase =
Peter Collingbourne24018462011-09-26 01:57:12 +0000228 cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
Timur Iskhodzhanov2fca8022013-05-08 08:09:21 +0000229 break;
Peter Collingbourne24018462011-09-26 01:57:12 +0000230 }
231 }
232
233 // Now compute the non-virtual offset.
234 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
235 const CXXBasePathElement &Element = Path[I];
236
237 // Check the base class offset.
238 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
239
240 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
241 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
242
243 NonVirtualOffset += Layout.getBaseClassOffset(Base);
244 }
245
246 // FIXME: This should probably use CharUnits or something. Maybe we should
247 // even change the base offsets in ASTRecordLayout to be specified in
248 // CharUnits.
249 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
250
251}
252
253static BaseOffset ComputeBaseOffset(ASTContext &Context,
254 const CXXRecordDecl *BaseRD,
255 const CXXRecordDecl *DerivedRD) {
256 CXXBasePaths Paths(/*FindAmbiguities=*/false,
257 /*RecordPaths=*/true, /*DetectVirtual=*/false);
Benjamin Kramer922cec22013-02-03 18:55:34 +0000258
259 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbourne24018462011-09-26 01:57:12 +0000260 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbourne24018462011-09-26 01:57:12 +0000261
262 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
263}
264
265static BaseOffset
266ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
267 const CXXMethodDecl *DerivedMD,
268 const CXXMethodDecl *BaseMD) {
269 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
270 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
271
272 // Canonicalize the return types.
273 CanQualType CanDerivedReturnType =
274 Context.getCanonicalType(DerivedFT->getResultType());
275 CanQualType CanBaseReturnType =
276 Context.getCanonicalType(BaseFT->getResultType());
277
278 assert(CanDerivedReturnType->getTypeClass() ==
279 CanBaseReturnType->getTypeClass() &&
280 "Types must have same type class!");
281
282 if (CanDerivedReturnType == CanBaseReturnType) {
283 // No adjustment needed.
284 return BaseOffset();
285 }
286
287 if (isa<ReferenceType>(CanDerivedReturnType)) {
288 CanDerivedReturnType =
289 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
290 CanBaseReturnType =
291 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
292 } else if (isa<PointerType>(CanDerivedReturnType)) {
293 CanDerivedReturnType =
294 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
295 CanBaseReturnType =
296 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
297 } else {
298 llvm_unreachable("Unexpected return type!");
299 }
300
301 // We need to compare unqualified types here; consider
302 // const T *Base::foo();
303 // T *Derived::foo();
304 if (CanDerivedReturnType.getUnqualifiedType() ==
305 CanBaseReturnType.getUnqualifiedType()) {
306 // No adjustment needed.
307 return BaseOffset();
308 }
309
310 const CXXRecordDecl *DerivedRD =
311 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
312
313 const CXXRecordDecl *BaseRD =
314 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
315
316 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
317}
318
319void
320FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
321 CharUnits OffsetInLayoutClass,
322 SubobjectOffsetMapTy &SubobjectOffsets,
323 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
324 SubobjectCountMapTy &SubobjectCounts) {
325 const CXXRecordDecl *RD = Base.getBase();
326
327 unsigned SubobjectNumber = 0;
328 if (!IsVirtual)
329 SubobjectNumber = ++SubobjectCounts[RD];
330
331 // Set up the subobject to offset mapping.
332 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
333 && "Subobject offset already exists!");
334 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
335 && "Subobject offset already exists!");
336
337 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
338 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
339 OffsetInLayoutClass;
340
341 // Traverse our bases.
342 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
343 E = RD->bases_end(); I != E; ++I) {
344 const CXXRecordDecl *BaseDecl =
345 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
346
347 CharUnits BaseOffset;
348 CharUnits BaseOffsetInLayoutClass;
349 if (I->isVirtual()) {
350 // Check if we've visited this virtual base before.
351 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
352 continue;
353
354 const ASTRecordLayout &LayoutClassLayout =
355 Context.getASTRecordLayout(LayoutClass);
356
357 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
358 BaseOffsetInLayoutClass =
359 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
360 } else {
361 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
362 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
363
364 BaseOffset = Base.getBaseOffset() + Offset;
365 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
366 }
367
368 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
369 I->isVirtual(), BaseOffsetInLayoutClass,
370 SubobjectOffsets, SubobjectLayoutClassOffsets,
371 SubobjectCounts);
372 }
373}
374
375void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
376 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
377 const CXXRecordDecl *RD = Base.getBase();
378 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
379
380 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
381 E = RD->bases_end(); I != E; ++I) {
382 const CXXRecordDecl *BaseDecl =
383 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
384
385 // Ignore bases that don't have any virtual member functions.
386 if (!BaseDecl->isPolymorphic())
387 continue;
388
389 CharUnits BaseOffset;
390 if (I->isVirtual()) {
391 if (!VisitedVirtualBases.insert(BaseDecl)) {
392 // We've visited this base before.
393 continue;
394 }
395
396 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
397 } else {
398 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
399 }
400
401 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
402 }
403
404 Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
405 Out << Base.getBaseOffset().getQuantity() << ")\n";
406
407 // Now dump the overriders for this base subobject.
408 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
409 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000410 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000411
412 if (!MD->isVirtual())
413 continue;
414
415 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
416
417 Out << " " << MD->getQualifiedNameAsString() << " - (";
418 Out << Overrider.Method->getQualifiedNameAsString();
Timur Iskhodzhanovc65ee8f2013-06-05 06:40:07 +0000419 Out << ", " << Overrider.Offset.getQuantity() << ')';
Peter Collingbourne24018462011-09-26 01:57:12 +0000420
421 BaseOffset Offset;
422 if (!Overrider.Method->isPure())
423 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
424
425 if (!Offset.isEmpty()) {
426 Out << " [ret-adj: ";
427 if (Offset.VirtualBase)
428 Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
429
430 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
431 }
432
433 Out << "\n";
434 }
435}
436
437/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
438struct VCallOffsetMap {
439
440 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
441
442 /// Offsets - Keeps track of methods and their offsets.
443 // FIXME: This should be a real map and not a vector.
444 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
445
446 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
447 /// can share the same vcall offset.
448 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
449 const CXXMethodDecl *RHS);
450
451public:
452 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
453 /// add was successful, or false if there was already a member function with
454 /// the same signature in the map.
455 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
456
457 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
458 /// vtable address point) for the given virtual member function.
459 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
460
461 // empty - Return whether the offset map is empty or not.
462 bool empty() const { return Offsets.empty(); }
463};
464
465static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
466 const CXXMethodDecl *RHS) {
John McCall260a3e42012-03-21 06:57:19 +0000467 const FunctionProtoType *LT =
468 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
469 const FunctionProtoType *RT =
470 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbourne24018462011-09-26 01:57:12 +0000471
472 // Fast-path matches in the canonical types.
473 if (LT == RT) return true;
474
475 // Force the signatures to match. We can't rely on the overrides
476 // list here because there isn't necessarily an inheritance
477 // relationship between the two methods.
John McCall260a3e42012-03-21 06:57:19 +0000478 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Peter Collingbourne24018462011-09-26 01:57:12 +0000479 LT->getNumArgs() != RT->getNumArgs())
480 return false;
481 for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
482 if (LT->getArgType(I) != RT->getArgType(I))
483 return false;
484 return true;
485}
486
487bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
488 const CXXMethodDecl *RHS) {
489 assert(LHS->isVirtual() && "LHS must be virtual!");
490 assert(RHS->isVirtual() && "LHS must be virtual!");
491
492 // A destructor can share a vcall offset with another destructor.
493 if (isa<CXXDestructorDecl>(LHS))
494 return isa<CXXDestructorDecl>(RHS);
495
496 // FIXME: We need to check more things here.
497
498 // The methods must have the same name.
499 DeclarationName LHSName = LHS->getDeclName();
500 DeclarationName RHSName = RHS->getDeclName();
501 if (LHSName != RHSName)
502 return false;
503
504 // And the same signatures.
505 return HasSameVirtualSignature(LHS, RHS);
506}
507
508bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
509 CharUnits OffsetOffset) {
510 // Check if we can reuse an offset.
511 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
512 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
513 return false;
514 }
515
516 // Add the offset.
517 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
518 return true;
519}
520
521CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
522 // Look for an offset.
523 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
524 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
525 return Offsets[I].second;
526 }
527
528 llvm_unreachable("Should always find a vcall offset offset!");
529}
530
531/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
532class VCallAndVBaseOffsetBuilder {
533public:
534 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
535 VBaseOffsetOffsetsMapTy;
536
537private:
538 /// MostDerivedClass - The most derived class for which we're building vcall
539 /// and vbase offsets.
540 const CXXRecordDecl *MostDerivedClass;
541
542 /// LayoutClass - The class we're using for layout information. Will be
543 /// different than the most derived class if we're building a construction
544 /// vtable.
545 const CXXRecordDecl *LayoutClass;
546
547 /// Context - The ASTContext which we will use for layout information.
548 ASTContext &Context;
549
550 /// Components - vcall and vbase offset components
551 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
552 VTableComponentVectorTy Components;
553
554 /// VisitedVirtualBases - Visited virtual bases.
555 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
556
557 /// VCallOffsets - Keeps track of vcall offsets.
558 VCallOffsetMap VCallOffsets;
559
560
561 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
562 /// relative to the address point.
563 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
564
565 /// FinalOverriders - The final overriders of the most derived class.
566 /// (Can be null when we're not building a vtable of the most derived class).
567 const FinalOverriders *Overriders;
568
569 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
570 /// given base subobject.
571 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
572 CharUnits RealBaseOffset);
573
574 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
575 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
576
577 /// AddVBaseOffsets - Add vbase offsets for the given class.
578 void AddVBaseOffsets(const CXXRecordDecl *Base,
579 CharUnits OffsetInLayoutClass);
580
581 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
582 /// chars, relative to the vtable address point.
583 CharUnits getCurrentOffsetOffset() const;
584
585public:
586 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
587 const CXXRecordDecl *LayoutClass,
588 const FinalOverriders *Overriders,
589 BaseSubobject Base, bool BaseIsVirtual,
590 CharUnits OffsetInLayoutClass)
591 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
592 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
593
594 // Add vcall and vbase offsets.
595 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
596 }
597
598 /// Methods for iterating over the components.
599 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
600 const_iterator components_begin() const { return Components.rbegin(); }
601 const_iterator components_end() const { return Components.rend(); }
602
603 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
604 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
605 return VBaseOffsetOffsets;
606 }
607};
608
609void
610VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
611 bool BaseIsVirtual,
612 CharUnits RealBaseOffset) {
613 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
614
615 // Itanium C++ ABI 2.5.2:
616 // ..in classes sharing a virtual table with a primary base class, the vcall
617 // and vbase offsets added by the derived class all come before the vcall
618 // and vbase offsets required by the base class, so that the latter may be
619 // laid out as required by the base class without regard to additions from
620 // the derived class(es).
621
622 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
623 // emit them for the primary base first).
624 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
625 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
626
627 CharUnits PrimaryBaseOffset;
628
629 // Get the base offset of the primary base.
630 if (PrimaryBaseIsVirtual) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000631 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000632 "Primary vbase should have a zero offset!");
633
634 const ASTRecordLayout &MostDerivedClassLayout =
635 Context.getASTRecordLayout(MostDerivedClass);
636
637 PrimaryBaseOffset =
638 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
639 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000640 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000641 "Primary base should have a zero offset!");
642
643 PrimaryBaseOffset = Base.getBaseOffset();
644 }
645
646 AddVCallAndVBaseOffsets(
647 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
648 PrimaryBaseIsVirtual, RealBaseOffset);
649 }
650
651 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
652
653 // We only want to add vcall offsets for virtual bases.
654 if (BaseIsVirtual)
655 AddVCallOffsets(Base, RealBaseOffset);
656}
657
658CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
659 // OffsetIndex is the index of this vcall or vbase offset, relative to the
660 // vtable address point. (We subtract 3 to account for the information just
661 // above the address point, the RTTI info, the offset to top, and the
662 // vcall offset itself).
663 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
664
665 CharUnits PointerWidth =
666 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
667 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
668 return OffsetOffset;
669}
670
671void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
672 CharUnits VBaseOffset) {
673 const CXXRecordDecl *RD = Base.getBase();
674 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
675
676 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
677
678 // Handle the primary base first.
679 // We only want to add vcall offsets if the base is non-virtual; a virtual
680 // primary base will have its vcall and vbase offsets emitted already.
681 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
682 // Get the base offset of the primary base.
Benjamin Kramerd4f51982012-07-04 18:45:14 +0000683 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +0000684 "Primary base should have a zero offset!");
685
686 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
687 VBaseOffset);
688 }
689
690 // Add the vcall offsets.
691 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
692 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +0000693 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +0000694
695 if (!MD->isVirtual())
696 continue;
697
698 CharUnits OffsetOffset = getCurrentOffsetOffset();
699
700 // Don't add a vcall offset if we already have one for this member function
701 // signature.
702 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
703 continue;
704
705 CharUnits Offset = CharUnits::Zero();
706
707 if (Overriders) {
708 // Get the final overrider.
709 FinalOverriders::OverriderInfo Overrider =
710 Overriders->getOverrider(MD, Base.getBaseOffset());
711
712 /// The vcall offset is the offset from the virtual base to the object
713 /// where the function was overridden.
714 Offset = Overrider.Offset - VBaseOffset;
715 }
716
717 Components.push_back(
718 VTableComponent::MakeVCallOffset(Offset));
719 }
720
721 // And iterate over all non-virtual bases (ignoring the primary base).
722 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
723 E = RD->bases_end(); I != E; ++I) {
724
725 if (I->isVirtual())
726 continue;
727
728 const CXXRecordDecl *BaseDecl =
729 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
730 if (BaseDecl == PrimaryBase)
731 continue;
732
733 // Get the base offset of this base.
734 CharUnits BaseOffset = Base.getBaseOffset() +
735 Layout.getBaseClassOffset(BaseDecl);
736
737 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
738 VBaseOffset);
739 }
740}
741
742void
743VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
744 CharUnits OffsetInLayoutClass) {
745 const ASTRecordLayout &LayoutClassLayout =
746 Context.getASTRecordLayout(LayoutClass);
747
748 // Add vbase offsets.
749 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
750 E = RD->bases_end(); I != E; ++I) {
751 const CXXRecordDecl *BaseDecl =
752 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
753
754 // Check if this is a virtual base that we haven't visited before.
755 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
756 CharUnits Offset =
757 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
758
759 // Add the vbase offset offset.
760 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
761 "vbase offset offset already exists!");
762
763 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
764 VBaseOffsetOffsets.insert(
765 std::make_pair(BaseDecl, VBaseOffsetOffset));
766
767 Components.push_back(
768 VTableComponent::MakeVBaseOffset(Offset));
769 }
770
771 // Check the base class looking for more vbase offsets.
772 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
773 }
774}
775
776/// VTableBuilder - Class for building vtable layout information.
777class VTableBuilder {
778public:
779 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
780 /// primary bases.
781 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
782 PrimaryBasesSetVectorTy;
783
784 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
785 VBaseOffsetOffsetsMapTy;
786
787 typedef llvm::DenseMap<BaseSubobject, uint64_t>
788 AddressPointsMapTy;
789
790private:
791 /// VTables - Global vtable information.
792 VTableContext &VTables;
793
794 /// MostDerivedClass - The most derived class for which we're building this
795 /// vtable.
796 const CXXRecordDecl *MostDerivedClass;
797
798 /// MostDerivedClassOffset - If we're building a construction vtable, this
799 /// holds the offset from the layout class to the most derived class.
800 const CharUnits MostDerivedClassOffset;
801
802 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
803 /// base. (This only makes sense when building a construction vtable).
804 bool MostDerivedClassIsVirtual;
805
806 /// LayoutClass - The class we're using for layout information. Will be
807 /// different than the most derived class if we're building a construction
808 /// vtable.
809 const CXXRecordDecl *LayoutClass;
810
811 /// Context - The ASTContext which we will use for layout information.
812 ASTContext &Context;
813
814 /// FinalOverriders - The final overriders of the most derived class.
815 const FinalOverriders Overriders;
816
817 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
818 /// bases in this vtable.
819 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
820
821 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
822 /// the most derived class.
823 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
824
825 /// Components - The components of the vtable being built.
826 SmallVector<VTableComponent, 64> Components;
827
828 /// AddressPoints - Address points for the vtable being built.
829 AddressPointsMapTy AddressPoints;
830
831 /// MethodInfo - Contains information about a method in a vtable.
832 /// (Used for computing 'this' pointer adjustment thunks.
833 struct MethodInfo {
834 /// BaseOffset - The base offset of this method.
835 const CharUnits BaseOffset;
836
837 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
838 /// method.
839 const CharUnits BaseOffsetInLayoutClass;
840
841 /// VTableIndex - The index in the vtable that this method has.
842 /// (For destructors, this is the index of the complete destructor).
843 const uint64_t VTableIndex;
844
845 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
846 uint64_t VTableIndex)
847 : BaseOffset(BaseOffset),
848 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
849 VTableIndex(VTableIndex) { }
850
851 MethodInfo()
852 : BaseOffset(CharUnits::Zero()),
853 BaseOffsetInLayoutClass(CharUnits::Zero()),
854 VTableIndex(0) { }
855 };
856
857 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
858
859 /// MethodInfoMap - The information for all methods in the vtable we're
860 /// currently building.
861 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanovd38a21f2013-06-05 12:24:46 +0000862
Peter Collingbourne24018462011-09-26 01:57:12 +0000863 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
864
865 /// VTableThunks - The thunks by vtable index in the vtable currently being
866 /// built.
867 VTableThunksMapTy VTableThunks;
868
869 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
870 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
871
872 /// Thunks - A map that contains all the thunks needed for all methods in the
873 /// most derived class for which the vtable is currently being built.
874 ThunksMapTy Thunks;
875
876 /// AddThunk - Add a thunk for the given method.
877 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
878
879 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
880 /// part of the vtable we're currently building.
881 void ComputeThisAdjustments();
882
883 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
884
885 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
886 /// some other base.
887 VisitedVirtualBasesSetTy PrimaryVirtualBases;
888
889 /// ComputeReturnAdjustment - Compute the return adjustment given a return
890 /// adjustment base offset.
891 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
892
893 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
894 /// the 'this' pointer from the base subobject to the derived subobject.
895 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
896 BaseSubobject Derived) const;
897
898 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
899 /// given virtual member function, its offset in the layout class and its
900 /// final overrider.
901 ThisAdjustment
902 ComputeThisAdjustment(const CXXMethodDecl *MD,
903 CharUnits BaseOffsetInLayoutClass,
904 FinalOverriders::OverriderInfo Overrider);
905
906 /// AddMethod - Add a single virtual member function to the vtable
907 /// components vector.
908 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
909
910 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
911 /// part of the vtable.
912 ///
913 /// Itanium C++ ABI 2.5.2:
914 ///
915 /// struct A { virtual void f(); };
916 /// struct B : virtual public A { int i; };
917 /// struct C : virtual public A { int j; };
918 /// struct D : public B, public C {};
919 ///
920 /// When B and C are declared, A is a primary base in each case, so although
921 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
922 /// adjustment is required and no thunk is generated. However, inside D
923 /// objects, A is no longer a primary base of C, so if we allowed calls to
924 /// C::f() to use the copy of A's vtable in the C subobject, we would need
925 /// to adjust this from C* to B::A*, which would require a third-party
926 /// thunk. Since we require that a call to C::f() first convert to A*,
927 /// C-in-D's copy of A's vtable is never referenced, so this is not
928 /// necessary.
929 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
930 CharUnits BaseOffsetInLayoutClass,
931 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
932 CharUnits FirstBaseOffsetInLayoutClass) const;
933
934
935 /// AddMethods - Add the methods of this base subobject and all its
936 /// primary bases to the vtable components vector.
937 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
938 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
939 CharUnits FirstBaseOffsetInLayoutClass,
940 PrimaryBasesSetVectorTy &PrimaryBases);
941
942 // LayoutVTable - Layout the vtable for the given base class, including its
943 // secondary vtables and any vtables for virtual bases.
944 void LayoutVTable();
945
946 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
947 /// given base subobject, as well as all its secondary vtables.
948 ///
949 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
950 /// or a direct or indirect base of a virtual base.
951 ///
952 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
953 /// in the layout class.
954 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
955 bool BaseIsMorallyVirtual,
956 bool BaseIsVirtualInLayoutClass,
957 CharUnits OffsetInLayoutClass);
958
959 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
960 /// subobject.
961 ///
962 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
963 /// or a direct or indirect base of a virtual base.
964 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
965 CharUnits OffsetInLayoutClass);
966
967 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
968 /// class hierarchy.
969 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
970 CharUnits OffsetInLayoutClass,
971 VisitedVirtualBasesSetTy &VBases);
972
973 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
974 /// given base (excluding any primary bases).
975 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
976 VisitedVirtualBasesSetTy &VBases);
977
978 /// isBuildingConstructionVTable - Return whether this vtable builder is
979 /// building a construction vtable.
980 bool isBuildingConstructorVTable() const {
981 return MostDerivedClass != LayoutClass;
982 }
983
984public:
985 VTableBuilder(VTableContext &VTables, const CXXRecordDecl *MostDerivedClass,
986 CharUnits MostDerivedClassOffset,
987 bool MostDerivedClassIsVirtual, const
988 CXXRecordDecl *LayoutClass)
989 : VTables(VTables), MostDerivedClass(MostDerivedClass),
990 MostDerivedClassOffset(MostDerivedClassOffset),
991 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
992 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
993 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
994
995 LayoutVTable();
996
David Blaikie4e4d0842012-03-11 07:00:24 +0000997 if (Context.getLangOpts().DumpVTableLayouts)
Peter Collingbourne24018462011-09-26 01:57:12 +0000998 dumpLayout(llvm::errs());
999 }
1000
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001001 bool isMicrosoftABI() const {
1002 return VTables.isMicrosoftABI();
1003 }
1004
Peter Collingbourne24018462011-09-26 01:57:12 +00001005 uint64_t getNumThunks() const {
1006 return Thunks.size();
1007 }
1008
1009 ThunksMapTy::const_iterator thunks_begin() const {
1010 return Thunks.begin();
1011 }
1012
1013 ThunksMapTy::const_iterator thunks_end() const {
1014 return Thunks.end();
1015 }
1016
1017 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1018 return VBaseOffsetOffsets;
1019 }
1020
1021 const AddressPointsMapTy &getAddressPoints() const {
1022 return AddressPoints;
1023 }
1024
1025 /// getNumVTableComponents - Return the number of components in the vtable
1026 /// currently built.
1027 uint64_t getNumVTableComponents() const {
1028 return Components.size();
1029 }
1030
1031 const VTableComponent *vtable_component_begin() const {
1032 return Components.begin();
1033 }
1034
1035 const VTableComponent *vtable_component_end() const {
1036 return Components.end();
1037 }
1038
1039 AddressPointsMapTy::const_iterator address_points_begin() const {
1040 return AddressPoints.begin();
1041 }
1042
1043 AddressPointsMapTy::const_iterator address_points_end() const {
1044 return AddressPoints.end();
1045 }
1046
1047 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1048 return VTableThunks.begin();
1049 }
1050
1051 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1052 return VTableThunks.end();
1053 }
1054
1055 /// dumpLayout - Dump the vtable layout.
1056 void dumpLayout(raw_ostream&);
1057};
1058
1059void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1060 assert(!isBuildingConstructorVTable() &&
1061 "Can't add thunks for construction vtable");
1062
1063 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
1064
1065 // Check if we have this thunk already.
1066 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1067 ThunksVector.end())
1068 return;
1069
1070 ThunksVector.push_back(Thunk);
1071}
1072
1073typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1074
1075/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1076/// the overridden methods that the function decl overrides.
1077static void
1078ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1079 OverriddenMethodsSetTy& OverriddenMethods) {
1080 assert(MD->isVirtual() && "Method is not virtual!");
1081
1082 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1083 E = MD->end_overridden_methods(); I != E; ++I) {
1084 const CXXMethodDecl *OverriddenMD = *I;
1085
1086 OverriddenMethods.insert(OverriddenMD);
1087
1088 ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1089 }
1090}
1091
1092void VTableBuilder::ComputeThisAdjustments() {
1093 // Now go through the method info map and see if any of the methods need
1094 // 'this' pointer adjustments.
1095 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1096 E = MethodInfoMap.end(); I != E; ++I) {
1097 const CXXMethodDecl *MD = I->first;
1098 const MethodInfo &MethodInfo = I->second;
1099
1100 // Ignore adjustments for unused function pointers.
1101 uint64_t VTableIndex = MethodInfo.VTableIndex;
1102 if (Components[VTableIndex].getKind() ==
1103 VTableComponent::CK_UnusedFunctionPointer)
1104 continue;
1105
1106 // Get the final overrider for this method.
1107 FinalOverriders::OverriderInfo Overrider =
1108 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1109
1110 // Check if we need an adjustment at all.
1111 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1112 // When a return thunk is needed by a derived class that overrides a
1113 // virtual base, gcc uses a virtual 'this' adjustment as well.
1114 // While the thunk itself might be needed by vtables in subclasses or
1115 // in construction vtables, there doesn't seem to be a reason for using
1116 // the thunk in this vtable. Still, we do so to match gcc.
1117 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1118 continue;
1119 }
1120
1121 ThisAdjustment ThisAdjustment =
1122 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1123
1124 if (ThisAdjustment.isEmpty())
1125 continue;
1126
1127 // Add it.
1128 VTableThunks[VTableIndex].This = ThisAdjustment;
1129
1130 if (isa<CXXDestructorDecl>(MD)) {
1131 // Add an adjustment for the deleting destructor as well.
1132 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1133 }
1134 }
1135
1136 /// Clear the method info map.
1137 MethodInfoMap.clear();
1138
1139 if (isBuildingConstructorVTable()) {
1140 // We don't need to store thunk information for construction vtables.
1141 return;
1142 }
1143
1144 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1145 E = VTableThunks.end(); I != E; ++I) {
1146 const VTableComponent &Component = Components[I->first];
1147 const ThunkInfo &Thunk = I->second;
1148 const CXXMethodDecl *MD;
1149
1150 switch (Component.getKind()) {
1151 default:
1152 llvm_unreachable("Unexpected vtable component kind!");
1153 case VTableComponent::CK_FunctionPointer:
1154 MD = Component.getFunctionDecl();
1155 break;
1156 case VTableComponent::CK_CompleteDtorPointer:
1157 MD = Component.getDestructorDecl();
1158 break;
1159 case VTableComponent::CK_DeletingDtorPointer:
1160 // We've already added the thunk when we saw the complete dtor pointer.
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001161 // FIXME: check how this works in the Microsoft ABI
1162 // while working on the multiple inheritance patch.
Peter Collingbourne24018462011-09-26 01:57:12 +00001163 continue;
1164 }
1165
1166 if (MD->getParent() == MostDerivedClass)
1167 AddThunk(MD, Thunk);
1168 }
1169}
1170
1171ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1172 ReturnAdjustment Adjustment;
1173
1174 if (!Offset.isEmpty()) {
1175 if (Offset.VirtualBase) {
1176 // Get the virtual base offset offset.
1177 if (Offset.DerivedClass == MostDerivedClass) {
1178 // We can get the offset offset directly from our map.
1179 Adjustment.VBaseOffsetOffset =
1180 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1181 } else {
1182 Adjustment.VBaseOffsetOffset =
1183 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1184 Offset.VirtualBase).getQuantity();
1185 }
1186 }
1187
1188 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1189 }
1190
1191 return Adjustment;
1192}
1193
1194BaseOffset
1195VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1196 BaseSubobject Derived) const {
1197 const CXXRecordDecl *BaseRD = Base.getBase();
1198 const CXXRecordDecl *DerivedRD = Derived.getBase();
1199
1200 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1201 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1202
Benjamin Kramer922cec22013-02-03 18:55:34 +00001203 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbourne24018462011-09-26 01:57:12 +00001204 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbourne24018462011-09-26 01:57:12 +00001205
1206 // We have to go through all the paths, and see which one leads us to the
1207 // right base subobject.
1208 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1209 I != E; ++I) {
1210 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1211
1212 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1213
1214 if (Offset.VirtualBase) {
1215 // If we have a virtual base class, the non-virtual offset is relative
1216 // to the virtual base class offset.
1217 const ASTRecordLayout &LayoutClassLayout =
1218 Context.getASTRecordLayout(LayoutClass);
1219
1220 /// Get the virtual base offset, relative to the most derived class
1221 /// layout.
1222 OffsetToBaseSubobject +=
1223 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1224 } else {
1225 // Otherwise, the non-virtual offset is relative to the derived class
1226 // offset.
1227 OffsetToBaseSubobject += Derived.getBaseOffset();
1228 }
1229
1230 // Check if this path gives us the right base subobject.
1231 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1232 // Since we're going from the base class _to_ the derived class, we'll
1233 // invert the non-virtual offset here.
1234 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1235 return Offset;
1236 }
1237 }
1238
1239 return BaseOffset();
1240}
1241
1242ThisAdjustment
1243VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1244 CharUnits BaseOffsetInLayoutClass,
1245 FinalOverriders::OverriderInfo Overrider) {
1246 // Ignore adjustments for pure virtual member functions.
1247 if (Overrider.Method->isPure())
1248 return ThisAdjustment();
1249
1250 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1251 BaseOffsetInLayoutClass);
1252
1253 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1254 Overrider.Offset);
1255
1256 // Compute the adjustment offset.
1257 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1258 OverriderBaseSubobject);
1259 if (Offset.isEmpty())
1260 return ThisAdjustment();
1261
1262 ThisAdjustment Adjustment;
1263
1264 if (Offset.VirtualBase) {
1265 // Get the vcall offset map for this virtual base.
1266 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1267
1268 if (VCallOffsets.empty()) {
1269 // We don't have vcall offsets for this virtual base, go ahead and
1270 // build them.
1271 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1272 /*FinalOverriders=*/0,
1273 BaseSubobject(Offset.VirtualBase,
1274 CharUnits::Zero()),
1275 /*BaseIsVirtual=*/true,
1276 /*OffsetInLayoutClass=*/
1277 CharUnits::Zero());
1278
1279 VCallOffsets = Builder.getVCallOffsets();
1280 }
1281
1282 Adjustment.VCallOffsetOffset =
1283 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1284 }
1285
1286 // Set the non-virtual part of the adjustment.
1287 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1288
1289 return Adjustment;
1290}
1291
1292void
1293VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1294 ReturnAdjustment ReturnAdjustment) {
1295 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1296 assert(ReturnAdjustment.isEmpty() &&
1297 "Destructor can't have return adjustment!");
1298
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001299 // FIXME: Should probably add a layer of abstraction for vtable generation.
1300 if (!isMicrosoftABI()) {
1301 // Add both the complete destructor and the deleting destructor.
1302 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1303 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1304 } else {
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001305 // Add the scalar deleting destructor.
1306 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001307 }
Peter Collingbourne24018462011-09-26 01:57:12 +00001308 } else {
1309 // Add the return adjustment if necessary.
1310 if (!ReturnAdjustment.isEmpty())
1311 VTableThunks[Components.size()].Return = ReturnAdjustment;
1312
1313 // Add the function.
1314 Components.push_back(VTableComponent::MakeFunction(MD));
1315 }
1316}
1317
1318/// OverridesIndirectMethodInBase - Return whether the given member function
1319/// overrides any methods in the set of given bases.
1320/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1321/// For example, if we have:
1322///
1323/// struct A { virtual void f(); }
1324/// struct B : A { virtual void f(); }
1325/// struct C : B { virtual void f(); }
1326///
1327/// OverridesIndirectMethodInBase will return true if given C::f as the method
1328/// and { A } as the set of bases.
1329static bool
1330OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1331 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1332 if (Bases.count(MD->getParent()))
1333 return true;
1334
1335 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1336 E = MD->end_overridden_methods(); I != E; ++I) {
1337 const CXXMethodDecl *OverriddenMD = *I;
1338
1339 // Check "indirect overriders".
1340 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1341 return true;
1342 }
1343
1344 return false;
1345}
1346
1347bool
1348VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1349 CharUnits BaseOffsetInLayoutClass,
1350 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1351 CharUnits FirstBaseOffsetInLayoutClass) const {
1352 // If the base and the first base in the primary base chain have the same
1353 // offsets, then this overrider will be used.
1354 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1355 return true;
1356
1357 // We know now that Base (or a direct or indirect base of it) is a primary
1358 // base in part of the class hierarchy, but not a primary base in the most
1359 // derived class.
1360
1361 // If the overrider is the first base in the primary base chain, we know
1362 // that the overrider will be used.
1363 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1364 return true;
1365
1366 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1367
1368 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1369 PrimaryBases.insert(RD);
1370
1371 // Now traverse the base chain, starting with the first base, until we find
1372 // the base that is no longer a primary base.
1373 while (true) {
1374 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1375 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1376
1377 if (!PrimaryBase)
1378 break;
1379
1380 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001381 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001382 "Primary base should always be at offset 0!");
1383
1384 const ASTRecordLayout &LayoutClassLayout =
1385 Context.getASTRecordLayout(LayoutClass);
1386
1387 // Now check if this is the primary base that is not a primary base in the
1388 // most derived class.
1389 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1390 FirstBaseOffsetInLayoutClass) {
1391 // We found it, stop walking the chain.
1392 break;
1393 }
1394 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001395 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001396 "Primary base should always be at offset 0!");
1397 }
1398
1399 if (!PrimaryBases.insert(PrimaryBase))
1400 llvm_unreachable("Found a duplicate primary base!");
1401
1402 RD = PrimaryBase;
1403 }
1404
1405 // If the final overrider is an override of one of the primary bases,
1406 // then we know that it will be used.
1407 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1408}
1409
1410/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1411/// from the nearest base. Returns null if no method was found.
1412static const CXXMethodDecl *
1413FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1414 VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1415 OverriddenMethodsSetTy OverriddenMethods;
1416 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1417
1418 for (int I = Bases.size(), E = 0; I != E; --I) {
1419 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1420
1421 // Now check the overriden methods.
1422 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1423 E = OverriddenMethods.end(); I != E; ++I) {
1424 const CXXMethodDecl *OverriddenMD = *I;
1425
1426 // We found our overridden method.
1427 if (OverriddenMD->getParent() == PrimaryBase)
1428 return OverriddenMD;
1429 }
1430 }
1431
1432 return 0;
1433}
1434
1435void
1436VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1437 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1438 CharUnits FirstBaseOffsetInLayoutClass,
1439 PrimaryBasesSetVectorTy &PrimaryBases) {
1440 const CXXRecordDecl *RD = Base.getBase();
1441 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1442
1443 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1444 CharUnits PrimaryBaseOffset;
1445 CharUnits PrimaryBaseOffsetInLayoutClass;
1446 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001447 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001448 "Primary vbase should have a zero offset!");
1449
1450 const ASTRecordLayout &MostDerivedClassLayout =
1451 Context.getASTRecordLayout(MostDerivedClass);
1452
1453 PrimaryBaseOffset =
1454 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1455
1456 const ASTRecordLayout &LayoutClassLayout =
1457 Context.getASTRecordLayout(LayoutClass);
1458
1459 PrimaryBaseOffsetInLayoutClass =
1460 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1461 } else {
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001462 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbourne24018462011-09-26 01:57:12 +00001463 "Primary base should have a zero offset!");
1464
1465 PrimaryBaseOffset = Base.getBaseOffset();
1466 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1467 }
1468
1469 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1470 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1471 FirstBaseOffsetInLayoutClass, PrimaryBases);
1472
1473 if (!PrimaryBases.insert(PrimaryBase))
1474 llvm_unreachable("Found a duplicate primary base!");
1475 }
1476
1477 // Now go through all virtual member functions and add them.
1478 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1479 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001480 const CXXMethodDecl *MD = *I;
Peter Collingbourne24018462011-09-26 01:57:12 +00001481
1482 if (!MD->isVirtual())
1483 continue;
1484
1485 // Get the final overrider.
1486 FinalOverriders::OverriderInfo Overrider =
1487 Overriders.getOverrider(MD, Base.getBaseOffset());
1488
1489 // Check if this virtual member function overrides a method in a primary
1490 // base. If this is the case, and the return type doesn't require adjustment
1491 // then we can just use the member function from the primary base.
1492 if (const CXXMethodDecl *OverriddenMD =
1493 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1494 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1495 OverriddenMD).isEmpty()) {
1496 // Replace the method info of the overridden method with our own
1497 // method.
1498 assert(MethodInfoMap.count(OverriddenMD) &&
1499 "Did not find the overridden method!");
1500 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1501
1502 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1503 OverriddenMethodInfo.VTableIndex);
1504
1505 assert(!MethodInfoMap.count(MD) &&
1506 "Should not have method info for this method yet!");
1507
1508 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1509 MethodInfoMap.erase(OverriddenMD);
1510
1511 // If the overridden method exists in a virtual base class or a direct
1512 // or indirect base class of a virtual base class, we need to emit a
1513 // thunk if we ever have a class hierarchy where the base class is not
1514 // a primary base in the complete object.
1515 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1516 // Compute the this adjustment.
1517 ThisAdjustment ThisAdjustment =
1518 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1519 Overrider);
1520
1521 if (ThisAdjustment.VCallOffsetOffset &&
1522 Overrider.Method->getParent() == MostDerivedClass) {
1523
1524 // There's no return adjustment from OverriddenMD and MD,
1525 // but that doesn't mean there isn't one between MD and
1526 // the final overrider.
1527 BaseOffset ReturnAdjustmentOffset =
1528 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1529 ReturnAdjustment ReturnAdjustment =
1530 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1531
1532 // This is a virtual thunk for the most derived class, add it.
1533 AddThunk(Overrider.Method,
1534 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1535 }
1536 }
1537
1538 continue;
1539 }
1540 }
1541
1542 // Insert the method info for this method.
1543 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1544 Components.size());
1545
1546 assert(!MethodInfoMap.count(MD) &&
1547 "Should not have method info for this method yet!");
1548 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1549
1550 // Check if this overrider is going to be used.
1551 const CXXMethodDecl *OverriderMD = Overrider.Method;
1552 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1553 FirstBaseInPrimaryBaseChain,
1554 FirstBaseOffsetInLayoutClass)) {
1555 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1556 continue;
1557 }
Timur Iskhodzhanovd38a21f2013-06-05 12:24:46 +00001558
Peter Collingbourne24018462011-09-26 01:57:12 +00001559 // Check if this overrider needs a return adjustment.
1560 // We don't want to do this for pure virtual member functions.
1561 BaseOffset ReturnAdjustmentOffset;
1562 if (!OverriderMD->isPure()) {
1563 ReturnAdjustmentOffset =
1564 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1565 }
1566
1567 ReturnAdjustment ReturnAdjustment =
1568 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1569
1570 AddMethod(Overrider.Method, ReturnAdjustment);
1571 }
1572}
1573
1574void VTableBuilder::LayoutVTable() {
1575 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1576 CharUnits::Zero()),
1577 /*BaseIsMorallyVirtual=*/false,
1578 MostDerivedClassIsVirtual,
1579 MostDerivedClassOffset);
1580
1581 VisitedVirtualBasesSetTy VBases;
1582
1583 // Determine the primary virtual bases.
1584 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1585 VBases);
1586 VBases.clear();
1587
1588 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1589
1590 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikie4e4d0842012-03-11 07:00:24 +00001591 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbourne24018462011-09-26 01:57:12 +00001592 if (IsAppleKext)
1593 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1594}
1595
1596void
1597VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1598 bool BaseIsMorallyVirtual,
1599 bool BaseIsVirtualInLayoutClass,
1600 CharUnits OffsetInLayoutClass) {
1601 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1602
1603 // Add vcall and vbase offsets for this vtable.
1604 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1605 Base, BaseIsVirtualInLayoutClass,
1606 OffsetInLayoutClass);
1607 Components.append(Builder.components_begin(), Builder.components_end());
1608
1609 // Check if we need to add these vcall offsets.
1610 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1611 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1612
1613 if (VCallOffsets.empty())
1614 VCallOffsets = Builder.getVCallOffsets();
1615 }
1616
1617 // If we're laying out the most derived class we want to keep track of the
1618 // virtual base class offset offsets.
1619 if (Base.getBase() == MostDerivedClass)
1620 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1621
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00001622 // FIXME: Should probably add a layer of abstraction for vtable generation.
1623 if (!isMicrosoftABI()) {
1624 // Add the offset to top.
1625 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1626 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1627
1628 // Next, add the RTTI.
1629 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1630 } else {
1631 // FIXME: unclear what to do with RTTI in MS ABI as emitting it anywhere
1632 // breaks the vftable layout. Just skip RTTI for now, can't mangle anyway.
1633 }
1634
Peter Collingbourne24018462011-09-26 01:57:12 +00001635 uint64_t AddressPoint = Components.size();
1636
1637 // Now go through all virtual member functions and add them.
1638 PrimaryBasesSetVectorTy PrimaryBases;
1639 AddMethods(Base, OffsetInLayoutClass,
1640 Base.getBase(), OffsetInLayoutClass,
1641 PrimaryBases);
1642
1643 // Compute 'this' pointer adjustments.
1644 ComputeThisAdjustments();
1645
1646 // Add all address points.
Timur Iskhodzhanovd38a21f2013-06-05 12:24:46 +00001647 const CXXRecordDecl *RD = Base.getBase();
Peter Collingbourne24018462011-09-26 01:57:12 +00001648 while (true) {
1649 AddressPoints.insert(std::make_pair(
1650 BaseSubobject(RD, OffsetInLayoutClass),
1651 AddressPoint));
1652
1653 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1654 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1655
1656 if (!PrimaryBase)
1657 break;
1658
1659 if (Layout.isPrimaryBaseVirtual()) {
1660 // Check if this virtual primary base is a primary base in the layout
1661 // class. If it's not, we don't want to add it.
1662 const ASTRecordLayout &LayoutClassLayout =
1663 Context.getASTRecordLayout(LayoutClass);
1664
1665 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1666 OffsetInLayoutClass) {
1667 // We don't want to add this class (or any of its primary bases).
1668 break;
1669 }
1670 }
1671
1672 RD = PrimaryBase;
1673 }
1674
1675 // Layout secondary vtables.
1676 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1677}
1678
1679void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1680 bool BaseIsMorallyVirtual,
1681 CharUnits OffsetInLayoutClass) {
1682 // Itanium C++ ABI 2.5.2:
1683 // Following the primary virtual table of a derived class are secondary
1684 // virtual tables for each of its proper base classes, except any primary
1685 // base(s) with which it shares its primary virtual table.
1686
1687 const CXXRecordDecl *RD = Base.getBase();
1688 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1689 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1690
1691 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1692 E = RD->bases_end(); I != E; ++I) {
1693 // Ignore virtual bases, we'll emit them later.
1694 if (I->isVirtual())
1695 continue;
1696
1697 const CXXRecordDecl *BaseDecl =
1698 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1699
1700 // Ignore bases that don't have a vtable.
1701 if (!BaseDecl->isDynamicClass())
1702 continue;
1703
1704 if (isBuildingConstructorVTable()) {
1705 // Itanium C++ ABI 2.6.4:
1706 // Some of the base class subobjects may not need construction virtual
1707 // tables, which will therefore not be present in the construction
1708 // virtual table group, even though the subobject virtual tables are
1709 // present in the main virtual table group for the complete object.
1710 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1711 continue;
1712 }
1713
1714 // Get the base offset of this base.
1715 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1716 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1717
1718 CharUnits BaseOffsetInLayoutClass =
1719 OffsetInLayoutClass + RelativeBaseOffset;
1720
1721 // Don't emit a secondary vtable for a primary base. We might however want
1722 // to emit secondary vtables for other bases of this base.
1723 if (BaseDecl == PrimaryBase) {
1724 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1725 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1726 continue;
1727 }
1728
1729 // Layout the primary vtable (and any secondary vtables) for this base.
1730 LayoutPrimaryAndSecondaryVTables(
1731 BaseSubobject(BaseDecl, BaseOffset),
1732 BaseIsMorallyVirtual,
1733 /*BaseIsVirtualInLayoutClass=*/false,
1734 BaseOffsetInLayoutClass);
1735 }
1736}
1737
1738void
1739VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1740 CharUnits OffsetInLayoutClass,
1741 VisitedVirtualBasesSetTy &VBases) {
1742 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1743
1744 // Check if this base has a primary base.
1745 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1746
1747 // Check if it's virtual.
1748 if (Layout.isPrimaryBaseVirtual()) {
1749 bool IsPrimaryVirtualBase = true;
1750
1751 if (isBuildingConstructorVTable()) {
1752 // Check if the base is actually a primary base in the class we use for
1753 // layout.
1754 const ASTRecordLayout &LayoutClassLayout =
1755 Context.getASTRecordLayout(LayoutClass);
1756
1757 CharUnits PrimaryBaseOffsetInLayoutClass =
1758 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1759
1760 // We know that the base is not a primary base in the layout class if
1761 // the base offsets are different.
1762 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1763 IsPrimaryVirtualBase = false;
1764 }
1765
1766 if (IsPrimaryVirtualBase)
1767 PrimaryVirtualBases.insert(PrimaryBase);
1768 }
1769 }
1770
1771 // Traverse bases, looking for more primary virtual bases.
1772 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1773 E = RD->bases_end(); I != E; ++I) {
1774 const CXXRecordDecl *BaseDecl =
1775 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1776
1777 CharUnits BaseOffsetInLayoutClass;
1778
1779 if (I->isVirtual()) {
1780 if (!VBases.insert(BaseDecl))
1781 continue;
1782
1783 const ASTRecordLayout &LayoutClassLayout =
1784 Context.getASTRecordLayout(LayoutClass);
1785
1786 BaseOffsetInLayoutClass =
1787 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1788 } else {
1789 BaseOffsetInLayoutClass =
1790 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1791 }
1792
1793 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1794 }
1795}
1796
1797void
1798VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1799 VisitedVirtualBasesSetTy &VBases) {
1800 // Itanium C++ ABI 2.5.2:
1801 // Then come the virtual base virtual tables, also in inheritance graph
1802 // order, and again excluding primary bases (which share virtual tables with
1803 // the classes for which they are primary).
1804 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1805 E = RD->bases_end(); I != E; ++I) {
1806 const CXXRecordDecl *BaseDecl =
1807 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1808
1809 // Check if this base needs a vtable. (If it's virtual, not a primary base
1810 // of some other class, and we haven't visited it before).
1811 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1812 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1813 const ASTRecordLayout &MostDerivedClassLayout =
1814 Context.getASTRecordLayout(MostDerivedClass);
1815 CharUnits BaseOffset =
1816 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1817
1818 const ASTRecordLayout &LayoutClassLayout =
1819 Context.getASTRecordLayout(LayoutClass);
1820 CharUnits BaseOffsetInLayoutClass =
1821 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1822
1823 LayoutPrimaryAndSecondaryVTables(
1824 BaseSubobject(BaseDecl, BaseOffset),
1825 /*BaseIsMorallyVirtual=*/true,
1826 /*BaseIsVirtualInLayoutClass=*/true,
1827 BaseOffsetInLayoutClass);
1828 }
1829
1830 // We only need to check the base for virtual base vtables if it actually
1831 // has virtual bases.
1832 if (BaseDecl->getNumVBases())
1833 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1834 }
1835}
1836
1837/// dumpLayout - Dump the vtable layout.
1838void VTableBuilder::dumpLayout(raw_ostream& Out) {
1839
1840 if (isBuildingConstructorVTable()) {
1841 Out << "Construction vtable for ('";
1842 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1843 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1844 Out << LayoutClass->getQualifiedNameAsString();
1845 } else {
1846 Out << "Vtable for '";
1847 Out << MostDerivedClass->getQualifiedNameAsString();
1848 }
1849 Out << "' (" << Components.size() << " entries).\n";
1850
1851 // Iterate through the address points and insert them into a new map where
1852 // they are keyed by the index and not the base object.
1853 // Since an address point can be shared by multiple subobjects, we use an
1854 // STL multimap.
1855 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1856 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1857 E = AddressPoints.end(); I != E; ++I) {
1858 const BaseSubobject& Base = I->first;
1859 uint64_t Index = I->second;
1860
1861 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1862 }
1863
1864 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1865 uint64_t Index = I;
1866
1867 Out << llvm::format("%4d | ", I);
1868
1869 const VTableComponent &Component = Components[I];
1870
1871 // Dump the component.
1872 switch (Component.getKind()) {
1873
1874 case VTableComponent::CK_VCallOffset:
1875 Out << "vcall_offset ("
1876 << Component.getVCallOffset().getQuantity()
1877 << ")";
1878 break;
1879
1880 case VTableComponent::CK_VBaseOffset:
1881 Out << "vbase_offset ("
1882 << Component.getVBaseOffset().getQuantity()
1883 << ")";
1884 break;
1885
1886 case VTableComponent::CK_OffsetToTop:
1887 Out << "offset_to_top ("
1888 << Component.getOffsetToTop().getQuantity()
1889 << ")";
1890 break;
1891
1892 case VTableComponent::CK_RTTI:
1893 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
1894 break;
1895
1896 case VTableComponent::CK_FunctionPointer: {
1897 const CXXMethodDecl *MD = Component.getFunctionDecl();
1898
1899 std::string Str =
1900 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1901 MD);
1902 Out << Str;
1903 if (MD->isPure())
1904 Out << " [pure]";
1905
David Blaikied954ab42012-10-16 20:25:33 +00001906 if (MD->isDeleted())
1907 Out << " [deleted]";
1908
Peter Collingbourne24018462011-09-26 01:57:12 +00001909 ThunkInfo Thunk = VTableThunks.lookup(I);
1910 if (!Thunk.isEmpty()) {
1911 // If this function pointer has a return adjustment, dump it.
1912 if (!Thunk.Return.isEmpty()) {
1913 Out << "\n [return adjustment: ";
1914 Out << Thunk.Return.NonVirtual << " non-virtual";
1915
1916 if (Thunk.Return.VBaseOffsetOffset) {
1917 Out << ", " << Thunk.Return.VBaseOffsetOffset;
1918 Out << " vbase offset offset";
1919 }
1920
1921 Out << ']';
1922 }
1923
1924 // If this function pointer has a 'this' pointer adjustment, dump it.
1925 if (!Thunk.This.isEmpty()) {
1926 Out << "\n [this adjustment: ";
1927 Out << Thunk.This.NonVirtual << " non-virtual";
1928
1929 if (Thunk.This.VCallOffsetOffset) {
1930 Out << ", " << Thunk.This.VCallOffsetOffset;
1931 Out << " vcall offset offset";
1932 }
1933
1934 Out << ']';
1935 }
1936 }
1937
1938 break;
1939 }
1940
1941 case VTableComponent::CK_CompleteDtorPointer:
1942 case VTableComponent::CK_DeletingDtorPointer: {
1943 bool IsComplete =
1944 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
1945
1946 const CXXDestructorDecl *DD = Component.getDestructorDecl();
1947
1948 Out << DD->getQualifiedNameAsString();
1949 if (IsComplete)
1950 Out << "() [complete]";
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001951 else if (isMicrosoftABI())
1952 Out << "() [scalar deleting]";
Peter Collingbourne24018462011-09-26 01:57:12 +00001953 else
1954 Out << "() [deleting]";
1955
1956 if (DD->isPure())
1957 Out << " [pure]";
1958
1959 ThunkInfo Thunk = VTableThunks.lookup(I);
1960 if (!Thunk.isEmpty()) {
1961 // If this destructor has a 'this' pointer adjustment, dump it.
1962 if (!Thunk.This.isEmpty()) {
1963 Out << "\n [this adjustment: ";
1964 Out << Thunk.This.NonVirtual << " non-virtual";
1965
1966 if (Thunk.This.VCallOffsetOffset) {
1967 Out << ", " << Thunk.This.VCallOffsetOffset;
1968 Out << " vcall offset offset";
1969 }
1970
1971 Out << ']';
1972 }
1973 }
1974
1975 break;
1976 }
1977
1978 case VTableComponent::CK_UnusedFunctionPointer: {
1979 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
1980
1981 std::string Str =
1982 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1983 MD);
1984 Out << "[unused] " << Str;
1985 if (MD->isPure())
1986 Out << " [pure]";
1987 }
1988
1989 }
1990
1991 Out << '\n';
1992
1993 // Dump the next address point.
1994 uint64_t NextIndex = Index + 1;
1995 if (AddressPointsByIndex.count(NextIndex)) {
1996 if (AddressPointsByIndex.count(NextIndex) == 1) {
1997 const BaseSubobject &Base =
1998 AddressPointsByIndex.find(NextIndex)->second;
1999
2000 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
2001 Out << ", " << Base.getBaseOffset().getQuantity();
2002 Out << ") vtable address --\n";
2003 } else {
2004 CharUnits BaseOffset =
2005 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2006
2007 // We store the class names in a set to get a stable order.
2008 std::set<std::string> ClassNames;
2009 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2010 AddressPointsByIndex.lower_bound(NextIndex), E =
2011 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2012 assert(I->second.getBaseOffset() == BaseOffset &&
2013 "Invalid base offset!");
2014 const CXXRecordDecl *RD = I->second.getBase();
2015 ClassNames.insert(RD->getQualifiedNameAsString());
2016 }
2017
2018 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2019 E = ClassNames.end(); I != E; ++I) {
2020 Out << " -- (" << *I;
2021 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2022 }
2023 }
2024 }
2025 }
2026
2027 Out << '\n';
2028
2029 if (isBuildingConstructorVTable())
2030 return;
2031
2032 if (MostDerivedClass->getNumVBases()) {
2033 // We store the virtual base class names and their offsets in a map to get
2034 // a stable order.
2035
2036 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2037 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2038 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2039 std::string ClassName = I->first->getQualifiedNameAsString();
2040 CharUnits OffsetOffset = I->second;
2041 ClassNamesAndOffsets.insert(
2042 std::make_pair(ClassName, OffsetOffset));
2043 }
2044
2045 Out << "Virtual base offset offsets for '";
2046 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2047 Out << ClassNamesAndOffsets.size();
2048 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2049
2050 for (std::map<std::string, CharUnits>::const_iterator I =
2051 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2052 I != E; ++I)
2053 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2054
2055 Out << "\n";
2056 }
2057
2058 if (!Thunks.empty()) {
2059 // We store the method names in a map to get a stable order.
2060 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2061
2062 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2063 I != E; ++I) {
2064 const CXXMethodDecl *MD = I->first;
2065 std::string MethodName =
2066 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2067 MD);
2068
2069 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2070 }
2071
2072 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2073 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2074 I != E; ++I) {
2075 const std::string &MethodName = I->first;
2076 const CXXMethodDecl *MD = I->second;
2077
2078 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2079 std::sort(ThunksVector.begin(), ThunksVector.end());
2080
2081 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2082 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2083
2084 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2085 const ThunkInfo &Thunk = ThunksVector[I];
2086
2087 Out << llvm::format("%4d | ", I);
2088
2089 // If this function pointer has a return pointer adjustment, dump it.
2090 if (!Thunk.Return.isEmpty()) {
2091 Out << "return adjustment: " << Thunk.This.NonVirtual;
2092 Out << " non-virtual";
2093 if (Thunk.Return.VBaseOffsetOffset) {
2094 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2095 Out << " vbase offset offset";
2096 }
2097
2098 if (!Thunk.This.isEmpty())
2099 Out << "\n ";
2100 }
2101
2102 // If this function pointer has a 'this' pointer adjustment, dump it.
2103 if (!Thunk.This.isEmpty()) {
2104 Out << "this adjustment: ";
2105 Out << Thunk.This.NonVirtual << " non-virtual";
2106
2107 if (Thunk.This.VCallOffsetOffset) {
2108 Out << ", " << Thunk.This.VCallOffsetOffset;
2109 Out << " vcall offset offset";
2110 }
2111 }
2112
2113 Out << '\n';
2114 }
2115
2116 Out << '\n';
2117 }
2118 }
2119
2120 // Compute the vtable indices for all the member functions.
2121 // Store them in a map keyed by the index so we'll get a sorted table.
2122 std::map<uint64_t, std::string> IndicesMap;
2123
2124 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2125 e = MostDerivedClass->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002126 const CXXMethodDecl *MD = *i;
Peter Collingbourne24018462011-09-26 01:57:12 +00002127
2128 // We only want virtual member functions.
2129 if (!MD->isVirtual())
2130 continue;
2131
2132 std::string MethodName =
2133 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2134 MD);
2135
2136 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002137 // FIXME: Should add a layer of abstraction for vtable generation.
2138 if (!isMicrosoftABI()) {
Timur Iskhodzhanovd38a21f2013-06-05 12:24:46 +00002139 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Complete))]
2140 = MethodName + " [complete]";
2141 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))]
2142 = MethodName + " [deleting]";
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002143 } else {
Timur Iskhodzhanovd38a21f2013-06-05 12:24:46 +00002144 IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))]
2145 = MethodName + " [scalar deleting]";
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002146 }
Peter Collingbourne24018462011-09-26 01:57:12 +00002147 } else {
Timur Iskhodzhanovd38a21f2013-06-05 12:24:46 +00002148 IndicesMap[VTables.getMethodVTableIndex(MD)] = MethodName;
Peter Collingbourne24018462011-09-26 01:57:12 +00002149 }
2150 }
2151
2152 // Print the vtable indices for all the member functions.
2153 if (!IndicesMap.empty()) {
2154 Out << "VTable indices for '";
2155 Out << MostDerivedClass->getQualifiedNameAsString();
2156 Out << "' (" << IndicesMap.size() << " entries).\n";
2157
2158 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2159 E = IndicesMap.end(); I != E; ++I) {
2160 uint64_t VTableIndex = I->first;
2161 const std::string &MethodName = I->second;
2162
Timur Iskhodzhanovd38a21f2013-06-05 12:24:46 +00002163 Out << llvm::format(" %4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer79a55012012-03-10 02:06:27 +00002164 << '\n';
Peter Collingbourne24018462011-09-26 01:57:12 +00002165 }
2166 }
2167
2168 Out << '\n';
2169}
2170
2171}
2172
2173VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2174 const VTableComponent *VTableComponents,
2175 uint64_t NumVTableThunks,
2176 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002177 const AddressPointsMapTy &AddressPoints,
2178 bool IsMicrosoftABI)
Peter Collingbourne24018462011-09-26 01:57:12 +00002179 : NumVTableComponents(NumVTableComponents),
2180 VTableComponents(new VTableComponent[NumVTableComponents]),
2181 NumVTableThunks(NumVTableThunks),
2182 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002183 AddressPoints(AddressPoints),
2184 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbourne24018462011-09-26 01:57:12 +00002185 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002186 this->VTableComponents.get());
2187 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2188 this->VTableThunks.get());
Peter Collingbourne24018462011-09-26 01:57:12 +00002189}
2190
Benjamin Kramer8fb9fb62012-04-14 14:13:43 +00002191VTableLayout::~VTableLayout() { }
Peter Collingbourne24018462011-09-26 01:57:12 +00002192
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002193VTableContext::VTableContext(ASTContext &Context)
2194 : Context(Context),
John McCallb8b2c9d2013-01-25 22:30:49 +00002195 IsMicrosoftABI(Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2196}
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002197
Peter Collingbourne24018462011-09-26 01:57:12 +00002198VTableContext::~VTableContext() {
2199 llvm::DeleteContainerSeconds(VTableLayouts);
2200}
2201
Timur Iskhodzhanovd38a21f2013-06-05 12:24:46 +00002202static void
2203CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2204 VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2205 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2206 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2207
2208 if (!PrimaryBase)
2209 return;
2210
2211 CollectPrimaryBases(PrimaryBase, Context, PrimaryBases);
2212
2213 if (!PrimaryBases.insert(PrimaryBase))
2214 llvm_unreachable("Found a duplicate primary base!");
2215}
2216
2217void VTableContext::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2218
2219 // Itanium C++ ABI 2.5.2:
2220 // The order of the virtual function pointers in a virtual table is the
2221 // order of declaration of the corresponding member functions in the class.
2222 //
2223 // There is an entry for any virtual function declared in a class,
2224 // whether it is a new function or overrides a base class function,
2225 // unless it overrides a function from the primary base, and conversion
2226 // between their return types does not require an adjustment.
2227
2228 int64_t CurrentIndex = 0;
2229
2230 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2231 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2232
2233 if (PrimaryBase) {
2234 assert(PrimaryBase->isCompleteDefinition() &&
2235 "Should have the definition decl of the primary base!");
2236
2237 // Since the record decl shares its vtable pointer with the primary base
2238 // we need to start counting at the end of the primary base's vtable.
2239 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2240 }
2241
2242 // Collect all the primary bases, so we can check whether methods override
2243 // a method from the base.
2244 VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2245 CollectPrimaryBases(RD, Context, PrimaryBases);
2246
2247 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2248
2249 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2250 e = RD->method_end(); i != e; ++i) {
2251 const CXXMethodDecl *MD = *i;
2252
2253 // We only want virtual methods.
2254 if (!MD->isVirtual())
2255 continue;
2256
2257 // Check if this method overrides a method in the primary base.
2258 if (const CXXMethodDecl *OverriddenMD =
2259 FindNearestOverriddenMethod(MD, PrimaryBases)) {
2260 // Check if converting from the return type of the method to the
2261 // return type of the overridden method requires conversion.
2262 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
2263 OverriddenMD).isEmpty()) {
2264 // This index is shared between the index in the vtable of the primary
2265 // base class.
2266 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2267 const CXXDestructorDecl *OverriddenDD =
2268 cast<CXXDestructorDecl>(OverriddenMD);
2269
2270 if (!isMicrosoftABI()) {
2271 // Add both the complete and deleting entries.
2272 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2273 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2274 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2275 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2276 } else {
2277 // Add the scalar deleting destructor.
2278 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2279 getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2280 }
2281 } else {
2282 MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2283 }
2284
2285 // We don't need to add an entry for this method.
2286 continue;
2287 }
2288 }
2289
2290 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2291 if (MD->isImplicit()) {
2292 assert(!ImplicitVirtualDtor &&
2293 "Did already see an implicit virtual dtor!");
2294 ImplicitVirtualDtor = DD;
2295 continue;
2296 }
2297
2298 if (!isMicrosoftABI()) {
2299 // Add the complete dtor.
2300 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2301
2302 // Add the deleting dtor.
2303 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2304 } else {
2305 // Add the scalar deleting dtor.
2306 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2307 }
2308 } else {
2309 // Add the entry.
2310 MethodVTableIndices[MD] = CurrentIndex++;
2311 }
2312 }
2313
2314 if (ImplicitVirtualDtor) {
2315 // Itanium C++ ABI 2.5.2:
2316 // If a class has an implicitly-defined virtual destructor,
2317 // its entries come after the declared virtual function pointers.
2318
2319 if (isMicrosoftABI()) {
2320 ErrorUnsupported("implicit virtual destructor in the Microsoft ABI",
2321 ImplicitVirtualDtor->getLocation());
2322 }
2323
2324 // Add the complete dtor.
2325 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
2326 CurrentIndex++;
2327
2328 // Add the deleting dtor.
2329 MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
2330 CurrentIndex++;
2331 }
2332
2333 NumVirtualFunctionPointers[RD] = CurrentIndex;
2334}
2335
2336uint64_t VTableContext::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2337 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2338 NumVirtualFunctionPointers.find(RD);
2339 if (I != NumVirtualFunctionPointers.end())
2340 return I->second;
2341
2342 ComputeMethodVTableIndices(RD);
2343
2344 I = NumVirtualFunctionPointers.find(RD);
2345 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2346 return I->second;
2347}
2348
Peter Collingbourne24018462011-09-26 01:57:12 +00002349uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
2350 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2351 if (I != MethodVTableIndices.end())
2352 return I->second;
2353
2354 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2355
Timur Iskhodzhanovd38a21f2013-06-05 12:24:46 +00002356 ComputeMethodVTableIndices(RD);
Peter Collingbourne24018462011-09-26 01:57:12 +00002357
2358 I = MethodVTableIndices.find(GD);
2359 assert(I != MethodVTableIndices.end() && "Did not find index!");
2360 return I->second;
2361}
2362
2363CharUnits
2364VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2365 const CXXRecordDecl *VBase) {
2366 ClassPairTy ClassPair(RD, VBase);
2367
2368 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2369 VirtualBaseClassOffsetOffsets.find(ClassPair);
2370 if (I != VirtualBaseClassOffsetOffsets.end())
2371 return I->second;
2372
2373 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2374 BaseSubobject(RD, CharUnits::Zero()),
2375 /*BaseIsVirtual=*/false,
2376 /*OffsetInLayoutClass=*/CharUnits::Zero());
2377
2378 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2379 Builder.getVBaseOffsetOffsets().begin(),
2380 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2381 // Insert all types.
2382 ClassPairTy ClassPair(RD, I->first);
2383
2384 VirtualBaseClassOffsetOffsets.insert(
2385 std::make_pair(ClassPair, I->second));
2386 }
2387
2388 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2389 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2390
2391 return I->second;
2392}
2393
2394static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
2395 SmallVector<VTableLayout::VTableThunkTy, 1>
2396 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2397 std::sort(VTableThunks.begin(), VTableThunks.end());
2398
2399 return new VTableLayout(Builder.getNumVTableComponents(),
2400 Builder.vtable_component_begin(),
2401 VTableThunks.size(),
2402 VTableThunks.data(),
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002403 Builder.getAddressPoints(),
2404 Builder.isMicrosoftABI());
Peter Collingbourne24018462011-09-26 01:57:12 +00002405}
2406
2407void VTableContext::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
2408 const VTableLayout *&Entry = VTableLayouts[RD];
2409
2410 // Check if we've computed this information before.
2411 if (Entry)
2412 return;
2413
2414 VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2415 /*MostDerivedClassIsVirtual=*/0, RD);
2416 Entry = CreateVTableLayout(Builder);
2417
2418 // Add the known thunks.
2419 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2420
2421 // If we don't have the vbase information for this class, insert it.
2422 // getVirtualBaseOffsetOffset will compute it separately without computing
2423 // the rest of the vtable related information.
2424 if (!RD->getNumVBases())
2425 return;
2426
2427 const RecordType *VBaseRT =
2428 RD->vbases_begin()->getType()->getAs<RecordType>();
2429 const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2430
2431 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2432 return;
2433
2434 for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2435 Builder.getVBaseOffsetOffsets().begin(),
2436 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2437 // Insert all types.
2438 ClassPairTy ClassPair(RD, I->first);
2439
2440 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2441 }
2442}
2443
Timur Iskhodzhanov649c7312013-01-21 13:02:41 +00002444void VTableContext::ErrorUnsupported(StringRef Feature,
2445 SourceLocation Location) {
2446 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2447 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2448 "v-table layout for %0 is not supported yet");
2449 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2450}
2451
Peter Collingbourne24018462011-09-26 01:57:12 +00002452VTableLayout *VTableContext::createConstructionVTableLayout(
2453 const CXXRecordDecl *MostDerivedClass,
2454 CharUnits MostDerivedClassOffset,
2455 bool MostDerivedClassIsVirtual,
2456 const CXXRecordDecl *LayoutClass) {
2457 VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2458 MostDerivedClassIsVirtual, LayoutClass);
2459 return CreateVTableLayout(Builder);
2460}