CGVTables.cpp revision bb625e9692e5b8d839f64208b8fa29684c668f8b
1//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
16#include "CGCXXABI.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/RecordLayout.h"
19#include "clang/Frontend/CodeGenOptions.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/SetVector.h"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Support/Format.h"
24#include <algorithm>
25#include <cstdio>
26
27using namespace clang;
28using namespace CodeGen;
29
30namespace {
31
32/// BaseOffset - Represents an offset from a derived class to a direct or
33/// indirect base class.
34struct BaseOffset {
35  /// DerivedClass - The derived class.
36  const CXXRecordDecl *DerivedClass;
37
38  /// VirtualBase - If the path from the derived class to the base class
39  /// involves a virtual base class, this holds its declaration.
40  const CXXRecordDecl *VirtualBase;
41
42  /// NonVirtualOffset - The offset from the derived class to the base class.
43  /// (Or the offset from the virtual base class to the base class, if the
44  /// path from the derived class to the base class involves a virtual base
45  /// class.
46  int64_t NonVirtualOffset;
47
48  BaseOffset() : DerivedClass(0), VirtualBase(0), NonVirtualOffset(0) { }
49  BaseOffset(const CXXRecordDecl *DerivedClass,
50             const CXXRecordDecl *VirtualBase, int64_t NonVirtualOffset)
51    : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
52    NonVirtualOffset(NonVirtualOffset) { }
53
54  bool isEmpty() const { return !NonVirtualOffset && !VirtualBase; }
55};
56
57/// FinalOverriders - Contains the final overrider member functions for all
58/// member functions in the base subobjects of a class.
59class FinalOverriders {
60public:
61  /// OverriderInfo - Information about a final overrider.
62  struct OverriderInfo {
63    /// Method - The method decl of the overrider.
64    const CXXMethodDecl *Method;
65
66    /// Offset - the base offset of the overrider in the layout class.
67    CharUnits Offset;
68
69    OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
70  };
71
72private:
73  /// MostDerivedClass - The most derived class for which the final overriders
74  /// are stored.
75  const CXXRecordDecl *MostDerivedClass;
76
77  /// MostDerivedClassOffset - If we're building final overriders for a
78  /// construction vtable, this holds the offset from the layout class to the
79  /// most derived class.
80  const CharUnits MostDerivedClassOffset;
81
82  /// LayoutClass - The class we're using for layout information. Will be
83  /// different than the most derived class if the final overriders are for a
84  /// construction vtable.
85  const CXXRecordDecl *LayoutClass;
86
87  ASTContext &Context;
88
89  /// MostDerivedClassLayout - the AST record layout of the most derived class.
90  const ASTRecordLayout &MostDerivedClassLayout;
91
92  /// MethodBaseOffsetPairTy - Uniquely identifies a member function
93  /// in a base subobject.
94  typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
95
96  typedef llvm::DenseMap<MethodBaseOffsetPairTy,
97                         OverriderInfo> OverridersMapTy;
98
99  /// OverridersMap - The final overriders for all virtual member functions of
100  /// all the base subobjects of the most derived class.
101  OverridersMapTy OverridersMap;
102
103  /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
104  /// as a record decl and a subobject number) and its offsets in the most
105  /// derived class as well as the layout class.
106  typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
107                         CharUnits> SubobjectOffsetMapTy;
108
109  typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
110
111  /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
112  /// given base.
113  void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
114                          CharUnits OffsetInLayoutClass,
115                          SubobjectOffsetMapTy &SubobjectOffsets,
116                          SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
117                          SubobjectCountMapTy &SubobjectCounts);
118
119  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
120
121  /// dump - dump the final overriders for a base subobject, and all its direct
122  /// and indirect base subobjects.
123  void dump(llvm::raw_ostream &Out, BaseSubobject Base,
124            VisitedVirtualBasesSetTy& VisitedVirtualBases);
125
126public:
127  FinalOverriders(const CXXRecordDecl *MostDerivedClass,
128                  CharUnits MostDerivedClassOffset,
129                  const CXXRecordDecl *LayoutClass);
130
131  /// getOverrider - Get the final overrider for the given method declaration in
132  /// the subobject with the given base offset.
133  OverriderInfo getOverrider(const CXXMethodDecl *MD,
134                             CharUnits BaseOffset) const {
135    assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
136           "Did not find overrider!");
137
138    return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
139  }
140
141  /// dump - dump the final overriders.
142  void dump() {
143    VisitedVirtualBasesSetTy VisitedVirtualBases;
144    dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
145         VisitedVirtualBases);
146  }
147
148};
149
150#define DUMP_OVERRIDERS 0
151
152FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
153                                 CharUnits MostDerivedClassOffset,
154                                 const CXXRecordDecl *LayoutClass)
155  : MostDerivedClass(MostDerivedClass),
156  MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
157  Context(MostDerivedClass->getASTContext()),
158  MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
159
160  // Compute base offsets.
161  SubobjectOffsetMapTy SubobjectOffsets;
162  SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
163  SubobjectCountMapTy SubobjectCounts;
164  ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
165                     /*IsVirtual=*/false,
166                     MostDerivedClassOffset,
167                     SubobjectOffsets, SubobjectLayoutClassOffsets,
168                     SubobjectCounts);
169
170  // Get the the final overriders.
171  CXXFinalOverriderMap FinalOverriders;
172  MostDerivedClass->getFinalOverriders(FinalOverriders);
173
174  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
175       E = FinalOverriders.end(); I != E; ++I) {
176    const CXXMethodDecl *MD = I->first;
177    const OverridingMethods& Methods = I->second;
178
179    for (OverridingMethods::const_iterator I = Methods.begin(),
180         E = Methods.end(); I != E; ++I) {
181      unsigned SubobjectNumber = I->first;
182      assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
183                                                   SubobjectNumber)) &&
184             "Did not find subobject offset!");
185
186      CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
187                                                            SubobjectNumber)];
188
189      assert(I->second.size() == 1 && "Final overrider is not unique!");
190      const UniqueVirtualMethod &Method = I->second.front();
191
192      const CXXRecordDecl *OverriderRD = Method.Method->getParent();
193      assert(SubobjectLayoutClassOffsets.count(
194             std::make_pair(OverriderRD, Method.Subobject))
195             && "Did not find subobject offset!");
196      CharUnits OverriderOffset =
197        SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
198                                                   Method.Subobject)];
199
200      OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
201      assert(!Overrider.Method && "Overrider should not exist yet!");
202
203      Overrider.Offset = OverriderOffset;
204      Overrider.Method = Method.Method;
205    }
206  }
207
208#if DUMP_OVERRIDERS
209  // And dump them (for now).
210  dump();
211#endif
212}
213
214static BaseOffset ComputeBaseOffset(ASTContext &Context,
215                                    const CXXRecordDecl *DerivedRD,
216                                    const CXXBasePath &Path) {
217  int64_t NonVirtualOffset = 0;
218
219  unsigned NonVirtualStart = 0;
220  const CXXRecordDecl *VirtualBase = 0;
221
222  // First, look for the virtual base class.
223  for (unsigned I = 0, E = Path.size(); I != E; ++I) {
224    const CXXBasePathElement &Element = Path[I];
225
226    if (Element.Base->isVirtual()) {
227      // FIXME: Can we break when we find the first virtual base?
228      // (If we can't, can't we just iterate over the path in reverse order?)
229      NonVirtualStart = I + 1;
230      QualType VBaseType = Element.Base->getType();
231      VirtualBase =
232        cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
233    }
234  }
235
236  // Now compute the non-virtual offset.
237  for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
238    const CXXBasePathElement &Element = Path[I];
239
240    // Check the base class offset.
241    const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
242
243    const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
244    const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
245
246    NonVirtualOffset += Layout.getBaseClassOffsetInBits(Base);
247  }
248
249  // FIXME: This should probably use CharUnits or something. Maybe we should
250  // even change the base offsets in ASTRecordLayout to be specified in
251  // CharUnits.
252  return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset / 8);
253
254}
255
256static BaseOffset ComputeBaseOffset(ASTContext &Context,
257                                    const CXXRecordDecl *BaseRD,
258                                    const CXXRecordDecl *DerivedRD) {
259  CXXBasePaths Paths(/*FindAmbiguities=*/false,
260                     /*RecordPaths=*/true, /*DetectVirtual=*/false);
261
262  if (!const_cast<CXXRecordDecl *>(DerivedRD)->
263      isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
264    assert(false && "Class must be derived from the passed in base class!");
265    return BaseOffset();
266  }
267
268  return ComputeBaseOffset(Context, DerivedRD, Paths.front());
269}
270
271static BaseOffset
272ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
273                                  const CXXMethodDecl *DerivedMD,
274                                  const CXXMethodDecl *BaseMD) {
275  const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
276  const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
277
278  // Canonicalize the return types.
279  CanQualType CanDerivedReturnType =
280    Context.getCanonicalType(DerivedFT->getResultType());
281  CanQualType CanBaseReturnType =
282    Context.getCanonicalType(BaseFT->getResultType());
283
284  assert(CanDerivedReturnType->getTypeClass() ==
285         CanBaseReturnType->getTypeClass() &&
286         "Types must have same type class!");
287
288  if (CanDerivedReturnType == CanBaseReturnType) {
289    // No adjustment needed.
290    return BaseOffset();
291  }
292
293  if (isa<ReferenceType>(CanDerivedReturnType)) {
294    CanDerivedReturnType =
295      CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
296    CanBaseReturnType =
297      CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
298  } else if (isa<PointerType>(CanDerivedReturnType)) {
299    CanDerivedReturnType =
300      CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
301    CanBaseReturnType =
302      CanBaseReturnType->getAs<PointerType>()->getPointeeType();
303  } else {
304    assert(false && "Unexpected return type!");
305  }
306
307  // We need to compare unqualified types here; consider
308  //   const T *Base::foo();
309  //   T *Derived::foo();
310  if (CanDerivedReturnType.getUnqualifiedType() ==
311      CanBaseReturnType.getUnqualifiedType()) {
312    // No adjustment needed.
313    return BaseOffset();
314  }
315
316  const CXXRecordDecl *DerivedRD =
317    cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
318
319  const CXXRecordDecl *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 (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
349       E = RD->bases_end(); I != E; ++I) {
350    const CXXRecordDecl *BaseDecl =
351      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
352
353    CharUnits BaseOffset;
354    CharUnits BaseOffsetInLayoutClass;
355    if (I->isVirtual()) {
356      // Check if we've visited this virtual base before.
357      if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
358        continue;
359
360      const ASTRecordLayout &LayoutClassLayout =
361        Context.getASTRecordLayout(LayoutClass);
362
363      BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
364      BaseOffsetInLayoutClass =
365        LayoutClassLayout.getVBaseClassOffset(BaseDecl);
366    } else {
367      const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
368      CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
369
370      BaseOffset = Base.getBaseOffset() + Offset;
371      BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
372    }
373
374    ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
375                       I->isVirtual(), BaseOffsetInLayoutClass,
376                       SubobjectOffsets, SubobjectLayoutClassOffsets,
377                       SubobjectCounts);
378  }
379}
380
381void FinalOverriders::dump(llvm::raw_ostream &Out, BaseSubobject Base,
382                           VisitedVirtualBasesSetTy &VisitedVirtualBases) {
383  const CXXRecordDecl *RD = Base.getBase();
384  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
385
386  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
387       E = RD->bases_end(); I != E; ++I) {
388    const CXXRecordDecl *BaseDecl =
389      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
390
391    // Ignore bases that don't have any virtual member functions.
392    if (!BaseDecl->isPolymorphic())
393      continue;
394
395    CharUnits BaseOffset;
396    if (I->isVirtual()) {
397      if (!VisitedVirtualBases.insert(BaseDecl)) {
398        // We've visited this base before.
399        continue;
400      }
401
402      BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
403    } else {
404      BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
405    }
406
407    dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
408  }
409
410  Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
411  Out << Base.getBaseOffset().getQuantity() << ")\n";
412
413  // Now dump the overriders for this base subobject.
414  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
415       E = RD->method_end(); I != E; ++I) {
416    const CXXMethodDecl *MD = *I;
417
418    if (!MD->isVirtual())
419      continue;
420
421    OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
422
423    Out << "  " << MD->getQualifiedNameAsString() << " - (";
424    Out << Overrider.Method->getQualifiedNameAsString();
425    Out << ", " << ", " << Overrider.Offset.getQuantity() << ')';
426
427    BaseOffset Offset;
428    if (!Overrider.Method->isPure())
429      Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
430
431    if (!Offset.isEmpty()) {
432      Out << " [ret-adj: ";
433      if (Offset.VirtualBase)
434        Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
435
436      Out << Offset.NonVirtualOffset << " nv]";
437    }
438
439    Out << "\n";
440  }
441}
442
443/// VTableComponent - Represents a single component in a vtable.
444class VTableComponent {
445public:
446  enum Kind {
447    CK_VCallOffset,
448    CK_VBaseOffset,
449    CK_OffsetToTop,
450    CK_RTTI,
451    CK_FunctionPointer,
452
453    /// CK_CompleteDtorPointer - A pointer to the complete destructor.
454    CK_CompleteDtorPointer,
455
456    /// CK_DeletingDtorPointer - A pointer to the deleting destructor.
457    CK_DeletingDtorPointer,
458
459    /// CK_UnusedFunctionPointer - In some cases, a vtable function pointer
460    /// will end up never being called. Such vtable function pointers are
461    /// represented as a CK_UnusedFunctionPointer.
462    CK_UnusedFunctionPointer
463  };
464
465  static VTableComponent MakeVCallOffset(int64_t Offset) {
466    return VTableComponent(CK_VCallOffset, Offset);
467  }
468
469  static VTableComponent MakeVBaseOffset(int64_t Offset) {
470    return VTableComponent(CK_VBaseOffset, Offset);
471  }
472
473  static VTableComponent MakeOffsetToTop(int64_t Offset) {
474    return VTableComponent(CK_OffsetToTop, Offset);
475  }
476
477  static VTableComponent MakeRTTI(const CXXRecordDecl *RD) {
478    return VTableComponent(CK_RTTI, reinterpret_cast<uintptr_t>(RD));
479  }
480
481  static VTableComponent MakeFunction(const CXXMethodDecl *MD) {
482    assert(!isa<CXXDestructorDecl>(MD) &&
483           "Don't use MakeFunction with destructors!");
484
485    return VTableComponent(CK_FunctionPointer,
486                           reinterpret_cast<uintptr_t>(MD));
487  }
488
489  static VTableComponent MakeCompleteDtor(const CXXDestructorDecl *DD) {
490    return VTableComponent(CK_CompleteDtorPointer,
491                           reinterpret_cast<uintptr_t>(DD));
492  }
493
494  static VTableComponent MakeDeletingDtor(const CXXDestructorDecl *DD) {
495    return VTableComponent(CK_DeletingDtorPointer,
496                           reinterpret_cast<uintptr_t>(DD));
497  }
498
499  static VTableComponent MakeUnusedFunction(const CXXMethodDecl *MD) {
500    assert(!isa<CXXDestructorDecl>(MD) &&
501           "Don't use MakeUnusedFunction with destructors!");
502    return VTableComponent(CK_UnusedFunctionPointer,
503                           reinterpret_cast<uintptr_t>(MD));
504  }
505
506  static VTableComponent getFromOpaqueInteger(uint64_t I) {
507    return VTableComponent(I);
508  }
509
510  /// getKind - Get the kind of this vtable component.
511  Kind getKind() const {
512    return (Kind)(Value & 0x7);
513  }
514
515  int64_t getVCallOffset() const {
516    assert(getKind() == CK_VCallOffset && "Invalid component kind!");
517
518    return getOffset();
519  }
520
521  int64_t getVBaseOffset() const {
522    assert(getKind() == CK_VBaseOffset && "Invalid component kind!");
523
524    return getOffset();
525  }
526
527  int64_t getOffsetToTop() const {
528    assert(getKind() == CK_OffsetToTop && "Invalid component kind!");
529
530    return getOffset();
531  }
532
533  const CXXRecordDecl *getRTTIDecl() const {
534    assert(getKind() == CK_RTTI && "Invalid component kind!");
535
536    return reinterpret_cast<CXXRecordDecl *>(getPointer());
537  }
538
539  const CXXMethodDecl *getFunctionDecl() const {
540    assert(getKind() == CK_FunctionPointer);
541
542    return reinterpret_cast<CXXMethodDecl *>(getPointer());
543  }
544
545  const CXXDestructorDecl *getDestructorDecl() const {
546    assert((getKind() == CK_CompleteDtorPointer ||
547            getKind() == CK_DeletingDtorPointer) && "Invalid component kind!");
548
549    return reinterpret_cast<CXXDestructorDecl *>(getPointer());
550  }
551
552  const CXXMethodDecl *getUnusedFunctionDecl() const {
553    assert(getKind() == CK_UnusedFunctionPointer);
554
555    return reinterpret_cast<CXXMethodDecl *>(getPointer());
556  }
557
558private:
559  VTableComponent(Kind ComponentKind, int64_t Offset) {
560    assert((ComponentKind == CK_VCallOffset ||
561            ComponentKind == CK_VBaseOffset ||
562            ComponentKind == CK_OffsetToTop) && "Invalid component kind!");
563    assert(Offset <= ((1LL << 56) - 1) && "Offset is too big!");
564
565    Value = ((Offset << 3) | ComponentKind);
566  }
567
568  VTableComponent(Kind ComponentKind, uintptr_t Ptr) {
569    assert((ComponentKind == CK_RTTI ||
570            ComponentKind == CK_FunctionPointer ||
571            ComponentKind == CK_CompleteDtorPointer ||
572            ComponentKind == CK_DeletingDtorPointer ||
573            ComponentKind == CK_UnusedFunctionPointer) &&
574            "Invalid component kind!");
575
576    assert((Ptr & 7) == 0 && "Pointer not sufficiently aligned!");
577
578    Value = Ptr | ComponentKind;
579  }
580
581  int64_t getOffset() const {
582    assert((getKind() == CK_VCallOffset || getKind() == CK_VBaseOffset ||
583            getKind() == CK_OffsetToTop) && "Invalid component kind!");
584
585    return Value >> 3;
586  }
587
588  uintptr_t getPointer() const {
589    assert((getKind() == CK_RTTI ||
590            getKind() == CK_FunctionPointer ||
591            getKind() == CK_CompleteDtorPointer ||
592            getKind() == CK_DeletingDtorPointer ||
593            getKind() == CK_UnusedFunctionPointer) &&
594           "Invalid component kind!");
595
596    return static_cast<uintptr_t>(Value & ~7ULL);
597  }
598
599  explicit VTableComponent(uint64_t Value)
600    : Value(Value) { }
601
602  /// The kind is stored in the lower 3 bits of the value. For offsets, we
603  /// make use of the facts that classes can't be larger than 2^55 bytes,
604  /// so we store the offset in the lower part of the 61 bytes that remain.
605  /// (The reason that we're not simply using a PointerIntPair here is that we
606  /// need the offsets to be 64-bit, even when on a 32-bit machine).
607  int64_t Value;
608};
609
610/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
611struct VCallOffsetMap {
612
613  typedef std::pair<const CXXMethodDecl *, int64_t> MethodAndOffsetPairTy;
614
615  /// Offsets - Keeps track of methods and their offsets.
616  // FIXME: This should be a real map and not a vector.
617  llvm::SmallVector<MethodAndOffsetPairTy, 16> Offsets;
618
619  /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
620  /// can share the same vcall offset.
621  static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
622                                         const CXXMethodDecl *RHS);
623
624public:
625  /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
626  /// add was successful, or false if there was already a member function with
627  /// the same signature in the map.
628  bool AddVCallOffset(const CXXMethodDecl *MD, int64_t OffsetOffset);
629
630  /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
631  /// vtable address point) for the given virtual member function.
632  int64_t getVCallOffsetOffset(const CXXMethodDecl *MD);
633
634  // empty - Return whether the offset map is empty or not.
635  bool empty() const { return Offsets.empty(); }
636};
637
638static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
639                                    const CXXMethodDecl *RHS) {
640  ASTContext &C = LHS->getASTContext(); // TODO: thread this down
641  CanQual<FunctionProtoType>
642    LT = C.getCanonicalType(LHS->getType()).getAs<FunctionProtoType>(),
643    RT = C.getCanonicalType(RHS->getType()).getAs<FunctionProtoType>();
644
645  // Fast-path matches in the canonical types.
646  if (LT == RT) return true;
647
648  // Force the signatures to match.  We can't rely on the overrides
649  // list here because there isn't necessarily an inheritance
650  // relationship between the two methods.
651  if (LT.getQualifiers() != RT.getQualifiers() ||
652      LT->getNumArgs() != RT->getNumArgs())
653    return false;
654  for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
655    if (LT->getArgType(I) != RT->getArgType(I))
656      return false;
657  return true;
658}
659
660bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
661                                                const CXXMethodDecl *RHS) {
662  assert(LHS->isVirtual() && "LHS must be virtual!");
663  assert(RHS->isVirtual() && "LHS must be virtual!");
664
665  // A destructor can share a vcall offset with another destructor.
666  if (isa<CXXDestructorDecl>(LHS))
667    return isa<CXXDestructorDecl>(RHS);
668
669  // FIXME: We need to check more things here.
670
671  // The methods must have the same name.
672  DeclarationName LHSName = LHS->getDeclName();
673  DeclarationName RHSName = RHS->getDeclName();
674  if (LHSName != RHSName)
675    return false;
676
677  // And the same signatures.
678  return HasSameVirtualSignature(LHS, RHS);
679}
680
681bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
682                                    int64_t OffsetOffset) {
683  // Check if we can reuse an offset.
684  for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
685    if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
686      return false;
687  }
688
689  // Add the offset.
690  Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
691  return true;
692}
693
694int64_t VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
695  // Look for an offset.
696  for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
697    if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
698      return Offsets[I].second;
699  }
700
701  assert(false && "Should always find a vcall offset offset!");
702  return 0;
703}
704
705/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
706class VCallAndVBaseOffsetBuilder {
707public:
708  typedef llvm::DenseMap<const CXXRecordDecl *, int64_t>
709    VBaseOffsetOffsetsMapTy;
710
711private:
712  /// MostDerivedClass - The most derived class for which we're building vcall
713  /// and vbase offsets.
714  const CXXRecordDecl *MostDerivedClass;
715
716  /// LayoutClass - The class we're using for layout information. Will be
717  /// different than the most derived class if we're building a construction
718  /// vtable.
719  const CXXRecordDecl *LayoutClass;
720
721  /// Context - The ASTContext which we will use for layout information.
722  ASTContext &Context;
723
724  /// Components - vcall and vbase offset components
725  typedef llvm::SmallVector<VTableComponent, 64> VTableComponentVectorTy;
726  VTableComponentVectorTy Components;
727
728  /// VisitedVirtualBases - Visited virtual bases.
729  llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
730
731  /// VCallOffsets - Keeps track of vcall offsets.
732  VCallOffsetMap VCallOffsets;
733
734
735  /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
736  /// relative to the address point.
737  VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
738
739  /// FinalOverriders - The final overriders of the most derived class.
740  /// (Can be null when we're not building a vtable of the most derived class).
741  const FinalOverriders *Overriders;
742
743  /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
744  /// given base subobject.
745  void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
746                               CharUnits RealBaseOffset);
747
748  /// AddVCallOffsets - Add vcall offsets for the given base subobject.
749  void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
750
751  /// AddVBaseOffsets - Add vbase offsets for the given class.
752  void AddVBaseOffsets(const CXXRecordDecl *Base,
753                       CharUnits OffsetInLayoutClass);
754
755  /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
756  /// bytes, relative to the vtable address point.
757  int64_t getCurrentOffsetOffset() const;
758
759public:
760  VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
761                             const CXXRecordDecl *LayoutClass,
762                             const FinalOverriders *Overriders,
763                             BaseSubobject Base, bool BaseIsVirtual,
764                             CharUnits OffsetInLayoutClass)
765    : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
766    Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
767
768    // Add vcall and vbase offsets.
769    AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
770  }
771
772  /// Methods for iterating over the components.
773  typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
774  const_iterator components_begin() const { return Components.rbegin(); }
775  const_iterator components_end() const { return Components.rend(); }
776
777  const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
778  const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
779    return VBaseOffsetOffsets;
780  }
781};
782
783void
784VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
785                                                    bool BaseIsVirtual,
786                                                    CharUnits RealBaseOffset) {
787  const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
788
789  // Itanium C++ ABI 2.5.2:
790  //   ..in classes sharing a virtual table with a primary base class, the vcall
791  //   and vbase offsets added by the derived class all come before the vcall
792  //   and vbase offsets required by the base class, so that the latter may be
793  //   laid out as required by the base class without regard to additions from
794  //   the derived class(es).
795
796  // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
797  // emit them for the primary base first).
798  if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
799    bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
800
801    CharUnits PrimaryBaseOffset;
802
803    // Get the base offset of the primary base.
804    if (PrimaryBaseIsVirtual) {
805      assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
806             "Primary vbase should have a zero offset!");
807
808      const ASTRecordLayout &MostDerivedClassLayout =
809        Context.getASTRecordLayout(MostDerivedClass);
810
811      PrimaryBaseOffset =
812        MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
813    } else {
814      assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
815             "Primary base should have a zero offset!");
816
817      PrimaryBaseOffset = Base.getBaseOffset();
818    }
819
820    AddVCallAndVBaseOffsets(
821      BaseSubobject(PrimaryBase,PrimaryBaseOffset),
822      PrimaryBaseIsVirtual, RealBaseOffset);
823  }
824
825  AddVBaseOffsets(Base.getBase(), RealBaseOffset);
826
827  // We only want to add vcall offsets for virtual bases.
828  if (BaseIsVirtual)
829    AddVCallOffsets(Base, RealBaseOffset);
830}
831
832int64_t VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
833  // OffsetIndex is the index of this vcall or vbase offset, relative to the
834  // vtable address point. (We subtract 3 to account for the information just
835  // above the address point, the RTTI info, the offset to top, and the
836  // vcall offset itself).
837  int64_t OffsetIndex = -(int64_t)(3 + Components.size());
838
839  // FIXME: We shouldn't use / 8 here.
840  int64_t OffsetOffset = OffsetIndex *
841    (int64_t)Context.Target.getPointerWidth(0) / 8;
842
843  return OffsetOffset;
844}
845
846void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
847                                                 CharUnits VBaseOffset) {
848  const CXXRecordDecl *RD = Base.getBase();
849  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
850
851  const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
852
853  // Handle the primary base first.
854  // We only want to add vcall offsets if the base is non-virtual; a virtual
855  // primary base will have its vcall and vbase offsets emitted already.
856  if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
857    // Get the base offset of the primary base.
858    assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
859           "Primary base should have a zero offset!");
860
861    AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
862                    VBaseOffset);
863  }
864
865  // Add the vcall offsets.
866  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
867       E = RD->method_end(); I != E; ++I) {
868    const CXXMethodDecl *MD = *I;
869
870    if (!MD->isVirtual())
871      continue;
872
873    int64_t OffsetOffset = getCurrentOffsetOffset();
874
875    // Don't add a vcall offset if we already have one for this member function
876    // signature.
877    if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
878      continue;
879
880    CharUnits Offset = CharUnits::Zero();
881
882    if (Overriders) {
883      // Get the final overrider.
884      FinalOverriders::OverriderInfo Overrider =
885        Overriders->getOverrider(MD, Base.getBaseOffset());
886
887      /// The vcall offset is the offset from the virtual base to the object
888      /// where the function was overridden.
889      Offset = Overrider.Offset - VBaseOffset;
890    }
891
892    Components.push_back(
893      VTableComponent::MakeVCallOffset(Offset.getQuantity()));
894  }
895
896  // And iterate over all non-virtual bases (ignoring the primary base).
897  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
898       E = RD->bases_end(); I != E; ++I) {
899
900    if (I->isVirtual())
901      continue;
902
903    const CXXRecordDecl *BaseDecl =
904      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
905    if (BaseDecl == PrimaryBase)
906      continue;
907
908    // Get the base offset of this base.
909    CharUnits BaseOffset = Base.getBaseOffset() +
910      Layout.getBaseClassOffset(BaseDecl);
911
912    AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
913                    VBaseOffset);
914  }
915}
916
917void
918VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
919                                            CharUnits OffsetInLayoutClass) {
920  const ASTRecordLayout &LayoutClassLayout =
921    Context.getASTRecordLayout(LayoutClass);
922
923  // Add vbase offsets.
924  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
925       E = RD->bases_end(); I != E; ++I) {
926    const CXXRecordDecl *BaseDecl =
927      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
928
929    // Check if this is a virtual base that we haven't visited before.
930    if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
931      CharUnits Offset =
932        LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
933
934      // Add the vbase offset offset.
935      assert(!VBaseOffsetOffsets.count(BaseDecl) &&
936             "vbase offset offset already exists!");
937
938      int64_t VBaseOffsetOffset = getCurrentOffsetOffset();
939      VBaseOffsetOffsets.insert(std::make_pair(BaseDecl, VBaseOffsetOffset));
940
941      Components.push_back(
942          VTableComponent::MakeVBaseOffset(Offset.getQuantity()));
943    }
944
945    // Check the base class looking for more vbase offsets.
946    AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
947  }
948}
949
950/// VTableBuilder - Class for building vtable layout information.
951class VTableBuilder {
952public:
953  /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
954  /// primary bases.
955  typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
956    PrimaryBasesSetVectorTy;
957
958  typedef llvm::DenseMap<const CXXRecordDecl *, int64_t>
959    VBaseOffsetOffsetsMapTy;
960
961  typedef llvm::DenseMap<BaseSubobject, uint64_t>
962    AddressPointsMapTy;
963
964private:
965  /// VTables - Global vtable information.
966  CodeGenVTables &VTables;
967
968  /// MostDerivedClass - The most derived class for which we're building this
969  /// vtable.
970  const CXXRecordDecl *MostDerivedClass;
971
972  /// MostDerivedClassOffset - If we're building a construction vtable, this
973  /// holds the offset from the layout class to the most derived class.
974  const CharUnits MostDerivedClassOffset;
975
976  /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
977  /// base. (This only makes sense when building a construction vtable).
978  bool MostDerivedClassIsVirtual;
979
980  /// LayoutClass - The class we're using for layout information. Will be
981  /// different than the most derived class if we're building a construction
982  /// vtable.
983  const CXXRecordDecl *LayoutClass;
984
985  /// Context - The ASTContext which we will use for layout information.
986  ASTContext &Context;
987
988  /// FinalOverriders - The final overriders of the most derived class.
989  const FinalOverriders Overriders;
990
991  /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
992  /// bases in this vtable.
993  llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
994
995  /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
996  /// the most derived class.
997  VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
998
999  /// Components - The components of the vtable being built.
1000  llvm::SmallVector<VTableComponent, 64> Components;
1001
1002  /// AddressPoints - Address points for the vtable being built.
1003  AddressPointsMapTy AddressPoints;
1004
1005  /// MethodInfo - Contains information about a method in a vtable.
1006  /// (Used for computing 'this' pointer adjustment thunks.
1007  struct MethodInfo {
1008    /// BaseOffset - The base offset of this method.
1009    const CharUnits BaseOffset;
1010
1011    /// BaseOffsetInLayoutClass - The base offset in the layout class of this
1012    /// method.
1013    const CharUnits BaseOffsetInLayoutClass;
1014
1015    /// VTableIndex - The index in the vtable that this method has.
1016    /// (For destructors, this is the index of the complete destructor).
1017    const uint64_t VTableIndex;
1018
1019    MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
1020               uint64_t VTableIndex)
1021      : BaseOffset(BaseOffset),
1022      BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
1023      VTableIndex(VTableIndex) { }
1024
1025    MethodInfo()
1026      : BaseOffset(CharUnits::Zero()),
1027      BaseOffsetInLayoutClass(CharUnits::Zero()),
1028      VTableIndex(0) { }
1029  };
1030
1031  typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
1032
1033  /// MethodInfoMap - The information for all methods in the vtable we're
1034  /// currently building.
1035  MethodInfoMapTy MethodInfoMap;
1036
1037  typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
1038
1039  /// VTableThunks - The thunks by vtable index in the vtable currently being
1040  /// built.
1041  VTableThunksMapTy VTableThunks;
1042
1043  typedef llvm::SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
1044  typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
1045
1046  /// Thunks - A map that contains all the thunks needed for all methods in the
1047  /// most derived class for which the vtable is currently being built.
1048  ThunksMapTy Thunks;
1049
1050  /// AddThunk - Add a thunk for the given method.
1051  void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
1052
1053  /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
1054  /// part of the vtable we're currently building.
1055  void ComputeThisAdjustments();
1056
1057  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1058
1059  /// PrimaryVirtualBases - All known virtual bases who are a primary base of
1060  /// some other base.
1061  VisitedVirtualBasesSetTy PrimaryVirtualBases;
1062
1063  /// ComputeReturnAdjustment - Compute the return adjustment given a return
1064  /// adjustment base offset.
1065  ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
1066
1067  /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
1068  /// the 'this' pointer from the base subobject to the derived subobject.
1069  BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1070                                             BaseSubobject Derived) const;
1071
1072  /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
1073  /// given virtual member function, its offset in the layout class and its
1074  /// final overrider.
1075  ThisAdjustment
1076  ComputeThisAdjustment(const CXXMethodDecl *MD,
1077                        CharUnits BaseOffsetInLayoutClass,
1078                        FinalOverriders::OverriderInfo Overrider);
1079
1080  /// AddMethod - Add a single virtual member function to the vtable
1081  /// components vector.
1082  void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
1083
1084  /// IsOverriderUsed - Returns whether the overrider will ever be used in this
1085  /// part of the vtable.
1086  ///
1087  /// Itanium C++ ABI 2.5.2:
1088  ///
1089  ///   struct A { virtual void f(); };
1090  ///   struct B : virtual public A { int i; };
1091  ///   struct C : virtual public A { int j; };
1092  ///   struct D : public B, public C {};
1093  ///
1094  ///   When B and C are declared, A is a primary base in each case, so although
1095  ///   vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
1096  ///   adjustment is required and no thunk is generated. However, inside D
1097  ///   objects, A is no longer a primary base of C, so if we allowed calls to
1098  ///   C::f() to use the copy of A's vtable in the C subobject, we would need
1099  ///   to adjust this from C* to B::A*, which would require a third-party
1100  ///   thunk. Since we require that a call to C::f() first convert to A*,
1101  ///   C-in-D's copy of A's vtable is never referenced, so this is not
1102  ///   necessary.
1103  bool IsOverriderUsed(const CXXMethodDecl *Overrider,
1104                       uint64_t BaseOffsetInLayoutClass,
1105                       const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1106                       uint64_t FirstBaseOffsetInLayoutClass) const;
1107
1108
1109  /// AddMethods - Add the methods of this base subobject and all its
1110  /// primary bases to the vtable components vector.
1111  void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1112                  const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1113                  CharUnits FirstBaseOffsetInLayoutClass,
1114                  PrimaryBasesSetVectorTy &PrimaryBases);
1115
1116  // LayoutVTable - Layout the vtable for the given base class, including its
1117  // secondary vtables and any vtables for virtual bases.
1118  void LayoutVTable();
1119
1120  /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
1121  /// given base subobject, as well as all its secondary vtables.
1122  ///
1123  /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
1124  /// or a direct or indirect base of a virtual base.
1125  ///
1126  /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
1127  /// in the layout class.
1128  void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1129                                        bool BaseIsMorallyVirtual,
1130                                        bool BaseIsVirtualInLayoutClass,
1131                                        CharUnits OffsetInLayoutClass);
1132
1133  /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
1134  /// subobject.
1135  ///
1136  /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
1137  /// or a direct or indirect base of a virtual base.
1138  void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
1139                              CharUnits OffsetInLayoutClass);
1140
1141  /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
1142  /// class hierarchy.
1143  void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1144                                    CharUnits OffsetInLayoutClass,
1145                                    VisitedVirtualBasesSetTy &VBases);
1146
1147  /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
1148  /// given base (excluding any primary bases).
1149  void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1150                                    VisitedVirtualBasesSetTy &VBases);
1151
1152  /// isBuildingConstructionVTable - Return whether this vtable builder is
1153  /// building a construction vtable.
1154  bool isBuildingConstructorVTable() const {
1155    return MostDerivedClass != LayoutClass;
1156  }
1157
1158public:
1159  VTableBuilder(CodeGenVTables &VTables, const CXXRecordDecl *MostDerivedClass,
1160                CharUnits MostDerivedClassOffset,
1161                bool MostDerivedClassIsVirtual, const
1162                CXXRecordDecl *LayoutClass)
1163    : VTables(VTables), MostDerivedClass(MostDerivedClass),
1164    MostDerivedClassOffset(MostDerivedClassOffset),
1165    MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
1166    LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
1167    Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
1168
1169    LayoutVTable();
1170  }
1171
1172  ThunksMapTy::const_iterator thunks_begin() const {
1173    return Thunks.begin();
1174  }
1175
1176  ThunksMapTy::const_iterator thunks_end() const {
1177    return Thunks.end();
1178  }
1179
1180  const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1181    return VBaseOffsetOffsets;
1182  }
1183
1184  /// getNumVTableComponents - Return the number of components in the vtable
1185  /// currently built.
1186  uint64_t getNumVTableComponents() const {
1187    return Components.size();
1188  }
1189
1190  const uint64_t *vtable_components_data_begin() const {
1191    return reinterpret_cast<const uint64_t *>(Components.begin());
1192  }
1193
1194  const uint64_t *vtable_components_data_end() const {
1195    return reinterpret_cast<const uint64_t *>(Components.end());
1196  }
1197
1198  AddressPointsMapTy::const_iterator address_points_begin() const {
1199    return AddressPoints.begin();
1200  }
1201
1202  AddressPointsMapTy::const_iterator address_points_end() const {
1203    return AddressPoints.end();
1204  }
1205
1206  VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1207    return VTableThunks.begin();
1208  }
1209
1210  VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1211    return VTableThunks.end();
1212  }
1213
1214  /// dumpLayout - Dump the vtable layout.
1215  void dumpLayout(llvm::raw_ostream&);
1216};
1217
1218void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1219  assert(!isBuildingConstructorVTable() &&
1220         "Can't add thunks for construction vtable");
1221
1222  llvm::SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
1223
1224  // Check if we have this thunk already.
1225  if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1226      ThunksVector.end())
1227    return;
1228
1229  ThunksVector.push_back(Thunk);
1230}
1231
1232typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1233
1234/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1235/// the overridden methods that the function decl overrides.
1236static void
1237ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1238                            OverriddenMethodsSetTy& OverriddenMethods) {
1239  assert(MD->isVirtual() && "Method is not virtual!");
1240
1241  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1242       E = MD->end_overridden_methods(); I != E; ++I) {
1243    const CXXMethodDecl *OverriddenMD = *I;
1244
1245    OverriddenMethods.insert(OverriddenMD);
1246
1247    ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1248  }
1249}
1250
1251void VTableBuilder::ComputeThisAdjustments() {
1252  // Now go through the method info map and see if any of the methods need
1253  // 'this' pointer adjustments.
1254  for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1255       E = MethodInfoMap.end(); I != E; ++I) {
1256    const CXXMethodDecl *MD = I->first;
1257    const MethodInfo &MethodInfo = I->second;
1258
1259    // Ignore adjustments for unused function pointers.
1260    uint64_t VTableIndex = MethodInfo.VTableIndex;
1261    if (Components[VTableIndex].getKind() ==
1262        VTableComponent::CK_UnusedFunctionPointer)
1263      continue;
1264
1265    // Get the final overrider for this method.
1266    FinalOverriders::OverriderInfo Overrider =
1267      Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1268
1269    // Check if we need an adjustment at all.
1270    if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1271      // When a return thunk is needed by a derived class that overrides a
1272      // virtual base, gcc uses a virtual 'this' adjustment as well.
1273      // While the thunk itself might be needed by vtables in subclasses or
1274      // in construction vtables, there doesn't seem to be a reason for using
1275      // the thunk in this vtable. Still, we do so to match gcc.
1276      if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1277        continue;
1278    }
1279
1280    ThisAdjustment ThisAdjustment =
1281      ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1282
1283    if (ThisAdjustment.isEmpty())
1284      continue;
1285
1286    // Add it.
1287    VTableThunks[VTableIndex].This = ThisAdjustment;
1288
1289    if (isa<CXXDestructorDecl>(MD)) {
1290      // Add an adjustment for the deleting destructor as well.
1291      VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1292    }
1293  }
1294
1295  /// Clear the method info map.
1296  MethodInfoMap.clear();
1297
1298  if (isBuildingConstructorVTable()) {
1299    // We don't need to store thunk information for construction vtables.
1300    return;
1301  }
1302
1303  for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1304       E = VTableThunks.end(); I != E; ++I) {
1305    const VTableComponent &Component = Components[I->first];
1306    const ThunkInfo &Thunk = I->second;
1307    const CXXMethodDecl *MD;
1308
1309    switch (Component.getKind()) {
1310    default:
1311      llvm_unreachable("Unexpected vtable component kind!");
1312    case VTableComponent::CK_FunctionPointer:
1313      MD = Component.getFunctionDecl();
1314      break;
1315    case VTableComponent::CK_CompleteDtorPointer:
1316      MD = Component.getDestructorDecl();
1317      break;
1318    case VTableComponent::CK_DeletingDtorPointer:
1319      // We've already added the thunk when we saw the complete dtor pointer.
1320      continue;
1321    }
1322
1323    if (MD->getParent() == MostDerivedClass)
1324      AddThunk(MD, Thunk);
1325  }
1326}
1327
1328ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1329  ReturnAdjustment Adjustment;
1330
1331  if (!Offset.isEmpty()) {
1332    if (Offset.VirtualBase) {
1333      // Get the virtual base offset offset.
1334      if (Offset.DerivedClass == MostDerivedClass) {
1335        // We can get the offset offset directly from our map.
1336        Adjustment.VBaseOffsetOffset =
1337          VBaseOffsetOffsets.lookup(Offset.VirtualBase);
1338      } else {
1339        Adjustment.VBaseOffsetOffset =
1340          VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1341                                             Offset.VirtualBase);
1342      }
1343    }
1344
1345    Adjustment.NonVirtual = Offset.NonVirtualOffset;
1346  }
1347
1348  return Adjustment;
1349}
1350
1351BaseOffset
1352VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1353                                               BaseSubobject Derived) const {
1354  const CXXRecordDecl *BaseRD = Base.getBase();
1355  const CXXRecordDecl *DerivedRD = Derived.getBase();
1356
1357  CXXBasePaths Paths(/*FindAmbiguities=*/true,
1358                     /*RecordPaths=*/true, /*DetectVirtual=*/true);
1359
1360  if (!const_cast<CXXRecordDecl *>(DerivedRD)->
1361      isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
1362    assert(false && "Class must be derived from the passed in base class!");
1363    return BaseOffset();
1364  }
1365
1366  // We have to go through all the paths, and see which one leads us to the
1367  // right base subobject.
1368  for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1369       I != E; ++I) {
1370    BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1371
1372    CharUnits OffsetToBaseSubobject =
1373      CharUnits::fromQuantity(Offset.NonVirtualOffset);
1374
1375    if (Offset.VirtualBase) {
1376      // If we have a virtual base class, the non-virtual offset is relative
1377      // to the virtual base class offset.
1378      const ASTRecordLayout &LayoutClassLayout =
1379        Context.getASTRecordLayout(LayoutClass);
1380
1381      /// Get the virtual base offset, relative to the most derived class
1382      /// layout.
1383      OffsetToBaseSubobject +=
1384        LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1385    } else {
1386      // Otherwise, the non-virtual offset is relative to the derived class
1387      // offset.
1388      OffsetToBaseSubobject += Derived.getBaseOffset();
1389    }
1390
1391    // Check if this path gives us the right base subobject.
1392    if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1393      // Since we're going from the base class _to_ the derived class, we'll
1394      // invert the non-virtual offset here.
1395      Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1396      return Offset;
1397    }
1398  }
1399
1400  return BaseOffset();
1401}
1402
1403ThisAdjustment
1404VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1405                                     CharUnits BaseOffsetInLayoutClass,
1406                                     FinalOverriders::OverriderInfo Overrider) {
1407  // Ignore adjustments for pure virtual member functions.
1408  if (Overrider.Method->isPure())
1409    return ThisAdjustment();
1410
1411  BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1412                                        BaseOffsetInLayoutClass);
1413
1414  BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1415                                       Overrider.Offset);
1416
1417  // Compute the adjustment offset.
1418  BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1419                                                      OverriderBaseSubobject);
1420  if (Offset.isEmpty())
1421    return ThisAdjustment();
1422
1423  ThisAdjustment Adjustment;
1424
1425  if (Offset.VirtualBase) {
1426    // Get the vcall offset map for this virtual base.
1427    VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1428
1429    if (VCallOffsets.empty()) {
1430      // We don't have vcall offsets for this virtual base, go ahead and
1431      // build them.
1432      VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1433                                         /*FinalOverriders=*/0,
1434                                         BaseSubobject(Offset.VirtualBase,
1435                                                       CharUnits::Zero()),
1436                                         /*BaseIsVirtual=*/true,
1437                                         /*OffsetInLayoutClass=*/
1438                                             CharUnits::Zero());
1439
1440      VCallOffsets = Builder.getVCallOffsets();
1441    }
1442
1443    Adjustment.VCallOffsetOffset = VCallOffsets.getVCallOffsetOffset(MD);
1444  }
1445
1446  // Set the non-virtual part of the adjustment.
1447  Adjustment.NonVirtual = Offset.NonVirtualOffset;
1448
1449  return Adjustment;
1450}
1451
1452void
1453VTableBuilder::AddMethod(const CXXMethodDecl *MD,
1454                         ReturnAdjustment ReturnAdjustment) {
1455  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1456    assert(ReturnAdjustment.isEmpty() &&
1457           "Destructor can't have return adjustment!");
1458
1459    // Add both the complete destructor and the deleting destructor.
1460    Components.push_back(VTableComponent::MakeCompleteDtor(DD));
1461    Components.push_back(VTableComponent::MakeDeletingDtor(DD));
1462  } else {
1463    // Add the return adjustment if necessary.
1464    if (!ReturnAdjustment.isEmpty())
1465      VTableThunks[Components.size()].Return = ReturnAdjustment;
1466
1467    // Add the function.
1468    Components.push_back(VTableComponent::MakeFunction(MD));
1469  }
1470}
1471
1472/// OverridesIndirectMethodInBase - Return whether the given member function
1473/// overrides any methods in the set of given bases.
1474/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1475/// For example, if we have:
1476///
1477/// struct A { virtual void f(); }
1478/// struct B : A { virtual void f(); }
1479/// struct C : B { virtual void f(); }
1480///
1481/// OverridesIndirectMethodInBase will return true if given C::f as the method
1482/// and { A } as the set of bases.
1483static bool
1484OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
1485                               VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1486  if (Bases.count(MD->getParent()))
1487    return true;
1488
1489  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1490       E = MD->end_overridden_methods(); I != E; ++I) {
1491    const CXXMethodDecl *OverriddenMD = *I;
1492
1493    // Check "indirect overriders".
1494    if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1495      return true;
1496  }
1497
1498  return false;
1499}
1500
1501bool
1502VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1503                               uint64_t BaseOffsetInLayoutClass,
1504                               const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1505                               uint64_t FirstBaseOffsetInLayoutClass) const {
1506  // If the base and the first base in the primary base chain have the same
1507  // offsets, then this overrider will be used.
1508  if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
1509   return true;
1510
1511  // We know now that Base (or a direct or indirect base of it) is a primary
1512  // base in part of the class hierarchy, but not a primary base in the most
1513  // derived class.
1514
1515  // If the overrider is the first base in the primary base chain, we know
1516  // that the overrider will be used.
1517  if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
1518    return true;
1519
1520  VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
1521
1522  const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
1523  PrimaryBases.insert(RD);
1524
1525  // Now traverse the base chain, starting with the first base, until we find
1526  // the base that is no longer a primary base.
1527  while (true) {
1528    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1529    const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1530
1531    if (!PrimaryBase)
1532      break;
1533
1534    if (Layout.isPrimaryBaseVirtual()) {
1535      assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
1536             "Primary base should always be at offset 0!");
1537
1538      const ASTRecordLayout &LayoutClassLayout =
1539        Context.getASTRecordLayout(LayoutClass);
1540
1541      // Now check if this is the primary base that is not a primary base in the
1542      // most derived class.
1543      if (LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase) !=
1544          FirstBaseOffsetInLayoutClass) {
1545        // We found it, stop walking the chain.
1546        break;
1547      }
1548    } else {
1549      assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
1550             "Primary base should always be at offset 0!");
1551    }
1552
1553    if (!PrimaryBases.insert(PrimaryBase))
1554      assert(false && "Found a duplicate primary base!");
1555
1556    RD = PrimaryBase;
1557  }
1558
1559  // If the final overrider is an override of one of the primary bases,
1560  // then we know that it will be used.
1561  return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
1562}
1563
1564/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1565/// from the nearest base. Returns null if no method was found.
1566static const CXXMethodDecl *
1567FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1568                            VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
1569  OverriddenMethodsSetTy OverriddenMethods;
1570  ComputeAllOverriddenMethods(MD, OverriddenMethods);
1571
1572  for (int I = Bases.size(), E = 0; I != E; --I) {
1573    const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1574
1575    // Now check the overriden methods.
1576    for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
1577         E = OverriddenMethods.end(); I != E; ++I) {
1578      const CXXMethodDecl *OverriddenMD = *I;
1579
1580      // We found our overridden method.
1581      if (OverriddenMD->getParent() == PrimaryBase)
1582        return OverriddenMD;
1583    }
1584  }
1585
1586  return 0;
1587}
1588
1589void
1590VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1591                          const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1592                          CharUnits FirstBaseOffsetInLayoutClass,
1593                          PrimaryBasesSetVectorTy &PrimaryBases) {
1594  const CXXRecordDecl *RD = Base.getBase();
1595  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1596
1597  if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1598    CharUnits PrimaryBaseOffset;
1599    CharUnits PrimaryBaseOffsetInLayoutClass;
1600    if (Layout.isPrimaryBaseVirtual()) {
1601      assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
1602             "Primary vbase should have a zero offset!");
1603
1604      const ASTRecordLayout &MostDerivedClassLayout =
1605        Context.getASTRecordLayout(MostDerivedClass);
1606
1607      PrimaryBaseOffset =
1608        MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1609
1610      const ASTRecordLayout &LayoutClassLayout =
1611        Context.getASTRecordLayout(LayoutClass);
1612
1613      PrimaryBaseOffsetInLayoutClass =
1614        LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1615    } else {
1616      assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
1617             "Primary base should have a zero offset!");
1618
1619      PrimaryBaseOffset = Base.getBaseOffset();
1620      PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
1621    }
1622
1623    AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1624               PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1625               FirstBaseOffsetInLayoutClass, PrimaryBases);
1626
1627    if (!PrimaryBases.insert(PrimaryBase))
1628      assert(false && "Found a duplicate primary base!");
1629  }
1630
1631  // Now go through all virtual member functions and add them.
1632  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1633       E = RD->method_end(); I != E; ++I) {
1634    const CXXMethodDecl *MD = *I;
1635
1636    if (!MD->isVirtual())
1637      continue;
1638
1639    // Get the final overrider.
1640    FinalOverriders::OverriderInfo Overrider =
1641      Overriders.getOverrider(MD, Base.getBaseOffset());
1642
1643    // Check if this virtual member function overrides a method in a primary
1644    // base. If this is the case, and the return type doesn't require adjustment
1645    // then we can just use the member function from the primary base.
1646    if (const CXXMethodDecl *OverriddenMD =
1647          FindNearestOverriddenMethod(MD, PrimaryBases)) {
1648      if (ComputeReturnAdjustmentBaseOffset(Context, MD,
1649                                            OverriddenMD).isEmpty()) {
1650        // Replace the method info of the overridden method with our own
1651        // method.
1652        assert(MethodInfoMap.count(OverriddenMD) &&
1653               "Did not find the overridden method!");
1654        MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1655
1656        MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1657                              OverriddenMethodInfo.VTableIndex);
1658
1659        assert(!MethodInfoMap.count(MD) &&
1660               "Should not have method info for this method yet!");
1661
1662        MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1663        MethodInfoMap.erase(OverriddenMD);
1664
1665        // If the overridden method exists in a virtual base class or a direct
1666        // or indirect base class of a virtual base class, we need to emit a
1667        // thunk if we ever have a class hierarchy where the base class is not
1668        // a primary base in the complete object.
1669        if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
1670          // Compute the this adjustment.
1671          ThisAdjustment ThisAdjustment =
1672            ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
1673                                  Overrider);
1674
1675          if (ThisAdjustment.VCallOffsetOffset &&
1676              Overrider.Method->getParent() == MostDerivedClass) {
1677
1678            // There's no return adjustment from OverriddenMD and MD,
1679            // but that doesn't mean there isn't one between MD and
1680            // the final overrider.
1681            BaseOffset ReturnAdjustmentOffset =
1682              ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
1683            ReturnAdjustment ReturnAdjustment =
1684              ComputeReturnAdjustment(ReturnAdjustmentOffset);
1685
1686            // This is a virtual thunk for the most derived class, add it.
1687            AddThunk(Overrider.Method,
1688                     ThunkInfo(ThisAdjustment, ReturnAdjustment));
1689          }
1690        }
1691
1692        continue;
1693      }
1694    }
1695
1696    // Insert the method info for this method.
1697    MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1698                          Components.size());
1699
1700    assert(!MethodInfoMap.count(MD) &&
1701           "Should not have method info for this method yet!");
1702    MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1703
1704    // Check if this overrider is going to be used.
1705    const CXXMethodDecl *OverriderMD = Overrider.Method;
1706    if (!IsOverriderUsed(OverriderMD, Context.toBits(BaseOffsetInLayoutClass),
1707                         FirstBaseInPrimaryBaseChain,
1708                         Context.toBits(FirstBaseOffsetInLayoutClass))) {
1709      Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
1710      continue;
1711    }
1712
1713    // Check if this overrider needs a return adjustment.
1714    // We don't want to do this for pure virtual member functions.
1715    BaseOffset ReturnAdjustmentOffset;
1716    if (!OverriderMD->isPure()) {
1717      ReturnAdjustmentOffset =
1718        ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
1719    }
1720
1721    ReturnAdjustment ReturnAdjustment =
1722      ComputeReturnAdjustment(ReturnAdjustmentOffset);
1723
1724    AddMethod(Overrider.Method, ReturnAdjustment);
1725  }
1726}
1727
1728void VTableBuilder::LayoutVTable() {
1729  LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
1730                                                 CharUnits::Zero()),
1731                                   /*BaseIsMorallyVirtual=*/false,
1732                                   MostDerivedClassIsVirtual,
1733                                   MostDerivedClassOffset);
1734
1735  VisitedVirtualBasesSetTy VBases;
1736
1737  // Determine the primary virtual bases.
1738  DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1739                               VBases);
1740  VBases.clear();
1741
1742  LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
1743}
1744
1745void
1746VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1747                                                bool BaseIsMorallyVirtual,
1748                                                bool BaseIsVirtualInLayoutClass,
1749                                                CharUnits OffsetInLayoutClass) {
1750  assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
1751
1752  // Add vcall and vbase offsets for this vtable.
1753  VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1754                                     Base, BaseIsVirtualInLayoutClass,
1755                                     OffsetInLayoutClass);
1756  Components.append(Builder.components_begin(), Builder.components_end());
1757
1758  // Check if we need to add these vcall offsets.
1759  if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
1760    VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1761
1762    if (VCallOffsets.empty())
1763      VCallOffsets = Builder.getVCallOffsets();
1764  }
1765
1766  // If we're laying out the most derived class we want to keep track of the
1767  // virtual base class offset offsets.
1768  if (Base.getBase() == MostDerivedClass)
1769    VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1770
1771  // Add the offset to top.
1772  CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
1773  Components.push_back(
1774    VTableComponent::MakeOffsetToTop(OffsetToTop.getQuantity()));
1775
1776  // Next, add the RTTI.
1777  Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1778
1779  uint64_t AddressPoint = Components.size();
1780
1781  // Now go through all virtual member functions and add them.
1782  PrimaryBasesSetVectorTy PrimaryBases;
1783  AddMethods(Base, OffsetInLayoutClass,
1784             Base.getBase(), OffsetInLayoutClass,
1785             PrimaryBases);
1786
1787  // Compute 'this' pointer adjustments.
1788  ComputeThisAdjustments();
1789
1790  // Add all address points.
1791  const CXXRecordDecl *RD = Base.getBase();
1792  while (true) {
1793    AddressPoints.insert(std::make_pair(
1794      BaseSubobject(RD, OffsetInLayoutClass),
1795      AddressPoint));
1796
1797    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1798    const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1799
1800    if (!PrimaryBase)
1801      break;
1802
1803    if (Layout.isPrimaryBaseVirtual()) {
1804      // Check if this virtual primary base is a primary base in the layout
1805      // class. If it's not, we don't want to add it.
1806      const ASTRecordLayout &LayoutClassLayout =
1807        Context.getASTRecordLayout(LayoutClass);
1808
1809      if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
1810          OffsetInLayoutClass) {
1811        // We don't want to add this class (or any of its primary bases).
1812        break;
1813      }
1814    }
1815
1816    RD = PrimaryBase;
1817  }
1818
1819  // Layout secondary vtables.
1820  LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1821}
1822
1823void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1824                                           bool BaseIsMorallyVirtual,
1825                                           CharUnits OffsetInLayoutClass) {
1826  // Itanium C++ ABI 2.5.2:
1827  //   Following the primary virtual table of a derived class are secondary
1828  //   virtual tables for each of its proper base classes, except any primary
1829  //   base(s) with which it shares its primary virtual table.
1830
1831  const CXXRecordDecl *RD = Base.getBase();
1832  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1833  const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1834
1835  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1836       E = RD->bases_end(); I != E; ++I) {
1837    // Ignore virtual bases, we'll emit them later.
1838    if (I->isVirtual())
1839      continue;
1840
1841    const CXXRecordDecl *BaseDecl =
1842      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1843
1844    // Ignore bases that don't have a vtable.
1845    if (!BaseDecl->isDynamicClass())
1846      continue;
1847
1848    if (isBuildingConstructorVTable()) {
1849      // Itanium C++ ABI 2.6.4:
1850      //   Some of the base class subobjects may not need construction virtual
1851      //   tables, which will therefore not be present in the construction
1852      //   virtual table group, even though the subobject virtual tables are
1853      //   present in the main virtual table group for the complete object.
1854      if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1855        continue;
1856    }
1857
1858    // Get the base offset of this base.
1859    CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1860    CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1861
1862    CharUnits BaseOffsetInLayoutClass =
1863      OffsetInLayoutClass + RelativeBaseOffset;
1864
1865    // Don't emit a secondary vtable for a primary base. We might however want
1866    // to emit secondary vtables for other bases of this base.
1867    if (BaseDecl == PrimaryBase) {
1868      LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
1869                             BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
1870      continue;
1871    }
1872
1873    // Layout the primary vtable (and any secondary vtables) for this base.
1874    LayoutPrimaryAndSecondaryVTables(
1875      BaseSubobject(BaseDecl, BaseOffset),
1876      BaseIsMorallyVirtual,
1877      /*BaseIsVirtualInLayoutClass=*/false,
1878      BaseOffsetInLayoutClass);
1879  }
1880}
1881
1882void
1883VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1884                                            CharUnits OffsetInLayoutClass,
1885                                            VisitedVirtualBasesSetTy &VBases) {
1886  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1887
1888  // Check if this base has a primary base.
1889  if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1890
1891    // Check if it's virtual.
1892    if (Layout.isPrimaryBaseVirtual()) {
1893      bool IsPrimaryVirtualBase = true;
1894
1895      if (isBuildingConstructorVTable()) {
1896        // Check if the base is actually a primary base in the class we use for
1897        // layout.
1898        const ASTRecordLayout &LayoutClassLayout =
1899          Context.getASTRecordLayout(LayoutClass);
1900
1901        CharUnits PrimaryBaseOffsetInLayoutClass =
1902          LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
1903
1904        // We know that the base is not a primary base in the layout class if
1905        // the base offsets are different.
1906        if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1907          IsPrimaryVirtualBase = false;
1908      }
1909
1910      if (IsPrimaryVirtualBase)
1911        PrimaryVirtualBases.insert(PrimaryBase);
1912    }
1913  }
1914
1915  // Traverse bases, looking for more primary virtual bases.
1916  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1917       E = RD->bases_end(); I != E; ++I) {
1918    const CXXRecordDecl *BaseDecl =
1919      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1920
1921    CharUnits BaseOffsetInLayoutClass;
1922
1923    if (I->isVirtual()) {
1924      if (!VBases.insert(BaseDecl))
1925        continue;
1926
1927      const ASTRecordLayout &LayoutClassLayout =
1928        Context.getASTRecordLayout(LayoutClass);
1929
1930      BaseOffsetInLayoutClass =
1931        LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1932    } else {
1933      BaseOffsetInLayoutClass =
1934        OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
1935    }
1936
1937    DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1938  }
1939}
1940
1941void
1942VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1943                                            VisitedVirtualBasesSetTy &VBases) {
1944  // Itanium C++ ABI 2.5.2:
1945  //   Then come the virtual base virtual tables, also in inheritance graph
1946  //   order, and again excluding primary bases (which share virtual tables with
1947  //   the classes for which they are primary).
1948  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1949       E = RD->bases_end(); I != E; ++I) {
1950    const CXXRecordDecl *BaseDecl =
1951      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1952
1953    // Check if this base needs a vtable. (If it's virtual, not a primary base
1954    // of some other class, and we haven't visited it before).
1955    if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1956        !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1957      const ASTRecordLayout &MostDerivedClassLayout =
1958        Context.getASTRecordLayout(MostDerivedClass);
1959      CharUnits BaseOffset =
1960        MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
1961
1962      const ASTRecordLayout &LayoutClassLayout =
1963        Context.getASTRecordLayout(LayoutClass);
1964      CharUnits BaseOffsetInLayoutClass =
1965        LayoutClassLayout.getVBaseClassOffset(BaseDecl);
1966
1967      LayoutPrimaryAndSecondaryVTables(
1968        BaseSubobject(BaseDecl, BaseOffset),
1969        /*BaseIsMorallyVirtual=*/true,
1970        /*BaseIsVirtualInLayoutClass=*/true,
1971        BaseOffsetInLayoutClass);
1972    }
1973
1974    // We only need to check the base for virtual base vtables if it actually
1975    // has virtual bases.
1976    if (BaseDecl->getNumVBases())
1977      LayoutVTablesForVirtualBases(BaseDecl, VBases);
1978  }
1979}
1980
1981/// dumpLayout - Dump the vtable layout.
1982void VTableBuilder::dumpLayout(llvm::raw_ostream& Out) {
1983
1984  if (isBuildingConstructorVTable()) {
1985    Out << "Construction vtable for ('";
1986    Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1987    Out << MostDerivedClassOffset.getQuantity() << ") in '";
1988    Out << LayoutClass->getQualifiedNameAsString();
1989  } else {
1990    Out << "Vtable for '";
1991    Out << MostDerivedClass->getQualifiedNameAsString();
1992  }
1993  Out << "' (" << Components.size() << " entries).\n";
1994
1995  // Iterate through the address points and insert them into a new map where
1996  // they are keyed by the index and not the base object.
1997  // Since an address point can be shared by multiple subobjects, we use an
1998  // STL multimap.
1999  std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
2000  for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
2001       E = AddressPoints.end(); I != E; ++I) {
2002    const BaseSubobject& Base = I->first;
2003    uint64_t Index = I->second;
2004
2005    AddressPointsByIndex.insert(std::make_pair(Index, Base));
2006  }
2007
2008  for (unsigned I = 0, E = Components.size(); I != E; ++I) {
2009    uint64_t Index = I;
2010
2011    Out << llvm::format("%4d | ", I);
2012
2013    const VTableComponent &Component = Components[I];
2014
2015    // Dump the component.
2016    switch (Component.getKind()) {
2017
2018    case VTableComponent::CK_VCallOffset:
2019      Out << "vcall_offset (" << Component.getVCallOffset() << ")";
2020      break;
2021
2022    case VTableComponent::CK_VBaseOffset:
2023      Out << "vbase_offset (" << Component.getVBaseOffset() << ")";
2024      break;
2025
2026    case VTableComponent::CK_OffsetToTop:
2027      Out << "offset_to_top (" << Component.getOffsetToTop() << ")";
2028      break;
2029
2030    case VTableComponent::CK_RTTI:
2031      Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
2032      break;
2033
2034    case VTableComponent::CK_FunctionPointer: {
2035      const CXXMethodDecl *MD = Component.getFunctionDecl();
2036
2037      std::string Str =
2038        PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2039                                    MD);
2040      Out << Str;
2041      if (MD->isPure())
2042        Out << " [pure]";
2043
2044      ThunkInfo Thunk = VTableThunks.lookup(I);
2045      if (!Thunk.isEmpty()) {
2046        // If this function pointer has a return adjustment, dump it.
2047        if (!Thunk.Return.isEmpty()) {
2048          Out << "\n       [return adjustment: ";
2049          Out << Thunk.Return.NonVirtual << " non-virtual";
2050
2051          if (Thunk.Return.VBaseOffsetOffset) {
2052            Out << ", " << Thunk.Return.VBaseOffsetOffset;
2053            Out << " vbase offset offset";
2054          }
2055
2056          Out << ']';
2057        }
2058
2059        // If this function pointer has a 'this' pointer adjustment, dump it.
2060        if (!Thunk.This.isEmpty()) {
2061          Out << "\n       [this adjustment: ";
2062          Out << Thunk.This.NonVirtual << " non-virtual";
2063
2064          if (Thunk.This.VCallOffsetOffset) {
2065            Out << ", " << Thunk.This.VCallOffsetOffset;
2066            Out << " vcall offset offset";
2067          }
2068
2069          Out << ']';
2070        }
2071      }
2072
2073      break;
2074    }
2075
2076    case VTableComponent::CK_CompleteDtorPointer:
2077    case VTableComponent::CK_DeletingDtorPointer: {
2078      bool IsComplete =
2079        Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2080
2081      const CXXDestructorDecl *DD = Component.getDestructorDecl();
2082
2083      Out << DD->getQualifiedNameAsString();
2084      if (IsComplete)
2085        Out << "() [complete]";
2086      else
2087        Out << "() [deleting]";
2088
2089      if (DD->isPure())
2090        Out << " [pure]";
2091
2092      ThunkInfo Thunk = VTableThunks.lookup(I);
2093      if (!Thunk.isEmpty()) {
2094        // If this destructor has a 'this' pointer adjustment, dump it.
2095        if (!Thunk.This.isEmpty()) {
2096          Out << "\n       [this adjustment: ";
2097          Out << Thunk.This.NonVirtual << " non-virtual";
2098
2099          if (Thunk.This.VCallOffsetOffset) {
2100            Out << ", " << Thunk.This.VCallOffsetOffset;
2101            Out << " vcall offset offset";
2102          }
2103
2104          Out << ']';
2105        }
2106      }
2107
2108      break;
2109    }
2110
2111    case VTableComponent::CK_UnusedFunctionPointer: {
2112      const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2113
2114      std::string Str =
2115        PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2116                                    MD);
2117      Out << "[unused] " << Str;
2118      if (MD->isPure())
2119        Out << " [pure]";
2120    }
2121
2122    }
2123
2124    Out << '\n';
2125
2126    // Dump the next address point.
2127    uint64_t NextIndex = Index + 1;
2128    if (AddressPointsByIndex.count(NextIndex)) {
2129      if (AddressPointsByIndex.count(NextIndex) == 1) {
2130        const BaseSubobject &Base =
2131          AddressPointsByIndex.find(NextIndex)->second;
2132
2133        Out << "       -- (" << Base.getBase()->getQualifiedNameAsString();
2134        Out << ", " << Base.getBaseOffset().getQuantity();
2135        Out << ") vtable address --\n";
2136      } else {
2137        CharUnits BaseOffset =
2138          AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2139
2140        // We store the class names in a set to get a stable order.
2141        std::set<std::string> ClassNames;
2142        for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2143             AddressPointsByIndex.lower_bound(NextIndex), E =
2144             AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2145          assert(I->second.getBaseOffset() == BaseOffset &&
2146                 "Invalid base offset!");
2147          const CXXRecordDecl *RD = I->second.getBase();
2148          ClassNames.insert(RD->getQualifiedNameAsString());
2149        }
2150
2151        for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2152             E = ClassNames.end(); I != E; ++I) {
2153          Out << "       -- (" << *I;
2154          Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2155        }
2156      }
2157    }
2158  }
2159
2160  Out << '\n';
2161
2162  if (isBuildingConstructorVTable())
2163    return;
2164
2165  if (MostDerivedClass->getNumVBases()) {
2166    // We store the virtual base class names and their offsets in a map to get
2167    // a stable order.
2168
2169    std::map<std::string, int64_t> ClassNamesAndOffsets;
2170    for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2171         E = VBaseOffsetOffsets.end(); I != E; ++I) {
2172      std::string ClassName = I->first->getQualifiedNameAsString();
2173      int64_t OffsetOffset = I->second;
2174      ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
2175    }
2176
2177    Out << "Virtual base offset offsets for '";
2178    Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2179    Out << ClassNamesAndOffsets.size();
2180    Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2181
2182    for (std::map<std::string, int64_t>::const_iterator I =
2183         ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2184         I != E; ++I)
2185      Out << "   " << I->first << " | " << I->second << '\n';
2186
2187    Out << "\n";
2188  }
2189
2190  if (!Thunks.empty()) {
2191    // We store the method names in a map to get a stable order.
2192    std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2193
2194    for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2195         I != E; ++I) {
2196      const CXXMethodDecl *MD = I->first;
2197      std::string MethodName =
2198        PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2199                                    MD);
2200
2201      MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2202    }
2203
2204    for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2205         MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2206         I != E; ++I) {
2207      const std::string &MethodName = I->first;
2208      const CXXMethodDecl *MD = I->second;
2209
2210      ThunkInfoVectorTy ThunksVector = Thunks[MD];
2211      std::sort(ThunksVector.begin(), ThunksVector.end());
2212
2213      Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2214      Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2215
2216      for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2217        const ThunkInfo &Thunk = ThunksVector[I];
2218
2219        Out << llvm::format("%4d | ", I);
2220
2221        // If this function pointer has a return pointer adjustment, dump it.
2222        if (!Thunk.Return.isEmpty()) {
2223          Out << "return adjustment: " << Thunk.This.NonVirtual;
2224          Out << " non-virtual";
2225          if (Thunk.Return.VBaseOffsetOffset) {
2226            Out << ", " << Thunk.Return.VBaseOffsetOffset;
2227            Out << " vbase offset offset";
2228          }
2229
2230          if (!Thunk.This.isEmpty())
2231            Out << "\n       ";
2232        }
2233
2234        // If this function pointer has a 'this' pointer adjustment, dump it.
2235        if (!Thunk.This.isEmpty()) {
2236          Out << "this adjustment: ";
2237          Out << Thunk.This.NonVirtual << " non-virtual";
2238
2239          if (Thunk.This.VCallOffsetOffset) {
2240            Out << ", " << Thunk.This.VCallOffsetOffset;
2241            Out << " vcall offset offset";
2242          }
2243        }
2244
2245        Out << '\n';
2246      }
2247
2248      Out << '\n';
2249
2250    }
2251  }
2252}
2253
2254}
2255
2256static void
2257CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2258                    VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2259  while (RD) {
2260    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2261    const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2262    if (PrimaryBase)
2263      PrimaryBases.insert(PrimaryBase);
2264
2265    RD = PrimaryBase;
2266  }
2267}
2268
2269void CodeGenVTables::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2270
2271  // Itanium C++ ABI 2.5.2:
2272  //   The order of the virtual function pointers in a virtual table is the
2273  //   order of declaration of the corresponding member functions in the class.
2274  //
2275  //   There is an entry for any virtual function declared in a class,
2276  //   whether it is a new function or overrides a base class function,
2277  //   unless it overrides a function from the primary base, and conversion
2278  //   between their return types does not require an adjustment.
2279
2280  int64_t CurrentIndex = 0;
2281
2282  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2283  const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2284
2285  if (PrimaryBase) {
2286    assert(PrimaryBase->isDefinition() &&
2287           "Should have the definition decl of the primary base!");
2288
2289    // Since the record decl shares its vtable pointer with the primary base
2290    // we need to start counting at the end of the primary base's vtable.
2291    CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2292  }
2293
2294  // Collect all the primary bases, so we can check whether methods override
2295  // a method from the base.
2296  VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2297  CollectPrimaryBases(RD, CGM.getContext(), PrimaryBases);
2298
2299  const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2300
2301  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2302       e = RD->method_end(); i != e; ++i) {
2303    const CXXMethodDecl *MD = *i;
2304
2305    // We only want virtual methods.
2306    if (!MD->isVirtual())
2307      continue;
2308
2309    // Check if this method overrides a method in the primary base.
2310    if (const CXXMethodDecl *OverriddenMD =
2311          FindNearestOverriddenMethod(MD, PrimaryBases)) {
2312      // Check if converting from the return type of the method to the
2313      // return type of the overridden method requires conversion.
2314      if (ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD,
2315                                            OverriddenMD).isEmpty()) {
2316        // This index is shared between the index in the vtable of the primary
2317        // base class.
2318        if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2319          const CXXDestructorDecl *OverriddenDD =
2320            cast<CXXDestructorDecl>(OverriddenMD);
2321
2322          // Add both the complete and deleting entries.
2323          MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2324            getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2325          MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2326            getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2327        } else {
2328          MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2329        }
2330
2331        // We don't need to add an entry for this method.
2332        continue;
2333      }
2334    }
2335
2336    if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2337      if (MD->isImplicit()) {
2338        assert(!ImplicitVirtualDtor &&
2339               "Did already see an implicit virtual dtor!");
2340        ImplicitVirtualDtor = DD;
2341        continue;
2342      }
2343
2344      // Add the complete dtor.
2345      MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2346
2347      // Add the deleting dtor.
2348      MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2349    } else {
2350      // Add the entry.
2351      MethodVTableIndices[MD] = CurrentIndex++;
2352    }
2353  }
2354
2355  if (ImplicitVirtualDtor) {
2356    // Itanium C++ ABI 2.5.2:
2357    //   If a class has an implicitly-defined virtual destructor,
2358    //   its entries come after the declared virtual function pointers.
2359
2360    // Add the complete dtor.
2361    MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
2362      CurrentIndex++;
2363
2364    // Add the deleting dtor.
2365    MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
2366      CurrentIndex++;
2367  }
2368
2369  NumVirtualFunctionPointers[RD] = CurrentIndex;
2370}
2371
2372bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) {
2373  assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
2374
2375  TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2376  if (TSK == TSK_ExplicitInstantiationDeclaration)
2377    return false;
2378
2379  const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
2380  if (!KeyFunction)
2381    return true;
2382
2383  // Itanium C++ ABI, 5.2.6 Instantiated Templates:
2384  //    An instantiation of a class template requires:
2385  //        - In the object where instantiated, the virtual table...
2386  if (TSK == TSK_ImplicitInstantiation ||
2387      TSK == TSK_ExplicitInstantiationDefinition)
2388    return true;
2389
2390  // If we're building with optimization, we always emit VTables since that
2391  // allows for virtual function calls to be devirtualized.
2392  // (We don't want to do this in -fapple-kext mode however).
2393  if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOptions().AppleKext)
2394    return true;
2395
2396  return KeyFunction->hasBody();
2397}
2398
2399uint64_t CodeGenVTables::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2400  llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2401    NumVirtualFunctionPointers.find(RD);
2402  if (I != NumVirtualFunctionPointers.end())
2403    return I->second;
2404
2405  ComputeMethodVTableIndices(RD);
2406
2407  I = NumVirtualFunctionPointers.find(RD);
2408  assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2409  return I->second;
2410}
2411
2412uint64_t CodeGenVTables::getMethodVTableIndex(GlobalDecl GD) {
2413  MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2414  if (I != MethodVTableIndices.end())
2415    return I->second;
2416
2417  const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2418
2419  ComputeMethodVTableIndices(RD);
2420
2421  I = MethodVTableIndices.find(GD);
2422  assert(I != MethodVTableIndices.end() && "Did not find index!");
2423  return I->second;
2424}
2425
2426int64_t CodeGenVTables::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2427                                                   const CXXRecordDecl *VBase) {
2428  ClassPairTy ClassPair(RD, VBase);
2429
2430  VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2431    VirtualBaseClassOffsetOffsets.find(ClassPair);
2432  if (I != VirtualBaseClassOffsetOffsets.end())
2433    return I->second;
2434
2435  VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2436                                     BaseSubobject(RD, CharUnits::Zero()),
2437                                     /*BaseIsVirtual=*/false,
2438                                     /*OffsetInLayoutClass=*/CharUnits::Zero());
2439
2440  for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2441       Builder.getVBaseOffsetOffsets().begin(),
2442       E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2443    // Insert all types.
2444    ClassPairTy ClassPair(RD, I->first);
2445
2446    VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2447  }
2448
2449  I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2450  assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2451
2452  return I->second;
2453}
2454
2455uint64_t
2456CodeGenVTables::getAddressPoint(BaseSubobject Base, const CXXRecordDecl *RD) {
2457  assert(AddressPoints.count(std::make_pair(RD, Base)) &&
2458         "Did not find address point!");
2459
2460  uint64_t AddressPoint = AddressPoints.lookup(std::make_pair(RD, Base));
2461  assert(AddressPoint && "Address point must not be zero!");
2462
2463  return AddressPoint;
2464}
2465
2466llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
2467                                              const ThunkInfo &Thunk) {
2468  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2469
2470  // Compute the mangled name.
2471  llvm::SmallString<256> Name;
2472  llvm::raw_svector_ostream Out(Name);
2473  if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
2474    getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
2475                                                      Thunk.This, Out);
2476  else
2477    getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
2478  Out.flush();
2479
2480  const llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
2481  return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
2482}
2483
2484static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
2485                                          llvm::Value *Ptr,
2486                                          int64_t NonVirtualAdjustment,
2487                                          int64_t VirtualAdjustment) {
2488  if (!NonVirtualAdjustment && !VirtualAdjustment)
2489    return Ptr;
2490
2491  const llvm::Type *Int8PtrTy =
2492    llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
2493
2494  llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
2495
2496  if (NonVirtualAdjustment) {
2497    // Do the non-virtual adjustment.
2498    V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
2499  }
2500
2501  if (VirtualAdjustment) {
2502    const llvm::Type *PtrDiffTy =
2503      CGF.ConvertType(CGF.getContext().getPointerDiffType());
2504
2505    // Do the virtual adjustment.
2506    llvm::Value *VTablePtrPtr =
2507      CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
2508
2509    llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
2510
2511    llvm::Value *OffsetPtr =
2512      CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
2513
2514    OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
2515
2516    // Load the adjustment offset from the vtable.
2517    llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
2518
2519    // Adjust our pointer.
2520    V = CGF.Builder.CreateInBoundsGEP(V, Offset);
2521  }
2522
2523  // Cast back to the original type.
2524  return CGF.Builder.CreateBitCast(V, Ptr->getType());
2525}
2526
2527static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
2528                               const ThunkInfo &Thunk, llvm::Function *Fn) {
2529  CGM.setGlobalVisibility(Fn, MD);
2530
2531  if (!CGM.getCodeGenOpts().HiddenWeakVTables)
2532    return;
2533
2534  // If the thunk has weak/linkonce linkage, but the function must be
2535  // emitted in every translation unit that references it, then we can
2536  // emit its thunks with hidden visibility, since its thunks must be
2537  // emitted when the function is.
2538
2539  // This follows CodeGenModule::setTypeVisibility; see the comments
2540  // there for explanation.
2541
2542  if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
2543       Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
2544      Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
2545    return;
2546
2547  if (MD->getExplicitVisibility())
2548    return;
2549
2550  switch (MD->getTemplateSpecializationKind()) {
2551  case TSK_ExplicitInstantiationDefinition:
2552  case TSK_ExplicitInstantiationDeclaration:
2553    return;
2554
2555  case TSK_Undeclared:
2556    break;
2557
2558  case TSK_ExplicitSpecialization:
2559  case TSK_ImplicitInstantiation:
2560    if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables)
2561      return;
2562    break;
2563  }
2564
2565  // If there's an explicit definition, and that definition is
2566  // out-of-line, then we can't assume that all users will have a
2567  // definition to emit.
2568  const FunctionDecl *Def = 0;
2569  if (MD->hasBody(Def) && Def->isOutOfLine())
2570    return;
2571
2572  Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
2573}
2574
2575#ifndef NDEBUG
2576static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
2577                    const ABIArgInfo &infoR, CanQualType typeR) {
2578  return (infoL.getKind() == infoR.getKind() &&
2579          (typeL == typeR ||
2580           (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
2581           (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
2582}
2583#endif
2584
2585void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
2586                                    const CGFunctionInfo &FnInfo,
2587                                    GlobalDecl GD, const ThunkInfo &Thunk) {
2588  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2589  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
2590  QualType ResultType = FPT->getResultType();
2591  QualType ThisType = MD->getThisType(getContext());
2592
2593  FunctionArgList FunctionArgs;
2594
2595  // FIXME: It would be nice if more of this code could be shared with
2596  // CodeGenFunction::GenerateCode.
2597
2598  // Create the implicit 'this' parameter declaration.
2599  CurGD = GD;
2600  CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
2601
2602  // Add the rest of the parameters.
2603  for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2604       E = MD->param_end(); I != E; ++I) {
2605    ParmVarDecl *Param = *I;
2606
2607    FunctionArgs.push_back(Param);
2608  }
2609
2610  StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
2611                SourceLocation());
2612
2613  CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2614
2615  // Adjust the 'this' pointer if necessary.
2616  llvm::Value *AdjustedThisPtr =
2617    PerformTypeAdjustment(*this, LoadCXXThis(),
2618                          Thunk.This.NonVirtual,
2619                          Thunk.This.VCallOffsetOffset);
2620
2621  CallArgList CallArgs;
2622
2623  // Add our adjusted 'this' pointer.
2624  CallArgs.push_back(std::make_pair(RValue::get(AdjustedThisPtr), ThisType));
2625
2626  // Add the rest of the parameters.
2627  for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2628       E = MD->param_end(); I != E; ++I) {
2629    ParmVarDecl *param = *I;
2630    EmitDelegateCallArg(CallArgs, param);
2631  }
2632
2633  // Get our callee.
2634  const llvm::Type *Ty =
2635    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(GD),
2636                                   FPT->isVariadic());
2637  llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
2638
2639#ifndef NDEBUG
2640  const CGFunctionInfo &CallFnInfo =
2641    CGM.getTypes().getFunctionInfo(ResultType, CallArgs, FPT->getExtInfo());
2642  assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
2643         CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
2644         CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
2645  assert(similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
2646                 FnInfo.getReturnInfo(), FnInfo.getReturnType()));
2647  assert(CallFnInfo.arg_size() == FnInfo.arg_size());
2648  for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
2649    assert(similar(CallFnInfo.arg_begin()[i].info,
2650                   CallFnInfo.arg_begin()[i].type,
2651                   FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
2652#endif
2653
2654  // Determine whether we have a return value slot to use.
2655  ReturnValueSlot Slot;
2656  if (!ResultType->isVoidType() &&
2657      FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2658      hasAggregateLLVMType(CurFnInfo->getReturnType()))
2659    Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
2660
2661  // Now emit our call.
2662  RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
2663
2664  if (!Thunk.Return.isEmpty()) {
2665    // Emit the return adjustment.
2666    bool NullCheckValue = !ResultType->isReferenceType();
2667
2668    llvm::BasicBlock *AdjustNull = 0;
2669    llvm::BasicBlock *AdjustNotNull = 0;
2670    llvm::BasicBlock *AdjustEnd = 0;
2671
2672    llvm::Value *ReturnValue = RV.getScalarVal();
2673
2674    if (NullCheckValue) {
2675      AdjustNull = createBasicBlock("adjust.null");
2676      AdjustNotNull = createBasicBlock("adjust.notnull");
2677      AdjustEnd = createBasicBlock("adjust.end");
2678
2679      llvm::Value *IsNull = Builder.CreateIsNull(ReturnValue);
2680      Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
2681      EmitBlock(AdjustNotNull);
2682    }
2683
2684    ReturnValue = PerformTypeAdjustment(*this, ReturnValue,
2685                                        Thunk.Return.NonVirtual,
2686                                        Thunk.Return.VBaseOffsetOffset);
2687
2688    if (NullCheckValue) {
2689      Builder.CreateBr(AdjustEnd);
2690      EmitBlock(AdjustNull);
2691      Builder.CreateBr(AdjustEnd);
2692      EmitBlock(AdjustEnd);
2693
2694      llvm::PHINode *PHI = Builder.CreatePHI(ReturnValue->getType(), 2);
2695      PHI->addIncoming(ReturnValue, AdjustNotNull);
2696      PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
2697                       AdjustNull);
2698      ReturnValue = PHI;
2699    }
2700
2701    RV = RValue::get(ReturnValue);
2702  }
2703
2704  if (!ResultType->isVoidType() && Slot.isNull())
2705    CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
2706
2707  FinishFunction();
2708
2709  // Set the right linkage.
2710  CGM.setFunctionLinkage(MD, Fn);
2711
2712  // Set the right visibility.
2713  setThunkVisibility(CGM, MD, Thunk, Fn);
2714}
2715
2716void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
2717                               bool UseAvailableExternallyLinkage)
2718{
2719  const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(GD);
2720
2721  // FIXME: re-use FnInfo in this computation.
2722  llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
2723
2724  // Strip off a bitcast if we got one back.
2725  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2726    assert(CE->getOpcode() == llvm::Instruction::BitCast);
2727    Entry = CE->getOperand(0);
2728  }
2729
2730  // There's already a declaration with the same name, check if it has the same
2731  // type or if we need to replace it.
2732  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
2733      CGM.getTypes().GetFunctionTypeForVTable(GD)) {
2734    llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
2735
2736    // If the types mismatch then we have to rewrite the definition.
2737    assert(OldThunkFn->isDeclaration() &&
2738           "Shouldn't replace non-declaration");
2739
2740    // Remove the name from the old thunk function and get a new thunk.
2741    OldThunkFn->setName(llvm::StringRef());
2742    Entry = CGM.GetAddrOfThunk(GD, Thunk);
2743
2744    // If needed, replace the old thunk with a bitcast.
2745    if (!OldThunkFn->use_empty()) {
2746      llvm::Constant *NewPtrForOldDecl =
2747        llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
2748      OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
2749    }
2750
2751    // Remove the old thunk.
2752    OldThunkFn->eraseFromParent();
2753  }
2754
2755  llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
2756
2757  if (!ThunkFn->isDeclaration()) {
2758    if (UseAvailableExternallyLinkage) {
2759      // There is already a thunk emitted for this function, do nothing.
2760      return;
2761    }
2762
2763    // If a function has a body, it should have available_externally linkage.
2764    assert(ThunkFn->hasAvailableExternallyLinkage() &&
2765           "Function should have available_externally linkage!");
2766
2767    // Change the linkage.
2768    CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn);
2769    return;
2770  }
2771
2772  // Actually generate the thunk body.
2773  CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
2774
2775  if (UseAvailableExternallyLinkage)
2776    ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
2777}
2778
2779void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
2780                                                       const ThunkInfo &Thunk) {
2781  // We only want to do this when building with optimizations.
2782  if (!CGM.getCodeGenOpts().OptimizationLevel)
2783    return;
2784
2785  // We can't emit thunks for member functions with incomplete types.
2786  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2787  if (CGM.getTypes().VerifyFuncTypeComplete(MD->getType().getTypePtr()))
2788    return;
2789
2790  EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
2791}
2792
2793void CodeGenVTables::EmitThunks(GlobalDecl GD)
2794{
2795  const CXXMethodDecl *MD =
2796    cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
2797
2798  // We don't need to generate thunks for the base destructor.
2799  if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2800    return;
2801
2802  const CXXRecordDecl *RD = MD->getParent();
2803
2804  // Compute VTable related info for this class.
2805  ComputeVTableRelatedInformation(RD, false);
2806
2807  ThunksMapTy::const_iterator I = Thunks.find(MD);
2808  if (I == Thunks.end()) {
2809    // We did not find a thunk for this method.
2810    return;
2811  }
2812
2813  const ThunkInfoVectorTy &ThunkInfoVector = I->second;
2814  for (unsigned I = 0, E = ThunkInfoVector.size(); I != E; ++I)
2815    EmitThunk(GD, ThunkInfoVector[I], /*UseAvailableExternallyLinkage=*/false);
2816}
2817
2818void CodeGenVTables::ComputeVTableRelatedInformation(const CXXRecordDecl *RD,
2819                                                     bool RequireVTable) {
2820  VTableLayoutData &Entry = VTableLayoutMap[RD];
2821
2822  // We may need to generate a definition for this vtable.
2823  if (RequireVTable && !Entry.getInt()) {
2824    if (ShouldEmitVTableInThisTU(RD))
2825      CGM.DeferredVTables.push_back(RD);
2826
2827    Entry.setInt(true);
2828  }
2829
2830  // Check if we've computed this information before.
2831  if (Entry.getPointer())
2832    return;
2833
2834  VTableBuilder Builder(*this, RD, CharUnits::Zero(),
2835                        /*MostDerivedClassIsVirtual=*/0, RD);
2836
2837  // Add the VTable layout.
2838  uint64_t NumVTableComponents = Builder.getNumVTableComponents();
2839  // -fapple-kext adds an extra entry at end of vtbl.
2840  bool IsAppleKext = CGM.getContext().getLangOptions().AppleKext;
2841  if (IsAppleKext)
2842    NumVTableComponents += 1;
2843
2844  uint64_t *LayoutData = new uint64_t[NumVTableComponents + 1];
2845  if (IsAppleKext)
2846    LayoutData[NumVTableComponents] = 0;
2847  Entry.setPointer(LayoutData);
2848
2849  // Store the number of components.
2850  LayoutData[0] = NumVTableComponents;
2851
2852  // Store the components.
2853  std::copy(Builder.vtable_components_data_begin(),
2854            Builder.vtable_components_data_end(),
2855            &LayoutData[1]);
2856
2857  // Add the known thunks.
2858  Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2859
2860  // Add the thunks needed in this vtable.
2861  assert(!VTableThunksMap.count(RD) &&
2862         "Thunks already exists for this vtable!");
2863
2864  VTableThunksTy &VTableThunks = VTableThunksMap[RD];
2865  VTableThunks.append(Builder.vtable_thunks_begin(),
2866                      Builder.vtable_thunks_end());
2867
2868  // Sort them.
2869  std::sort(VTableThunks.begin(), VTableThunks.end());
2870
2871  // Add the address points.
2872  for (VTableBuilder::AddressPointsMapTy::const_iterator I =
2873       Builder.address_points_begin(), E = Builder.address_points_end();
2874       I != E; ++I) {
2875
2876    uint64_t &AddressPoint = AddressPoints[std::make_pair(RD, I->first)];
2877
2878    // Check if we already have the address points for this base.
2879    assert(!AddressPoint && "Address point already exists for this base!");
2880
2881    AddressPoint = I->second;
2882  }
2883
2884  // If we don't have the vbase information for this class, insert it.
2885  // getVirtualBaseOffsetOffset will compute it separately without computing
2886  // the rest of the vtable related information.
2887  if (!RD->getNumVBases())
2888    return;
2889
2890  const RecordType *VBaseRT =
2891    RD->vbases_begin()->getType()->getAs<RecordType>();
2892  const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2893
2894  if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2895    return;
2896
2897  for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2898       Builder.getVBaseOffsetOffsets().begin(),
2899       E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2900    // Insert all types.
2901    ClassPairTy ClassPair(RD, I->first);
2902
2903    VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2904  }
2905}
2906
2907llvm::Constant *
2908CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
2909                                        const uint64_t *Components,
2910                                        unsigned NumComponents,
2911                                        const VTableThunksTy &VTableThunks) {
2912  llvm::SmallVector<llvm::Constant *, 64> Inits;
2913
2914  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
2915
2916  const llvm::Type *PtrDiffTy =
2917    CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2918
2919  QualType ClassType = CGM.getContext().getTagDeclType(RD);
2920  llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
2921
2922  unsigned NextVTableThunkIndex = 0;
2923
2924  llvm::Constant* PureVirtualFn = 0;
2925
2926  for (unsigned I = 0; I != NumComponents; ++I) {
2927    VTableComponent Component =
2928      VTableComponent::getFromOpaqueInteger(Components[I]);
2929
2930    llvm::Constant *Init = 0;
2931
2932    switch (Component.getKind()) {
2933    case VTableComponent::CK_VCallOffset:
2934      Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVCallOffset());
2935      Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
2936      break;
2937    case VTableComponent::CK_VBaseOffset:
2938      Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVBaseOffset());
2939      Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
2940      break;
2941    case VTableComponent::CK_OffsetToTop:
2942      Init = llvm::ConstantInt::get(PtrDiffTy, Component.getOffsetToTop());
2943      Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
2944      break;
2945    case VTableComponent::CK_RTTI:
2946      Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
2947      break;
2948    case VTableComponent::CK_FunctionPointer:
2949    case VTableComponent::CK_CompleteDtorPointer:
2950    case VTableComponent::CK_DeletingDtorPointer: {
2951      GlobalDecl GD;
2952
2953      // Get the right global decl.
2954      switch (Component.getKind()) {
2955      default:
2956        llvm_unreachable("Unexpected vtable component kind");
2957      case VTableComponent::CK_FunctionPointer:
2958        GD = Component.getFunctionDecl();
2959        break;
2960      case VTableComponent::CK_CompleteDtorPointer:
2961        GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
2962        break;
2963      case VTableComponent::CK_DeletingDtorPointer:
2964        GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
2965        break;
2966      }
2967
2968      if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
2969        // We have a pure virtual member function.
2970        if (!PureVirtualFn) {
2971          const llvm::FunctionType *Ty =
2972            llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2973                                    /*isVarArg=*/false);
2974          PureVirtualFn =
2975            CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
2976          PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
2977                                                         Int8PtrTy);
2978        }
2979
2980        Init = PureVirtualFn;
2981      } else {
2982        // Check if we should use a thunk.
2983        if (NextVTableThunkIndex < VTableThunks.size() &&
2984            VTableThunks[NextVTableThunkIndex].first == I) {
2985          const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
2986
2987          Init = CGM.GetAddrOfThunk(GD, Thunk);
2988          MaybeEmitThunkAvailableExternally(GD, Thunk);
2989
2990          NextVTableThunkIndex++;
2991        } else {
2992          const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
2993
2994          Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
2995        }
2996
2997        Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
2998      }
2999      break;
3000    }
3001
3002    case VTableComponent::CK_UnusedFunctionPointer:
3003      Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
3004      break;
3005    };
3006
3007    Inits.push_back(Init);
3008  }
3009
3010  llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
3011  return llvm::ConstantArray::get(ArrayType, Inits.data(), Inits.size());
3012}
3013
3014llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
3015  llvm::SmallString<256> OutName;
3016  llvm::raw_svector_ostream Out(OutName);
3017  CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
3018  Out.flush();
3019  llvm::StringRef Name = OutName.str();
3020
3021  ComputeVTableRelatedInformation(RD, true);
3022
3023  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
3024  llvm::ArrayType *ArrayType =
3025    llvm::ArrayType::get(Int8PtrTy, getNumVTableComponents(RD));
3026
3027  llvm::GlobalVariable *GV =
3028    CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
3029                                          llvm::GlobalValue::ExternalLinkage);
3030  GV->setUnnamedAddr(true);
3031  return GV;
3032}
3033
3034void
3035CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
3036                                     llvm::GlobalVariable::LinkageTypes Linkage,
3037                                     const CXXRecordDecl *RD) {
3038  // Dump the vtable layout if necessary.
3039  if (CGM.getLangOptions().DumpVTableLayouts) {
3040    VTableBuilder Builder(*this, RD, CharUnits::Zero(),
3041                          /*MostDerivedClassIsVirtual=*/0, RD);
3042
3043    Builder.dumpLayout(llvm::errs());
3044  }
3045
3046  assert(VTableThunksMap.count(RD) &&
3047         "No thunk status for this record decl!");
3048
3049  const VTableThunksTy& Thunks = VTableThunksMap[RD];
3050
3051  // Create and set the initializer.
3052  llvm::Constant *Init =
3053    CreateVTableInitializer(RD, getVTableComponentsData(RD),
3054                            getNumVTableComponents(RD), Thunks);
3055  VTable->setInitializer(Init);
3056
3057  // Set the correct linkage.
3058  VTable->setLinkage(Linkage);
3059
3060  // Set the right visibility.
3061  CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
3062}
3063
3064llvm::GlobalVariable *
3065CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
3066                                      const BaseSubobject &Base,
3067                                      bool BaseIsVirtual,
3068                                   llvm::GlobalVariable::LinkageTypes Linkage,
3069                                      VTableAddressPointsMapTy& AddressPoints) {
3070  VTableBuilder Builder(*this, Base.getBase(),
3071                        Base.getBaseOffset(),
3072                        /*MostDerivedClassIsVirtual=*/BaseIsVirtual, RD);
3073
3074  // Dump the vtable layout if necessary.
3075  if (CGM.getLangOptions().DumpVTableLayouts)
3076    Builder.dumpLayout(llvm::errs());
3077
3078  // Add the address points.
3079  AddressPoints.insert(Builder.address_points_begin(),
3080                       Builder.address_points_end());
3081
3082  // Get the mangled construction vtable name.
3083  llvm::SmallString<256> OutName;
3084  llvm::raw_svector_ostream Out(OutName);
3085  CGM.getCXXABI().getMangleContext().
3086    mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
3087                        Out);
3088  Out.flush();
3089  llvm::StringRef Name = OutName.str();
3090
3091  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
3092  llvm::ArrayType *ArrayType =
3093    llvm::ArrayType::get(Int8PtrTy, Builder.getNumVTableComponents());
3094
3095  // Create the variable that will hold the construction vtable.
3096  llvm::GlobalVariable *VTable =
3097    CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
3098  CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
3099
3100  // V-tables are always unnamed_addr.
3101  VTable->setUnnamedAddr(true);
3102
3103  // Add the thunks.
3104  VTableThunksTy VTableThunks;
3105  VTableThunks.append(Builder.vtable_thunks_begin(),
3106                      Builder.vtable_thunks_end());
3107
3108  // Sort them.
3109  std::sort(VTableThunks.begin(), VTableThunks.end());
3110
3111  // Create and set the initializer.
3112  llvm::Constant *Init =
3113    CreateVTableInitializer(Base.getBase(),
3114                            Builder.vtable_components_data_begin(),
3115                            Builder.getNumVTableComponents(), VTableThunks);
3116  VTable->setInitializer(Init);
3117
3118  return VTable;
3119}
3120
3121void
3122CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
3123                                  const CXXRecordDecl *RD) {
3124  llvm::GlobalVariable *&VTable = VTables[RD];
3125  if (VTable) {
3126    assert(VTable->getInitializer() && "VTable doesn't have a definition!");
3127    return;
3128  }
3129
3130  VTable = GetAddrOfVTable(RD);
3131  EmitVTableDefinition(VTable, Linkage, RD);
3132
3133  if (RD->getNumVBases()) {
3134    llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
3135    EmitVTTDefinition(VTT, Linkage, RD);
3136  }
3137
3138  // If this is the magic class __cxxabiv1::__fundamental_type_info,
3139  // we will emit the typeinfo for the fundamental types. This is the
3140  // same behaviour as GCC.
3141  const DeclContext *DC = RD->getDeclContext();
3142  if (RD->getIdentifier() &&
3143      RD->getIdentifier()->isStr("__fundamental_type_info") &&
3144      isa<NamespaceDecl>(DC) &&
3145      cast<NamespaceDecl>(DC)->getIdentifier() &&
3146      cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
3147      DC->getParent()->isTranslationUnit())
3148    CGM.EmitFundamentalRTTIDescriptors();
3149}
3150