blob: 01372341177ccc804513048789344787d17e0c95 [file] [log] [blame]
Peter Collingbournecfd23562011-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 Kramer2ef30312012-07-04 18:45:14 +000015#include "clang/AST/ASTContext.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/Basic/TargetInfo.h"
Reid Kleckner5f080942014-01-03 23:42:00 +000019#include "llvm/ADT/SmallPtrSet.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000020#include "llvm/Support/Format.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000021#include "llvm/Support/raw_ostream.h"
Peter Collingbournecfd23562011-09-26 01:57:12 +000022#include <algorithm>
23#include <cstdio>
24
25using namespace clang;
26
27#define DUMP_OVERRIDERS 0
28
29namespace {
30
31/// BaseOffset - Represents an offset from a derived class to a direct or
32/// indirect base class.
33struct BaseOffset {
34 /// DerivedClass - The derived class.
35 const CXXRecordDecl *DerivedClass;
36
37 /// VirtualBase - If the path from the derived class to the base class
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +000038 /// involves virtual base classes, this holds the declaration of the last
39 /// virtual base in this path (i.e. closest to the base class).
Peter Collingbournecfd23562011-09-26 01:57:12 +000040 const CXXRecordDecl *VirtualBase;
41
42 /// NonVirtualOffset - The offset from the derived class to the base class.
43 /// (Or the offset from the virtual base class to the base class, if the
44 /// path from the derived class to the base class involves a virtual base
45 /// class.
46 CharUnits NonVirtualOffset;
47
48 BaseOffset() : DerivedClass(0), VirtualBase(0),
49 NonVirtualOffset(CharUnits::Zero()) { }
50 BaseOffset(const CXXRecordDecl *DerivedClass,
51 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
52 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
53 NonVirtualOffset(NonVirtualOffset) { }
54
55 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
56};
57
58/// FinalOverriders - Contains the final overrider member functions for all
59/// member functions in the base subobjects of a class.
60class FinalOverriders {
61public:
62 /// OverriderInfo - Information about a final overrider.
63 struct OverriderInfo {
64 /// Method - The method decl of the overrider.
65 const CXXMethodDecl *Method;
66
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000067 /// Offset - the base offset of the overrider's parent in the layout class.
Peter Collingbournecfd23562011-09-26 01:57:12 +000068 CharUnits Offset;
69
70 OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
71 };
72
73private:
74 /// MostDerivedClass - The most derived class for which the final overriders
75 /// are stored.
76 const CXXRecordDecl *MostDerivedClass;
77
78 /// MostDerivedClassOffset - If we're building final overriders for a
79 /// construction vtable, this holds the offset from the layout class to the
80 /// most derived class.
81 const CharUnits MostDerivedClassOffset;
82
83 /// LayoutClass - The class we're using for layout information. Will be
84 /// different than the most derived class if the final overriders are for a
85 /// construction vtable.
86 const CXXRecordDecl *LayoutClass;
87
88 ASTContext &Context;
89
90 /// MostDerivedClassLayout - the AST record layout of the most derived class.
91 const ASTRecordLayout &MostDerivedClassLayout;
92
93 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
94 /// in a base subobject.
95 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
96
97 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
98 OverriderInfo> OverridersMapTy;
99
100 /// OverridersMap - The final overriders for all virtual member functions of
101 /// all the base subobjects of the most derived class.
102 OverridersMapTy OverridersMap;
103
104 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
105 /// as a record decl and a subobject number) and its offsets in the most
106 /// derived class as well as the layout class.
107 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
108 CharUnits> SubobjectOffsetMapTy;
109
110 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
111
112 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
113 /// given base.
114 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
115 CharUnits OffsetInLayoutClass,
116 SubobjectOffsetMapTy &SubobjectOffsets,
117 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
118 SubobjectCountMapTy &SubobjectCounts);
119
120 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
121
122 /// dump - dump the final overriders for a base subobject, and all its direct
123 /// and indirect base subobjects.
124 void dump(raw_ostream &Out, BaseSubobject Base,
125 VisitedVirtualBasesSetTy& VisitedVirtualBases);
126
127public:
128 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
129 CharUnits MostDerivedClassOffset,
130 const CXXRecordDecl *LayoutClass);
131
132 /// getOverrider - Get the final overrider for the given method declaration in
133 /// the subobject with the given base offset.
134 OverriderInfo getOverrider(const CXXMethodDecl *MD,
135 CharUnits BaseOffset) const {
136 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
137 "Did not find overrider!");
138
139 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
140 }
141
142 /// dump - dump the final overriders.
143 void dump() {
144 VisitedVirtualBasesSetTy VisitedVirtualBases;
145 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
146 VisitedVirtualBases);
147 }
148
149};
150
Peter Collingbournecfd23562011-09-26 01:57:12 +0000151FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
152 CharUnits MostDerivedClassOffset,
153 const CXXRecordDecl *LayoutClass)
154 : MostDerivedClass(MostDerivedClass),
155 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
156 Context(MostDerivedClass->getASTContext()),
157 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
158
159 // Compute base offsets.
160 SubobjectOffsetMapTy SubobjectOffsets;
161 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
162 SubobjectCountMapTy SubobjectCounts;
163 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
164 /*IsVirtual=*/false,
165 MostDerivedClassOffset,
166 SubobjectOffsets, SubobjectLayoutClassOffsets,
167 SubobjectCounts);
168
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000169 // Get the final overriders.
Peter Collingbournecfd23562011-09-26 01:57:12 +0000170 CXXFinalOverriderMap FinalOverriders;
171 MostDerivedClass->getFinalOverriders(FinalOverriders);
172
173 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
174 E = FinalOverriders.end(); I != E; ++I) {
175 const CXXMethodDecl *MD = I->first;
176 const OverridingMethods& Methods = I->second;
177
178 for (OverridingMethods::const_iterator I = Methods.begin(),
179 E = Methods.end(); I != E; ++I) {
180 unsigned SubobjectNumber = I->first;
181 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
182 SubobjectNumber)) &&
183 "Did not find subobject offset!");
184
185 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
186 SubobjectNumber)];
187
188 assert(I->second.size() == 1 && "Final overrider is not unique!");
189 const UniqueVirtualMethod &Method = I->second.front();
190
191 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
192 assert(SubobjectLayoutClassOffsets.count(
193 std::make_pair(OverriderRD, Method.Subobject))
194 && "Did not find subobject offset!");
195 CharUnits OverriderOffset =
196 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
197 Method.Subobject)];
198
199 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
200 assert(!Overrider.Method && "Overrider should not exist yet!");
201
202 Overrider.Offset = OverriderOffset;
203 Overrider.Method = Method.Method;
204 }
205 }
206
207#if DUMP_OVERRIDERS
208 // And dump them (for now).
209 dump();
210#endif
211}
212
213static BaseOffset ComputeBaseOffset(ASTContext &Context,
214 const CXXRecordDecl *DerivedRD,
215 const CXXBasePath &Path) {
216 CharUnits NonVirtualOffset = CharUnits::Zero();
217
218 unsigned NonVirtualStart = 0;
219 const CXXRecordDecl *VirtualBase = 0;
220
221 // First, look for the virtual base class.
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000222 for (int I = Path.size(), E = 0; I != E; --I) {
223 const CXXBasePathElement &Element = Path[I - 1];
224
Peter Collingbournecfd23562011-09-26 01:57:12 +0000225 if (Element.Base->isVirtual()) {
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000226 NonVirtualStart = I;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000227 QualType VBaseType = Element.Base->getType();
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000228 VirtualBase = VBaseType->getAsCXXRecordDecl();
Timur Iskhodzhanovbb5a17e2013-05-08 08:09:21 +0000229 break;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000230 }
231 }
232
233 // Now compute the non-virtual offset.
234 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
235 const CXXBasePathElement &Element = Path[I];
236
237 // Check the base class offset.
238 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
239
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +0000240 const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000241
242 NonVirtualOffset += Layout.getBaseClassOffset(Base);
243 }
244
245 // FIXME: This should probably use CharUnits or something. Maybe we should
246 // even change the base offsets in ASTRecordLayout to be specified in
247 // CharUnits.
248 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
249
250}
251
252static BaseOffset ComputeBaseOffset(ASTContext &Context,
253 const CXXRecordDecl *BaseRD,
254 const CXXRecordDecl *DerivedRD) {
255 CXXBasePaths Paths(/*FindAmbiguities=*/false,
256 /*RecordPaths=*/true, /*DetectVirtual=*/false);
Benjamin Kramer325d7452013-02-03 18:55:34 +0000257
258 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000259 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +0000260
261 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
262}
263
264static BaseOffset
265ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
266 const CXXMethodDecl *DerivedMD,
267 const CXXMethodDecl *BaseMD) {
268 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
269 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
270
271 // Canonicalize the return types.
Alp Toker314cc812014-01-25 16:55:45 +0000272 CanQualType CanDerivedReturnType =
273 Context.getCanonicalType(DerivedFT->getReturnType());
274 CanQualType CanBaseReturnType =
275 Context.getCanonicalType(BaseFT->getReturnType());
276
Peter Collingbournecfd23562011-09-26 01:57:12 +0000277 assert(CanDerivedReturnType->getTypeClass() ==
278 CanBaseReturnType->getTypeClass() &&
279 "Types must have same type class!");
280
281 if (CanDerivedReturnType == CanBaseReturnType) {
282 // No adjustment needed.
283 return BaseOffset();
284 }
285
286 if (isa<ReferenceType>(CanDerivedReturnType)) {
287 CanDerivedReturnType =
288 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
289 CanBaseReturnType =
290 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
291 } else if (isa<PointerType>(CanDerivedReturnType)) {
292 CanDerivedReturnType =
293 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
294 CanBaseReturnType =
295 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
296 } else {
297 llvm_unreachable("Unexpected return type!");
298 }
299
300 // We need to compare unqualified types here; consider
301 // const T *Base::foo();
302 // T *Derived::foo();
303 if (CanDerivedReturnType.getUnqualifiedType() ==
304 CanBaseReturnType.getUnqualifiedType()) {
305 // No adjustment needed.
306 return BaseOffset();
307 }
308
309 const CXXRecordDecl *DerivedRD =
310 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
311
312 const CXXRecordDecl *BaseRD =
313 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
314
315 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
316}
317
318void
319FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
320 CharUnits OffsetInLayoutClass,
321 SubobjectOffsetMapTy &SubobjectOffsets,
322 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
323 SubobjectCountMapTy &SubobjectCounts) {
324 const CXXRecordDecl *RD = Base.getBase();
325
326 unsigned SubobjectNumber = 0;
327 if (!IsVirtual)
328 SubobjectNumber = ++SubobjectCounts[RD];
329
330 // Set up the subobject to offset mapping.
331 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
332 && "Subobject offset already exists!");
333 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
334 && "Subobject offset already exists!");
335
336 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
337 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
338 OffsetInLayoutClass;
339
340 // Traverse our bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000341 for (const auto &I : RD->bases()) {
342 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000343
344 CharUnits BaseOffset;
345 CharUnits BaseOffsetInLayoutClass;
Aaron Ballman574705e2014-03-13 15:41:46 +0000346 if (I.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000347 // Check if we've visited this virtual base before.
348 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
349 continue;
350
351 const ASTRecordLayout &LayoutClassLayout =
352 Context.getASTRecordLayout(LayoutClass);
353
354 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
355 BaseOffsetInLayoutClass =
356 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
357 } else {
358 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
359 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
360
361 BaseOffset = Base.getBaseOffset() + Offset;
362 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
363 }
364
365 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
Aaron Ballman574705e2014-03-13 15:41:46 +0000366 I.isVirtual(), BaseOffsetInLayoutClass,
Peter Collingbournecfd23562011-09-26 01:57:12 +0000367 SubobjectOffsets, SubobjectLayoutClassOffsets,
368 SubobjectCounts);
369 }
370}
371
372void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
373 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
374 const CXXRecordDecl *RD = Base.getBase();
375 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
376
Aaron Ballman574705e2014-03-13 15:41:46 +0000377 for (const auto &I : RD->bases()) {
378 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000379
380 // Ignore bases that don't have any virtual member functions.
381 if (!BaseDecl->isPolymorphic())
382 continue;
383
384 CharUnits BaseOffset;
Aaron Ballman574705e2014-03-13 15:41:46 +0000385 if (I.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000386 if (!VisitedVirtualBases.insert(BaseDecl)) {
387 // We've visited this base before.
388 continue;
389 }
390
391 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
392 } else {
393 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
394 }
395
396 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
397 }
398
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000399 Out << "Final overriders for (";
400 RD->printQualifiedName(Out);
401 Out << ", ";
Peter Collingbournecfd23562011-09-26 01:57:12 +0000402 Out << Base.getBaseOffset().getQuantity() << ")\n";
403
404 // Now dump the overriders for this base subobject.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000405 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000406 if (!MD->isVirtual())
407 continue;
408
409 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
410
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000411 Out << " ";
412 MD->printQualifiedName(Out);
413 Out << " - (";
414 Overrider.Method->printQualifiedName(Out);
Timur Iskhodzhanovbe5a3d82013-06-05 06:40:07 +0000415 Out << ", " << Overrider.Offset.getQuantity() << ')';
Peter Collingbournecfd23562011-09-26 01:57:12 +0000416
417 BaseOffset Offset;
418 if (!Overrider.Method->isPure())
419 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
420
421 if (!Offset.isEmpty()) {
422 Out << " [ret-adj: ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000423 if (Offset.VirtualBase) {
424 Offset.VirtualBase->printQualifiedName(Out);
425 Out << " vbase, ";
426 }
Peter Collingbournecfd23562011-09-26 01:57:12 +0000427
428 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
429 }
430
431 Out << "\n";
432 }
433}
434
435/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
436struct VCallOffsetMap {
437
438 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
439
440 /// Offsets - Keeps track of methods and their offsets.
441 // FIXME: This should be a real map and not a vector.
442 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
443
444 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
445 /// can share the same vcall offset.
446 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
447 const CXXMethodDecl *RHS);
448
449public:
450 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
451 /// add was successful, or false if there was already a member function with
452 /// the same signature in the map.
453 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
454
455 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
456 /// vtable address point) for the given virtual member function.
457 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
458
459 // empty - Return whether the offset map is empty or not.
460 bool empty() const { return Offsets.empty(); }
461};
462
463static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
464 const CXXMethodDecl *RHS) {
John McCallb6c4a7e2012-03-21 06:57:19 +0000465 const FunctionProtoType *LT =
466 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
467 const FunctionProtoType *RT =
468 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000469
470 // Fast-path matches in the canonical types.
471 if (LT == RT) return true;
472
473 // Force the signatures to match. We can't rely on the overrides
474 // list here because there isn't necessarily an inheritance
475 // relationship between the two methods.
John McCallb6c4a7e2012-03-21 06:57:19 +0000476 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000477 LT->getNumParams() != RT->getNumParams())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000478 return false;
Alp Toker9cacbab2014-01-20 20:26:09 +0000479 for (unsigned I = 0, E = LT->getNumParams(); I != E; ++I)
480 if (LT->getParamType(I) != RT->getParamType(I))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000481 return false;
482 return true;
483}
484
485bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
486 const CXXMethodDecl *RHS) {
487 assert(LHS->isVirtual() && "LHS must be virtual!");
488 assert(RHS->isVirtual() && "LHS must be virtual!");
489
490 // A destructor can share a vcall offset with another destructor.
491 if (isa<CXXDestructorDecl>(LHS))
492 return isa<CXXDestructorDecl>(RHS);
493
494 // FIXME: We need to check more things here.
495
496 // The methods must have the same name.
497 DeclarationName LHSName = LHS->getDeclName();
498 DeclarationName RHSName = RHS->getDeclName();
499 if (LHSName != RHSName)
500 return false;
501
502 // And the same signatures.
503 return HasSameVirtualSignature(LHS, RHS);
504}
505
506bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
507 CharUnits OffsetOffset) {
508 // Check if we can reuse an offset.
509 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
510 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
511 return false;
512 }
513
514 // Add the offset.
515 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
516 return true;
517}
518
519CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
520 // Look for an offset.
521 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
522 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
523 return Offsets[I].second;
524 }
525
526 llvm_unreachable("Should always find a vcall offset offset!");
527}
528
529/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
530class VCallAndVBaseOffsetBuilder {
531public:
532 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
533 VBaseOffsetOffsetsMapTy;
534
535private:
536 /// MostDerivedClass - The most derived class for which we're building vcall
537 /// and vbase offsets.
538 const CXXRecordDecl *MostDerivedClass;
539
540 /// LayoutClass - The class we're using for layout information. Will be
541 /// different than the most derived class if we're building a construction
542 /// vtable.
543 const CXXRecordDecl *LayoutClass;
544
545 /// Context - The ASTContext which we will use for layout information.
546 ASTContext &Context;
547
548 /// Components - vcall and vbase offset components
549 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
550 VTableComponentVectorTy Components;
551
552 /// VisitedVirtualBases - Visited virtual bases.
553 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
554
555 /// VCallOffsets - Keeps track of vcall offsets.
556 VCallOffsetMap VCallOffsets;
557
558
559 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
560 /// relative to the address point.
561 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
562
563 /// FinalOverriders - The final overriders of the most derived class.
564 /// (Can be null when we're not building a vtable of the most derived class).
565 const FinalOverriders *Overriders;
566
567 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
568 /// given base subobject.
569 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
570 CharUnits RealBaseOffset);
571
572 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
573 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
574
575 /// AddVBaseOffsets - Add vbase offsets for the given class.
576 void AddVBaseOffsets(const CXXRecordDecl *Base,
577 CharUnits OffsetInLayoutClass);
578
579 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
580 /// chars, relative to the vtable address point.
581 CharUnits getCurrentOffsetOffset() const;
582
583public:
584 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
585 const CXXRecordDecl *LayoutClass,
586 const FinalOverriders *Overriders,
587 BaseSubobject Base, bool BaseIsVirtual,
588 CharUnits OffsetInLayoutClass)
589 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
590 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
591
592 // Add vcall and vbase offsets.
593 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
594 }
595
596 /// Methods for iterating over the components.
597 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
598 const_iterator components_begin() const { return Components.rbegin(); }
599 const_iterator components_end() const { return Components.rend(); }
600
601 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
602 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
603 return VBaseOffsetOffsets;
604 }
605};
606
607void
608VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
609 bool BaseIsVirtual,
610 CharUnits RealBaseOffset) {
611 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
612
613 // Itanium C++ ABI 2.5.2:
614 // ..in classes sharing a virtual table with a primary base class, the vcall
615 // and vbase offsets added by the derived class all come before the vcall
616 // and vbase offsets required by the base class, so that the latter may be
617 // laid out as required by the base class without regard to additions from
618 // the derived class(es).
619
620 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
621 // emit them for the primary base first).
622 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
623 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
624
625 CharUnits PrimaryBaseOffset;
626
627 // Get the base offset of the primary base.
628 if (PrimaryBaseIsVirtual) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000629 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000630 "Primary vbase should have a zero offset!");
631
632 const ASTRecordLayout &MostDerivedClassLayout =
633 Context.getASTRecordLayout(MostDerivedClass);
634
635 PrimaryBaseOffset =
636 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
637 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000638 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000639 "Primary base should have a zero offset!");
640
641 PrimaryBaseOffset = Base.getBaseOffset();
642 }
643
644 AddVCallAndVBaseOffsets(
645 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
646 PrimaryBaseIsVirtual, RealBaseOffset);
647 }
648
649 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
650
651 // We only want to add vcall offsets for virtual bases.
652 if (BaseIsVirtual)
653 AddVCallOffsets(Base, RealBaseOffset);
654}
655
656CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
657 // OffsetIndex is the index of this vcall or vbase offset, relative to the
658 // vtable address point. (We subtract 3 to account for the information just
659 // above the address point, the RTTI info, the offset to top, and the
660 // vcall offset itself).
661 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
662
663 CharUnits PointerWidth =
664 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
665 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
666 return OffsetOffset;
667}
668
669void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
670 CharUnits VBaseOffset) {
671 const CXXRecordDecl *RD = Base.getBase();
672 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
673
674 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
675
676 // Handle the primary base first.
677 // We only want to add vcall offsets if the base is non-virtual; a virtual
678 // primary base will have its vcall and vbase offsets emitted already.
679 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
680 // Get the base offset of the primary base.
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000681 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000682 "Primary base should have a zero offset!");
683
684 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
685 VBaseOffset);
686 }
687
688 // Add the vcall offsets.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000689 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000690 if (!MD->isVirtual())
691 continue;
692
693 CharUnits OffsetOffset = getCurrentOffsetOffset();
694
695 // Don't add a vcall offset if we already have one for this member function
696 // signature.
697 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
698 continue;
699
700 CharUnits Offset = CharUnits::Zero();
701
702 if (Overriders) {
703 // Get the final overrider.
704 FinalOverriders::OverriderInfo Overrider =
705 Overriders->getOverrider(MD, Base.getBaseOffset());
706
707 /// The vcall offset is the offset from the virtual base to the object
708 /// where the function was overridden.
709 Offset = Overrider.Offset - VBaseOffset;
710 }
711
712 Components.push_back(
713 VTableComponent::MakeVCallOffset(Offset));
714 }
715
716 // And iterate over all non-virtual bases (ignoring the primary base).
Aaron Ballman574705e2014-03-13 15:41:46 +0000717 for (const auto &I : RD->bases()) {
718 if (I.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000719 continue;
720
Aaron Ballman574705e2014-03-13 15:41:46 +0000721 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000722 if (BaseDecl == PrimaryBase)
723 continue;
724
725 // Get the base offset of this base.
726 CharUnits BaseOffset = Base.getBaseOffset() +
727 Layout.getBaseClassOffset(BaseDecl);
728
729 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
730 VBaseOffset);
731 }
732}
733
734void
735VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
736 CharUnits OffsetInLayoutClass) {
737 const ASTRecordLayout &LayoutClassLayout =
738 Context.getASTRecordLayout(LayoutClass);
739
740 // Add vbase offsets.
Aaron Ballman574705e2014-03-13 15:41:46 +0000741 for (const auto &I : RD->bases()) {
742 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000743
744 // Check if this is a virtual base that we haven't visited before.
Aaron Ballman574705e2014-03-13 15:41:46 +0000745 if (I.isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000746 CharUnits Offset =
747 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
748
749 // Add the vbase offset offset.
750 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
751 "vbase offset offset already exists!");
752
753 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
754 VBaseOffsetOffsets.insert(
755 std::make_pair(BaseDecl, VBaseOffsetOffset));
756
757 Components.push_back(
758 VTableComponent::MakeVBaseOffset(Offset));
759 }
760
761 // Check the base class looking for more vbase offsets.
762 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
763 }
764}
765
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000766/// ItaniumVTableBuilder - Class for building vtable layout information.
767class ItaniumVTableBuilder {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000768public:
769 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
770 /// primary bases.
771 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
772 PrimaryBasesSetVectorTy;
773
774 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
775 VBaseOffsetOffsetsMapTy;
776
777 typedef llvm::DenseMap<BaseSubobject, uint64_t>
778 AddressPointsMapTy;
779
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000780 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
781
Peter Collingbournecfd23562011-09-26 01:57:12 +0000782private:
783 /// VTables - Global vtable information.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000784 ItaniumVTableContext &VTables;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000785
786 /// MostDerivedClass - The most derived class for which we're building this
787 /// vtable.
788 const CXXRecordDecl *MostDerivedClass;
789
790 /// MostDerivedClassOffset - If we're building a construction vtable, this
791 /// holds the offset from the layout class to the most derived class.
792 const CharUnits MostDerivedClassOffset;
793
794 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
795 /// base. (This only makes sense when building a construction vtable).
796 bool MostDerivedClassIsVirtual;
797
798 /// LayoutClass - The class we're using for layout information. Will be
799 /// different than the most derived class if we're building a construction
800 /// vtable.
801 const CXXRecordDecl *LayoutClass;
802
803 /// Context - The ASTContext which we will use for layout information.
804 ASTContext &Context;
805
806 /// FinalOverriders - The final overriders of the most derived class.
807 const FinalOverriders Overriders;
808
809 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
810 /// bases in this vtable.
811 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
812
813 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
814 /// the most derived class.
815 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
816
817 /// Components - The components of the vtable being built.
818 SmallVector<VTableComponent, 64> Components;
819
820 /// AddressPoints - Address points for the vtable being built.
821 AddressPointsMapTy AddressPoints;
822
823 /// MethodInfo - Contains information about a method in a vtable.
824 /// (Used for computing 'this' pointer adjustment thunks.
825 struct MethodInfo {
826 /// BaseOffset - The base offset of this method.
827 const CharUnits BaseOffset;
828
829 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
830 /// method.
831 const CharUnits BaseOffsetInLayoutClass;
832
833 /// VTableIndex - The index in the vtable that this method has.
834 /// (For destructors, this is the index of the complete destructor).
835 const uint64_t VTableIndex;
836
837 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
838 uint64_t VTableIndex)
839 : BaseOffset(BaseOffset),
840 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
841 VTableIndex(VTableIndex) { }
842
843 MethodInfo()
844 : BaseOffset(CharUnits::Zero()),
845 BaseOffsetInLayoutClass(CharUnits::Zero()),
846 VTableIndex(0) { }
847 };
848
849 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
850
851 /// MethodInfoMap - The information for all methods in the vtable we're
852 /// currently building.
853 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000854
855 /// MethodVTableIndices - Contains the index (relative to the vtable address
856 /// point) where the function pointer for a virtual function is stored.
857 MethodVTableIndicesTy MethodVTableIndices;
858
Peter Collingbournecfd23562011-09-26 01:57:12 +0000859 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
860
861 /// VTableThunks - The thunks by vtable index in the vtable currently being
862 /// built.
863 VTableThunksMapTy VTableThunks;
864
865 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
866 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
867
868 /// Thunks - A map that contains all the thunks needed for all methods in the
869 /// most derived class for which the vtable is currently being built.
870 ThunksMapTy Thunks;
871
872 /// AddThunk - Add a thunk for the given method.
873 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
874
875 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
876 /// part of the vtable we're currently building.
877 void ComputeThisAdjustments();
878
879 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
880
881 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
882 /// some other base.
883 VisitedVirtualBasesSetTy PrimaryVirtualBases;
884
885 /// ComputeReturnAdjustment - Compute the return adjustment given a return
886 /// adjustment base offset.
887 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
888
889 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
890 /// the 'this' pointer from the base subobject to the derived subobject.
891 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
892 BaseSubobject Derived) const;
893
894 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
895 /// given virtual member function, its offset in the layout class and its
896 /// final overrider.
897 ThisAdjustment
898 ComputeThisAdjustment(const CXXMethodDecl *MD,
899 CharUnits BaseOffsetInLayoutClass,
900 FinalOverriders::OverriderInfo Overrider);
901
902 /// AddMethod - Add a single virtual member function to the vtable
903 /// components vector.
904 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
905
906 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
907 /// part of the vtable.
908 ///
909 /// Itanium C++ ABI 2.5.2:
910 ///
911 /// struct A { virtual void f(); };
912 /// struct B : virtual public A { int i; };
913 /// struct C : virtual public A { int j; };
914 /// struct D : public B, public C {};
915 ///
916 /// When B and C are declared, A is a primary base in each case, so although
917 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
918 /// adjustment is required and no thunk is generated. However, inside D
919 /// objects, A is no longer a primary base of C, so if we allowed calls to
920 /// C::f() to use the copy of A's vtable in the C subobject, we would need
921 /// to adjust this from C* to B::A*, which would require a third-party
922 /// thunk. Since we require that a call to C::f() first convert to A*,
923 /// C-in-D's copy of A's vtable is never referenced, so this is not
924 /// necessary.
925 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
926 CharUnits BaseOffsetInLayoutClass,
927 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
928 CharUnits FirstBaseOffsetInLayoutClass) const;
929
930
931 /// AddMethods - Add the methods of this base subobject and all its
932 /// primary bases to the vtable components vector.
933 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
934 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
935 CharUnits FirstBaseOffsetInLayoutClass,
936 PrimaryBasesSetVectorTy &PrimaryBases);
937
938 // LayoutVTable - Layout the vtable for the given base class, including its
939 // secondary vtables and any vtables for virtual bases.
940 void LayoutVTable();
941
942 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
943 /// given base subobject, as well as all its secondary vtables.
944 ///
945 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
946 /// or a direct or indirect base of a virtual base.
947 ///
948 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
949 /// in the layout class.
950 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
951 bool BaseIsMorallyVirtual,
952 bool BaseIsVirtualInLayoutClass,
953 CharUnits OffsetInLayoutClass);
954
955 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
956 /// subobject.
957 ///
958 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
959 /// or a direct or indirect base of a virtual base.
960 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
961 CharUnits OffsetInLayoutClass);
962
963 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
964 /// class hierarchy.
965 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
966 CharUnits OffsetInLayoutClass,
967 VisitedVirtualBasesSetTy &VBases);
968
969 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
970 /// given base (excluding any primary bases).
971 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
972 VisitedVirtualBasesSetTy &VBases);
973
974 /// isBuildingConstructionVTable - Return whether this vtable builder is
975 /// building a construction vtable.
976 bool isBuildingConstructorVTable() const {
977 return MostDerivedClass != LayoutClass;
978 }
979
980public:
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000981 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
982 const CXXRecordDecl *MostDerivedClass,
983 CharUnits MostDerivedClassOffset,
984 bool MostDerivedClassIsVirtual,
985 const CXXRecordDecl *LayoutClass)
986 : VTables(VTables), MostDerivedClass(MostDerivedClass),
987 MostDerivedClassOffset(MostDerivedClassOffset),
988 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
989 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
990 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000991 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000992
993 LayoutVTable();
994
David Blaikiebbafb8a2012-03-11 07:00:24 +0000995 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +0000996 dumpLayout(llvm::outs());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000997 }
998
999 uint64_t getNumThunks() const {
1000 return Thunks.size();
1001 }
1002
1003 ThunksMapTy::const_iterator thunks_begin() const {
1004 return Thunks.begin();
1005 }
1006
1007 ThunksMapTy::const_iterator thunks_end() const {
1008 return Thunks.end();
1009 }
1010
1011 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1012 return VBaseOffsetOffsets;
1013 }
1014
1015 const AddressPointsMapTy &getAddressPoints() const {
1016 return AddressPoints;
1017 }
1018
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001019 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1020 return MethodVTableIndices.begin();
1021 }
1022
1023 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1024 return MethodVTableIndices.end();
1025 }
1026
Peter Collingbournecfd23562011-09-26 01:57:12 +00001027 /// getNumVTableComponents - Return the number of components in the vtable
1028 /// currently built.
1029 uint64_t getNumVTableComponents() const {
1030 return Components.size();
1031 }
1032
1033 const VTableComponent *vtable_component_begin() const {
1034 return Components.begin();
1035 }
1036
1037 const VTableComponent *vtable_component_end() const {
1038 return Components.end();
1039 }
1040
1041 AddressPointsMapTy::const_iterator address_points_begin() const {
1042 return AddressPoints.begin();
1043 }
1044
1045 AddressPointsMapTy::const_iterator address_points_end() const {
1046 return AddressPoints.end();
1047 }
1048
1049 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1050 return VTableThunks.begin();
1051 }
1052
1053 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1054 return VTableThunks.end();
1055 }
1056
1057 /// dumpLayout - Dump the vtable layout.
1058 void dumpLayout(raw_ostream&);
1059};
1060
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001061void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1062 const ThunkInfo &Thunk) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001063 assert(!isBuildingConstructorVTable() &&
1064 "Can't add thunks for construction vtable");
1065
Craig Topper5603df42013-07-05 19:34:19 +00001066 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1067
Peter Collingbournecfd23562011-09-26 01:57:12 +00001068 // Check if we have this thunk already.
1069 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1070 ThunksVector.end())
1071 return;
1072
1073 ThunksVector.push_back(Thunk);
1074}
1075
1076typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1077
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001078/// Visit all the methods overridden by the given method recursively,
1079/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1080/// indicating whether to continue the recursion for the given overridden
1081/// method (i.e. returning false stops the iteration).
1082template <class VisitorTy>
1083static void
1084visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001085 assert(MD->isVirtual() && "Method is not virtual!");
1086
1087 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1088 E = MD->end_overridden_methods(); I != E; ++I) {
1089 const CXXMethodDecl *OverriddenMD = *I;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001090 if (!Visitor.visit(OverriddenMD))
1091 continue;
1092 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001093 }
1094}
1095
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001096namespace {
1097 struct OverriddenMethodsCollector {
1098 OverriddenMethodsSetTy *Methods;
1099
1100 bool visit(const CXXMethodDecl *MD) {
1101 // Don't recurse on this method if we've already collected it.
1102 return Methods->insert(MD);
1103 }
1104 };
1105}
1106
1107/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1108/// the overridden methods that the function decl overrides.
1109static void
1110ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1111 OverriddenMethodsSetTy& OverriddenMethods) {
1112 OverriddenMethodsCollector Collector = { &OverriddenMethods };
1113 visitAllOverriddenMethods(MD, Collector);
1114}
1115
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001116void ItaniumVTableBuilder::ComputeThisAdjustments() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001117 // Now go through the method info map and see if any of the methods need
1118 // 'this' pointer adjustments.
1119 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1120 E = MethodInfoMap.end(); I != E; ++I) {
1121 const CXXMethodDecl *MD = I->first;
1122 const MethodInfo &MethodInfo = I->second;
1123
1124 // Ignore adjustments for unused function pointers.
1125 uint64_t VTableIndex = MethodInfo.VTableIndex;
1126 if (Components[VTableIndex].getKind() ==
1127 VTableComponent::CK_UnusedFunctionPointer)
1128 continue;
1129
1130 // Get the final overrider for this method.
1131 FinalOverriders::OverriderInfo Overrider =
1132 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1133
1134 // Check if we need an adjustment at all.
1135 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1136 // When a return thunk is needed by a derived class that overrides a
1137 // virtual base, gcc uses a virtual 'this' adjustment as well.
1138 // While the thunk itself might be needed by vtables in subclasses or
1139 // in construction vtables, there doesn't seem to be a reason for using
1140 // the thunk in this vtable. Still, we do so to match gcc.
1141 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1142 continue;
1143 }
1144
1145 ThisAdjustment ThisAdjustment =
1146 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1147
1148 if (ThisAdjustment.isEmpty())
1149 continue;
1150
1151 // Add it.
1152 VTableThunks[VTableIndex].This = ThisAdjustment;
1153
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001154 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001155 // Add an adjustment for the deleting destructor as well.
1156 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1157 }
1158 }
1159
1160 /// Clear the method info map.
1161 MethodInfoMap.clear();
1162
1163 if (isBuildingConstructorVTable()) {
1164 // We don't need to store thunk information for construction vtables.
1165 return;
1166 }
1167
1168 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1169 E = VTableThunks.end(); I != E; ++I) {
1170 const VTableComponent &Component = Components[I->first];
1171 const ThunkInfo &Thunk = I->second;
1172 const CXXMethodDecl *MD;
1173
1174 switch (Component.getKind()) {
1175 default:
1176 llvm_unreachable("Unexpected vtable component kind!");
1177 case VTableComponent::CK_FunctionPointer:
1178 MD = Component.getFunctionDecl();
1179 break;
1180 case VTableComponent::CK_CompleteDtorPointer:
1181 MD = Component.getDestructorDecl();
1182 break;
1183 case VTableComponent::CK_DeletingDtorPointer:
1184 // We've already added the thunk when we saw the complete dtor pointer.
1185 continue;
1186 }
1187
1188 if (MD->getParent() == MostDerivedClass)
1189 AddThunk(MD, Thunk);
1190 }
1191}
1192
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001193ReturnAdjustment
1194ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001195 ReturnAdjustment Adjustment;
1196
1197 if (!Offset.isEmpty()) {
1198 if (Offset.VirtualBase) {
1199 // Get the virtual base offset offset.
1200 if (Offset.DerivedClass == MostDerivedClass) {
1201 // We can get the offset offset directly from our map.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001202 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001203 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1204 } else {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001205 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001206 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1207 Offset.VirtualBase).getQuantity();
1208 }
1209 }
1210
1211 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1212 }
1213
1214 return Adjustment;
1215}
1216
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001217BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1218 BaseSubobject Base, BaseSubobject Derived) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001219 const CXXRecordDecl *BaseRD = Base.getBase();
1220 const CXXRecordDecl *DerivedRD = Derived.getBase();
1221
1222 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1223 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1224
Benjamin Kramer325d7452013-02-03 18:55:34 +00001225 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +00001226 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +00001227
1228 // We have to go through all the paths, and see which one leads us to the
1229 // right base subobject.
1230 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1231 I != E; ++I) {
1232 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1233
1234 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1235
1236 if (Offset.VirtualBase) {
1237 // If we have a virtual base class, the non-virtual offset is relative
1238 // to the virtual base class offset.
1239 const ASTRecordLayout &LayoutClassLayout =
1240 Context.getASTRecordLayout(LayoutClass);
1241
1242 /// Get the virtual base offset, relative to the most derived class
1243 /// layout.
1244 OffsetToBaseSubobject +=
1245 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1246 } else {
1247 // Otherwise, the non-virtual offset is relative to the derived class
1248 // offset.
1249 OffsetToBaseSubobject += Derived.getBaseOffset();
1250 }
1251
1252 // Check if this path gives us the right base subobject.
1253 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1254 // Since we're going from the base class _to_ the derived class, we'll
1255 // invert the non-virtual offset here.
1256 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1257 return Offset;
1258 }
1259 }
1260
1261 return BaseOffset();
1262}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001263
1264ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1265 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1266 FinalOverriders::OverriderInfo Overrider) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001267 // Ignore adjustments for pure virtual member functions.
1268 if (Overrider.Method->isPure())
1269 return ThisAdjustment();
1270
1271 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1272 BaseOffsetInLayoutClass);
1273
1274 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1275 Overrider.Offset);
1276
1277 // Compute the adjustment offset.
1278 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1279 OverriderBaseSubobject);
1280 if (Offset.isEmpty())
1281 return ThisAdjustment();
1282
1283 ThisAdjustment Adjustment;
1284
1285 if (Offset.VirtualBase) {
1286 // Get the vcall offset map for this virtual base.
1287 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1288
1289 if (VCallOffsets.empty()) {
1290 // We don't have vcall offsets for this virtual base, go ahead and
1291 // build them.
1292 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1293 /*FinalOverriders=*/0,
1294 BaseSubobject(Offset.VirtualBase,
1295 CharUnits::Zero()),
1296 /*BaseIsVirtual=*/true,
1297 /*OffsetInLayoutClass=*/
1298 CharUnits::Zero());
1299
1300 VCallOffsets = Builder.getVCallOffsets();
1301 }
1302
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001303 Adjustment.Virtual.Itanium.VCallOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001304 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1305 }
1306
1307 // Set the non-virtual part of the adjustment.
1308 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1309
1310 return Adjustment;
1311}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001312
1313void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1314 ReturnAdjustment ReturnAdjustment) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001315 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1316 assert(ReturnAdjustment.isEmpty() &&
1317 "Destructor can't have return adjustment!");
1318
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001319 // Add both the complete destructor and the deleting destructor.
1320 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1321 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbournecfd23562011-09-26 01:57:12 +00001322 } else {
1323 // Add the return adjustment if necessary.
1324 if (!ReturnAdjustment.isEmpty())
1325 VTableThunks[Components.size()].Return = ReturnAdjustment;
1326
1327 // Add the function.
1328 Components.push_back(VTableComponent::MakeFunction(MD));
1329 }
1330}
1331
1332/// OverridesIndirectMethodInBase - Return whether the given member function
1333/// overrides any methods in the set of given bases.
1334/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1335/// For example, if we have:
1336///
1337/// struct A { virtual void f(); }
1338/// struct B : A { virtual void f(); }
1339/// struct C : B { virtual void f(); }
1340///
1341/// OverridesIndirectMethodInBase will return true if given C::f as the method
1342/// and { A } as the set of bases.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001343static bool OverridesIndirectMethodInBases(
1344 const CXXMethodDecl *MD,
1345 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001346 if (Bases.count(MD->getParent()))
1347 return true;
1348
1349 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1350 E = MD->end_overridden_methods(); I != E; ++I) {
1351 const CXXMethodDecl *OverriddenMD = *I;
1352
1353 // Check "indirect overriders".
1354 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1355 return true;
1356 }
1357
1358 return false;
1359}
1360
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001361bool ItaniumVTableBuilder::IsOverriderUsed(
1362 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1363 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1364 CharUnits FirstBaseOffsetInLayoutClass) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001365 // If the base and the first base in the primary base chain have the same
1366 // offsets, then this overrider will be used.
1367 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1368 return true;
1369
1370 // We know now that Base (or a direct or indirect base of it) is a primary
1371 // base in part of the class hierarchy, but not a primary base in the most
1372 // derived class.
1373
1374 // If the overrider is the first base in the primary base chain, we know
1375 // that the overrider will be used.
1376 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1377 return true;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001378
1379 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001380
1381 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1382 PrimaryBases.insert(RD);
1383
1384 // Now traverse the base chain, starting with the first base, until we find
1385 // the base that is no longer a primary base.
1386 while (true) {
1387 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1388 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1389
1390 if (!PrimaryBase)
1391 break;
1392
1393 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001394 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001395 "Primary base should always be at offset 0!");
1396
1397 const ASTRecordLayout &LayoutClassLayout =
1398 Context.getASTRecordLayout(LayoutClass);
1399
1400 // Now check if this is the primary base that is not a primary base in the
1401 // most derived class.
1402 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1403 FirstBaseOffsetInLayoutClass) {
1404 // We found it, stop walking the chain.
1405 break;
1406 }
1407 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001408 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001409 "Primary base should always be at offset 0!");
1410 }
1411
1412 if (!PrimaryBases.insert(PrimaryBase))
1413 llvm_unreachable("Found a duplicate primary base!");
1414
1415 RD = PrimaryBase;
1416 }
1417
1418 // If the final overrider is an override of one of the primary bases,
1419 // then we know that it will be used.
1420 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1421}
1422
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001423typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1424
Peter Collingbournecfd23562011-09-26 01:57:12 +00001425/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1426/// from the nearest base. Returns null if no method was found.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001427/// The Bases are expected to be sorted in a base-to-derived order.
1428static const CXXMethodDecl *
Peter Collingbournecfd23562011-09-26 01:57:12 +00001429FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001430 BasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001431 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
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001437 // Now check the overridden methods.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001438 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;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001449}
Peter Collingbournecfd23562011-09-26 01:57:12 +00001450
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001451void ItaniumVTableBuilder::AddMethods(
1452 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1453 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1454 CharUnits FirstBaseOffsetInLayoutClass,
1455 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +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 Collingbournecfd23562011-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 Kramer2ef30312012-07-04 18:45:14 +00001472 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-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 Kramer2ef30312012-07-04 18:45:14 +00001487 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-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 Iskhodzhanov05e36702013-06-05 14:05:50 +00001502 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1503
1504 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1505 NewVirtualFunctionsTy NewVirtualFunctions;
1506
Peter Collingbournecfd23562011-09-26 01:57:12 +00001507 // Now go through all virtual member functions and add them.
Aaron Ballman2b124d12014-03-13 16:36:16 +00001508 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001509 if (!MD->isVirtual())
1510 continue;
1511
1512 // Get the final overrider.
1513 FinalOverriders::OverriderInfo Overrider =
1514 Overriders.getOverrider(MD, Base.getBaseOffset());
1515
1516 // Check if this virtual member function overrides a method in a primary
1517 // base. If this is the case, and the return type doesn't require adjustment
1518 // then we can just use the member function from the primary base.
1519 if (const CXXMethodDecl *OverriddenMD =
1520 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1521 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1522 OverriddenMD).isEmpty()) {
1523 // Replace the method info of the overridden method with our own
1524 // method.
1525 assert(MethodInfoMap.count(OverriddenMD) &&
1526 "Did not find the overridden method!");
1527 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1528
1529 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1530 OverriddenMethodInfo.VTableIndex);
1531
1532 assert(!MethodInfoMap.count(MD) &&
1533 "Should not have method info for this method yet!");
1534
1535 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1536 MethodInfoMap.erase(OverriddenMD);
1537
1538 // If the overridden method exists in a virtual base class or a direct
1539 // or indirect base class of a virtual base class, we need to emit a
1540 // thunk if we ever have a class hierarchy where the base class is not
1541 // a primary base in the complete object.
1542 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1543 // Compute the this adjustment.
1544 ThisAdjustment ThisAdjustment =
1545 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1546 Overrider);
1547
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001548 if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001549 Overrider.Method->getParent() == MostDerivedClass) {
1550
1551 // There's no return adjustment from OverriddenMD and MD,
1552 // but that doesn't mean there isn't one between MD and
1553 // the final overrider.
1554 BaseOffset ReturnAdjustmentOffset =
1555 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1556 ReturnAdjustment ReturnAdjustment =
1557 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1558
1559 // This is a virtual thunk for the most derived class, add it.
1560 AddThunk(Overrider.Method,
1561 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1562 }
1563 }
1564
1565 continue;
1566 }
1567 }
1568
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001569 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1570 if (MD->isImplicit()) {
1571 // Itanium C++ ABI 2.5.2:
1572 // If a class has an implicitly-defined virtual destructor,
1573 // its entries come after the declared virtual function pointers.
1574
1575 assert(!ImplicitVirtualDtor &&
1576 "Did already see an implicit virtual dtor!");
1577 ImplicitVirtualDtor = DD;
1578 continue;
1579 }
1580 }
1581
1582 NewVirtualFunctions.push_back(MD);
1583 }
1584
1585 if (ImplicitVirtualDtor)
1586 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1587
1588 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1589 E = NewVirtualFunctions.end(); I != E; ++I) {
1590 const CXXMethodDecl *MD = *I;
1591
1592 // Get the final overrider.
1593 FinalOverriders::OverriderInfo Overrider =
1594 Overriders.getOverrider(MD, Base.getBaseOffset());
1595
Peter Collingbournecfd23562011-09-26 01:57:12 +00001596 // Insert the method info for this method.
1597 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1598 Components.size());
1599
1600 assert(!MethodInfoMap.count(MD) &&
1601 "Should not have method info for this method yet!");
1602 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1603
1604 // Check if this overrider is going to be used.
1605 const CXXMethodDecl *OverriderMD = Overrider.Method;
1606 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1607 FirstBaseInPrimaryBaseChain,
1608 FirstBaseOffsetInLayoutClass)) {
1609 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1610 continue;
1611 }
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001612
Peter Collingbournecfd23562011-09-26 01:57:12 +00001613 // Check if this overrider needs a return adjustment.
1614 // We don't want to do this for pure virtual member functions.
1615 BaseOffset ReturnAdjustmentOffset;
1616 if (!OverriderMD->isPure()) {
1617 ReturnAdjustmentOffset =
1618 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1619 }
1620
1621 ReturnAdjustment ReturnAdjustment =
1622 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1623
1624 AddMethod(Overrider.Method, ReturnAdjustment);
1625 }
1626}
1627
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001628void ItaniumVTableBuilder::LayoutVTable() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001629 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1630 CharUnits::Zero()),
1631 /*BaseIsMorallyVirtual=*/false,
1632 MostDerivedClassIsVirtual,
1633 MostDerivedClassOffset);
1634
1635 VisitedVirtualBasesSetTy VBases;
1636
1637 // Determine the primary virtual bases.
1638 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1639 VBases);
1640 VBases.clear();
1641
1642 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1643
1644 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001645 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001646 if (IsAppleKext)
1647 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1648}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001649
1650void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1651 BaseSubobject Base, bool BaseIsMorallyVirtual,
1652 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001653 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1654
1655 // Add vcall and vbase offsets for this vtable.
1656 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1657 Base, BaseIsVirtualInLayoutClass,
1658 OffsetInLayoutClass);
1659 Components.append(Builder.components_begin(), Builder.components_end());
1660
1661 // Check if we need to add these vcall offsets.
1662 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1663 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1664
1665 if (VCallOffsets.empty())
1666 VCallOffsets = Builder.getVCallOffsets();
1667 }
1668
1669 // If we're laying out the most derived class we want to keep track of the
1670 // virtual base class offset offsets.
1671 if (Base.getBase() == MostDerivedClass)
1672 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1673
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001674 // Add the offset to top.
1675 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1676 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001677
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001678 // Next, add the RTTI.
1679 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001680
Peter Collingbournecfd23562011-09-26 01:57:12 +00001681 uint64_t AddressPoint = Components.size();
1682
1683 // Now go through all virtual member functions and add them.
1684 PrimaryBasesSetVectorTy PrimaryBases;
1685 AddMethods(Base, OffsetInLayoutClass,
1686 Base.getBase(), OffsetInLayoutClass,
1687 PrimaryBases);
1688
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001689 const CXXRecordDecl *RD = Base.getBase();
1690 if (RD == MostDerivedClass) {
1691 assert(MethodVTableIndices.empty());
1692 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1693 E = MethodInfoMap.end(); I != E; ++I) {
1694 const CXXMethodDecl *MD = I->first;
1695 const MethodInfo &MI = I->second;
1696 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001697 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1698 = MI.VTableIndex - AddressPoint;
1699 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1700 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001701 } else {
1702 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1703 }
1704 }
1705 }
1706
Peter Collingbournecfd23562011-09-26 01:57:12 +00001707 // Compute 'this' pointer adjustments.
1708 ComputeThisAdjustments();
1709
1710 // Add all address points.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001711 while (true) {
1712 AddressPoints.insert(std::make_pair(
1713 BaseSubobject(RD, OffsetInLayoutClass),
1714 AddressPoint));
1715
1716 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1717 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1718
1719 if (!PrimaryBase)
1720 break;
1721
1722 if (Layout.isPrimaryBaseVirtual()) {
1723 // Check if this virtual primary base is a primary base in the layout
1724 // class. If it's not, we don't want to add it.
1725 const ASTRecordLayout &LayoutClassLayout =
1726 Context.getASTRecordLayout(LayoutClass);
1727
1728 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1729 OffsetInLayoutClass) {
1730 // We don't want to add this class (or any of its primary bases).
1731 break;
1732 }
1733 }
1734
1735 RD = PrimaryBase;
1736 }
1737
1738 // Layout secondary vtables.
1739 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1740}
1741
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001742void
1743ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1744 bool BaseIsMorallyVirtual,
1745 CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001746 // Itanium C++ ABI 2.5.2:
1747 // Following the primary virtual table of a derived class are secondary
1748 // virtual tables for each of its proper base classes, except any primary
1749 // base(s) with which it shares its primary virtual table.
1750
1751 const CXXRecordDecl *RD = Base.getBase();
1752 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1753 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1754
Aaron Ballman574705e2014-03-13 15:41:46 +00001755 for (const auto &I : RD->bases()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001756 // Ignore virtual bases, we'll emit them later.
Aaron Ballman574705e2014-03-13 15:41:46 +00001757 if (I.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +00001758 continue;
1759
Aaron Ballman574705e2014-03-13 15:41:46 +00001760 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001761
1762 // Ignore bases that don't have a vtable.
1763 if (!BaseDecl->isDynamicClass())
1764 continue;
1765
1766 if (isBuildingConstructorVTable()) {
1767 // Itanium C++ ABI 2.6.4:
1768 // Some of the base class subobjects may not need construction virtual
1769 // tables, which will therefore not be present in the construction
1770 // virtual table group, even though the subobject virtual tables are
1771 // present in the main virtual table group for the complete object.
1772 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1773 continue;
1774 }
1775
1776 // Get the base offset of this base.
1777 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1778 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1779
1780 CharUnits BaseOffsetInLayoutClass =
1781 OffsetInLayoutClass + RelativeBaseOffset;
1782
1783 // Don't emit a secondary vtable for a primary base. We might however want
1784 // to emit secondary vtables for other bases of this base.
1785 if (BaseDecl == PrimaryBase) {
1786 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1787 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1788 continue;
1789 }
1790
1791 // Layout the primary vtable (and any secondary vtables) for this base.
1792 LayoutPrimaryAndSecondaryVTables(
1793 BaseSubobject(BaseDecl, BaseOffset),
1794 BaseIsMorallyVirtual,
1795 /*BaseIsVirtualInLayoutClass=*/false,
1796 BaseOffsetInLayoutClass);
1797 }
1798}
1799
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001800void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1801 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1802 VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001803 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1804
1805 // Check if this base has a primary base.
1806 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1807
1808 // Check if it's virtual.
1809 if (Layout.isPrimaryBaseVirtual()) {
1810 bool IsPrimaryVirtualBase = true;
1811
1812 if (isBuildingConstructorVTable()) {
1813 // Check if the base is actually a primary base in the class we use for
1814 // layout.
1815 const ASTRecordLayout &LayoutClassLayout =
1816 Context.getASTRecordLayout(LayoutClass);
1817
1818 CharUnits PrimaryBaseOffsetInLayoutClass =
1819 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1820
1821 // We know that the base is not a primary base in the layout class if
1822 // the base offsets are different.
1823 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1824 IsPrimaryVirtualBase = false;
1825 }
1826
1827 if (IsPrimaryVirtualBase)
1828 PrimaryVirtualBases.insert(PrimaryBase);
1829 }
1830 }
1831
1832 // Traverse bases, looking for more primary virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001833 for (const auto &I : RD->bases()) {
1834 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001835
1836 CharUnits BaseOffsetInLayoutClass;
1837
Aaron Ballman574705e2014-03-13 15:41:46 +00001838 if (I.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001839 if (!VBases.insert(BaseDecl))
1840 continue;
1841
1842 const ASTRecordLayout &LayoutClassLayout =
1843 Context.getASTRecordLayout(LayoutClass);
1844
1845 BaseOffsetInLayoutClass =
1846 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1847 } else {
1848 BaseOffsetInLayoutClass =
1849 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1850 }
1851
1852 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1853 }
1854}
1855
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001856void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1857 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001858 // Itanium C++ ABI 2.5.2:
1859 // Then come the virtual base virtual tables, also in inheritance graph
1860 // order, and again excluding primary bases (which share virtual tables with
1861 // the classes for which they are primary).
Aaron Ballman574705e2014-03-13 15:41:46 +00001862 for (const auto &I : RD->bases()) {
1863 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001864
1865 // Check if this base needs a vtable. (If it's virtual, not a primary base
1866 // of some other class, and we haven't visited it before).
Aaron Ballman574705e2014-03-13 15:41:46 +00001867 if (I.isVirtual() && BaseDecl->isDynamicClass() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001868 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1869 const ASTRecordLayout &MostDerivedClassLayout =
1870 Context.getASTRecordLayout(MostDerivedClass);
1871 CharUnits BaseOffset =
1872 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1873
1874 const ASTRecordLayout &LayoutClassLayout =
1875 Context.getASTRecordLayout(LayoutClass);
1876 CharUnits BaseOffsetInLayoutClass =
1877 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1878
1879 LayoutPrimaryAndSecondaryVTables(
1880 BaseSubobject(BaseDecl, BaseOffset),
1881 /*BaseIsMorallyVirtual=*/true,
1882 /*BaseIsVirtualInLayoutClass=*/true,
1883 BaseOffsetInLayoutClass);
1884 }
1885
1886 // We only need to check the base for virtual base vtables if it actually
1887 // has virtual bases.
1888 if (BaseDecl->getNumVBases())
1889 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1890 }
1891}
1892
1893/// dumpLayout - Dump the vtable layout.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001894void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00001895 // FIXME: write more tests that actually use the dumpLayout output to prevent
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001896 // ItaniumVTableBuilder regressions.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001897
1898 if (isBuildingConstructorVTable()) {
1899 Out << "Construction vtable for ('";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001900 MostDerivedClass->printQualifiedName(Out);
1901 Out << "', ";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001902 Out << MostDerivedClassOffset.getQuantity() << ") in '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001903 LayoutClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001904 } else {
1905 Out << "Vtable for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001906 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001907 }
1908 Out << "' (" << Components.size() << " entries).\n";
1909
1910 // Iterate through the address points and insert them into a new map where
1911 // they are keyed by the index and not the base object.
1912 // Since an address point can be shared by multiple subobjects, we use an
1913 // STL multimap.
1914 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1915 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1916 E = AddressPoints.end(); I != E; ++I) {
1917 const BaseSubobject& Base = I->first;
1918 uint64_t Index = I->second;
1919
1920 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1921 }
1922
1923 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1924 uint64_t Index = I;
1925
1926 Out << llvm::format("%4d | ", I);
1927
1928 const VTableComponent &Component = Components[I];
1929
1930 // Dump the component.
1931 switch (Component.getKind()) {
1932
1933 case VTableComponent::CK_VCallOffset:
1934 Out << "vcall_offset ("
1935 << Component.getVCallOffset().getQuantity()
1936 << ")";
1937 break;
1938
1939 case VTableComponent::CK_VBaseOffset:
1940 Out << "vbase_offset ("
1941 << Component.getVBaseOffset().getQuantity()
1942 << ")";
1943 break;
1944
1945 case VTableComponent::CK_OffsetToTop:
1946 Out << "offset_to_top ("
1947 << Component.getOffsetToTop().getQuantity()
1948 << ")";
1949 break;
1950
1951 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001952 Component.getRTTIDecl()->printQualifiedName(Out);
1953 Out << " RTTI";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001954 break;
1955
1956 case VTableComponent::CK_FunctionPointer: {
1957 const CXXMethodDecl *MD = Component.getFunctionDecl();
1958
1959 std::string Str =
1960 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1961 MD);
1962 Out << Str;
1963 if (MD->isPure())
1964 Out << " [pure]";
1965
David Blaikie596d2ca2012-10-16 20:25:33 +00001966 if (MD->isDeleted())
1967 Out << " [deleted]";
1968
Peter Collingbournecfd23562011-09-26 01:57:12 +00001969 ThunkInfo Thunk = VTableThunks.lookup(I);
1970 if (!Thunk.isEmpty()) {
1971 // If this function pointer has a return adjustment, dump it.
1972 if (!Thunk.Return.isEmpty()) {
1973 Out << "\n [return adjustment: ";
1974 Out << Thunk.Return.NonVirtual << " non-virtual";
1975
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001976 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1977 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001978 Out << " vbase offset offset";
1979 }
1980
1981 Out << ']';
1982 }
1983
1984 // If this function pointer has a 'this' pointer adjustment, dump it.
1985 if (!Thunk.This.isEmpty()) {
1986 Out << "\n [this adjustment: ";
1987 Out << Thunk.This.NonVirtual << " non-virtual";
1988
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001989 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
1990 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001991 Out << " vcall offset offset";
1992 }
1993
1994 Out << ']';
1995 }
1996 }
1997
1998 break;
1999 }
2000
2001 case VTableComponent::CK_CompleteDtorPointer:
2002 case VTableComponent::CK_DeletingDtorPointer: {
2003 bool IsComplete =
2004 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2005
2006 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2007
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002008 DD->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002009 if (IsComplete)
2010 Out << "() [complete]";
2011 else
2012 Out << "() [deleting]";
2013
2014 if (DD->isPure())
2015 Out << " [pure]";
2016
2017 ThunkInfo Thunk = VTableThunks.lookup(I);
2018 if (!Thunk.isEmpty()) {
2019 // If this destructor has a 'this' pointer adjustment, dump it.
2020 if (!Thunk.This.isEmpty()) {
2021 Out << "\n [this adjustment: ";
2022 Out << Thunk.This.NonVirtual << " non-virtual";
2023
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002024 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2025 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002026 Out << " vcall offset offset";
2027 }
2028
2029 Out << ']';
2030 }
2031 }
2032
2033 break;
2034 }
2035
2036 case VTableComponent::CK_UnusedFunctionPointer: {
2037 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2038
2039 std::string Str =
2040 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2041 MD);
2042 Out << "[unused] " << Str;
2043 if (MD->isPure())
2044 Out << " [pure]";
2045 }
2046
2047 }
2048
2049 Out << '\n';
2050
2051 // Dump the next address point.
2052 uint64_t NextIndex = Index + 1;
2053 if (AddressPointsByIndex.count(NextIndex)) {
2054 if (AddressPointsByIndex.count(NextIndex) == 1) {
2055 const BaseSubobject &Base =
2056 AddressPointsByIndex.find(NextIndex)->second;
2057
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002058 Out << " -- (";
2059 Base.getBase()->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002060 Out << ", " << Base.getBaseOffset().getQuantity();
2061 Out << ") vtable address --\n";
2062 } else {
2063 CharUnits BaseOffset =
2064 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2065
2066 // We store the class names in a set to get a stable order.
2067 std::set<std::string> ClassNames;
2068 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2069 AddressPointsByIndex.lower_bound(NextIndex), E =
2070 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2071 assert(I->second.getBaseOffset() == BaseOffset &&
2072 "Invalid base offset!");
2073 const CXXRecordDecl *RD = I->second.getBase();
2074 ClassNames.insert(RD->getQualifiedNameAsString());
2075 }
2076
2077 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2078 E = ClassNames.end(); I != E; ++I) {
2079 Out << " -- (" << *I;
2080 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2081 }
2082 }
2083 }
2084 }
2085
2086 Out << '\n';
2087
2088 if (isBuildingConstructorVTable())
2089 return;
2090
2091 if (MostDerivedClass->getNumVBases()) {
2092 // We store the virtual base class names and their offsets in a map to get
2093 // a stable order.
2094
2095 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2096 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2097 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2098 std::string ClassName = I->first->getQualifiedNameAsString();
2099 CharUnits OffsetOffset = I->second;
2100 ClassNamesAndOffsets.insert(
2101 std::make_pair(ClassName, OffsetOffset));
2102 }
2103
2104 Out << "Virtual base offset offsets for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002105 MostDerivedClass->printQualifiedName(Out);
2106 Out << "' (";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002107 Out << ClassNamesAndOffsets.size();
2108 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2109
2110 for (std::map<std::string, CharUnits>::const_iterator I =
2111 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2112 I != E; ++I)
2113 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2114
2115 Out << "\n";
2116 }
2117
2118 if (!Thunks.empty()) {
2119 // We store the method names in a map to get a stable order.
2120 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2121
2122 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2123 I != E; ++I) {
2124 const CXXMethodDecl *MD = I->first;
2125 std::string MethodName =
2126 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2127 MD);
2128
2129 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2130 }
2131
2132 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2133 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2134 I != E; ++I) {
2135 const std::string &MethodName = I->first;
2136 const CXXMethodDecl *MD = I->second;
2137
2138 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002139 std::sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002140 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
2141 assert(LHS.Method == 0 && RHS.Method == 0);
Benjamin Kramera741b8c2014-03-03 20:26:46 +00002142 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002143 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002144
2145 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2146 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2147
2148 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2149 const ThunkInfo &Thunk = ThunksVector[I];
2150
2151 Out << llvm::format("%4d | ", I);
2152
2153 // If this function pointer has a return pointer adjustment, dump it.
2154 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00002155 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002156 Out << " non-virtual";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002157 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2158 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002159 Out << " vbase offset offset";
2160 }
2161
2162 if (!Thunk.This.isEmpty())
2163 Out << "\n ";
2164 }
2165
2166 // If this function pointer has a 'this' pointer adjustment, dump it.
2167 if (!Thunk.This.isEmpty()) {
2168 Out << "this adjustment: ";
2169 Out << Thunk.This.NonVirtual << " non-virtual";
2170
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002171 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2172 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002173 Out << " vcall offset offset";
2174 }
2175 }
2176
2177 Out << '\n';
2178 }
2179
2180 Out << '\n';
2181 }
2182 }
2183
2184 // Compute the vtable indices for all the member functions.
2185 // Store them in a map keyed by the index so we'll get a sorted table.
2186 std::map<uint64_t, std::string> IndicesMap;
2187
Aaron Ballman2b124d12014-03-13 16:36:16 +00002188 for (const auto *MD : MostDerivedClass->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002189 // We only want virtual member functions.
2190 if (!MD->isVirtual())
2191 continue;
2192
2193 std::string MethodName =
2194 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2195 MD);
2196
2197 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002198 GlobalDecl GD(DD, Dtor_Complete);
2199 assert(MethodVTableIndices.count(GD));
2200 uint64_t VTableIndex = MethodVTableIndices[GD];
2201 IndicesMap[VTableIndex] = MethodName + " [complete]";
2202 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002203 } else {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002204 assert(MethodVTableIndices.count(MD));
2205 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002206 }
2207 }
2208
2209 // Print the vtable indices for all the member functions.
2210 if (!IndicesMap.empty()) {
2211 Out << "VTable indices for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002212 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002213 Out << "' (" << IndicesMap.size() << " entries).\n";
2214
2215 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2216 E = IndicesMap.end(); I != E; ++I) {
2217 uint64_t VTableIndex = I->first;
2218 const std::string &MethodName = I->second;
2219
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002220 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer5291e682012-03-10 02:06:27 +00002221 << '\n';
Peter Collingbournecfd23562011-09-26 01:57:12 +00002222 }
2223 }
2224
2225 Out << '\n';
2226}
Peter Collingbournecfd23562011-09-26 01:57:12 +00002227}
2228
2229VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2230 const VTableComponent *VTableComponents,
2231 uint64_t NumVTableThunks,
2232 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002233 const AddressPointsMapTy &AddressPoints,
2234 bool IsMicrosoftABI)
Peter Collingbournecfd23562011-09-26 01:57:12 +00002235 : NumVTableComponents(NumVTableComponents),
2236 VTableComponents(new VTableComponent[NumVTableComponents]),
2237 NumVTableThunks(NumVTableThunks),
2238 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002239 AddressPoints(AddressPoints),
2240 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002241 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramere2980632012-04-14 14:13:43 +00002242 this->VTableComponents.get());
2243 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2244 this->VTableThunks.get());
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002245 std::sort(this->VTableThunks.get(),
2246 this->VTableThunks.get() + NumVTableThunks,
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002247 [](const VTableLayout::VTableThunkTy &LHS,
2248 const VTableLayout::VTableThunkTy &RHS) {
2249 assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2250 "Different thunks should have unique indices!");
2251 return LHS.first < RHS.first;
2252 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002253}
2254
Benjamin Kramere2980632012-04-14 14:13:43 +00002255VTableLayout::~VTableLayout() { }
Peter Collingbournecfd23562011-09-26 01:57:12 +00002256
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002257ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
Reid Klecknerb60a3d52013-12-20 23:58:52 +00002258 : VTableContextBase(/*MS=*/false) {}
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002259
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002260ItaniumVTableContext::~ItaniumVTableContext() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002261 llvm::DeleteContainerSeconds(VTableLayouts);
2262}
2263
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002264uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002265 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2266 if (I != MethodVTableIndices.end())
2267 return I->second;
2268
2269 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2270
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002271 computeVTableRelatedInformation(RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002272
2273 I = MethodVTableIndices.find(GD);
2274 assert(I != MethodVTableIndices.end() && "Did not find index!");
2275 return I->second;
2276}
2277
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002278CharUnits
2279ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2280 const CXXRecordDecl *VBase) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002281 ClassPairTy ClassPair(RD, VBase);
2282
2283 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2284 VirtualBaseClassOffsetOffsets.find(ClassPair);
2285 if (I != VirtualBaseClassOffsetOffsets.end())
2286 return I->second;
2287
2288 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2289 BaseSubobject(RD, CharUnits::Zero()),
2290 /*BaseIsVirtual=*/false,
2291 /*OffsetInLayoutClass=*/CharUnits::Zero());
2292
2293 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2294 Builder.getVBaseOffsetOffsets().begin(),
2295 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2296 // Insert all types.
2297 ClassPairTy ClassPair(RD, I->first);
2298
2299 VirtualBaseClassOffsetOffsets.insert(
2300 std::make_pair(ClassPair, I->second));
2301 }
2302
2303 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2304 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2305
2306 return I->second;
2307}
2308
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002309static VTableLayout *CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002310 SmallVector<VTableLayout::VTableThunkTy, 1>
2311 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002312
2313 return new VTableLayout(Builder.getNumVTableComponents(),
2314 Builder.vtable_component_begin(),
2315 VTableThunks.size(),
2316 VTableThunks.data(),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002317 Builder.getAddressPoints(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002318 /*IsMicrosoftABI=*/false);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002319}
2320
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002321void
2322ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002323 const VTableLayout *&Entry = VTableLayouts[RD];
2324
2325 // Check if we've computed this information before.
2326 if (Entry)
2327 return;
2328
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002329 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2330 /*MostDerivedClassIsVirtual=*/0, RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002331 Entry = CreateVTableLayout(Builder);
2332
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002333 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2334 Builder.vtable_indices_end());
2335
Peter Collingbournecfd23562011-09-26 01:57:12 +00002336 // Add the known thunks.
2337 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2338
2339 // If we don't have the vbase information for this class, insert it.
2340 // getVirtualBaseOffsetOffset will compute it separately without computing
2341 // the rest of the vtable related information.
2342 if (!RD->getNumVBases())
2343 return;
2344
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00002345 const CXXRecordDecl *VBase =
2346 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002347
2348 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2349 return;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002350
2351 for (ItaniumVTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator
2352 I = Builder.getVBaseOffsetOffsets().begin(),
2353 E = Builder.getVBaseOffsetOffsets().end();
2354 I != E; ++I) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002355 // Insert all types.
2356 ClassPairTy ClassPair(RD, I->first);
2357
2358 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2359 }
2360}
2361
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002362VTableLayout *ItaniumVTableContext::createConstructionVTableLayout(
2363 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2364 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2365 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2366 MostDerivedClassIsVirtual, LayoutClass);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002367 return CreateVTableLayout(Builder);
2368}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002369
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002370namespace {
2371
2372// Vtables in the Microsoft ABI are different from the Itanium ABI.
2373//
2374// The main differences are:
2375// 1. Separate vftable and vbtable.
2376//
2377// 2. Each subobject with a vfptr gets its own vftable rather than an address
2378// point in a single vtable shared between all the subobjects.
2379// Each vftable is represented by a separate section and virtual calls
2380// must be done using the vftable which has a slot for the function to be
2381// called.
2382//
2383// 3. Virtual method definitions expect their 'this' parameter to point to the
2384// first vfptr whose table provides a compatible overridden method. In many
2385// cases, this permits the original vf-table entry to directly call
2386// the method instead of passing through a thunk.
2387//
2388// A compatible overridden method is one which does not have a non-trivial
2389// covariant-return adjustment.
2390//
2391// The first vfptr is the one with the lowest offset in the complete-object
2392// layout of the defining class, and the method definition will subtract
2393// that constant offset from the parameter value to get the real 'this'
2394// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2395// function defined in a virtual base is overridden in a more derived
2396// virtual base and these bases have a reverse order in the complete
2397// object), the vf-table may require a this-adjustment thunk.
2398//
2399// 4. vftables do not contain new entries for overrides that merely require
2400// this-adjustment. Together with #3, this keeps vf-tables smaller and
2401// eliminates the need for this-adjustment thunks in many cases, at the cost
2402// of often requiring redundant work to adjust the "this" pointer.
2403//
2404// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2405// Vtordisps are emitted into the class layout if a class has
2406// a) a user-defined ctor/dtor
2407// and
2408// b) a method overriding a method in a virtual base.
2409
2410class VFTableBuilder {
2411public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002412 typedef MicrosoftVTableContext::MethodVFTableLocation MethodVFTableLocation;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002413
2414 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2415 MethodVFTableLocationsTy;
2416
2417private:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002418 /// VTables - Global vtable information.
2419 MicrosoftVTableContext &VTables;
2420
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002421 /// Context - The ASTContext which we will use for layout information.
2422 ASTContext &Context;
2423
2424 /// MostDerivedClass - The most derived class for which we're building this
2425 /// vtable.
2426 const CXXRecordDecl *MostDerivedClass;
2427
2428 const ASTRecordLayout &MostDerivedClassLayout;
2429
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002430 const VPtrInfo &WhichVFPtr;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002431
2432 /// FinalOverriders - The final overriders of the most derived class.
2433 const FinalOverriders Overriders;
2434
2435 /// Components - The components of the vftable being built.
2436 SmallVector<VTableComponent, 64> Components;
2437
2438 MethodVFTableLocationsTy MethodVFTableLocations;
2439
2440 /// MethodInfo - Contains information about a method in a vtable.
2441 /// (Used for computing 'this' pointer adjustment thunks.
2442 struct MethodInfo {
2443 /// VBTableIndex - The nonzero index in the vbtable that
2444 /// this method's base has, or zero.
2445 const uint64_t VBTableIndex;
2446
2447 /// VFTableIndex - The index in the vftable that this method has.
2448 const uint64_t VFTableIndex;
2449
2450 /// Shadowed - Indicates if this vftable slot is shadowed by
2451 /// a slot for a covariant-return override. If so, it shouldn't be printed
2452 /// or used for vcalls in the most derived class.
2453 bool Shadowed;
2454
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002455 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex)
2456 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002457 Shadowed(false) {}
2458
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002459 MethodInfo() : VBTableIndex(0), VFTableIndex(0), Shadowed(false) {}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002460 };
2461
2462 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2463
2464 /// MethodInfoMap - The information for all methods in the vftable we're
2465 /// currently building.
2466 MethodInfoMapTy MethodInfoMap;
2467
2468 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2469
2470 /// VTableThunks - The thunks by vftable index in the vftable currently being
2471 /// built.
2472 VTableThunksMapTy VTableThunks;
2473
2474 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2475 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2476
2477 /// Thunks - A map that contains all the thunks needed for all methods in the
2478 /// most derived class for which the vftable is currently being built.
2479 ThunksMapTy Thunks;
2480
2481 /// AddThunk - Add a thunk for the given method.
2482 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2483 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2484
2485 // Check if we have this thunk already.
2486 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2487 ThunksVector.end())
2488 return;
2489
2490 ThunksVector.push_back(Thunk);
2491 }
2492
2493 /// ComputeThisOffset - Returns the 'this' argument offset for the given
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002494 /// method, relative to the beginning of the MostDerivedClass.
2495 CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002496
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002497 void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2498 CharUnits ThisOffset, ThisAdjustment &TA);
2499
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002500 /// AddMethod - Add a single virtual member function to the vftable
2501 /// components vector.
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002502 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002503 if (!TI.isEmpty()) {
2504 VTableThunks[Components.size()] = TI;
2505 AddThunk(MD, TI);
2506 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002507 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002508 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002509 "Destructor can't have return adjustment!");
2510 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2511 } else {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002512 Components.push_back(VTableComponent::MakeFunction(MD));
2513 }
2514 }
2515
Reid Kleckner558cab22013-12-27 19:45:53 +00002516 bool NeedsReturnAdjustingThunk(const CXXMethodDecl *MD);
Reid Kleckner604c8b42013-12-27 19:43:59 +00002517
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002518 /// AddMethods - Add the methods of this base subobject and the relevant
2519 /// subbases to the vftable we're currently laying out.
2520 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2521 const CXXRecordDecl *LastVBase,
2522 BasesSetVectorTy &VisitedBases);
2523
2524 void LayoutVFTable() {
2525 // FIXME: add support for RTTI when we have proper LLVM support for symbols
2526 // pointing to the middle of a section.
2527
2528 BasesSetVectorTy VisitedBases;
2529 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, 0,
2530 VisitedBases);
2531
2532 assert(MethodVFTableLocations.empty());
2533 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2534 E = MethodInfoMap.end(); I != E; ++I) {
2535 const CXXMethodDecl *MD = I->first;
2536 const MethodInfo &MI = I->second;
2537 // Skip the methods that the MostDerivedClass didn't override
2538 // and the entries shadowed by return adjusting thunks.
2539 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2540 continue;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002541 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2542 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002543 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2544 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2545 } else {
2546 MethodVFTableLocations[MD] = Loc;
2547 }
2548 }
2549 }
2550
2551 void ErrorUnsupported(StringRef Feature, SourceLocation Location) {
2552 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2553 unsigned DiagID = Diags.getCustomDiagID(
2554 DiagnosticsEngine::Error, "v-table layout for %0 is not supported yet");
2555 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2556 }
2557
2558public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002559 VFTableBuilder(MicrosoftVTableContext &VTables,
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002560 const CXXRecordDecl *MostDerivedClass, const VPtrInfo *Which)
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002561 : VTables(VTables),
2562 Context(MostDerivedClass->getASTContext()),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002563 MostDerivedClass(MostDerivedClass),
2564 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002565 WhichVFPtr(*Which),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002566 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2567 LayoutVFTable();
2568
2569 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00002570 dumpLayout(llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002571 }
2572
2573 uint64_t getNumThunks() const { return Thunks.size(); }
2574
2575 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2576
2577 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2578
2579 MethodVFTableLocationsTy::const_iterator vtable_indices_begin() const {
2580 return MethodVFTableLocations.begin();
2581 }
2582
2583 MethodVFTableLocationsTy::const_iterator vtable_indices_end() const {
2584 return MethodVFTableLocations.end();
2585 }
2586
2587 uint64_t getNumVTableComponents() const { return Components.size(); }
2588
2589 const VTableComponent *vtable_component_begin() const {
2590 return Components.begin();
2591 }
2592
2593 const VTableComponent *vtable_component_end() const {
2594 return Components.end();
2595 }
2596
2597 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2598 return VTableThunks.begin();
2599 }
2600
2601 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2602 return VTableThunks.end();
2603 }
2604
2605 void dumpLayout(raw_ostream &);
2606};
2607
Reid Klecknerb40a27d2014-01-03 00:14:35 +00002608} // end namespace
2609
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002610/// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2611/// that define the given method.
2612struct InitialOverriddenDefinitionCollector {
2613 BasesSetVectorTy Bases;
2614 OverriddenMethodsSetTy VisitedOverriddenMethods;
2615
2616 bool visit(const CXXMethodDecl *OverriddenMD) {
2617 if (OverriddenMD->size_overridden_methods() == 0)
2618 Bases.insert(OverriddenMD->getParent());
2619 // Don't recurse on this method if we've already collected it.
2620 return VisitedOverriddenMethods.insert(OverriddenMD);
2621 }
2622};
2623
2624static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2625 CXXBasePath &Path, void *BasesSet) {
2626 BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2627 return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2628}
2629
2630CharUnits
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002631VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002632 InitialOverriddenDefinitionCollector Collector;
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002633 visitAllOverriddenMethods(Overrider.Method, Collector);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002634
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002635 // If there are no overrides then 'this' is located
2636 // in the base that defines the method.
2637 if (Collector.Bases.size() == 0)
2638 return Overrider.Offset;
2639
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002640 CXXBasePaths Paths;
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002641 Overrider.Method->getParent()->lookupInBases(BaseInSet, &Collector.Bases,
2642 Paths);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002643
2644 // This will hold the smallest this offset among overridees of MD.
2645 // This implies that an offset of a non-virtual base will dominate an offset
2646 // of a virtual base to potentially reduce the number of thunks required
2647 // in the derived classes that inherit this method.
2648 CharUnits Ret;
2649 bool First = true;
2650
2651 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2652 I != E; ++I) {
2653 const CXXBasePath &Path = (*I);
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002654 CharUnits ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002655 CharUnits LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002656
2657 // For each path from the overrider to the parents of the overridden methods,
2658 // traverse the path, calculating the this offset in the most derived class.
2659 for (int J = 0, F = Path.size(); J != F; ++J) {
2660 const CXXBasePathElement &Element = Path[J];
2661 QualType CurTy = Element.Base->getType();
2662 const CXXRecordDecl *PrevRD = Element.Class,
2663 *CurRD = CurTy->getAsCXXRecordDecl();
2664 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2665
2666 if (Element.Base->isVirtual()) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002667 LastVBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(CurRD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002668 if (Overrider.Method->getParent() == PrevRD) {
2669 // This one's interesting. If the final overrider is in a vbase B of the
2670 // most derived class and it overrides a method of the B's own vbase A,
2671 // it uses A* as "this". In its prologue, it can cast A* to B* with
2672 // a static offset. This offset is used regardless of the actual
2673 // offset of A from B in the most derived class, requiring an
2674 // this-adjusting thunk in the vftable if A and B are laid out
2675 // differently in the most derived class.
2676 ThisOffset += Layout.getVBaseClassOffset(CurRD);
2677 } else {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002678 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002679 }
2680 } else {
2681 ThisOffset += Layout.getBaseClassOffset(CurRD);
2682 }
2683 }
2684
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002685 if (isa<CXXDestructorDecl>(Overrider.Method)) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002686 if (LastVBaseOffset.isZero()) {
2687 // If a "Base" class has at least one non-virtual base with a virtual
2688 // destructor, the "Base" virtual destructor will take the address
2689 // of the "Base" subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002690 ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002691 } else {
2692 // A virtual destructor of a virtual base takes the address of the
2693 // virtual base subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002694 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002695 }
2696 }
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +00002697
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002698 if (Ret > ThisOffset || First) {
2699 First = false;
2700 Ret = ThisOffset;
2701 }
2702 }
2703
2704 assert(!First && "Method not found in the given subobject?");
2705 return Ret;
2706}
2707
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002708void VFTableBuilder::CalculateVtordispAdjustment(
2709 FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2710 ThisAdjustment &TA) {
2711 const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2712 MostDerivedClassLayout.getVBaseOffsetsMap();
2713 const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002714 VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002715 assert(VBaseMapEntry != VBaseMap.end());
2716
2717 // Check if we need a vtordisp adjustment at all.
2718 if (!VBaseMapEntry->second.hasVtorDisp())
2719 return;
2720
2721 CharUnits VFPtrVBaseOffset = VBaseMapEntry->second.VBaseOffset;
2722 // The implicit vtordisp field is located right before the vbase.
2723 TA.Virtual.Microsoft.VtordispOffset =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002724 (VFPtrVBaseOffset - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002725
2726 // If the final overrider is defined in either:
2727 // - the most derived class or its non-virtual base or
2728 // - the same vbase as the initial declaration,
2729 // a simple vtordisp thunk will suffice.
2730 const CXXRecordDecl *OverriderRD = Overrider.Method->getParent();
2731 if (OverriderRD == MostDerivedClass)
2732 return;
2733
2734 const CXXRecordDecl *OverriderVBase =
2735 ComputeBaseOffset(Context, OverriderRD, MostDerivedClass).VirtualBase;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002736 if (!OverriderVBase || OverriderVBase == WhichVFPtr.getVBaseWithVPtr())
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002737 return;
2738
2739 // Otherwise, we need to do use the dynamic offset of the final overrider
2740 // in order to get "this" adjustment right.
2741 TA.Virtual.Microsoft.VBPtrOffset =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002742 (VFPtrVBaseOffset + WhichVFPtr.NonVirtualOffset -
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002743 MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2744 TA.Virtual.Microsoft.VBOffsetOffset =
2745 Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
2746 VTables.getVBTableIndex(MostDerivedClass, OverriderVBase);
2747
2748 TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2749}
2750
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002751static void GroupNewVirtualOverloads(
2752 const CXXRecordDecl *RD,
2753 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2754 // Put the virtual methods into VirtualMethods in the proper order:
2755 // 1) Group overloads by declaration name. New groups are added to the
2756 // vftable in the order of their first declarations in this class
Reid Kleckner6701de22014-02-19 22:06:10 +00002757 // (including overrides and non-virtual methods).
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002758 // 2) In each group, new overloads appear in the reverse order of declaration.
2759 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2760 SmallVector<MethodGroup, 10> Groups;
2761 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2762 VisitedGroupIndicesTy VisitedGroupIndices;
Aaron Ballman2b124d12014-03-13 16:36:16 +00002763 for (const auto *MD : RD->methods()) {
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002764 VisitedGroupIndicesTy::iterator J;
2765 bool Inserted;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002766 std::tie(J, Inserted) = VisitedGroupIndices.insert(
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002767 std::make_pair(MD->getDeclName(), Groups.size()));
2768 if (Inserted)
Reid Kleckner6701de22014-02-19 22:06:10 +00002769 Groups.push_back(MethodGroup());
Aaron Ballman2b124d12014-03-13 16:36:16 +00002770 if (MD->isVirtual())
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002771 Groups[J->second].push_back(MD);
2772 }
2773
2774 for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2775 VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2776}
2777
Reid Kleckner604c8b42013-12-27 19:43:59 +00002778/// We need a return adjusting thunk for this method if its return type is
2779/// not trivially convertible to the return type of any of its overridden
2780/// methods.
2781bool VFTableBuilder::NeedsReturnAdjustingThunk(const CXXMethodDecl *MD) {
2782 OverriddenMethodsSetTy OverriddenMethods;
2783 ComputeAllOverriddenMethods(MD, OverriddenMethods);
2784 for (OverriddenMethodsSetTy::iterator I = OverriddenMethods.begin(),
2785 E = OverriddenMethods.end();
2786 I != E; ++I) {
2787 const CXXMethodDecl *OverriddenMD = *I;
2788 BaseOffset Adjustment =
2789 ComputeReturnAdjustmentBaseOffset(Context, MD, OverriddenMD);
2790 if (!Adjustment.isEmpty())
2791 return true;
2792 }
2793 return false;
2794}
2795
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002796void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2797 const CXXRecordDecl *LastVBase,
2798 BasesSetVectorTy &VisitedBases) {
2799 const CXXRecordDecl *RD = Base.getBase();
2800 if (!RD->isPolymorphic())
2801 return;
2802
2803 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2804
2805 // See if this class expands a vftable of the base we look at, which is either
2806 // the one defined by the vfptr base path or the primary base of the current class.
2807 const CXXRecordDecl *NextBase = 0, *NextLastVBase = LastVBase;
2808 CharUnits NextBaseOffset;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002809 if (BaseDepth < WhichVFPtr.PathToBaseWithVPtr.size()) {
2810 NextBase = WhichVFPtr.PathToBaseWithVPtr[BaseDepth];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002811 if (Layout.getVBaseOffsetsMap().count(NextBase)) {
2812 NextLastVBase = NextBase;
2813 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2814 } else {
2815 NextBaseOffset =
2816 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2817 }
2818 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2819 assert(!Layout.isPrimaryBaseVirtual() &&
2820 "No primary virtual bases in this ABI");
2821 NextBase = PrimaryBase;
2822 NextBaseOffset = Base.getBaseOffset();
2823 }
2824
2825 if (NextBase) {
2826 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2827 NextLastVBase, VisitedBases);
2828 if (!VisitedBases.insert(NextBase))
2829 llvm_unreachable("Found a duplicate primary base!");
2830 }
2831
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002832 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2833 // Put virtual methods in the proper order.
2834 GroupNewVirtualOverloads(RD, VirtualMethods);
2835
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002836 // Now go through all virtual member functions and add them to the current
2837 // vftable. This is done by
2838 // - replacing overridden methods in their existing slots, as long as they
2839 // don't require return adjustment; calculating This adjustment if needed.
2840 // - adding new slots for methods of the current base not present in any
2841 // sub-bases;
2842 // - adding new slots for methods that require Return adjustment.
2843 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002844 for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
2845 const CXXMethodDecl *MD = VirtualMethods[I];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002846
2847 FinalOverriders::OverriderInfo Overrider =
2848 Overriders.getOverrider(MD, Base.getBaseOffset());
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002849 const CXXMethodDecl *OverriderMD = Overrider.Method;
2850 const CXXMethodDecl *OverriddenMD =
2851 FindNearestOverriddenMethod(MD, VisitedBases);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002852
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002853 ThisAdjustment ThisAdjustmentOffset;
2854 bool ReturnAdjustingThunk = false;
2855 CharUnits ThisOffset = ComputeThisOffset(Overrider);
2856 ThisAdjustmentOffset.NonVirtual =
2857 (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
2858 if ((OverriddenMD || OverriderMD != MD) &&
2859 WhichVFPtr.getVBaseWithVPtr())
2860 CalculateVtordispAdjustment(Overrider, ThisOffset, ThisAdjustmentOffset);
2861
2862 if (OverriddenMD) {
2863 // If MD overrides anything in this vftable, we need to update the entries.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002864 MethodInfoMapTy::iterator OverriddenMDIterator =
2865 MethodInfoMap.find(OverriddenMD);
2866
2867 // If the overridden method went to a different vftable, skip it.
2868 if (OverriddenMDIterator == MethodInfoMap.end())
2869 continue;
2870
2871 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2872
Reid Kleckner604c8b42013-12-27 19:43:59 +00002873 if (!NeedsReturnAdjustingThunk(MD)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002874 // No return adjustment needed - just replace the overridden method info
2875 // with the current info.
2876 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
2877 OverriddenMethodInfo.VFTableIndex);
2878 MethodInfoMap.erase(OverriddenMDIterator);
2879
2880 assert(!MethodInfoMap.count(MD) &&
2881 "Should not have method info for this method yet!");
2882 MethodInfoMap.insert(std::make_pair(MD, MI));
2883 continue;
Reid Kleckner31a9f742013-12-27 20:29:16 +00002884 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002885
Reid Kleckner31a9f742013-12-27 20:29:16 +00002886 // In case we need a return adjustment, we'll add a new slot for
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002887 // the overrider. Mark the overriden method as shadowed by the new slot.
Reid Kleckner31a9f742013-12-27 20:29:16 +00002888 OverriddenMethodInfo.Shadowed = true;
Reid Kleckner31a9f742013-12-27 20:29:16 +00002889
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002890 // Force a special name mangling for a return-adjusting thunk
2891 // unless the method is the final overrider without this adjustment.
2892 ReturnAdjustingThunk =
2893 !(MD == OverriderMD && ThisAdjustmentOffset.isEmpty());
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002894 } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002895 MD->size_overridden_methods()) {
2896 // Skip methods that don't belong to the vftable of the current class,
2897 // e.g. each method that wasn't seen in any of the visited sub-bases
2898 // but overrides multiple methods of other sub-bases.
2899 continue;
2900 }
2901
2902 // If we got here, MD is a method not seen in any of the sub-bases or
2903 // it requires return adjustment. Insert the method info for this method.
2904 unsigned VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002905 LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002906 MethodInfo MI(VBIndex, Components.size());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002907
2908 assert(!MethodInfoMap.count(MD) &&
2909 "Should not have method info for this method yet!");
2910 MethodInfoMap.insert(std::make_pair(MD, MI));
2911
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002912 // Check if this overrider needs a return adjustment.
2913 // We don't want to do this for pure virtual member functions.
2914 BaseOffset ReturnAdjustmentOffset;
2915 ReturnAdjustment ReturnAdjustment;
2916 if (!OverriderMD->isPure()) {
2917 ReturnAdjustmentOffset =
2918 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
2919 }
2920 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002921 ReturnAdjustingThunk = true;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002922 ReturnAdjustment.NonVirtual =
2923 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
2924 if (ReturnAdjustmentOffset.VirtualBase) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002925 const ASTRecordLayout &DerivedLayout =
2926 Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
2927 ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
2928 DerivedLayout.getVBPtrOffset().getQuantity();
2929 ReturnAdjustment.Virtual.Microsoft.VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002930 VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
2931 ReturnAdjustmentOffset.VirtualBase);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002932 }
2933 }
2934
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002935 AddMethod(OverriderMD, ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002936 ReturnAdjustingThunk ? MD : 0));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002937 }
2938}
2939
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002940static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
2941 for (VPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002942 E = Path.rend(); I != E; ++I) {
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002943 Out << "'";
2944 (*I)->printQualifiedName(Out);
2945 Out << "' in ";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002946 }
2947}
2948
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002949static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
2950 bool ContinueFirstLine) {
2951 const ReturnAdjustment &R = TI.Return;
2952 bool Multiline = false;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002953 const char *LinePrefix = "\n ";
2954 if (!R.isEmpty() || TI.Method) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002955 if (!ContinueFirstLine)
2956 Out << LinePrefix;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002957 Out << "[return adjustment (to type '"
2958 << TI.Method->getReturnType().getCanonicalType().getAsString()
2959 << "'): ";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002960 if (R.Virtual.Microsoft.VBPtrOffset)
2961 Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
2962 if (R.Virtual.Microsoft.VBIndex)
2963 Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
2964 Out << R.NonVirtual << " non-virtual]";
2965 Multiline = true;
2966 }
2967
2968 const ThisAdjustment &T = TI.This;
2969 if (!T.isEmpty()) {
2970 if (Multiline || !ContinueFirstLine)
2971 Out << LinePrefix;
2972 Out << "[this adjustment: ";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002973 if (!TI.This.Virtual.isEmpty()) {
2974 assert(T.Virtual.Microsoft.VtordispOffset < 0);
2975 Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
2976 if (T.Virtual.Microsoft.VBPtrOffset) {
2977 Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002978 << " to the left,";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002979 assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
2980 Out << LinePrefix << " vboffset at "
2981 << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
2982 }
2983 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002984 Out << T.NonVirtual << " non-virtual]";
2985 }
2986}
2987
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002988void VFTableBuilder::dumpLayout(raw_ostream &Out) {
2989 Out << "VFTable for ";
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002990 PrintBasePath(WhichVFPtr.PathToBaseWithVPtr, Out);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002991 Out << "'";
2992 MostDerivedClass->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00002993 Out << "' (" << Components.size()
2994 << (Components.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002995
2996 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
2997 Out << llvm::format("%4d | ", I);
2998
2999 const VTableComponent &Component = Components[I];
3000
3001 // Dump the component.
3002 switch (Component.getKind()) {
3003 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003004 Component.getRTTIDecl()->printQualifiedName(Out);
3005 Out << " RTTI";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003006 break;
3007
3008 case VTableComponent::CK_FunctionPointer: {
3009 const CXXMethodDecl *MD = Component.getFunctionDecl();
3010
Reid Kleckner604c8b42013-12-27 19:43:59 +00003011 // FIXME: Figure out how to print the real thunk type, since they can
3012 // differ in the return type.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003013 std::string Str = PredefinedExpr::ComputeName(
3014 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3015 Out << Str;
3016 if (MD->isPure())
3017 Out << " [pure]";
3018
3019 if (MD->isDeleted()) {
3020 ErrorUnsupported("deleted methods", MD->getLocation());
3021 Out << " [deleted]";
3022 }
3023
3024 ThunkInfo Thunk = VTableThunks.lookup(I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003025 if (!Thunk.isEmpty())
3026 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003027
3028 break;
3029 }
3030
3031 case VTableComponent::CK_DeletingDtorPointer: {
3032 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3033
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003034 DD->printQualifiedName(Out);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003035 Out << "() [scalar deleting]";
3036
3037 if (DD->isPure())
3038 Out << " [pure]";
3039
3040 ThunkInfo Thunk = VTableThunks.lookup(I);
3041 if (!Thunk.isEmpty()) {
3042 assert(Thunk.Return.isEmpty() &&
3043 "No return adjustment needed for destructors!");
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003044 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003045 }
3046
3047 break;
3048 }
3049
3050 default:
3051 DiagnosticsEngine &Diags = Context.getDiagnostics();
3052 unsigned DiagID = Diags.getCustomDiagID(
3053 DiagnosticsEngine::Error,
3054 "Unexpected vftable component type %0 for component number %1");
3055 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3056 << I << Component.getKind();
3057 }
3058
3059 Out << '\n';
3060 }
3061
3062 Out << '\n';
3063
3064 if (!Thunks.empty()) {
3065 // We store the method names in a map to get a stable order.
3066 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3067
3068 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3069 I != E; ++I) {
3070 const CXXMethodDecl *MD = I->first;
3071 std::string MethodName = PredefinedExpr::ComputeName(
3072 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3073
3074 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3075 }
3076
3077 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3078 I = MethodNamesAndDecls.begin(),
3079 E = MethodNamesAndDecls.end();
3080 I != E; ++I) {
3081 const std::string &MethodName = I->first;
3082 const CXXMethodDecl *MD = I->second;
3083
3084 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00003085 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003086 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
3087 // Keep different thunks with the same adjustments in the order they
3088 // were put into the vector.
Benjamin Kramera741b8c2014-03-03 20:26:46 +00003089 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003090 });
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003091
3092 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3093 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3094
3095 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3096 const ThunkInfo &Thunk = ThunksVector[I];
3097
3098 Out << llvm::format("%4d | ", I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003099 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003100 Out << '\n';
3101 }
3102
3103 Out << '\n';
3104 }
3105 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003106
3107 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003108}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003109
Reid Kleckner5f080942014-01-03 23:42:00 +00003110static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
3111 const llvm::ArrayRef<const CXXRecordDecl *> &B) {
3112 for (llvm::ArrayRef<const CXXRecordDecl *>::iterator I = B.begin(),
3113 E = B.end();
3114 I != E; ++I) {
3115 if (A.count(*I))
3116 return true;
3117 }
3118 return false;
3119}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003120
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003121static bool rebucketPaths(VPtrInfoVector &Paths);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003122
Reid Kleckner5f080942014-01-03 23:42:00 +00003123/// Produces MSVC-compatible vbtable data. The symbols produced by this
3124/// algorithm match those produced by MSVC 2012 and newer, which is different
3125/// from MSVC 2010.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003126///
3127/// MSVC 2012 appears to minimize the vbtable names using the following
3128/// algorithm. First, walk the class hierarchy in the usual order, depth first,
3129/// left to right, to find all of the subobjects which contain a vbptr field.
3130/// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3131/// record with a vbptr creates an initially empty path.
3132///
3133/// To combine paths from child nodes, the paths are compared to check for
3134/// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3135/// components in the same order. Each group of ambiguous paths is extended by
3136/// appending the class of the base from which it came. If the current class
3137/// node produced an ambiguous path, its path is extended with the current class.
3138/// After extending paths, MSVC again checks for ambiguity, and extends any
3139/// ambiguous path which wasn't already extended. Because each node yields an
3140/// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3141/// to produce an unambiguous set of paths.
3142///
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003143/// TODO: Presumably vftables use the same algorithm.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003144void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3145 const CXXRecordDecl *RD,
3146 VPtrInfoVector &Paths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003147 assert(Paths.empty());
3148 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003149
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003150 // Base case: this subobject has its own vptr.
3151 if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
3152 Paths.push_back(new VPtrInfo(RD));
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003153
Reid Kleckner5f080942014-01-03 23:42:00 +00003154 // Recursive case: get all the vbtables from our bases and remove anything
3155 // that shares a virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003156 llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
Aaron Ballman574705e2014-03-13 15:41:46 +00003157 for (const auto &I : RD->bases()) {
3158 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
3159 if (I.isVirtual() && VBasesSeen.count(Base))
Reid Kleckner5f080942014-01-03 23:42:00 +00003160 continue;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003161
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003162 if (!Base->isDynamicClass())
3163 continue;
Reid Kleckner5f080942014-01-03 23:42:00 +00003164
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003165 const VPtrInfoVector &BasePaths =
3166 ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3167
3168 for (VPtrInfoVector::const_iterator II = BasePaths.begin(),
3169 EE = BasePaths.end();
Reid Kleckner5f080942014-01-03 23:42:00 +00003170 II != EE; ++II) {
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003171 VPtrInfo *BaseInfo = *II;
Reid Kleckner5f080942014-01-03 23:42:00 +00003172
3173 // Don't include the path if it goes through a virtual base that we've
3174 // already included.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003175 if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
Reid Kleckner5f080942014-01-03 23:42:00 +00003176 continue;
3177
3178 // Copy the path and adjust it as necessary.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003179 VPtrInfo *P = new VPtrInfo(*BaseInfo);
Reid Kleckner5f080942014-01-03 23:42:00 +00003180
3181 // We mangle Base into the path if the path would've been ambiguous and it
3182 // wasn't already extended with Base.
3183 if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3184 P->NextBaseToMangle = Base;
3185
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003186 // Keep track of the full path.
3187 // FIXME: Why do we need this?
3188 P->PathToBaseWithVPtr.insert(P->PathToBaseWithVPtr.begin(), Base);
3189
3190 // Keep track of which derived class ultimately uses the vtable, and what
3191 // the full adjustment is from the MDC to this vtable. The adjustment is
Reid Kleckner5f080942014-01-03 23:42:00 +00003192 // captured by an optional vbase and a non-virtual offset.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003193 if (Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
3194 : Layout.getPrimaryBase()))
Reid Kleckner5f080942014-01-03 23:42:00 +00003195 P->ReusingBase = RD;
Aaron Ballman574705e2014-03-13 15:41:46 +00003196 if (I.isVirtual())
Reid Kleckner5f080942014-01-03 23:42:00 +00003197 P->ContainingVBases.push_back(Base);
3198 else if (P->ContainingVBases.empty())
3199 P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3200
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003201 // Update the full offset in the MDC.
3202 P->FullOffsetInMDC = P->NonVirtualOffset;
3203 if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3204 P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3205
Reid Kleckner5f080942014-01-03 23:42:00 +00003206 Paths.push_back(P);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003207 }
3208
Reid Kleckner5f080942014-01-03 23:42:00 +00003209 // After visiting any direct base, we've transitively visited all of its
3210 // morally virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003211 for (const auto &I : Base->vbases())
3212 VBasesSeen.insert(I.getType()->getAsCXXRecordDecl());
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003213 }
3214
Reid Kleckner5f080942014-01-03 23:42:00 +00003215 // Sort the paths into buckets, and if any of them are ambiguous, extend all
3216 // paths in ambiguous buckets.
3217 bool Changed = true;
3218 while (Changed)
3219 Changed = rebucketPaths(Paths);
3220}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003221
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003222static bool extendPath(VPtrInfo *P) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003223 if (P->NextBaseToMangle) {
3224 P->MangledPath.push_back(P->NextBaseToMangle);
3225 P->NextBaseToMangle = 0; // Prevent the path from being extended twice.
3226 return true;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003227 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003228 return false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003229}
3230
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003231static bool rebucketPaths(VPtrInfoVector &Paths) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003232 // What we're essentially doing here is bucketing together ambiguous paths.
3233 // Any bucket with more than one path in it gets extended by NextBase, which
3234 // is usually the direct base of the inherited the vbptr. This code uses a
3235 // sorted vector to implement a multiset to form the buckets. Note that the
3236 // ordering is based on pointers, but it doesn't change our output order. The
3237 // current algorithm is designed to match MSVC 2012's names.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003238 VPtrInfoVector PathsSorted(Paths);
Benjamin Kramer15ae7832014-03-07 21:35:40 +00003239 std::sort(PathsSorted.begin(), PathsSorted.end(),
3240 [](const VPtrInfo *LHS, const VPtrInfo *RHS) {
3241 return LHS->MangledPath < RHS->MangledPath;
3242 });
Reid Kleckner5f080942014-01-03 23:42:00 +00003243 bool Changed = false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003244 for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3245 // Scan forward to find the end of the bucket.
3246 size_t BucketStart = I;
3247 do {
3248 ++I;
Reid Kleckner5f080942014-01-03 23:42:00 +00003249 } while (I != E && PathsSorted[BucketStart]->MangledPath ==
3250 PathsSorted[I]->MangledPath);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003251
3252 // If this bucket has multiple paths, extend them all.
3253 if (I - BucketStart > 1) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003254 for (size_t II = BucketStart; II != I; ++II)
Reid Kleckner5f080942014-01-03 23:42:00 +00003255 Changed |= extendPath(PathsSorted[II]);
3256 assert(Changed && "no paths were extended to fix ambiguity");
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003257 }
3258 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003259 return Changed;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003260}
3261
3262MicrosoftVTableContext::~MicrosoftVTableContext() {
Reid Kleckner33311282014-02-28 23:26:22 +00003263 llvm::DeleteContainerSeconds(VFPtrLocations);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003264 llvm::DeleteContainerSeconds(VFTableLayouts);
3265 llvm::DeleteContainerSeconds(VBaseInfo);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003266}
3267
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003268void MicrosoftVTableContext::computeVTableRelatedInformation(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003269 const CXXRecordDecl *RD) {
3270 assert(RD->isDynamicClass());
3271
3272 // Check if we've computed this information before.
3273 if (VFPtrLocations.count(RD))
3274 return;
3275
3276 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3277
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003278 VPtrInfoVector *VFPtrs = new VPtrInfoVector();
3279 computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3280 VFPtrLocations[RD] = VFPtrs;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003281
3282 MethodVFTableLocationsTy NewMethodLocations;
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003283 for (VPtrInfoVector::iterator I = VFPtrs->begin(), E = VFPtrs->end();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003284 I != E; ++I) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003285 VFTableBuilder Builder(*this, RD, *I);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003286
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003287 VFTableIdTy id(RD, (*I)->FullOffsetInMDC);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003288 assert(VFTableLayouts.count(id) == 0);
3289 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3290 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003291 VFTableLayouts[id] = new VTableLayout(
3292 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3293 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
3294 NewMethodLocations.insert(Builder.vtable_indices_begin(),
3295 Builder.vtable_indices_end());
3296 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3297 }
3298
3299 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3300 NewMethodLocations.end());
3301 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00003302 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003303}
3304
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003305void MicrosoftVTableContext::dumpMethodLocations(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003306 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3307 raw_ostream &Out) {
3308 // Compute the vtable indices for all the member functions.
3309 // Store them in a map keyed by the location so we'll get a sorted table.
3310 std::map<MethodVFTableLocation, std::string> IndicesMap;
3311 bool HasNonzeroOffset = false;
3312
3313 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3314 E = NewMethods.end(); I != E; ++I) {
3315 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3316 assert(MD->isVirtual());
3317
3318 std::string MethodName = PredefinedExpr::ComputeName(
3319 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3320
3321 if (isa<CXXDestructorDecl>(MD)) {
3322 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3323 } else {
3324 IndicesMap[I->second] = MethodName;
3325 }
3326
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003327 if (!I->second.VFPtrOffset.isZero() || I->second.VBTableIndex != 0)
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003328 HasNonzeroOffset = true;
3329 }
3330
3331 // Print the vtable indices for all the member functions.
3332 if (!IndicesMap.empty()) {
3333 Out << "VFTable indices for ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003334 Out << "'";
3335 RD->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003336 Out << "' (" << IndicesMap.size()
3337 << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003338
3339 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3340 uint64_t LastVBIndex = 0;
3341 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3342 I = IndicesMap.begin(),
3343 E = IndicesMap.end();
3344 I != E; ++I) {
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003345 CharUnits VFPtrOffset = I->first.VFPtrOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003346 uint64_t VBIndex = I->first.VBTableIndex;
3347 if (HasNonzeroOffset &&
3348 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3349 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3350 Out << " -- accessible via ";
3351 if (VBIndex)
3352 Out << "vbtable index " << VBIndex << ", ";
3353 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3354 LastVFPtrOffset = VFPtrOffset;
3355 LastVBIndex = VBIndex;
3356 }
3357
3358 uint64_t VTableIndex = I->first.Index;
3359 const std::string &MethodName = I->second;
3360 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3361 }
3362 Out << '\n';
3363 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003364
3365 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003366}
3367
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003368const VirtualBaseInfo *MicrosoftVTableContext::computeVBTableRelatedInformation(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003369 const CXXRecordDecl *RD) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003370 VirtualBaseInfo *VBI;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003371
Reid Kleckner5f080942014-01-03 23:42:00 +00003372 {
3373 // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
3374 // as it may be modified and rehashed under us.
3375 VirtualBaseInfo *&Entry = VBaseInfo[RD];
3376 if (Entry)
3377 return Entry;
3378 Entry = VBI = new VirtualBaseInfo();
3379 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003380
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003381 computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003382
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003383 // First, see if the Derived class shared the vbptr with a non-virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003384 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003385 if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003386 // If the Derived class shares the vbptr with a non-virtual base, the shared
3387 // virtual bases come first so that the layout is the same.
3388 const VirtualBaseInfo *BaseInfo =
3389 computeVBTableRelatedInformation(VBPtrBase);
Reid Kleckner5f080942014-01-03 23:42:00 +00003390 VBI->VBTableIndices.insert(BaseInfo->VBTableIndices.begin(),
3391 BaseInfo->VBTableIndices.end());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003392 }
3393
3394 // New vbases are added to the end of the vbtable.
3395 // Skip the self entry and vbases visited in the non-virtual base, if any.
Reid Kleckner5f080942014-01-03 23:42:00 +00003396 unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
Aaron Ballman445a9392014-03-13 16:15:17 +00003397 for (const auto &I : RD->vbases()) {
3398 const CXXRecordDecl *CurVBase = I.getType()->getAsCXXRecordDecl();
Reid Kleckner5f080942014-01-03 23:42:00 +00003399 if (!VBI->VBTableIndices.count(CurVBase))
3400 VBI->VBTableIndices[CurVBase] = VBTableIndex++;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003401 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003402
Reid Kleckner5f080942014-01-03 23:42:00 +00003403 return VBI;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003404}
3405
3406unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3407 const CXXRecordDecl *VBase) {
3408 const VirtualBaseInfo *VBInfo = computeVBTableRelatedInformation(Derived);
3409 assert(VBInfo->VBTableIndices.count(VBase));
3410 return VBInfo->VBTableIndices.find(VBase)->second;
3411}
3412
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003413const VPtrInfoVector &
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003414MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003415 return computeVBTableRelatedInformation(RD)->VBPtrPaths;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003416}
3417
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003418const VPtrInfoVector &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003419MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003420 computeVTableRelatedInformation(RD);
3421
3422 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003423 return *VFPtrLocations[RD];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003424}
3425
3426const VTableLayout &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003427MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3428 CharUnits VFPtrOffset) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003429 computeVTableRelatedInformation(RD);
3430
3431 VFTableIdTy id(RD, VFPtrOffset);
3432 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3433 return *VFTableLayouts[id];
3434}
3435
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003436const MicrosoftVTableContext::MethodVFTableLocation &
3437MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003438 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3439 "Only use this method for virtual methods or dtors");
3440 if (isa<CXXDestructorDecl>(GD.getDecl()))
3441 assert(GD.getDtorType() == Dtor_Deleting);
3442
3443 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3444 if (I != MethodVFTableLocations.end())
3445 return I->second;
3446
3447 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3448
3449 computeVTableRelatedInformation(RD);
3450
3451 I = MethodVFTableLocations.find(GD);
3452 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3453 return I->second;
3454}