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