blob: 02f6d8ce87da6903614fd07cb28c8d5602020cff [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.
405 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
406 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +0000407 const CXXMethodDecl *MD = *I;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000408
409 if (!MD->isVirtual())
410 continue;
411
412 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
413
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000414 Out << " ";
415 MD->printQualifiedName(Out);
416 Out << " - (";
417 Overrider.Method->printQualifiedName(Out);
Timur Iskhodzhanovbe5a3d82013-06-05 06:40:07 +0000418 Out << ", " << Overrider.Offset.getQuantity() << ')';
Peter Collingbournecfd23562011-09-26 01:57:12 +0000419
420 BaseOffset Offset;
421 if (!Overrider.Method->isPure())
422 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
423
424 if (!Offset.isEmpty()) {
425 Out << " [ret-adj: ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000426 if (Offset.VirtualBase) {
427 Offset.VirtualBase->printQualifiedName(Out);
428 Out << " vbase, ";
429 }
Peter Collingbournecfd23562011-09-26 01:57:12 +0000430
431 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
432 }
433
434 Out << "\n";
435 }
436}
437
438/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
439struct VCallOffsetMap {
440
441 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
442
443 /// Offsets - Keeps track of methods and their offsets.
444 // FIXME: This should be a real map and not a vector.
445 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
446
447 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
448 /// can share the same vcall offset.
449 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
450 const CXXMethodDecl *RHS);
451
452public:
453 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
454 /// add was successful, or false if there was already a member function with
455 /// the same signature in the map.
456 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
457
458 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
459 /// vtable address point) for the given virtual member function.
460 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
461
462 // empty - Return whether the offset map is empty or not.
463 bool empty() const { return Offsets.empty(); }
464};
465
466static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
467 const CXXMethodDecl *RHS) {
John McCallb6c4a7e2012-03-21 06:57:19 +0000468 const FunctionProtoType *LT =
469 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
470 const FunctionProtoType *RT =
471 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000472
473 // Fast-path matches in the canonical types.
474 if (LT == RT) return true;
475
476 // Force the signatures to match. We can't rely on the overrides
477 // list here because there isn't necessarily an inheritance
478 // relationship between the two methods.
John McCallb6c4a7e2012-03-21 06:57:19 +0000479 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000480 LT->getNumParams() != RT->getNumParams())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000481 return false;
Alp Toker9cacbab2014-01-20 20:26:09 +0000482 for (unsigned I = 0, E = LT->getNumParams(); I != E; ++I)
483 if (LT->getParamType(I) != RT->getParamType(I))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000484 return false;
485 return true;
486}
487
488bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
489 const CXXMethodDecl *RHS) {
490 assert(LHS->isVirtual() && "LHS must be virtual!");
491 assert(RHS->isVirtual() && "LHS must be virtual!");
492
493 // A destructor can share a vcall offset with another destructor.
494 if (isa<CXXDestructorDecl>(LHS))
495 return isa<CXXDestructorDecl>(RHS);
496
497 // FIXME: We need to check more things here.
498
499 // The methods must have the same name.
500 DeclarationName LHSName = LHS->getDeclName();
501 DeclarationName RHSName = RHS->getDeclName();
502 if (LHSName != RHSName)
503 return false;
504
505 // And the same signatures.
506 return HasSameVirtualSignature(LHS, RHS);
507}
508
509bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
510 CharUnits OffsetOffset) {
511 // Check if we can reuse an offset.
512 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
513 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
514 return false;
515 }
516
517 // Add the offset.
518 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
519 return true;
520}
521
522CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
523 // Look for an offset.
524 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
525 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
526 return Offsets[I].second;
527 }
528
529 llvm_unreachable("Should always find a vcall offset offset!");
530}
531
532/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
533class VCallAndVBaseOffsetBuilder {
534public:
535 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
536 VBaseOffsetOffsetsMapTy;
537
538private:
539 /// MostDerivedClass - The most derived class for which we're building vcall
540 /// and vbase offsets.
541 const CXXRecordDecl *MostDerivedClass;
542
543 /// LayoutClass - The class we're using for layout information. Will be
544 /// different than the most derived class if we're building a construction
545 /// vtable.
546 const CXXRecordDecl *LayoutClass;
547
548 /// Context - The ASTContext which we will use for layout information.
549 ASTContext &Context;
550
551 /// Components - vcall and vbase offset components
552 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
553 VTableComponentVectorTy Components;
554
555 /// VisitedVirtualBases - Visited virtual bases.
556 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
557
558 /// VCallOffsets - Keeps track of vcall offsets.
559 VCallOffsetMap VCallOffsets;
560
561
562 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
563 /// relative to the address point.
564 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
565
566 /// FinalOverriders - The final overriders of the most derived class.
567 /// (Can be null when we're not building a vtable of the most derived class).
568 const FinalOverriders *Overriders;
569
570 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
571 /// given base subobject.
572 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
573 CharUnits RealBaseOffset);
574
575 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
576 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
577
578 /// AddVBaseOffsets - Add vbase offsets for the given class.
579 void AddVBaseOffsets(const CXXRecordDecl *Base,
580 CharUnits OffsetInLayoutClass);
581
582 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
583 /// chars, relative to the vtable address point.
584 CharUnits getCurrentOffsetOffset() const;
585
586public:
587 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
588 const CXXRecordDecl *LayoutClass,
589 const FinalOverriders *Overriders,
590 BaseSubobject Base, bool BaseIsVirtual,
591 CharUnits OffsetInLayoutClass)
592 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
593 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
594
595 // Add vcall and vbase offsets.
596 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
597 }
598
599 /// Methods for iterating over the components.
600 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
601 const_iterator components_begin() const { return Components.rbegin(); }
602 const_iterator components_end() const { return Components.rend(); }
603
604 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
605 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
606 return VBaseOffsetOffsets;
607 }
608};
609
610void
611VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
612 bool BaseIsVirtual,
613 CharUnits RealBaseOffset) {
614 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
615
616 // Itanium C++ ABI 2.5.2:
617 // ..in classes sharing a virtual table with a primary base class, the vcall
618 // and vbase offsets added by the derived class all come before the vcall
619 // and vbase offsets required by the base class, so that the latter may be
620 // laid out as required by the base class without regard to additions from
621 // the derived class(es).
622
623 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
624 // emit them for the primary base first).
625 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
626 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
627
628 CharUnits PrimaryBaseOffset;
629
630 // Get the base offset of the primary base.
631 if (PrimaryBaseIsVirtual) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000632 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000633 "Primary vbase should have a zero offset!");
634
635 const ASTRecordLayout &MostDerivedClassLayout =
636 Context.getASTRecordLayout(MostDerivedClass);
637
638 PrimaryBaseOffset =
639 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
640 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000641 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000642 "Primary base should have a zero offset!");
643
644 PrimaryBaseOffset = Base.getBaseOffset();
645 }
646
647 AddVCallAndVBaseOffsets(
648 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
649 PrimaryBaseIsVirtual, RealBaseOffset);
650 }
651
652 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
653
654 // We only want to add vcall offsets for virtual bases.
655 if (BaseIsVirtual)
656 AddVCallOffsets(Base, RealBaseOffset);
657}
658
659CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
660 // OffsetIndex is the index of this vcall or vbase offset, relative to the
661 // vtable address point. (We subtract 3 to account for the information just
662 // above the address point, the RTTI info, the offset to top, and the
663 // vcall offset itself).
664 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
665
666 CharUnits PointerWidth =
667 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
668 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
669 return OffsetOffset;
670}
671
672void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
673 CharUnits VBaseOffset) {
674 const CXXRecordDecl *RD = Base.getBase();
675 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
676
677 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
678
679 // Handle the primary base first.
680 // We only want to add vcall offsets if the base is non-virtual; a virtual
681 // primary base will have its vcall and vbase offsets emitted already.
682 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
683 // Get the base offset of the primary base.
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000684 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000685 "Primary base should have a zero offset!");
686
687 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
688 VBaseOffset);
689 }
690
691 // Add the vcall offsets.
692 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
693 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +0000694 const CXXMethodDecl *MD = *I;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000695
696 if (!MD->isVirtual())
697 continue;
698
699 CharUnits OffsetOffset = getCurrentOffsetOffset();
700
701 // Don't add a vcall offset if we already have one for this member function
702 // signature.
703 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
704 continue;
705
706 CharUnits Offset = CharUnits::Zero();
707
708 if (Overriders) {
709 // Get the final overrider.
710 FinalOverriders::OverriderInfo Overrider =
711 Overriders->getOverrider(MD, Base.getBaseOffset());
712
713 /// The vcall offset is the offset from the virtual base to the object
714 /// where the function was overridden.
715 Offset = Overrider.Offset - VBaseOffset;
716 }
717
718 Components.push_back(
719 VTableComponent::MakeVCallOffset(Offset));
720 }
721
722 // And iterate over all non-virtual bases (ignoring the primary base).
Aaron Ballman574705e2014-03-13 15:41:46 +0000723 for (const auto &I : RD->bases()) {
724 if (I.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000725 continue;
726
Aaron Ballman574705e2014-03-13 15:41:46 +0000727 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000728 if (BaseDecl == PrimaryBase)
729 continue;
730
731 // Get the base offset of this base.
732 CharUnits BaseOffset = Base.getBaseOffset() +
733 Layout.getBaseClassOffset(BaseDecl);
734
735 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
736 VBaseOffset);
737 }
738}
739
740void
741VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
742 CharUnits OffsetInLayoutClass) {
743 const ASTRecordLayout &LayoutClassLayout =
744 Context.getASTRecordLayout(LayoutClass);
745
746 // Add vbase offsets.
Aaron Ballman574705e2014-03-13 15:41:46 +0000747 for (const auto &I : RD->bases()) {
748 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000749
750 // Check if this is a virtual base that we haven't visited before.
Aaron Ballman574705e2014-03-13 15:41:46 +0000751 if (I.isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000752 CharUnits Offset =
753 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
754
755 // Add the vbase offset offset.
756 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
757 "vbase offset offset already exists!");
758
759 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
760 VBaseOffsetOffsets.insert(
761 std::make_pair(BaseDecl, VBaseOffsetOffset));
762
763 Components.push_back(
764 VTableComponent::MakeVBaseOffset(Offset));
765 }
766
767 // Check the base class looking for more vbase offsets.
768 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
769 }
770}
771
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000772/// ItaniumVTableBuilder - Class for building vtable layout information.
773class ItaniumVTableBuilder {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000774public:
775 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
776 /// primary bases.
777 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
778 PrimaryBasesSetVectorTy;
779
780 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
781 VBaseOffsetOffsetsMapTy;
782
783 typedef llvm::DenseMap<BaseSubobject, uint64_t>
784 AddressPointsMapTy;
785
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000786 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
787
Peter Collingbournecfd23562011-09-26 01:57:12 +0000788private:
789 /// VTables - Global vtable information.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000790 ItaniumVTableContext &VTables;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000791
792 /// MostDerivedClass - The most derived class for which we're building this
793 /// vtable.
794 const CXXRecordDecl *MostDerivedClass;
795
796 /// MostDerivedClassOffset - If we're building a construction vtable, this
797 /// holds the offset from the layout class to the most derived class.
798 const CharUnits MostDerivedClassOffset;
799
800 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
801 /// base. (This only makes sense when building a construction vtable).
802 bool MostDerivedClassIsVirtual;
803
804 /// LayoutClass - The class we're using for layout information. Will be
805 /// different than the most derived class if we're building a construction
806 /// vtable.
807 const CXXRecordDecl *LayoutClass;
808
809 /// Context - The ASTContext which we will use for layout information.
810 ASTContext &Context;
811
812 /// FinalOverriders - The final overriders of the most derived class.
813 const FinalOverriders Overriders;
814
815 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
816 /// bases in this vtable.
817 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
818
819 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
820 /// the most derived class.
821 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
822
823 /// Components - The components of the vtable being built.
824 SmallVector<VTableComponent, 64> Components;
825
826 /// AddressPoints - Address points for the vtable being built.
827 AddressPointsMapTy AddressPoints;
828
829 /// MethodInfo - Contains information about a method in a vtable.
830 /// (Used for computing 'this' pointer adjustment thunks.
831 struct MethodInfo {
832 /// BaseOffset - The base offset of this method.
833 const CharUnits BaseOffset;
834
835 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
836 /// method.
837 const CharUnits BaseOffsetInLayoutClass;
838
839 /// VTableIndex - The index in the vtable that this method has.
840 /// (For destructors, this is the index of the complete destructor).
841 const uint64_t VTableIndex;
842
843 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
844 uint64_t VTableIndex)
845 : BaseOffset(BaseOffset),
846 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
847 VTableIndex(VTableIndex) { }
848
849 MethodInfo()
850 : BaseOffset(CharUnits::Zero()),
851 BaseOffsetInLayoutClass(CharUnits::Zero()),
852 VTableIndex(0) { }
853 };
854
855 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
856
857 /// MethodInfoMap - The information for all methods in the vtable we're
858 /// currently building.
859 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000860
861 /// MethodVTableIndices - Contains the index (relative to the vtable address
862 /// point) where the function pointer for a virtual function is stored.
863 MethodVTableIndicesTy MethodVTableIndices;
864
Peter Collingbournecfd23562011-09-26 01:57:12 +0000865 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
866
867 /// VTableThunks - The thunks by vtable index in the vtable currently being
868 /// built.
869 VTableThunksMapTy VTableThunks;
870
871 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
872 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
873
874 /// Thunks - A map that contains all the thunks needed for all methods in the
875 /// most derived class for which the vtable is currently being built.
876 ThunksMapTy Thunks;
877
878 /// AddThunk - Add a thunk for the given method.
879 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
880
881 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
882 /// part of the vtable we're currently building.
883 void ComputeThisAdjustments();
884
885 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
886
887 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
888 /// some other base.
889 VisitedVirtualBasesSetTy PrimaryVirtualBases;
890
891 /// ComputeReturnAdjustment - Compute the return adjustment given a return
892 /// adjustment base offset.
893 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
894
895 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
896 /// the 'this' pointer from the base subobject to the derived subobject.
897 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
898 BaseSubobject Derived) const;
899
900 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
901 /// given virtual member function, its offset in the layout class and its
902 /// final overrider.
903 ThisAdjustment
904 ComputeThisAdjustment(const CXXMethodDecl *MD,
905 CharUnits BaseOffsetInLayoutClass,
906 FinalOverriders::OverriderInfo Overrider);
907
908 /// AddMethod - Add a single virtual member function to the vtable
909 /// components vector.
910 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
911
912 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
913 /// part of the vtable.
914 ///
915 /// Itanium C++ ABI 2.5.2:
916 ///
917 /// struct A { virtual void f(); };
918 /// struct B : virtual public A { int i; };
919 /// struct C : virtual public A { int j; };
920 /// struct D : public B, public C {};
921 ///
922 /// When B and C are declared, A is a primary base in each case, so although
923 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
924 /// adjustment is required and no thunk is generated. However, inside D
925 /// objects, A is no longer a primary base of C, so if we allowed calls to
926 /// C::f() to use the copy of A's vtable in the C subobject, we would need
927 /// to adjust this from C* to B::A*, which would require a third-party
928 /// thunk. Since we require that a call to C::f() first convert to A*,
929 /// C-in-D's copy of A's vtable is never referenced, so this is not
930 /// necessary.
931 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
932 CharUnits BaseOffsetInLayoutClass,
933 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
934 CharUnits FirstBaseOffsetInLayoutClass) const;
935
936
937 /// AddMethods - Add the methods of this base subobject and all its
938 /// primary bases to the vtable components vector.
939 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
940 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
941 CharUnits FirstBaseOffsetInLayoutClass,
942 PrimaryBasesSetVectorTy &PrimaryBases);
943
944 // LayoutVTable - Layout the vtable for the given base class, including its
945 // secondary vtables and any vtables for virtual bases.
946 void LayoutVTable();
947
948 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
949 /// given base subobject, as well as all its secondary vtables.
950 ///
951 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
952 /// or a direct or indirect base of a virtual base.
953 ///
954 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
955 /// in the layout class.
956 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
957 bool BaseIsMorallyVirtual,
958 bool BaseIsVirtualInLayoutClass,
959 CharUnits OffsetInLayoutClass);
960
961 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
962 /// subobject.
963 ///
964 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
965 /// or a direct or indirect base of a virtual base.
966 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
967 CharUnits OffsetInLayoutClass);
968
969 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
970 /// class hierarchy.
971 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
972 CharUnits OffsetInLayoutClass,
973 VisitedVirtualBasesSetTy &VBases);
974
975 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
976 /// given base (excluding any primary bases).
977 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
978 VisitedVirtualBasesSetTy &VBases);
979
980 /// isBuildingConstructionVTable - Return whether this vtable builder is
981 /// building a construction vtable.
982 bool isBuildingConstructorVTable() const {
983 return MostDerivedClass != LayoutClass;
984 }
985
986public:
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000987 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
988 const CXXRecordDecl *MostDerivedClass,
989 CharUnits MostDerivedClassOffset,
990 bool MostDerivedClassIsVirtual,
991 const CXXRecordDecl *LayoutClass)
992 : VTables(VTables), MostDerivedClass(MostDerivedClass),
993 MostDerivedClassOffset(MostDerivedClassOffset),
994 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
995 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
996 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000997 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000998
999 LayoutVTable();
1000
David Blaikiebbafb8a2012-03-11 07:00:24 +00001001 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00001002 dumpLayout(llvm::outs());
Peter Collingbournecfd23562011-09-26 01:57:12 +00001003 }
1004
1005 uint64_t getNumThunks() const {
1006 return Thunks.size();
1007 }
1008
1009 ThunksMapTy::const_iterator thunks_begin() const {
1010 return Thunks.begin();
1011 }
1012
1013 ThunksMapTy::const_iterator thunks_end() const {
1014 return Thunks.end();
1015 }
1016
1017 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1018 return VBaseOffsetOffsets;
1019 }
1020
1021 const AddressPointsMapTy &getAddressPoints() const {
1022 return AddressPoints;
1023 }
1024
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001025 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1026 return MethodVTableIndices.begin();
1027 }
1028
1029 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1030 return MethodVTableIndices.end();
1031 }
1032
Peter Collingbournecfd23562011-09-26 01:57:12 +00001033 /// getNumVTableComponents - Return the number of components in the vtable
1034 /// currently built.
1035 uint64_t getNumVTableComponents() const {
1036 return Components.size();
1037 }
1038
1039 const VTableComponent *vtable_component_begin() const {
1040 return Components.begin();
1041 }
1042
1043 const VTableComponent *vtable_component_end() const {
1044 return Components.end();
1045 }
1046
1047 AddressPointsMapTy::const_iterator address_points_begin() const {
1048 return AddressPoints.begin();
1049 }
1050
1051 AddressPointsMapTy::const_iterator address_points_end() const {
1052 return AddressPoints.end();
1053 }
1054
1055 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1056 return VTableThunks.begin();
1057 }
1058
1059 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1060 return VTableThunks.end();
1061 }
1062
1063 /// dumpLayout - Dump the vtable layout.
1064 void dumpLayout(raw_ostream&);
1065};
1066
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001067void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1068 const ThunkInfo &Thunk) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001069 assert(!isBuildingConstructorVTable() &&
1070 "Can't add thunks for construction vtable");
1071
Craig Topper5603df42013-07-05 19:34:19 +00001072 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1073
Peter Collingbournecfd23562011-09-26 01:57:12 +00001074 // Check if we have this thunk already.
1075 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1076 ThunksVector.end())
1077 return;
1078
1079 ThunksVector.push_back(Thunk);
1080}
1081
1082typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1083
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001084/// Visit all the methods overridden by the given method recursively,
1085/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1086/// indicating whether to continue the recursion for the given overridden
1087/// method (i.e. returning false stops the iteration).
1088template <class VisitorTy>
1089static void
1090visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001091 assert(MD->isVirtual() && "Method is not virtual!");
1092
1093 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1094 E = MD->end_overridden_methods(); I != E; ++I) {
1095 const CXXMethodDecl *OverriddenMD = *I;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001096 if (!Visitor.visit(OverriddenMD))
1097 continue;
1098 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001099 }
1100}
1101
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001102namespace {
1103 struct OverriddenMethodsCollector {
1104 OverriddenMethodsSetTy *Methods;
1105
1106 bool visit(const CXXMethodDecl *MD) {
1107 // Don't recurse on this method if we've already collected it.
1108 return Methods->insert(MD);
1109 }
1110 };
1111}
1112
1113/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1114/// the overridden methods that the function decl overrides.
1115static void
1116ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1117 OverriddenMethodsSetTy& OverriddenMethods) {
1118 OverriddenMethodsCollector Collector = { &OverriddenMethods };
1119 visitAllOverriddenMethods(MD, Collector);
1120}
1121
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001122void ItaniumVTableBuilder::ComputeThisAdjustments() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001123 // Now go through the method info map and see if any of the methods need
1124 // 'this' pointer adjustments.
1125 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1126 E = MethodInfoMap.end(); I != E; ++I) {
1127 const CXXMethodDecl *MD = I->first;
1128 const MethodInfo &MethodInfo = I->second;
1129
1130 // Ignore adjustments for unused function pointers.
1131 uint64_t VTableIndex = MethodInfo.VTableIndex;
1132 if (Components[VTableIndex].getKind() ==
1133 VTableComponent::CK_UnusedFunctionPointer)
1134 continue;
1135
1136 // Get the final overrider for this method.
1137 FinalOverriders::OverriderInfo Overrider =
1138 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1139
1140 // Check if we need an adjustment at all.
1141 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1142 // When a return thunk is needed by a derived class that overrides a
1143 // virtual base, gcc uses a virtual 'this' adjustment as well.
1144 // While the thunk itself might be needed by vtables in subclasses or
1145 // in construction vtables, there doesn't seem to be a reason for using
1146 // the thunk in this vtable. Still, we do so to match gcc.
1147 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1148 continue;
1149 }
1150
1151 ThisAdjustment ThisAdjustment =
1152 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1153
1154 if (ThisAdjustment.isEmpty())
1155 continue;
1156
1157 // Add it.
1158 VTableThunks[VTableIndex].This = ThisAdjustment;
1159
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001160 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001161 // Add an adjustment for the deleting destructor as well.
1162 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1163 }
1164 }
1165
1166 /// Clear the method info map.
1167 MethodInfoMap.clear();
1168
1169 if (isBuildingConstructorVTable()) {
1170 // We don't need to store thunk information for construction vtables.
1171 return;
1172 }
1173
1174 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1175 E = VTableThunks.end(); I != E; ++I) {
1176 const VTableComponent &Component = Components[I->first];
1177 const ThunkInfo &Thunk = I->second;
1178 const CXXMethodDecl *MD;
1179
1180 switch (Component.getKind()) {
1181 default:
1182 llvm_unreachable("Unexpected vtable component kind!");
1183 case VTableComponent::CK_FunctionPointer:
1184 MD = Component.getFunctionDecl();
1185 break;
1186 case VTableComponent::CK_CompleteDtorPointer:
1187 MD = Component.getDestructorDecl();
1188 break;
1189 case VTableComponent::CK_DeletingDtorPointer:
1190 // We've already added the thunk when we saw the complete dtor pointer.
1191 continue;
1192 }
1193
1194 if (MD->getParent() == MostDerivedClass)
1195 AddThunk(MD, Thunk);
1196 }
1197}
1198
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001199ReturnAdjustment
1200ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001201 ReturnAdjustment Adjustment;
1202
1203 if (!Offset.isEmpty()) {
1204 if (Offset.VirtualBase) {
1205 // Get the virtual base offset offset.
1206 if (Offset.DerivedClass == MostDerivedClass) {
1207 // We can get the offset offset directly from our map.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001208 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001209 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1210 } else {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001211 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001212 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1213 Offset.VirtualBase).getQuantity();
1214 }
1215 }
1216
1217 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1218 }
1219
1220 return Adjustment;
1221}
1222
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001223BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1224 BaseSubobject Base, BaseSubobject Derived) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001225 const CXXRecordDecl *BaseRD = Base.getBase();
1226 const CXXRecordDecl *DerivedRD = Derived.getBase();
1227
1228 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1229 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1230
Benjamin Kramer325d7452013-02-03 18:55:34 +00001231 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +00001232 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +00001233
1234 // We have to go through all the paths, and see which one leads us to the
1235 // right base subobject.
1236 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1237 I != E; ++I) {
1238 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1239
1240 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1241
1242 if (Offset.VirtualBase) {
1243 // If we have a virtual base class, the non-virtual offset is relative
1244 // to the virtual base class offset.
1245 const ASTRecordLayout &LayoutClassLayout =
1246 Context.getASTRecordLayout(LayoutClass);
1247
1248 /// Get the virtual base offset, relative to the most derived class
1249 /// layout.
1250 OffsetToBaseSubobject +=
1251 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1252 } else {
1253 // Otherwise, the non-virtual offset is relative to the derived class
1254 // offset.
1255 OffsetToBaseSubobject += Derived.getBaseOffset();
1256 }
1257
1258 // Check if this path gives us the right base subobject.
1259 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1260 // Since we're going from the base class _to_ the derived class, we'll
1261 // invert the non-virtual offset here.
1262 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1263 return Offset;
1264 }
1265 }
1266
1267 return BaseOffset();
1268}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001269
1270ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1271 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1272 FinalOverriders::OverriderInfo Overrider) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001273 // Ignore adjustments for pure virtual member functions.
1274 if (Overrider.Method->isPure())
1275 return ThisAdjustment();
1276
1277 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1278 BaseOffsetInLayoutClass);
1279
1280 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1281 Overrider.Offset);
1282
1283 // Compute the adjustment offset.
1284 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1285 OverriderBaseSubobject);
1286 if (Offset.isEmpty())
1287 return ThisAdjustment();
1288
1289 ThisAdjustment Adjustment;
1290
1291 if (Offset.VirtualBase) {
1292 // Get the vcall offset map for this virtual base.
1293 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1294
1295 if (VCallOffsets.empty()) {
1296 // We don't have vcall offsets for this virtual base, go ahead and
1297 // build them.
1298 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1299 /*FinalOverriders=*/0,
1300 BaseSubobject(Offset.VirtualBase,
1301 CharUnits::Zero()),
1302 /*BaseIsVirtual=*/true,
1303 /*OffsetInLayoutClass=*/
1304 CharUnits::Zero());
1305
1306 VCallOffsets = Builder.getVCallOffsets();
1307 }
1308
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001309 Adjustment.Virtual.Itanium.VCallOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001310 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1311 }
1312
1313 // Set the non-virtual part of the adjustment.
1314 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1315
1316 return Adjustment;
1317}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001318
1319void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1320 ReturnAdjustment ReturnAdjustment) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001321 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1322 assert(ReturnAdjustment.isEmpty() &&
1323 "Destructor can't have return adjustment!");
1324
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001325 // Add both the complete destructor and the deleting destructor.
1326 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1327 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbournecfd23562011-09-26 01:57:12 +00001328 } else {
1329 // Add the return adjustment if necessary.
1330 if (!ReturnAdjustment.isEmpty())
1331 VTableThunks[Components.size()].Return = ReturnAdjustment;
1332
1333 // Add the function.
1334 Components.push_back(VTableComponent::MakeFunction(MD));
1335 }
1336}
1337
1338/// OverridesIndirectMethodInBase - Return whether the given member function
1339/// overrides any methods in the set of given bases.
1340/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1341/// For example, if we have:
1342///
1343/// struct A { virtual void f(); }
1344/// struct B : A { virtual void f(); }
1345/// struct C : B { virtual void f(); }
1346///
1347/// OverridesIndirectMethodInBase will return true if given C::f as the method
1348/// and { A } as the set of bases.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001349static bool OverridesIndirectMethodInBases(
1350 const CXXMethodDecl *MD,
1351 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001352 if (Bases.count(MD->getParent()))
1353 return true;
1354
1355 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1356 E = MD->end_overridden_methods(); I != E; ++I) {
1357 const CXXMethodDecl *OverriddenMD = *I;
1358
1359 // Check "indirect overriders".
1360 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1361 return true;
1362 }
1363
1364 return false;
1365}
1366
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001367bool ItaniumVTableBuilder::IsOverriderUsed(
1368 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1369 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1370 CharUnits FirstBaseOffsetInLayoutClass) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001371 // If the base and the first base in the primary base chain have the same
1372 // offsets, then this overrider will be used.
1373 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1374 return true;
1375
1376 // We know now that Base (or a direct or indirect base of it) is a primary
1377 // base in part of the class hierarchy, but not a primary base in the most
1378 // derived class.
1379
1380 // If the overrider is the first base in the primary base chain, we know
1381 // that the overrider will be used.
1382 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1383 return true;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001384
1385 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001386
1387 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1388 PrimaryBases.insert(RD);
1389
1390 // Now traverse the base chain, starting with the first base, until we find
1391 // the base that is no longer a primary base.
1392 while (true) {
1393 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1394 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1395
1396 if (!PrimaryBase)
1397 break;
1398
1399 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001400 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001401 "Primary base should always be at offset 0!");
1402
1403 const ASTRecordLayout &LayoutClassLayout =
1404 Context.getASTRecordLayout(LayoutClass);
1405
1406 // Now check if this is the primary base that is not a primary base in the
1407 // most derived class.
1408 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1409 FirstBaseOffsetInLayoutClass) {
1410 // We found it, stop walking the chain.
1411 break;
1412 }
1413 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001414 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001415 "Primary base should always be at offset 0!");
1416 }
1417
1418 if (!PrimaryBases.insert(PrimaryBase))
1419 llvm_unreachable("Found a duplicate primary base!");
1420
1421 RD = PrimaryBase;
1422 }
1423
1424 // If the final overrider is an override of one of the primary bases,
1425 // then we know that it will be used.
1426 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1427}
1428
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001429typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1430
Peter Collingbournecfd23562011-09-26 01:57:12 +00001431/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1432/// from the nearest base. Returns null if no method was found.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001433/// The Bases are expected to be sorted in a base-to-derived order.
1434static const CXXMethodDecl *
Peter Collingbournecfd23562011-09-26 01:57:12 +00001435FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001436 BasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001437 OverriddenMethodsSetTy OverriddenMethods;
1438 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1439
1440 for (int I = Bases.size(), E = 0; I != E; --I) {
1441 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1442
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001443 // Now check the overridden methods.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001444 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1445 E = OverriddenMethods.end(); I != E; ++I) {
1446 const CXXMethodDecl *OverriddenMD = *I;
1447
1448 // We found our overridden method.
1449 if (OverriddenMD->getParent() == PrimaryBase)
1450 return OverriddenMD;
1451 }
1452 }
1453
1454 return 0;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001455}
Peter Collingbournecfd23562011-09-26 01:57:12 +00001456
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001457void ItaniumVTableBuilder::AddMethods(
1458 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1459 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1460 CharUnits FirstBaseOffsetInLayoutClass,
1461 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001462 // Itanium C++ ABI 2.5.2:
1463 // The order of the virtual function pointers in a virtual table is the
1464 // order of declaration of the corresponding member functions in the class.
1465 //
1466 // There is an entry for any virtual function declared in a class,
1467 // whether it is a new function or overrides a base class function,
1468 // unless it overrides a function from the primary base, and conversion
1469 // between their return types does not require an adjustment.
1470
Peter Collingbournecfd23562011-09-26 01:57:12 +00001471 const CXXRecordDecl *RD = Base.getBase();
1472 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1473
1474 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1475 CharUnits PrimaryBaseOffset;
1476 CharUnits PrimaryBaseOffsetInLayoutClass;
1477 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001478 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001479 "Primary vbase should have a zero offset!");
1480
1481 const ASTRecordLayout &MostDerivedClassLayout =
1482 Context.getASTRecordLayout(MostDerivedClass);
1483
1484 PrimaryBaseOffset =
1485 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1486
1487 const ASTRecordLayout &LayoutClassLayout =
1488 Context.getASTRecordLayout(LayoutClass);
1489
1490 PrimaryBaseOffsetInLayoutClass =
1491 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1492 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001493 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001494 "Primary base should have a zero offset!");
1495
1496 PrimaryBaseOffset = Base.getBaseOffset();
1497 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1498 }
1499
1500 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1501 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1502 FirstBaseOffsetInLayoutClass, PrimaryBases);
1503
1504 if (!PrimaryBases.insert(PrimaryBase))
1505 llvm_unreachable("Found a duplicate primary base!");
1506 }
1507
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001508 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1509
1510 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1511 NewVirtualFunctionsTy NewVirtualFunctions;
1512
Peter Collingbournecfd23562011-09-26 01:57:12 +00001513 // Now go through all virtual member functions and add them.
1514 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1515 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001516 const CXXMethodDecl *MD = *I;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001517
1518 if (!MD->isVirtual())
1519 continue;
1520
1521 // Get the final overrider.
1522 FinalOverriders::OverriderInfo Overrider =
1523 Overriders.getOverrider(MD, Base.getBaseOffset());
1524
1525 // Check if this virtual member function overrides a method in a primary
1526 // base. If this is the case, and the return type doesn't require adjustment
1527 // then we can just use the member function from the primary base.
1528 if (const CXXMethodDecl *OverriddenMD =
1529 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1530 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1531 OverriddenMD).isEmpty()) {
1532 // Replace the method info of the overridden method with our own
1533 // method.
1534 assert(MethodInfoMap.count(OverriddenMD) &&
1535 "Did not find the overridden method!");
1536 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1537
1538 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1539 OverriddenMethodInfo.VTableIndex);
1540
1541 assert(!MethodInfoMap.count(MD) &&
1542 "Should not have method info for this method yet!");
1543
1544 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1545 MethodInfoMap.erase(OverriddenMD);
1546
1547 // If the overridden method exists in a virtual base class or a direct
1548 // or indirect base class of a virtual base class, we need to emit a
1549 // thunk if we ever have a class hierarchy where the base class is not
1550 // a primary base in the complete object.
1551 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1552 // Compute the this adjustment.
1553 ThisAdjustment ThisAdjustment =
1554 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1555 Overrider);
1556
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001557 if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001558 Overrider.Method->getParent() == MostDerivedClass) {
1559
1560 // There's no return adjustment from OverriddenMD and MD,
1561 // but that doesn't mean there isn't one between MD and
1562 // the final overrider.
1563 BaseOffset ReturnAdjustmentOffset =
1564 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1565 ReturnAdjustment ReturnAdjustment =
1566 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1567
1568 // This is a virtual thunk for the most derived class, add it.
1569 AddThunk(Overrider.Method,
1570 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1571 }
1572 }
1573
1574 continue;
1575 }
1576 }
1577
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001578 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1579 if (MD->isImplicit()) {
1580 // Itanium C++ ABI 2.5.2:
1581 // If a class has an implicitly-defined virtual destructor,
1582 // its entries come after the declared virtual function pointers.
1583
1584 assert(!ImplicitVirtualDtor &&
1585 "Did already see an implicit virtual dtor!");
1586 ImplicitVirtualDtor = DD;
1587 continue;
1588 }
1589 }
1590
1591 NewVirtualFunctions.push_back(MD);
1592 }
1593
1594 if (ImplicitVirtualDtor)
1595 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1596
1597 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1598 E = NewVirtualFunctions.end(); I != E; ++I) {
1599 const CXXMethodDecl *MD = *I;
1600
1601 // Get the final overrider.
1602 FinalOverriders::OverriderInfo Overrider =
1603 Overriders.getOverrider(MD, Base.getBaseOffset());
1604
Peter Collingbournecfd23562011-09-26 01:57:12 +00001605 // Insert the method info for this method.
1606 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1607 Components.size());
1608
1609 assert(!MethodInfoMap.count(MD) &&
1610 "Should not have method info for this method yet!");
1611 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1612
1613 // Check if this overrider is going to be used.
1614 const CXXMethodDecl *OverriderMD = Overrider.Method;
1615 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1616 FirstBaseInPrimaryBaseChain,
1617 FirstBaseOffsetInLayoutClass)) {
1618 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1619 continue;
1620 }
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001621
Peter Collingbournecfd23562011-09-26 01:57:12 +00001622 // Check if this overrider needs a return adjustment.
1623 // We don't want to do this for pure virtual member functions.
1624 BaseOffset ReturnAdjustmentOffset;
1625 if (!OverriderMD->isPure()) {
1626 ReturnAdjustmentOffset =
1627 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1628 }
1629
1630 ReturnAdjustment ReturnAdjustment =
1631 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1632
1633 AddMethod(Overrider.Method, ReturnAdjustment);
1634 }
1635}
1636
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001637void ItaniumVTableBuilder::LayoutVTable() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001638 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1639 CharUnits::Zero()),
1640 /*BaseIsMorallyVirtual=*/false,
1641 MostDerivedClassIsVirtual,
1642 MostDerivedClassOffset);
1643
1644 VisitedVirtualBasesSetTy VBases;
1645
1646 // Determine the primary virtual bases.
1647 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1648 VBases);
1649 VBases.clear();
1650
1651 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1652
1653 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001654 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001655 if (IsAppleKext)
1656 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1657}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001658
1659void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1660 BaseSubobject Base, bool BaseIsMorallyVirtual,
1661 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001662 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1663
1664 // Add vcall and vbase offsets for this vtable.
1665 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1666 Base, BaseIsVirtualInLayoutClass,
1667 OffsetInLayoutClass);
1668 Components.append(Builder.components_begin(), Builder.components_end());
1669
1670 // Check if we need to add these vcall offsets.
1671 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1672 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1673
1674 if (VCallOffsets.empty())
1675 VCallOffsets = Builder.getVCallOffsets();
1676 }
1677
1678 // If we're laying out the most derived class we want to keep track of the
1679 // virtual base class offset offsets.
1680 if (Base.getBase() == MostDerivedClass)
1681 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1682
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001683 // Add the offset to top.
1684 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1685 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001686
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001687 // Next, add the RTTI.
1688 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001689
Peter Collingbournecfd23562011-09-26 01:57:12 +00001690 uint64_t AddressPoint = Components.size();
1691
1692 // Now go through all virtual member functions and add them.
1693 PrimaryBasesSetVectorTy PrimaryBases;
1694 AddMethods(Base, OffsetInLayoutClass,
1695 Base.getBase(), OffsetInLayoutClass,
1696 PrimaryBases);
1697
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001698 const CXXRecordDecl *RD = Base.getBase();
1699 if (RD == MostDerivedClass) {
1700 assert(MethodVTableIndices.empty());
1701 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1702 E = MethodInfoMap.end(); I != E; ++I) {
1703 const CXXMethodDecl *MD = I->first;
1704 const MethodInfo &MI = I->second;
1705 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001706 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1707 = MI.VTableIndex - AddressPoint;
1708 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1709 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001710 } else {
1711 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1712 }
1713 }
1714 }
1715
Peter Collingbournecfd23562011-09-26 01:57:12 +00001716 // Compute 'this' pointer adjustments.
1717 ComputeThisAdjustments();
1718
1719 // Add all address points.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001720 while (true) {
1721 AddressPoints.insert(std::make_pair(
1722 BaseSubobject(RD, OffsetInLayoutClass),
1723 AddressPoint));
1724
1725 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1726 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1727
1728 if (!PrimaryBase)
1729 break;
1730
1731 if (Layout.isPrimaryBaseVirtual()) {
1732 // Check if this virtual primary base is a primary base in the layout
1733 // class. If it's not, we don't want to add it.
1734 const ASTRecordLayout &LayoutClassLayout =
1735 Context.getASTRecordLayout(LayoutClass);
1736
1737 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1738 OffsetInLayoutClass) {
1739 // We don't want to add this class (or any of its primary bases).
1740 break;
1741 }
1742 }
1743
1744 RD = PrimaryBase;
1745 }
1746
1747 // Layout secondary vtables.
1748 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1749}
1750
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001751void
1752ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1753 bool BaseIsMorallyVirtual,
1754 CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001755 // Itanium C++ ABI 2.5.2:
1756 // Following the primary virtual table of a derived class are secondary
1757 // virtual tables for each of its proper base classes, except any primary
1758 // base(s) with which it shares its primary virtual table.
1759
1760 const CXXRecordDecl *RD = Base.getBase();
1761 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1762 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1763
Aaron Ballman574705e2014-03-13 15:41:46 +00001764 for (const auto &I : RD->bases()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001765 // Ignore virtual bases, we'll emit them later.
Aaron Ballman574705e2014-03-13 15:41:46 +00001766 if (I.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +00001767 continue;
1768
Aaron Ballman574705e2014-03-13 15:41:46 +00001769 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001770
1771 // Ignore bases that don't have a vtable.
1772 if (!BaseDecl->isDynamicClass())
1773 continue;
1774
1775 if (isBuildingConstructorVTable()) {
1776 // Itanium C++ ABI 2.6.4:
1777 // Some of the base class subobjects may not need construction virtual
1778 // tables, which will therefore not be present in the construction
1779 // virtual table group, even though the subobject virtual tables are
1780 // present in the main virtual table group for the complete object.
1781 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1782 continue;
1783 }
1784
1785 // Get the base offset of this base.
1786 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1787 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1788
1789 CharUnits BaseOffsetInLayoutClass =
1790 OffsetInLayoutClass + RelativeBaseOffset;
1791
1792 // Don't emit a secondary vtable for a primary base. We might however want
1793 // to emit secondary vtables for other bases of this base.
1794 if (BaseDecl == PrimaryBase) {
1795 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1796 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1797 continue;
1798 }
1799
1800 // Layout the primary vtable (and any secondary vtables) for this base.
1801 LayoutPrimaryAndSecondaryVTables(
1802 BaseSubobject(BaseDecl, BaseOffset),
1803 BaseIsMorallyVirtual,
1804 /*BaseIsVirtualInLayoutClass=*/false,
1805 BaseOffsetInLayoutClass);
1806 }
1807}
1808
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001809void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1810 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1811 VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001812 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1813
1814 // Check if this base has a primary base.
1815 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1816
1817 // Check if it's virtual.
1818 if (Layout.isPrimaryBaseVirtual()) {
1819 bool IsPrimaryVirtualBase = true;
1820
1821 if (isBuildingConstructorVTable()) {
1822 // Check if the base is actually a primary base in the class we use for
1823 // layout.
1824 const ASTRecordLayout &LayoutClassLayout =
1825 Context.getASTRecordLayout(LayoutClass);
1826
1827 CharUnits PrimaryBaseOffsetInLayoutClass =
1828 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1829
1830 // We know that the base is not a primary base in the layout class if
1831 // the base offsets are different.
1832 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1833 IsPrimaryVirtualBase = false;
1834 }
1835
1836 if (IsPrimaryVirtualBase)
1837 PrimaryVirtualBases.insert(PrimaryBase);
1838 }
1839 }
1840
1841 // Traverse bases, looking for more primary virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001842 for (const auto &I : RD->bases()) {
1843 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001844
1845 CharUnits BaseOffsetInLayoutClass;
1846
Aaron Ballman574705e2014-03-13 15:41:46 +00001847 if (I.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001848 if (!VBases.insert(BaseDecl))
1849 continue;
1850
1851 const ASTRecordLayout &LayoutClassLayout =
1852 Context.getASTRecordLayout(LayoutClass);
1853
1854 BaseOffsetInLayoutClass =
1855 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1856 } else {
1857 BaseOffsetInLayoutClass =
1858 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1859 }
1860
1861 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1862 }
1863}
1864
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001865void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1866 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001867 // Itanium C++ ABI 2.5.2:
1868 // Then come the virtual base virtual tables, also in inheritance graph
1869 // order, and again excluding primary bases (which share virtual tables with
1870 // the classes for which they are primary).
Aaron Ballman574705e2014-03-13 15:41:46 +00001871 for (const auto &I : RD->bases()) {
1872 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001873
1874 // Check if this base needs a vtable. (If it's virtual, not a primary base
1875 // of some other class, and we haven't visited it before).
Aaron Ballman574705e2014-03-13 15:41:46 +00001876 if (I.isVirtual() && BaseDecl->isDynamicClass() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001877 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1878 const ASTRecordLayout &MostDerivedClassLayout =
1879 Context.getASTRecordLayout(MostDerivedClass);
1880 CharUnits BaseOffset =
1881 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1882
1883 const ASTRecordLayout &LayoutClassLayout =
1884 Context.getASTRecordLayout(LayoutClass);
1885 CharUnits BaseOffsetInLayoutClass =
1886 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1887
1888 LayoutPrimaryAndSecondaryVTables(
1889 BaseSubobject(BaseDecl, BaseOffset),
1890 /*BaseIsMorallyVirtual=*/true,
1891 /*BaseIsVirtualInLayoutClass=*/true,
1892 BaseOffsetInLayoutClass);
1893 }
1894
1895 // We only need to check the base for virtual base vtables if it actually
1896 // has virtual bases.
1897 if (BaseDecl->getNumVBases())
1898 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1899 }
1900}
1901
1902/// dumpLayout - Dump the vtable layout.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001903void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00001904 // FIXME: write more tests that actually use the dumpLayout output to prevent
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001905 // ItaniumVTableBuilder regressions.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001906
1907 if (isBuildingConstructorVTable()) {
1908 Out << "Construction vtable for ('";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001909 MostDerivedClass->printQualifiedName(Out);
1910 Out << "', ";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001911 Out << MostDerivedClassOffset.getQuantity() << ") in '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001912 LayoutClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001913 } else {
1914 Out << "Vtable for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001915 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001916 }
1917 Out << "' (" << Components.size() << " entries).\n";
1918
1919 // Iterate through the address points and insert them into a new map where
1920 // they are keyed by the index and not the base object.
1921 // Since an address point can be shared by multiple subobjects, we use an
1922 // STL multimap.
1923 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1924 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1925 E = AddressPoints.end(); I != E; ++I) {
1926 const BaseSubobject& Base = I->first;
1927 uint64_t Index = I->second;
1928
1929 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1930 }
1931
1932 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1933 uint64_t Index = I;
1934
1935 Out << llvm::format("%4d | ", I);
1936
1937 const VTableComponent &Component = Components[I];
1938
1939 // Dump the component.
1940 switch (Component.getKind()) {
1941
1942 case VTableComponent::CK_VCallOffset:
1943 Out << "vcall_offset ("
1944 << Component.getVCallOffset().getQuantity()
1945 << ")";
1946 break;
1947
1948 case VTableComponent::CK_VBaseOffset:
1949 Out << "vbase_offset ("
1950 << Component.getVBaseOffset().getQuantity()
1951 << ")";
1952 break;
1953
1954 case VTableComponent::CK_OffsetToTop:
1955 Out << "offset_to_top ("
1956 << Component.getOffsetToTop().getQuantity()
1957 << ")";
1958 break;
1959
1960 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001961 Component.getRTTIDecl()->printQualifiedName(Out);
1962 Out << " RTTI";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001963 break;
1964
1965 case VTableComponent::CK_FunctionPointer: {
1966 const CXXMethodDecl *MD = Component.getFunctionDecl();
1967
1968 std::string Str =
1969 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1970 MD);
1971 Out << Str;
1972 if (MD->isPure())
1973 Out << " [pure]";
1974
David Blaikie596d2ca2012-10-16 20:25:33 +00001975 if (MD->isDeleted())
1976 Out << " [deleted]";
1977
Peter Collingbournecfd23562011-09-26 01:57:12 +00001978 ThunkInfo Thunk = VTableThunks.lookup(I);
1979 if (!Thunk.isEmpty()) {
1980 // If this function pointer has a return adjustment, dump it.
1981 if (!Thunk.Return.isEmpty()) {
1982 Out << "\n [return adjustment: ";
1983 Out << Thunk.Return.NonVirtual << " non-virtual";
1984
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001985 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1986 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001987 Out << " vbase offset offset";
1988 }
1989
1990 Out << ']';
1991 }
1992
1993 // If this function pointer has a 'this' pointer adjustment, dump it.
1994 if (!Thunk.This.isEmpty()) {
1995 Out << "\n [this adjustment: ";
1996 Out << Thunk.This.NonVirtual << " non-virtual";
1997
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001998 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
1999 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002000 Out << " vcall offset offset";
2001 }
2002
2003 Out << ']';
2004 }
2005 }
2006
2007 break;
2008 }
2009
2010 case VTableComponent::CK_CompleteDtorPointer:
2011 case VTableComponent::CK_DeletingDtorPointer: {
2012 bool IsComplete =
2013 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2014
2015 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2016
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002017 DD->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002018 if (IsComplete)
2019 Out << "() [complete]";
2020 else
2021 Out << "() [deleting]";
2022
2023 if (DD->isPure())
2024 Out << " [pure]";
2025
2026 ThunkInfo Thunk = VTableThunks.lookup(I);
2027 if (!Thunk.isEmpty()) {
2028 // If this destructor has a 'this' pointer adjustment, dump it.
2029 if (!Thunk.This.isEmpty()) {
2030 Out << "\n [this adjustment: ";
2031 Out << Thunk.This.NonVirtual << " non-virtual";
2032
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002033 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2034 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002035 Out << " vcall offset offset";
2036 }
2037
2038 Out << ']';
2039 }
2040 }
2041
2042 break;
2043 }
2044
2045 case VTableComponent::CK_UnusedFunctionPointer: {
2046 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2047
2048 std::string Str =
2049 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2050 MD);
2051 Out << "[unused] " << Str;
2052 if (MD->isPure())
2053 Out << " [pure]";
2054 }
2055
2056 }
2057
2058 Out << '\n';
2059
2060 // Dump the next address point.
2061 uint64_t NextIndex = Index + 1;
2062 if (AddressPointsByIndex.count(NextIndex)) {
2063 if (AddressPointsByIndex.count(NextIndex) == 1) {
2064 const BaseSubobject &Base =
2065 AddressPointsByIndex.find(NextIndex)->second;
2066
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002067 Out << " -- (";
2068 Base.getBase()->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002069 Out << ", " << Base.getBaseOffset().getQuantity();
2070 Out << ") vtable address --\n";
2071 } else {
2072 CharUnits BaseOffset =
2073 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2074
2075 // We store the class names in a set to get a stable order.
2076 std::set<std::string> ClassNames;
2077 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2078 AddressPointsByIndex.lower_bound(NextIndex), E =
2079 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2080 assert(I->second.getBaseOffset() == BaseOffset &&
2081 "Invalid base offset!");
2082 const CXXRecordDecl *RD = I->second.getBase();
2083 ClassNames.insert(RD->getQualifiedNameAsString());
2084 }
2085
2086 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2087 E = ClassNames.end(); I != E; ++I) {
2088 Out << " -- (" << *I;
2089 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2090 }
2091 }
2092 }
2093 }
2094
2095 Out << '\n';
2096
2097 if (isBuildingConstructorVTable())
2098 return;
2099
2100 if (MostDerivedClass->getNumVBases()) {
2101 // We store the virtual base class names and their offsets in a map to get
2102 // a stable order.
2103
2104 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2105 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2106 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2107 std::string ClassName = I->first->getQualifiedNameAsString();
2108 CharUnits OffsetOffset = I->second;
2109 ClassNamesAndOffsets.insert(
2110 std::make_pair(ClassName, OffsetOffset));
2111 }
2112
2113 Out << "Virtual base offset offsets for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002114 MostDerivedClass->printQualifiedName(Out);
2115 Out << "' (";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002116 Out << ClassNamesAndOffsets.size();
2117 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2118
2119 for (std::map<std::string, CharUnits>::const_iterator I =
2120 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2121 I != E; ++I)
2122 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2123
2124 Out << "\n";
2125 }
2126
2127 if (!Thunks.empty()) {
2128 // We store the method names in a map to get a stable order.
2129 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2130
2131 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2132 I != E; ++I) {
2133 const CXXMethodDecl *MD = I->first;
2134 std::string MethodName =
2135 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2136 MD);
2137
2138 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2139 }
2140
2141 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2142 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2143 I != E; ++I) {
2144 const std::string &MethodName = I->first;
2145 const CXXMethodDecl *MD = I->second;
2146
2147 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002148 std::sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002149 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
2150 assert(LHS.Method == 0 && RHS.Method == 0);
Benjamin Kramera741b8c2014-03-03 20:26:46 +00002151 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002152 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002153
2154 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2155 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2156
2157 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2158 const ThunkInfo &Thunk = ThunksVector[I];
2159
2160 Out << llvm::format("%4d | ", I);
2161
2162 // If this function pointer has a return pointer adjustment, dump it.
2163 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00002164 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002165 Out << " non-virtual";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002166 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2167 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002168 Out << " vbase offset offset";
2169 }
2170
2171 if (!Thunk.This.isEmpty())
2172 Out << "\n ";
2173 }
2174
2175 // If this function pointer has a 'this' pointer adjustment, dump it.
2176 if (!Thunk.This.isEmpty()) {
2177 Out << "this adjustment: ";
2178 Out << Thunk.This.NonVirtual << " non-virtual";
2179
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002180 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2181 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002182 Out << " vcall offset offset";
2183 }
2184 }
2185
2186 Out << '\n';
2187 }
2188
2189 Out << '\n';
2190 }
2191 }
2192
2193 // Compute the vtable indices for all the member functions.
2194 // Store them in a map keyed by the index so we'll get a sorted table.
2195 std::map<uint64_t, std::string> IndicesMap;
2196
2197 for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
2198 e = MostDerivedClass->method_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002199 const CXXMethodDecl *MD = *i;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002200
2201 // We only want virtual member functions.
2202 if (!MD->isVirtual())
2203 continue;
2204
2205 std::string MethodName =
2206 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2207 MD);
2208
2209 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002210 GlobalDecl GD(DD, Dtor_Complete);
2211 assert(MethodVTableIndices.count(GD));
2212 uint64_t VTableIndex = MethodVTableIndices[GD];
2213 IndicesMap[VTableIndex] = MethodName + " [complete]";
2214 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002215 } else {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002216 assert(MethodVTableIndices.count(MD));
2217 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002218 }
2219 }
2220
2221 // Print the vtable indices for all the member functions.
2222 if (!IndicesMap.empty()) {
2223 Out << "VTable indices for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002224 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002225 Out << "' (" << IndicesMap.size() << " entries).\n";
2226
2227 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2228 E = IndicesMap.end(); I != E; ++I) {
2229 uint64_t VTableIndex = I->first;
2230 const std::string &MethodName = I->second;
2231
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002232 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer5291e682012-03-10 02:06:27 +00002233 << '\n';
Peter Collingbournecfd23562011-09-26 01:57:12 +00002234 }
2235 }
2236
2237 Out << '\n';
2238}
Peter Collingbournecfd23562011-09-26 01:57:12 +00002239}
2240
2241VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2242 const VTableComponent *VTableComponents,
2243 uint64_t NumVTableThunks,
2244 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002245 const AddressPointsMapTy &AddressPoints,
2246 bool IsMicrosoftABI)
Peter Collingbournecfd23562011-09-26 01:57:12 +00002247 : NumVTableComponents(NumVTableComponents),
2248 VTableComponents(new VTableComponent[NumVTableComponents]),
2249 NumVTableThunks(NumVTableThunks),
2250 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002251 AddressPoints(AddressPoints),
2252 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002253 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramere2980632012-04-14 14:13:43 +00002254 this->VTableComponents.get());
2255 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2256 this->VTableThunks.get());
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002257 std::sort(this->VTableThunks.get(),
2258 this->VTableThunks.get() + NumVTableThunks,
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002259 [](const VTableLayout::VTableThunkTy &LHS,
2260 const VTableLayout::VTableThunkTy &RHS) {
2261 assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2262 "Different thunks should have unique indices!");
2263 return LHS.first < RHS.first;
2264 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002265}
2266
Benjamin Kramere2980632012-04-14 14:13:43 +00002267VTableLayout::~VTableLayout() { }
Peter Collingbournecfd23562011-09-26 01:57:12 +00002268
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002269ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
Reid Klecknerb60a3d52013-12-20 23:58:52 +00002270 : VTableContextBase(/*MS=*/false) {}
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002271
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002272ItaniumVTableContext::~ItaniumVTableContext() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002273 llvm::DeleteContainerSeconds(VTableLayouts);
2274}
2275
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002276uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002277 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2278 if (I != MethodVTableIndices.end())
2279 return I->second;
2280
2281 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2282
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002283 computeVTableRelatedInformation(RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002284
2285 I = MethodVTableIndices.find(GD);
2286 assert(I != MethodVTableIndices.end() && "Did not find index!");
2287 return I->second;
2288}
2289
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002290CharUnits
2291ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2292 const CXXRecordDecl *VBase) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002293 ClassPairTy ClassPair(RD, VBase);
2294
2295 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2296 VirtualBaseClassOffsetOffsets.find(ClassPair);
2297 if (I != VirtualBaseClassOffsetOffsets.end())
2298 return I->second;
2299
2300 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2301 BaseSubobject(RD, CharUnits::Zero()),
2302 /*BaseIsVirtual=*/false,
2303 /*OffsetInLayoutClass=*/CharUnits::Zero());
2304
2305 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2306 Builder.getVBaseOffsetOffsets().begin(),
2307 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2308 // Insert all types.
2309 ClassPairTy ClassPair(RD, I->first);
2310
2311 VirtualBaseClassOffsetOffsets.insert(
2312 std::make_pair(ClassPair, I->second));
2313 }
2314
2315 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2316 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2317
2318 return I->second;
2319}
2320
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002321static VTableLayout *CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002322 SmallVector<VTableLayout::VTableThunkTy, 1>
2323 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002324
2325 return new VTableLayout(Builder.getNumVTableComponents(),
2326 Builder.vtable_component_begin(),
2327 VTableThunks.size(),
2328 VTableThunks.data(),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002329 Builder.getAddressPoints(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002330 /*IsMicrosoftABI=*/false);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002331}
2332
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002333void
2334ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002335 const VTableLayout *&Entry = VTableLayouts[RD];
2336
2337 // Check if we've computed this information before.
2338 if (Entry)
2339 return;
2340
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002341 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2342 /*MostDerivedClassIsVirtual=*/0, RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002343 Entry = CreateVTableLayout(Builder);
2344
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002345 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2346 Builder.vtable_indices_end());
2347
Peter Collingbournecfd23562011-09-26 01:57:12 +00002348 // Add the known thunks.
2349 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2350
2351 // If we don't have the vbase information for this class, insert it.
2352 // getVirtualBaseOffsetOffset will compute it separately without computing
2353 // the rest of the vtable related information.
2354 if (!RD->getNumVBases())
2355 return;
2356
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00002357 const CXXRecordDecl *VBase =
2358 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002359
2360 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2361 return;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002362
2363 for (ItaniumVTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator
2364 I = Builder.getVBaseOffsetOffsets().begin(),
2365 E = Builder.getVBaseOffsetOffsets().end();
2366 I != E; ++I) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002367 // Insert all types.
2368 ClassPairTy ClassPair(RD, I->first);
2369
2370 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2371 }
2372}
2373
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002374VTableLayout *ItaniumVTableContext::createConstructionVTableLayout(
2375 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2376 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2377 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2378 MostDerivedClassIsVirtual, LayoutClass);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002379 return CreateVTableLayout(Builder);
2380}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002381
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002382namespace {
2383
2384// Vtables in the Microsoft ABI are different from the Itanium ABI.
2385//
2386// The main differences are:
2387// 1. Separate vftable and vbtable.
2388//
2389// 2. Each subobject with a vfptr gets its own vftable rather than an address
2390// point in a single vtable shared between all the subobjects.
2391// Each vftable is represented by a separate section and virtual calls
2392// must be done using the vftable which has a slot for the function to be
2393// called.
2394//
2395// 3. Virtual method definitions expect their 'this' parameter to point to the
2396// first vfptr whose table provides a compatible overridden method. In many
2397// cases, this permits the original vf-table entry to directly call
2398// the method instead of passing through a thunk.
2399//
2400// A compatible overridden method is one which does not have a non-trivial
2401// covariant-return adjustment.
2402//
2403// The first vfptr is the one with the lowest offset in the complete-object
2404// layout of the defining class, and the method definition will subtract
2405// that constant offset from the parameter value to get the real 'this'
2406// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2407// function defined in a virtual base is overridden in a more derived
2408// virtual base and these bases have a reverse order in the complete
2409// object), the vf-table may require a this-adjustment thunk.
2410//
2411// 4. vftables do not contain new entries for overrides that merely require
2412// this-adjustment. Together with #3, this keeps vf-tables smaller and
2413// eliminates the need for this-adjustment thunks in many cases, at the cost
2414// of often requiring redundant work to adjust the "this" pointer.
2415//
2416// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2417// Vtordisps are emitted into the class layout if a class has
2418// a) a user-defined ctor/dtor
2419// and
2420// b) a method overriding a method in a virtual base.
2421
2422class VFTableBuilder {
2423public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002424 typedef MicrosoftVTableContext::MethodVFTableLocation MethodVFTableLocation;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002425
2426 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2427 MethodVFTableLocationsTy;
2428
2429private:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002430 /// VTables - Global vtable information.
2431 MicrosoftVTableContext &VTables;
2432
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002433 /// Context - The ASTContext which we will use for layout information.
2434 ASTContext &Context;
2435
2436 /// MostDerivedClass - The most derived class for which we're building this
2437 /// vtable.
2438 const CXXRecordDecl *MostDerivedClass;
2439
2440 const ASTRecordLayout &MostDerivedClassLayout;
2441
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002442 const VPtrInfo &WhichVFPtr;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002443
2444 /// FinalOverriders - The final overriders of the most derived class.
2445 const FinalOverriders Overriders;
2446
2447 /// Components - The components of the vftable being built.
2448 SmallVector<VTableComponent, 64> Components;
2449
2450 MethodVFTableLocationsTy MethodVFTableLocations;
2451
2452 /// MethodInfo - Contains information about a method in a vtable.
2453 /// (Used for computing 'this' pointer adjustment thunks.
2454 struct MethodInfo {
2455 /// VBTableIndex - The nonzero index in the vbtable that
2456 /// this method's base has, or zero.
2457 const uint64_t VBTableIndex;
2458
2459 /// VFTableIndex - The index in the vftable that this method has.
2460 const uint64_t VFTableIndex;
2461
2462 /// Shadowed - Indicates if this vftable slot is shadowed by
2463 /// a slot for a covariant-return override. If so, it shouldn't be printed
2464 /// or used for vcalls in the most derived class.
2465 bool Shadowed;
2466
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002467 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex)
2468 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002469 Shadowed(false) {}
2470
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002471 MethodInfo() : VBTableIndex(0), VFTableIndex(0), Shadowed(false) {}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002472 };
2473
2474 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2475
2476 /// MethodInfoMap - The information for all methods in the vftable we're
2477 /// currently building.
2478 MethodInfoMapTy MethodInfoMap;
2479
2480 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2481
2482 /// VTableThunks - The thunks by vftable index in the vftable currently being
2483 /// built.
2484 VTableThunksMapTy VTableThunks;
2485
2486 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2487 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2488
2489 /// Thunks - A map that contains all the thunks needed for all methods in the
2490 /// most derived class for which the vftable is currently being built.
2491 ThunksMapTy Thunks;
2492
2493 /// AddThunk - Add a thunk for the given method.
2494 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2495 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2496
2497 // Check if we have this thunk already.
2498 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2499 ThunksVector.end())
2500 return;
2501
2502 ThunksVector.push_back(Thunk);
2503 }
2504
2505 /// ComputeThisOffset - Returns the 'this' argument offset for the given
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002506 /// method, relative to the beginning of the MostDerivedClass.
2507 CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002508
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002509 void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2510 CharUnits ThisOffset, ThisAdjustment &TA);
2511
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002512 /// AddMethod - Add a single virtual member function to the vftable
2513 /// components vector.
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002514 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002515 if (!TI.isEmpty()) {
2516 VTableThunks[Components.size()] = TI;
2517 AddThunk(MD, TI);
2518 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002519 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002520 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002521 "Destructor can't have return adjustment!");
2522 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2523 } else {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002524 Components.push_back(VTableComponent::MakeFunction(MD));
2525 }
2526 }
2527
Reid Kleckner558cab22013-12-27 19:45:53 +00002528 bool NeedsReturnAdjustingThunk(const CXXMethodDecl *MD);
Reid Kleckner604c8b42013-12-27 19:43:59 +00002529
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002530 /// AddMethods - Add the methods of this base subobject and the relevant
2531 /// subbases to the vftable we're currently laying out.
2532 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2533 const CXXRecordDecl *LastVBase,
2534 BasesSetVectorTy &VisitedBases);
2535
2536 void LayoutVFTable() {
2537 // FIXME: add support for RTTI when we have proper LLVM support for symbols
2538 // pointing to the middle of a section.
2539
2540 BasesSetVectorTy VisitedBases;
2541 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, 0,
2542 VisitedBases);
2543
2544 assert(MethodVFTableLocations.empty());
2545 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2546 E = MethodInfoMap.end(); I != E; ++I) {
2547 const CXXMethodDecl *MD = I->first;
2548 const MethodInfo &MI = I->second;
2549 // Skip the methods that the MostDerivedClass didn't override
2550 // and the entries shadowed by return adjusting thunks.
2551 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2552 continue;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002553 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2554 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002555 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2556 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2557 } else {
2558 MethodVFTableLocations[MD] = Loc;
2559 }
2560 }
2561 }
2562
2563 void ErrorUnsupported(StringRef Feature, SourceLocation Location) {
2564 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2565 unsigned DiagID = Diags.getCustomDiagID(
2566 DiagnosticsEngine::Error, "v-table layout for %0 is not supported yet");
2567 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2568 }
2569
2570public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002571 VFTableBuilder(MicrosoftVTableContext &VTables,
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002572 const CXXRecordDecl *MostDerivedClass, const VPtrInfo *Which)
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002573 : VTables(VTables),
2574 Context(MostDerivedClass->getASTContext()),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002575 MostDerivedClass(MostDerivedClass),
2576 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002577 WhichVFPtr(*Which),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002578 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2579 LayoutVFTable();
2580
2581 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00002582 dumpLayout(llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002583 }
2584
2585 uint64_t getNumThunks() const { return Thunks.size(); }
2586
2587 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2588
2589 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2590
2591 MethodVFTableLocationsTy::const_iterator vtable_indices_begin() const {
2592 return MethodVFTableLocations.begin();
2593 }
2594
2595 MethodVFTableLocationsTy::const_iterator vtable_indices_end() const {
2596 return MethodVFTableLocations.end();
2597 }
2598
2599 uint64_t getNumVTableComponents() const { return Components.size(); }
2600
2601 const VTableComponent *vtable_component_begin() const {
2602 return Components.begin();
2603 }
2604
2605 const VTableComponent *vtable_component_end() const {
2606 return Components.end();
2607 }
2608
2609 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2610 return VTableThunks.begin();
2611 }
2612
2613 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2614 return VTableThunks.end();
2615 }
2616
2617 void dumpLayout(raw_ostream &);
2618};
2619
Reid Klecknerb40a27d2014-01-03 00:14:35 +00002620} // end namespace
2621
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002622/// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2623/// that define the given method.
2624struct InitialOverriddenDefinitionCollector {
2625 BasesSetVectorTy Bases;
2626 OverriddenMethodsSetTy VisitedOverriddenMethods;
2627
2628 bool visit(const CXXMethodDecl *OverriddenMD) {
2629 if (OverriddenMD->size_overridden_methods() == 0)
2630 Bases.insert(OverriddenMD->getParent());
2631 // Don't recurse on this method if we've already collected it.
2632 return VisitedOverriddenMethods.insert(OverriddenMD);
2633 }
2634};
2635
2636static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2637 CXXBasePath &Path, void *BasesSet) {
2638 BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2639 return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2640}
2641
2642CharUnits
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002643VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002644 InitialOverriddenDefinitionCollector Collector;
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002645 visitAllOverriddenMethods(Overrider.Method, Collector);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002646
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002647 // If there are no overrides then 'this' is located
2648 // in the base that defines the method.
2649 if (Collector.Bases.size() == 0)
2650 return Overrider.Offset;
2651
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002652 CXXBasePaths Paths;
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002653 Overrider.Method->getParent()->lookupInBases(BaseInSet, &Collector.Bases,
2654 Paths);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002655
2656 // This will hold the smallest this offset among overridees of MD.
2657 // This implies that an offset of a non-virtual base will dominate an offset
2658 // of a virtual base to potentially reduce the number of thunks required
2659 // in the derived classes that inherit this method.
2660 CharUnits Ret;
2661 bool First = true;
2662
2663 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2664 I != E; ++I) {
2665 const CXXBasePath &Path = (*I);
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002666 CharUnits ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002667 CharUnits LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002668
2669 // For each path from the overrider to the parents of the overridden methods,
2670 // traverse the path, calculating the this offset in the most derived class.
2671 for (int J = 0, F = Path.size(); J != F; ++J) {
2672 const CXXBasePathElement &Element = Path[J];
2673 QualType CurTy = Element.Base->getType();
2674 const CXXRecordDecl *PrevRD = Element.Class,
2675 *CurRD = CurTy->getAsCXXRecordDecl();
2676 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2677
2678 if (Element.Base->isVirtual()) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002679 LastVBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(CurRD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002680 if (Overrider.Method->getParent() == PrevRD) {
2681 // This one's interesting. If the final overrider is in a vbase B of the
2682 // most derived class and it overrides a method of the B's own vbase A,
2683 // it uses A* as "this". In its prologue, it can cast A* to B* with
2684 // a static offset. This offset is used regardless of the actual
2685 // offset of A from B in the most derived class, requiring an
2686 // this-adjusting thunk in the vftable if A and B are laid out
2687 // differently in the most derived class.
2688 ThisOffset += Layout.getVBaseClassOffset(CurRD);
2689 } else {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002690 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002691 }
2692 } else {
2693 ThisOffset += Layout.getBaseClassOffset(CurRD);
2694 }
2695 }
2696
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002697 if (isa<CXXDestructorDecl>(Overrider.Method)) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002698 if (LastVBaseOffset.isZero()) {
2699 // If a "Base" class has at least one non-virtual base with a virtual
2700 // destructor, the "Base" virtual destructor will take the address
2701 // of the "Base" subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002702 ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002703 } else {
2704 // A virtual destructor of a virtual base takes the address of the
2705 // virtual base subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002706 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002707 }
2708 }
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +00002709
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002710 if (Ret > ThisOffset || First) {
2711 First = false;
2712 Ret = ThisOffset;
2713 }
2714 }
2715
2716 assert(!First && "Method not found in the given subobject?");
2717 return Ret;
2718}
2719
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002720void VFTableBuilder::CalculateVtordispAdjustment(
2721 FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2722 ThisAdjustment &TA) {
2723 const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2724 MostDerivedClassLayout.getVBaseOffsetsMap();
2725 const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002726 VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002727 assert(VBaseMapEntry != VBaseMap.end());
2728
2729 // Check if we need a vtordisp adjustment at all.
2730 if (!VBaseMapEntry->second.hasVtorDisp())
2731 return;
2732
2733 CharUnits VFPtrVBaseOffset = VBaseMapEntry->second.VBaseOffset;
2734 // The implicit vtordisp field is located right before the vbase.
2735 TA.Virtual.Microsoft.VtordispOffset =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002736 (VFPtrVBaseOffset - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002737
2738 // If the final overrider is defined in either:
2739 // - the most derived class or its non-virtual base or
2740 // - the same vbase as the initial declaration,
2741 // a simple vtordisp thunk will suffice.
2742 const CXXRecordDecl *OverriderRD = Overrider.Method->getParent();
2743 if (OverriderRD == MostDerivedClass)
2744 return;
2745
2746 const CXXRecordDecl *OverriderVBase =
2747 ComputeBaseOffset(Context, OverriderRD, MostDerivedClass).VirtualBase;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002748 if (!OverriderVBase || OverriderVBase == WhichVFPtr.getVBaseWithVPtr())
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002749 return;
2750
2751 // Otherwise, we need to do use the dynamic offset of the final overrider
2752 // in order to get "this" adjustment right.
2753 TA.Virtual.Microsoft.VBPtrOffset =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002754 (VFPtrVBaseOffset + WhichVFPtr.NonVirtualOffset -
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002755 MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2756 TA.Virtual.Microsoft.VBOffsetOffset =
2757 Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
2758 VTables.getVBTableIndex(MostDerivedClass, OverriderVBase);
2759
2760 TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2761}
2762
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002763static void GroupNewVirtualOverloads(
2764 const CXXRecordDecl *RD,
2765 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2766 // Put the virtual methods into VirtualMethods in the proper order:
2767 // 1) Group overloads by declaration name. New groups are added to the
2768 // vftable in the order of their first declarations in this class
Reid Kleckner6701de22014-02-19 22:06:10 +00002769 // (including overrides and non-virtual methods).
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002770 // 2) In each group, new overloads appear in the reverse order of declaration.
2771 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2772 SmallVector<MethodGroup, 10> Groups;
2773 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2774 VisitedGroupIndicesTy VisitedGroupIndices;
2775 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2776 E = RD->method_end(); I != E; ++I) {
2777 const CXXMethodDecl *MD = *I;
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002778
2779 VisitedGroupIndicesTy::iterator J;
2780 bool Inserted;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002781 std::tie(J, Inserted) = VisitedGroupIndices.insert(
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002782 std::make_pair(MD->getDeclName(), Groups.size()));
2783 if (Inserted)
Reid Kleckner6701de22014-02-19 22:06:10 +00002784 Groups.push_back(MethodGroup());
2785 if (I->isVirtual())
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002786 Groups[J->second].push_back(MD);
2787 }
2788
2789 for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2790 VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2791}
2792
Reid Kleckner604c8b42013-12-27 19:43:59 +00002793/// We need a return adjusting thunk for this method if its return type is
2794/// not trivially convertible to the return type of any of its overridden
2795/// methods.
2796bool VFTableBuilder::NeedsReturnAdjustingThunk(const CXXMethodDecl *MD) {
2797 OverriddenMethodsSetTy OverriddenMethods;
2798 ComputeAllOverriddenMethods(MD, OverriddenMethods);
2799 for (OverriddenMethodsSetTy::iterator I = OverriddenMethods.begin(),
2800 E = OverriddenMethods.end();
2801 I != E; ++I) {
2802 const CXXMethodDecl *OverriddenMD = *I;
2803 BaseOffset Adjustment =
2804 ComputeReturnAdjustmentBaseOffset(Context, MD, OverriddenMD);
2805 if (!Adjustment.isEmpty())
2806 return true;
2807 }
2808 return false;
2809}
2810
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002811void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2812 const CXXRecordDecl *LastVBase,
2813 BasesSetVectorTy &VisitedBases) {
2814 const CXXRecordDecl *RD = Base.getBase();
2815 if (!RD->isPolymorphic())
2816 return;
2817
2818 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2819
2820 // See if this class expands a vftable of the base we look at, which is either
2821 // the one defined by the vfptr base path or the primary base of the current class.
2822 const CXXRecordDecl *NextBase = 0, *NextLastVBase = LastVBase;
2823 CharUnits NextBaseOffset;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002824 if (BaseDepth < WhichVFPtr.PathToBaseWithVPtr.size()) {
2825 NextBase = WhichVFPtr.PathToBaseWithVPtr[BaseDepth];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002826 if (Layout.getVBaseOffsetsMap().count(NextBase)) {
2827 NextLastVBase = NextBase;
2828 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2829 } else {
2830 NextBaseOffset =
2831 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2832 }
2833 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2834 assert(!Layout.isPrimaryBaseVirtual() &&
2835 "No primary virtual bases in this ABI");
2836 NextBase = PrimaryBase;
2837 NextBaseOffset = Base.getBaseOffset();
2838 }
2839
2840 if (NextBase) {
2841 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2842 NextLastVBase, VisitedBases);
2843 if (!VisitedBases.insert(NextBase))
2844 llvm_unreachable("Found a duplicate primary base!");
2845 }
2846
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002847 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2848 // Put virtual methods in the proper order.
2849 GroupNewVirtualOverloads(RD, VirtualMethods);
2850
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002851 // Now go through all virtual member functions and add them to the current
2852 // vftable. This is done by
2853 // - replacing overridden methods in their existing slots, as long as they
2854 // don't require return adjustment; calculating This adjustment if needed.
2855 // - adding new slots for methods of the current base not present in any
2856 // sub-bases;
2857 // - adding new slots for methods that require Return adjustment.
2858 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002859 for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
2860 const CXXMethodDecl *MD = VirtualMethods[I];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002861
2862 FinalOverriders::OverriderInfo Overrider =
2863 Overriders.getOverrider(MD, Base.getBaseOffset());
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002864 const CXXMethodDecl *OverriderMD = Overrider.Method;
2865 const CXXMethodDecl *OverriddenMD =
2866 FindNearestOverriddenMethod(MD, VisitedBases);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002867
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002868 ThisAdjustment ThisAdjustmentOffset;
2869 bool ReturnAdjustingThunk = false;
2870 CharUnits ThisOffset = ComputeThisOffset(Overrider);
2871 ThisAdjustmentOffset.NonVirtual =
2872 (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
2873 if ((OverriddenMD || OverriderMD != MD) &&
2874 WhichVFPtr.getVBaseWithVPtr())
2875 CalculateVtordispAdjustment(Overrider, ThisOffset, ThisAdjustmentOffset);
2876
2877 if (OverriddenMD) {
2878 // If MD overrides anything in this vftable, we need to update the entries.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002879 MethodInfoMapTy::iterator OverriddenMDIterator =
2880 MethodInfoMap.find(OverriddenMD);
2881
2882 // If the overridden method went to a different vftable, skip it.
2883 if (OverriddenMDIterator == MethodInfoMap.end())
2884 continue;
2885
2886 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2887
Reid Kleckner604c8b42013-12-27 19:43:59 +00002888 if (!NeedsReturnAdjustingThunk(MD)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002889 // No return adjustment needed - just replace the overridden method info
2890 // with the current info.
2891 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
2892 OverriddenMethodInfo.VFTableIndex);
2893 MethodInfoMap.erase(OverriddenMDIterator);
2894
2895 assert(!MethodInfoMap.count(MD) &&
2896 "Should not have method info for this method yet!");
2897 MethodInfoMap.insert(std::make_pair(MD, MI));
2898 continue;
Reid Kleckner31a9f742013-12-27 20:29:16 +00002899 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002900
Reid Kleckner31a9f742013-12-27 20:29:16 +00002901 // In case we need a return adjustment, we'll add a new slot for
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002902 // the overrider. Mark the overriden method as shadowed by the new slot.
Reid Kleckner31a9f742013-12-27 20:29:16 +00002903 OverriddenMethodInfo.Shadowed = true;
Reid Kleckner31a9f742013-12-27 20:29:16 +00002904
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002905 // Force a special name mangling for a return-adjusting thunk
2906 // unless the method is the final overrider without this adjustment.
2907 ReturnAdjustingThunk =
2908 !(MD == OverriderMD && ThisAdjustmentOffset.isEmpty());
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002909 } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002910 MD->size_overridden_methods()) {
2911 // Skip methods that don't belong to the vftable of the current class,
2912 // e.g. each method that wasn't seen in any of the visited sub-bases
2913 // but overrides multiple methods of other sub-bases.
2914 continue;
2915 }
2916
2917 // If we got here, MD is a method not seen in any of the sub-bases or
2918 // it requires return adjustment. Insert the method info for this method.
2919 unsigned VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002920 LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002921 MethodInfo MI(VBIndex, Components.size());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002922
2923 assert(!MethodInfoMap.count(MD) &&
2924 "Should not have method info for this method yet!");
2925 MethodInfoMap.insert(std::make_pair(MD, MI));
2926
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002927 // Check if this overrider needs a return adjustment.
2928 // We don't want to do this for pure virtual member functions.
2929 BaseOffset ReturnAdjustmentOffset;
2930 ReturnAdjustment ReturnAdjustment;
2931 if (!OverriderMD->isPure()) {
2932 ReturnAdjustmentOffset =
2933 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
2934 }
2935 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002936 ReturnAdjustingThunk = true;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002937 ReturnAdjustment.NonVirtual =
2938 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
2939 if (ReturnAdjustmentOffset.VirtualBase) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002940 const ASTRecordLayout &DerivedLayout =
2941 Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
2942 ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
2943 DerivedLayout.getVBPtrOffset().getQuantity();
2944 ReturnAdjustment.Virtual.Microsoft.VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002945 VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
2946 ReturnAdjustmentOffset.VirtualBase);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002947 }
2948 }
2949
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002950 AddMethod(OverriderMD, ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002951 ReturnAdjustingThunk ? MD : 0));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002952 }
2953}
2954
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002955static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
2956 for (VPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002957 E = Path.rend(); I != E; ++I) {
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002958 Out << "'";
2959 (*I)->printQualifiedName(Out);
2960 Out << "' in ";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002961 }
2962}
2963
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002964static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
2965 bool ContinueFirstLine) {
2966 const ReturnAdjustment &R = TI.Return;
2967 bool Multiline = false;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002968 const char *LinePrefix = "\n ";
2969 if (!R.isEmpty() || TI.Method) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002970 if (!ContinueFirstLine)
2971 Out << LinePrefix;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002972 Out << "[return adjustment (to type '"
2973 << TI.Method->getReturnType().getCanonicalType().getAsString()
2974 << "'): ";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002975 if (R.Virtual.Microsoft.VBPtrOffset)
2976 Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
2977 if (R.Virtual.Microsoft.VBIndex)
2978 Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
2979 Out << R.NonVirtual << " non-virtual]";
2980 Multiline = true;
2981 }
2982
2983 const ThisAdjustment &T = TI.This;
2984 if (!T.isEmpty()) {
2985 if (Multiline || !ContinueFirstLine)
2986 Out << LinePrefix;
2987 Out << "[this adjustment: ";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002988 if (!TI.This.Virtual.isEmpty()) {
2989 assert(T.Virtual.Microsoft.VtordispOffset < 0);
2990 Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
2991 if (T.Virtual.Microsoft.VBPtrOffset) {
2992 Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002993 << " to the left,";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002994 assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
2995 Out << LinePrefix << " vboffset at "
2996 << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
2997 }
2998 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002999 Out << T.NonVirtual << " non-virtual]";
3000 }
3001}
3002
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003003void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3004 Out << "VFTable for ";
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003005 PrintBasePath(WhichVFPtr.PathToBaseWithVPtr, Out);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003006 Out << "'";
3007 MostDerivedClass->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003008 Out << "' (" << Components.size()
3009 << (Components.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003010
3011 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3012 Out << llvm::format("%4d | ", I);
3013
3014 const VTableComponent &Component = Components[I];
3015
3016 // Dump the component.
3017 switch (Component.getKind()) {
3018 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003019 Component.getRTTIDecl()->printQualifiedName(Out);
3020 Out << " RTTI";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003021 break;
3022
3023 case VTableComponent::CK_FunctionPointer: {
3024 const CXXMethodDecl *MD = Component.getFunctionDecl();
3025
Reid Kleckner604c8b42013-12-27 19:43:59 +00003026 // FIXME: Figure out how to print the real thunk type, since they can
3027 // differ in the return type.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003028 std::string Str = PredefinedExpr::ComputeName(
3029 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3030 Out << Str;
3031 if (MD->isPure())
3032 Out << " [pure]";
3033
3034 if (MD->isDeleted()) {
3035 ErrorUnsupported("deleted methods", MD->getLocation());
3036 Out << " [deleted]";
3037 }
3038
3039 ThunkInfo Thunk = VTableThunks.lookup(I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003040 if (!Thunk.isEmpty())
3041 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003042
3043 break;
3044 }
3045
3046 case VTableComponent::CK_DeletingDtorPointer: {
3047 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3048
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003049 DD->printQualifiedName(Out);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003050 Out << "() [scalar deleting]";
3051
3052 if (DD->isPure())
3053 Out << " [pure]";
3054
3055 ThunkInfo Thunk = VTableThunks.lookup(I);
3056 if (!Thunk.isEmpty()) {
3057 assert(Thunk.Return.isEmpty() &&
3058 "No return adjustment needed for destructors!");
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003059 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003060 }
3061
3062 break;
3063 }
3064
3065 default:
3066 DiagnosticsEngine &Diags = Context.getDiagnostics();
3067 unsigned DiagID = Diags.getCustomDiagID(
3068 DiagnosticsEngine::Error,
3069 "Unexpected vftable component type %0 for component number %1");
3070 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3071 << I << Component.getKind();
3072 }
3073
3074 Out << '\n';
3075 }
3076
3077 Out << '\n';
3078
3079 if (!Thunks.empty()) {
3080 // We store the method names in a map to get a stable order.
3081 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3082
3083 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3084 I != E; ++I) {
3085 const CXXMethodDecl *MD = I->first;
3086 std::string MethodName = PredefinedExpr::ComputeName(
3087 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3088
3089 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3090 }
3091
3092 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3093 I = MethodNamesAndDecls.begin(),
3094 E = MethodNamesAndDecls.end();
3095 I != E; ++I) {
3096 const std::string &MethodName = I->first;
3097 const CXXMethodDecl *MD = I->second;
3098
3099 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00003100 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003101 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
3102 // Keep different thunks with the same adjustments in the order they
3103 // were put into the vector.
Benjamin Kramera741b8c2014-03-03 20:26:46 +00003104 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003105 });
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003106
3107 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3108 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3109
3110 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3111 const ThunkInfo &Thunk = ThunksVector[I];
3112
3113 Out << llvm::format("%4d | ", I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003114 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003115 Out << '\n';
3116 }
3117
3118 Out << '\n';
3119 }
3120 }
3121}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003122
Reid Kleckner5f080942014-01-03 23:42:00 +00003123static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
3124 const llvm::ArrayRef<const CXXRecordDecl *> &B) {
3125 for (llvm::ArrayRef<const CXXRecordDecl *>::iterator I = B.begin(),
3126 E = B.end();
3127 I != E; ++I) {
3128 if (A.count(*I))
3129 return true;
3130 }
3131 return false;
3132}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003133
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003134static bool rebucketPaths(VPtrInfoVector &Paths);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003135
Reid Kleckner5f080942014-01-03 23:42:00 +00003136/// Produces MSVC-compatible vbtable data. The symbols produced by this
3137/// algorithm match those produced by MSVC 2012 and newer, which is different
3138/// from MSVC 2010.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003139///
3140/// MSVC 2012 appears to minimize the vbtable names using the following
3141/// algorithm. First, walk the class hierarchy in the usual order, depth first,
3142/// left to right, to find all of the subobjects which contain a vbptr field.
3143/// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3144/// record with a vbptr creates an initially empty path.
3145///
3146/// To combine paths from child nodes, the paths are compared to check for
3147/// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3148/// components in the same order. Each group of ambiguous paths is extended by
3149/// appending the class of the base from which it came. If the current class
3150/// node produced an ambiguous path, its path is extended with the current class.
3151/// After extending paths, MSVC again checks for ambiguity, and extends any
3152/// ambiguous path which wasn't already extended. Because each node yields an
3153/// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3154/// to produce an unambiguous set of paths.
3155///
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003156/// TODO: Presumably vftables use the same algorithm.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003157void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3158 const CXXRecordDecl *RD,
3159 VPtrInfoVector &Paths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003160 assert(Paths.empty());
3161 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003162
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003163 // Base case: this subobject has its own vptr.
3164 if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
3165 Paths.push_back(new VPtrInfo(RD));
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003166
Reid Kleckner5f080942014-01-03 23:42:00 +00003167 // Recursive case: get all the vbtables from our bases and remove anything
3168 // that shares a virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003169 llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
Aaron Ballman574705e2014-03-13 15:41:46 +00003170 for (const auto &I : RD->bases()) {
3171 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
3172 if (I.isVirtual() && VBasesSeen.count(Base))
Reid Kleckner5f080942014-01-03 23:42:00 +00003173 continue;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003174
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003175 if (!Base->isDynamicClass())
3176 continue;
Reid Kleckner5f080942014-01-03 23:42:00 +00003177
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003178 const VPtrInfoVector &BasePaths =
3179 ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3180
3181 for (VPtrInfoVector::const_iterator II = BasePaths.begin(),
3182 EE = BasePaths.end();
Reid Kleckner5f080942014-01-03 23:42:00 +00003183 II != EE; ++II) {
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003184 VPtrInfo *BaseInfo = *II;
Reid Kleckner5f080942014-01-03 23:42:00 +00003185
3186 // Don't include the path if it goes through a virtual base that we've
3187 // already included.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003188 if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
Reid Kleckner5f080942014-01-03 23:42:00 +00003189 continue;
3190
3191 // Copy the path and adjust it as necessary.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003192 VPtrInfo *P = new VPtrInfo(*BaseInfo);
Reid Kleckner5f080942014-01-03 23:42:00 +00003193
3194 // We mangle Base into the path if the path would've been ambiguous and it
3195 // wasn't already extended with Base.
3196 if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3197 P->NextBaseToMangle = Base;
3198
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003199 // Keep track of the full path.
3200 // FIXME: Why do we need this?
3201 P->PathToBaseWithVPtr.insert(P->PathToBaseWithVPtr.begin(), Base);
3202
3203 // Keep track of which derived class ultimately uses the vtable, and what
3204 // the full adjustment is from the MDC to this vtable. The adjustment is
Reid Kleckner5f080942014-01-03 23:42:00 +00003205 // captured by an optional vbase and a non-virtual offset.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003206 if (Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
3207 : Layout.getPrimaryBase()))
Reid Kleckner5f080942014-01-03 23:42:00 +00003208 P->ReusingBase = RD;
Aaron Ballman574705e2014-03-13 15:41:46 +00003209 if (I.isVirtual())
Reid Kleckner5f080942014-01-03 23:42:00 +00003210 P->ContainingVBases.push_back(Base);
3211 else if (P->ContainingVBases.empty())
3212 P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3213
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003214 // Update the full offset in the MDC.
3215 P->FullOffsetInMDC = P->NonVirtualOffset;
3216 if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3217 P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3218
Reid Kleckner5f080942014-01-03 23:42:00 +00003219 Paths.push_back(P);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003220 }
3221
Reid Kleckner5f080942014-01-03 23:42:00 +00003222 // After visiting any direct base, we've transitively visited all of its
3223 // morally virtual bases.
3224 for (CXXRecordDecl::base_class_const_iterator II = Base->vbases_begin(),
3225 EE = Base->vbases_end();
3226 II != EE; ++II)
3227 VBasesSeen.insert(II->getType()->getAsCXXRecordDecl());
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003228 }
3229
Reid Kleckner5f080942014-01-03 23:42:00 +00003230 // Sort the paths into buckets, and if any of them are ambiguous, extend all
3231 // paths in ambiguous buckets.
3232 bool Changed = true;
3233 while (Changed)
3234 Changed = rebucketPaths(Paths);
3235}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003236
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003237static bool extendPath(VPtrInfo *P) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003238 if (P->NextBaseToMangle) {
3239 P->MangledPath.push_back(P->NextBaseToMangle);
3240 P->NextBaseToMangle = 0; // Prevent the path from being extended twice.
3241 return true;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003242 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003243 return false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003244}
3245
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003246static bool rebucketPaths(VPtrInfoVector &Paths) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003247 // What we're essentially doing here is bucketing together ambiguous paths.
3248 // Any bucket with more than one path in it gets extended by NextBase, which
3249 // is usually the direct base of the inherited the vbptr. This code uses a
3250 // sorted vector to implement a multiset to form the buckets. Note that the
3251 // ordering is based on pointers, but it doesn't change our output order. The
3252 // current algorithm is designed to match MSVC 2012's names.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003253 VPtrInfoVector PathsSorted(Paths);
Benjamin Kramer15ae7832014-03-07 21:35:40 +00003254 std::sort(PathsSorted.begin(), PathsSorted.end(),
3255 [](const VPtrInfo *LHS, const VPtrInfo *RHS) {
3256 return LHS->MangledPath < RHS->MangledPath;
3257 });
Reid Kleckner5f080942014-01-03 23:42:00 +00003258 bool Changed = false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003259 for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3260 // Scan forward to find the end of the bucket.
3261 size_t BucketStart = I;
3262 do {
3263 ++I;
Reid Kleckner5f080942014-01-03 23:42:00 +00003264 } while (I != E && PathsSorted[BucketStart]->MangledPath ==
3265 PathsSorted[I]->MangledPath);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003266
3267 // If this bucket has multiple paths, extend them all.
3268 if (I - BucketStart > 1) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003269 for (size_t II = BucketStart; II != I; ++II)
Reid Kleckner5f080942014-01-03 23:42:00 +00003270 Changed |= extendPath(PathsSorted[II]);
3271 assert(Changed && "no paths were extended to fix ambiguity");
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003272 }
3273 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003274 return Changed;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003275}
3276
3277MicrosoftVTableContext::~MicrosoftVTableContext() {
Reid Kleckner33311282014-02-28 23:26:22 +00003278 llvm::DeleteContainerSeconds(VFPtrLocations);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003279 llvm::DeleteContainerSeconds(VFTableLayouts);
3280 llvm::DeleteContainerSeconds(VBaseInfo);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003281}
3282
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003283void MicrosoftVTableContext::computeVTableRelatedInformation(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003284 const CXXRecordDecl *RD) {
3285 assert(RD->isDynamicClass());
3286
3287 // Check if we've computed this information before.
3288 if (VFPtrLocations.count(RD))
3289 return;
3290
3291 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3292
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003293 VPtrInfoVector *VFPtrs = new VPtrInfoVector();
3294 computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3295 VFPtrLocations[RD] = VFPtrs;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003296
3297 MethodVFTableLocationsTy NewMethodLocations;
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003298 for (VPtrInfoVector::iterator I = VFPtrs->begin(), E = VFPtrs->end();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003299 I != E; ++I) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003300 VFTableBuilder Builder(*this, RD, *I);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003301
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003302 VFTableIdTy id(RD, (*I)->FullOffsetInMDC);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003303 assert(VFTableLayouts.count(id) == 0);
3304 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3305 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003306 VFTableLayouts[id] = new VTableLayout(
3307 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3308 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
3309 NewMethodLocations.insert(Builder.vtable_indices_begin(),
3310 Builder.vtable_indices_end());
3311 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3312 }
3313
3314 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3315 NewMethodLocations.end());
3316 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00003317 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003318}
3319
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003320void MicrosoftVTableContext::dumpMethodLocations(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003321 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3322 raw_ostream &Out) {
3323 // Compute the vtable indices for all the member functions.
3324 // Store them in a map keyed by the location so we'll get a sorted table.
3325 std::map<MethodVFTableLocation, std::string> IndicesMap;
3326 bool HasNonzeroOffset = false;
3327
3328 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3329 E = NewMethods.end(); I != E; ++I) {
3330 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3331 assert(MD->isVirtual());
3332
3333 std::string MethodName = PredefinedExpr::ComputeName(
3334 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3335
3336 if (isa<CXXDestructorDecl>(MD)) {
3337 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3338 } else {
3339 IndicesMap[I->second] = MethodName;
3340 }
3341
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003342 if (!I->second.VFPtrOffset.isZero() || I->second.VBTableIndex != 0)
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003343 HasNonzeroOffset = true;
3344 }
3345
3346 // Print the vtable indices for all the member functions.
3347 if (!IndicesMap.empty()) {
3348 Out << "VFTable indices for ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003349 Out << "'";
3350 RD->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003351 Out << "' (" << IndicesMap.size()
3352 << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003353
3354 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3355 uint64_t LastVBIndex = 0;
3356 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3357 I = IndicesMap.begin(),
3358 E = IndicesMap.end();
3359 I != E; ++I) {
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003360 CharUnits VFPtrOffset = I->first.VFPtrOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003361 uint64_t VBIndex = I->first.VBTableIndex;
3362 if (HasNonzeroOffset &&
3363 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3364 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3365 Out << " -- accessible via ";
3366 if (VBIndex)
3367 Out << "vbtable index " << VBIndex << ", ";
3368 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3369 LastVFPtrOffset = VFPtrOffset;
3370 LastVBIndex = VBIndex;
3371 }
3372
3373 uint64_t VTableIndex = I->first.Index;
3374 const std::string &MethodName = I->second;
3375 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3376 }
3377 Out << '\n';
3378 }
3379}
3380
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003381const VirtualBaseInfo *MicrosoftVTableContext::computeVBTableRelatedInformation(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003382 const CXXRecordDecl *RD) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003383 VirtualBaseInfo *VBI;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003384
Reid Kleckner5f080942014-01-03 23:42:00 +00003385 {
3386 // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
3387 // as it may be modified and rehashed under us.
3388 VirtualBaseInfo *&Entry = VBaseInfo[RD];
3389 if (Entry)
3390 return Entry;
3391 Entry = VBI = new VirtualBaseInfo();
3392 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003393
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003394 computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003395
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003396 // First, see if the Derived class shared the vbptr with a non-virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003397 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003398 if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003399 // If the Derived class shares the vbptr with a non-virtual base, the shared
3400 // virtual bases come first so that the layout is the same.
3401 const VirtualBaseInfo *BaseInfo =
3402 computeVBTableRelatedInformation(VBPtrBase);
Reid Kleckner5f080942014-01-03 23:42:00 +00003403 VBI->VBTableIndices.insert(BaseInfo->VBTableIndices.begin(),
3404 BaseInfo->VBTableIndices.end());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003405 }
3406
3407 // New vbases are added to the end of the vbtable.
3408 // Skip the self entry and vbases visited in the non-virtual base, if any.
Reid Kleckner5f080942014-01-03 23:42:00 +00003409 unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003410 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003411 E = RD->vbases_end();
3412 I != E; ++I) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003413 const CXXRecordDecl *CurVBase = I->getType()->getAsCXXRecordDecl();
Reid Kleckner5f080942014-01-03 23:42:00 +00003414 if (!VBI->VBTableIndices.count(CurVBase))
3415 VBI->VBTableIndices[CurVBase] = VBTableIndex++;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003416 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003417
Reid Kleckner5f080942014-01-03 23:42:00 +00003418 return VBI;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003419}
3420
3421unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3422 const CXXRecordDecl *VBase) {
3423 const VirtualBaseInfo *VBInfo = computeVBTableRelatedInformation(Derived);
3424 assert(VBInfo->VBTableIndices.count(VBase));
3425 return VBInfo->VBTableIndices.find(VBase)->second;
3426}
3427
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003428const VPtrInfoVector &
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003429MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003430 return computeVBTableRelatedInformation(RD)->VBPtrPaths;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003431}
3432
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003433const VPtrInfoVector &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003434MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003435 computeVTableRelatedInformation(RD);
3436
3437 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003438 return *VFPtrLocations[RD];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003439}
3440
3441const VTableLayout &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003442MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3443 CharUnits VFPtrOffset) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003444 computeVTableRelatedInformation(RD);
3445
3446 VFTableIdTy id(RD, VFPtrOffset);
3447 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3448 return *VFTableLayouts[id];
3449}
3450
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003451const MicrosoftVTableContext::MethodVFTableLocation &
3452MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003453 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3454 "Only use this method for virtual methods or dtors");
3455 if (isa<CXXDestructorDecl>(GD.getDecl()))
3456 assert(GD.getDtorType() == Dtor_Deleting);
3457
3458 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3459 if (I != MethodVFTableLocations.end())
3460 return I->second;
3461
3462 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3463
3464 computeVTableRelatedInformation(RD);
3465
3466 I = MethodVFTableLocations.find(GD);
3467 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3468 return I->second;
3469}