blob: c6b38d31d4f1a7273fc471cc0f4b4e96ffa84bc0 [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.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000341 for (const auto &B : RD->bases()) {
342 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000343
344 CharUnits BaseOffset;
345 CharUnits BaseOffsetInLayoutClass;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000346 if (B.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),
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000366 B.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
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000377 for (const auto &B : RD->bases()) {
378 const CXXRecordDecl *BaseDecl = B.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;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000385 if (B.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000386 if (!VisitedVirtualBases.insert(BaseDecl)) {
387 // We've visited this base before.
388 continue;
389 }
390
391 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
392 } else {
393 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
394 }
395
396 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
397 }
398
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000399 Out << "Final overriders for (";
400 RD->printQualifiedName(Out);
401 Out << ", ";
Peter Collingbournecfd23562011-09-26 01:57:12 +0000402 Out << Base.getBaseOffset().getQuantity() << ")\n";
403
404 // Now dump the overriders for this base subobject.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000405 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000406 if (!MD->isVirtual())
407 continue;
408
409 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
410
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000411 Out << " ";
412 MD->printQualifiedName(Out);
413 Out << " - (";
414 Overrider.Method->printQualifiedName(Out);
Timur Iskhodzhanovbe5a3d82013-06-05 06:40:07 +0000415 Out << ", " << Overrider.Offset.getQuantity() << ')';
Peter Collingbournecfd23562011-09-26 01:57:12 +0000416
417 BaseOffset Offset;
418 if (!Overrider.Method->isPure())
419 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
420
421 if (!Offset.isEmpty()) {
422 Out << " [ret-adj: ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +0000423 if (Offset.VirtualBase) {
424 Offset.VirtualBase->printQualifiedName(Out);
425 Out << " vbase, ";
426 }
Peter Collingbournecfd23562011-09-26 01:57:12 +0000427
428 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
429 }
430
431 Out << "\n";
432 }
433}
434
435/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
436struct VCallOffsetMap {
437
438 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
439
440 /// Offsets - Keeps track of methods and their offsets.
441 // FIXME: This should be a real map and not a vector.
442 SmallVector<MethodAndOffsetPairTy, 16> Offsets;
443
444 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
445 /// can share the same vcall offset.
446 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
447 const CXXMethodDecl *RHS);
448
449public:
450 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
451 /// add was successful, or false if there was already a member function with
452 /// the same signature in the map.
453 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
454
455 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
456 /// vtable address point) for the given virtual member function.
457 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
458
459 // empty - Return whether the offset map is empty or not.
460 bool empty() const { return Offsets.empty(); }
461};
462
463static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
464 const CXXMethodDecl *RHS) {
John McCallb6c4a7e2012-03-21 06:57:19 +0000465 const FunctionProtoType *LT =
466 cast<FunctionProtoType>(LHS->getType().getCanonicalType());
467 const FunctionProtoType *RT =
468 cast<FunctionProtoType>(RHS->getType().getCanonicalType());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000469
470 // Fast-path matches in the canonical types.
471 if (LT == RT) return true;
472
473 // Force the signatures to match. We can't rely on the overrides
474 // list here because there isn't necessarily an inheritance
475 // relationship between the two methods.
John McCallb6c4a7e2012-03-21 06:57:19 +0000476 if (LT->getTypeQuals() != RT->getTypeQuals() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000477 LT->getNumParams() != RT->getNumParams())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000478 return false;
Alp Toker9cacbab2014-01-20 20:26:09 +0000479 for (unsigned I = 0, E = LT->getNumParams(); I != E; ++I)
480 if (LT->getParamType(I) != RT->getParamType(I))
Peter Collingbournecfd23562011-09-26 01:57:12 +0000481 return false;
482 return true;
483}
484
485bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
486 const CXXMethodDecl *RHS) {
487 assert(LHS->isVirtual() && "LHS must be virtual!");
488 assert(RHS->isVirtual() && "LHS must be virtual!");
489
490 // A destructor can share a vcall offset with another destructor.
491 if (isa<CXXDestructorDecl>(LHS))
492 return isa<CXXDestructorDecl>(RHS);
493
494 // FIXME: We need to check more things here.
495
496 // The methods must have the same name.
497 DeclarationName LHSName = LHS->getDeclName();
498 DeclarationName RHSName = RHS->getDeclName();
499 if (LHSName != RHSName)
500 return false;
501
502 // And the same signatures.
503 return HasSameVirtualSignature(LHS, RHS);
504}
505
506bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
507 CharUnits OffsetOffset) {
508 // Check if we can reuse an offset.
509 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
510 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
511 return false;
512 }
513
514 // Add the offset.
515 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
516 return true;
517}
518
519CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
520 // Look for an offset.
521 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
522 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
523 return Offsets[I].second;
524 }
525
526 llvm_unreachable("Should always find a vcall offset offset!");
527}
528
529/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
530class VCallAndVBaseOffsetBuilder {
531public:
532 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
533 VBaseOffsetOffsetsMapTy;
534
535private:
536 /// MostDerivedClass - The most derived class for which we're building vcall
537 /// and vbase offsets.
538 const CXXRecordDecl *MostDerivedClass;
539
540 /// LayoutClass - The class we're using for layout information. Will be
541 /// different than the most derived class if we're building a construction
542 /// vtable.
543 const CXXRecordDecl *LayoutClass;
544
545 /// Context - The ASTContext which we will use for layout information.
546 ASTContext &Context;
547
548 /// Components - vcall and vbase offset components
549 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
550 VTableComponentVectorTy Components;
551
552 /// VisitedVirtualBases - Visited virtual bases.
553 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
554
555 /// VCallOffsets - Keeps track of vcall offsets.
556 VCallOffsetMap VCallOffsets;
557
558
559 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
560 /// relative to the address point.
561 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
562
563 /// FinalOverriders - The final overriders of the most derived class.
564 /// (Can be null when we're not building a vtable of the most derived class).
565 const FinalOverriders *Overriders;
566
567 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
568 /// given base subobject.
569 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
570 CharUnits RealBaseOffset);
571
572 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
573 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
574
575 /// AddVBaseOffsets - Add vbase offsets for the given class.
576 void AddVBaseOffsets(const CXXRecordDecl *Base,
577 CharUnits OffsetInLayoutClass);
578
579 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
580 /// chars, relative to the vtable address point.
581 CharUnits getCurrentOffsetOffset() const;
582
583public:
584 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
585 const CXXRecordDecl *LayoutClass,
586 const FinalOverriders *Overriders,
587 BaseSubobject Base, bool BaseIsVirtual,
588 CharUnits OffsetInLayoutClass)
589 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
590 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
591
592 // Add vcall and vbase offsets.
593 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
594 }
595
596 /// Methods for iterating over the components.
597 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
598 const_iterator components_begin() const { return Components.rbegin(); }
599 const_iterator components_end() const { return Components.rend(); }
600
601 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
602 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
603 return VBaseOffsetOffsets;
604 }
605};
606
607void
608VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
609 bool BaseIsVirtual,
610 CharUnits RealBaseOffset) {
611 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
612
613 // Itanium C++ ABI 2.5.2:
614 // ..in classes sharing a virtual table with a primary base class, the vcall
615 // and vbase offsets added by the derived class all come before the vcall
616 // and vbase offsets required by the base class, so that the latter may be
617 // laid out as required by the base class without regard to additions from
618 // the derived class(es).
619
620 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
621 // emit them for the primary base first).
622 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
623 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
624
625 CharUnits PrimaryBaseOffset;
626
627 // Get the base offset of the primary base.
628 if (PrimaryBaseIsVirtual) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000629 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000630 "Primary vbase should have a zero offset!");
631
632 const ASTRecordLayout &MostDerivedClassLayout =
633 Context.getASTRecordLayout(MostDerivedClass);
634
635 PrimaryBaseOffset =
636 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
637 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000638 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000639 "Primary base should have a zero offset!");
640
641 PrimaryBaseOffset = Base.getBaseOffset();
642 }
643
644 AddVCallAndVBaseOffsets(
645 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
646 PrimaryBaseIsVirtual, RealBaseOffset);
647 }
648
649 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
650
651 // We only want to add vcall offsets for virtual bases.
652 if (BaseIsVirtual)
653 AddVCallOffsets(Base, RealBaseOffset);
654}
655
656CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
657 // OffsetIndex is the index of this vcall or vbase offset, relative to the
658 // vtable address point. (We subtract 3 to account for the information just
659 // above the address point, the RTTI info, the offset to top, and the
660 // vcall offset itself).
661 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
662
663 CharUnits PointerWidth =
664 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
665 CharUnits OffsetOffset = PointerWidth * OffsetIndex;
666 return OffsetOffset;
667}
668
669void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
670 CharUnits VBaseOffset) {
671 const CXXRecordDecl *RD = Base.getBase();
672 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
673
674 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
675
676 // Handle the primary base first.
677 // We only want to add vcall offsets if the base is non-virtual; a virtual
678 // primary base will have its vcall and vbase offsets emitted already.
679 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
680 // Get the base offset of the primary base.
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000681 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +0000682 "Primary base should have a zero offset!");
683
684 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
685 VBaseOffset);
686 }
687
688 // Add the vcall offsets.
Aaron Ballman2b124d12014-03-13 16:36:16 +0000689 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000690 if (!MD->isVirtual())
691 continue;
692
693 CharUnits OffsetOffset = getCurrentOffsetOffset();
694
695 // Don't add a vcall offset if we already have one for this member function
696 // signature.
697 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
698 continue;
699
700 CharUnits Offset = CharUnits::Zero();
701
702 if (Overriders) {
703 // Get the final overrider.
704 FinalOverriders::OverriderInfo Overrider =
705 Overriders->getOverrider(MD, Base.getBaseOffset());
706
707 /// The vcall offset is the offset from the virtual base to the object
708 /// where the function was overridden.
709 Offset = Overrider.Offset - VBaseOffset;
710 }
711
712 Components.push_back(
713 VTableComponent::MakeVCallOffset(Offset));
714 }
715
716 // And iterate over all non-virtual bases (ignoring the primary base).
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000717 for (const auto &B : RD->bases()) {
718 if (B.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +0000719 continue;
720
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000721 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000722 if (BaseDecl == PrimaryBase)
723 continue;
724
725 // Get the base offset of this base.
726 CharUnits BaseOffset = Base.getBaseOffset() +
727 Layout.getBaseClassOffset(BaseDecl);
728
729 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
730 VBaseOffset);
731 }
732}
733
734void
735VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
736 CharUnits OffsetInLayoutClass) {
737 const ASTRecordLayout &LayoutClassLayout =
738 Context.getASTRecordLayout(LayoutClass);
739
740 // Add vbase offsets.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000741 for (const auto &B : RD->bases()) {
742 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +0000743
744 // Check if this is a virtual base that we haven't visited before.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +0000745 if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000746 CharUnits Offset =
747 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
748
749 // Add the vbase offset offset.
750 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
751 "vbase offset offset already exists!");
752
753 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
754 VBaseOffsetOffsets.insert(
755 std::make_pair(BaseDecl, VBaseOffsetOffset));
756
757 Components.push_back(
758 VTableComponent::MakeVBaseOffset(Offset));
759 }
760
761 // Check the base class looking for more vbase offsets.
762 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
763 }
764}
765
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000766/// ItaniumVTableBuilder - Class for building vtable layout information.
767class ItaniumVTableBuilder {
Peter Collingbournecfd23562011-09-26 01:57:12 +0000768public:
769 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
770 /// primary bases.
771 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
772 PrimaryBasesSetVectorTy;
773
774 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
775 VBaseOffsetOffsetsMapTy;
776
777 typedef llvm::DenseMap<BaseSubobject, uint64_t>
778 AddressPointsMapTy;
779
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000780 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
781
Peter Collingbournecfd23562011-09-26 01:57:12 +0000782private:
783 /// VTables - Global vtable information.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000784 ItaniumVTableContext &VTables;
Peter Collingbournecfd23562011-09-26 01:57:12 +0000785
786 /// MostDerivedClass - The most derived class for which we're building this
787 /// vtable.
788 const CXXRecordDecl *MostDerivedClass;
789
790 /// MostDerivedClassOffset - If we're building a construction vtable, this
791 /// holds the offset from the layout class to the most derived class.
792 const CharUnits MostDerivedClassOffset;
793
794 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
795 /// base. (This only makes sense when building a construction vtable).
796 bool MostDerivedClassIsVirtual;
797
798 /// LayoutClass - The class we're using for layout information. Will be
799 /// different than the most derived class if we're building a construction
800 /// vtable.
801 const CXXRecordDecl *LayoutClass;
802
803 /// Context - The ASTContext which we will use for layout information.
804 ASTContext &Context;
805
806 /// FinalOverriders - The final overriders of the most derived class.
807 const FinalOverriders Overriders;
808
809 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
810 /// bases in this vtable.
811 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
812
813 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
814 /// the most derived class.
815 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
816
817 /// Components - The components of the vtable being built.
818 SmallVector<VTableComponent, 64> Components;
819
820 /// AddressPoints - Address points for the vtable being built.
821 AddressPointsMapTy AddressPoints;
822
823 /// MethodInfo - Contains information about a method in a vtable.
824 /// (Used for computing 'this' pointer adjustment thunks.
825 struct MethodInfo {
826 /// BaseOffset - The base offset of this method.
827 const CharUnits BaseOffset;
828
829 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
830 /// method.
831 const CharUnits BaseOffsetInLayoutClass;
832
833 /// VTableIndex - The index in the vtable that this method has.
834 /// (For destructors, this is the index of the complete destructor).
835 const uint64_t VTableIndex;
836
837 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
838 uint64_t VTableIndex)
839 : BaseOffset(BaseOffset),
840 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
841 VTableIndex(VTableIndex) { }
842
843 MethodInfo()
844 : BaseOffset(CharUnits::Zero()),
845 BaseOffsetInLayoutClass(CharUnits::Zero()),
846 VTableIndex(0) { }
847 };
848
849 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
850
851 /// MethodInfoMap - The information for all methods in the vtable we're
852 /// currently building.
853 MethodInfoMapTy MethodInfoMap;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +0000854
855 /// MethodVTableIndices - Contains the index (relative to the vtable address
856 /// point) where the function pointer for a virtual function is stored.
857 MethodVTableIndicesTy MethodVTableIndices;
858
Peter Collingbournecfd23562011-09-26 01:57:12 +0000859 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
860
861 /// VTableThunks - The thunks by vtable index in the vtable currently being
862 /// built.
863 VTableThunksMapTy VTableThunks;
864
865 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
866 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
867
868 /// Thunks - A map that contains all the thunks needed for all methods in the
869 /// most derived class for which the vtable is currently being built.
870 ThunksMapTy Thunks;
871
872 /// AddThunk - Add a thunk for the given method.
873 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
874
875 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
876 /// part of the vtable we're currently building.
877 void ComputeThisAdjustments();
878
879 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
880
881 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
882 /// some other base.
883 VisitedVirtualBasesSetTy PrimaryVirtualBases;
884
885 /// ComputeReturnAdjustment - Compute the return adjustment given a return
886 /// adjustment base offset.
887 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
888
889 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
890 /// the 'this' pointer from the base subobject to the derived subobject.
891 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
892 BaseSubobject Derived) const;
893
894 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
895 /// given virtual member function, its offset in the layout class and its
896 /// final overrider.
897 ThisAdjustment
898 ComputeThisAdjustment(const CXXMethodDecl *MD,
899 CharUnits BaseOffsetInLayoutClass,
900 FinalOverriders::OverriderInfo Overrider);
901
902 /// AddMethod - Add a single virtual member function to the vtable
903 /// components vector.
904 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
905
906 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
907 /// part of the vtable.
908 ///
909 /// Itanium C++ ABI 2.5.2:
910 ///
911 /// struct A { virtual void f(); };
912 /// struct B : virtual public A { int i; };
913 /// struct C : virtual public A { int j; };
914 /// struct D : public B, public C {};
915 ///
916 /// When B and C are declared, A is a primary base in each case, so although
917 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
918 /// adjustment is required and no thunk is generated. However, inside D
919 /// objects, A is no longer a primary base of C, so if we allowed calls to
920 /// C::f() to use the copy of A's vtable in the C subobject, we would need
921 /// to adjust this from C* to B::A*, which would require a third-party
922 /// thunk. Since we require that a call to C::f() first convert to A*,
923 /// C-in-D's copy of A's vtable is never referenced, so this is not
924 /// necessary.
925 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
926 CharUnits BaseOffsetInLayoutClass,
927 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
928 CharUnits FirstBaseOffsetInLayoutClass) const;
929
930
931 /// AddMethods - Add the methods of this base subobject and all its
932 /// primary bases to the vtable components vector.
933 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
934 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
935 CharUnits FirstBaseOffsetInLayoutClass,
936 PrimaryBasesSetVectorTy &PrimaryBases);
937
938 // LayoutVTable - Layout the vtable for the given base class, including its
939 // secondary vtables and any vtables for virtual bases.
940 void LayoutVTable();
941
942 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
943 /// given base subobject, as well as all its secondary vtables.
944 ///
945 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
946 /// or a direct or indirect base of a virtual base.
947 ///
948 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
949 /// in the layout class.
950 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
951 bool BaseIsMorallyVirtual,
952 bool BaseIsVirtualInLayoutClass,
953 CharUnits OffsetInLayoutClass);
954
955 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
956 /// subobject.
957 ///
958 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
959 /// or a direct or indirect base of a virtual base.
960 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
961 CharUnits OffsetInLayoutClass);
962
963 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
964 /// class hierarchy.
965 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
966 CharUnits OffsetInLayoutClass,
967 VisitedVirtualBasesSetTy &VBases);
968
969 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
970 /// given base (excluding any primary bases).
971 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
972 VisitedVirtualBasesSetTy &VBases);
973
974 /// isBuildingConstructionVTable - Return whether this vtable builder is
975 /// building a construction vtable.
976 bool isBuildingConstructorVTable() const {
977 return MostDerivedClass != LayoutClass;
978 }
979
980public:
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000981 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
982 const CXXRecordDecl *MostDerivedClass,
983 CharUnits MostDerivedClassOffset,
984 bool MostDerivedClassIsVirtual,
985 const CXXRecordDecl *LayoutClass)
986 : VTables(VTables), MostDerivedClass(MostDerivedClass),
987 MostDerivedClassOffset(MostDerivedClassOffset),
988 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
989 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
990 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000991 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000992
993 LayoutVTable();
994
David Blaikiebbafb8a2012-03-11 07:00:24 +0000995 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +0000996 dumpLayout(llvm::outs());
Peter Collingbournecfd23562011-09-26 01:57:12 +0000997 }
998
999 uint64_t getNumThunks() const {
1000 return Thunks.size();
1001 }
1002
1003 ThunksMapTy::const_iterator thunks_begin() const {
1004 return Thunks.begin();
1005 }
1006
1007 ThunksMapTy::const_iterator thunks_end() const {
1008 return Thunks.end();
1009 }
1010
1011 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1012 return VBaseOffsetOffsets;
1013 }
1014
1015 const AddressPointsMapTy &getAddressPoints() const {
1016 return AddressPoints;
1017 }
1018
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001019 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1020 return MethodVTableIndices.begin();
1021 }
1022
1023 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1024 return MethodVTableIndices.end();
1025 }
1026
Peter Collingbournecfd23562011-09-26 01:57:12 +00001027 /// getNumVTableComponents - Return the number of components in the vtable
1028 /// currently built.
1029 uint64_t getNumVTableComponents() const {
1030 return Components.size();
1031 }
1032
1033 const VTableComponent *vtable_component_begin() const {
1034 return Components.begin();
1035 }
1036
1037 const VTableComponent *vtable_component_end() const {
1038 return Components.end();
1039 }
1040
1041 AddressPointsMapTy::const_iterator address_points_begin() const {
1042 return AddressPoints.begin();
1043 }
1044
1045 AddressPointsMapTy::const_iterator address_points_end() const {
1046 return AddressPoints.end();
1047 }
1048
1049 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1050 return VTableThunks.begin();
1051 }
1052
1053 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1054 return VTableThunks.end();
1055 }
1056
1057 /// dumpLayout - Dump the vtable layout.
1058 void dumpLayout(raw_ostream&);
1059};
1060
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001061void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1062 const ThunkInfo &Thunk) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001063 assert(!isBuildingConstructorVTable() &&
1064 "Can't add thunks for construction vtable");
1065
Craig Topper5603df42013-07-05 19:34:19 +00001066 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1067
Peter Collingbournecfd23562011-09-26 01:57:12 +00001068 // Check if we have this thunk already.
1069 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1070 ThunksVector.end())
1071 return;
1072
1073 ThunksVector.push_back(Thunk);
1074}
1075
1076typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1077
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001078/// Visit all the methods overridden by the given method recursively,
1079/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1080/// indicating whether to continue the recursion for the given overridden
1081/// method (i.e. returning false stops the iteration).
1082template <class VisitorTy>
1083static void
1084visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001085 assert(MD->isVirtual() && "Method is not virtual!");
1086
1087 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1088 E = MD->end_overridden_methods(); I != E; ++I) {
1089 const CXXMethodDecl *OverriddenMD = *I;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001090 if (!Visitor.visit(OverriddenMD))
1091 continue;
1092 visitAllOverriddenMethods(OverriddenMD, Visitor);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001093 }
1094}
1095
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001096namespace {
1097 struct OverriddenMethodsCollector {
1098 OverriddenMethodsSetTy *Methods;
1099
1100 bool visit(const CXXMethodDecl *MD) {
1101 // Don't recurse on this method if we've already collected it.
1102 return Methods->insert(MD);
1103 }
1104 };
1105}
1106
1107/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1108/// the overridden methods that the function decl overrides.
1109static void
1110ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1111 OverriddenMethodsSetTy& OverriddenMethods) {
1112 OverriddenMethodsCollector Collector = { &OverriddenMethods };
1113 visitAllOverriddenMethods(MD, Collector);
1114}
1115
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001116void ItaniumVTableBuilder::ComputeThisAdjustments() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001117 // Now go through the method info map and see if any of the methods need
1118 // 'this' pointer adjustments.
1119 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1120 E = MethodInfoMap.end(); I != E; ++I) {
1121 const CXXMethodDecl *MD = I->first;
1122 const MethodInfo &MethodInfo = I->second;
1123
1124 // Ignore adjustments for unused function pointers.
1125 uint64_t VTableIndex = MethodInfo.VTableIndex;
1126 if (Components[VTableIndex].getKind() ==
1127 VTableComponent::CK_UnusedFunctionPointer)
1128 continue;
1129
1130 // Get the final overrider for this method.
1131 FinalOverriders::OverriderInfo Overrider =
1132 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1133
1134 // Check if we need an adjustment at all.
1135 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1136 // When a return thunk is needed by a derived class that overrides a
1137 // virtual base, gcc uses a virtual 'this' adjustment as well.
1138 // While the thunk itself might be needed by vtables in subclasses or
1139 // in construction vtables, there doesn't seem to be a reason for using
1140 // the thunk in this vtable. Still, we do so to match gcc.
1141 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1142 continue;
1143 }
1144
1145 ThisAdjustment ThisAdjustment =
1146 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1147
1148 if (ThisAdjustment.isEmpty())
1149 continue;
1150
1151 // Add it.
1152 VTableThunks[VTableIndex].This = ThisAdjustment;
1153
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001154 if (isa<CXXDestructorDecl>(MD)) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001155 // Add an adjustment for the deleting destructor as well.
1156 VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1157 }
1158 }
1159
1160 /// Clear the method info map.
1161 MethodInfoMap.clear();
1162
1163 if (isBuildingConstructorVTable()) {
1164 // We don't need to store thunk information for construction vtables.
1165 return;
1166 }
1167
1168 for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1169 E = VTableThunks.end(); I != E; ++I) {
1170 const VTableComponent &Component = Components[I->first];
1171 const ThunkInfo &Thunk = I->second;
1172 const CXXMethodDecl *MD;
1173
1174 switch (Component.getKind()) {
1175 default:
1176 llvm_unreachable("Unexpected vtable component kind!");
1177 case VTableComponent::CK_FunctionPointer:
1178 MD = Component.getFunctionDecl();
1179 break;
1180 case VTableComponent::CK_CompleteDtorPointer:
1181 MD = Component.getDestructorDecl();
1182 break;
1183 case VTableComponent::CK_DeletingDtorPointer:
1184 // We've already added the thunk when we saw the complete dtor pointer.
1185 continue;
1186 }
1187
1188 if (MD->getParent() == MostDerivedClass)
1189 AddThunk(MD, Thunk);
1190 }
1191}
1192
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001193ReturnAdjustment
1194ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001195 ReturnAdjustment Adjustment;
1196
1197 if (!Offset.isEmpty()) {
1198 if (Offset.VirtualBase) {
1199 // Get the virtual base offset offset.
1200 if (Offset.DerivedClass == MostDerivedClass) {
1201 // We can get the offset offset directly from our map.
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001202 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001203 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1204 } else {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001205 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001206 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1207 Offset.VirtualBase).getQuantity();
1208 }
1209 }
1210
1211 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1212 }
1213
1214 return Adjustment;
1215}
1216
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001217BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1218 BaseSubobject Base, BaseSubobject Derived) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001219 const CXXRecordDecl *BaseRD = Base.getBase();
1220 const CXXRecordDecl *DerivedRD = Derived.getBase();
1221
1222 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1223 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1224
Benjamin Kramer325d7452013-02-03 18:55:34 +00001225 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
Peter Collingbournecfd23562011-09-26 01:57:12 +00001226 llvm_unreachable("Class must be derived from the passed in base class!");
Peter Collingbournecfd23562011-09-26 01:57:12 +00001227
1228 // We have to go through all the paths, and see which one leads us to the
1229 // right base subobject.
1230 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1231 I != E; ++I) {
1232 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1233
1234 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1235
1236 if (Offset.VirtualBase) {
1237 // If we have a virtual base class, the non-virtual offset is relative
1238 // to the virtual base class offset.
1239 const ASTRecordLayout &LayoutClassLayout =
1240 Context.getASTRecordLayout(LayoutClass);
1241
1242 /// Get the virtual base offset, relative to the most derived class
1243 /// layout.
1244 OffsetToBaseSubobject +=
1245 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1246 } else {
1247 // Otherwise, the non-virtual offset is relative to the derived class
1248 // offset.
1249 OffsetToBaseSubobject += Derived.getBaseOffset();
1250 }
1251
1252 // Check if this path gives us the right base subobject.
1253 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1254 // Since we're going from the base class _to_ the derived class, we'll
1255 // invert the non-virtual offset here.
1256 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1257 return Offset;
1258 }
1259 }
1260
1261 return BaseOffset();
1262}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001263
1264ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1265 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1266 FinalOverriders::OverriderInfo Overrider) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001267 // Ignore adjustments for pure virtual member functions.
1268 if (Overrider.Method->isPure())
1269 return ThisAdjustment();
1270
1271 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1272 BaseOffsetInLayoutClass);
1273
1274 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1275 Overrider.Offset);
1276
1277 // Compute the adjustment offset.
1278 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1279 OverriderBaseSubobject);
1280 if (Offset.isEmpty())
1281 return ThisAdjustment();
1282
1283 ThisAdjustment Adjustment;
1284
1285 if (Offset.VirtualBase) {
1286 // Get the vcall offset map for this virtual base.
1287 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1288
1289 if (VCallOffsets.empty()) {
1290 // We don't have vcall offsets for this virtual base, go ahead and
1291 // build them.
1292 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1293 /*FinalOverriders=*/0,
1294 BaseSubobject(Offset.VirtualBase,
1295 CharUnits::Zero()),
1296 /*BaseIsVirtual=*/true,
1297 /*OffsetInLayoutClass=*/
1298 CharUnits::Zero());
1299
1300 VCallOffsets = Builder.getVCallOffsets();
1301 }
1302
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001303 Adjustment.Virtual.Itanium.VCallOffsetOffset =
Peter Collingbournecfd23562011-09-26 01:57:12 +00001304 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1305 }
1306
1307 // Set the non-virtual part of the adjustment.
1308 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1309
1310 return Adjustment;
1311}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001312
1313void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1314 ReturnAdjustment ReturnAdjustment) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001315 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1316 assert(ReturnAdjustment.isEmpty() &&
1317 "Destructor can't have return adjustment!");
1318
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001319 // Add both the complete destructor and the deleting destructor.
1320 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1321 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
Peter Collingbournecfd23562011-09-26 01:57:12 +00001322 } else {
1323 // Add the return adjustment if necessary.
1324 if (!ReturnAdjustment.isEmpty())
1325 VTableThunks[Components.size()].Return = ReturnAdjustment;
1326
1327 // Add the function.
1328 Components.push_back(VTableComponent::MakeFunction(MD));
1329 }
1330}
1331
1332/// OverridesIndirectMethodInBase - Return whether the given member function
1333/// overrides any methods in the set of given bases.
1334/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1335/// For example, if we have:
1336///
1337/// struct A { virtual void f(); }
1338/// struct B : A { virtual void f(); }
1339/// struct C : B { virtual void f(); }
1340///
1341/// OverridesIndirectMethodInBase will return true if given C::f as the method
1342/// and { A } as the set of bases.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001343static bool OverridesIndirectMethodInBases(
1344 const CXXMethodDecl *MD,
1345 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001346 if (Bases.count(MD->getParent()))
1347 return true;
1348
1349 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1350 E = MD->end_overridden_methods(); I != E; ++I) {
1351 const CXXMethodDecl *OverriddenMD = *I;
1352
1353 // Check "indirect overriders".
1354 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1355 return true;
1356 }
1357
1358 return false;
1359}
1360
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001361bool ItaniumVTableBuilder::IsOverriderUsed(
1362 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1363 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1364 CharUnits FirstBaseOffsetInLayoutClass) const {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001365 // If the base and the first base in the primary base chain have the same
1366 // offsets, then this overrider will be used.
1367 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1368 return true;
1369
1370 // We know now that Base (or a direct or indirect base of it) is a primary
1371 // base in part of the class hierarchy, but not a primary base in the most
1372 // derived class.
1373
1374 // If the overrider is the first base in the primary base chain, we know
1375 // that the overrider will be used.
1376 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1377 return true;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001378
1379 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001380
1381 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1382 PrimaryBases.insert(RD);
1383
1384 // Now traverse the base chain, starting with the first base, until we find
1385 // the base that is no longer a primary base.
1386 while (true) {
1387 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1388 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1389
1390 if (!PrimaryBase)
1391 break;
1392
1393 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001394 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001395 "Primary base should always be at offset 0!");
1396
1397 const ASTRecordLayout &LayoutClassLayout =
1398 Context.getASTRecordLayout(LayoutClass);
1399
1400 // Now check if this is the primary base that is not a primary base in the
1401 // most derived class.
1402 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1403 FirstBaseOffsetInLayoutClass) {
1404 // We found it, stop walking the chain.
1405 break;
1406 }
1407 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001408 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001409 "Primary base should always be at offset 0!");
1410 }
1411
1412 if (!PrimaryBases.insert(PrimaryBase))
1413 llvm_unreachable("Found a duplicate primary base!");
1414
1415 RD = PrimaryBase;
1416 }
1417
1418 // If the final overrider is an override of one of the primary bases,
1419 // then we know that it will be used.
1420 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1421}
1422
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001423typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1424
Peter Collingbournecfd23562011-09-26 01:57:12 +00001425/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1426/// from the nearest base. Returns null if no method was found.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001427/// The Bases are expected to be sorted in a base-to-derived order.
1428static const CXXMethodDecl *
Peter Collingbournecfd23562011-09-26 01:57:12 +00001429FindNearestOverriddenMethod(const CXXMethodDecl *MD,
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001430 BasesSetVectorTy &Bases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001431 OverriddenMethodsSetTy OverriddenMethods;
1432 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1433
1434 for (int I = Bases.size(), E = 0; I != E; --I) {
1435 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1436
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00001437 // Now check the overridden methods.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001438 for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1439 E = OverriddenMethods.end(); I != E; ++I) {
1440 const CXXMethodDecl *OverriddenMD = *I;
1441
1442 // We found our overridden method.
1443 if (OverriddenMD->getParent() == PrimaryBase)
1444 return OverriddenMD;
1445 }
1446 }
1447
1448 return 0;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001449}
Peter Collingbournecfd23562011-09-26 01:57:12 +00001450
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001451void ItaniumVTableBuilder::AddMethods(
1452 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1453 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1454 CharUnits FirstBaseOffsetInLayoutClass,
1455 PrimaryBasesSetVectorTy &PrimaryBases) {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001456 // Itanium C++ ABI 2.5.2:
1457 // The order of the virtual function pointers in a virtual table is the
1458 // order of declaration of the corresponding member functions in the class.
1459 //
1460 // There is an entry for any virtual function declared in a class,
1461 // whether it is a new function or overrides a base class function,
1462 // unless it overrides a function from the primary base, and conversion
1463 // between their return types does not require an adjustment.
1464
Peter Collingbournecfd23562011-09-26 01:57:12 +00001465 const CXXRecordDecl *RD = Base.getBase();
1466 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1467
1468 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1469 CharUnits PrimaryBaseOffset;
1470 CharUnits PrimaryBaseOffsetInLayoutClass;
1471 if (Layout.isPrimaryBaseVirtual()) {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001472 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001473 "Primary vbase should have a zero offset!");
1474
1475 const ASTRecordLayout &MostDerivedClassLayout =
1476 Context.getASTRecordLayout(MostDerivedClass);
1477
1478 PrimaryBaseOffset =
1479 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1480
1481 const ASTRecordLayout &LayoutClassLayout =
1482 Context.getASTRecordLayout(LayoutClass);
1483
1484 PrimaryBaseOffsetInLayoutClass =
1485 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1486 } else {
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001487 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001488 "Primary base should have a zero offset!");
1489
1490 PrimaryBaseOffset = Base.getBaseOffset();
1491 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1492 }
1493
1494 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1495 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1496 FirstBaseOffsetInLayoutClass, PrimaryBases);
1497
1498 if (!PrimaryBases.insert(PrimaryBase))
1499 llvm_unreachable("Found a duplicate primary base!");
1500 }
1501
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001502 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1503
1504 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1505 NewVirtualFunctionsTy NewVirtualFunctions;
1506
Peter Collingbournecfd23562011-09-26 01:57:12 +00001507 // Now go through all virtual member functions and add them.
Aaron Ballman2b124d12014-03-13 16:36:16 +00001508 for (const auto *MD : RD->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001509 if (!MD->isVirtual())
1510 continue;
1511
1512 // Get the final overrider.
1513 FinalOverriders::OverriderInfo Overrider =
1514 Overriders.getOverrider(MD, Base.getBaseOffset());
1515
1516 // Check if this virtual member function overrides a method in a primary
1517 // base. If this is the case, and the return type doesn't require adjustment
1518 // then we can just use the member function from the primary base.
1519 if (const CXXMethodDecl *OverriddenMD =
1520 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1521 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1522 OverriddenMD).isEmpty()) {
1523 // Replace the method info of the overridden method with our own
1524 // method.
1525 assert(MethodInfoMap.count(OverriddenMD) &&
1526 "Did not find the overridden method!");
1527 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1528
1529 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1530 OverriddenMethodInfo.VTableIndex);
1531
1532 assert(!MethodInfoMap.count(MD) &&
1533 "Should not have method info for this method yet!");
1534
1535 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1536 MethodInfoMap.erase(OverriddenMD);
1537
1538 // If the overridden method exists in a virtual base class or a direct
1539 // or indirect base class of a virtual base class, we need to emit a
1540 // thunk if we ever have a class hierarchy where the base class is not
1541 // a primary base in the complete object.
1542 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1543 // Compute the this adjustment.
1544 ThisAdjustment ThisAdjustment =
1545 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1546 Overrider);
1547
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001548 if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001549 Overrider.Method->getParent() == MostDerivedClass) {
1550
1551 // There's no return adjustment from OverriddenMD and MD,
1552 // but that doesn't mean there isn't one between MD and
1553 // the final overrider.
1554 BaseOffset ReturnAdjustmentOffset =
1555 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1556 ReturnAdjustment ReturnAdjustment =
1557 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1558
1559 // This is a virtual thunk for the most derived class, add it.
1560 AddThunk(Overrider.Method,
1561 ThunkInfo(ThisAdjustment, ReturnAdjustment));
1562 }
1563 }
1564
1565 continue;
1566 }
1567 }
1568
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001569 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1570 if (MD->isImplicit()) {
1571 // Itanium C++ ABI 2.5.2:
1572 // If a class has an implicitly-defined virtual destructor,
1573 // its entries come after the declared virtual function pointers.
1574
1575 assert(!ImplicitVirtualDtor &&
1576 "Did already see an implicit virtual dtor!");
1577 ImplicitVirtualDtor = DD;
1578 continue;
1579 }
1580 }
1581
1582 NewVirtualFunctions.push_back(MD);
1583 }
1584
1585 if (ImplicitVirtualDtor)
1586 NewVirtualFunctions.push_back(ImplicitVirtualDtor);
1587
1588 for (NewVirtualFunctionsTy::const_iterator I = NewVirtualFunctions.begin(),
1589 E = NewVirtualFunctions.end(); I != E; ++I) {
1590 const CXXMethodDecl *MD = *I;
1591
1592 // Get the final overrider.
1593 FinalOverriders::OverriderInfo Overrider =
1594 Overriders.getOverrider(MD, Base.getBaseOffset());
1595
Peter Collingbournecfd23562011-09-26 01:57:12 +00001596 // Insert the method info for this method.
1597 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1598 Components.size());
1599
1600 assert(!MethodInfoMap.count(MD) &&
1601 "Should not have method info for this method yet!");
1602 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1603
1604 // Check if this overrider is going to be used.
1605 const CXXMethodDecl *OverriderMD = Overrider.Method;
1606 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1607 FirstBaseInPrimaryBaseChain,
1608 FirstBaseOffsetInLayoutClass)) {
1609 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1610 continue;
1611 }
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001612
Peter Collingbournecfd23562011-09-26 01:57:12 +00001613 // Check if this overrider needs a return adjustment.
1614 // We don't want to do this for pure virtual member functions.
1615 BaseOffset ReturnAdjustmentOffset;
1616 if (!OverriderMD->isPure()) {
1617 ReturnAdjustmentOffset =
1618 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1619 }
1620
1621 ReturnAdjustment ReturnAdjustment =
1622 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1623
1624 AddMethod(Overrider.Method, ReturnAdjustment);
1625 }
1626}
1627
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001628void ItaniumVTableBuilder::LayoutVTable() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001629 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1630 CharUnits::Zero()),
1631 /*BaseIsMorallyVirtual=*/false,
1632 MostDerivedClassIsVirtual,
1633 MostDerivedClassOffset);
1634
1635 VisitedVirtualBasesSetTy VBases;
1636
1637 // Determine the primary virtual bases.
1638 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1639 VBases);
1640 VBases.clear();
1641
1642 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1643
1644 // -fapple-kext adds an extra entry at end of vtbl.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001645 bool IsAppleKext = Context.getLangOpts().AppleKext;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001646 if (IsAppleKext)
1647 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1648}
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001649
1650void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1651 BaseSubobject Base, bool BaseIsMorallyVirtual,
1652 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001653 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1654
1655 // Add vcall and vbase offsets for this vtable.
1656 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1657 Base, BaseIsVirtualInLayoutClass,
1658 OffsetInLayoutClass);
1659 Components.append(Builder.components_begin(), Builder.components_end());
1660
1661 // Check if we need to add these vcall offsets.
1662 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1663 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1664
1665 if (VCallOffsets.empty())
1666 VCallOffsets = Builder.getVCallOffsets();
1667 }
1668
1669 // If we're laying out the most derived class we want to keep track of the
1670 // virtual base class offset offsets.
1671 if (Base.getBase() == MostDerivedClass)
1672 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1673
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001674 // Add the offset to top.
1675 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1676 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001677
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001678 // Next, add the RTTI.
1679 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00001680
Peter Collingbournecfd23562011-09-26 01:57:12 +00001681 uint64_t AddressPoint = Components.size();
1682
1683 // Now go through all virtual member functions and add them.
1684 PrimaryBasesSetVectorTy PrimaryBases;
1685 AddMethods(Base, OffsetInLayoutClass,
1686 Base.getBase(), OffsetInLayoutClass,
1687 PrimaryBases);
1688
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001689 const CXXRecordDecl *RD = Base.getBase();
1690 if (RD == MostDerivedClass) {
1691 assert(MethodVTableIndices.empty());
1692 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1693 E = MethodInfoMap.end(); I != E; ++I) {
1694 const CXXMethodDecl *MD = I->first;
1695 const MethodInfo &MI = I->second;
1696 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001697 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1698 = MI.VTableIndex - AddressPoint;
1699 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1700 = MI.VTableIndex + 1 - AddressPoint;
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00001701 } else {
1702 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1703 }
1704 }
1705 }
1706
Peter Collingbournecfd23562011-09-26 01:57:12 +00001707 // Compute 'this' pointer adjustments.
1708 ComputeThisAdjustments();
1709
1710 // Add all address points.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001711 while (true) {
1712 AddressPoints.insert(std::make_pair(
1713 BaseSubobject(RD, OffsetInLayoutClass),
1714 AddressPoint));
1715
1716 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1717 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1718
1719 if (!PrimaryBase)
1720 break;
1721
1722 if (Layout.isPrimaryBaseVirtual()) {
1723 // Check if this virtual primary base is a primary base in the layout
1724 // class. If it's not, we don't want to add it.
1725 const ASTRecordLayout &LayoutClassLayout =
1726 Context.getASTRecordLayout(LayoutClass);
1727
1728 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1729 OffsetInLayoutClass) {
1730 // We don't want to add this class (or any of its primary bases).
1731 break;
1732 }
1733 }
1734
1735 RD = PrimaryBase;
1736 }
1737
1738 // Layout secondary vtables.
1739 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1740}
1741
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001742void
1743ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1744 bool BaseIsMorallyVirtual,
1745 CharUnits OffsetInLayoutClass) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001746 // Itanium C++ ABI 2.5.2:
1747 // Following the primary virtual table of a derived class are secondary
1748 // virtual tables for each of its proper base classes, except any primary
1749 // base(s) with which it shares its primary virtual table.
1750
1751 const CXXRecordDecl *RD = Base.getBase();
1752 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1753 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1754
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001755 for (const auto &B : RD->bases()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001756 // Ignore virtual bases, we'll emit them later.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001757 if (B.isVirtual())
Peter Collingbournecfd23562011-09-26 01:57:12 +00001758 continue;
1759
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001760 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001761
1762 // Ignore bases that don't have a vtable.
1763 if (!BaseDecl->isDynamicClass())
1764 continue;
1765
1766 if (isBuildingConstructorVTable()) {
1767 // Itanium C++ ABI 2.6.4:
1768 // Some of the base class subobjects may not need construction virtual
1769 // tables, which will therefore not be present in the construction
1770 // virtual table group, even though the subobject virtual tables are
1771 // present in the main virtual table group for the complete object.
1772 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1773 continue;
1774 }
1775
1776 // Get the base offset of this base.
1777 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1778 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1779
1780 CharUnits BaseOffsetInLayoutClass =
1781 OffsetInLayoutClass + RelativeBaseOffset;
1782
1783 // Don't emit a secondary vtable for a primary base. We might however want
1784 // to emit secondary vtables for other bases of this base.
1785 if (BaseDecl == PrimaryBase) {
1786 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1787 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1788 continue;
1789 }
1790
1791 // Layout the primary vtable (and any secondary vtables) for this base.
1792 LayoutPrimaryAndSecondaryVTables(
1793 BaseSubobject(BaseDecl, BaseOffset),
1794 BaseIsMorallyVirtual,
1795 /*BaseIsVirtualInLayoutClass=*/false,
1796 BaseOffsetInLayoutClass);
1797 }
1798}
1799
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001800void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1801 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1802 VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001803 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1804
1805 // Check if this base has a primary base.
1806 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1807
1808 // Check if it's virtual.
1809 if (Layout.isPrimaryBaseVirtual()) {
1810 bool IsPrimaryVirtualBase = true;
1811
1812 if (isBuildingConstructorVTable()) {
1813 // Check if the base is actually a primary base in the class we use for
1814 // layout.
1815 const ASTRecordLayout &LayoutClassLayout =
1816 Context.getASTRecordLayout(LayoutClass);
1817
1818 CharUnits PrimaryBaseOffsetInLayoutClass =
1819 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1820
1821 // We know that the base is not a primary base in the layout class if
1822 // the base offsets are different.
1823 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1824 IsPrimaryVirtualBase = false;
1825 }
1826
1827 if (IsPrimaryVirtualBase)
1828 PrimaryVirtualBases.insert(PrimaryBase);
1829 }
1830 }
1831
1832 // Traverse bases, looking for more primary virtual bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001833 for (const auto &B : RD->bases()) {
1834 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001835
1836 CharUnits BaseOffsetInLayoutClass;
1837
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001838 if (B.isVirtual()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001839 if (!VBases.insert(BaseDecl))
1840 continue;
1841
1842 const ASTRecordLayout &LayoutClassLayout =
1843 Context.getASTRecordLayout(LayoutClass);
1844
1845 BaseOffsetInLayoutClass =
1846 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1847 } else {
1848 BaseOffsetInLayoutClass =
1849 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1850 }
1851
1852 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1853 }
1854}
1855
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001856void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1857 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00001858 // Itanium C++ ABI 2.5.2:
1859 // Then come the virtual base virtual tables, also in inheritance graph
1860 // order, and again excluding primary bases (which share virtual tables with
1861 // the classes for which they are primary).
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001862 for (const auto &B : RD->bases()) {
1863 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00001864
1865 // Check if this base needs a vtable. (If it's virtual, not a primary base
1866 // of some other class, and we haven't visited it before).
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00001867 if (B.isVirtual() && BaseDecl->isDynamicClass() &&
Peter Collingbournecfd23562011-09-26 01:57:12 +00001868 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1869 const ASTRecordLayout &MostDerivedClassLayout =
1870 Context.getASTRecordLayout(MostDerivedClass);
1871 CharUnits BaseOffset =
1872 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1873
1874 const ASTRecordLayout &LayoutClassLayout =
1875 Context.getASTRecordLayout(LayoutClass);
1876 CharUnits BaseOffsetInLayoutClass =
1877 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1878
1879 LayoutPrimaryAndSecondaryVTables(
1880 BaseSubobject(BaseDecl, BaseOffset),
1881 /*BaseIsMorallyVirtual=*/true,
1882 /*BaseIsVirtualInLayoutClass=*/true,
1883 BaseOffsetInLayoutClass);
1884 }
1885
1886 // We only need to check the base for virtual base vtables if it actually
1887 // has virtual bases.
1888 if (BaseDecl->getNumVBases())
1889 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1890 }
1891}
1892
1893/// dumpLayout - Dump the vtable layout.
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001894void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00001895 // FIXME: write more tests that actually use the dumpLayout output to prevent
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00001896 // ItaniumVTableBuilder regressions.
Peter Collingbournecfd23562011-09-26 01:57:12 +00001897
1898 if (isBuildingConstructorVTable()) {
1899 Out << "Construction vtable for ('";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001900 MostDerivedClass->printQualifiedName(Out);
1901 Out << "', ";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001902 Out << MostDerivedClassOffset.getQuantity() << ") in '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001903 LayoutClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001904 } else {
1905 Out << "Vtable for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001906 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00001907 }
1908 Out << "' (" << Components.size() << " entries).\n";
1909
1910 // Iterate through the address points and insert them into a new map where
1911 // they are keyed by the index and not the base object.
1912 // Since an address point can be shared by multiple subobjects, we use an
1913 // STL multimap.
1914 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1915 for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
1916 E = AddressPoints.end(); I != E; ++I) {
1917 const BaseSubobject& Base = I->first;
1918 uint64_t Index = I->second;
1919
1920 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1921 }
1922
1923 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1924 uint64_t Index = I;
1925
1926 Out << llvm::format("%4d | ", I);
1927
1928 const VTableComponent &Component = Components[I];
1929
1930 // Dump the component.
1931 switch (Component.getKind()) {
1932
1933 case VTableComponent::CK_VCallOffset:
1934 Out << "vcall_offset ("
1935 << Component.getVCallOffset().getQuantity()
1936 << ")";
1937 break;
1938
1939 case VTableComponent::CK_VBaseOffset:
1940 Out << "vbase_offset ("
1941 << Component.getVBaseOffset().getQuantity()
1942 << ")";
1943 break;
1944
1945 case VTableComponent::CK_OffsetToTop:
1946 Out << "offset_to_top ("
1947 << Component.getOffsetToTop().getQuantity()
1948 << ")";
1949 break;
1950
1951 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001952 Component.getRTTIDecl()->printQualifiedName(Out);
1953 Out << " RTTI";
Peter Collingbournecfd23562011-09-26 01:57:12 +00001954 break;
1955
1956 case VTableComponent::CK_FunctionPointer: {
1957 const CXXMethodDecl *MD = Component.getFunctionDecl();
1958
1959 std::string Str =
1960 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
1961 MD);
1962 Out << Str;
1963 if (MD->isPure())
1964 Out << " [pure]";
1965
David Blaikie596d2ca2012-10-16 20:25:33 +00001966 if (MD->isDeleted())
1967 Out << " [deleted]";
1968
Peter Collingbournecfd23562011-09-26 01:57:12 +00001969 ThunkInfo Thunk = VTableThunks.lookup(I);
1970 if (!Thunk.isEmpty()) {
1971 // If this function pointer has a return adjustment, dump it.
1972 if (!Thunk.Return.isEmpty()) {
1973 Out << "\n [return adjustment: ";
1974 Out << Thunk.Return.NonVirtual << " non-virtual";
1975
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001976 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
1977 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001978 Out << " vbase offset offset";
1979 }
1980
1981 Out << ']';
1982 }
1983
1984 // If this function pointer has a 'this' pointer adjustment, dump it.
1985 if (!Thunk.This.isEmpty()) {
1986 Out << "\n [this adjustment: ";
1987 Out << Thunk.This.NonVirtual << " non-virtual";
1988
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001989 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
1990 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00001991 Out << " vcall offset offset";
1992 }
1993
1994 Out << ']';
1995 }
1996 }
1997
1998 break;
1999 }
2000
2001 case VTableComponent::CK_CompleteDtorPointer:
2002 case VTableComponent::CK_DeletingDtorPointer: {
2003 bool IsComplete =
2004 Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2005
2006 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2007
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002008 DD->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002009 if (IsComplete)
2010 Out << "() [complete]";
2011 else
2012 Out << "() [deleting]";
2013
2014 if (DD->isPure())
2015 Out << " [pure]";
2016
2017 ThunkInfo Thunk = VTableThunks.lookup(I);
2018 if (!Thunk.isEmpty()) {
2019 // If this destructor has a 'this' pointer adjustment, dump it.
2020 if (!Thunk.This.isEmpty()) {
2021 Out << "\n [this adjustment: ";
2022 Out << Thunk.This.NonVirtual << " non-virtual";
2023
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002024 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2025 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002026 Out << " vcall offset offset";
2027 }
2028
2029 Out << ']';
2030 }
2031 }
2032
2033 break;
2034 }
2035
2036 case VTableComponent::CK_UnusedFunctionPointer: {
2037 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2038
2039 std::string Str =
2040 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2041 MD);
2042 Out << "[unused] " << Str;
2043 if (MD->isPure())
2044 Out << " [pure]";
2045 }
2046
2047 }
2048
2049 Out << '\n';
2050
2051 // Dump the next address point.
2052 uint64_t NextIndex = Index + 1;
2053 if (AddressPointsByIndex.count(NextIndex)) {
2054 if (AddressPointsByIndex.count(NextIndex) == 1) {
2055 const BaseSubobject &Base =
2056 AddressPointsByIndex.find(NextIndex)->second;
2057
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002058 Out << " -- (";
2059 Base.getBase()->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002060 Out << ", " << Base.getBaseOffset().getQuantity();
2061 Out << ") vtable address --\n";
2062 } else {
2063 CharUnits BaseOffset =
2064 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2065
2066 // We store the class names in a set to get a stable order.
2067 std::set<std::string> ClassNames;
2068 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2069 AddressPointsByIndex.lower_bound(NextIndex), E =
2070 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2071 assert(I->second.getBaseOffset() == BaseOffset &&
2072 "Invalid base offset!");
2073 const CXXRecordDecl *RD = I->second.getBase();
2074 ClassNames.insert(RD->getQualifiedNameAsString());
2075 }
2076
2077 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2078 E = ClassNames.end(); I != E; ++I) {
2079 Out << " -- (" << *I;
2080 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2081 }
2082 }
2083 }
2084 }
2085
2086 Out << '\n';
2087
2088 if (isBuildingConstructorVTable())
2089 return;
2090
2091 if (MostDerivedClass->getNumVBases()) {
2092 // We store the virtual base class names and their offsets in a map to get
2093 // a stable order.
2094
2095 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2096 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2097 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2098 std::string ClassName = I->first->getQualifiedNameAsString();
2099 CharUnits OffsetOffset = I->second;
2100 ClassNamesAndOffsets.insert(
2101 std::make_pair(ClassName, OffsetOffset));
2102 }
2103
2104 Out << "Virtual base offset offsets for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002105 MostDerivedClass->printQualifiedName(Out);
2106 Out << "' (";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002107 Out << ClassNamesAndOffsets.size();
2108 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2109
2110 for (std::map<std::string, CharUnits>::const_iterator I =
2111 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2112 I != E; ++I)
2113 Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
2114
2115 Out << "\n";
2116 }
2117
2118 if (!Thunks.empty()) {
2119 // We store the method names in a map to get a stable order.
2120 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2121
2122 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2123 I != E; ++I) {
2124 const CXXMethodDecl *MD = I->first;
2125 std::string MethodName =
2126 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2127 MD);
2128
2129 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2130 }
2131
2132 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2133 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2134 I != E; ++I) {
2135 const std::string &MethodName = I->first;
2136 const CXXMethodDecl *MD = I->second;
2137
2138 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002139 std::sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002140 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
2141 assert(LHS.Method == 0 && RHS.Method == 0);
Benjamin Kramera741b8c2014-03-03 20:26:46 +00002142 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002143 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002144
2145 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2146 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2147
2148 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2149 const ThunkInfo &Thunk = ThunksVector[I];
2150
2151 Out << llvm::format("%4d | ", I);
2152
2153 // If this function pointer has a return pointer adjustment, dump it.
2154 if (!Thunk.Return.isEmpty()) {
Timur Iskhodzhanov11510312013-06-28 15:42:28 +00002155 Out << "return adjustment: " << Thunk.Return.NonVirtual;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002156 Out << " non-virtual";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002157 if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
2158 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002159 Out << " vbase offset offset";
2160 }
2161
2162 if (!Thunk.This.isEmpty())
2163 Out << "\n ";
2164 }
2165
2166 // If this function pointer has a 'this' pointer adjustment, dump it.
2167 if (!Thunk.This.isEmpty()) {
2168 Out << "this adjustment: ";
2169 Out << Thunk.This.NonVirtual << " non-virtual";
2170
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002171 if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
2172 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002173 Out << " vcall offset offset";
2174 }
2175 }
2176
2177 Out << '\n';
2178 }
2179
2180 Out << '\n';
2181 }
2182 }
2183
2184 // Compute the vtable indices for all the member functions.
2185 // Store them in a map keyed by the index so we'll get a sorted table.
2186 std::map<uint64_t, std::string> IndicesMap;
2187
Aaron Ballman2b124d12014-03-13 16:36:16 +00002188 for (const auto *MD : MostDerivedClass->methods()) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002189 // We only want virtual member functions.
2190 if (!MD->isVirtual())
2191 continue;
2192
2193 std::string MethodName =
2194 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2195 MD);
2196
2197 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002198 GlobalDecl GD(DD, Dtor_Complete);
2199 assert(MethodVTableIndices.count(GD));
2200 uint64_t VTableIndex = MethodVTableIndices[GD];
2201 IndicesMap[VTableIndex] = MethodName + " [complete]";
2202 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
Peter Collingbournecfd23562011-09-26 01:57:12 +00002203 } else {
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002204 assert(MethodVTableIndices.count(MD));
2205 IndicesMap[MethodVTableIndices[MD]] = MethodName;
Peter Collingbournecfd23562011-09-26 01:57:12 +00002206 }
2207 }
2208
2209 // Print the vtable indices for all the member functions.
2210 if (!IndicesMap.empty()) {
2211 Out << "VTable indices for '";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002212 MostDerivedClass->printQualifiedName(Out);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002213 Out << "' (" << IndicesMap.size() << " entries).\n";
2214
2215 for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
2216 E = IndicesMap.end(); I != E; ++I) {
2217 uint64_t VTableIndex = I->first;
2218 const std::string &MethodName = I->second;
2219
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002220 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
Benjamin Kramer5291e682012-03-10 02:06:27 +00002221 << '\n';
Peter Collingbournecfd23562011-09-26 01:57:12 +00002222 }
2223 }
2224
2225 Out << '\n';
2226}
Peter Collingbournecfd23562011-09-26 01:57:12 +00002227}
2228
2229VTableLayout::VTableLayout(uint64_t NumVTableComponents,
2230 const VTableComponent *VTableComponents,
2231 uint64_t NumVTableThunks,
2232 const VTableThunkTy *VTableThunks,
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002233 const AddressPointsMapTy &AddressPoints,
2234 bool IsMicrosoftABI)
Peter Collingbournecfd23562011-09-26 01:57:12 +00002235 : NumVTableComponents(NumVTableComponents),
2236 VTableComponents(new VTableComponent[NumVTableComponents]),
2237 NumVTableThunks(NumVTableThunks),
2238 VTableThunks(new VTableThunkTy[NumVTableThunks]),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002239 AddressPoints(AddressPoints),
2240 IsMicrosoftABI(IsMicrosoftABI) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002241 std::copy(VTableComponents, VTableComponents+NumVTableComponents,
Benjamin Kramere2980632012-04-14 14:13:43 +00002242 this->VTableComponents.get());
2243 std::copy(VTableThunks, VTableThunks+NumVTableThunks,
2244 this->VTableThunks.get());
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002245 std::sort(this->VTableThunks.get(),
2246 this->VTableThunks.get() + NumVTableThunks,
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00002247 [](const VTableLayout::VTableThunkTy &LHS,
2248 const VTableLayout::VTableThunkTy &RHS) {
2249 assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2250 "Different thunks should have unique indices!");
2251 return LHS.first < RHS.first;
2252 });
Peter Collingbournecfd23562011-09-26 01:57:12 +00002253}
2254
Benjamin Kramere2980632012-04-14 14:13:43 +00002255VTableLayout::~VTableLayout() { }
Peter Collingbournecfd23562011-09-26 01:57:12 +00002256
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002257ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
Reid Klecknerb60a3d52013-12-20 23:58:52 +00002258 : VTableContextBase(/*MS=*/false) {}
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002259
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002260ItaniumVTableContext::~ItaniumVTableContext() {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002261 llvm::DeleteContainerSeconds(VTableLayouts);
2262}
2263
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002264uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002265 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2266 if (I != MethodVTableIndices.end())
2267 return I->second;
2268
2269 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2270
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002271 computeVTableRelatedInformation(RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002272
2273 I = MethodVTableIndices.find(GD);
2274 assert(I != MethodVTableIndices.end() && "Did not find index!");
2275 return I->second;
2276}
2277
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002278CharUnits
2279ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2280 const CXXRecordDecl *VBase) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002281 ClassPairTy ClassPair(RD, VBase);
2282
2283 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2284 VirtualBaseClassOffsetOffsets.find(ClassPair);
2285 if (I != VirtualBaseClassOffsetOffsets.end())
2286 return I->second;
2287
2288 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2289 BaseSubobject(RD, CharUnits::Zero()),
2290 /*BaseIsVirtual=*/false,
2291 /*OffsetInLayoutClass=*/CharUnits::Zero());
2292
2293 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2294 Builder.getVBaseOffsetOffsets().begin(),
2295 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2296 // Insert all types.
2297 ClassPairTy ClassPair(RD, I->first);
2298
2299 VirtualBaseClassOffsetOffsets.insert(
2300 std::make_pair(ClassPair, I->second));
2301 }
2302
2303 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2304 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2305
2306 return I->second;
2307}
2308
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002309static VTableLayout *CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002310 SmallVector<VTableLayout::VTableThunkTy, 1>
2311 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Peter Collingbournecfd23562011-09-26 01:57:12 +00002312
2313 return new VTableLayout(Builder.getNumVTableComponents(),
2314 Builder.vtable_component_begin(),
2315 VTableThunks.size(),
2316 VTableThunks.data(),
Timur Iskhodzhanov52b8a052013-01-21 13:02:41 +00002317 Builder.getAddressPoints(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002318 /*IsMicrosoftABI=*/false);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002319}
2320
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002321void
2322ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002323 const VTableLayout *&Entry = VTableLayouts[RD];
2324
2325 // Check if we've computed this information before.
2326 if (Entry)
2327 return;
2328
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002329 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2330 /*MostDerivedClassIsVirtual=*/0, RD);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002331 Entry = CreateVTableLayout(Builder);
2332
Timur Iskhodzhanov05e36702013-06-05 14:05:50 +00002333 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2334 Builder.vtable_indices_end());
2335
Peter Collingbournecfd23562011-09-26 01:57:12 +00002336 // Add the known thunks.
2337 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2338
2339 // If we don't have the vbase information for this class, insert it.
2340 // getVirtualBaseOffsetOffset will compute it separately without computing
2341 // the rest of the vtable related information.
2342 if (!RD->getNumVBases())
2343 return;
2344
Timur Iskhodzhanov7f55a452013-07-02 16:00:40 +00002345 const CXXRecordDecl *VBase =
2346 RD->vbases_begin()->getType()->getAsCXXRecordDecl();
Peter Collingbournecfd23562011-09-26 01:57:12 +00002347
2348 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2349 return;
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002350
2351 for (ItaniumVTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator
2352 I = Builder.getVBaseOffsetOffsets().begin(),
2353 E = Builder.getVBaseOffsetOffsets().end();
2354 I != E; ++I) {
Peter Collingbournecfd23562011-09-26 01:57:12 +00002355 // Insert all types.
2356 ClassPairTy ClassPair(RD, I->first);
2357
2358 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2359 }
2360}
2361
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +00002362VTableLayout *ItaniumVTableContext::createConstructionVTableLayout(
2363 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2364 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2365 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2366 MostDerivedClassIsVirtual, LayoutClass);
Peter Collingbournecfd23562011-09-26 01:57:12 +00002367 return CreateVTableLayout(Builder);
2368}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002369
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002370namespace {
2371
2372// Vtables in the Microsoft ABI are different from the Itanium ABI.
2373//
2374// The main differences are:
2375// 1. Separate vftable and vbtable.
2376//
2377// 2. Each subobject with a vfptr gets its own vftable rather than an address
2378// point in a single vtable shared between all the subobjects.
2379// Each vftable is represented by a separate section and virtual calls
2380// must be done using the vftable which has a slot for the function to be
2381// called.
2382//
2383// 3. Virtual method definitions expect their 'this' parameter to point to the
2384// first vfptr whose table provides a compatible overridden method. In many
2385// cases, this permits the original vf-table entry to directly call
2386// the method instead of passing through a thunk.
2387//
2388// A compatible overridden method is one which does not have a non-trivial
2389// covariant-return adjustment.
2390//
2391// The first vfptr is the one with the lowest offset in the complete-object
2392// layout of the defining class, and the method definition will subtract
2393// that constant offset from the parameter value to get the real 'this'
2394// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2395// function defined in a virtual base is overridden in a more derived
2396// virtual base and these bases have a reverse order in the complete
2397// object), the vf-table may require a this-adjustment thunk.
2398//
2399// 4. vftables do not contain new entries for overrides that merely require
2400// this-adjustment. Together with #3, this keeps vf-tables smaller and
2401// eliminates the need for this-adjustment thunks in many cases, at the cost
2402// of often requiring redundant work to adjust the "this" pointer.
2403//
2404// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2405// Vtordisps are emitted into the class layout if a class has
2406// a) a user-defined ctor/dtor
2407// and
2408// b) a method overriding a method in a virtual base.
2409
2410class VFTableBuilder {
2411public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002412 typedef MicrosoftVTableContext::MethodVFTableLocation MethodVFTableLocation;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002413
2414 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2415 MethodVFTableLocationsTy;
2416
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00002417 typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
2418 method_locations_range;
2419
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002420private:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002421 /// VTables - Global vtable information.
2422 MicrosoftVTableContext &VTables;
2423
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002424 /// Context - The ASTContext which we will use for layout information.
2425 ASTContext &Context;
2426
2427 /// MostDerivedClass - The most derived class for which we're building this
2428 /// vtable.
2429 const CXXRecordDecl *MostDerivedClass;
2430
2431 const ASTRecordLayout &MostDerivedClassLayout;
2432
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002433 const VPtrInfo &WhichVFPtr;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002434
2435 /// FinalOverriders - The final overriders of the most derived class.
2436 const FinalOverriders Overriders;
2437
2438 /// Components - The components of the vftable being built.
2439 SmallVector<VTableComponent, 64> Components;
2440
2441 MethodVFTableLocationsTy MethodVFTableLocations;
2442
2443 /// MethodInfo - Contains information about a method in a vtable.
2444 /// (Used for computing 'this' pointer adjustment thunks.
2445 struct MethodInfo {
2446 /// VBTableIndex - The nonzero index in the vbtable that
2447 /// this method's base has, or zero.
2448 const uint64_t VBTableIndex;
2449
2450 /// VFTableIndex - The index in the vftable that this method has.
2451 const uint64_t VFTableIndex;
2452
2453 /// Shadowed - Indicates if this vftable slot is shadowed by
2454 /// a slot for a covariant-return override. If so, it shouldn't be printed
2455 /// or used for vcalls in the most derived class.
2456 bool Shadowed;
2457
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002458 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex)
2459 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002460 Shadowed(false) {}
2461
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002462 MethodInfo() : VBTableIndex(0), VFTableIndex(0), Shadowed(false) {}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002463 };
2464
2465 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2466
2467 /// MethodInfoMap - The information for all methods in the vftable we're
2468 /// currently building.
2469 MethodInfoMapTy MethodInfoMap;
2470
2471 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2472
2473 /// VTableThunks - The thunks by vftable index in the vftable currently being
2474 /// built.
2475 VTableThunksMapTy VTableThunks;
2476
2477 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2478 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2479
2480 /// Thunks - A map that contains all the thunks needed for all methods in the
2481 /// most derived class for which the vftable is currently being built.
2482 ThunksMapTy Thunks;
2483
2484 /// AddThunk - Add a thunk for the given method.
2485 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2486 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2487
2488 // Check if we have this thunk already.
2489 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
2490 ThunksVector.end())
2491 return;
2492
2493 ThunksVector.push_back(Thunk);
2494 }
2495
2496 /// ComputeThisOffset - Returns the 'this' argument offset for the given
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002497 /// method, relative to the beginning of the MostDerivedClass.
2498 CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002499
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002500 void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2501 CharUnits ThisOffset, ThisAdjustment &TA);
2502
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002503 /// AddMethod - Add a single virtual member function to the vftable
2504 /// components vector.
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002505 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002506 if (!TI.isEmpty()) {
2507 VTableThunks[Components.size()] = TI;
2508 AddThunk(MD, TI);
2509 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002510 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002511 assert(TI.Return.isEmpty() &&
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002512 "Destructor can't have return adjustment!");
2513 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2514 } else {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002515 Components.push_back(VTableComponent::MakeFunction(MD));
2516 }
2517 }
2518
Reid Kleckner558cab22013-12-27 19:45:53 +00002519 bool NeedsReturnAdjustingThunk(const CXXMethodDecl *MD);
Reid Kleckner604c8b42013-12-27 19:43:59 +00002520
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002521 /// AddMethods - Add the methods of this base subobject and the relevant
2522 /// subbases to the vftable we're currently laying out.
2523 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2524 const CXXRecordDecl *LastVBase,
2525 BasesSetVectorTy &VisitedBases);
2526
2527 void LayoutVFTable() {
2528 // FIXME: add support for RTTI when we have proper LLVM support for symbols
2529 // pointing to the middle of a section.
2530
2531 BasesSetVectorTy VisitedBases;
2532 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, 0,
2533 VisitedBases);
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002534 assert(Components.size() && "vftable can't be empty");
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002535
2536 assert(MethodVFTableLocations.empty());
2537 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
2538 E = MethodInfoMap.end(); I != E; ++I) {
2539 const CXXMethodDecl *MD = I->first;
2540 const MethodInfo &MI = I->second;
2541 // Skip the methods that the MostDerivedClass didn't override
2542 // and the entries shadowed by return adjusting thunks.
2543 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2544 continue;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002545 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2546 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002547 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2548 MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
2549 } else {
2550 MethodVFTableLocations[MD] = Loc;
2551 }
2552 }
2553 }
2554
2555 void ErrorUnsupported(StringRef Feature, SourceLocation Location) {
2556 clang::DiagnosticsEngine &Diags = Context.getDiagnostics();
2557 unsigned DiagID = Diags.getCustomDiagID(
2558 DiagnosticsEngine::Error, "v-table layout for %0 is not supported yet");
2559 Diags.Report(Context.getFullLoc(Location), DiagID) << Feature;
2560 }
2561
2562public:
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002563 VFTableBuilder(MicrosoftVTableContext &VTables,
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002564 const CXXRecordDecl *MostDerivedClass, const VPtrInfo *Which)
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002565 : VTables(VTables),
2566 Context(MostDerivedClass->getASTContext()),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002567 MostDerivedClass(MostDerivedClass),
2568 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002569 WhichVFPtr(*Which),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002570 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2571 LayoutVFTable();
2572
2573 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00002574 dumpLayout(llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002575 }
2576
2577 uint64_t getNumThunks() const { return Thunks.size(); }
2578
2579 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2580
2581 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2582
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00002583 method_locations_range vtable_locations() const {
2584 return method_locations_range(MethodVFTableLocations.begin(),
2585 MethodVFTableLocations.end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002586 }
2587
2588 uint64_t getNumVTableComponents() const { return Components.size(); }
2589
2590 const VTableComponent *vtable_component_begin() const {
2591 return Components.begin();
2592 }
2593
2594 const VTableComponent *vtable_component_end() const {
2595 return Components.end();
2596 }
2597
2598 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2599 return VTableThunks.begin();
2600 }
2601
2602 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2603 return VTableThunks.end();
2604 }
2605
2606 void dumpLayout(raw_ostream &);
2607};
2608
Reid Klecknerb40a27d2014-01-03 00:14:35 +00002609} // end namespace
2610
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002611/// InitialOverriddenDefinitionCollector - Finds the set of least derived bases
2612/// that define the given method.
2613struct InitialOverriddenDefinitionCollector {
2614 BasesSetVectorTy Bases;
2615 OverriddenMethodsSetTy VisitedOverriddenMethods;
2616
2617 bool visit(const CXXMethodDecl *OverriddenMD) {
2618 if (OverriddenMD->size_overridden_methods() == 0)
2619 Bases.insert(OverriddenMD->getParent());
2620 // Don't recurse on this method if we've already collected it.
2621 return VisitedOverriddenMethods.insert(OverriddenMD);
2622 }
2623};
2624
2625static bool BaseInSet(const CXXBaseSpecifier *Specifier,
2626 CXXBasePath &Path, void *BasesSet) {
2627 BasesSetVectorTy *Bases = (BasesSetVectorTy *)BasesSet;
2628 return Bases->count(Specifier->getType()->getAsCXXRecordDecl());
2629}
2630
2631CharUnits
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002632VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002633 InitialOverriddenDefinitionCollector Collector;
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002634 visitAllOverriddenMethods(Overrider.Method, Collector);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002635
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002636 // If there are no overrides then 'this' is located
2637 // in the base that defines the method.
2638 if (Collector.Bases.size() == 0)
2639 return Overrider.Offset;
2640
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002641 CXXBasePaths Paths;
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002642 Overrider.Method->getParent()->lookupInBases(BaseInSet, &Collector.Bases,
2643 Paths);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002644
2645 // This will hold the smallest this offset among overridees of MD.
2646 // This implies that an offset of a non-virtual base will dominate an offset
2647 // of a virtual base to potentially reduce the number of thunks required
2648 // in the derived classes that inherit this method.
2649 CharUnits Ret;
2650 bool First = true;
2651
2652 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
2653 I != E; ++I) {
2654 const CXXBasePath &Path = (*I);
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002655 CharUnits ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002656 CharUnits LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002657
2658 // For each path from the overrider to the parents of the overridden methods,
2659 // traverse the path, calculating the this offset in the most derived class.
2660 for (int J = 0, F = Path.size(); J != F; ++J) {
2661 const CXXBasePathElement &Element = Path[J];
2662 QualType CurTy = Element.Base->getType();
2663 const CXXRecordDecl *PrevRD = Element.Class,
2664 *CurRD = CurTy->getAsCXXRecordDecl();
2665 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2666
2667 if (Element.Base->isVirtual()) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002668 LastVBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(CurRD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002669 if (Overrider.Method->getParent() == PrevRD) {
2670 // This one's interesting. If the final overrider is in a vbase B of the
2671 // most derived class and it overrides a method of the B's own vbase A,
2672 // it uses A* as "this". In its prologue, it can cast A* to B* with
2673 // a static offset. This offset is used regardless of the actual
2674 // offset of A from B in the most derived class, requiring an
2675 // this-adjusting thunk in the vftable if A and B are laid out
2676 // differently in the most derived class.
2677 ThisOffset += Layout.getVBaseClassOffset(CurRD);
2678 } else {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002679 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002680 }
2681 } else {
2682 ThisOffset += Layout.getBaseClassOffset(CurRD);
2683 }
2684 }
2685
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002686 if (isa<CXXDestructorDecl>(Overrider.Method)) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002687 if (LastVBaseOffset.isZero()) {
2688 // If a "Base" class has at least one non-virtual base with a virtual
2689 // destructor, the "Base" virtual destructor will take the address
2690 // of the "Base" subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002691 ThisOffset = Overrider.Offset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002692 } else {
2693 // A virtual destructor of a virtual base takes the address of the
2694 // virtual base subobject as the "this" argument.
Timur Iskhodzhanov3a9ac932014-03-04 18:17:38 +00002695 ThisOffset = LastVBaseOffset;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002696 }
2697 }
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +00002698
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002699 if (Ret > ThisOffset || First) {
2700 First = false;
2701 Ret = ThisOffset;
2702 }
2703 }
2704
2705 assert(!First && "Method not found in the given subobject?");
2706 return Ret;
2707}
2708
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002709void VFTableBuilder::CalculateVtordispAdjustment(
2710 FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2711 ThisAdjustment &TA) {
2712 const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2713 MostDerivedClassLayout.getVBaseOffsetsMap();
2714 const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002715 VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002716 assert(VBaseMapEntry != VBaseMap.end());
2717
2718 // Check if we need a vtordisp adjustment at all.
2719 if (!VBaseMapEntry->second.hasVtorDisp())
2720 return;
2721
2722 CharUnits VFPtrVBaseOffset = VBaseMapEntry->second.VBaseOffset;
2723 // The implicit vtordisp field is located right before the vbase.
2724 TA.Virtual.Microsoft.VtordispOffset =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002725 (VFPtrVBaseOffset - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002726
2727 // If the final overrider is defined in either:
2728 // - the most derived class or its non-virtual base or
2729 // - the same vbase as the initial declaration,
2730 // a simple vtordisp thunk will suffice.
2731 const CXXRecordDecl *OverriderRD = Overrider.Method->getParent();
2732 if (OverriderRD == MostDerivedClass)
2733 return;
2734
2735 const CXXRecordDecl *OverriderVBase =
2736 ComputeBaseOffset(Context, OverriderRD, MostDerivedClass).VirtualBase;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002737 if (!OverriderVBase || OverriderVBase == WhichVFPtr.getVBaseWithVPtr())
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002738 return;
2739
2740 // Otherwise, we need to do use the dynamic offset of the final overrider
2741 // in order to get "this" adjustment right.
2742 TA.Virtual.Microsoft.VBPtrOffset =
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002743 (VFPtrVBaseOffset + WhichVFPtr.NonVirtualOffset -
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002744 MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2745 TA.Virtual.Microsoft.VBOffsetOffset =
2746 Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
2747 VTables.getVBTableIndex(MostDerivedClass, OverriderVBase);
2748
2749 TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
2750}
2751
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002752static void GroupNewVirtualOverloads(
2753 const CXXRecordDecl *RD,
2754 SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
2755 // Put the virtual methods into VirtualMethods in the proper order:
2756 // 1) Group overloads by declaration name. New groups are added to the
2757 // vftable in the order of their first declarations in this class
Reid Kleckner6701de22014-02-19 22:06:10 +00002758 // (including overrides and non-virtual methods).
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002759 // 2) In each group, new overloads appear in the reverse order of declaration.
2760 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
2761 SmallVector<MethodGroup, 10> Groups;
2762 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
2763 VisitedGroupIndicesTy VisitedGroupIndices;
Aaron Ballman2b124d12014-03-13 16:36:16 +00002764 for (const auto *MD : RD->methods()) {
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002765 VisitedGroupIndicesTy::iterator J;
2766 bool Inserted;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002767 std::tie(J, Inserted) = VisitedGroupIndices.insert(
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002768 std::make_pair(MD->getDeclName(), Groups.size()));
2769 if (Inserted)
Reid Kleckner6701de22014-02-19 22:06:10 +00002770 Groups.push_back(MethodGroup());
Aaron Ballman2b124d12014-03-13 16:36:16 +00002771 if (MD->isVirtual())
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002772 Groups[J->second].push_back(MD);
2773 }
2774
2775 for (unsigned I = 0, E = Groups.size(); I != E; ++I)
2776 VirtualMethods.append(Groups[I].rbegin(), Groups[I].rend());
2777}
2778
Reid Kleckner604c8b42013-12-27 19:43:59 +00002779/// We need a return adjusting thunk for this method if its return type is
2780/// not trivially convertible to the return type of any of its overridden
2781/// methods.
2782bool VFTableBuilder::NeedsReturnAdjustingThunk(const CXXMethodDecl *MD) {
2783 OverriddenMethodsSetTy OverriddenMethods;
2784 ComputeAllOverriddenMethods(MD, OverriddenMethods);
2785 for (OverriddenMethodsSetTy::iterator I = OverriddenMethods.begin(),
2786 E = OverriddenMethods.end();
2787 I != E; ++I) {
2788 const CXXMethodDecl *OverriddenMD = *I;
2789 BaseOffset Adjustment =
2790 ComputeReturnAdjustmentBaseOffset(Context, MD, OverriddenMD);
2791 if (!Adjustment.isEmpty())
2792 return true;
2793 }
2794 return false;
2795}
2796
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002797static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
2798 for (const auto &B : RD->bases()) {
2799 if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
2800 return true;
2801 }
2802 return false;
2803}
2804
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002805void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
2806 const CXXRecordDecl *LastVBase,
2807 BasesSetVectorTy &VisitedBases) {
2808 const CXXRecordDecl *RD = Base.getBase();
2809 if (!RD->isPolymorphic())
2810 return;
2811
2812 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2813
2814 // See if this class expands a vftable of the base we look at, which is either
2815 // the one defined by the vfptr base path or the primary base of the current class.
2816 const CXXRecordDecl *NextBase = 0, *NextLastVBase = LastVBase;
2817 CharUnits NextBaseOffset;
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002818 if (BaseDepth < WhichVFPtr.PathToBaseWithVPtr.size()) {
2819 NextBase = WhichVFPtr.PathToBaseWithVPtr[BaseDepth];
Timur Iskhodzhanovdd0a27662014-03-26 08:12:53 +00002820 if (isDirectVBase(NextBase, RD)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002821 NextLastVBase = NextBase;
2822 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
2823 } else {
2824 NextBaseOffset =
2825 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
2826 }
2827 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
2828 assert(!Layout.isPrimaryBaseVirtual() &&
2829 "No primary virtual bases in this ABI");
2830 NextBase = PrimaryBase;
2831 NextBaseOffset = Base.getBaseOffset();
2832 }
2833
2834 if (NextBase) {
2835 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
2836 NextLastVBase, VisitedBases);
2837 if (!VisitedBases.insert(NextBase))
2838 llvm_unreachable("Found a duplicate primary base!");
2839 }
2840
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002841 SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
2842 // Put virtual methods in the proper order.
2843 GroupNewVirtualOverloads(RD, VirtualMethods);
2844
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002845 // Now go through all virtual member functions and add them to the current
2846 // vftable. This is done by
2847 // - replacing overridden methods in their existing slots, as long as they
2848 // don't require return adjustment; calculating This adjustment if needed.
2849 // - adding new slots for methods of the current base not present in any
2850 // sub-bases;
2851 // - adding new slots for methods that require Return adjustment.
2852 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
Timur Iskhodzhanov20df98c2013-10-06 15:31:37 +00002853 for (unsigned I = 0, E = VirtualMethods.size(); I != E; ++I) {
2854 const CXXMethodDecl *MD = VirtualMethods[I];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002855
2856 FinalOverriders::OverriderInfo Overrider =
2857 Overriders.getOverrider(MD, Base.getBaseOffset());
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002858 const CXXMethodDecl *OverriderMD = Overrider.Method;
2859 const CXXMethodDecl *OverriddenMD =
2860 FindNearestOverriddenMethod(MD, VisitedBases);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002861
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002862 ThisAdjustment ThisAdjustmentOffset;
2863 bool ReturnAdjustingThunk = false;
2864 CharUnits ThisOffset = ComputeThisOffset(Overrider);
2865 ThisAdjustmentOffset.NonVirtual =
2866 (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
2867 if ((OverriddenMD || OverriderMD != MD) &&
2868 WhichVFPtr.getVBaseWithVPtr())
2869 CalculateVtordispAdjustment(Overrider, ThisOffset, ThisAdjustmentOffset);
2870
2871 if (OverriddenMD) {
2872 // If MD overrides anything in this vftable, we need to update the entries.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002873 MethodInfoMapTy::iterator OverriddenMDIterator =
2874 MethodInfoMap.find(OverriddenMD);
2875
2876 // If the overridden method went to a different vftable, skip it.
2877 if (OverriddenMDIterator == MethodInfoMap.end())
2878 continue;
2879
2880 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
2881
Reid Kleckner604c8b42013-12-27 19:43:59 +00002882 if (!NeedsReturnAdjustingThunk(MD)) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002883 // No return adjustment needed - just replace the overridden method info
2884 // with the current info.
2885 MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
2886 OverriddenMethodInfo.VFTableIndex);
2887 MethodInfoMap.erase(OverriddenMDIterator);
2888
2889 assert(!MethodInfoMap.count(MD) &&
2890 "Should not have method info for this method yet!");
2891 MethodInfoMap.insert(std::make_pair(MD, MI));
2892 continue;
Reid Kleckner31a9f742013-12-27 20:29:16 +00002893 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002894
Reid Kleckner31a9f742013-12-27 20:29:16 +00002895 // In case we need a return adjustment, we'll add a new slot for
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002896 // the overrider. Mark the overriden method as shadowed by the new slot.
Reid Kleckner31a9f742013-12-27 20:29:16 +00002897 OverriddenMethodInfo.Shadowed = true;
Reid Kleckner31a9f742013-12-27 20:29:16 +00002898
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002899 // Force a special name mangling for a return-adjusting thunk
2900 // unless the method is the final overrider without this adjustment.
2901 ReturnAdjustingThunk =
2902 !(MD == OverriderMD && ThisAdjustmentOffset.isEmpty());
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002903 } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002904 MD->size_overridden_methods()) {
2905 // Skip methods that don't belong to the vftable of the current class,
2906 // e.g. each method that wasn't seen in any of the visited sub-bases
2907 // but overrides multiple methods of other sub-bases.
2908 continue;
2909 }
2910
2911 // If we got here, MD is a method not seen in any of the sub-bases or
2912 // it requires return adjustment. Insert the method info for this method.
2913 unsigned VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002914 LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
Timur Iskhodzhanov8b142422013-10-22 14:50:20 +00002915 MethodInfo MI(VBIndex, Components.size());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002916
2917 assert(!MethodInfoMap.count(MD) &&
2918 "Should not have method info for this method yet!");
2919 MethodInfoMap.insert(std::make_pair(MD, MI));
2920
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002921 // Check if this overrider needs a return adjustment.
2922 // We don't want to do this for pure virtual member functions.
2923 BaseOffset ReturnAdjustmentOffset;
2924 ReturnAdjustment ReturnAdjustment;
2925 if (!OverriderMD->isPure()) {
2926 ReturnAdjustmentOffset =
2927 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
2928 }
2929 if (!ReturnAdjustmentOffset.isEmpty()) {
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002930 ReturnAdjustingThunk = true;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002931 ReturnAdjustment.NonVirtual =
2932 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
2933 if (ReturnAdjustmentOffset.VirtualBase) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002934 const ASTRecordLayout &DerivedLayout =
2935 Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
2936 ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
2937 DerivedLayout.getVBPtrOffset().getQuantity();
2938 ReturnAdjustment.Virtual.Microsoft.VBIndex =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00002939 VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
2940 ReturnAdjustmentOffset.VirtualBase);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002941 }
2942 }
2943
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002944 AddMethod(OverriderMD, ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002945 ReturnAdjustingThunk ? MD : 0));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002946 }
2947}
2948
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002949static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
2950 for (VPtrInfo::BasePath::const_reverse_iterator I = Path.rbegin(),
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002951 E = Path.rend(); I != E; ++I) {
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00002952 Out << "'";
2953 (*I)->printQualifiedName(Out);
2954 Out << "' in ";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002955 }
2956}
2957
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002958static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
2959 bool ContinueFirstLine) {
2960 const ReturnAdjustment &R = TI.Return;
2961 bool Multiline = false;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002962 const char *LinePrefix = "\n ";
2963 if (!R.isEmpty() || TI.Method) {
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002964 if (!ContinueFirstLine)
2965 Out << LinePrefix;
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002966 Out << "[return adjustment (to type '"
2967 << TI.Method->getReturnType().getCanonicalType().getAsString()
2968 << "'): ";
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002969 if (R.Virtual.Microsoft.VBPtrOffset)
2970 Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
2971 if (R.Virtual.Microsoft.VBIndex)
2972 Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
2973 Out << R.NonVirtual << " non-virtual]";
2974 Multiline = true;
2975 }
2976
2977 const ThisAdjustment &T = TI.This;
2978 if (!T.isEmpty()) {
2979 if (Multiline || !ContinueFirstLine)
2980 Out << LinePrefix;
2981 Out << "[this adjustment: ";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002982 if (!TI.This.Virtual.isEmpty()) {
2983 assert(T.Virtual.Microsoft.VtordispOffset < 0);
2984 Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
2985 if (T.Virtual.Microsoft.VBPtrOffset) {
2986 Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
Timur Iskhodzhanova8957582014-03-07 09:34:59 +00002987 << " to the left,";
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002988 assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
2989 Out << LinePrefix << " vboffset at "
2990 << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
2991 }
2992 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00002993 Out << T.NonVirtual << " non-virtual]";
2994 }
2995}
2996
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002997void VFTableBuilder::dumpLayout(raw_ostream &Out) {
2998 Out << "VFTable for ";
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00002999 PrintBasePath(WhichVFPtr.PathToBaseWithVPtr, Out);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003000 Out << "'";
3001 MostDerivedClass->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003002 Out << "' (" << Components.size()
3003 << (Components.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003004
3005 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3006 Out << llvm::format("%4d | ", I);
3007
3008 const VTableComponent &Component = Components[I];
3009
3010 // Dump the component.
3011 switch (Component.getKind()) {
3012 case VTableComponent::CK_RTTI:
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003013 Component.getRTTIDecl()->printQualifiedName(Out);
3014 Out << " RTTI";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003015 break;
3016
3017 case VTableComponent::CK_FunctionPointer: {
3018 const CXXMethodDecl *MD = Component.getFunctionDecl();
3019
Reid Kleckner604c8b42013-12-27 19:43:59 +00003020 // FIXME: Figure out how to print the real thunk type, since they can
3021 // differ in the return type.
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003022 std::string Str = PredefinedExpr::ComputeName(
3023 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3024 Out << Str;
3025 if (MD->isPure())
3026 Out << " [pure]";
3027
3028 if (MD->isDeleted()) {
3029 ErrorUnsupported("deleted methods", MD->getLocation());
3030 Out << " [deleted]";
3031 }
3032
3033 ThunkInfo Thunk = VTableThunks.lookup(I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003034 if (!Thunk.isEmpty())
3035 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003036
3037 break;
3038 }
3039
3040 case VTableComponent::CK_DeletingDtorPointer: {
3041 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3042
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003043 DD->printQualifiedName(Out);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003044 Out << "() [scalar deleting]";
3045
3046 if (DD->isPure())
3047 Out << " [pure]";
3048
3049 ThunkInfo Thunk = VTableThunks.lookup(I);
3050 if (!Thunk.isEmpty()) {
3051 assert(Thunk.Return.isEmpty() &&
3052 "No return adjustment needed for destructors!");
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003053 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003054 }
3055
3056 break;
3057 }
3058
3059 default:
3060 DiagnosticsEngine &Diags = Context.getDiagnostics();
3061 unsigned DiagID = Diags.getCustomDiagID(
3062 DiagnosticsEngine::Error,
3063 "Unexpected vftable component type %0 for component number %1");
3064 Diags.Report(MostDerivedClass->getLocation(), DiagID)
3065 << I << Component.getKind();
3066 }
3067
3068 Out << '\n';
3069 }
3070
3071 Out << '\n';
3072
3073 if (!Thunks.empty()) {
3074 // We store the method names in a map to get a stable order.
3075 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3076
3077 for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
3078 I != E; ++I) {
3079 const CXXMethodDecl *MD = I->first;
3080 std::string MethodName = PredefinedExpr::ComputeName(
3081 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3082
3083 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3084 }
3085
3086 for (std::map<std::string, const CXXMethodDecl *>::const_iterator
3087 I = MethodNamesAndDecls.begin(),
3088 E = MethodNamesAndDecls.end();
3089 I != E; ++I) {
3090 const std::string &MethodName = I->first;
3091 const CXXMethodDecl *MD = I->second;
3092
3093 ThunkInfoVectorTy ThunksVector = Thunks[MD];
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00003094 std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003095 [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
3096 // Keep different thunks with the same adjustments in the order they
3097 // were put into the vector.
Benjamin Kramera741b8c2014-03-03 20:26:46 +00003098 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003099 });
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003100
3101 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3102 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3103
3104 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3105 const ThunkInfo &Thunk = ThunksVector[I];
3106
3107 Out << llvm::format("%4d | ", I);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003108 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003109 Out << '\n';
3110 }
3111
3112 Out << '\n';
3113 }
3114 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003115
3116 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003117}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003118
Reid Kleckner5f080942014-01-03 23:42:00 +00003119static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
3120 const llvm::ArrayRef<const CXXRecordDecl *> &B) {
3121 for (llvm::ArrayRef<const CXXRecordDecl *>::iterator I = B.begin(),
3122 E = B.end();
3123 I != E; ++I) {
3124 if (A.count(*I))
3125 return true;
3126 }
3127 return false;
3128}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003129
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003130static bool rebucketPaths(VPtrInfoVector &Paths);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003131
Reid Kleckner5f080942014-01-03 23:42:00 +00003132/// Produces MSVC-compatible vbtable data. The symbols produced by this
3133/// algorithm match those produced by MSVC 2012 and newer, which is different
3134/// from MSVC 2010.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003135///
3136/// MSVC 2012 appears to minimize the vbtable names using the following
3137/// algorithm. First, walk the class hierarchy in the usual order, depth first,
3138/// left to right, to find all of the subobjects which contain a vbptr field.
3139/// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3140/// record with a vbptr creates an initially empty path.
3141///
3142/// To combine paths from child nodes, the paths are compared to check for
3143/// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3144/// components in the same order. Each group of ambiguous paths is extended by
3145/// appending the class of the base from which it came. If the current class
3146/// node produced an ambiguous path, its path is extended with the current class.
3147/// After extending paths, MSVC again checks for ambiguity, and extends any
3148/// ambiguous path which wasn't already extended. Because each node yields an
3149/// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3150/// to produce an unambiguous set of paths.
3151///
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003152/// TODO: Presumably vftables use the same algorithm.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003153void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3154 const CXXRecordDecl *RD,
3155 VPtrInfoVector &Paths) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003156 assert(Paths.empty());
3157 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003158
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003159 // Base case: this subobject has its own vptr.
3160 if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
3161 Paths.push_back(new VPtrInfo(RD));
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003162
Reid Kleckner5f080942014-01-03 23:42:00 +00003163 // Recursive case: get all the vbtables from our bases and remove anything
3164 // that shares a virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003165 llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003166 for (const auto &B : RD->bases()) {
3167 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
3168 if (B.isVirtual() && VBasesSeen.count(Base))
Reid Kleckner5f080942014-01-03 23:42:00 +00003169 continue;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003170
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003171 if (!Base->isDynamicClass())
3172 continue;
Reid Kleckner5f080942014-01-03 23:42:00 +00003173
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003174 const VPtrInfoVector &BasePaths =
3175 ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3176
3177 for (VPtrInfoVector::const_iterator II = BasePaths.begin(),
3178 EE = BasePaths.end();
Reid Kleckner5f080942014-01-03 23:42:00 +00003179 II != EE; ++II) {
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003180 VPtrInfo *BaseInfo = *II;
Reid Kleckner5f080942014-01-03 23:42:00 +00003181
3182 // Don't include the path if it goes through a virtual base that we've
3183 // already included.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003184 if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
Reid Kleckner5f080942014-01-03 23:42:00 +00003185 continue;
3186
3187 // Copy the path and adjust it as necessary.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003188 VPtrInfo *P = new VPtrInfo(*BaseInfo);
Reid Kleckner5f080942014-01-03 23:42:00 +00003189
3190 // We mangle Base into the path if the path would've been ambiguous and it
3191 // wasn't already extended with Base.
3192 if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3193 P->NextBaseToMangle = Base;
3194
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003195 // Keep track of the full path.
3196 // FIXME: Why do we need this?
3197 P->PathToBaseWithVPtr.insert(P->PathToBaseWithVPtr.begin(), Base);
3198
3199 // Keep track of which derived class ultimately uses the vtable, and what
3200 // the full adjustment is from the MDC to this vtable. The adjustment is
Reid Kleckner5f080942014-01-03 23:42:00 +00003201 // captured by an optional vbase and a non-virtual offset.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003202 if (Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
3203 : Layout.getPrimaryBase()))
Reid Kleckner5f080942014-01-03 23:42:00 +00003204 P->ReusingBase = RD;
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003205 if (B.isVirtual())
Reid Kleckner5f080942014-01-03 23:42:00 +00003206 P->ContainingVBases.push_back(Base);
3207 else if (P->ContainingVBases.empty())
3208 P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3209
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003210 // Update the full offset in the MDC.
3211 P->FullOffsetInMDC = P->NonVirtualOffset;
3212 if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3213 P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3214
Reid Kleckner5f080942014-01-03 23:42:00 +00003215 Paths.push_back(P);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003216 }
3217
Timur Iskhodzhanov9ae7d3b2014-03-31 11:01:51 +00003218 if (B.isVirtual())
3219 VBasesSeen.insert(Base);
3220
Reid Kleckner5f080942014-01-03 23:42:00 +00003221 // After visiting any direct base, we've transitively visited all of its
3222 // morally virtual bases.
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003223 for (const auto &VB : Base->vbases())
3224 VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003225 }
3226
Reid Kleckner5f080942014-01-03 23:42:00 +00003227 // Sort the paths into buckets, and if any of them are ambiguous, extend all
3228 // paths in ambiguous buckets.
3229 bool Changed = true;
3230 while (Changed)
3231 Changed = rebucketPaths(Paths);
3232}
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003233
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003234static bool extendPath(VPtrInfo *P) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003235 if (P->NextBaseToMangle) {
3236 P->MangledPath.push_back(P->NextBaseToMangle);
3237 P->NextBaseToMangle = 0; // Prevent the path from being extended twice.
3238 return true;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003239 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003240 return false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003241}
3242
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003243static bool rebucketPaths(VPtrInfoVector &Paths) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003244 // What we're essentially doing here is bucketing together ambiguous paths.
3245 // Any bucket with more than one path in it gets extended by NextBase, which
3246 // is usually the direct base of the inherited the vbptr. This code uses a
3247 // sorted vector to implement a multiset to form the buckets. Note that the
3248 // ordering is based on pointers, but it doesn't change our output order. The
3249 // current algorithm is designed to match MSVC 2012's names.
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003250 VPtrInfoVector PathsSorted(Paths);
Benjamin Kramer15ae7832014-03-07 21:35:40 +00003251 std::sort(PathsSorted.begin(), PathsSorted.end(),
3252 [](const VPtrInfo *LHS, const VPtrInfo *RHS) {
3253 return LHS->MangledPath < RHS->MangledPath;
3254 });
Reid Kleckner5f080942014-01-03 23:42:00 +00003255 bool Changed = false;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003256 for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3257 // Scan forward to find the end of the bucket.
3258 size_t BucketStart = I;
3259 do {
3260 ++I;
Reid Kleckner5f080942014-01-03 23:42:00 +00003261 } while (I != E && PathsSorted[BucketStart]->MangledPath ==
3262 PathsSorted[I]->MangledPath);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003263
3264 // If this bucket has multiple paths, extend them all.
3265 if (I - BucketStart > 1) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003266 for (size_t II = BucketStart; II != I; ++II)
Reid Kleckner5f080942014-01-03 23:42:00 +00003267 Changed |= extendPath(PathsSorted[II]);
3268 assert(Changed && "no paths were extended to fix ambiguity");
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003269 }
3270 }
Reid Kleckner5f080942014-01-03 23:42:00 +00003271 return Changed;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003272}
3273
3274MicrosoftVTableContext::~MicrosoftVTableContext() {
Reid Kleckner33311282014-02-28 23:26:22 +00003275 llvm::DeleteContainerSeconds(VFPtrLocations);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003276 llvm::DeleteContainerSeconds(VFTableLayouts);
3277 llvm::DeleteContainerSeconds(VBaseInfo);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003278}
3279
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003280void MicrosoftVTableContext::computeVTableRelatedInformation(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003281 const CXXRecordDecl *RD) {
3282 assert(RD->isDynamicClass());
3283
3284 // Check if we've computed this information before.
3285 if (VFPtrLocations.count(RD))
3286 return;
3287
3288 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3289
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003290 VPtrInfoVector *VFPtrs = new VPtrInfoVector();
3291 computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3292 VFPtrLocations[RD] = VFPtrs;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003293
3294 MethodVFTableLocationsTy NewMethodLocations;
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003295 for (VPtrInfoVector::iterator I = VFPtrs->begin(), E = VFPtrs->end();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003296 I != E; ++I) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003297 VFTableBuilder Builder(*this, RD, *I);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003298
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003299 VFTableIdTy id(RD, (*I)->FullOffsetInMDC);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003300 assert(VFTableLayouts.count(id) == 0);
3301 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3302 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003303 VFTableLayouts[id] = new VTableLayout(
3304 Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
3305 VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003306 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00003307
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003308 for (const auto &Loc : Builder.vtable_locations()) {
3309 GlobalDecl GD = Loc.first;
3310 MethodVFTableLocation NewLoc = Loc.second;
Timur Iskhodzhanovba557022014-03-20 20:38:34 +00003311 auto M = NewMethodLocations.find(GD);
3312 if (M == NewMethodLocations.end() || NewLoc < M->second)
3313 NewMethodLocations[GD] = NewLoc;
3314 }
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003315 }
3316
3317 MethodVFTableLocations.insert(NewMethodLocations.begin(),
3318 NewMethodLocations.end());
3319 if (Context.getLangOpts().DumpVTableLayouts)
Reid Kleckner5bc6d0f2013-11-08 21:28:00 +00003320 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003321}
3322
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003323void MicrosoftVTableContext::dumpMethodLocations(
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003324 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3325 raw_ostream &Out) {
3326 // Compute the vtable indices for all the member functions.
3327 // Store them in a map keyed by the location so we'll get a sorted table.
3328 std::map<MethodVFTableLocation, std::string> IndicesMap;
3329 bool HasNonzeroOffset = false;
3330
3331 for (MethodVFTableLocationsTy::const_iterator I = NewMethods.begin(),
3332 E = NewMethods.end(); I != E; ++I) {
3333 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I->first.getDecl());
3334 assert(MD->isVirtual());
3335
3336 std::string MethodName = PredefinedExpr::ComputeName(
3337 PredefinedExpr::PrettyFunctionNoVirtual, MD);
3338
3339 if (isa<CXXDestructorDecl>(MD)) {
3340 IndicesMap[I->second] = MethodName + " [scalar deleting]";
3341 } else {
3342 IndicesMap[I->second] = MethodName;
3343 }
3344
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003345 if (!I->second.VFPtrOffset.isZero() || I->second.VBTableIndex != 0)
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003346 HasNonzeroOffset = true;
3347 }
3348
3349 // Print the vtable indices for all the member functions.
3350 if (!IndicesMap.empty()) {
3351 Out << "VFTable indices for ";
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00003352 Out << "'";
3353 RD->printQualifiedName(Out);
Timur Iskhodzhanov77764b62014-03-05 13:54:07 +00003354 Out << "' (" << IndicesMap.size()
3355 << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003356
3357 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3358 uint64_t LastVBIndex = 0;
3359 for (std::map<MethodVFTableLocation, std::string>::const_iterator
3360 I = IndicesMap.begin(),
3361 E = IndicesMap.end();
3362 I != E; ++I) {
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +00003363 CharUnits VFPtrOffset = I->first.VFPtrOffset;
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003364 uint64_t VBIndex = I->first.VBTableIndex;
3365 if (HasNonzeroOffset &&
3366 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3367 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3368 Out << " -- accessible via ";
3369 if (VBIndex)
3370 Out << "vbtable index " << VBIndex << ", ";
3371 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3372 LastVFPtrOffset = VFPtrOffset;
3373 LastVBIndex = VBIndex;
3374 }
3375
3376 uint64_t VTableIndex = I->first.Index;
3377 const std::string &MethodName = I->second;
3378 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3379 }
3380 Out << '\n';
3381 }
Timur Iskhodzhanov4fea4f92014-03-20 13:42:14 +00003382
3383 Out.flush();
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003384}
3385
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003386const VirtualBaseInfo *MicrosoftVTableContext::computeVBTableRelatedInformation(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003387 const CXXRecordDecl *RD) {
Reid Kleckner5f080942014-01-03 23:42:00 +00003388 VirtualBaseInfo *VBI;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003389
Reid Kleckner5f080942014-01-03 23:42:00 +00003390 {
3391 // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
3392 // as it may be modified and rehashed under us.
3393 VirtualBaseInfo *&Entry = VBaseInfo[RD];
3394 if (Entry)
3395 return Entry;
3396 Entry = VBI = new VirtualBaseInfo();
3397 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003398
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003399 computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003400
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003401 // First, see if the Derived class shared the vbptr with a non-virtual base.
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003402 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Timur Iskhodzhanov2c9341f2013-11-08 11:45:35 +00003403 if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003404 // If the Derived class shares the vbptr with a non-virtual base, the shared
3405 // virtual bases come first so that the layout is the same.
3406 const VirtualBaseInfo *BaseInfo =
3407 computeVBTableRelatedInformation(VBPtrBase);
Reid Kleckner5f080942014-01-03 23:42:00 +00003408 VBI->VBTableIndices.insert(BaseInfo->VBTableIndices.begin(),
3409 BaseInfo->VBTableIndices.end());
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003410 }
3411
3412 // New vbases are added to the end of the vbtable.
3413 // Skip the self entry and vbases visited in the non-virtual base, if any.
Reid Kleckner5f080942014-01-03 23:42:00 +00003414 unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
Timur Iskhodzhanov1523c612014-03-26 08:22:48 +00003415 for (const auto &VB : RD->vbases()) {
3416 const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
Reid Kleckner5f080942014-01-03 23:42:00 +00003417 if (!VBI->VBTableIndices.count(CurVBase))
3418 VBI->VBTableIndices[CurVBase] = VBTableIndex++;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003419 }
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003420
Reid Kleckner5f080942014-01-03 23:42:00 +00003421 return VBI;
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003422}
3423
3424unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
3425 const CXXRecordDecl *VBase) {
3426 const VirtualBaseInfo *VBInfo = computeVBTableRelatedInformation(Derived);
3427 assert(VBInfo->VBTableIndices.count(VBase));
3428 return VBInfo->VBTableIndices.find(VBase)->second;
3429}
3430
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003431const VPtrInfoVector &
Reid Klecknerb40a27d2014-01-03 00:14:35 +00003432MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003433 return computeVBTableRelatedInformation(RD)->VBPtrPaths;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003434}
3435
Reid Kleckner9c6e9e32014-02-27 19:40:09 +00003436const VPtrInfoVector &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003437MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003438 computeVTableRelatedInformation(RD);
3439
3440 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
Reid Klecknerd6f9b832014-02-27 22:51:43 +00003441 return *VFPtrLocations[RD];
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003442}
3443
3444const VTableLayout &
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003445MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
3446 CharUnits VFPtrOffset) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003447 computeVTableRelatedInformation(RD);
3448
3449 VFTableIdTy id(RD, VFPtrOffset);
3450 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3451 return *VFTableLayouts[id];
3452}
3453
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00003454const MicrosoftVTableContext::MethodVFTableLocation &
3455MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00003456 assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
3457 "Only use this method for virtual methods or dtors");
3458 if (isa<CXXDestructorDecl>(GD.getDecl()))
3459 assert(GD.getDtorType() == Dtor_Deleting);
3460
3461 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3462 if (I != MethodVFTableLocations.end())
3463 return I->second;
3464
3465 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3466
3467 computeVTableRelatedInformation(RD);
3468
3469 I = MethodVFTableLocations.find(GD);
3470 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3471 return I->second;
3472}