CGVTables.cpp revision fc72420a2245774b5a3f0cd0d7f7527f0f5c84db
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                               uint64_t RealBaseOffset);
747
748  /// AddVCallOffsets - Add vcall offsets for the given base subobject.
749  void AddVCallOffsets(BaseSubobject Base, uint64_t VBaseOffset);
750
751  /// AddVBaseOffsets - Add vbase offsets for the given class.
752  void AddVBaseOffsets(const CXXRecordDecl *Base, uint64_t OffsetInLayoutClass);
753
754  /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
755  /// bytes, relative to the vtable address point.
756  int64_t getCurrentOffsetOffset() const;
757
758public:
759  VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
760                             const CXXRecordDecl *LayoutClass,
761                             const FinalOverriders *Overriders,
762                             BaseSubobject Base, bool BaseIsVirtual,
763                             uint64_t OffsetInLayoutClass)
764    : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
765    Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
766
767    // Add vcall and vbase offsets.
768    AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
769  }
770
771  /// Methods for iterating over the components.
772  typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
773  const_iterator components_begin() const { return Components.rbegin(); }
774  const_iterator components_end() const { return Components.rend(); }
775
776  const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
777  const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
778    return VBaseOffsetOffsets;
779  }
780};
781
782void
783VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
784                                                    bool BaseIsVirtual,
785                                                    uint64_t RealBaseOffset) {
786  const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
787
788  // Itanium C++ ABI 2.5.2:
789  //   ..in classes sharing a virtual table with a primary base class, the vcall
790  //   and vbase offsets added by the derived class all come before the vcall
791  //   and vbase offsets required by the base class, so that the latter may be
792  //   laid out as required by the base class without regard to additions from
793  //   the derived class(es).
794
795  // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
796  // emit them for the primary base first).
797  if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
798    bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
799
800    CharUnits PrimaryBaseOffset;
801
802    // Get the base offset of the primary base.
803    if (PrimaryBaseIsVirtual) {
804      assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
805             "Primary vbase should have a zero offset!");
806
807      const ASTRecordLayout &MostDerivedClassLayout =
808        Context.getASTRecordLayout(MostDerivedClass);
809
810      PrimaryBaseOffset =
811        MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
812    } else {
813      assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
814             "Primary base should have a zero offset!");
815
816      PrimaryBaseOffset = Base.getBaseOffset();
817    }
818
819    AddVCallAndVBaseOffsets(
820      BaseSubobject(PrimaryBase,PrimaryBaseOffset),
821      PrimaryBaseIsVirtual, RealBaseOffset);
822  }
823
824  AddVBaseOffsets(Base.getBase(), RealBaseOffset);
825
826  // We only want to add vcall offsets for virtual bases.
827  if (BaseIsVirtual)
828    AddVCallOffsets(Base, RealBaseOffset);
829}
830
831int64_t VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
832  // OffsetIndex is the index of this vcall or vbase offset, relative to the
833  // vtable address point. (We subtract 3 to account for the information just
834  // above the address point, the RTTI info, the offset to top, and the
835  // vcall offset itself).
836  int64_t OffsetIndex = -(int64_t)(3 + Components.size());
837
838  // FIXME: We shouldn't use / 8 here.
839  int64_t OffsetOffset = OffsetIndex *
840    (int64_t)Context.Target.getPointerWidth(0) / 8;
841
842  return OffsetOffset;
843}
844
845void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
846                                                 uint64_t VBaseOffset) {
847  const CXXRecordDecl *RD = Base.getBase();
848  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
849
850  const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
851
852  // Handle the primary base first.
853  // We only want to add vcall offsets if the base is non-virtual; a virtual
854  // primary base will have its vcall and vbase offsets emitted already.
855  if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
856    // Get the base offset of the primary base.
857    assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
858           "Primary base should have a zero offset!");
859
860    AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
861                    VBaseOffset);
862  }
863
864  // Add the vcall offsets.
865  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
866       E = RD->method_end(); I != E; ++I) {
867    const CXXMethodDecl *MD = *I;
868
869    if (!MD->isVirtual())
870      continue;
871
872    int64_t OffsetOffset = getCurrentOffsetOffset();
873
874    // Don't add a vcall offset if we already have one for this member function
875    // signature.
876    if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
877      continue;
878
879    int64_t Offset = 0;
880
881    if (Overriders) {
882      // Get the final overrider.
883      FinalOverriders::OverriderInfo Overrider =
884        Overriders->getOverrider(MD, Base.getBaseOffset());
885
886      /// The vcall offset is the offset from the virtual base to the object
887      /// where the function was overridden.
888      // FIXME: We should not use / 8 here.
889      Offset = (int64_t)(Context.toBits(Overrider.Offset) - VBaseOffset) / 8;
890    }
891
892    Components.push_back(VTableComponent::MakeVCallOffset(Offset));
893  }
894
895  // And iterate over all non-virtual bases (ignoring the primary base).
896  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
897       E = RD->bases_end(); I != E; ++I) {
898
899    if (I->isVirtual())
900      continue;
901
902    const CXXRecordDecl *BaseDecl =
903      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
904    if (BaseDecl == PrimaryBase)
905      continue;
906
907    // Get the base offset of this base.
908    CharUnits BaseOffset = Base.getBaseOffset() +
909      Layout.getBaseClassOffset(BaseDecl);
910
911    AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
912                    VBaseOffset);
913  }
914}
915
916void VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
917                                                 uint64_t OffsetInLayoutClass) {
918  const ASTRecordLayout &LayoutClassLayout =
919    Context.getASTRecordLayout(LayoutClass);
920
921  // Add vbase offsets.
922  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
923       E = RD->bases_end(); I != E; ++I) {
924    const CXXRecordDecl *BaseDecl =
925      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
926
927    // Check if this is a virtual base that we haven't visited before.
928    if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
929      // FIXME: We shouldn't use / 8 here.
930      int64_t Offset =
931        (int64_t)(LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl) -
932                  OffsetInLayoutClass) / 8;
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(VTableComponent::MakeVBaseOffset(Offset));
942    }
943
944    // Check the base class looking for more vbase offsets.
945    AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
946  }
947}
948
949/// VTableBuilder - Class for building vtable layout information.
950class VTableBuilder {
951public:
952  /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
953  /// primary bases.
954  typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
955    PrimaryBasesSetVectorTy;
956
957  typedef llvm::DenseMap<const CXXRecordDecl *, int64_t>
958    VBaseOffsetOffsetsMapTy;
959
960  typedef llvm::DenseMap<BaseSubobject, uint64_t>
961    AddressPointsMapTy;
962
963private:
964  /// VTables - Global vtable information.
965  CodeGenVTables &VTables;
966
967  /// MostDerivedClass - The most derived class for which we're building this
968  /// vtable.
969  const CXXRecordDecl *MostDerivedClass;
970
971  /// MostDerivedClassOffset - If we're building a construction vtable, this
972  /// holds the offset from the layout class to the most derived class.
973  const uint64_t MostDerivedClassOffset;
974
975  /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
976  /// base. (This only makes sense when building a construction vtable).
977  bool MostDerivedClassIsVirtual;
978
979  /// LayoutClass - The class we're using for layout information. Will be
980  /// different than the most derived class if we're building a construction
981  /// vtable.
982  const CXXRecordDecl *LayoutClass;
983
984  /// Context - The ASTContext which we will use for layout information.
985  ASTContext &Context;
986
987  /// FinalOverriders - The final overriders of the most derived class.
988  const FinalOverriders Overriders;
989
990  /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
991  /// bases in this vtable.
992  llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
993
994  /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
995  /// the most derived class.
996  VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
997
998  /// Components - The components of the vtable being built.
999  llvm::SmallVector<VTableComponent, 64> Components;
1000
1001  /// AddressPoints - Address points for the vtable being built.
1002  AddressPointsMapTy AddressPoints;
1003
1004  /// MethodInfo - Contains information about a method in a vtable.
1005  /// (Used for computing 'this' pointer adjustment thunks.
1006  struct MethodInfo {
1007    /// BaseOffset - The base offset of this method.
1008    const CharUnits BaseOffset;
1009
1010    /// BaseOffsetInLayoutClass - The base offset in the layout class of this
1011    /// method.
1012    const CharUnits BaseOffsetInLayoutClass;
1013
1014    /// VTableIndex - The index in the vtable that this method has.
1015    /// (For destructors, this is the index of the complete destructor).
1016    const uint64_t VTableIndex;
1017
1018    MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
1019               uint64_t VTableIndex)
1020      : BaseOffset(BaseOffset),
1021      BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
1022      VTableIndex(VTableIndex) { }
1023
1024    MethodInfo()
1025      : BaseOffset(CharUnits::Zero()),
1026      BaseOffsetInLayoutClass(CharUnits::Zero()),
1027      VTableIndex(0) { }
1028  };
1029
1030  typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
1031
1032  /// MethodInfoMap - The information for all methods in the vtable we're
1033  /// currently building.
1034  MethodInfoMapTy MethodInfoMap;
1035
1036  typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
1037
1038  /// VTableThunks - The thunks by vtable index in the vtable currently being
1039  /// built.
1040  VTableThunksMapTy VTableThunks;
1041
1042  typedef llvm::SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
1043  typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
1044
1045  /// Thunks - A map that contains all the thunks needed for all methods in the
1046  /// most derived class for which the vtable is currently being built.
1047  ThunksMapTy Thunks;
1048
1049  /// AddThunk - Add a thunk for the given method.
1050  void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
1051
1052  /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
1053  /// part of the vtable we're currently building.
1054  void ComputeThisAdjustments();
1055
1056  typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1057
1058  /// PrimaryVirtualBases - All known virtual bases who are a primary base of
1059  /// some other base.
1060  VisitedVirtualBasesSetTy PrimaryVirtualBases;
1061
1062  /// ComputeReturnAdjustment - Compute the return adjustment given a return
1063  /// adjustment base offset.
1064  ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
1065
1066  /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
1067  /// the 'this' pointer from the base subobject to the derived subobject.
1068  BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1069                                             BaseSubobject Derived) const;
1070
1071  /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
1072  /// given virtual member function, its offset in the layout class and its
1073  /// final overrider.
1074  ThisAdjustment
1075  ComputeThisAdjustment(const CXXMethodDecl *MD,
1076                        CharUnits BaseOffsetInLayoutClass,
1077                        FinalOverriders::OverriderInfo Overrider);
1078
1079  /// AddMethod - Add a single virtual member function to the vtable
1080  /// components vector.
1081  void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
1082
1083  /// IsOverriderUsed - Returns whether the overrider will ever be used in this
1084  /// part of the vtable.
1085  ///
1086  /// Itanium C++ ABI 2.5.2:
1087  ///
1088  ///   struct A { virtual void f(); };
1089  ///   struct B : virtual public A { int i; };
1090  ///   struct C : virtual public A { int j; };
1091  ///   struct D : public B, public C {};
1092  ///
1093  ///   When B and C are declared, A is a primary base in each case, so although
1094  ///   vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
1095  ///   adjustment is required and no thunk is generated. However, inside D
1096  ///   objects, A is no longer a primary base of C, so if we allowed calls to
1097  ///   C::f() to use the copy of A's vtable in the C subobject, we would need
1098  ///   to adjust this from C* to B::A*, which would require a third-party
1099  ///   thunk. Since we require that a call to C::f() first convert to A*,
1100  ///   C-in-D's copy of A's vtable is never referenced, so this is not
1101  ///   necessary.
1102  bool IsOverriderUsed(const CXXMethodDecl *Overrider,
1103                       uint64_t BaseOffsetInLayoutClass,
1104                       const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1105                       uint64_t FirstBaseOffsetInLayoutClass) const;
1106
1107
1108  /// AddMethods - Add the methods of this base subobject and all its
1109  /// primary bases to the vtable components vector.
1110  void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
1111                  const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1112                  CharUnits FirstBaseOffsetInLayoutClass,
1113                  PrimaryBasesSetVectorTy &PrimaryBases);
1114
1115  // LayoutVTable - Layout the vtable for the given base class, including its
1116  // secondary vtables and any vtables for virtual bases.
1117  void LayoutVTable();
1118
1119  /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
1120  /// given base subobject, as well as all its secondary vtables.
1121  ///
1122  /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
1123  /// or a direct or indirect base of a virtual base.
1124  ///
1125  /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
1126  /// in the layout class.
1127  void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
1128                                        bool BaseIsMorallyVirtual,
1129                                        bool BaseIsVirtualInLayoutClass,
1130                                        uint64_t OffsetInLayoutClass);
1131
1132  /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
1133  /// subobject.
1134  ///
1135  /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
1136  /// or a direct or indirect base of a virtual base.
1137  void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
1138                              uint64_t OffsetInLayoutClass);
1139
1140  /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
1141  /// class hierarchy.
1142  void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1143                                    uint64_t OffsetInLayoutClass,
1144                                    VisitedVirtualBasesSetTy &VBases);
1145
1146  /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
1147  /// given base (excluding any primary bases).
1148  void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1149                                    VisitedVirtualBasesSetTy &VBases);
1150
1151  /// isBuildingConstructionVTable - Return whether this vtable builder is
1152  /// building a construction vtable.
1153  bool isBuildingConstructorVTable() const {
1154    return MostDerivedClass != LayoutClass;
1155  }
1156
1157public:
1158  VTableBuilder(CodeGenVTables &VTables, const CXXRecordDecl *MostDerivedClass,
1159                uint64_t MostDerivedClassOffset, bool MostDerivedClassIsVirtual,
1160                const CXXRecordDecl *LayoutClass)
1161    : VTables(VTables), MostDerivedClass(MostDerivedClass),
1162    MostDerivedClassOffset(MostDerivedClassOffset),
1163    MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
1164    LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
1165    Overriders(MostDerivedClass,
1166      MostDerivedClass->getASTContext().toCharUnitsFromBits(
1167        MostDerivedClassOffset),
1168      LayoutClass) {
1169
1170    LayoutVTable();
1171  }
1172
1173  ThunksMapTy::const_iterator thunks_begin() const {
1174    return Thunks.begin();
1175  }
1176
1177  ThunksMapTy::const_iterator thunks_end() const {
1178    return Thunks.end();
1179  }
1180
1181  const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
1182    return VBaseOffsetOffsets;
1183  }
1184
1185  /// getNumVTableComponents - Return the number of components in the vtable
1186  /// currently built.
1187  uint64_t getNumVTableComponents() const {
1188    return Components.size();
1189  }
1190
1191  const uint64_t *vtable_components_data_begin() const {
1192    return reinterpret_cast<const uint64_t *>(Components.begin());
1193  }
1194
1195  const uint64_t *vtable_components_data_end() const {
1196    return reinterpret_cast<const uint64_t *>(Components.end());
1197  }
1198
1199  AddressPointsMapTy::const_iterator address_points_begin() const {
1200    return AddressPoints.begin();
1201  }
1202
1203  AddressPointsMapTy::const_iterator address_points_end() const {
1204    return AddressPoints.end();
1205  }
1206
1207  VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
1208    return VTableThunks.begin();
1209  }
1210
1211  VTableThunksMapTy::const_iterator vtable_thunks_end() const {
1212    return VTableThunks.end();
1213  }
1214
1215  /// dumpLayout - Dump the vtable layout.
1216  void dumpLayout(llvm::raw_ostream&);
1217};
1218
1219void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
1220  assert(!isBuildingConstructorVTable() &&
1221         "Can't add thunks for construction vtable");
1222
1223  llvm::SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
1224
1225  // Check if we have this thunk already.
1226  if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1227      ThunksVector.end())
1228    return;
1229
1230  ThunksVector.push_back(Thunk);
1231}
1232
1233typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
1234
1235/// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
1236/// the overridden methods that the function decl overrides.
1237static void
1238ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
1239                            OverriddenMethodsSetTy& OverriddenMethods) {
1240  assert(MD->isVirtual() && "Method is not virtual!");
1241
1242  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1243       E = MD->end_overridden_methods(); I != E; ++I) {
1244    const CXXMethodDecl *OverriddenMD = *I;
1245
1246    OverriddenMethods.insert(OverriddenMD);
1247
1248    ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
1249  }
1250}
1251
1252void VTableBuilder::ComputeThisAdjustments() {
1253  // Now go through the method info map and see if any of the methods need
1254  // 'this' pointer adjustments.
1255  for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1256       E = MethodInfoMap.end(); I != E; ++I) {
1257    const CXXMethodDecl *MD = I->first;
1258    const MethodInfo &MethodInfo = I->second;
1259
1260    // Ignore adjustments for unused function pointers.
1261    uint64_t VTableIndex = MethodInfo.VTableIndex;
1262    if (Components[VTableIndex].getKind() ==
1263        VTableComponent::CK_UnusedFunctionPointer)
1264      continue;
1265
1266    // Get the final overrider for this method.
1267    FinalOverriders::OverriderInfo Overrider =
1268      Overriders.getOverrider(MD, MethodInfo.BaseOffset);
1269
1270    // Check if we need an adjustment at all.
1271    if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
1272      // When a return thunk is needed by a derived class that overrides a
1273      // virtual base, gcc uses a virtual 'this' adjustment as well.
1274      // While the thunk itself might be needed by vtables in subclasses or
1275      // in construction vtables, there doesn't seem to be a reason for using
1276      // the thunk in this vtable. Still, we do so to match gcc.
1277      if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
1278        continue;
1279    }
1280
1281    ThisAdjustment ThisAdjustment =
1282      ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1283
1284    if (ThisAdjustment.isEmpty())
1285      continue;
1286
1287    // Add it.
1288    VTableThunks[VTableIndex].This = ThisAdjustment;
1289
1290    if (isa<CXXDestructorDecl>(MD)) {
1291      // Add an adjustment for the deleting destructor as well.
1292      VTableThunks[VTableIndex + 1].This = ThisAdjustment;
1293    }
1294  }
1295
1296  /// Clear the method info map.
1297  MethodInfoMap.clear();
1298
1299  if (isBuildingConstructorVTable()) {
1300    // We don't need to store thunk information for construction vtables.
1301    return;
1302  }
1303
1304  for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
1305       E = VTableThunks.end(); I != E; ++I) {
1306    const VTableComponent &Component = Components[I->first];
1307    const ThunkInfo &Thunk = I->second;
1308    const CXXMethodDecl *MD;
1309
1310    switch (Component.getKind()) {
1311    default:
1312      llvm_unreachable("Unexpected vtable component kind!");
1313    case VTableComponent::CK_FunctionPointer:
1314      MD = Component.getFunctionDecl();
1315      break;
1316    case VTableComponent::CK_CompleteDtorPointer:
1317      MD = Component.getDestructorDecl();
1318      break;
1319    case VTableComponent::CK_DeletingDtorPointer:
1320      // We've already added the thunk when we saw the complete dtor pointer.
1321      continue;
1322    }
1323
1324    if (MD->getParent() == MostDerivedClass)
1325      AddThunk(MD, Thunk);
1326  }
1327}
1328
1329ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
1330  ReturnAdjustment Adjustment;
1331
1332  if (!Offset.isEmpty()) {
1333    if (Offset.VirtualBase) {
1334      // Get the virtual base offset offset.
1335      if (Offset.DerivedClass == MostDerivedClass) {
1336        // We can get the offset offset directly from our map.
1337        Adjustment.VBaseOffsetOffset =
1338          VBaseOffsetOffsets.lookup(Offset.VirtualBase);
1339      } else {
1340        Adjustment.VBaseOffsetOffset =
1341          VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1342                                             Offset.VirtualBase);
1343      }
1344    }
1345
1346    Adjustment.NonVirtual = Offset.NonVirtualOffset;
1347  }
1348
1349  return Adjustment;
1350}
1351
1352BaseOffset
1353VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1354                                               BaseSubobject Derived) const {
1355  const CXXRecordDecl *BaseRD = Base.getBase();
1356  const CXXRecordDecl *DerivedRD = Derived.getBase();
1357
1358  CXXBasePaths Paths(/*FindAmbiguities=*/true,
1359                     /*RecordPaths=*/true, /*DetectVirtual=*/true);
1360
1361  if (!const_cast<CXXRecordDecl *>(DerivedRD)->
1362      isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
1363    assert(false && "Class must be derived from the passed in base class!");
1364    return BaseOffset();
1365  }
1366
1367  // We have to go through all the paths, and see which one leads us to the
1368  // right base subobject.
1369  for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1370       I != E; ++I) {
1371    BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1372
1373    CharUnits OffsetToBaseSubobject =
1374      CharUnits::fromQuantity(Offset.NonVirtualOffset);
1375
1376    if (Offset.VirtualBase) {
1377      // If we have a virtual base class, the non-virtual offset is relative
1378      // to the virtual base class offset.
1379      const ASTRecordLayout &LayoutClassLayout =
1380        Context.getASTRecordLayout(LayoutClass);
1381
1382      /// Get the virtual base offset, relative to the most derived class
1383      /// layout.
1384      OffsetToBaseSubobject +=
1385        LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
1386    } else {
1387      // Otherwise, the non-virtual offset is relative to the derived class
1388      // offset.
1389      OffsetToBaseSubobject += Derived.getBaseOffset();
1390    }
1391
1392    // Check if this path gives us the right base subobject.
1393    if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1394      // Since we're going from the base class _to_ the derived class, we'll
1395      // invert the non-virtual offset here.
1396      Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1397      return Offset;
1398    }
1399  }
1400
1401  return BaseOffset();
1402}
1403
1404ThisAdjustment
1405VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1406                                     CharUnits BaseOffsetInLayoutClass,
1407                                     FinalOverriders::OverriderInfo Overrider) {
1408  // Ignore adjustments for pure virtual member functions.
1409  if (Overrider.Method->isPure())
1410    return ThisAdjustment();
1411
1412  BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1413                                        BaseOffsetInLayoutClass);
1414
1415  BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1416                                       Overrider.Offset);
1417
1418  // Compute the adjustment offset.
1419  BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1420                                                      OverriderBaseSubobject);
1421  if (Offset.isEmpty())
1422    return ThisAdjustment();
1423
1424  ThisAdjustment Adjustment;
1425
1426  if (Offset.VirtualBase) {
1427    // Get the vcall offset map for this virtual base.
1428    VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
1429
1430    if (VCallOffsets.empty()) {
1431      // We don't have vcall offsets for this virtual base, go ahead and
1432      // build them.
1433      VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1434                                         /*FinalOverriders=*/0,
1435                                         BaseSubobject(Offset.VirtualBase,
1436                                                       CharUnits::Zero()),
1437                                         /*BaseIsVirtual=*/true,
1438                                         /*OffsetInLayoutClass=*/0);
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                                                uint64_t 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  // FIXME: We should not use / 8 here.
1773  int64_t OffsetToTop = -(int64_t)(OffsetInLayoutClass -
1774                                   MostDerivedClassOffset) / 8;
1775  Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
1776
1777  // Next, add the RTTI.
1778  Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
1779
1780  uint64_t AddressPoint = Components.size();
1781
1782  // Now go through all virtual member functions and add them.
1783  PrimaryBasesSetVectorTy PrimaryBases;
1784  AddMethods(Base, Context.toCharUnitsFromBits(OffsetInLayoutClass),
1785             Base.getBase(), Context.toCharUnitsFromBits(OffsetInLayoutClass),
1786             PrimaryBases);
1787
1788  // Compute 'this' pointer adjustments.
1789  ComputeThisAdjustments();
1790
1791  // Add all address points.
1792  const CXXRecordDecl *RD = Base.getBase();
1793  while (true) {
1794    AddressPoints.insert(std::make_pair(
1795      BaseSubobject(RD, Context.toCharUnitsFromBits(OffsetInLayoutClass)),
1796      AddressPoint));
1797
1798    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1799    const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1800
1801    if (!PrimaryBase)
1802      break;
1803
1804    if (Layout.isPrimaryBaseVirtual()) {
1805      // Check if this virtual primary base is a primary base in the layout
1806      // class. If it's not, we don't want to add it.
1807      const ASTRecordLayout &LayoutClassLayout =
1808        Context.getASTRecordLayout(LayoutClass);
1809
1810      if (LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase) !=
1811          OffsetInLayoutClass) {
1812        // We don't want to add this class (or any of its primary bases).
1813        break;
1814      }
1815    }
1816
1817    RD = PrimaryBase;
1818  }
1819
1820  // Layout secondary vtables.
1821  LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
1822}
1823
1824void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
1825                                           bool BaseIsMorallyVirtual,
1826                                           uint64_t OffsetInLayoutClass) {
1827  // Itanium C++ ABI 2.5.2:
1828  //   Following the primary virtual table of a derived class are secondary
1829  //   virtual tables for each of its proper base classes, except any primary
1830  //   base(s) with which it shares its primary virtual table.
1831
1832  const CXXRecordDecl *RD = Base.getBase();
1833  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1834  const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1835
1836  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1837       E = RD->bases_end(); I != E; ++I) {
1838    // Ignore virtual bases, we'll emit them later.
1839    if (I->isVirtual())
1840      continue;
1841
1842    const CXXRecordDecl *BaseDecl =
1843      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1844
1845    // Ignore bases that don't have a vtable.
1846    if (!BaseDecl->isDynamicClass())
1847      continue;
1848
1849    if (isBuildingConstructorVTable()) {
1850      // Itanium C++ ABI 2.6.4:
1851      //   Some of the base class subobjects may not need construction virtual
1852      //   tables, which will therefore not be present in the construction
1853      //   virtual table group, even though the subobject virtual tables are
1854      //   present in the main virtual table group for the complete object.
1855      if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
1856        continue;
1857    }
1858
1859    // Get the base offset of this base.
1860    CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1861    CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1862
1863    CharUnits BaseOffsetInLayoutClass =
1864      Context.toCharUnitsFromBits(OffsetInLayoutClass) + RelativeBaseOffset;
1865
1866    // Don't emit a secondary vtable for a primary base. We might however want
1867    // to emit secondary vtables for other bases of this base.
1868    if (BaseDecl == PrimaryBase) {
1869      LayoutSecondaryVTables(
1870        BaseSubobject(BaseDecl, BaseOffset),
1871        BaseIsMorallyVirtual, Context.toBits(BaseOffsetInLayoutClass));
1872      continue;
1873    }
1874
1875    // Layout the primary vtable (and any secondary vtables) for this base.
1876    LayoutPrimaryAndSecondaryVTables(
1877      BaseSubobject(BaseDecl, BaseOffset),
1878      BaseIsMorallyVirtual,
1879      /*BaseIsVirtualInLayoutClass=*/false,
1880      Context.toBits(BaseOffsetInLayoutClass));
1881  }
1882}
1883
1884void
1885VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
1886                                            uint64_t OffsetInLayoutClass,
1887                                            VisitedVirtualBasesSetTy &VBases) {
1888  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1889
1890  // Check if this base has a primary base.
1891  if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
1892
1893    // Check if it's virtual.
1894    if (Layout.isPrimaryBaseVirtual()) {
1895      bool IsPrimaryVirtualBase = true;
1896
1897      if (isBuildingConstructorVTable()) {
1898        // Check if the base is actually a primary base in the class we use for
1899        // layout.
1900        const ASTRecordLayout &LayoutClassLayout =
1901          Context.getASTRecordLayout(LayoutClass);
1902
1903        uint64_t PrimaryBaseOffsetInLayoutClass =
1904          LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase);
1905
1906        // We know that the base is not a primary base in the layout class if
1907        // the base offsets are different.
1908        if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
1909          IsPrimaryVirtualBase = false;
1910      }
1911
1912      if (IsPrimaryVirtualBase)
1913        PrimaryVirtualBases.insert(PrimaryBase);
1914    }
1915  }
1916
1917  // Traverse bases, looking for more primary virtual bases.
1918  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1919       E = RD->bases_end(); I != E; ++I) {
1920    const CXXRecordDecl *BaseDecl =
1921      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1922
1923    uint64_t BaseOffsetInLayoutClass;
1924
1925    if (I->isVirtual()) {
1926      if (!VBases.insert(BaseDecl))
1927        continue;
1928
1929      const ASTRecordLayout &LayoutClassLayout =
1930        Context.getASTRecordLayout(LayoutClass);
1931
1932      BaseOffsetInLayoutClass =
1933        LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl);
1934    } else {
1935      BaseOffsetInLayoutClass =
1936        OffsetInLayoutClass + Layout.getBaseClassOffsetInBits(BaseDecl);
1937    }
1938
1939    DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
1940  }
1941}
1942
1943void
1944VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
1945                                            VisitedVirtualBasesSetTy &VBases) {
1946  // Itanium C++ ABI 2.5.2:
1947  //   Then come the virtual base virtual tables, also in inheritance graph
1948  //   order, and again excluding primary bases (which share virtual tables with
1949  //   the classes for which they are primary).
1950  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1951       E = RD->bases_end(); I != E; ++I) {
1952    const CXXRecordDecl *BaseDecl =
1953      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1954
1955    // Check if this base needs a vtable. (If it's virtual, not a primary base
1956    // of some other class, and we haven't visited it before).
1957    if (I->isVirtual() && BaseDecl->isDynamicClass() &&
1958        !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
1959      const ASTRecordLayout &MostDerivedClassLayout =
1960        Context.getASTRecordLayout(MostDerivedClass);
1961      uint64_t BaseOffset =
1962        MostDerivedClassLayout.getVBaseClassOffsetInBits(BaseDecl);
1963
1964      const ASTRecordLayout &LayoutClassLayout =
1965        Context.getASTRecordLayout(LayoutClass);
1966      uint64_t BaseOffsetInLayoutClass =
1967        LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl);
1968
1969      LayoutPrimaryAndSecondaryVTables(
1970        BaseSubobject(BaseDecl, Context.toCharUnitsFromBits(BaseOffset)),
1971        /*BaseIsMorallyVirtual=*/true,
1972        /*BaseIsVirtualInLayoutClass=*/true,
1973        BaseOffsetInLayoutClass);
1974    }
1975
1976    // We only need to check the base for virtual base vtables if it actually
1977    // has virtual bases.
1978    if (BaseDecl->getNumVBases())
1979      LayoutVTablesForVirtualBases(BaseDecl, VBases);
1980  }
1981}
1982
1983/// dumpLayout - Dump the vtable layout.
1984void VTableBuilder::dumpLayout(llvm::raw_ostream& Out) {
1985
1986  if (isBuildingConstructorVTable()) {
1987    Out << "Construction vtable for ('";
1988    Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
1989    // FIXME: Don't use / 8 .
1990    Out << MostDerivedClassOffset / 8 << ") in '";
1991    Out << LayoutClass->getQualifiedNameAsString();
1992  } else {
1993    Out << "Vtable for '";
1994    Out << MostDerivedClass->getQualifiedNameAsString();
1995  }
1996  Out << "' (" << Components.size() << " entries).\n";
1997
1998  // Iterate through the address points and insert them into a new map where
1999  // they are keyed by the index and not the base object.
2000  // Since an address point can be shared by multiple subobjects, we use an
2001  // STL multimap.
2002  std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
2003  for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
2004       E = AddressPoints.end(); I != E; ++I) {
2005    const BaseSubobject& Base = I->first;
2006    uint64_t Index = I->second;
2007
2008    AddressPointsByIndex.insert(std::make_pair(Index, Base));
2009  }
2010
2011  for (unsigned I = 0, E = Components.size(); I != E; ++I) {
2012    uint64_t Index = I;
2013
2014    Out << llvm::format("%4d | ", I);
2015
2016    const VTableComponent &Component = Components[I];
2017
2018    // Dump the component.
2019    switch (Component.getKind()) {
2020
2021    case VTableComponent::CK_VCallOffset:
2022      Out << "vcall_offset (" << Component.getVCallOffset() << ")";
2023      break;
2024
2025    case VTableComponent::CK_VBaseOffset:
2026      Out << "vbase_offset (" << Component.getVBaseOffset() << ")";
2027      break;
2028
2029    case VTableComponent::CK_OffsetToTop:
2030      Out << "offset_to_top (" << Component.getOffsetToTop() << ")";
2031      break;
2032
2033    case VTableComponent::CK_RTTI:
2034      Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
2035      break;
2036
2037    case VTableComponent::CK_FunctionPointer: {
2038      const CXXMethodDecl *MD = Component.getFunctionDecl();
2039
2040      std::string Str =
2041        PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2042                                    MD);
2043      Out << Str;
2044      if (MD->isPure())
2045        Out << " [pure]";
2046
2047      ThunkInfo Thunk = VTableThunks.lookup(I);
2048      if (!Thunk.isEmpty()) {
2049        // If this function pointer has a return adjustment, dump it.
2050        if (!Thunk.Return.isEmpty()) {
2051          Out << "\n       [return adjustment: ";
2052          Out << Thunk.Return.NonVirtual << " non-virtual";
2053
2054          if (Thunk.Return.VBaseOffsetOffset) {
2055            Out << ", " << Thunk.Return.VBaseOffsetOffset;
2056            Out << " vbase offset offset";
2057          }
2058
2059          Out << ']';
2060        }
2061
2062        // If this function pointer has a 'this' pointer adjustment, dump it.
2063        if (!Thunk.This.isEmpty()) {
2064          Out << "\n       [this adjustment: ";
2065          Out << Thunk.This.NonVirtual << " non-virtual";
2066
2067          if (Thunk.This.VCallOffsetOffset) {
2068            Out << ", " << Thunk.This.VCallOffsetOffset;
2069            Out << " vcall offset offset";
2070          }
2071
2072          Out << ']';
2073        }
2074      }
2075
2076      break;
2077    }
2078
2079    case VTableComponent::CK_CompleteDtorPointer:
2080    case VTableComponent::CK_DeletingDtorPointer: {
2081      bool IsComplete =
2082        Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
2083
2084      const CXXDestructorDecl *DD = Component.getDestructorDecl();
2085
2086      Out << DD->getQualifiedNameAsString();
2087      if (IsComplete)
2088        Out << "() [complete]";
2089      else
2090        Out << "() [deleting]";
2091
2092      if (DD->isPure())
2093        Out << " [pure]";
2094
2095      ThunkInfo Thunk = VTableThunks.lookup(I);
2096      if (!Thunk.isEmpty()) {
2097        // If this destructor has a 'this' pointer adjustment, dump it.
2098        if (!Thunk.This.isEmpty()) {
2099          Out << "\n       [this adjustment: ";
2100          Out << Thunk.This.NonVirtual << " non-virtual";
2101
2102          if (Thunk.This.VCallOffsetOffset) {
2103            Out << ", " << Thunk.This.VCallOffsetOffset;
2104            Out << " vcall offset offset";
2105          }
2106
2107          Out << ']';
2108        }
2109      }
2110
2111      break;
2112    }
2113
2114    case VTableComponent::CK_UnusedFunctionPointer: {
2115      const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2116
2117      std::string Str =
2118        PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2119                                    MD);
2120      Out << "[unused] " << Str;
2121      if (MD->isPure())
2122        Out << " [pure]";
2123    }
2124
2125    }
2126
2127    Out << '\n';
2128
2129    // Dump the next address point.
2130    uint64_t NextIndex = Index + 1;
2131    if (AddressPointsByIndex.count(NextIndex)) {
2132      if (AddressPointsByIndex.count(NextIndex) == 1) {
2133        const BaseSubobject &Base =
2134          AddressPointsByIndex.find(NextIndex)->second;
2135
2136        Out << "       -- (" << Base.getBase()->getQualifiedNameAsString();
2137        Out << ", " << Base.getBaseOffset().getQuantity();
2138        Out << ") vtable address --\n";
2139      } else {
2140        CharUnits BaseOffset =
2141          AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2142
2143        // We store the class names in a set to get a stable order.
2144        std::set<std::string> ClassNames;
2145        for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2146             AddressPointsByIndex.lower_bound(NextIndex), E =
2147             AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2148          assert(I->second.getBaseOffset() == BaseOffset &&
2149                 "Invalid base offset!");
2150          const CXXRecordDecl *RD = I->second.getBase();
2151          ClassNames.insert(RD->getQualifiedNameAsString());
2152        }
2153
2154        for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2155             E = ClassNames.end(); I != E; ++I) {
2156          Out << "       -- (" << *I;
2157          Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
2158        }
2159      }
2160    }
2161  }
2162
2163  Out << '\n';
2164
2165  if (isBuildingConstructorVTable())
2166    return;
2167
2168  if (MostDerivedClass->getNumVBases()) {
2169    // We store the virtual base class names and their offsets in a map to get
2170    // a stable order.
2171
2172    std::map<std::string, int64_t> ClassNamesAndOffsets;
2173    for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2174         E = VBaseOffsetOffsets.end(); I != E; ++I) {
2175      std::string ClassName = I->first->getQualifiedNameAsString();
2176      int64_t OffsetOffset = I->second;
2177      ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
2178    }
2179
2180    Out << "Virtual base offset offsets for '";
2181    Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2182    Out << ClassNamesAndOffsets.size();
2183    Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
2184
2185    for (std::map<std::string, int64_t>::const_iterator I =
2186         ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2187         I != E; ++I)
2188      Out << "   " << I->first << " | " << I->second << '\n';
2189
2190    Out << "\n";
2191  }
2192
2193  if (!Thunks.empty()) {
2194    // We store the method names in a map to get a stable order.
2195    std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2196
2197    for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
2198         I != E; ++I) {
2199      const CXXMethodDecl *MD = I->first;
2200      std::string MethodName =
2201        PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2202                                    MD);
2203
2204      MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2205    }
2206
2207    for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2208         MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2209         I != E; ++I) {
2210      const std::string &MethodName = I->first;
2211      const CXXMethodDecl *MD = I->second;
2212
2213      ThunkInfoVectorTy ThunksVector = Thunks[MD];
2214      std::sort(ThunksVector.begin(), ThunksVector.end());
2215
2216      Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2217      Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2218
2219      for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2220        const ThunkInfo &Thunk = ThunksVector[I];
2221
2222        Out << llvm::format("%4d | ", I);
2223
2224        // If this function pointer has a return pointer adjustment, dump it.
2225        if (!Thunk.Return.isEmpty()) {
2226          Out << "return adjustment: " << Thunk.This.NonVirtual;
2227          Out << " non-virtual";
2228          if (Thunk.Return.VBaseOffsetOffset) {
2229            Out << ", " << Thunk.Return.VBaseOffsetOffset;
2230            Out << " vbase offset offset";
2231          }
2232
2233          if (!Thunk.This.isEmpty())
2234            Out << "\n       ";
2235        }
2236
2237        // If this function pointer has a 'this' pointer adjustment, dump it.
2238        if (!Thunk.This.isEmpty()) {
2239          Out << "this adjustment: ";
2240          Out << Thunk.This.NonVirtual << " non-virtual";
2241
2242          if (Thunk.This.VCallOffsetOffset) {
2243            Out << ", " << Thunk.This.VCallOffsetOffset;
2244            Out << " vcall offset offset";
2245          }
2246        }
2247
2248        Out << '\n';
2249      }
2250
2251      Out << '\n';
2252
2253    }
2254  }
2255}
2256
2257}
2258
2259static void
2260CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
2261                    VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
2262  while (RD) {
2263    const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2264    const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2265    if (PrimaryBase)
2266      PrimaryBases.insert(PrimaryBase);
2267
2268    RD = PrimaryBase;
2269  }
2270}
2271
2272void CodeGenVTables::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
2273
2274  // Itanium C++ ABI 2.5.2:
2275  //   The order of the virtual function pointers in a virtual table is the
2276  //   order of declaration of the corresponding member functions in the class.
2277  //
2278  //   There is an entry for any virtual function declared in a class,
2279  //   whether it is a new function or overrides a base class function,
2280  //   unless it overrides a function from the primary base, and conversion
2281  //   between their return types does not require an adjustment.
2282
2283  int64_t CurrentIndex = 0;
2284
2285  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2286  const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2287
2288  if (PrimaryBase) {
2289    assert(PrimaryBase->isDefinition() &&
2290           "Should have the definition decl of the primary base!");
2291
2292    // Since the record decl shares its vtable pointer with the primary base
2293    // we need to start counting at the end of the primary base's vtable.
2294    CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
2295  }
2296
2297  // Collect all the primary bases, so we can check whether methods override
2298  // a method from the base.
2299  VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
2300  CollectPrimaryBases(RD, CGM.getContext(), PrimaryBases);
2301
2302  const CXXDestructorDecl *ImplicitVirtualDtor = 0;
2303
2304  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2305       e = RD->method_end(); i != e; ++i) {
2306    const CXXMethodDecl *MD = *i;
2307
2308    // We only want virtual methods.
2309    if (!MD->isVirtual())
2310      continue;
2311
2312    // Check if this method overrides a method in the primary base.
2313    if (const CXXMethodDecl *OverriddenMD =
2314          FindNearestOverriddenMethod(MD, PrimaryBases)) {
2315      // Check if converting from the return type of the method to the
2316      // return type of the overridden method requires conversion.
2317      if (ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD,
2318                                            OverriddenMD).isEmpty()) {
2319        // This index is shared between the index in the vtable of the primary
2320        // base class.
2321        if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2322          const CXXDestructorDecl *OverriddenDD =
2323            cast<CXXDestructorDecl>(OverriddenMD);
2324
2325          // Add both the complete and deleting entries.
2326          MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
2327            getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
2328          MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
2329            getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
2330        } else {
2331          MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
2332        }
2333
2334        // We don't need to add an entry for this method.
2335        continue;
2336      }
2337    }
2338
2339    if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2340      if (MD->isImplicit()) {
2341        assert(!ImplicitVirtualDtor &&
2342               "Did already see an implicit virtual dtor!");
2343        ImplicitVirtualDtor = DD;
2344        continue;
2345      }
2346
2347      // Add the complete dtor.
2348      MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
2349
2350      // Add the deleting dtor.
2351      MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
2352    } else {
2353      // Add the entry.
2354      MethodVTableIndices[MD] = CurrentIndex++;
2355    }
2356  }
2357
2358  if (ImplicitVirtualDtor) {
2359    // Itanium C++ ABI 2.5.2:
2360    //   If a class has an implicitly-defined virtual destructor,
2361    //   its entries come after the declared virtual function pointers.
2362
2363    // Add the complete dtor.
2364    MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
2365      CurrentIndex++;
2366
2367    // Add the deleting dtor.
2368    MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
2369      CurrentIndex++;
2370  }
2371
2372  NumVirtualFunctionPointers[RD] = CurrentIndex;
2373}
2374
2375bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) {
2376  assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
2377
2378  TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2379  if (TSK == TSK_ExplicitInstantiationDeclaration)
2380    return false;
2381
2382  const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
2383  if (!KeyFunction)
2384    return true;
2385
2386  // Itanium C++ ABI, 5.2.6 Instantiated Templates:
2387  //    An instantiation of a class template requires:
2388  //        - In the object where instantiated, the virtual table...
2389  if (TSK == TSK_ImplicitInstantiation ||
2390      TSK == TSK_ExplicitInstantiationDefinition)
2391    return true;
2392
2393  // If we're building with optimization, we always emit VTables since that
2394  // allows for virtual function calls to be devirtualized.
2395  // (We don't want to do this in -fapple-kext mode however).
2396  if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOptions().AppleKext)
2397    return true;
2398
2399  return KeyFunction->hasBody();
2400}
2401
2402uint64_t CodeGenVTables::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
2403  llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2404    NumVirtualFunctionPointers.find(RD);
2405  if (I != NumVirtualFunctionPointers.end())
2406    return I->second;
2407
2408  ComputeMethodVTableIndices(RD);
2409
2410  I = NumVirtualFunctionPointers.find(RD);
2411  assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2412  return I->second;
2413}
2414
2415uint64_t CodeGenVTables::getMethodVTableIndex(GlobalDecl GD) {
2416  MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
2417  if (I != MethodVTableIndices.end())
2418    return I->second;
2419
2420  const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
2421
2422  ComputeMethodVTableIndices(RD);
2423
2424  I = MethodVTableIndices.find(GD);
2425  assert(I != MethodVTableIndices.end() && "Did not find index!");
2426  return I->second;
2427}
2428
2429int64_t CodeGenVTables::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
2430                                                   const CXXRecordDecl *VBase) {
2431  ClassPairTy ClassPair(RD, VBase);
2432
2433  VirtualBaseClassOffsetOffsetsMapTy::iterator I =
2434    VirtualBaseClassOffsetOffsets.find(ClassPair);
2435  if (I != VirtualBaseClassOffsetOffsets.end())
2436    return I->second;
2437
2438  VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
2439                                     BaseSubobject(RD, CharUnits::Zero()),
2440                                     /*BaseIsVirtual=*/false,
2441                                     /*OffsetInLayoutClass=*/0);
2442
2443  for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2444       Builder.getVBaseOffsetOffsets().begin(),
2445       E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2446    // Insert all types.
2447    ClassPairTy ClassPair(RD, I->first);
2448
2449    VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2450  }
2451
2452  I = VirtualBaseClassOffsetOffsets.find(ClassPair);
2453  assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
2454
2455  return I->second;
2456}
2457
2458uint64_t
2459CodeGenVTables::getAddressPoint(BaseSubobject Base, const CXXRecordDecl *RD) {
2460  assert(AddressPoints.count(std::make_pair(RD, Base)) &&
2461         "Did not find address point!");
2462
2463  uint64_t AddressPoint = AddressPoints.lookup(std::make_pair(RD, Base));
2464  assert(AddressPoint && "Address point must not be zero!");
2465
2466  return AddressPoint;
2467}
2468
2469llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
2470                                              const ThunkInfo &Thunk) {
2471  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2472
2473  // Compute the mangled name.
2474  llvm::SmallString<256> Name;
2475  llvm::raw_svector_ostream Out(Name);
2476  if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
2477    getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
2478                                                      Thunk.This, Out);
2479  else
2480    getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
2481  Out.flush();
2482
2483  const llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
2484  return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
2485}
2486
2487static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
2488                                          llvm::Value *Ptr,
2489                                          int64_t NonVirtualAdjustment,
2490                                          int64_t VirtualAdjustment) {
2491  if (!NonVirtualAdjustment && !VirtualAdjustment)
2492    return Ptr;
2493
2494  const llvm::Type *Int8PtrTy =
2495    llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
2496
2497  llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
2498
2499  if (NonVirtualAdjustment) {
2500    // Do the non-virtual adjustment.
2501    V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
2502  }
2503
2504  if (VirtualAdjustment) {
2505    const llvm::Type *PtrDiffTy =
2506      CGF.ConvertType(CGF.getContext().getPointerDiffType());
2507
2508    // Do the virtual adjustment.
2509    llvm::Value *VTablePtrPtr =
2510      CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
2511
2512    llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
2513
2514    llvm::Value *OffsetPtr =
2515      CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
2516
2517    OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
2518
2519    // Load the adjustment offset from the vtable.
2520    llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
2521
2522    // Adjust our pointer.
2523    V = CGF.Builder.CreateInBoundsGEP(V, Offset);
2524  }
2525
2526  // Cast back to the original type.
2527  return CGF.Builder.CreateBitCast(V, Ptr->getType());
2528}
2529
2530static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
2531                               const ThunkInfo &Thunk, llvm::Function *Fn) {
2532  CGM.setGlobalVisibility(Fn, MD);
2533
2534  if (!CGM.getCodeGenOpts().HiddenWeakVTables)
2535    return;
2536
2537  // If the thunk has weak/linkonce linkage, but the function must be
2538  // emitted in every translation unit that references it, then we can
2539  // emit its thunks with hidden visibility, since its thunks must be
2540  // emitted when the function is.
2541
2542  // This follows CodeGenModule::setTypeVisibility; see the comments
2543  // there for explanation.
2544
2545  if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
2546       Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
2547      Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
2548    return;
2549
2550  if (MD->getExplicitVisibility())
2551    return;
2552
2553  switch (MD->getTemplateSpecializationKind()) {
2554  case TSK_ExplicitInstantiationDefinition:
2555  case TSK_ExplicitInstantiationDeclaration:
2556    return;
2557
2558  case TSK_Undeclared:
2559    break;
2560
2561  case TSK_ExplicitSpecialization:
2562  case TSK_ImplicitInstantiation:
2563    if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables)
2564      return;
2565    break;
2566  }
2567
2568  // If there's an explicit definition, and that definition is
2569  // out-of-line, then we can't assume that all users will have a
2570  // definition to emit.
2571  const FunctionDecl *Def = 0;
2572  if (MD->hasBody(Def) && Def->isOutOfLine())
2573    return;
2574
2575  Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
2576}
2577
2578#ifndef NDEBUG
2579static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
2580                    const ABIArgInfo &infoR, CanQualType typeR) {
2581  return (infoL.getKind() == infoR.getKind() &&
2582          (typeL == typeR ||
2583           (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
2584           (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
2585}
2586#endif
2587
2588void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
2589                                    const CGFunctionInfo &FnInfo,
2590                                    GlobalDecl GD, const ThunkInfo &Thunk) {
2591  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2592  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
2593  QualType ResultType = FPT->getResultType();
2594  QualType ThisType = MD->getThisType(getContext());
2595
2596  FunctionArgList FunctionArgs;
2597
2598  // FIXME: It would be nice if more of this code could be shared with
2599  // CodeGenFunction::GenerateCode.
2600
2601  // Create the implicit 'this' parameter declaration.
2602  CurGD = GD;
2603  CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
2604
2605  // Add the rest of the parameters.
2606  for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2607       E = MD->param_end(); I != E; ++I) {
2608    ParmVarDecl *Param = *I;
2609
2610    FunctionArgs.push_back(Param);
2611  }
2612
2613  StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
2614                SourceLocation());
2615
2616  CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2617
2618  // Adjust the 'this' pointer if necessary.
2619  llvm::Value *AdjustedThisPtr =
2620    PerformTypeAdjustment(*this, LoadCXXThis(),
2621                          Thunk.This.NonVirtual,
2622                          Thunk.This.VCallOffsetOffset);
2623
2624  CallArgList CallArgs;
2625
2626  // Add our adjusted 'this' pointer.
2627  CallArgs.push_back(std::make_pair(RValue::get(AdjustedThisPtr), ThisType));
2628
2629  // Add the rest of the parameters.
2630  for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2631       E = MD->param_end(); I != E; ++I) {
2632    ParmVarDecl *param = *I;
2633    EmitDelegateCallArg(CallArgs, param);
2634  }
2635
2636  // Get our callee.
2637  const llvm::Type *Ty =
2638    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(GD),
2639                                   FPT->isVariadic());
2640  llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
2641
2642#ifndef NDEBUG
2643  const CGFunctionInfo &CallFnInfo =
2644    CGM.getTypes().getFunctionInfo(ResultType, CallArgs, FPT->getExtInfo());
2645  assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
2646         CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
2647         CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
2648  assert(similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
2649                 FnInfo.getReturnInfo(), FnInfo.getReturnType()));
2650  assert(CallFnInfo.arg_size() == FnInfo.arg_size());
2651  for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
2652    assert(similar(CallFnInfo.arg_begin()[i].info,
2653                   CallFnInfo.arg_begin()[i].type,
2654                   FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
2655#endif
2656
2657  // Determine whether we have a return value slot to use.
2658  ReturnValueSlot Slot;
2659  if (!ResultType->isVoidType() &&
2660      FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2661      hasAggregateLLVMType(CurFnInfo->getReturnType()))
2662    Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
2663
2664  // Now emit our call.
2665  RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
2666
2667  if (!Thunk.Return.isEmpty()) {
2668    // Emit the return adjustment.
2669    bool NullCheckValue = !ResultType->isReferenceType();
2670
2671    llvm::BasicBlock *AdjustNull = 0;
2672    llvm::BasicBlock *AdjustNotNull = 0;
2673    llvm::BasicBlock *AdjustEnd = 0;
2674
2675    llvm::Value *ReturnValue = RV.getScalarVal();
2676
2677    if (NullCheckValue) {
2678      AdjustNull = createBasicBlock("adjust.null");
2679      AdjustNotNull = createBasicBlock("adjust.notnull");
2680      AdjustEnd = createBasicBlock("adjust.end");
2681
2682      llvm::Value *IsNull = Builder.CreateIsNull(ReturnValue);
2683      Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
2684      EmitBlock(AdjustNotNull);
2685    }
2686
2687    ReturnValue = PerformTypeAdjustment(*this, ReturnValue,
2688                                        Thunk.Return.NonVirtual,
2689                                        Thunk.Return.VBaseOffsetOffset);
2690
2691    if (NullCheckValue) {
2692      Builder.CreateBr(AdjustEnd);
2693      EmitBlock(AdjustNull);
2694      Builder.CreateBr(AdjustEnd);
2695      EmitBlock(AdjustEnd);
2696
2697      llvm::PHINode *PHI = Builder.CreatePHI(ReturnValue->getType());
2698      PHI->reserveOperandSpace(2);
2699      PHI->addIncoming(ReturnValue, AdjustNotNull);
2700      PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
2701                       AdjustNull);
2702      ReturnValue = PHI;
2703    }
2704
2705    RV = RValue::get(ReturnValue);
2706  }
2707
2708  if (!ResultType->isVoidType() && Slot.isNull())
2709    CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
2710
2711  FinishFunction();
2712
2713  // Set the right linkage.
2714  CGM.setFunctionLinkage(MD, Fn);
2715
2716  // Set the right visibility.
2717  setThunkVisibility(CGM, MD, Thunk, Fn);
2718}
2719
2720void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
2721                               bool UseAvailableExternallyLinkage)
2722{
2723  const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(GD);
2724
2725  // FIXME: re-use FnInfo in this computation.
2726  llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
2727
2728  // Strip off a bitcast if we got one back.
2729  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2730    assert(CE->getOpcode() == llvm::Instruction::BitCast);
2731    Entry = CE->getOperand(0);
2732  }
2733
2734  // There's already a declaration with the same name, check if it has the same
2735  // type or if we need to replace it.
2736  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
2737      CGM.getTypes().GetFunctionTypeForVTable(GD)) {
2738    llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
2739
2740    // If the types mismatch then we have to rewrite the definition.
2741    assert(OldThunkFn->isDeclaration() &&
2742           "Shouldn't replace non-declaration");
2743
2744    // Remove the name from the old thunk function and get a new thunk.
2745    OldThunkFn->setName(llvm::StringRef());
2746    Entry = CGM.GetAddrOfThunk(GD, Thunk);
2747
2748    // If needed, replace the old thunk with a bitcast.
2749    if (!OldThunkFn->use_empty()) {
2750      llvm::Constant *NewPtrForOldDecl =
2751        llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
2752      OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
2753    }
2754
2755    // Remove the old thunk.
2756    OldThunkFn->eraseFromParent();
2757  }
2758
2759  llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
2760
2761  if (!ThunkFn->isDeclaration()) {
2762    if (UseAvailableExternallyLinkage) {
2763      // There is already a thunk emitted for this function, do nothing.
2764      return;
2765    }
2766
2767    // If a function has a body, it should have available_externally linkage.
2768    assert(ThunkFn->hasAvailableExternallyLinkage() &&
2769           "Function should have available_externally linkage!");
2770
2771    // Change the linkage.
2772    CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn);
2773    return;
2774  }
2775
2776  // Actually generate the thunk body.
2777  CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
2778
2779  if (UseAvailableExternallyLinkage)
2780    ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
2781}
2782
2783void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
2784                                                       const ThunkInfo &Thunk) {
2785  // We only want to do this when building with optimizations.
2786  if (!CGM.getCodeGenOpts().OptimizationLevel)
2787    return;
2788
2789  // We can't emit thunks for member functions with incomplete types.
2790  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2791  if (CGM.getTypes().VerifyFuncTypeComplete(MD->getType().getTypePtr()))
2792    return;
2793
2794  EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
2795}
2796
2797void CodeGenVTables::EmitThunks(GlobalDecl GD)
2798{
2799  const CXXMethodDecl *MD =
2800    cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
2801
2802  // We don't need to generate thunks for the base destructor.
2803  if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2804    return;
2805
2806  const CXXRecordDecl *RD = MD->getParent();
2807
2808  // Compute VTable related info for this class.
2809  ComputeVTableRelatedInformation(RD, false);
2810
2811  ThunksMapTy::const_iterator I = Thunks.find(MD);
2812  if (I == Thunks.end()) {
2813    // We did not find a thunk for this method.
2814    return;
2815  }
2816
2817  const ThunkInfoVectorTy &ThunkInfoVector = I->second;
2818  for (unsigned I = 0, E = ThunkInfoVector.size(); I != E; ++I)
2819    EmitThunk(GD, ThunkInfoVector[I], /*UseAvailableExternallyLinkage=*/false);
2820}
2821
2822void CodeGenVTables::ComputeVTableRelatedInformation(const CXXRecordDecl *RD,
2823                                                     bool RequireVTable) {
2824  VTableLayoutData &Entry = VTableLayoutMap[RD];
2825
2826  // We may need to generate a definition for this vtable.
2827  if (RequireVTable && !Entry.getInt()) {
2828    if (ShouldEmitVTableInThisTU(RD))
2829      CGM.DeferredVTables.push_back(RD);
2830
2831    Entry.setInt(true);
2832  }
2833
2834  // Check if we've computed this information before.
2835  if (Entry.getPointer())
2836    return;
2837
2838  VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
2839
2840  // Add the VTable layout.
2841  uint64_t NumVTableComponents = Builder.getNumVTableComponents();
2842  // -fapple-kext adds an extra entry at end of vtbl.
2843  bool IsAppleKext = CGM.getContext().getLangOptions().AppleKext;
2844  if (IsAppleKext)
2845    NumVTableComponents += 1;
2846
2847  uint64_t *LayoutData = new uint64_t[NumVTableComponents + 1];
2848  if (IsAppleKext)
2849    LayoutData[NumVTableComponents] = 0;
2850  Entry.setPointer(LayoutData);
2851
2852  // Store the number of components.
2853  LayoutData[0] = NumVTableComponents;
2854
2855  // Store the components.
2856  std::copy(Builder.vtable_components_data_begin(),
2857            Builder.vtable_components_data_end(),
2858            &LayoutData[1]);
2859
2860  // Add the known thunks.
2861  Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
2862
2863  // Add the thunks needed in this vtable.
2864  assert(!VTableThunksMap.count(RD) &&
2865         "Thunks already exists for this vtable!");
2866
2867  VTableThunksTy &VTableThunks = VTableThunksMap[RD];
2868  VTableThunks.append(Builder.vtable_thunks_begin(),
2869                      Builder.vtable_thunks_end());
2870
2871  // Sort them.
2872  std::sort(VTableThunks.begin(), VTableThunks.end());
2873
2874  // Add the address points.
2875  for (VTableBuilder::AddressPointsMapTy::const_iterator I =
2876       Builder.address_points_begin(), E = Builder.address_points_end();
2877       I != E; ++I) {
2878
2879    uint64_t &AddressPoint = AddressPoints[std::make_pair(RD, I->first)];
2880
2881    // Check if we already have the address points for this base.
2882    assert(!AddressPoint && "Address point already exists for this base!");
2883
2884    AddressPoint = I->second;
2885  }
2886
2887  // If we don't have the vbase information for this class, insert it.
2888  // getVirtualBaseOffsetOffset will compute it separately without computing
2889  // the rest of the vtable related information.
2890  if (!RD->getNumVBases())
2891    return;
2892
2893  const RecordType *VBaseRT =
2894    RD->vbases_begin()->getType()->getAs<RecordType>();
2895  const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
2896
2897  if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
2898    return;
2899
2900  for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
2901       Builder.getVBaseOffsetOffsets().begin(),
2902       E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
2903    // Insert all types.
2904    ClassPairTy ClassPair(RD, I->first);
2905
2906    VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
2907  }
2908}
2909
2910llvm::Constant *
2911CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
2912                                        const uint64_t *Components,
2913                                        unsigned NumComponents,
2914                                        const VTableThunksTy &VTableThunks) {
2915  llvm::SmallVector<llvm::Constant *, 64> Inits;
2916
2917  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
2918
2919  const llvm::Type *PtrDiffTy =
2920    CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2921
2922  QualType ClassType = CGM.getContext().getTagDeclType(RD);
2923  llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
2924
2925  unsigned NextVTableThunkIndex = 0;
2926
2927  llvm::Constant* PureVirtualFn = 0;
2928
2929  for (unsigned I = 0; I != NumComponents; ++I) {
2930    VTableComponent Component =
2931      VTableComponent::getFromOpaqueInteger(Components[I]);
2932
2933    llvm::Constant *Init = 0;
2934
2935    switch (Component.getKind()) {
2936    case VTableComponent::CK_VCallOffset:
2937      Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVCallOffset());
2938      Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
2939      break;
2940    case VTableComponent::CK_VBaseOffset:
2941      Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVBaseOffset());
2942      Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
2943      break;
2944    case VTableComponent::CK_OffsetToTop:
2945      Init = llvm::ConstantInt::get(PtrDiffTy, Component.getOffsetToTop());
2946      Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
2947      break;
2948    case VTableComponent::CK_RTTI:
2949      Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
2950      break;
2951    case VTableComponent::CK_FunctionPointer:
2952    case VTableComponent::CK_CompleteDtorPointer:
2953    case VTableComponent::CK_DeletingDtorPointer: {
2954      GlobalDecl GD;
2955
2956      // Get the right global decl.
2957      switch (Component.getKind()) {
2958      default:
2959        llvm_unreachable("Unexpected vtable component kind");
2960      case VTableComponent::CK_FunctionPointer:
2961        GD = Component.getFunctionDecl();
2962        break;
2963      case VTableComponent::CK_CompleteDtorPointer:
2964        GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
2965        break;
2966      case VTableComponent::CK_DeletingDtorPointer:
2967        GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
2968        break;
2969      }
2970
2971      if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
2972        // We have a pure virtual member function.
2973        if (!PureVirtualFn) {
2974          const llvm::FunctionType *Ty =
2975            llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2976                                    /*isVarArg=*/false);
2977          PureVirtualFn =
2978            CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
2979          PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
2980                                                         Int8PtrTy);
2981        }
2982
2983        Init = PureVirtualFn;
2984      } else {
2985        // Check if we should use a thunk.
2986        if (NextVTableThunkIndex < VTableThunks.size() &&
2987            VTableThunks[NextVTableThunkIndex].first == I) {
2988          const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
2989
2990          Init = CGM.GetAddrOfThunk(GD, Thunk);
2991          MaybeEmitThunkAvailableExternally(GD, Thunk);
2992
2993          NextVTableThunkIndex++;
2994        } else {
2995          const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
2996
2997          Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
2998        }
2999
3000        Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
3001      }
3002      break;
3003    }
3004
3005    case VTableComponent::CK_UnusedFunctionPointer:
3006      Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
3007      break;
3008    };
3009
3010    Inits.push_back(Init);
3011  }
3012
3013  llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
3014  return llvm::ConstantArray::get(ArrayType, Inits.data(), Inits.size());
3015}
3016
3017llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
3018  llvm::SmallString<256> OutName;
3019  llvm::raw_svector_ostream Out(OutName);
3020  CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
3021  Out.flush();
3022  llvm::StringRef Name = OutName.str();
3023
3024  ComputeVTableRelatedInformation(RD, true);
3025
3026  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
3027  llvm::ArrayType *ArrayType =
3028    llvm::ArrayType::get(Int8PtrTy, getNumVTableComponents(RD));
3029
3030  llvm::GlobalVariable *GV =
3031    CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
3032                                          llvm::GlobalValue::ExternalLinkage);
3033  GV->setUnnamedAddr(true);
3034  return GV;
3035}
3036
3037void
3038CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
3039                                     llvm::GlobalVariable::LinkageTypes Linkage,
3040                                     const CXXRecordDecl *RD) {
3041  // Dump the vtable layout if necessary.
3042  if (CGM.getLangOptions().DumpVTableLayouts) {
3043    VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
3044
3045    Builder.dumpLayout(llvm::errs());
3046  }
3047
3048  assert(VTableThunksMap.count(RD) &&
3049         "No thunk status for this record decl!");
3050
3051  const VTableThunksTy& Thunks = VTableThunksMap[RD];
3052
3053  // Create and set the initializer.
3054  llvm::Constant *Init =
3055    CreateVTableInitializer(RD, getVTableComponentsData(RD),
3056                            getNumVTableComponents(RD), Thunks);
3057  VTable->setInitializer(Init);
3058
3059  // Set the correct linkage.
3060  VTable->setLinkage(Linkage);
3061
3062  // Set the right visibility.
3063  CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
3064}
3065
3066llvm::GlobalVariable *
3067CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
3068                                      const BaseSubobject &Base,
3069                                      bool BaseIsVirtual,
3070                                   llvm::GlobalVariable::LinkageTypes Linkage,
3071                                      VTableAddressPointsMapTy& AddressPoints) {
3072  VTableBuilder Builder(*this, Base.getBase(),
3073                        CGM.getContext().toBits(Base.getBaseOffset()),
3074                        /*MostDerivedClassIsVirtual=*/BaseIsVirtual, RD);
3075
3076  // Dump the vtable layout if necessary.
3077  if (CGM.getLangOptions().DumpVTableLayouts)
3078    Builder.dumpLayout(llvm::errs());
3079
3080  // Add the address points.
3081  AddressPoints.insert(Builder.address_points_begin(),
3082                       Builder.address_points_end());
3083
3084  // Get the mangled construction vtable name.
3085  llvm::SmallString<256> OutName;
3086  llvm::raw_svector_ostream Out(OutName);
3087  CGM.getCXXABI().getMangleContext().
3088    mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
3089                        Out);
3090  Out.flush();
3091  llvm::StringRef Name = OutName.str();
3092
3093  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
3094  llvm::ArrayType *ArrayType =
3095    llvm::ArrayType::get(Int8PtrTy, Builder.getNumVTableComponents());
3096
3097  // Create the variable that will hold the construction vtable.
3098  llvm::GlobalVariable *VTable =
3099    CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
3100  CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
3101
3102  // V-tables are always unnamed_addr.
3103  VTable->setUnnamedAddr(true);
3104
3105  // Add the thunks.
3106  VTableThunksTy VTableThunks;
3107  VTableThunks.append(Builder.vtable_thunks_begin(),
3108                      Builder.vtable_thunks_end());
3109
3110  // Sort them.
3111  std::sort(VTableThunks.begin(), VTableThunks.end());
3112
3113  // Create and set the initializer.
3114  llvm::Constant *Init =
3115    CreateVTableInitializer(Base.getBase(),
3116                            Builder.vtable_components_data_begin(),
3117                            Builder.getNumVTableComponents(), VTableThunks);
3118  VTable->setInitializer(Init);
3119
3120  return VTable;
3121}
3122
3123void
3124CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
3125                                  const CXXRecordDecl *RD) {
3126  llvm::GlobalVariable *&VTable = VTables[RD];
3127  if (VTable) {
3128    assert(VTable->getInitializer() && "VTable doesn't have a definition!");
3129    return;
3130  }
3131
3132  VTable = GetAddrOfVTable(RD);
3133  EmitVTableDefinition(VTable, Linkage, RD);
3134
3135  if (RD->getNumVBases()) {
3136    llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
3137    EmitVTTDefinition(VTT, Linkage, RD);
3138  }
3139
3140  // If this is the magic class __cxxabiv1::__fundamental_type_info,
3141  // we will emit the typeinfo for the fundamental types. This is the
3142  // same behaviour as GCC.
3143  const DeclContext *DC = RD->getDeclContext();
3144  if (RD->getIdentifier() &&
3145      RD->getIdentifier()->isStr("__fundamental_type_info") &&
3146      isa<NamespaceDecl>(DC) &&
3147      cast<NamespaceDecl>(DC)->getIdentifier() &&
3148      cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
3149      DC->getParent()->isTranslationUnit())
3150    CGM.EmitFundamentalRTTIDescriptors();
3151}
3152