clang 24.0.0git
VTableBuilder.cpp
Go to the documentation of this file.
1//===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with generation of the layout of virtual tables.
10//
11//===----------------------------------------------------------------------===//
12
19#include "llvm/ADT/SetOperations.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/Support/Format.h"
23#include "llvm/Support/raw_ostream.h"
24#include <algorithm>
25#include <cstdio>
26
27using namespace clang;
28
29#define DUMP_OVERRIDERS 0
30
31namespace {
32
33/// BaseOffset - Represents an offset from a derived class to a direct or
34/// indirect base class.
35struct BaseOffset {
36 /// DerivedClass - The derived class.
37 const CXXRecordDecl *DerivedClass;
38
39 /// VirtualBase - If the path from the derived class to the base class
40 /// involves virtual base classes, this holds the declaration of the last
41 /// virtual base in this path (i.e. closest to the base class).
43
44 /// NonVirtualOffset - The offset from the derived class to the base class.
45 /// (Or the offset from the virtual base class to the base class, if the
46 /// path from the derived class to the base class involves a virtual base
47 /// class.
48 CharUnits NonVirtualOffset;
49
50 BaseOffset() : DerivedClass(nullptr), VirtualBase(nullptr),
51 NonVirtualOffset(CharUnits::Zero()) { }
52 BaseOffset(const CXXRecordDecl *DerivedClass,
53 const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
54 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
55 NonVirtualOffset(NonVirtualOffset) { }
56
57 bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
58};
59
60/// FinalOverriders - Contains the final overrider member functions for all
61/// member functions in the base subobjects of a class.
62class FinalOverriders {
63public:
64 /// OverriderInfo - Information about a final overrider.
65 struct OverriderInfo {
66 /// Method - The method decl of the overrider.
67 const CXXMethodDecl *Method;
68
69 /// VirtualBase - The virtual base class subobject of this overrider.
70 /// Note that this records the closest derived virtual base class subobject.
72
73 /// Offset - the base offset of the overrider's parent in the layout class.
74 CharUnits Offset;
75
76 OverriderInfo() : Method(nullptr), VirtualBase(nullptr),
77 Offset(CharUnits::Zero()) { }
78 };
79
80private:
81 /// MostDerivedClass - The most derived class for which the final overriders
82 /// are stored.
83 const CXXRecordDecl *MostDerivedClass;
84
85 /// MostDerivedClassOffset - If we're building final overriders for a
86 /// construction vtable, this holds the offset from the layout class to the
87 /// most derived class.
88 const CharUnits MostDerivedClassOffset;
89
90 /// LayoutClass - The class we're using for layout information. Will be
91 /// different than the most derived class if the final overriders are for a
92 /// construction vtable.
93 const CXXRecordDecl *LayoutClass;
94
95 ASTContext &Context;
96
97 /// MostDerivedClassLayout - the AST record layout of the most derived class.
98 const ASTRecordLayout &MostDerivedClassLayout;
99
100 /// MethodBaseOffsetPairTy - Uniquely identifies a member function
101 /// in a base subobject.
102 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
103
104 typedef llvm::DenseMap<MethodBaseOffsetPairTy,
105 OverriderInfo> OverridersMapTy;
106
107 /// OverridersMap - The final overriders for all virtual member functions of
108 /// all the base subobjects of the most derived class.
109 OverridersMapTy OverridersMap;
110
111 /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
112 /// as a record decl and a subobject number) and its offsets in the most
113 /// derived class as well as the layout class.
114 typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
115 CharUnits> SubobjectOffsetMapTy;
116
117 typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
118
119 /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
120 /// given base.
121 void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
122 CharUnits OffsetInLayoutClass,
123 SubobjectOffsetMapTy &SubobjectOffsets,
124 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
125 SubobjectCountMapTy &SubobjectCounts);
126
127 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
128
129 /// dump - dump the final overriders for a base subobject, and all its direct
130 /// and indirect base subobjects.
131 void dump(raw_ostream &Out, BaseSubobject Base,
132 VisitedVirtualBasesSetTy& VisitedVirtualBases);
133
134public:
135 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
136 CharUnits MostDerivedClassOffset,
137 const CXXRecordDecl *LayoutClass);
138
139 /// getOverrider - Get the final overrider for the given method declaration in
140 /// the subobject with the given base offset.
141 OverriderInfo getOverrider(const CXXMethodDecl *MD,
142 CharUnits BaseOffset) const {
143 assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
144 "Did not find overrider!");
145
146 return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
147 }
148
149 /// dump - dump the final overriders.
150 void dump() {
151 VisitedVirtualBasesSetTy VisitedVirtualBases;
152 dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
153 VisitedVirtualBases);
154 }
155
156};
157
158FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
159 CharUnits MostDerivedClassOffset,
160 const CXXRecordDecl *LayoutClass)
161 : MostDerivedClass(MostDerivedClass),
162 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
163 Context(MostDerivedClass->getASTContext()),
164 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
165
166 // Compute base offsets.
167 SubobjectOffsetMapTy SubobjectOffsets;
168 SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
169 SubobjectCountMapTy SubobjectCounts;
170 ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
171 /*IsVirtual=*/false,
172 MostDerivedClassOffset,
173 SubobjectOffsets, SubobjectLayoutClassOffsets,
174 SubobjectCounts);
175
176 // Get the final overriders.
177 CXXFinalOverriderMap FinalOverriders;
178 MostDerivedClass->getFinalOverriders(FinalOverriders);
179
180 for (const auto &Overrider : FinalOverriders) {
181 const CXXMethodDecl *MD = Overrider.first;
182 const OverridingMethods &Methods = Overrider.second;
183
184 for (const auto &M : Methods) {
185 unsigned SubobjectNumber = M.first;
186 assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
187 SubobjectNumber)) &&
188 "Did not find subobject offset!");
189
190 CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
191 SubobjectNumber)];
192
193 assert(M.second.size() == 1 && "Final overrider is not unique!");
194 const UniqueVirtualMethod &Method = M.second.front();
195
196 const CXXRecordDecl *OverriderRD = Method.Method->getParent();
197 assert(SubobjectLayoutClassOffsets.count(
198 std::make_pair(OverriderRD, Method.Subobject))
199 && "Did not find subobject offset!");
200 CharUnits OverriderOffset =
201 SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
202 Method.Subobject)];
203
204 OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
205 assert(!Overrider.Method && "Overrider should not exist yet!");
206
207 Overrider.Offset = OverriderOffset;
208 Overrider.Method = Method.Method;
209 Overrider.VirtualBase = Method.InVirtualSubobject;
210 }
211 }
212
213#if DUMP_OVERRIDERS
214 // And dump them (for now).
215 dump();
216#endif
217}
218
219static BaseOffset ComputeBaseOffset(const ASTContext &Context,
220 const CXXRecordDecl *DerivedRD,
221 const CXXBasePath &Path) {
222 CharUnits NonVirtualOffset = CharUnits::Zero();
223
224 unsigned NonVirtualStart = 0;
225 const CXXRecordDecl *VirtualBase = nullptr;
226
227 // First, look for the virtual base class.
228 for (int I = Path.size(), E = 0; I != E; --I) {
229 const CXXBasePathElement &Element = Path[I - 1];
230
231 if (Element.Base->isVirtual()) {
232 NonVirtualStart = I;
233 QualType VBaseType = Element.Base->getType();
234 VirtualBase = VBaseType->getAsCXXRecordDecl();
235 break;
236 }
237 }
238
239 // Now compute the non-virtual offset.
240 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
241 const CXXBasePathElement &Element = Path[I];
242
243 // Check the base class offset.
244 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
245
246 const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
247
248 NonVirtualOffset += Layout.getBaseClassOffset(Base);
249 }
250
251 // FIXME: This should probably use CharUnits or something. Maybe we should
252 // even change the base offsets in ASTRecordLayout to be specified in
253 // CharUnits.
254 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
255
256}
257
258static BaseOffset ComputeBaseOffset(const ASTContext &Context,
259 const CXXRecordDecl *BaseRD,
260 const CXXRecordDecl *DerivedRD) {
261 CXXBasePaths Paths(/*FindAmbiguities=*/false,
262 /*RecordPaths=*/true, /*DetectVirtual=*/false);
263
264 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
265 llvm_unreachable("Class must be derived from the passed in base class!");
266
267 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
268}
269
270static BaseOffset
271ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
272 const CXXMethodDecl *DerivedMD,
273 const CXXMethodDecl *BaseMD) {
274 const auto *BaseFT = BaseMD->getType()->castAs<FunctionType>();
275 const auto *DerivedFT = DerivedMD->getType()->castAs<FunctionType>();
276
277 // Canonicalize the return types.
278 CanQualType CanDerivedReturnType =
279 Context.getCanonicalType(DerivedFT->getReturnType());
280 CanQualType CanBaseReturnType =
281 Context.getCanonicalType(BaseFT->getReturnType());
282
283 assert(CanDerivedReturnType->getTypeClass() ==
284 CanBaseReturnType->getTypeClass() &&
285 "Types must have same type class!");
286
287 if (CanDerivedReturnType == CanBaseReturnType) {
288 // No adjustment needed.
289 return BaseOffset();
290 }
291
292 if (isa<ReferenceType>(CanDerivedReturnType)) {
293 CanDerivedReturnType =
294 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
295 CanBaseReturnType =
296 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
297 } else if (isa<PointerType>(CanDerivedReturnType)) {
298 CanDerivedReturnType =
299 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
300 CanBaseReturnType =
301 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
302 } else {
303 llvm_unreachable("Unexpected return type!");
304 }
305
306 // We need to compare unqualified types here; consider
307 // const T *Base::foo();
308 // T *Derived::foo();
309 if (CanDerivedReturnType.getUnqualifiedType() ==
310 CanBaseReturnType.getUnqualifiedType()) {
311 // No adjustment needed.
312 return BaseOffset();
313 }
314
315 const auto *DerivedRD =
316 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl())
317 ->getDefinitionOrSelf();
318
319 const auto *BaseRD =
320 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
321
322 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
323}
324
325void
326FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
327 CharUnits OffsetInLayoutClass,
328 SubobjectOffsetMapTy &SubobjectOffsets,
329 SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
330 SubobjectCountMapTy &SubobjectCounts) {
331 const CXXRecordDecl *RD = Base.getBase();
332
333 unsigned SubobjectNumber = 0;
334 if (!IsVirtual)
335 SubobjectNumber = ++SubobjectCounts[RD];
336
337 // Set up the subobject to offset mapping.
338 assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
339 && "Subobject offset already exists!");
340 assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
341 && "Subobject offset already exists!");
342
343 SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
344 SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
345 OffsetInLayoutClass;
346
347 // Traverse our bases.
348 for (const auto &B : RD->bases()) {
349 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
350
351 CharUnits BaseOffset;
352 CharUnits BaseOffsetInLayoutClass;
353 if (B.isVirtual()) {
354 // Check if we've visited this virtual base before.
355 if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
356 continue;
357
358 const ASTRecordLayout &LayoutClassLayout =
359 Context.getASTRecordLayout(LayoutClass);
360
361 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
362 BaseOffsetInLayoutClass =
363 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
364 } else {
365 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
366 CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
367
368 BaseOffset = Base.getBaseOffset() + Offset;
369 BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
370 }
371
372 ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
373 B.isVirtual(), BaseOffsetInLayoutClass,
374 SubobjectOffsets, SubobjectLayoutClassOffsets,
375 SubobjectCounts);
376 }
377}
378
379void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
380 VisitedVirtualBasesSetTy &VisitedVirtualBases) {
381 const CXXRecordDecl *RD = Base.getBase();
382 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
383
384 for (const auto &B : RD->bases()) {
385 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
386
387 // Ignore bases that don't have any virtual member functions.
388 if (!BaseDecl->isPolymorphic())
389 continue;
390
391 CharUnits BaseOffset;
392 if (B.isVirtual()) {
393 if (!VisitedVirtualBases.insert(BaseDecl).second) {
394 // We've visited this base before.
395 continue;
396 }
397
398 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
399 } else {
400 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
401 }
402
403 dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
404 }
405
406 Out << "Final overriders for (";
407 RD->printQualifiedName(Out);
408 Out << ", ";
409 Out << Base.getBaseOffset().getQuantity() << ")\n";
410
411 // Now dump the overriders for this base subobject.
412 for (const auto *MD : RD->methods()) {
414 continue;
415 MD = MD->getCanonicalDecl();
416
417 OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
418
419 Out << " ";
420 MD->printQualifiedName(Out);
421 Out << " - (";
422 Overrider.Method->printQualifiedName(Out);
423 Out << ", " << Overrider.Offset.getQuantity() << ')';
424
425 BaseOffset Offset;
426 if (!Overrider.Method->isPureVirtual())
427 Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
428
429 if (!Offset.isEmpty()) {
430 Out << " [ret-adj: ";
431 if (Offset.VirtualBase) {
432 Offset.VirtualBase->printQualifiedName(Out);
433 Out << " vbase, ";
434 }
435
436 Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
437 }
438
439 Out << "\n";
440 }
441}
442
443/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
444struct VCallOffsetMap {
445
446 typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
447
448 /// Offsets - Keeps track of methods and their offsets.
449 // FIXME: This should be a real map and not a vector.
451
452 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
453 /// can share the same vcall offset.
454 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
455 const CXXMethodDecl *RHS);
456
457public:
458 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
459 /// add was successful, or false if there was already a member function with
460 /// the same signature in the map.
461 bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
462
463 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
464 /// vtable address point) for the given virtual member function.
465 CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
466
467 // empty - Return whether the offset map is empty or not.
468 bool empty() const { return Offsets.empty(); }
469};
470
471static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
472 const CXXMethodDecl *RHS) {
473 const FunctionProtoType *LT =
475 const FunctionProtoType *RT =
477
478 // Fast-path matches in the canonical types.
479 if (LT == RT) return true;
480
481 // Force the signatures to match. We can't rely on the overrides
482 // list here because there isn't necessarily an inheritance
483 // relationship between the two methods.
484 if (LT->getMethodQuals() != RT->getMethodQuals())
485 return false;
486 return LT->getParamTypes() == RT->getParamTypes();
487}
488
489bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
490 const CXXMethodDecl *RHS) {
491 assert(VTableContextBase::hasVtableSlot(LHS) && "LHS must be virtual!");
492 assert(VTableContextBase::hasVtableSlot(RHS) && "RHS must be virtual!");
493
494 // A destructor can share a vcall offset with another destructor.
495 if (isa<CXXDestructorDecl>(LHS))
496 return isa<CXXDestructorDecl>(RHS);
497
498 // FIXME: We need to check more things here.
499
500 // The methods must have the same name.
501 DeclarationName LHSName = LHS->getDeclName();
502 DeclarationName RHSName = RHS->getDeclName();
503 if (LHSName != RHSName)
504 return false;
505
506 // And the same signatures.
507 return HasSameVirtualSignature(LHS, RHS);
508}
509
510bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
511 CharUnits OffsetOffset) {
512 // Check if we can reuse an offset.
513 for (const auto &OffsetPair : Offsets) {
514 if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
515 return false;
516 }
517
518 // Add the offset.
519 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
520 return true;
521}
522
523CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
524 // Look for an offset.
525 for (const auto &OffsetPair : Offsets) {
526 if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
527 return OffsetPair.second;
528 }
529
530 llvm_unreachable("Should always find a vcall offset offset!");
531}
532
533/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
534class VCallAndVBaseOffsetBuilder {
535public:
536 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
537 VBaseOffsetOffsetsMapTy;
538
539private:
540 /// MostDerivedClass - The most derived class for which we're building vcall
541 /// and vbase offsets.
542 const CXXRecordDecl *MostDerivedClass;
543
544 /// LayoutClass - The class we're using for layout information. Will be
545 /// different than the most derived class if we're building a construction
546 /// vtable.
547 const CXXRecordDecl *LayoutClass;
548
549 /// Context - The ASTContext which we will use for layout information.
550 ASTContext &Context;
551
552 /// Components - vcall and vbase offset components
553 typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
554 VTableComponentVectorTy Components;
555
556 /// VisitedVirtualBases - Visited virtual bases.
558
559 /// VCallOffsets - Keeps track of vcall offsets.
560 VCallOffsetMap VCallOffsets;
561
562
563 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
564 /// relative to the address point.
565 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
566
567 /// FinalOverriders - The final overriders of the most derived class.
568 /// (Can be null when we're not building a vtable of the most derived class).
569 const FinalOverriders *Overriders;
570
571 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
572 /// given base subobject.
573 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
574 CharUnits RealBaseOffset);
575
576 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
577 void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
578
579 /// AddVBaseOffsets - Add vbase offsets for the given class.
580 void AddVBaseOffsets(const CXXRecordDecl *Base,
581 CharUnits OffsetInLayoutClass);
582
583 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
584 /// chars, relative to the vtable address point.
585 CharUnits getCurrentOffsetOffset() const;
586
587public:
588 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
589 const CXXRecordDecl *LayoutClass,
590 const FinalOverriders *Overriders,
591 BaseSubobject Base, bool BaseIsVirtual,
592 CharUnits OffsetInLayoutClass)
593 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
594 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
595
596 // Add vcall and vbase offsets.
597 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
598 }
599
600 /// Methods for iterating over the components.
601 typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
602 const_iterator components_begin() const { return Components.rbegin(); }
603 const_iterator components_end() const { return Components.rend(); }
604
605 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
606 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
607 return VBaseOffsetOffsets;
608 }
609};
610
611void
612VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
613 bool BaseIsVirtual,
614 CharUnits RealBaseOffset) {
615 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
616
617 // Itanium C++ ABI 2.5.2:
618 // ..in classes sharing a virtual table with a primary base class, the vcall
619 // and vbase offsets added by the derived class all come before the vcall
620 // and vbase offsets required by the base class, so that the latter may be
621 // laid out as required by the base class without regard to additions from
622 // the derived class(es).
623
624 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
625 // emit them for the primary base first).
626 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
627 bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
628
629 CharUnits PrimaryBaseOffset;
630
631 // Get the base offset of the primary base.
632 if (PrimaryBaseIsVirtual) {
633 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
634 "Primary vbase should have a zero offset!");
635
636 const ASTRecordLayout &MostDerivedClassLayout =
637 Context.getASTRecordLayout(MostDerivedClass);
638
639 PrimaryBaseOffset =
640 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
641 } else {
642 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
643 "Primary base should have a zero offset!");
644
645 PrimaryBaseOffset = Base.getBaseOffset();
646 }
647
648 AddVCallAndVBaseOffsets(
649 BaseSubobject(PrimaryBase,PrimaryBaseOffset),
650 PrimaryBaseIsVirtual, RealBaseOffset);
651 }
652
653 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
654
655 // We only want to add vcall offsets for virtual bases.
656 if (BaseIsVirtual)
657 AddVCallOffsets(Base, RealBaseOffset);
658}
659
660CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
661 // OffsetIndex is the index of this vcall or vbase offset, relative to the
662 // vtable address point. (We subtract 3 to account for the information just
663 // above the address point, the RTTI info, the offset to top, and the
664 // vcall offset itself).
665 size_t NumComponentsAboveAddrPoint = 3;
666 if (Context.getLangOpts().OmitVTableRTTI)
667 NumComponentsAboveAddrPoint--;
668 int64_t OffsetIndex =
669 -(int64_t)(NumComponentsAboveAddrPoint + Components.size());
670
671 // Under the relative ABI, the offset widths are 32-bit ints instead of
672 // pointer widths.
673 CharUnits OffsetWidth = Context.toCharUnitsFromBits(
674 Context.getLangOpts().RelativeCXXABIVTables
675 ? 32
676 : Context.getTargetInfo().getPointerWidth(LangAS::Default));
677 CharUnits OffsetOffset = OffsetWidth * OffsetIndex;
678
679 return OffsetOffset;
680}
681
682void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
683 CharUnits VBaseOffset) {
684 const CXXRecordDecl *RD = Base.getBase();
685 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
686
687 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
688
689 // Handle the primary base first.
690 // We only want to add vcall offsets if the base is non-virtual; a virtual
691 // primary base will have its vcall and vbase offsets emitted already.
692 if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
693 // Get the base offset of the primary base.
694 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
695 "Primary base should have a zero offset!");
696
697 AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
698 VBaseOffset);
699 }
700
701 // Add the vcall offsets.
702 for (const auto *MD : RD->methods()) {
704 continue;
705 MD = MD->getCanonicalDecl();
706
707 CharUnits OffsetOffset = getCurrentOffsetOffset();
708
709 // Don't add a vcall offset if we already have one for this member function
710 // signature.
711 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
712 continue;
713
714 CharUnits Offset = CharUnits::Zero();
715
716 if (Overriders) {
717 // Get the final overrider.
718 FinalOverriders::OverriderInfo Overrider =
719 Overriders->getOverrider(MD, Base.getBaseOffset());
720
721 /// The vcall offset is the offset from the virtual base to the object
722 /// where the function was overridden.
723 Offset = Overrider.Offset - VBaseOffset;
724 }
725
726 Components.push_back(
728 }
729
730 // And iterate over all non-virtual bases (ignoring the primary base).
731 for (const auto &B : RD->bases()) {
732 if (B.isVirtual())
733 continue;
734
735 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
736 if (BaseDecl == PrimaryBase)
737 continue;
738
739 // Get the base offset of this base.
740 CharUnits BaseOffset = Base.getBaseOffset() +
741 Layout.getBaseClassOffset(BaseDecl);
742
743 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
744 VBaseOffset);
745 }
746}
747
748void
749VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
750 CharUnits OffsetInLayoutClass) {
751 const ASTRecordLayout &LayoutClassLayout =
752 Context.getASTRecordLayout(LayoutClass);
753
754 // Add vbase offsets.
755 for (const auto &B : RD->bases()) {
756 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
757
758 // Check if this is a virtual base that we haven't visited before.
759 if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) {
760 CharUnits Offset =
761 LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
762
763 // Add the vbase offset offset.
764 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
765 "vbase offset offset already exists!");
766
767 CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
768 VBaseOffsetOffsets.insert(
769 std::make_pair(BaseDecl, VBaseOffsetOffset));
770
771 Components.push_back(
773 }
774
775 // Check the base class looking for more vbase offsets.
776 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
777 }
778}
779
780/// ItaniumVTableBuilder - Class for building vtable layout information.
781class ItaniumVTableBuilder {
782public:
783 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
784 /// primary bases.
786 PrimaryBasesSetVectorTy;
787
788 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
789 VBaseOffsetOffsetsMapTy;
790
791 typedef VTableLayout::AddressPointsMapTy AddressPointsMapTy;
792
793 typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
794
795private:
796 /// VTables - Global vtable information.
797 ItaniumVTableContext &VTables;
798
799 /// MostDerivedClass - The most derived class for which we're building this
800 /// vtable.
801 const CXXRecordDecl *MostDerivedClass;
802
803 /// MostDerivedClassOffset - If we're building a construction vtable, this
804 /// holds the offset from the layout class to the most derived class.
805 const CharUnits MostDerivedClassOffset;
806
807 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
808 /// base. (This only makes sense when building a construction vtable).
809 bool MostDerivedClassIsVirtual;
810
811 /// LayoutClass - The class we're using for layout information. Will be
812 /// different than the most derived class if we're building a construction
813 /// vtable.
814 const CXXRecordDecl *LayoutClass;
815
816 /// Context - The ASTContext which we will use for layout information.
817 ASTContext &Context;
818
819 /// FinalOverriders - The final overriders of the most derived class.
820 const FinalOverriders Overriders;
821
822 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
823 /// bases in this vtable.
824 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
825
826 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
827 /// the most derived class.
828 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
829
830 /// Components - The components of the vtable being built.
832
833 /// AddressPoints - Address points for the vtable being built.
834 AddressPointsMapTy AddressPoints;
835
836 /// MethodInfo - Contains information about a method in a vtable.
837 /// (Used for computing 'this' pointer adjustment thunks.
838 struct MethodInfo {
839 /// BaseOffset - The base offset of this method.
840 const CharUnits BaseOffset;
841
842 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
843 /// method.
844 const CharUnits BaseOffsetInLayoutClass;
845
846 /// VTableIndex - The index in the vtable that this method has.
847 /// (For destructors, this is the index of the complete destructor).
848 const uint64_t VTableIndex;
849
850 MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
851 uint64_t VTableIndex)
852 : BaseOffset(BaseOffset),
853 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
854 VTableIndex(VTableIndex) { }
855
856 MethodInfo()
857 : BaseOffset(CharUnits::Zero()),
858 BaseOffsetInLayoutClass(CharUnits::Zero()),
859 VTableIndex(0) { }
860
861 MethodInfo(MethodInfo const&) = default;
862 };
863
864 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
865
866 /// MethodInfoMap - The information for all methods in the vtable we're
867 /// currently building.
868 MethodInfoMapTy MethodInfoMap;
869
870 /// MethodVTableIndices - Contains the index (relative to the vtable address
871 /// point) where the function pointer for a virtual function is stored.
872 MethodVTableIndicesTy MethodVTableIndices;
873
874 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
875
876 /// VTableThunks - The thunks by vtable index in the vtable currently being
877 /// built.
878 VTableThunksMapTy VTableThunks;
879
880 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
881 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
882
883 /// Thunks - A map that contains all the thunks needed for all methods in the
884 /// most derived class for which the vtable is currently being built.
885 ThunksMapTy Thunks;
886
887 /// AddThunk - Add a thunk for the given method.
888 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
889
890 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
891 /// part of the vtable we're currently building.
892 void ComputeThisAdjustments();
893
894 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
895
896 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
897 /// some other base.
898 VisitedVirtualBasesSetTy PrimaryVirtualBases;
899
900 /// ComputeReturnAdjustment - Compute the return adjustment given a return
901 /// adjustment base offset.
902 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
903
904 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
905 /// the 'this' pointer from the base subobject to the derived subobject.
906 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
907 BaseSubobject Derived) const;
908
909 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
910 /// given virtual member function, its offset in the layout class and its
911 /// final overrider.
913 ComputeThisAdjustment(const CXXMethodDecl *MD,
914 CharUnits BaseOffsetInLayoutClass,
915 FinalOverriders::OverriderInfo Overrider);
916
917 /// AddMethod - Add a single virtual member function to the vtable
918 /// components vector.
919 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
920
921 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
922 /// part of the vtable.
923 ///
924 /// Itanium C++ ABI 2.5.2:
925 ///
926 /// struct A { virtual void f(); };
927 /// struct B : virtual public A { int i; };
928 /// struct C : virtual public A { int j; };
929 /// struct D : public B, public C {};
930 ///
931 /// When B and C are declared, A is a primary base in each case, so although
932 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
933 /// adjustment is required and no thunk is generated. However, inside D
934 /// objects, A is no longer a primary base of C, so if we allowed calls to
935 /// C::f() to use the copy of A's vtable in the C subobject, we would need
936 /// to adjust this from C* to B::A*, which would require a third-party
937 /// thunk. Since we require that a call to C::f() first convert to A*,
938 /// C-in-D's copy of A's vtable is never referenced, so this is not
939 /// necessary.
940 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
941 CharUnits BaseOffsetInLayoutClass,
942 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
943 CharUnits FirstBaseOffsetInLayoutClass) const;
944
945
946 /// AddMethods - Add the methods of this base subobject and all its
947 /// primary bases to the vtable components vector.
948 void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
949 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
950 CharUnits FirstBaseOffsetInLayoutClass,
951 PrimaryBasesSetVectorTy &PrimaryBases);
952
953 // LayoutVTable - Layout the vtable for the given base class, including its
954 // secondary vtables and any vtables for virtual bases.
955 void LayoutVTable();
956
957 /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
958 /// given base subobject, as well as all its secondary vtables.
959 ///
960 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
961 /// or a direct or indirect base of a virtual base.
962 ///
963 /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
964 /// in the layout class.
965 void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
966 bool BaseIsMorallyVirtual,
967 bool BaseIsVirtualInLayoutClass,
968 CharUnits OffsetInLayoutClass);
969
970 /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
971 /// subobject.
972 ///
973 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
974 /// or a direct or indirect base of a virtual base.
975 void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
976 CharUnits OffsetInLayoutClass);
977
978 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
979 /// class hierarchy.
980 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
981 CharUnits OffsetInLayoutClass,
982 VisitedVirtualBasesSetTy &VBases);
983
984 /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
985 /// given base (excluding any primary bases).
986 void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
987 VisitedVirtualBasesSetTy &VBases);
988
989 /// isBuildingConstructionVTable - Return whether this vtable builder is
990 /// building a construction vtable.
991 bool isBuildingConstructorVTable() const {
992 return MostDerivedClass != LayoutClass;
993 }
994
995public:
996 /// Component indices of the first component of each of the vtables in the
997 /// vtable group.
998 VTableLayout::VTableIndicesTy VTableIndices;
999
1000 ItaniumVTableBuilder(ItaniumVTableContext &VTables,
1001 const CXXRecordDecl *MostDerivedClass,
1002 CharUnits MostDerivedClassOffset,
1003 bool MostDerivedClassIsVirtual,
1004 const CXXRecordDecl *LayoutClass)
1005 : VTables(VTables), MostDerivedClass(MostDerivedClass),
1006 MostDerivedClassOffset(MostDerivedClassOffset),
1007 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
1008 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
1009 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
1010 assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
1011
1012 LayoutVTable();
1013
1014 if (Context.getLangOpts().DumpVTableLayouts)
1015 dumpLayout(llvm::outs());
1016 }
1017
1018 uint64_t getNumThunks() const {
1019 return Thunks.size();
1020 }
1021
1022 ThunksMapTy::const_iterator thunks_begin() const {
1023 return Thunks.begin();
1024 }
1025
1026 ThunksMapTy::const_iterator thunks_end() const {
1027 return Thunks.end();
1028 }
1029
1030 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1031 return VBaseOffsetOffsets;
1032 }
1033
1034 const AddressPointsMapTy &getAddressPoints() const {
1035 return AddressPoints;
1036 }
1037
1038 MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
1039 return MethodVTableIndices.begin();
1040 }
1041
1042 MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
1043 return MethodVTableIndices.end();
1044 }
1045
1046 ArrayRef<VTableComponent> vtable_components() const { return Components; }
1047
1048 AddressPointsMapTy::const_iterator address_points_begin() const {
1049 return AddressPoints.begin();
1050 }
1051
1052 AddressPointsMapTy::const_iterator address_points_end() const {
1053 return AddressPoints.end();
1054 }
1055
1056 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1057 return VTableThunks.begin();
1058 }
1059
1060 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1061 return VTableThunks.end();
1062 }
1063
1064 /// dumpLayout - Dump the vtable layout.
1065 void dumpLayout(raw_ostream&);
1066};
1067
1068void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
1069 const ThunkInfo &Thunk) {
1070 assert(!isBuildingConstructorVTable() &&
1071 "Can't add thunks for construction vtable");
1072
1073 SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
1074
1075 // Check if we have this thunk already.
1076 if (llvm::is_contained(ThunksVector, Thunk))
1077 return;
1078
1079 ThunksVector.push_back(Thunk);
1080}
1081
1082typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1083
1084/// Visit all the methods overridden by the given method recursively,
1085/// in a depth-first pre-order. The Visitor's visitor method returns a bool
1086/// indicating whether to continue the recursion for the given overridden
1087/// method (i.e. returning false stops the iteration).
1088template <class VisitorTy>
1089static void
1090visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
1091 assert(VTableContextBase::hasVtableSlot(MD) && "Method is not virtual!");
1092
1093 for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
1094 if (!Visitor(OverriddenMD))
1095 continue;
1096 visitAllOverriddenMethods(OverriddenMD, Visitor);
1097 }
1098}
1099
1100/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1101/// the overridden methods that the function decl overrides.
1102static void
1103ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1104 OverriddenMethodsSetTy& OverriddenMethods) {
1105 auto OverriddenMethodsCollector = [&](const CXXMethodDecl *MD) {
1106 // Don't recurse on this method if we've already collected it.
1107 return OverriddenMethods.insert(MD).second;
1108 };
1109 visitAllOverriddenMethods(MD, OverriddenMethodsCollector);
1110}
1111
1112void ItaniumVTableBuilder::ComputeThisAdjustments() {
1113 // Now go through the method info map and see if any of the methods need
1114 // 'this' pointer adjustments.
1115 for (const auto &MI : MethodInfoMap) {
1116 const CXXMethodDecl *MD = MI.first;
1117 const MethodInfo &MethodInfo = MI.second;
1118
1119 // Ignore adjustments for unused function pointers.
1120 uint64_t VTableIndex = MethodInfo.VTableIndex;
1121 if (Components[VTableIndex].getKind() ==
1123 continue;
1124
1125 // Get the final overrider for this method.
1126 FinalOverriders::OverriderInfo Overrider =
1127 Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1128
1129 // Check if we need an adjustment at all.
1130 if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1131 // When a return thunk is needed by a derived class that overrides a
1132 // virtual base, gcc uses a virtual 'this' adjustment as well.
1133 // While the thunk itself might be needed by vtables in subclasses or
1134 // in construction vtables, there doesn't seem to be a reason for using
1135 // the thunk in this vtable. Still, we do so to match gcc.
1136 if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1137 continue;
1138 }
1139
1141 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1142
1143 if (ThisAdjustment.isEmpty())
1144 continue;
1145
1146 // Add it.
1147 auto SetThisAdjustmentThunk = [&](uint64_t Idx) {
1148 // If a this pointer adjustment is required, record the method that
1149 // created the vtable entry. MD is not necessarily the method that
1150 // created the entry since derived classes overwrite base class
1151 // information in MethodInfoMap, hence findOriginalMethodInMap is called
1152 // here.
1153 //
1154 // For example, in the following class hierarchy, if MD = D1::m and
1155 // Overrider = D2:m, the original method that created the entry is B0:m,
1156 // which is what findOriginalMethodInMap(MD) returns:
1157 //
1158 // struct B0 { int a; virtual void m(); };
1159 // struct D0 : B0 { int a; void m() override; };
1160 // struct D1 : B0 { int a; void m() override; };
1161 // struct D2 : D0, D1 { int a; void m() override; };
1162 //
1163 // We need to record the method because we cannot
1164 // call findOriginalMethod to find the method that created the entry if
1165 // the method in the entry requires adjustment.
1166 //
1167 // Do not set ThunkInfo::Method if Idx is already in VTableThunks. This
1168 // can happen when covariant return adjustment is required too.
1169 auto [It, Inserted] = VTableThunks.try_emplace(Idx);
1170 if (Inserted) {
1171 const CXXMethodDecl *Method = VTables.findOriginalMethodInMap(MD);
1172 It->second.Method = Method;
1173 It->second.ThisType = Method->getThisType().getTypePtr();
1174 }
1175 It->second.This = ThisAdjustment;
1176 };
1177
1178 SetThisAdjustmentThunk(VTableIndex);
1179
1180 if (isa<CXXDestructorDecl>(MD)) {
1181 // Add an adjustment for the deleting destructor as well.
1182 SetThisAdjustmentThunk(VTableIndex + 1);
1183 }
1184 }
1185
1186 /// Clear the method info map.
1187 MethodInfoMap.clear();
1188
1189 if (isBuildingConstructorVTable()) {
1190 // We don't need to store thunk information for construction vtables.
1191 return;
1192 }
1193
1194 for (const auto &TI : VTableThunks) {
1195 const VTableComponent &Component = Components[TI.first];
1196 const ThunkInfo &Thunk = TI.second;
1197 const CXXMethodDecl *MD;
1198
1199 switch (Component.getKind()) {
1200 default:
1201 llvm_unreachable("Unexpected vtable component kind!");
1203 MD = Component.getFunctionDecl();
1204 break;
1206 MD = Component.getDestructorDecl();
1207 break;
1209 // We've already added the thunk when we saw the complete dtor pointer.
1210 continue;
1211 }
1212
1213 if (MD->getParent() == MostDerivedClass)
1214 AddThunk(MD, Thunk);
1215 }
1216}
1217
1219ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1220 ReturnAdjustment Adjustment;
1221
1222 if (!Offset.isEmpty()) {
1223 if (Offset.VirtualBase) {
1224 // Get the virtual base offset offset.
1225 if (Offset.DerivedClass == MostDerivedClass) {
1226 // We can get the offset offset directly from our map.
1227 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
1228 VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
1229 } else {
1230 Adjustment.Virtual.Itanium.VBaseOffsetOffset =
1231 VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1232 Offset.VirtualBase).getQuantity();
1233 }
1234 }
1235
1236 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1237 }
1238
1239 return Adjustment;
1240}
1241
1242BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
1243 BaseSubobject Base, BaseSubobject Derived) const {
1244 const CXXRecordDecl *BaseRD = Base.getBase();
1245 const CXXRecordDecl *DerivedRD = Derived.getBase();
1246
1247 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1248 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1249
1250 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
1251 llvm_unreachable("Class must be derived from the passed in base class!");
1252
1253 // We have to go through all the paths, and see which one leads us to the
1254 // right base subobject.
1255 for (const CXXBasePath &Path : Paths) {
1256 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, Path);
1257
1258 CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
1259
1260 if (Offset.VirtualBase) {
1261 // If we have a virtual base class, the non-virtual offset is relative
1262 // to the virtual base class offset.
1263 const ASTRecordLayout &LayoutClassLayout =
1264 Context.getASTRecordLayout(LayoutClass);
1265
1266 /// Get the virtual base offset, relative to the most derived class
1267 /// layout.
1268 OffsetToBaseSubobject +=
1269 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1270 } else {
1271 // Otherwise, the non-virtual offset is relative to the derived class
1272 // offset.
1273 OffsetToBaseSubobject += Derived.getBaseOffset();
1274 }
1275
1276 // Check if this path gives us the right base subobject.
1277 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1278 // Since we're going from the base class _to_ the derived class, we'll
1279 // invert the non-virtual offset here.
1280 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1281 return Offset;
1282 }
1283 }
1284
1285 return BaseOffset();
1286}
1287
1288ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
1289 const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
1290 FinalOverriders::OverriderInfo Overrider) {
1291 // Ignore adjustments for pure virtual member functions.
1292 if (Overrider.Method->isPureVirtual())
1293 return ThisAdjustment();
1294
1295 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1296 BaseOffsetInLayoutClass);
1297
1298 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1299 Overrider.Offset);
1300
1301 // Compute the adjustment offset.
1302 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1303 OverriderBaseSubobject);
1304 if (Offset.isEmpty())
1305 return ThisAdjustment();
1306
1307 ThisAdjustment Adjustment;
1308
1309 if (Offset.VirtualBase) {
1310 // Get the vcall offset map for this virtual base.
1311 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1312
1313 if (VCallOffsets.empty()) {
1314 // We don't have vcall offsets for this virtual base, go ahead and
1315 // build them.
1316 VCallAndVBaseOffsetBuilder Builder(
1317 MostDerivedClass, MostDerivedClass,
1318 /*Overriders=*/nullptr,
1319 BaseSubobject(Offset.VirtualBase, CharUnits::Zero()),
1320 /*BaseIsVirtual=*/true,
1321 /*OffsetInLayoutClass=*/
1322 CharUnits::Zero());
1323
1324 VCallOffsets = Builder.getVCallOffsets();
1325 }
1326
1327 Adjustment.Virtual.Itanium.VCallOffsetOffset =
1328 VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
1329 }
1330
1331 // Set the non-virtual part of the adjustment.
1332 Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
1333
1334 return Adjustment;
1335}
1336
1337void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
1339 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1340 assert(ReturnAdjustment.isEmpty() &&
1341 "Destructor can't have return adjustment!");
1342
1343 // Add both the complete destructor and the deleting destructor.
1344 Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1345 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1346 } else {
1347 // Add the return adjustment if necessary.
1349 VTableThunks[Components.size()].Return = ReturnAdjustment;
1350
1351 // Add the function.
1352 Components.push_back(VTableComponent::MakeFunction(MD));
1353 }
1354}
1355
1356/// OverridesIndirectMethodInBase - Return whether the given member function
1357/// overrides any methods in the set of given bases.
1358/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1359/// For example, if we have:
1360///
1361/// struct A { virtual void f(); }
1362/// struct B : A { virtual void f(); }
1363/// struct C : B { virtual void f(); }
1364///
1365/// OverridesIndirectMethodInBase will return true if given C::f as the method
1366/// and { A } as the set of bases.
1367static bool OverridesIndirectMethodInBases(
1368 const CXXMethodDecl *MD,
1369 ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1370 if (Bases.count(MD->getParent()))
1371 return true;
1372
1373 for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
1374 // Check "indirect overriders".
1375 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1376 return true;
1377 }
1378
1379 return false;
1380}
1381
1382bool ItaniumVTableBuilder::IsOverriderUsed(
1383 const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
1384 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1385 CharUnits FirstBaseOffsetInLayoutClass) const {
1386 // If the base and the first base in the primary base chain have the same
1387 // offsets, then this overrider will be used.
1388 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1389 return true;
1390
1391 // We know now that Base (or a direct or indirect base of it) is a primary
1392 // base in part of the class hierarchy, but not a primary base in the most
1393 // derived class.
1394
1395 // If the overrider is the first base in the primary base chain, we know
1396 // that the overrider will be used.
1397 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1398 return true;
1399
1400 ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1401
1402 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1403 PrimaryBases.insert(RD);
1404
1405 // Now traverse the base chain, starting with the first base, until we find
1406 // the base that is no longer a primary base.
1407 while (true) {
1408 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1409 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1410
1411 if (!PrimaryBase)
1412 break;
1413
1414 if (Layout.isPrimaryBaseVirtual()) {
1415 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1416 "Primary base should always be at offset 0!");
1417
1418 const ASTRecordLayout &LayoutClassLayout =
1419 Context.getASTRecordLayout(LayoutClass);
1420
1421 // Now check if this is the primary base that is not a primary base in the
1422 // most derived class.
1423 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1424 FirstBaseOffsetInLayoutClass) {
1425 // We found it, stop walking the chain.
1426 break;
1427 }
1428 } else {
1429 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1430 "Primary base should always be at offset 0!");
1431 }
1432
1433 if (!PrimaryBases.insert(PrimaryBase))
1434 llvm_unreachable("Found a duplicate primary base!");
1435
1436 RD = PrimaryBase;
1437 }
1438
1439 // If the final overrider is an override of one of the primary bases,
1440 // then we know that it will be used.
1441 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1442}
1443
1444typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
1445
1446/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1447/// from the nearest base. Returns null if no method was found.
1448/// The Bases are expected to be sorted in a base-to-derived order.
1449static const CXXMethodDecl *
1450FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1451 BasesSetVectorTy &Bases) {
1452 OverriddenMethodsSetTy OverriddenMethods;
1453 ComputeAllOverriddenMethods(MD, OverriddenMethods);
1454
1455 for (const CXXRecordDecl *PrimaryBase : llvm::reverse(Bases)) {
1456 // Now check the overridden methods.
1457 for (const CXXMethodDecl *OverriddenMD : OverriddenMethods) {
1458 // We found our overridden method.
1459 if (OverriddenMD->getParent() == PrimaryBase)
1460 return OverriddenMD;
1461 }
1462 }
1463
1464 return nullptr;
1465}
1466
1467void ItaniumVTableBuilder::AddMethods(
1468 BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1469 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1470 CharUnits FirstBaseOffsetInLayoutClass,
1471 PrimaryBasesSetVectorTy &PrimaryBases) {
1472 // Itanium C++ ABI 2.5.2:
1473 // The order of the virtual function pointers in a virtual table is the
1474 // order of declaration of the corresponding member functions in the class.
1475 //
1476 // There is an entry for any virtual function declared in a class,
1477 // whether it is a new function or overrides a base class function,
1478 // unless it overrides a function from the primary base, and conversion
1479 // between their return types does not require an adjustment.
1480
1481 const CXXRecordDecl *RD = Base.getBase();
1482 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1483
1484 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1485 CharUnits PrimaryBaseOffset;
1486 CharUnits PrimaryBaseOffsetInLayoutClass;
1487 if (Layout.isPrimaryBaseVirtual()) {
1488 assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
1489 "Primary vbase should have a zero offset!");
1490
1491 const ASTRecordLayout &MostDerivedClassLayout =
1492 Context.getASTRecordLayout(MostDerivedClass);
1493
1494 PrimaryBaseOffset =
1495 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1496
1497 const ASTRecordLayout &LayoutClassLayout =
1498 Context.getASTRecordLayout(LayoutClass);
1499
1500 PrimaryBaseOffsetInLayoutClass =
1501 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1502 } else {
1503 assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
1504 "Primary base should have a zero offset!");
1505
1506 PrimaryBaseOffset = Base.getBaseOffset();
1507 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1508 }
1509
1510 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1511 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1512 FirstBaseOffsetInLayoutClass, PrimaryBases);
1513
1514 if (!PrimaryBases.insert(PrimaryBase))
1515 llvm_unreachable("Found a duplicate primary base!");
1516 }
1517
1518 typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
1519 NewVirtualFunctionsTy NewVirtualFunctions;
1520
1521 llvm::SmallVector<const CXXMethodDecl*, 4> NewImplicitVirtualFunctions;
1522
1523 // Now go through all virtual member functions and add them.
1524 for (const auto *MD : RD->methods()) {
1526 continue;
1527 MD = MD->getCanonicalDecl();
1528
1529 // Get the final overrider.
1530 FinalOverriders::OverriderInfo Overrider =
1531 Overriders.getOverrider(MD, Base.getBaseOffset());
1532
1533 // Check if this virtual member function overrides a method in a primary
1534 // base. If this is the case, and the return type doesn't require adjustment
1535 // then we can just use the member function from the primary base.
1536 if (const CXXMethodDecl *OverriddenMD =
1537 FindNearestOverriddenMethod(MD, PrimaryBases)) {
1538 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1539 OverriddenMD).isEmpty()) {
1540 VTables.setOriginalMethod(MD, OverriddenMD);
1541
1542 // Replace the method info of the overridden method with our own
1543 // method.
1544 assert(MethodInfoMap.count(OverriddenMD) &&
1545 "Did not find the overridden method!");
1546 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1547
1548 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1549 OverriddenMethodInfo.VTableIndex);
1550
1551 assert(!MethodInfoMap.count(MD) &&
1552 "Should not have method info for this method yet!");
1553
1554 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1555 MethodInfoMap.erase(OverriddenMD);
1556
1557 // If the overridden method exists in a virtual base class or a direct
1558 // or indirect base class of a virtual base class, we need to emit a
1559 // thunk if we ever have a class hierarchy where the base class is not
1560 // a primary base in the complete object.
1561 if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1562 // Compute the this adjustment.
1564 ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1565 Overrider);
1566
1568 Overrider.Method->getParent() == MostDerivedClass) {
1569
1570 // There's no return adjustment from OverriddenMD and MD,
1571 // but that doesn't mean there isn't one between MD and
1572 // the final overrider.
1573 BaseOffset ReturnAdjustmentOffset =
1574 ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1576 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1577
1578 const CXXMethodDecl *OrigMD =
1579 VTables.findOriginalMethodInMap(OverriddenMD);
1580
1581 // This is a virtual thunk for the most derived class, add it.
1582 AddThunk(Overrider.Method,
1584 OrigMD->getThisType().getTypePtr(), OrigMD));
1585 }
1586 }
1587
1588 continue;
1589 }
1590 }
1591
1592 if (MD->isImplicit())
1593 NewImplicitVirtualFunctions.push_back(MD);
1594 else
1595 NewVirtualFunctions.push_back(MD);
1596 }
1597
1598 llvm::stable_sort(
1599 NewImplicitVirtualFunctions,
1600 [](const CXXMethodDecl *A, const CXXMethodDecl *B) {
1601 if (A == B)
1602 return false;
1604 return A->isCopyAssignmentOperator();
1606 return A->isMoveAssignmentOperator();
1608 return isa<CXXDestructorDecl>(A);
1609 assert(A->getOverloadedOperator() == OO_EqualEqual &&
1610 B->getOverloadedOperator() == OO_EqualEqual &&
1611 "unexpected or duplicate implicit virtual function");
1612 // We rely on Sema to have declared the operator== members in the
1613 // same order as the corresponding operator<=> members.
1614 return false;
1615 });
1616 NewVirtualFunctions.append(NewImplicitVirtualFunctions.begin(),
1617 NewImplicitVirtualFunctions.end());
1618
1619 for (const CXXMethodDecl *MD : NewVirtualFunctions) {
1620 // Get the final overrider.
1621 FinalOverriders::OverriderInfo Overrider =
1622 Overriders.getOverrider(MD, Base.getBaseOffset());
1623
1624 // Insert the method info for this method.
1625 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1626 Components.size());
1627
1628 assert(!MethodInfoMap.count(MD) &&
1629 "Should not have method info for this method yet!");
1630 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1631
1632 // Check if this overrider is going to be used.
1633 const CXXMethodDecl *OverriderMD = Overrider.Method;
1634 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1635 FirstBaseInPrimaryBaseChain,
1636 FirstBaseOffsetInLayoutClass)) {
1637 Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1638 continue;
1639 }
1640
1641 // Check if this overrider needs a return adjustment.
1642 // We don't want to do this for pure virtual member functions.
1643 BaseOffset ReturnAdjustmentOffset;
1644 if (!OverriderMD->isPureVirtual()) {
1645 ReturnAdjustmentOffset =
1646 ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1647 }
1648
1650 ComputeReturnAdjustment(ReturnAdjustmentOffset);
1651
1652 // If a return adjustment is required, record the method that created the
1653 // vtable entry. We need to record the method because we cannot call
1654 // findOriginalMethod to find the method that created the entry if the
1655 // method in the entry requires adjustment.
1656 if (!ReturnAdjustment.isEmpty()) {
1657 auto &VTT = VTableThunks[Components.size()];
1658 VTT.Method = MD;
1659 VTT.ThisType = MD->getThisType().getTypePtr();
1660 }
1661
1662 AddMethod(Overrider.Method, ReturnAdjustment);
1663 }
1664}
1665
1666void ItaniumVTableBuilder::LayoutVTable() {
1667 LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1668 CharUnits::Zero()),
1669 /*BaseIsMorallyVirtual=*/false,
1670 MostDerivedClassIsVirtual,
1671 MostDerivedClassOffset);
1672
1673 VisitedVirtualBasesSetTy VBases;
1674
1675 // Determine the primary virtual bases.
1676 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1677 VBases);
1678 VBases.clear();
1679
1680 LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1681
1682 // -fapple-kext adds an extra entry at end of vtbl.
1683 bool IsAppleKext = Context.getLangOpts().AppleKext;
1684 if (IsAppleKext)
1685 Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
1686}
1687
1688void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
1689 BaseSubobject Base, bool BaseIsMorallyVirtual,
1690 bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
1691 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1692
1693 unsigned VTableIndex = Components.size();
1694 VTableIndices.push_back(VTableIndex);
1695
1696 // Add vcall and vbase offsets for this vtable.
1697 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1698 Base, BaseIsVirtualInLayoutClass,
1699 OffsetInLayoutClass);
1700 Components.append(Builder.components_begin(), Builder.components_end());
1701
1702 // Check if we need to add these vcall offsets.
1703 if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1704 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1705
1706 if (VCallOffsets.empty())
1707 VCallOffsets = Builder.getVCallOffsets();
1708 }
1709
1710 // If we're laying out the most derived class we want to keep track of the
1711 // virtual base class offset offsets.
1712 if (Base.getBase() == MostDerivedClass)
1713 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1714
1715 // Add the offset to top.
1716 CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1717 Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1718
1719 // Next, add the RTTI.
1720 if (!Context.getLangOpts().OmitVTableRTTI)
1721 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1722
1723 uint64_t AddressPoint = Components.size();
1724
1725 // Now go through all virtual member functions and add them.
1726 PrimaryBasesSetVectorTy PrimaryBases;
1727 AddMethods(Base, OffsetInLayoutClass,
1728 Base.getBase(), OffsetInLayoutClass,
1729 PrimaryBases);
1730
1731 const CXXRecordDecl *RD = Base.getBase();
1732 if (RD == MostDerivedClass) {
1733 assert(MethodVTableIndices.empty());
1734 for (const auto &I : MethodInfoMap) {
1735 const CXXMethodDecl *MD = I.first;
1736 const MethodInfo &MI = I.second;
1737 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1738 MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
1739 = MI.VTableIndex - AddressPoint;
1740 MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
1741 = MI.VTableIndex + 1 - AddressPoint;
1742 } else {
1743 MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
1744 }
1745 }
1746 }
1747
1748 // Compute 'this' pointer adjustments.
1749 ComputeThisAdjustments();
1750
1751 // Add all address points.
1752 while (true) {
1753 AddressPoints.insert(
1754 std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
1756 unsigned(VTableIndices.size() - 1),
1757 unsigned(AddressPoint - VTableIndex)}));
1758
1759 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1760 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1761
1762 if (!PrimaryBase)
1763 break;
1764
1765 if (Layout.isPrimaryBaseVirtual()) {
1766 // Check if this virtual primary base is a primary base in the layout
1767 // class. If it's not, we don't want to add it.
1768 const ASTRecordLayout &LayoutClassLayout =
1769 Context.getASTRecordLayout(LayoutClass);
1770
1771 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1772 OffsetInLayoutClass) {
1773 // We don't want to add this class (or any of its primary bases).
1774 break;
1775 }
1776 }
1777
1778 RD = PrimaryBase;
1779 }
1780
1781 // Layout secondary vtables.
1782 LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1783}
1784
1785void
1786ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1787 bool BaseIsMorallyVirtual,
1788 CharUnits OffsetInLayoutClass) {
1789 // Itanium C++ ABI 2.5.2:
1790 // Following the primary virtual table of a derived class are secondary
1791 // virtual tables for each of its proper base classes, except any primary
1792 // base(s) with which it shares its primary virtual table.
1793
1794 const CXXRecordDecl *RD = Base.getBase();
1795 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1796 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1797
1798 for (const auto &B : RD->bases()) {
1799 // Ignore virtual bases, we'll emit them later.
1800 if (B.isVirtual())
1801 continue;
1802
1803 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1804
1805 // Ignore bases that don't have a vtable.
1806 if (!BaseDecl->isDynamicClass())
1807 continue;
1808
1809 if (isBuildingConstructorVTable()) {
1810 // Itanium C++ ABI 2.6.4:
1811 // Some of the base class subobjects may not need construction virtual
1812 // tables, which will therefore not be present in the construction
1813 // virtual table group, even though the subobject virtual tables are
1814 // present in the main virtual table group for the complete object.
1815 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1816 continue;
1817 }
1818
1819 // Get the base offset of this base.
1820 CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1821 CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1822
1823 CharUnits BaseOffsetInLayoutClass =
1824 OffsetInLayoutClass + RelativeBaseOffset;
1825
1826 // Don't emit a secondary vtable for a primary base. We might however want
1827 // to emit secondary vtables for other bases of this base.
1828 if (BaseDecl == PrimaryBase) {
1829 LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1830 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1831 continue;
1832 }
1833
1834 // Layout the primary vtable (and any secondary vtables) for this base.
1835 LayoutPrimaryAndSecondaryVTables(
1836 BaseSubobject(BaseDecl, BaseOffset),
1837 BaseIsMorallyVirtual,
1838 /*BaseIsVirtualInLayoutClass=*/false,
1839 BaseOffsetInLayoutClass);
1840 }
1841}
1842
1843void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
1844 const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
1845 VisitedVirtualBasesSetTy &VBases) {
1846 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1847
1848 // Check if this base has a primary base.
1849 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1850
1851 // Check if it's virtual.
1852 if (Layout.isPrimaryBaseVirtual()) {
1853 bool IsPrimaryVirtualBase = true;
1854
1855 if (isBuildingConstructorVTable()) {
1856 // Check if the base is actually a primary base in the class we use for
1857 // layout.
1858 const ASTRecordLayout &LayoutClassLayout =
1859 Context.getASTRecordLayout(LayoutClass);
1860
1861 CharUnits PrimaryBaseOffsetInLayoutClass =
1862 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1863
1864 // We know that the base is not a primary base in the layout class if
1865 // the base offsets are different.
1866 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1867 IsPrimaryVirtualBase = false;
1868 }
1869
1870 if (IsPrimaryVirtualBase)
1871 PrimaryVirtualBases.insert(PrimaryBase);
1872 }
1873 }
1874
1875 // Traverse bases, looking for more primary virtual bases.
1876 for (const auto &B : RD->bases()) {
1877 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1878
1879 CharUnits BaseOffsetInLayoutClass;
1880
1881 if (B.isVirtual()) {
1882 if (!VBases.insert(BaseDecl).second)
1883 continue;
1884
1885 const ASTRecordLayout &LayoutClassLayout =
1886 Context.getASTRecordLayout(LayoutClass);
1887
1888 BaseOffsetInLayoutClass =
1889 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1890 } else {
1891 BaseOffsetInLayoutClass =
1892 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1893 }
1894
1895 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1896 }
1897}
1898
1899void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
1900 const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
1901 // Itanium C++ ABI 2.5.2:
1902 // Then come the virtual base virtual tables, also in inheritance graph
1903 // order, and again excluding primary bases (which share virtual tables with
1904 // the classes for which they are primary).
1905 for (const auto &B : RD->bases()) {
1906 const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
1907
1908 // Check if this base needs a vtable. (If it's virtual, not a primary base
1909 // of some other class, and we haven't visited it before).
1910 if (B.isVirtual() && BaseDecl->isDynamicClass() &&
1911 !PrimaryVirtualBases.count(BaseDecl) &&
1912 VBases.insert(BaseDecl).second) {
1913 const ASTRecordLayout &MostDerivedClassLayout =
1914 Context.getASTRecordLayout(MostDerivedClass);
1915 CharUnits BaseOffset =
1916 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1917
1918 const ASTRecordLayout &LayoutClassLayout =
1919 Context.getASTRecordLayout(LayoutClass);
1920 CharUnits BaseOffsetInLayoutClass =
1921 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1922
1923 LayoutPrimaryAndSecondaryVTables(
1924 BaseSubobject(BaseDecl, BaseOffset),
1925 /*BaseIsMorallyVirtual=*/true,
1926 /*BaseIsVirtualInLayoutClass=*/true,
1927 BaseOffsetInLayoutClass);
1928 }
1929
1930 // We only need to check the base for virtual base vtables if it actually
1931 // has virtual bases.
1932 if (BaseDecl->getNumVBases())
1933 LayoutVTablesForVirtualBases(BaseDecl, VBases);
1934 }
1935}
1936
1937static void printThunkMethod(const ThunkInfo &Info, raw_ostream &Out) {
1938 if (!Info.Method)
1939 return;
1940 std::string Str = PredefinedExpr::ComputeName(
1942 Out << " method: " << Str;
1943}
1944
1945/// dumpLayout - Dump the vtable layout.
1946void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
1947 // FIXME: write more tests that actually use the dumpLayout output to prevent
1948 // ItaniumVTableBuilder regressions.
1949
1950 Out << "Original map\n";
1951
1952 for (const auto &P : VTables.getOriginalMethodMap()) {
1953 std::string Str0 =
1955 P.first);
1956 std::string Str1 =
1958 P.second);
1959 Out << " " << Str0 << " -> " << Str1 << "\n";
1960 }
1961
1962 if (isBuildingConstructorVTable()) {
1963 Out << "Construction vtable for ('";
1964 MostDerivedClass->printQualifiedName(Out);
1965 Out << "', ";
1966 Out << MostDerivedClassOffset.getQuantity() << ") in '";
1967 LayoutClass->printQualifiedName(Out);
1968 } else {
1969 Out << "Vtable for '";
1970 MostDerivedClass->printQualifiedName(Out);
1971 }
1972 Out << "' (" << Components.size() << " entries).\n";
1973
1974 // Iterate through the address points and insert them into a new map where
1975 // they are keyed by the index and not the base object.
1976 // Since an address point can be shared by multiple subobjects, we use an
1977 // STL multimap.
1978 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
1979 for (const auto &AP : AddressPoints) {
1980 const BaseSubobject &Base = AP.first;
1981 uint64_t Index =
1982 VTableIndices[AP.second.VTableIndex] + AP.second.AddressPointIndex;
1983
1984 AddressPointsByIndex.insert(std::make_pair(Index, Base));
1985 }
1986
1987 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
1988 uint64_t Index = I;
1989
1990 Out << llvm::format("%4d | ", I);
1991
1992 const VTableComponent &Component = Components[I];
1993
1994 // Dump the component.
1995 switch (Component.getKind()) {
1996
1998 Out << "vcall_offset ("
1999 << Component.getVCallOffset().getQuantity()
2000 << ")";
2001 break;
2002
2004 Out << "vbase_offset ("
2005 << Component.getVBaseOffset().getQuantity()
2006 << ")";
2007 break;
2008
2010 Out << "offset_to_top ("
2011 << Component.getOffsetToTop().getQuantity()
2012 << ")";
2013 break;
2014
2016 Component.getRTTIDecl()->printQualifiedName(Out);
2017 Out << " RTTI";
2018 break;
2019
2021 const CXXMethodDecl *MD = Component.getFunctionDecl();
2022
2023 std::string Str = PredefinedExpr::ComputeName(
2025 Out << Str;
2026 if (MD->isPureVirtual())
2027 Out << " [pure]";
2028
2029 if (MD->isDeleted())
2030 Out << " [deleted]";
2031
2032 ThunkInfo Thunk = VTableThunks.lookup(I);
2033 if (!Thunk.isEmpty()) {
2034 // If this function pointer has a return adjustment, dump it.
2035 if (!Thunk.Return.isEmpty()) {
2036 Out << "\n [return adjustment: ";
2037 Out << Thunk.Return.NonVirtual << " non-virtual";
2038
2040 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
2041 Out << " vbase offset offset";
2042 }
2043
2044 Out << ']';
2045 printThunkMethod(Thunk, Out);
2046 }
2047
2048 // If this function pointer has a 'this' pointer adjustment, dump it.
2049 if (!Thunk.This.isEmpty()) {
2050 Out << "\n [this adjustment: ";
2051 Out << Thunk.This.NonVirtual << " non-virtual";
2052
2054 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2055 Out << " vcall offset offset";
2056 }
2057
2058 Out << ']';
2059 printThunkMethod(Thunk, Out);
2060 }
2061 }
2062
2063 break;
2064 }
2065
2068 bool IsComplete =
2070
2071 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2072
2073 DD->printQualifiedName(Out);
2074 if (IsComplete)
2075 Out << "() [complete]";
2076 else
2077 Out << "() [deleting]";
2078
2079 if (DD->isPureVirtual())
2080 Out << " [pure]";
2081
2082 ThunkInfo Thunk = VTableThunks.lookup(I);
2083 if (!Thunk.isEmpty()) {
2084 // If this destructor has a 'this' pointer adjustment, dump it.
2085 if (!Thunk.This.isEmpty()) {
2086 Out << "\n [this adjustment: ";
2087 Out << Thunk.This.NonVirtual << " non-virtual";
2088
2090 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2091 Out << " vcall offset offset";
2092 }
2093
2094 Out << ']';
2095 }
2096 printThunkMethod(Thunk, Out);
2097 }
2098
2099 break;
2100 }
2101
2103 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2104
2105 std::string Str = PredefinedExpr::ComputeName(
2107 Out << "[unused] " << Str;
2108 if (MD->isPureVirtual())
2109 Out << " [pure]";
2110 }
2111
2112 }
2113
2114 Out << '\n';
2115
2116 // Dump the next address point.
2117 uint64_t NextIndex = Index + 1;
2118 if (unsigned Count = AddressPointsByIndex.count(NextIndex)) {
2119 if (Count == 1) {
2120 const BaseSubobject &Base =
2121 AddressPointsByIndex.find(NextIndex)->second;
2122
2123 Out << " -- (";
2124 Base.getBase()->printQualifiedName(Out);
2125 Out << ", " << Base.getBaseOffset().getQuantity();
2126 Out << ") vtable address --\n";
2127 } else {
2128 CharUnits BaseOffset =
2129 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2130
2131 // We store the class names in a set to get a stable order.
2132 std::set<std::string> ClassNames;
2133 for (const auto &I :
2134 llvm::make_range(AddressPointsByIndex.equal_range(NextIndex))) {
2135 assert(I.second.getBaseOffset() == BaseOffset &&
2136 "Invalid base offset!");
2137 const CXXRecordDecl *RD = I.second.getBase();
2138 ClassNames.insert(RD->getQualifiedNameAsString());
2139 }
2140
2141 for (const std::string &Name : ClassNames) {
2142 Out << " -- (" << Name;
2143 Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2144 }
2145 }
2146 }
2147 }
2148
2149 Out << '\n';
2150
2151 if (isBuildingConstructorVTable())
2152 return;
2153
2154 if (MostDerivedClass->getNumVBases()) {
2155 // We store the virtual base class names and their offsets in a map to get
2156 // a stable order.
2157
2158 std::map<std::string, CharUnits> ClassNamesAndOffsets;
2159 for (const auto &I : VBaseOffsetOffsets) {
2160 std::string ClassName = I.first->getQualifiedNameAsString();
2161 CharUnits OffsetOffset = I.second;
2162 ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
2163 }
2164
2165 Out << "Virtual base offset offsets for '";
2166 MostDerivedClass->printQualifiedName(Out);
2167 Out << "' (";
2168 Out << ClassNamesAndOffsets.size();
2169 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2170
2171 for (const auto &I : ClassNamesAndOffsets)
2172 Out << " " << I.first << " | " << I.second.getQuantity() << '\n';
2173
2174 Out << "\n";
2175 }
2176
2177 if (!Thunks.empty()) {
2178 // We store the method names in a map to get a stable order.
2179 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2180
2181 for (const auto &I : Thunks) {
2182 const CXXMethodDecl *MD = I.first;
2183 std::string MethodName = PredefinedExpr::ComputeName(
2185
2186 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2187 }
2188
2189 for (const auto &I : MethodNamesAndDecls) {
2190 const std::string &MethodName = I.first;
2191 const CXXMethodDecl *MD = I.second;
2192
2193 ThunkInfoVectorTy ThunksVector = Thunks[MD];
2194 llvm::sort(ThunksVector, [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
2195 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
2196 });
2197
2198 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2199 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2200
2201 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2202 const ThunkInfo &Thunk = ThunksVector[I];
2203
2204 Out << llvm::format("%4d | ", I);
2205
2206 // If this function pointer has a return pointer adjustment, dump it.
2207 if (!Thunk.Return.isEmpty()) {
2208 Out << "return adjustment: " << Thunk.Return.NonVirtual;
2209 Out << " non-virtual";
2211 Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
2212 Out << " vbase offset offset";
2213 }
2214
2215 if (!Thunk.This.isEmpty())
2216 Out << "\n ";
2217 }
2218
2219 // If this function pointer has a 'this' pointer adjustment, dump it.
2220 if (!Thunk.This.isEmpty()) {
2221 Out << "this adjustment: ";
2222 Out << Thunk.This.NonVirtual << " non-virtual";
2223
2225 Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
2226 Out << " vcall offset offset";
2227 }
2228 }
2229
2230 Out << '\n';
2231 }
2232
2233 Out << '\n';
2234 }
2235 }
2236
2237 // Compute the vtable indices for all the member functions.
2238 // Store them in a map keyed by the index so we'll get a sorted table.
2239 std::map<uint64_t, std::string> IndicesMap;
2240
2241 for (const auto *MD : MostDerivedClass->methods()) {
2242 // We only want virtual member functions.
2244 continue;
2245 MD = MD->getCanonicalDecl();
2246
2247 std::string MethodName = PredefinedExpr::ComputeName(
2249
2250 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2251 GlobalDecl GD(DD, Dtor_Complete);
2252 assert(MethodVTableIndices.count(GD));
2253 uint64_t VTableIndex = MethodVTableIndices[GD];
2254 IndicesMap[VTableIndex] = MethodName + " [complete]";
2255 IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
2256 } else {
2257 assert(MethodVTableIndices.count(MD));
2258 IndicesMap[MethodVTableIndices[MD]] = MethodName;
2259 }
2260 }
2261
2262 // Print the vtable indices for all the member functions.
2263 if (!IndicesMap.empty()) {
2264 Out << "VTable indices for '";
2265 MostDerivedClass->printQualifiedName(Out);
2266 Out << "' (" << IndicesMap.size() << " entries).\n";
2267
2268 for (const auto &I : IndicesMap) {
2269 uint64_t VTableIndex = I.first;
2270 const std::string &MethodName = I.second;
2271
2272 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
2273 << '\n';
2274 }
2275 }
2276
2277 Out << '\n';
2278}
2279}
2280
2283 unsigned numVTables) {
2284 VTableLayout::AddressPointsIndexMapTy indexMap(numVTables);
2285
2286 for (auto it = addressPoints.begin(); it != addressPoints.end(); ++it) {
2287 const auto &addressPointLoc = it->second;
2288 unsigned vtableIndex = addressPointLoc.VTableIndex;
2289 unsigned addressPoint = addressPointLoc.AddressPointIndex;
2290 if (indexMap[vtableIndex]) {
2291 // Multiple BaseSubobjects can map to the same AddressPointLocation, but
2292 // every vtable index should have a unique address point.
2293 assert(indexMap[vtableIndex] == addressPoint &&
2294 "Every vtable index should have a unique address point. Found a "
2295 "vtable that has two different address points.");
2296 } else {
2297 indexMap[vtableIndex] = addressPoint;
2298 }
2299 }
2300
2301 // Note that by this point, not all the address may be initialized if the
2302 // AddressPoints map is empty. This is ok if the map isn't needed. See
2303 // MicrosoftVTableContext::computeVTableRelatedInformation() which uses an
2304 // emprt map.
2305 return indexMap;
2306}
2307
2309 ArrayRef<VTableComponent> VTableComponents,
2310 ArrayRef<VTableThunkTy> VTableThunks,
2311 const AddressPointsMapTy &AddressPoints)
2312 : VTableIndices(std::move(VTableIndices)),
2313 VTableComponents(VTableComponents), VTableThunks(VTableThunks),
2314 AddressPoints(AddressPoints),
2315 AddressPointIndices(
2316 MakeAddressPointIndices(AddressPoints, this->VTableIndices.size())) {
2317 assert(!this->VTableIndices.empty() &&
2318 "VTableLayout requires at least one index.");
2319 assert(this->VTableIndices.front() == 0 &&
2320 "VTableLayout requires the first index is 0.");
2321 llvm::sort(this->VTableThunks, [](const VTableLayout::VTableThunkTy &LHS,
2322 const VTableLayout::VTableThunkTy &RHS) {
2323 assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
2324 "Different thunks should have unique indices!");
2325 return LHS.first < RHS.first;
2326 });
2327}
2328
2330
2332 return MD->isVirtual() && !MD->isImmediateFunction();
2333}
2334
2337
2339
2341 GD = GD.getCanonicalDecl();
2342 MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2343 if (I != MethodVTableIndices.end())
2344 return I->second;
2345
2346 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2347
2348 computeVTableRelatedInformation(RD);
2349
2350 I = MethodVTableIndices.find(GD);
2351 assert(I != MethodVTableIndices.end() && "Did not find index!");
2352 return I->second;
2353}
2354
2357 const CXXRecordDecl *VBase) {
2358 ClassPairTy ClassPair(RD, VBase);
2359
2360 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2361 VirtualBaseClassOffsetOffsets.find(ClassPair);
2362 if (I != VirtualBaseClassOffsetOffsets.end())
2363 return I->second;
2364
2365 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*Overriders=*/nullptr,
2367 /*BaseIsVirtual=*/false,
2368 /*OffsetInLayoutClass=*/CharUnits::Zero());
2369
2370 for (const auto &I : Builder.getVBaseOffsetOffsets()) {
2371 // Insert all types.
2372 ClassPairTy ClassPair(RD, I.first);
2373
2374 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
2375 }
2376
2377 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2378 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2379
2380 return I->second;
2381}
2382
2384 const auto *MD = cast<CXXMethodDecl>(GD.getDecl()->getCanonicalDecl());
2385 computeVTableRelatedInformation(MD->getParent());
2386 const CXXMethodDecl *OriginalMD = findOriginalMethodInMap(MD);
2387
2388 if (const auto *DD = dyn_cast<CXXDestructorDecl>(OriginalMD))
2389 return GlobalDecl(DD, GD.getDtorType());
2390 return OriginalMD;
2391}
2392
2393const CXXMethodDecl *
2395 // Traverse the chain of virtual methods until we find the method that added
2396 // the v-table slot.
2397 while (true) {
2398 auto I = OriginalMethodMap.find(MD);
2399
2400 // MD doesn't exist in OriginalMethodMap, so it must be the method we are
2401 // looking for.
2402 if (I == OriginalMethodMap.end())
2403 break;
2404
2405 // Set MD to the overridden method.
2406 MD = I->second;
2407 }
2408
2409 return MD;
2410}
2411
2412static std::unique_ptr<VTableLayout>
2413CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
2415 VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
2416
2417 return std::make_unique<VTableLayout>(
2418 Builder.VTableIndices, Builder.vtable_components(), VTableThunks,
2419 Builder.getAddressPoints());
2420}
2421
2422void
2423ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
2424 std::unique_ptr<const VTableLayout> &Entry = VTableLayouts[RD];
2425
2426 // Check if we've computed this information before.
2427 if (Entry)
2428 return;
2429
2430 ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
2431 /*MostDerivedClassIsVirtual=*/false, RD);
2432 Entry = CreateVTableLayout(Builder);
2433
2434 MethodVTableIndices.insert(Builder.vtable_indices_begin(),
2435 Builder.vtable_indices_end());
2436
2437 // Add the known thunks.
2438 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2439
2440 // If we don't have the vbase information for this class, insert it.
2441 // getVirtualBaseOffsetOffset will compute it separately without computing
2442 // the rest of the vtable related information.
2443 if (!RD->getNumVBases())
2444 return;
2445
2446 const CXXRecordDecl *VBase =
2448
2449 if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2450 return;
2451
2452 for (const auto &I : Builder.getVBaseOffsetOffsets()) {
2453 // Insert all types.
2454 ClassPairTy ClassPair(RD, I.first);
2455
2456 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
2457 }
2458}
2459
2460std::unique_ptr<VTableLayout>
2462 const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
2463 bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
2464 ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
2465 MostDerivedClassIsVirtual, LayoutClass);
2466 return CreateVTableLayout(Builder);
2467}
2468
2469namespace {
2470
2471// Vtables in the Microsoft ABI are different from the Itanium ABI.
2472//
2473// The main differences are:
2474// 1. Separate vftable and vbtable.
2475//
2476// 2. Each subobject with a vfptr gets its own vftable rather than an address
2477// point in a single vtable shared between all the subobjects.
2478// Each vftable is represented by a separate section and virtual calls
2479// must be done using the vftable which has a slot for the function to be
2480// called.
2481//
2482// 3. Virtual method definitions expect their 'this' parameter to point to the
2483// first vfptr whose table provides a compatible overridden method. In many
2484// cases, this permits the original vf-table entry to directly call
2485// the method instead of passing through a thunk.
2486// See example before VFTableBuilder::ComputeThisOffset below.
2487//
2488// A compatible overridden method is one which does not have a non-trivial
2489// covariant-return adjustment.
2490//
2491// The first vfptr is the one with the lowest offset in the complete-object
2492// layout of the defining class, and the method definition will subtract
2493// that constant offset from the parameter value to get the real 'this'
2494// value. Therefore, if the offset isn't really constant (e.g. if a virtual
2495// function defined in a virtual base is overridden in a more derived
2496// virtual base and these bases have a reverse order in the complete
2497// object), the vf-table may require a this-adjustment thunk.
2498//
2499// 4. vftables do not contain new entries for overrides that merely require
2500// this-adjustment. Together with #3, this keeps vf-tables smaller and
2501// eliminates the need for this-adjustment thunks in many cases, at the cost
2502// of often requiring redundant work to adjust the "this" pointer.
2503//
2504// 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
2505// Vtordisps are emitted into the class layout if a class has
2506// a) a user-defined ctor/dtor
2507// and
2508// b) a method overriding a method in a virtual base.
2509//
2510// To get a better understanding of this code,
2511// you might want to see examples in test/CodeGenCXX/microsoft-abi-vtables-*.cpp
2512
2513class VFTableBuilder {
2514public:
2515 typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
2516 MethodVFTableLocationsTy;
2517
2518 typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
2519 method_locations_range;
2520
2521private:
2522 /// VTables - Global vtable information.
2523 MicrosoftVTableContext &VTables;
2524
2525 /// Context - The ASTContext which we will use for layout information.
2526 ASTContext &Context;
2527
2528 /// MostDerivedClass - The most derived class for which we're building this
2529 /// vtable.
2530 const CXXRecordDecl *MostDerivedClass;
2531
2532 const ASTRecordLayout &MostDerivedClassLayout;
2533
2534 const VPtrInfo &WhichVFPtr;
2535
2536 /// FinalOverriders - The final overriders of the most derived class.
2537 const FinalOverriders Overriders;
2538
2539 /// Components - The components of the vftable being built.
2541
2542 MethodVFTableLocationsTy MethodVFTableLocations;
2543
2544 /// Does this class have an RTTI component?
2545 bool HasRTTIComponent = false;
2546
2547 /// MethodInfo - Contains information about a method in a vtable.
2548 /// (Used for computing 'this' pointer adjustment thunks.
2549 struct MethodInfo {
2550 /// VBTableIndex - The nonzero index in the vbtable that
2551 /// this method's base has, or zero.
2552 const uint64_t VBTableIndex;
2553
2554 /// VFTableIndex - The index in the vftable that this method has.
2555 const uint64_t VFTableIndex;
2556
2557 /// Shadowed - Indicates if this vftable slot is shadowed by
2558 /// a slot for a covariant-return override. If so, it shouldn't be printed
2559 /// or used for vcalls in the most derived class.
2560 bool Shadowed;
2561
2562 /// UsesExtraSlot - Indicates if this vftable slot was created because
2563 /// any of the overridden slots required a return adjusting thunk.
2564 bool UsesExtraSlot;
2565
2566 MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex,
2567 bool UsesExtraSlot = false)
2568 : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
2569 Shadowed(false), UsesExtraSlot(UsesExtraSlot) {}
2570
2571 MethodInfo()
2572 : VBTableIndex(0), VFTableIndex(0), Shadowed(false),
2573 UsesExtraSlot(false) {}
2574 };
2575
2576 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
2577
2578 /// MethodInfoMap - The information for all methods in the vftable we're
2579 /// currently building.
2580 MethodInfoMapTy MethodInfoMap;
2581
2582 typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
2583
2584 /// VTableThunks - The thunks by vftable index in the vftable currently being
2585 /// built.
2586 VTableThunksMapTy VTableThunks;
2587
2588 typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
2589 typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
2590
2591 /// Thunks - A map that contains all the thunks needed for all methods in the
2592 /// most derived class for which the vftable is currently being built.
2593 ThunksMapTy Thunks;
2594
2595 /// AddThunk - Add a thunk for the given method.
2596 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
2597 SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
2598
2599 // Check if we have this thunk already.
2600 if (llvm::is_contained(ThunksVector, Thunk))
2601 return;
2602
2603 ThunksVector.push_back(Thunk);
2604 }
2605
2606 /// ComputeThisOffset - Returns the 'this' argument offset for the given
2607 /// method, relative to the beginning of the MostDerivedClass.
2608 CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
2609
2610 void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
2611 CharUnits ThisOffset, ThisAdjustment &TA);
2612
2613 /// AddMethod - Add a single virtual member function to the vftable
2614 /// components vector.
2615 void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
2616 if (!TI.isEmpty()) {
2617 VTableThunks[Components.size()] = TI;
2618 AddThunk(MD, TI);
2619 }
2620 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2621 assert(TI.Return.isEmpty() &&
2622 "Destructor can't have return adjustment!");
2623 Components.push_back(VTableComponent::MakeDeletingDtor(DD));
2624 } else {
2625 Components.push_back(VTableComponent::MakeFunction(MD));
2626 }
2627 }
2628
2629 /// AddMethods - Add the methods of this base subobject and the relevant
2630 /// subbases to the vftable we're currently laying out.
2631 void AddMethods(BaseSubobject Base, unsigned BaseDepth,
2632 const CXXRecordDecl *LastVBase,
2633 BasesSetVectorTy &VisitedBases);
2634
2635 void LayoutVFTable() {
2636 // RTTI data goes before all other entries.
2637 if (HasRTTIComponent)
2638 Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
2639
2640 BasesSetVectorTy VisitedBases;
2641 AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, nullptr,
2642 VisitedBases);
2643 // Note that it is possible for the vftable to contain only an RTTI
2644 // pointer, if all virtual functions are constewval.
2645 assert(!Components.empty() && "vftable can't be empty");
2646
2647 assert(MethodVFTableLocations.empty());
2648 for (const auto &I : MethodInfoMap) {
2649 const CXXMethodDecl *MD = I.first;
2650 const MethodInfo &MI = I.second;
2651 assert(MD == MD->getCanonicalDecl());
2652
2653 // Skip the methods that the MostDerivedClass didn't override
2654 // and the entries shadowed by return adjusting thunks.
2655 if (MD->getParent() != MostDerivedClass || MI.Shadowed)
2656 continue;
2657 MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
2658 WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
2659 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2660 // In Microsoft ABI vftable always references vector deleting dtor.
2662 Context.getLangOpts())
2664 : Dtor_Deleting;
2665 MethodVFTableLocations[GlobalDecl(DD, DtorTy)] = Loc;
2666 } else {
2667 MethodVFTableLocations[MD] = Loc;
2668 }
2669 }
2670 }
2671
2672public:
2673 VFTableBuilder(MicrosoftVTableContext &VTables,
2674 const CXXRecordDecl *MostDerivedClass, const VPtrInfo &Which)
2675 : VTables(VTables),
2676 Context(MostDerivedClass->getASTContext()),
2677 MostDerivedClass(MostDerivedClass),
2678 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
2679 WhichVFPtr(Which),
2680 Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
2681 // Provide the RTTI component if RTTIData is enabled. If the vftable would
2682 // be available externally, we should not provide the RTTI componenent. It
2683 // is currently impossible to get available externally vftables with either
2684 // dllimport or extern template instantiations, but eventually we may add a
2685 // flag to support additional devirtualization that needs this.
2686 if (Context.getLangOpts().RTTIData)
2687 HasRTTIComponent = true;
2688
2689 LayoutVFTable();
2690
2691 if (Context.getLangOpts().DumpVTableLayouts)
2692 dumpLayout(llvm::outs());
2693 }
2694
2695 uint64_t getNumThunks() const { return Thunks.size(); }
2696
2697 ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
2698
2699 ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
2700
2701 method_locations_range vtable_locations() const {
2702 return method_locations_range(MethodVFTableLocations.begin(),
2703 MethodVFTableLocations.end());
2704 }
2705
2706 ArrayRef<VTableComponent> vtable_components() const { return Components; }
2707
2708 VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
2709 return VTableThunks.begin();
2710 }
2711
2712 VTableThunksMapTy::const_iterator vtable_thunks_end() const {
2713 return VTableThunks.end();
2714 }
2715
2716 void dumpLayout(raw_ostream &);
2717};
2718
2719} // end namespace
2720
2721// Let's study one class hierarchy as an example:
2722// struct A {
2723// virtual void f();
2724// int x;
2725// };
2726//
2727// struct B : virtual A {
2728// virtual void f();
2729// };
2730//
2731// Record layouts:
2732// struct A:
2733// 0 | (A vftable pointer)
2734// 4 | int x
2735//
2736// struct B:
2737// 0 | (B vbtable pointer)
2738// 4 | struct A (virtual base)
2739// 4 | (A vftable pointer)
2740// 8 | int x
2741//
2742// Let's assume we have a pointer to the A part of an object of dynamic type B:
2743// B b;
2744// A *a = (A*)&b;
2745// a->f();
2746//
2747// In this hierarchy, f() belongs to the vftable of A, so B::f() expects
2748// "this" parameter to point at the A subobject, which is B+4.
2749// In the B::f() prologue, it adjusts "this" back to B by subtracting 4,
2750// performed as a *static* adjustment.
2751//
2752// Interesting thing happens when we alter the relative placement of A and B
2753// subobjects in a class:
2754// struct C : virtual B { };
2755//
2756// C c;
2757// A *a = (A*)&c;
2758// a->f();
2759//
2760// Respective record layout is:
2761// 0 | (C vbtable pointer)
2762// 4 | struct A (virtual base)
2763// 4 | (A vftable pointer)
2764// 8 | int x
2765// 12 | struct B (virtual base)
2766// 12 | (B vbtable pointer)
2767//
2768// The final overrider of f() in class C is still B::f(), so B+4 should be
2769// passed as "this" to that code. However, "a" points at B-8, so the respective
2770// vftable entry should hold a thunk that adds 12 to the "this" argument before
2771// performing a tail call to B::f().
2772//
2773// With this example in mind, we can now calculate the 'this' argument offset
2774// for the given method, relative to the beginning of the MostDerivedClass.
2776VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
2777 BasesSetVectorTy Bases;
2778
2779 {
2780 // Find the set of least derived bases that define the given method.
2781 OverriddenMethodsSetTy VisitedOverriddenMethods;
2782 auto InitialOverriddenDefinitionCollector = [&](
2783 const CXXMethodDecl *OverriddenMD) {
2784 if (OverriddenMD->size_overridden_methods() == 0)
2785 Bases.insert(OverriddenMD->getParent());
2786 // Don't recurse on this method if we've already collected it.
2787 return VisitedOverriddenMethods.insert(OverriddenMD).second;
2788 };
2789 visitAllOverriddenMethods(Overrider.Method,
2790 InitialOverriddenDefinitionCollector);
2791 }
2792
2793 // If there are no overrides then 'this' is located
2794 // in the base that defines the method.
2795 if (Bases.size() == 0)
2796 return Overrider.Offset;
2797
2798 CXXBasePaths Paths;
2799 Overrider.Method->getParent()->lookupInBases(
2800 [&Bases](const CXXBaseSpecifier *Specifier, CXXBasePath &) {
2801 return Bases.count(Specifier->getType()->getAsCXXRecordDecl());
2802 },
2803 Paths);
2804
2805 // This will hold the smallest this offset among overridees of MD.
2806 // This implies that an offset of a non-virtual base will dominate an offset
2807 // of a virtual base to potentially reduce the number of thunks required
2808 // in the derived classes that inherit this method.
2809 CharUnits Ret;
2810 bool First = true;
2811
2812 const ASTRecordLayout &OverriderRDLayout =
2813 Context.getASTRecordLayout(Overrider.Method->getParent());
2814 for (const CXXBasePath &Path : Paths) {
2815 CharUnits ThisOffset = Overrider.Offset;
2816 CharUnits LastVBaseOffset;
2817
2818 // For each path from the overrider to the parents of the overridden
2819 // methods, traverse the path, calculating the this offset in the most
2820 // derived class.
2821 for (const CXXBasePathElement &Element : Path) {
2822 QualType CurTy = Element.Base->getType();
2823 const CXXRecordDecl *PrevRD = Element.Class,
2824 *CurRD = CurTy->getAsCXXRecordDecl();
2825 const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
2826
2827 if (Element.Base->isVirtual()) {
2828 // The interesting things begin when you have virtual inheritance.
2829 // The final overrider will use a static adjustment equal to the offset
2830 // of the vbase in the final overrider class.
2831 // For example, if the final overrider is in a vbase B of the most
2832 // derived class and it overrides a method of the B's own vbase A,
2833 // it uses A* as "this". In its prologue, it can cast A* to B* with
2834 // a static offset. This offset is used regardless of the actual
2835 // offset of A from B in the most derived class, requiring an
2836 // this-adjusting thunk in the vftable if A and B are laid out
2837 // differently in the most derived class.
2838 LastVBaseOffset = ThisOffset =
2839 Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
2840 } else {
2841 ThisOffset += Layout.getBaseClassOffset(CurRD);
2842 }
2843 }
2844
2845 if (isa<CXXDestructorDecl>(Overrider.Method)) {
2846 if (LastVBaseOffset.isZero()) {
2847 // If a "Base" class has at least one non-virtual base with a virtual
2848 // destructor, the "Base" virtual destructor will take the address
2849 // of the "Base" subobject as the "this" argument.
2850 ThisOffset = Overrider.Offset;
2851 } else {
2852 // A virtual destructor of a virtual base takes the address of the
2853 // virtual base subobject as the "this" argument.
2854 ThisOffset = LastVBaseOffset;
2855 }
2856 }
2857
2858 if (Ret > ThisOffset || First) {
2859 First = false;
2860 Ret = ThisOffset;
2861 }
2862 }
2863
2864 assert(!First && "Method not found in the given subobject?");
2865 return Ret;
2866}
2867
2868// Things are getting even more complex when the "this" adjustment has to
2869// use a dynamic offset instead of a static one, or even two dynamic offsets.
2870// This is sometimes required when a virtual call happens in the middle of
2871// a non-most-derived class construction or destruction.
2872//
2873// Let's take a look at the following example:
2874// struct A {
2875// virtual void f();
2876// };
2877//
2878// void foo(A *a) { a->f(); } // Knows nothing about siblings of A.
2879//
2880// struct B : virtual A {
2881// virtual void f();
2882// B() {
2883// foo(this);
2884// }
2885// };
2886//
2887// struct C : virtual B {
2888// virtual void f();
2889// };
2890//
2891// Record layouts for these classes are:
2892// struct A
2893// 0 | (A vftable pointer)
2894//
2895// struct B
2896// 0 | (B vbtable pointer)
2897// 4 | (vtordisp for vbase A)
2898// 8 | struct A (virtual base)
2899// 8 | (A vftable pointer)
2900//
2901// struct C
2902// 0 | (C vbtable pointer)
2903// 4 | (vtordisp for vbase A)
2904// 8 | struct A (virtual base) // A precedes B!
2905// 8 | (A vftable pointer)
2906// 12 | struct B (virtual base)
2907// 12 | (B vbtable pointer)
2908//
2909// When one creates an object of type C, the C constructor:
2910// - initializes all the vbptrs, then
2911// - calls the A subobject constructor
2912// (initializes A's vfptr with an address of A vftable), then
2913// - calls the B subobject constructor
2914// (initializes A's vfptr with an address of B vftable and vtordisp for A),
2915// that in turn calls foo(), then
2916// - initializes A's vfptr with an address of C vftable and zeroes out the
2917// vtordisp
2918// FIXME: if a structor knows it belongs to MDC, why doesn't it use a vftable
2919// without vtordisp thunks?
2920// FIXME: how are vtordisp handled in the presence of nooverride/final?
2921//
2922// When foo() is called, an object with a layout of class C has a vftable
2923// referencing B::f() that assumes a B layout, so the "this" adjustments are
2924// incorrect, unless an extra adjustment is done. This adjustment is called
2925// "vtordisp adjustment". Vtordisp basically holds the difference between the
2926// actual location of a vbase in the layout class and the location assumed by
2927// the vftable of the class being constructed/destructed. Vtordisp is only
2928// needed if "this" escapes a
2929// structor (or we can't prove otherwise).
2930// [i.e. vtordisp is a dynamic adjustment for a static adjustment, which is an
2931// estimation of a dynamic adjustment]
2932//
2933// foo() gets a pointer to the A vbase and doesn't know anything about B or C,
2934// so it just passes that pointer as "this" in a virtual call.
2935// If there was no vtordisp, that would just dispatch to B::f().
2936// However, B::f() assumes B+8 is passed as "this",
2937// yet the pointer foo() passes along is B-4 (i.e. C+8).
2938// An extra adjustment is needed, so we emit a thunk into the B vftable.
2939// This vtordisp thunk subtracts the value of vtordisp
2940// from the "this" argument (-12) before making a tailcall to B::f().
2941//
2942// Let's consider an even more complex example:
2943// struct D : virtual B, virtual C {
2944// D() {
2945// foo(this);
2946// }
2947// };
2948//
2949// struct D
2950// 0 | (D vbtable pointer)
2951// 4 | (vtordisp for vbase A)
2952// 8 | struct A (virtual base) // A precedes both B and C!
2953// 8 | (A vftable pointer)
2954// 12 | struct B (virtual base) // B precedes C!
2955// 12 | (B vbtable pointer)
2956// 16 | struct C (virtual base)
2957// 16 | (C vbtable pointer)
2958//
2959// When D::D() calls foo(), we find ourselves in a thunk that should tailcall
2960// to C::f(), which assumes C+8 as its "this" parameter. This time, foo()
2961// passes along A, which is C-8. The A vtordisp holds
2962// "D.vbptr[index_of_A] - offset_of_A_in_D"
2963// and we statically know offset_of_A_in_D, so can get a pointer to D.
2964// When we know it, we can make an extra vbtable lookup to locate the C vbase
2965// and one extra static adjustment to calculate the expected value of C+8.
2966void VFTableBuilder::CalculateVtordispAdjustment(
2967 FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
2968 ThisAdjustment &TA) {
2969 const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
2970 MostDerivedClassLayout.getVBaseOffsetsMap();
2971 const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
2972 VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
2973 assert(VBaseMapEntry != VBaseMap.end());
2974
2975 // If there's no vtordisp or the final overrider is defined in the same vbase
2976 // as the initial declaration, we don't need any vtordisp adjustment.
2977 if (!VBaseMapEntry->second.hasVtorDisp() ||
2978 Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
2979 return;
2980
2981 // OK, now we know we need to use a vtordisp thunk.
2982 // The implicit vtordisp field is located right before the vbase.
2983 CharUnits OffsetOfVBaseWithVFPtr = VBaseMapEntry->second.VBaseOffset;
2985 (OffsetOfVBaseWithVFPtr - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
2986
2987 // A simple vtordisp thunk will suffice if the final overrider is defined
2988 // in either the most derived class or its non-virtual base.
2989 if (Overrider.Method->getParent() == MostDerivedClass ||
2990 !Overrider.VirtualBase)
2991 return;
2992
2993 // Otherwise, we need to do use the dynamic offset of the final overrider
2994 // in order to get "this" adjustment right.
2996 (OffsetOfVBaseWithVFPtr + WhichVFPtr.NonVirtualOffset -
2997 MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
2999 Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
3000 VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
3001
3002 TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
3003}
3004
3006 const CXXRecordDecl *RD,
3008 // Put the virtual methods into VirtualMethods in the proper order:
3009 // 1) Group overloads by declaration name. New groups are added to the
3010 // vftable in the order of their first declarations in this class
3011 // (including overrides, non-virtual methods and any other named decl that
3012 // might be nested within the class).
3013 // 2) In each group, new overloads appear in the reverse order of declaration.
3014 typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
3016 typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
3017 VisitedGroupIndicesTy VisitedGroupIndices;
3018 for (const auto *D : RD->decls()) {
3019 const auto *ND = dyn_cast<NamedDecl>(D);
3020 if (!ND)
3021 continue;
3022 VisitedGroupIndicesTy::iterator J;
3023 bool Inserted;
3024 std::tie(J, Inserted) = VisitedGroupIndices.insert(
3025 std::make_pair(ND->getDeclName(), Groups.size()));
3026 if (Inserted)
3027 Groups.push_back(MethodGroup());
3028 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
3030 Groups[J->second].push_back(MD->getCanonicalDecl());
3031 }
3032
3033 for (const MethodGroup &Group : Groups)
3034 VirtualMethods.append(Group.rbegin(), Group.rend());
3035}
3036
3037static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
3038 for (const auto &B : RD->bases()) {
3039 if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
3040 return true;
3041 }
3042 return false;
3043}
3044
3045void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
3046 const CXXRecordDecl *LastVBase,
3047 BasesSetVectorTy &VisitedBases) {
3048 const CXXRecordDecl *RD = Base.getBase();
3049 if (!RD->isPolymorphic())
3050 return;
3051
3052 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3053
3054 // See if this class expands a vftable of the base we look at, which is either
3055 // the one defined by the vfptr base path or the primary base of the current
3056 // class.
3057 const CXXRecordDecl *NextBase = nullptr, *NextLastVBase = LastVBase;
3058 CharUnits NextBaseOffset;
3059 if (BaseDepth < WhichVFPtr.PathToIntroducingObject.size()) {
3060 NextBase = WhichVFPtr.PathToIntroducingObject[BaseDepth];
3061 if (isDirectVBase(NextBase, RD)) {
3062 NextLastVBase = NextBase;
3063 NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
3064 } else {
3065 NextBaseOffset =
3066 Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
3067 }
3068 } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
3069 assert(!Layout.isPrimaryBaseVirtual() &&
3070 "No primary virtual bases in this ABI");
3071 NextBase = PrimaryBase;
3072 NextBaseOffset = Base.getBaseOffset();
3073 }
3074
3075 if (NextBase) {
3076 AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
3077 NextLastVBase, VisitedBases);
3078 if (!VisitedBases.insert(NextBase))
3079 llvm_unreachable("Found a duplicate primary base!");
3080 }
3081
3083 // Put virtual methods in the proper order.
3084 GroupNewVirtualOverloads(RD, VirtualMethods);
3085
3086 // Now go through all virtual member functions and add them to the current
3087 // vftable. This is done by
3088 // - replacing overridden methods in their existing slots, as long as they
3089 // don't require return adjustment; calculating This adjustment if needed.
3090 // - adding new slots for methods of the current base not present in any
3091 // sub-bases;
3092 // - adding new slots for methods that require Return adjustment.
3093 // We keep track of the methods visited in the sub-bases in MethodInfoMap.
3094 for (const CXXMethodDecl *MD : VirtualMethods) {
3095 FinalOverriders::OverriderInfo FinalOverrider =
3096 Overriders.getOverrider(MD, Base.getBaseOffset());
3097 const CXXMethodDecl *FinalOverriderMD = FinalOverrider.Method;
3098 const CXXMethodDecl *OverriddenMD =
3099 FindNearestOverriddenMethod(MD, VisitedBases);
3100
3101 ThisAdjustment ThisAdjustmentOffset;
3102 bool ReturnAdjustingThunk = false, ForceReturnAdjustmentMangling = false;
3103 CharUnits ThisOffset = ComputeThisOffset(FinalOverrider);
3104 ThisAdjustmentOffset.NonVirtual =
3105 (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
3106 if ((OverriddenMD || FinalOverriderMD != MD) &&
3107 WhichVFPtr.getVBaseWithVPtr())
3108 CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
3109 ThisAdjustmentOffset);
3110
3111 unsigned VBIndex =
3112 LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
3113
3114 if (OverriddenMD) {
3115 // If MD overrides anything in this vftable, we need to update the
3116 // entries.
3117 MethodInfoMapTy::iterator OverriddenMDIterator =
3118 MethodInfoMap.find(OverriddenMD);
3119
3120 // If the overridden method went to a different vftable, skip it.
3121 if (OverriddenMDIterator == MethodInfoMap.end())
3122 continue;
3123
3124 MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
3125
3126 VBIndex = OverriddenMethodInfo.VBTableIndex;
3127
3128 // Let's check if the overrider requires any return adjustments.
3129 // We must create a new slot if the MD's return type is not trivially
3130 // convertible to the OverriddenMD's one.
3131 // Once a chain of method overrides adds a return adjusting vftable slot,
3132 // all subsequent overrides will also use an extra method slot.
3133 ReturnAdjustingThunk = !ComputeReturnAdjustmentBaseOffset(
3134 Context, MD, OverriddenMD).isEmpty() ||
3135 OverriddenMethodInfo.UsesExtraSlot;
3136
3137 if (!ReturnAdjustingThunk) {
3138 // No return adjustment needed - just replace the overridden method info
3139 // with the current info.
3140 MethodInfo MI(VBIndex, OverriddenMethodInfo.VFTableIndex);
3141 MethodInfoMap.erase(OverriddenMDIterator);
3142
3143 assert(!MethodInfoMap.count(MD) &&
3144 "Should not have method info for this method yet!");
3145 MethodInfoMap.insert(std::make_pair(MD, MI));
3146 continue;
3147 }
3148
3149 // In case we need a return adjustment, we'll add a new slot for
3150 // the overrider. Mark the overridden method as shadowed by the new slot.
3151 OverriddenMethodInfo.Shadowed = true;
3152
3153 // Force a special name mangling for a return-adjusting thunk
3154 // unless the method is the final overrider without this adjustment.
3155 ForceReturnAdjustmentMangling =
3156 !(MD == FinalOverriderMD && ThisAdjustmentOffset.isEmpty());
3157 } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
3159 // Skip methods that don't belong to the vftable of the current class,
3160 // e.g. each method that wasn't seen in any of the visited sub-bases
3161 // but overrides multiple methods of other sub-bases.
3162 continue;
3163 }
3164
3165 // If we got here, MD is a method not seen in any of the sub-bases or
3166 // it requires return adjustment. Insert the method info for this method.
3167 MethodInfo MI(VBIndex,
3168 HasRTTIComponent ? Components.size() - 1 : Components.size(),
3169 ReturnAdjustingThunk);
3170
3171 assert(!MethodInfoMap.count(MD) &&
3172 "Should not have method info for this method yet!");
3173 MethodInfoMap.insert(std::make_pair(MD, MI));
3174
3175 // Check if this overrider needs a return adjustment.
3176 // We don't want to do this for pure virtual member functions.
3177 BaseOffset ReturnAdjustmentOffset;
3179 if (!FinalOverriderMD->isPureVirtual()) {
3180 ReturnAdjustmentOffset =
3181 ComputeReturnAdjustmentBaseOffset(Context, FinalOverriderMD, MD);
3182 }
3183 if (!ReturnAdjustmentOffset.isEmpty()) {
3184 ForceReturnAdjustmentMangling = true;
3186 ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
3187 if (ReturnAdjustmentOffset.VirtualBase) {
3188 const ASTRecordLayout &DerivedLayout =
3189 Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
3191 DerivedLayout.getVBPtrOffset().getQuantity();
3193 VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
3194 ReturnAdjustmentOffset.VirtualBase);
3195 }
3196 }
3197 auto ThisType = (OverriddenMD ? OverriddenMD : MD)->getThisType().getTypePtr();
3198 AddMethod(FinalOverriderMD,
3199 ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment, ThisType,
3200 ForceReturnAdjustmentMangling ? MD : nullptr));
3201 }
3202}
3203
3204static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
3205 for (const CXXRecordDecl *Elem : llvm::reverse(Path)) {
3206 Out << "'";
3207 Elem->printQualifiedName(Out);
3208 Out << "' in ";
3209 }
3210}
3211
3212static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
3213 bool ContinueFirstLine) {
3214 const ReturnAdjustment &R = TI.Return;
3215 bool Multiline = false;
3216 const char *LinePrefix = "\n ";
3217 if (!R.isEmpty() || TI.Method) {
3218 if (!ContinueFirstLine)
3219 Out << LinePrefix;
3220 Out << "[return adjustment (to type '"
3221 << TI.Method->getReturnType().getCanonicalType() << "'): ";
3222 if (R.Virtual.Microsoft.VBPtrOffset)
3223 Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
3224 if (R.Virtual.Microsoft.VBIndex)
3225 Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
3226 Out << R.NonVirtual << " non-virtual]";
3227 Multiline = true;
3228 }
3229
3230 const ThisAdjustment &T = TI.This;
3231 if (!T.isEmpty()) {
3232 if (Multiline || !ContinueFirstLine)
3233 Out << LinePrefix;
3234 Out << "[this adjustment: ";
3235 if (!TI.This.Virtual.isEmpty()) {
3236 assert(T.Virtual.Microsoft.VtordispOffset < 0);
3237 Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
3238 if (T.Virtual.Microsoft.VBPtrOffset) {
3239 Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
3240 << " to the left,";
3241 assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
3242 Out << LinePrefix << " vboffset at "
3243 << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
3244 }
3245 }
3246 Out << T.NonVirtual << " non-virtual]";
3247 }
3248}
3249
3250void VFTableBuilder::dumpLayout(raw_ostream &Out) {
3251 Out << "VFTable for ";
3252 PrintBasePath(WhichVFPtr.PathToIntroducingObject, Out);
3253 Out << "'";
3254 MostDerivedClass->printQualifiedName(Out);
3255 Out << "' (" << Components.size()
3256 << (Components.size() == 1 ? " entry" : " entries") << ").\n";
3257
3258 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
3259 Out << llvm::format("%4d | ", I);
3260
3261 const VTableComponent &Component = Components[I];
3262
3263 // Dump the component.
3264 switch (Component.getKind()) {
3266 Component.getRTTIDecl()->printQualifiedName(Out);
3267 Out << " RTTI";
3268 break;
3269
3271 const CXXMethodDecl *MD = Component.getFunctionDecl();
3272
3273 // FIXME: Figure out how to print the real thunk type, since they can
3274 // differ in the return type.
3275 std::string Str = PredefinedExpr::ComputeName(
3277 Out << Str;
3278 if (MD->isPureVirtual())
3279 Out << " [pure]";
3280
3281 if (MD->isDeleted())
3282 Out << " [deleted]";
3283
3284 ThunkInfo Thunk = VTableThunks.lookup(I);
3285 if (!Thunk.isEmpty())
3286 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
3287
3288 break;
3289 }
3290
3292 const CXXDestructorDecl *DD = Component.getDestructorDecl();
3293
3294 DD->printQualifiedName(Out);
3296 Context.getLangOpts()))
3297 Out << "() [vector deleting]";
3298 else
3299 Out << "() [scalar deleting]";
3300
3301 if (DD->isPureVirtual())
3302 Out << " [pure]";
3303
3304 ThunkInfo Thunk = VTableThunks.lookup(I);
3305 if (!Thunk.isEmpty()) {
3306 assert(Thunk.Return.isEmpty() &&
3307 "No return adjustment needed for destructors!");
3308 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
3309 }
3310
3311 break;
3312 }
3313
3314 default:
3315 DiagnosticsEngine &Diags = Context.getDiagnostics();
3316 Diags.Report(MostDerivedClass->getLocation(),
3317 diag::err_unexpected_vftable_component)
3318 << Component.getKind() << I;
3319 }
3320
3321 Out << '\n';
3322 }
3323
3324 Out << '\n';
3325
3326 if (!Thunks.empty()) {
3327 // We store the method names in a map to get a stable order.
3328 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
3329
3330 for (const auto &I : Thunks) {
3331 const CXXMethodDecl *MD = I.first;
3332 std::string MethodName = PredefinedExpr::ComputeName(
3334
3335 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
3336 }
3337
3338 for (const auto &MethodNameAndDecl : MethodNamesAndDecls) {
3339 const std::string &MethodName = MethodNameAndDecl.first;
3340 const CXXMethodDecl *MD = MethodNameAndDecl.second;
3341
3342 ThunkInfoVectorTy ThunksVector = Thunks[MD];
3343 llvm::stable_sort(ThunksVector, [](const ThunkInfo &LHS,
3344 const ThunkInfo &RHS) {
3345 // Keep different thunks with the same adjustments in the order they
3346 // were put into the vector.
3347 return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
3348 });
3349
3350 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
3351 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
3352
3353 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
3354 const ThunkInfo &Thunk = ThunksVector[I];
3355
3356 Out << llvm::format("%4d | ", I);
3357 dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
3358 Out << '\n';
3359 }
3360
3361 Out << '\n';
3362 }
3363 }
3364
3365 Out.flush();
3366}
3367
3370 for (const CXXRecordDecl *Decl : B) {
3371 if (A.count(Decl))
3372 return true;
3373 }
3374 return false;
3375}
3376
3377static bool rebucketPaths(VPtrInfoVector &Paths);
3378
3379/// Produces MSVC-compatible vbtable data. The symbols produced by this
3380/// algorithm match those produced by MSVC 2012 and newer, which is different
3381/// from MSVC 2010.
3382///
3383/// MSVC 2012 appears to minimize the vbtable names using the following
3384/// algorithm. First, walk the class hierarchy in the usual order, depth first,
3385/// left to right, to find all of the subobjects which contain a vbptr field.
3386/// Visiting each class node yields a list of inheritance paths to vbptrs. Each
3387/// record with a vbptr creates an initially empty path.
3388///
3389/// To combine paths from child nodes, the paths are compared to check for
3390/// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
3391/// components in the same order. Each group of ambiguous paths is extended by
3392/// appending the class of the base from which it came. If the current class
3393/// node produced an ambiguous path, its path is extended with the current class.
3394/// After extending paths, MSVC again checks for ambiguity, and extends any
3395/// ambiguous path which wasn't already extended. Because each node yields an
3396/// unambiguous set of paths, MSVC doesn't need to extend any path more than once
3397/// to produce an unambiguous set of paths.
3398///
3399/// TODO: Presumably vftables use the same algorithm.
3400void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
3401 const CXXRecordDecl *RD,
3402 VPtrInfoVector &Paths) {
3403 assert(Paths.empty());
3404 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3405
3406 // Base case: this subobject has its own vptr.
3407 if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
3408 Paths.push_back(std::make_unique<VPtrInfo>(RD));
3409
3410 // Recursive case: get all the vbtables from our bases and remove anything
3411 // that shares a virtual base.
3412 llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
3413 for (const auto &B : RD->bases()) {
3414 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
3415 if (B.isVirtual() && VBasesSeen.count(Base))
3416 continue;
3417
3418 if (!Base->isDynamicClass())
3419 continue;
3420
3421 const VPtrInfoVector &BasePaths =
3422 ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
3423
3424 for (const std::unique_ptr<VPtrInfo> &BaseInfo : BasePaths) {
3425 // Don't include the path if it goes through a virtual base that we've
3426 // already included.
3427 if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
3428 continue;
3429
3430 // Copy the path and adjust it as necessary.
3431 auto P = std::make_unique<VPtrInfo>(*BaseInfo);
3432
3433 // We mangle Base into the path if the path would've been ambiguous and it
3434 // wasn't already extended with Base.
3435 if (P->MangledPath.empty() || P->MangledPath.back() != Base)
3436 P->NextBaseToMangle = Base;
3437
3438 // Keep track of which vtable the derived class is going to extend with
3439 // new methods or bases. We append to either the vftable of our primary
3440 // base, or the first non-virtual base that has a vbtable.
3441 if (P->ObjectWithVPtr == Base &&
3442 Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
3443 : Layout.getPrimaryBase()))
3444 P->ObjectWithVPtr = RD;
3445
3446 // Keep track of the full adjustment from the MDC to this vtable. The
3447 // adjustment is captured by an optional vbase and a non-virtual offset.
3448 if (B.isVirtual())
3449 P->ContainingVBases.push_back(Base);
3450 else if (P->ContainingVBases.empty())
3451 P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
3452
3453 // Update the full offset in the MDC.
3454 P->FullOffsetInMDC = P->NonVirtualOffset;
3455 if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
3456 P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
3457
3458 Paths.push_back(std::move(P));
3459 }
3460
3461 if (B.isVirtual())
3462 VBasesSeen.insert(Base);
3463
3464 // After visiting any direct base, we've transitively visited all of its
3465 // morally virtual bases.
3466 for (const auto &VB : Base->vbases())
3467 VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
3468 }
3469
3470 // Sort the paths into buckets, and if any of them are ambiguous, extend all
3471 // paths in ambiguous buckets.
3472 bool Changed = true;
3473 while (Changed)
3474 Changed = rebucketPaths(Paths);
3475}
3476
3477static bool extendPath(VPtrInfo &P) {
3478 if (P.NextBaseToMangle) {
3479 P.MangledPath.push_back(P.NextBaseToMangle);
3480 P.NextBaseToMangle = nullptr;// Prevent the path from being extended twice.
3481 return true;
3482 }
3483 return false;
3484}
3485
3486static bool rebucketPaths(VPtrInfoVector &Paths) {
3487 // What we're essentially doing here is bucketing together ambiguous paths.
3488 // Any bucket with more than one path in it gets extended by NextBase, which
3489 // is usually the direct base of the inherited the vbptr. This code uses a
3490 // sorted vector to implement a multiset to form the buckets. Note that the
3491 // ordering is based on pointers, but it doesn't change our output order. The
3492 // current algorithm is designed to match MSVC 2012's names.
3494 llvm::make_pointee_range(Paths));
3495 llvm::sort(PathsSorted, [](const VPtrInfo &LHS, const VPtrInfo &RHS) {
3496 return LHS.MangledPath < RHS.MangledPath;
3497 });
3498 bool Changed = false;
3499 for (size_t I = 0, E = PathsSorted.size(); I != E;) {
3500 // Scan forward to find the end of the bucket.
3501 size_t BucketStart = I;
3502 do {
3503 ++I;
3504 } while (I != E &&
3505 PathsSorted[BucketStart].get().MangledPath ==
3506 PathsSorted[I].get().MangledPath);
3507
3508 // If this bucket has multiple paths, extend them all.
3509 if (I - BucketStart > 1) {
3510 for (size_t II = BucketStart; II != I; ++II)
3511 Changed |= extendPath(PathsSorted[II]);
3512 assert(Changed && "no paths were extended to fix ambiguity");
3513 }
3514 }
3515 return Changed;
3516}
3517
3519
3520namespace {
3521typedef llvm::SetVector<BaseSubobject, std::vector<BaseSubobject>,
3522 llvm::DenseSet<BaseSubobject>> FullPathTy;
3523}
3524
3525// This recursive function finds all paths from a subobject centered at
3526// (RD, Offset) to the subobject located at IntroducingObject.
3528 const ASTRecordLayout &MostDerivedLayout,
3529 const CXXRecordDecl *RD, CharUnits Offset,
3530 BaseSubobject IntroducingObject,
3531 FullPathTy &FullPath,
3532 std::list<FullPathTy> &Paths) {
3533 if (BaseSubobject(RD, Offset) == IntroducingObject) {
3534 Paths.push_back(FullPath);
3535 return;
3536 }
3537
3538 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3539
3540 for (const CXXBaseSpecifier &BS : RD->bases()) {
3541 const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
3542 CharUnits NewOffset = BS.isVirtual()
3543 ? MostDerivedLayout.getVBaseClassOffset(Base)
3544 : Offset + Layout.getBaseClassOffset(Base);
3545 FullPath.insert(BaseSubobject(Base, NewOffset));
3546 findPathsToSubobject(Context, MostDerivedLayout, Base, NewOffset,
3547 IntroducingObject, FullPath, Paths);
3548 FullPath.pop_back();
3549 }
3550}
3551
3552// Return the paths which are not subsets of other paths.
3553static void removeRedundantPaths(std::list<FullPathTy> &FullPaths) {
3554 FullPaths.remove_if([&](const FullPathTy &SpecificPath) {
3555 for (const FullPathTy &OtherPath : FullPaths) {
3556 if (&SpecificPath == &OtherPath)
3557 continue;
3558 if (llvm::all_of(SpecificPath, [&](const BaseSubobject &BSO) {
3559 return OtherPath.contains(BSO);
3560 })) {
3561 return true;
3562 }
3563 }
3564 return false;
3565 });
3566}
3567
3569 const CXXRecordDecl *RD,
3570 const FullPathTy &FullPath) {
3571 const ASTRecordLayout &MostDerivedLayout =
3572 Context.getASTRecordLayout(RD);
3574 for (const BaseSubobject &BSO : FullPath) {
3575 const CXXRecordDecl *Base = BSO.getBase();
3576 // The first entry in the path is always the most derived record, skip it.
3577 if (Base == RD) {
3578 assert(Offset.getQuantity() == -1);
3579 Offset = CharUnits::Zero();
3580 continue;
3581 }
3582 assert(Offset.getQuantity() != -1);
3583 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3584 // While we know which base has to be traversed, we don't know if that base
3585 // was a virtual base.
3586 const CXXBaseSpecifier *BaseBS = std::find_if(
3587 RD->bases_begin(), RD->bases_end(), [&](const CXXBaseSpecifier &BS) {
3588 return BS.getType()->getAsCXXRecordDecl() == Base;
3589 });
3590 Offset = BaseBS->isVirtual() ? MostDerivedLayout.getVBaseClassOffset(Base)
3591 : Offset + Layout.getBaseClassOffset(Base);
3592 RD = Base;
3593 }
3594 return Offset;
3595}
3596
3597// We want to select the path which introduces the most covariant overrides. If
3598// two paths introduce overrides which the other path doesn't contain, issue a
3599// diagnostic.
3600static const FullPathTy *selectBestPath(ASTContext &Context,
3601 const CXXRecordDecl *RD,
3602 const VPtrInfo &Info,
3603 std::list<FullPathTy> &FullPaths) {
3604 // Handle some easy cases first.
3605 if (FullPaths.empty())
3606 return nullptr;
3607 if (FullPaths.size() == 1)
3608 return &FullPaths.front();
3609
3610 const FullPathTy *BestPath = nullptr;
3611 typedef std::set<const CXXMethodDecl *> OverriderSetTy;
3612 OverriderSetTy LastOverrides;
3613 for (const FullPathTy &SpecificPath : FullPaths) {
3614 assert(!SpecificPath.empty());
3615 OverriderSetTy CurrentOverrides;
3616 const CXXRecordDecl *TopLevelRD = SpecificPath.begin()->getBase();
3617 // Find the distance from the start of the path to the subobject with the
3618 // VPtr.
3619 CharUnits BaseOffset =
3620 getOffsetOfFullPath(Context, TopLevelRD, SpecificPath);
3621 FinalOverriders Overriders(TopLevelRD, CharUnits::Zero(), TopLevelRD);
3622 for (const CXXMethodDecl *MD : Info.IntroducingObject->methods()) {
3624 continue;
3625 FinalOverriders::OverriderInfo OI =
3626 Overriders.getOverrider(MD->getCanonicalDecl(), BaseOffset);
3627 const CXXMethodDecl *OverridingMethod = OI.Method;
3628 // Only overriders which have a return adjustment introduce problematic
3629 // thunks.
3630 if (ComputeReturnAdjustmentBaseOffset(Context, OverridingMethod, MD)
3631 .isEmpty())
3632 continue;
3633 // It's possible that the overrider isn't in this path. If so, skip it
3634 // because this path didn't introduce it.
3635 const CXXRecordDecl *OverridingParent = OverridingMethod->getParent();
3636 if (llvm::none_of(SpecificPath, [&](const BaseSubobject &BSO) {
3637 return BSO.getBase() == OverridingParent;
3638 }))
3639 continue;
3640 CurrentOverrides.insert(OverridingMethod);
3641 }
3642 OverriderSetTy NewOverrides =
3643 llvm::set_difference(CurrentOverrides, LastOverrides);
3644 if (NewOverrides.empty())
3645 continue;
3646 OverriderSetTy MissingOverrides =
3647 llvm::set_difference(LastOverrides, CurrentOverrides);
3648 if (MissingOverrides.empty()) {
3649 // This path is a strict improvement over the last path, let's use it.
3650 BestPath = &SpecificPath;
3651 std::swap(CurrentOverrides, LastOverrides);
3652 } else {
3653 // This path introduces an overrider with a conflicting covariant thunk.
3654 DiagnosticsEngine &Diags = Context.getDiagnostics();
3655 const CXXMethodDecl *CovariantMD = *NewOverrides.begin();
3656 const CXXMethodDecl *ConflictMD = *MissingOverrides.begin();
3657 Diags.Report(RD->getLocation(), diag::err_vftable_ambiguous_component)
3658 << RD;
3659 Diags.Report(CovariantMD->getLocation(), diag::note_covariant_thunk)
3660 << CovariantMD;
3661 Diags.Report(ConflictMD->getLocation(), diag::note_covariant_thunk)
3662 << ConflictMD;
3663 }
3664 }
3665 // Go with the path that introduced the most covariant overrides. If there is
3666 // no such path, pick the first path.
3667 return BestPath ? BestPath : &FullPaths.front();
3668}
3669
3671 const CXXRecordDecl *RD,
3672 VPtrInfoVector &Paths) {
3673 const ASTRecordLayout &MostDerivedLayout = Context.getASTRecordLayout(RD);
3674 FullPathTy FullPath;
3675 std::list<FullPathTy> FullPaths;
3676 for (const std::unique_ptr<VPtrInfo>& Info : Paths) {
3678 Context, MostDerivedLayout, RD, CharUnits::Zero(),
3679 BaseSubobject(Info->IntroducingObject, Info->FullOffsetInMDC), FullPath,
3680 FullPaths);
3681 FullPath.clear();
3682 removeRedundantPaths(FullPaths);
3683 Info->PathToIntroducingObject.clear();
3684 if (const FullPathTy *BestPath =
3685 selectBestPath(Context, RD, *Info, FullPaths))
3686 for (const BaseSubobject &BSO : *BestPath)
3687 Info->PathToIntroducingObject.push_back(BSO.getBase());
3688 FullPaths.clear();
3689 }
3690}
3691
3692static bool vfptrIsEarlierInMDC(const ASTRecordLayout &Layout,
3693 const MethodVFTableLocation &LHS,
3694 const MethodVFTableLocation &RHS) {
3695 CharUnits L = LHS.VFPtrOffset;
3696 CharUnits R = RHS.VFPtrOffset;
3697 if (LHS.VBase)
3698 L += Layout.getVBaseClassOffset(LHS.VBase);
3699 if (RHS.VBase)
3700 R += Layout.getVBaseClassOffset(RHS.VBase);
3701 return L < R;
3702}
3703
3704void MicrosoftVTableContext::computeVTableRelatedInformation(
3705 const CXXRecordDecl *RD) {
3706 assert(RD->isDynamicClass());
3707
3708 // Check if we've computed this information before.
3709 if (VFPtrLocations.count(RD))
3710 return;
3711
3712 const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
3713
3714 {
3715 auto VFPtrs = std::make_unique<VPtrInfoVector>();
3716 computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
3717 computeFullPathsForVFTables(Context, RD, *VFPtrs);
3718 VFPtrLocations[RD] = std::move(VFPtrs);
3719 }
3720
3721 MethodVFTableLocationsTy NewMethodLocations;
3722 for (const std::unique_ptr<VPtrInfo> &VFPtr : *VFPtrLocations[RD]) {
3723 VFTableBuilder Builder(*this, RD, *VFPtr);
3724
3725 VFTableIdTy id(RD, VFPtr->FullOffsetInMDC);
3726 assert(VFTableLayouts.count(id) == 0);
3727 SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
3728 Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
3729 VFTableLayouts[id] = std::make_unique<VTableLayout>(
3730 VTableLayout::VTableIndicesTy{0}, Builder.vtable_components(),
3731 VTableThunks, EmptyAddressPointsMap);
3732 Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
3733
3734 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3735 for (const auto &Loc : Builder.vtable_locations()) {
3736 auto Insert = NewMethodLocations.insert(Loc);
3737 if (!Insert.second) {
3738 const MethodVFTableLocation &NewLoc = Loc.second;
3739 MethodVFTableLocation &OldLoc = Insert.first->second;
3740 if (vfptrIsEarlierInMDC(Layout, NewLoc, OldLoc))
3741 OldLoc = NewLoc;
3742 }
3743 }
3744 }
3745
3746 MethodVFTableLocations.insert_range(NewMethodLocations);
3747 if (Context.getLangOpts().DumpVTableLayouts)
3748 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
3749}
3750
3751void MicrosoftVTableContext::dumpMethodLocations(
3752 const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
3753 raw_ostream &Out) {
3754 // Compute the vtable indices for all the member functions.
3755 // Store them in a map keyed by the location so we'll get a sorted table.
3756 std::map<MethodVFTableLocation, std::string> IndicesMap;
3757 bool HasNonzeroOffset = false;
3758
3759 for (const auto &I : NewMethods) {
3760 const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I.first.getDecl());
3761 assert(hasVtableSlot(MD));
3762
3763 std::string MethodName = PredefinedExpr::ComputeName(
3765
3766 if (isa<CXXDestructorDecl>(MD)) {
3767 IndicesMap[I.second] = MethodName + " [vector deleting]";
3768 } else {
3769 IndicesMap[I.second] = MethodName;
3770 }
3771
3772 if (!I.second.VFPtrOffset.isZero() || I.second.VBTableIndex != 0)
3773 HasNonzeroOffset = true;
3774 }
3775
3776 // Print the vtable indices for all the member functions.
3777 if (!IndicesMap.empty()) {
3778 Out << "VFTable indices for ";
3779 Out << "'";
3780 RD->printQualifiedName(Out);
3781 Out << "' (" << IndicesMap.size()
3782 << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
3783
3784 CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
3785 uint64_t LastVBIndex = 0;
3786 for (const auto &I : IndicesMap) {
3787 CharUnits VFPtrOffset = I.first.VFPtrOffset;
3788 uint64_t VBIndex = I.first.VBTableIndex;
3789 if (HasNonzeroOffset &&
3790 (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
3791 assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
3792 Out << " -- accessible via ";
3793 if (VBIndex)
3794 Out << "vbtable index " << VBIndex << ", ";
3795 Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
3796 LastVFPtrOffset = VFPtrOffset;
3797 LastVBIndex = VBIndex;
3798 }
3799
3800 uint64_t VTableIndex = I.first.Index;
3801 const std::string &MethodName = I.second;
3802 Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
3803 }
3804 Out << '\n';
3805 }
3806
3807 Out.flush();
3808}
3809
3810const VirtualBaseInfo &MicrosoftVTableContext::computeVBTableRelatedInformation(
3811 const CXXRecordDecl *RD) {
3812 VirtualBaseInfo *VBI;
3813
3814 {
3815 // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
3816 // as it may be modified and rehashed under us.
3817 std::unique_ptr<VirtualBaseInfo> &Entry = VBaseInfo[RD];
3818 if (Entry)
3819 return *Entry;
3820 Entry = std::make_unique<VirtualBaseInfo>();
3821 VBI = Entry.get();
3822 }
3823
3824 computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
3825
3826 // First, see if the Derived class shared the vbptr with a non-virtual base.
3827 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3828 if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
3829 // If the Derived class shares the vbptr with a non-virtual base, the shared
3830 // virtual bases come first so that the layout is the same.
3831 const VirtualBaseInfo &BaseInfo =
3832 computeVBTableRelatedInformation(VBPtrBase);
3833 VBI->VBTableIndices.insert_range(BaseInfo.VBTableIndices);
3834 }
3835
3836 // New vbases are added to the end of the vbtable.
3837 // Skip the self entry and vbases visited in the non-virtual base, if any.
3838 unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
3839 for (const auto &VB : RD->vbases()) {
3840 const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
3841 if (VBI->VBTableIndices.try_emplace(CurVBase, VBTableIndex).second)
3842 ++VBTableIndex;
3843 }
3844
3845 return *VBI;
3846}
3847
3849 const CXXRecordDecl *VBase) {
3850 const VirtualBaseInfo &VBInfo = computeVBTableRelatedInformation(Derived);
3851 assert(VBInfo.VBTableIndices.count(VBase));
3852 return VBInfo.VBTableIndices.find(VBase)->second;
3853}
3854
3855const VPtrInfoVector &
3857 return computeVBTableRelatedInformation(RD).VBPtrPaths;
3858}
3859
3860const VPtrInfoVector &
3862 computeVTableRelatedInformation(RD);
3863
3864 assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
3865 return *VFPtrLocations[RD];
3866}
3867
3868const VTableLayout &
3870 CharUnits VFPtrOffset) {
3871 computeVTableRelatedInformation(RD);
3872
3873 VFTableIdTy id(RD, VFPtrOffset);
3874 assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
3875 return *VFTableLayouts[id];
3876}
3877
3881 "Only use this method for virtual methods or dtors");
3883 assert(GD.getDtorType() == Dtor_VectorDeleting ||
3884 GD.getDtorType() == Dtor_Deleting);
3885
3886 GD = GD.getCanonicalDecl();
3887
3888 MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
3889 if (I != MethodVFTableLocations.end())
3890 return I->second;
3891
3892 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
3893
3894 computeVTableRelatedInformation(RD);
3895
3896 I = MethodVFTableLocations.find(GD);
3897 assert(I != MethodVFTableLocations.end() && "Did not find index!");
3898 return I->second;
3899}
Defines the clang::ASTContext interface.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
static Decl::Kind getKind(const Decl *D)
static QualType getPointeeType(const MemRegion *R)
static void findPathsToSubobject(ASTContext &Context, const ASTRecordLayout &MostDerivedLayout, const CXXRecordDecl *RD, CharUnits Offset, BaseSubobject IntroducingObject, FullPathTy &FullPath, std::list< FullPathTy > &Paths)
static const FullPathTy * selectBestPath(ASTContext &Context, const CXXRecordDecl *RD, const VPtrInfo &Info, std::list< FullPathTy > &FullPaths)
static CharUnits getOffsetOfFullPath(ASTContext &Context, const CXXRecordDecl *RD, const FullPathTy &FullPath)
static void removeRedundantPaths(std::list< FullPathTy > &FullPaths)
static std::unique_ptr< VTableLayout > CreateVTableLayout(const ItaniumVTableBuilder &Builder)
static bool vfptrIsEarlierInMDC(const ASTRecordLayout &Layout, const MethodVFTableLocation &LHS, const MethodVFTableLocation &RHS)
static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD)
static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out)
static VTableLayout::AddressPointsIndexMapTy MakeAddressPointIndices(const VTableLayout::AddressPointsMapTy &addressPoints, unsigned numVTables)
static bool rebucketPaths(VPtrInfoVector &Paths)
static bool extendPath(VPtrInfo &P)
static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out, bool ContinueFirstLine)
static void GroupNewVirtualOverloads(const CXXRecordDecl *RD, SmallVector< const CXXMethodDecl *, 10 > &VirtualMethods)
static void computeFullPathsForVFTables(ASTContext &Context, const CXXRecordDecl *RD, VPtrInfoVector &Paths)
static bool setsIntersect(const llvm::SmallPtrSet< const CXXRecordDecl *, 4 > &A, ArrayRef< const CXXRecordDecl * > B)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
const LangOptions & getLangOpts() const
CanQualType IntTy
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:974
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
bool hasOwnVFPtr() const
hasOwnVFPtr - Does this class provide its own virtual-function table pointer, rather than inheriting ...
const CXXRecordDecl * getBaseSharingVBPtr() const
bool hasOwnVBPtr() const
hasOwnVBPtr - Does this class provide its own virtual-base table pointer, rather than inheriting one ...
llvm::DenseMap< const CXXRecordDecl *, VBaseInfo > VBaseOffsetsMapTy
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
const VBaseOffsetsMapTy & getVBaseOffsetsMap() const
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
bool isPrimaryBaseVirtual() const
isPrimaryBaseVirtual - Get whether the primary base for this record is virtual or not.
const CXXRecordDecl * getBase() const
getBase - Returns the base class declaration.
CharUnits getBaseOffset() const
getBaseOffset - Returns the base class offset.
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
Represents a base class of a C++ class.
Definition DeclCXX.h:146
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
bool isVirtual() const
Definition DeclCXX.h:2208
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2828
unsigned size_overridden_methods() const
Definition DeclCXX.cpp:2822
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
QualType getThisType() const
Return the type of the this pointer.
Definition DeclCXX.cpp:2859
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2266
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
base_class_iterator bases_end()
Definition DeclCXX.h:618
base_class_range bases()
Definition DeclCXX.h:609
method_range methods() const
Definition DeclCXX.h:651
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition DeclCXX.h:616
base_class_range vbases()
Definition DeclCXX.h:626
base_class_iterator vbases_begin()
Definition DeclCXX.h:633
bool isDynamicClass() const
Definition DeclCXX.h:575
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:624
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static constexpr CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2110
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2407
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
SourceLocation getLocation() const
Definition DeclBase.h:448
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
The name of a declaration.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:240
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool isImmediateFunction() const
Definition Decl.cpp:3416
QualType getReturnType() const
Definition Decl.h:3022
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2709
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2522
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4208
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
Qualifiers getMethodQuals() const
Definition TypeBase.h:5974
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5833
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
QualType getReturnType() const
Definition TypeBase.h:5084
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
GlobalDecl getCanonicalDecl() const
Definition GlobalDecl.h:106
CXXDtorType getDtorType() const
Definition GlobalDecl.h:122
const Decl * getDecl() const
Definition GlobalDecl.h:115
const CXXMethodDecl * findOriginalMethodInMap(const CXXMethodDecl *MD) const
const OriginalMethodMapTy & getOriginalMethodMap()
This method is reserved for the implementation and shouldn't be used directly.
uint64_t getMethodVTableIndex(GlobalDecl GD)
Locate a virtual function in the vtable.
std::unique_ptr< VTableLayout > createConstructionVTableLayout(const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset, bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass)
CharUnits getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, const CXXRecordDecl *VBase)
Return the offset in chars (relative to the vtable address point) where the offset of the virtual bas...
GlobalDecl findOriginalMethod(GlobalDecl GD)
Return the method that added the v-table slot that will be used to call the given method.
void setOriginalMethod(const CXXMethodDecl *Key, const CXXMethodDecl *Val)
ItaniumVTableContext(ASTContext &Context)
unsigned getVBTableIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *VBase)
Returns the index of VBase in the vbtable of Derived.
const VPtrInfoVector & enumerateVBTables(const CXXRecordDecl *RD)
MethodVFTableLocation getMethodVFTableLocation(GlobalDecl GD)
const VPtrInfoVector & getVFPtrOffsets(const CXXRecordDecl *RD)
const VTableLayout & getVFTableLayout(const CXXRecordDecl *RD, CharUnits VFPtrOffset)
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1685
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1692
The set of methods that override a given virtual method in each subobject where it occurs.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:683
A (possibly-)qualified type.
Definition TypeBase.h:938
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
QualType getCanonicalType() const
Definition TypeBase.h:8630
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
virtual bool emitVectorDeletingDtors(const LangOptions &) const
Controls whether to emit MSVC vector deleting destructors.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
Represents a single component in a vtable.
static VTableComponent MakeCompleteDtor(const CXXDestructorDecl *DD)
static VTableComponent MakeRTTI(const CXXRecordDecl *RD)
const CXXMethodDecl * getUnusedFunctionDecl() const
static VTableComponent MakeOffsetToTop(CharUnits Offset)
CharUnits getVBaseOffset() const
static VTableComponent MakeUnusedFunction(const CXXMethodDecl *MD)
Kind getKind() const
Get the kind of this vtable component.
static VTableComponent MakeFunction(const CXXMethodDecl *MD)
@ CK_DeletingDtorPointer
A pointer to the deleting destructor.
@ CK_UnusedFunctionPointer
An entry that is never used.
@ CK_CompleteDtorPointer
A pointer to the complete destructor.
static VTableComponent MakeVBaseOffset(CharUnits Offset)
const CXXRecordDecl * getRTTIDecl() const
static VTableComponent MakeDeletingDtor(const CXXDestructorDecl *DD)
CharUnits getOffsetToTop() const
const CXXMethodDecl * getFunctionDecl() const
static VTableComponent MakeVCallOffset(CharUnits Offset)
CharUnits getVCallOffset() const
const CXXDestructorDecl * getDestructorDecl() const
static bool hasVtableSlot(const CXXMethodDecl *MD)
Determine whether this function should be assigned a vtable slot.
ThunksMapTy Thunks
Contains all thunks that a given method decl will need.
llvm::SmallVector< std::size_t > VTableIndicesTy
VTableLayout(VTableIndicesTy VTableIndices, ArrayRef< VTableComponent > VTableComponents, ArrayRef< VTableThunkTy > VTableThunks, const AddressPointsMapTy &AddressPoints)
llvm::SmallVector< unsigned, 4 > AddressPointsIndexMapTy
llvm::DenseMap< BaseSubobject, AddressPointLocation > AddressPointsMapTy
std::pair< uint64_t, ThunkInfo > VTableThunkTy
QualType getType() const
Definition Decl.h:725
Defines the clang::TargetInfo interface.
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:276
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
const FunctionProtoType * T
SmallVector< std::unique_ptr< VPtrInfo >, 2 > VPtrInfoVector
CXXDtorType
C++ destructor types.
Definition ABI.h:34
@ Dtor_VectorDeleting
Vector deleting dtor.
Definition ABI.h:40
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
@ Dtor_Deleting
Deleting dtor.
Definition ABI.h:35
for(const auto &A :T->param_types())
U cast(CodeGen::Address addr)
Definition Address.h:327
@ PrettyFunctionNoVirtual
The same as PrettyFunction, except that the 'virtual' keyword is omitted for virtual member functions...
Definition Expr.h:2068
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
#define false
Definition stdbool.h:26
Represents an element in a path from a derived class to a base class.
const CXXRecordDecl * Class
The record decl of the class that the base is a base of.
const CXXBaseSpecifier * Base
The base specifier that states the link from a derived class to a base class, which will be followed ...
const CXXRecordDecl * VBase
If nonnull, holds the last vbase which contains the vfptr that the method definition is adjusted to.
CharUnits VFPtrOffset
This is the offset of the vfptr from the start of the last vbase, or the complete type if there are n...
A return adjustment.
Definition Thunk.h:27
bool isEmpty() const
Definition Thunk.h:70
union clang::ReturnAdjustment::VirtualAdjustment Virtual
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition Thunk.h:30
A this pointer adjustment.
Definition Thunk.h:92
union clang::ThisAdjustment::VirtualAdjustment Virtual
bool isEmpty() const
Definition Thunk.h:137
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition Thunk.h:95
The this pointer adjustment as well as an optional return adjustment for a thunk.
Definition Thunk.h:157
bool isEmpty() const
Definition Thunk.h:186
ThisAdjustment This
The this pointer adjustment.
Definition Thunk.h:159
const CXXMethodDecl * Method
Holds a pointer to the overridden method this thunk is for, if needed by the ABI to distinguish diffe...
Definition Thunk.h:172
ReturnAdjustment Return
The return adjustment.
Definition Thunk.h:162
Uniquely identifies a virtual method within a class hierarchy by the method itself and a class subobj...
Holds information about the inheritance path to a virtual base or function table pointer.
CharUnits NonVirtualOffset
IntroducingObject is at this offset from its containing complete object or virtual base.
CharUnits FullOffsetInMDC
Static offset from the top of the most derived class to this vfptr, including any virtual base offset...
const CXXRecordDecl * getVBaseWithVPtr() const
The vptr is stored inside the non-virtual component of this virtual base.
SmallVector< const CXXRecordDecl *, 1 > BasePath
const CXXRecordDecl * IntroducingObject
This is the class that introduced the vptr by declaring new virtual methods or virtual bases.
BasePath MangledPath
The bases from the inheritance path that got used to mangle the vbtable name.
const CXXRecordDecl * NextBaseToMangle
The next base to push onto the mangled path if this path is ambiguous in a derived class.
BasePath PathToIntroducingObject
This holds the base classes path from the complete type to the first base with the given vfptr offset...
All virtual base related information about a given record decl.
VPtrInfoVector VBPtrPaths
Information on all virtual base tables used when this record is the most derived class.
llvm::DenseMap< const CXXRecordDecl *, unsigned > VBTableIndices
A map from virtual base to vbtable index for doing a conversion from the the derived class to the a b...
struct clang::ReturnAdjustment::VirtualAdjustment::@103031170252120233124322035264172076254313213024 Itanium
uint32_t VBPtrOffset
The offset (in bytes) of the vbptr, relative to the beginning of the derived class.
Definition Thunk.h:46
struct clang::ReturnAdjustment::VirtualAdjustment::@167242364125115315334113104006210160165266060257 Microsoft
int64_t VBaseOffsetOffset
The offset (in bytes), relative to the address point of the virtual base class offset.
Definition Thunk.h:39
uint32_t VBIndex
Index of the virtual base in the vbtable.
Definition Thunk.h:49
struct clang::ThisAdjustment::VirtualAdjustment::@106065375072164260365214033034320247050276346205 Itanium
int32_t VtordispOffset
The offset of the vtordisp (in bytes), relative to the ECX.
Definition Thunk.h:109
struct clang::ThisAdjustment::VirtualAdjustment::@312251255113040203233347230177110330127151157305 Microsoft
int32_t VBOffsetOffset
The offset (in bytes) of the vbase offset in the vbtable.
Definition Thunk.h:116
int64_t VCallOffsetOffset
The offset (in bytes), relative to the address point, of the virtual call offset.
Definition Thunk.h:104
int32_t VBPtrOffset
The offset of the vbptr of the derived class (in bytes), relative to the ECX after vtordisp adjustmen...
Definition Thunk.h:113