blob: b78867841cc49fb83dd1e824b98d70ae9a1bb054 [file] [log] [blame]
Anders Carlssondbd920c2009-10-11 22:13:54 +00001//===--- CGVtable.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"
Anders Carlssond6b07fb2009-11-27 20:47:55 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlssondbd920c2009-10-11 22:13:54 +000017#include "clang/AST/RecordLayout.h"
Anders Carlsson5dd730a2009-11-26 19:32:45 +000018#include "llvm/ADT/DenseSet.h"
Anders Carlssonb9021e92010-02-27 16:18:19 +000019#include "llvm/ADT/SetVector.h"
Chandler Carruthe087f072010-02-13 10:38:52 +000020#include "llvm/Support/Compiler.h"
Anders Carlsson824d7ea2010-02-11 08:02:13 +000021#include "llvm/Support/Format.h"
Anders Carlsson5e454aa2010-03-17 20:06:32 +000022#include <algorithm>
Zhongxing Xu7fe26ac2009-11-13 05:46:16 +000023#include <cstdio>
Anders Carlssondbd920c2009-10-11 22:13:54 +000024
25using namespace clang;
26using namespace CodeGen;
27
Anders Carlsson27f69d02009-11-27 22:21:51 +000028namespace {
Anders Carlsson824d7ea2010-02-11 08:02:13 +000029
Anders Carlsson2fca9be2010-02-23 01:34:28 +000030/// BaseOffset - Represents an offset from a derived class to a direct or
31/// indirect base class.
32struct BaseOffset {
33 /// DerivedClass - The derived class.
34 const CXXRecordDecl *DerivedClass;
35
36 /// VirtualBase - If the path from the derived class to the base class
37 /// involves a virtual base class, this holds its declaration.
38 const CXXRecordDecl *VirtualBase;
39
40 /// NonVirtualOffset - The offset from the derived class to the base class.
41 /// (Or the offset from the virtual base class to the base class, if the
42 /// path from the derived class to the base class involves a virtual base
43 /// class.
44 int64_t NonVirtualOffset;
45
46 BaseOffset() : DerivedClass(0), VirtualBase(0), NonVirtualOffset(0) { }
47 BaseOffset(const CXXRecordDecl *DerivedClass,
48 const CXXRecordDecl *VirtualBase, int64_t NonVirtualOffset)
49 : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
50 NonVirtualOffset(NonVirtualOffset) { }
51
52 bool isEmpty() const { return !NonVirtualOffset && !VirtualBase; }
53};
54
Anders Carlssonbdf73d82010-02-11 21:24:32 +000055/// FinalOverriders - Contains the final overrider member functions for all
56/// member functions in the base subobjects of a class.
57class FinalOverriders {
Anders Carlssona7575822010-02-12 16:55:34 +000058public:
59 /// OverriderInfo - Information about a final overrider.
60 struct OverriderInfo {
61 /// Method - The method decl of the overrider.
62 const CXXMethodDecl *Method;
Anders Carlsson96309c42010-02-18 16:29:24 +000063
Anders Carlssondb4022c2010-03-10 02:33:41 +000064 /// Offset - the base offset of the overrider in the layout class.
65 uint64_t Offset;
Anders Carlssona7575822010-02-12 16:55:34 +000066
Anders Carlssoncd0d27f2010-03-12 05:02:01 +000067 OverriderInfo() : Method(0), Offset(0) { }
Anders Carlssona7575822010-02-12 16:55:34 +000068 };
69
70private:
Anders Carlssonbdf73d82010-02-11 21:24:32 +000071 /// MostDerivedClass - The most derived class for which the final overriders
72 /// are stored.
73 const CXXRecordDecl *MostDerivedClass;
74
Anders Carlssondb4022c2010-03-10 02:33:41 +000075 /// MostDerivedClassOffset - If we're building final overriders for a
76 /// construction vtable, this holds the offset from the layout class to the
77 /// most derived class.
78 const uint64_t MostDerivedClassOffset;
79
80 /// LayoutClass - The class we're using for layout information. Will be
81 /// different than the most derived class if the final overriders are for a
82 /// construction vtable.
83 const CXXRecordDecl *LayoutClass;
84
Anders Carlssonbdf73d82010-02-11 21:24:32 +000085 ASTContext &Context;
86
87 /// MostDerivedClassLayout - the AST record layout of the most derived class.
88 const ASTRecordLayout &MostDerivedClassLayout;
89
Anders Carlsson0c0eeb22010-02-13 02:02:03 +000090 /// BaseSubobjectMethodPairTy - Uniquely identifies a member function
91 /// in a base subobject.
92 typedef std::pair<BaseSubobject, const CXXMethodDecl *>
93 BaseSubobjectMethodPairTy;
94
95 typedef llvm::DenseMap<BaseSubobjectMethodPairTy,
Anders Carlssona7575822010-02-12 16:55:34 +000096 OverriderInfo> OverridersMapTy;
Anders Carlssonbdf73d82010-02-11 21:24:32 +000097
98 /// OverridersMap - The final overriders for all virtual member functions of
99 /// all the base subobjects of the most derived class.
100 OverridersMapTy OverridersMap;
101
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000102 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
103 /// avoid visiting virtual bases more than once.
104 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
105
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000106 typedef llvm::DenseMap<BaseSubobjectMethodPairTy, BaseOffset>
107 AdjustmentOffsetsMapTy;
108
109 /// ReturnAdjustments - Holds return adjustments for all the overriders that
110 /// need to perform return value adjustments.
111 AdjustmentOffsetsMapTy ReturnAdjustments;
Anders Carlssondf31af12010-02-13 23:17:31 +0000112
Anders Carlssonce57dd52010-03-03 04:58:02 +0000113 // FIXME: We might be able to get away with making this a SmallSet.
114 typedef llvm::SmallSetVector<uint64_t, 2> OffsetSetVectorTy;
Anders Carlssonb8358d82010-02-12 01:40:03 +0000115
116 /// SubobjectOffsetsMapTy - This map is used for keeping track of all the
117 /// base subobject offsets that a single class declaration might refer to.
118 ///
119 /// For example, in:
120 ///
121 /// struct A { virtual void f(); };
122 /// struct B1 : A { };
123 /// struct B2 : A { };
124 /// struct C : B1, B2 { virtual void f(); };
125 ///
126 /// when we determine that C::f() overrides A::f(), we need to update the
127 /// overriders map for both A-in-B1 and A-in-B2 and the subobject offsets map
128 /// will have the subobject offsets for both A copies.
Anders Carlssonce57dd52010-03-03 04:58:02 +0000129 typedef llvm::DenseMap<const CXXRecordDecl *, OffsetSetVectorTy>
Anders Carlssonb8358d82010-02-12 01:40:03 +0000130 SubobjectOffsetsMapTy;
131
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000132 /// ComputeFinalOverriders - Compute the final overriders for a given base
133 /// subobject (and all its direct and indirect bases).
Anders Carlssonb8358d82010-02-12 01:40:03 +0000134 void ComputeFinalOverriders(BaseSubobject Base,
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000135 bool BaseSubobjectIsVisitedVBase,
Anders Carlssondb4022c2010-03-10 02:33:41 +0000136 uint64_t OffsetInLayoutClass,
Anders Carlssonb8358d82010-02-12 01:40:03 +0000137 SubobjectOffsetsMapTy &Offsets);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000138
139 /// AddOverriders - Add the final overriders for this base subobject to the
140 /// map of final overriders.
Anders Carlssondb4022c2010-03-10 02:33:41 +0000141 void AddOverriders(BaseSubobject Base,uint64_t OffsetInLayoutClass,
142 SubobjectOffsetsMapTy &Offsets);
Anders Carlssonb8358d82010-02-12 01:40:03 +0000143
144 /// PropagateOverrider - Propagate the NewMD overrider to all the functions
145 /// that OldMD overrides. For example, if we have:
146 ///
147 /// struct A { virtual void f(); };
148 /// struct B : A { virtual void f(); };
149 /// struct C : B { virtual void f(); };
150 ///
151 /// and we want to override B::f with C::f, we also need to override A::f with
152 /// C::f.
153 void PropagateOverrider(const CXXMethodDecl *OldMD,
Anders Carlsson74c364e2010-02-13 22:23:31 +0000154 BaseSubobject NewBase,
Anders Carlssondb4022c2010-03-10 02:33:41 +0000155 uint64_t OverriderOffsetInLayoutClass,
Anders Carlssonb8358d82010-02-12 01:40:03 +0000156 const CXXMethodDecl *NewMD,
157 SubobjectOffsetsMapTy &Offsets);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000158
Anders Carlssonb8358d82010-02-12 01:40:03 +0000159 static void MergeSubobjectOffsets(const SubobjectOffsetsMapTy &NewOffsets,
160 SubobjectOffsetsMapTy &Offsets);
161
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000162public:
Anders Carlssondb4022c2010-03-10 02:33:41 +0000163 FinalOverriders(const CXXRecordDecl *MostDerivedClass,
164 uint64_t MostDerivedClassOffset,
165 const CXXRecordDecl *LayoutClass);
Anders Carlsson2157d302010-02-24 22:18:01 +0000166
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000167 /// getOverrider - Get the final overrider for the given method declaration in
168 /// the given base subobject.
Anders Carlsson7dbf47a2010-02-13 20:11:51 +0000169 OverriderInfo getOverrider(BaseSubobject Base,
170 const CXXMethodDecl *MD) const {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000171 assert(OverridersMap.count(std::make_pair(Base, MD)) &&
172 "Did not find overrider!");
173
174 return OverridersMap.lookup(std::make_pair(Base, MD));
175 }
176
Anders Carlsson49bac9a2010-02-13 23:40:17 +0000177 /// getReturnAdjustmentOffset - Get the return adjustment offset for the
178 /// method decl in the given base subobject. Returns an empty base offset if
179 /// no adjustment is needed.
Anders Carlsson7dbf47a2010-02-13 20:11:51 +0000180 BaseOffset getReturnAdjustmentOffset(BaseSubobject Base,
181 const CXXMethodDecl *MD) const {
182 return ReturnAdjustments.lookup(std::make_pair(Base, MD));
183 }
184
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000185 /// dump - dump the final overriders.
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000186 void dump() {
187 assert(VisitedVirtualBases.empty() &&
188 "Visited virtual bases aren't empty!");
189 dump(llvm::errs(), BaseSubobject(MostDerivedClass, 0));
190 VisitedVirtualBases.clear();
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000191 }
192
193 /// dump - dump the final overriders for a base subobject, and all its direct
194 /// and indirect base subobjects.
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000195 void dump(llvm::raw_ostream &Out, BaseSubobject Base);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000196};
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000197
Anders Carlsson327568e2010-02-27 20:02:53 +0000198#define DUMP_OVERRIDERS 0
199
Anders Carlssondb4022c2010-03-10 02:33:41 +0000200FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
201 uint64_t MostDerivedClassOffset,
202 const CXXRecordDecl *LayoutClass)
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000203 : MostDerivedClass(MostDerivedClass),
Anders Carlssondb4022c2010-03-10 02:33:41 +0000204 MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000205 Context(MostDerivedClass->getASTContext()),
206 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
207
208 // Compute the final overriders.
Anders Carlssonb8358d82010-02-12 01:40:03 +0000209 SubobjectOffsetsMapTy Offsets;
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000210 ComputeFinalOverriders(BaseSubobject(MostDerivedClass, 0),
Anders Carlssondb4022c2010-03-10 02:33:41 +0000211 /*BaseSubobjectIsVisitedVBase=*/false,
212 MostDerivedClassOffset, Offsets);
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000213 VisitedVirtualBases.clear();
Anders Carlsson327568e2010-02-27 20:02:53 +0000214
215#if DUMP_OVERRIDERS
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000216 // And dump them (for now).
217 dump();
Anders Carlssona4699882010-02-13 21:33:22 +0000218
219 // Also dump the base offsets (for now).
220 for (SubobjectOffsetsMapTy::const_iterator I = Offsets.begin(),
221 E = Offsets.end(); I != E; ++I) {
Anders Carlssondb4022c2010-03-10 02:33:41 +0000222 const OffsetSetVectorTy& OffsetSetVector = I->second;
Anders Carlssona4699882010-02-13 21:33:22 +0000223
224 llvm::errs() << "Base offsets for ";
225 llvm::errs() << I->first->getQualifiedNameAsString() << '\n';
226
Anders Carlssondb4022c2010-03-10 02:33:41 +0000227 for (unsigned I = 0, E = OffsetSetVector.size(); I != E; ++I)
228 llvm::errs() << " " << I << " - " << OffsetSetVector[I] / 8 << '\n';
Anders Carlssona4699882010-02-13 21:33:22 +0000229 }
Anders Carlsson327568e2010-02-27 20:02:53 +0000230#endif
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000231}
232
Anders Carlssonb8358d82010-02-12 01:40:03 +0000233void FinalOverriders::AddOverriders(BaseSubobject Base,
Anders Carlssondb4022c2010-03-10 02:33:41 +0000234 uint64_t OffsetInLayoutClass,
Anders Carlssonb8358d82010-02-12 01:40:03 +0000235 SubobjectOffsetsMapTy &Offsets) {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000236 const CXXRecordDecl *RD = Base.getBase();
237
238 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
239 E = RD->method_end(); I != E; ++I) {
240 const CXXMethodDecl *MD = *I;
241
242 if (!MD->isVirtual())
243 continue;
244
Anders Carlssonb8358d82010-02-12 01:40:03 +0000245 // First, propagate the overrider.
Anders Carlssondb4022c2010-03-10 02:33:41 +0000246 PropagateOverrider(MD, Base, OffsetInLayoutClass, MD, Offsets);
Anders Carlssonb8358d82010-02-12 01:40:03 +0000247
248 // Add the overrider as the final overrider of itself.
Anders Carlssona7575822010-02-12 16:55:34 +0000249 OverriderInfo& Overrider = OverridersMap[std::make_pair(Base, MD)];
250 assert(!Overrider.Method && "Overrider should not exist yet!");
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000251
Anders Carlssondb4022c2010-03-10 02:33:41 +0000252 Overrider.Offset = OffsetInLayoutClass;
Anders Carlssona7575822010-02-12 16:55:34 +0000253 Overrider.Method = MD;
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000254 }
255}
256
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000257static BaseOffset ComputeBaseOffset(ASTContext &Context,
258 const CXXRecordDecl *DerivedRD,
259 const CXXBasePath &Path) {
Anders Carlssondf31af12010-02-13 23:17:31 +0000260 int64_t NonVirtualOffset = 0;
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000261
Anders Carlssona4a54172010-02-13 20:41:15 +0000262 unsigned NonVirtualStart = 0;
263 const CXXRecordDecl *VirtualBase = 0;
264
265 // First, look for the virtual base class.
266 for (unsigned I = 0, E = Path.size(); I != E; ++I) {
267 const CXXBasePathElement &Element = Path[I];
268
269 if (Element.Base->isVirtual()) {
270 // FIXME: Can we break when we find the first virtual base?
271 // (If we can't, can't we just iterate over the path in reverse order?)
272 NonVirtualStart = I + 1;
273 QualType VBaseType = Element.Base->getType();
274 VirtualBase =
275 cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
276 }
277 }
278
279 // Now compute the non-virtual offset.
280 for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
281 const CXXBasePathElement &Element = Path[I];
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000282
283 // Check the base class offset.
284 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
Anders Carlssonbf554f62010-02-25 22:18:35 +0000285
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000286 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
287 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
Anders Carlssonbf554f62010-02-25 22:18:35 +0000288
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000289 NonVirtualOffset += Layout.getBaseClassOffset(Base);
290 }
291
292 // FIXME: This should probably use CharUnits or something. Maybe we should
293 // even change the base offsets in ASTRecordLayout to be specified in
294 // CharUnits.
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000295 return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset / 8);
Anders Carlssone67dc302010-02-14 00:16:19 +0000296
297}
298
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000299static BaseOffset ComputeBaseOffset(ASTContext &Context,
300 const CXXRecordDecl *BaseRD,
301 const CXXRecordDecl *DerivedRD) {
Anders Carlssone67dc302010-02-14 00:16:19 +0000302 CXXBasePaths Paths(/*FindAmbiguities=*/false,
303 /*RecordPaths=*/true, /*DetectVirtual=*/false);
304
305 if (!const_cast<CXXRecordDecl *>(DerivedRD)->
306 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
307 assert(false && "Class must be derived from the passed in base class!");
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000308 return BaseOffset();
Anders Carlssone67dc302010-02-14 00:16:19 +0000309 }
310
311 return ComputeBaseOffset(Context, DerivedRD, Paths.front());
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000312}
313
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000314static BaseOffset
Anders Carlssondf31af12010-02-13 23:17:31 +0000315ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
316 const CXXMethodDecl *DerivedMD,
317 const CXXMethodDecl *BaseMD) {
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000318 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
319 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
320
321 // Canonicalize the return types.
322 CanQualType CanDerivedReturnType =
323 Context.getCanonicalType(DerivedFT->getResultType());
324 CanQualType CanBaseReturnType =
325 Context.getCanonicalType(BaseFT->getResultType());
326
327 assert(CanDerivedReturnType->getTypeClass() ==
328 CanBaseReturnType->getTypeClass() &&
329 "Types must have same type class!");
330
331 if (CanDerivedReturnType == CanBaseReturnType) {
332 // No adjustment needed.
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000333 return BaseOffset();
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000334 }
335
336 if (isa<ReferenceType>(CanDerivedReturnType)) {
337 CanDerivedReturnType =
338 CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
339 CanBaseReturnType =
340 CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
341 } else if (isa<PointerType>(CanDerivedReturnType)) {
342 CanDerivedReturnType =
343 CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
344 CanBaseReturnType =
345 CanBaseReturnType->getAs<PointerType>()->getPointeeType();
346 } else {
347 assert(false && "Unexpected return type!");
348 }
349
350 // We need to compare unqualified types here; consider
351 // const T *Base::foo();
352 // T *Derived::foo();
353 if (CanDerivedReturnType.getUnqualifiedType() ==
354 CanBaseReturnType.getUnqualifiedType()) {
355 // No adjustment needed.
Anders Carlsson2fca9be2010-02-23 01:34:28 +0000356 return BaseOffset();
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000357 }
358
359 const CXXRecordDecl *DerivedRD =
360 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
361
362 const CXXRecordDecl *BaseRD =
363 cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
364
Anders Carlssondf31af12010-02-13 23:17:31 +0000365 return ComputeBaseOffset(Context, BaseRD, DerivedRD);
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000366}
367
Anders Carlssonb8358d82010-02-12 01:40:03 +0000368void FinalOverriders::PropagateOverrider(const CXXMethodDecl *OldMD,
Anders Carlsson74c364e2010-02-13 22:23:31 +0000369 BaseSubobject NewBase,
Anders Carlssondb4022c2010-03-10 02:33:41 +0000370 uint64_t OverriderOffsetInLayoutClass,
Anders Carlssonb8358d82010-02-12 01:40:03 +0000371 const CXXMethodDecl *NewMD,
372 SubobjectOffsetsMapTy &Offsets) {
373 for (CXXMethodDecl::method_iterator I = OldMD->begin_overridden_methods(),
374 E = OldMD->end_overridden_methods(); I != E; ++I) {
375 const CXXMethodDecl *OverriddenMD = *I;
376 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
377
378 // We want to override OverriddenMD in all subobjects, for example:
379 //
380 /// struct A { virtual void f(); };
381 /// struct B1 : A { };
382 /// struct B2 : A { };
383 /// struct C : B1, B2 { virtual void f(); };
384 ///
385 /// When overriding A::f with C::f we need to do so in both A subobjects.
Anders Carlssonce57dd52010-03-03 04:58:02 +0000386 const OffsetSetVectorTy &OffsetVector = Offsets[OverriddenRD];
Anders Carlssonb8358d82010-02-12 01:40:03 +0000387
388 // Go through all the subobjects.
389 for (unsigned I = 0, E = OffsetVector.size(); I != E; ++I) {
390 uint64_t Offset = OffsetVector[I];
391
Anders Carlssone67dc302010-02-14 00:16:19 +0000392 BaseSubobject OverriddenSubobject = BaseSubobject(OverriddenRD, Offset);
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000393 BaseSubobjectMethodPairTy SubobjectAndMethod =
Anders Carlssone67dc302010-02-14 00:16:19 +0000394 std::make_pair(OverriddenSubobject, OverriddenMD);
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000395
396 OverriderInfo &Overrider = OverridersMap[SubobjectAndMethod];
397
Anders Carlssona7575822010-02-12 16:55:34 +0000398 assert(Overrider.Method && "Did not find existing overrider!");
Anders Carlssonb8358d82010-02-12 01:40:03 +0000399
Anders Carlssondf31af12010-02-13 23:17:31 +0000400 // Check if we need return adjustments or base adjustments.
Anders Carlsson1d05be52010-02-13 21:16:54 +0000401 // (We don't want to do this for pure virtual member functions).
402 if (!NewMD->isPure()) {
Anders Carlssondf31af12010-02-13 23:17:31 +0000403 // Get the return adjustment base offset.
Anders Carlsson1d05be52010-02-13 21:16:54 +0000404 BaseOffset ReturnBaseOffset =
Anders Carlssondf31af12010-02-13 23:17:31 +0000405 ComputeReturnAdjustmentBaseOffset(Context, NewMD, OverriddenMD);
406
Anders Carlsson1d05be52010-02-13 21:16:54 +0000407 if (!ReturnBaseOffset.isEmpty()) {
408 // Store the return adjustment base offset.
409 ReturnAdjustments[SubobjectAndMethod] = ReturnBaseOffset;
410 }
Anders Carlsson16b73122010-02-12 17:13:23 +0000411 }
412
Anders Carlssonb8358d82010-02-12 01:40:03 +0000413 // Set the new overrider.
Anders Carlssondb4022c2010-03-10 02:33:41 +0000414 Overrider.Offset = OverriderOffsetInLayoutClass;
Anders Carlssona7575822010-02-12 16:55:34 +0000415 Overrider.Method = NewMD;
Anders Carlssonb8358d82010-02-12 01:40:03 +0000416
417 // And propagate it further.
Anders Carlssondb4022c2010-03-10 02:33:41 +0000418 PropagateOverrider(OverriddenMD, NewBase, OverriderOffsetInLayoutClass,
419 NewMD, Offsets);
Anders Carlssonb8358d82010-02-12 01:40:03 +0000420 }
421 }
422}
423
424void
425FinalOverriders::MergeSubobjectOffsets(const SubobjectOffsetsMapTy &NewOffsets,
426 SubobjectOffsetsMapTy &Offsets) {
427 // Iterate over the new offsets.
428 for (SubobjectOffsetsMapTy::const_iterator I = NewOffsets.begin(),
429 E = NewOffsets.end(); I != E; ++I) {
430 const CXXRecordDecl *NewRD = I->first;
Anders Carlssonce57dd52010-03-03 04:58:02 +0000431 const OffsetSetVectorTy& NewOffsetVector = I->second;
Anders Carlssonb8358d82010-02-12 01:40:03 +0000432
Anders Carlssonce57dd52010-03-03 04:58:02 +0000433 OffsetSetVectorTy &OffsetVector = Offsets[NewRD];
Anders Carlssonb8358d82010-02-12 01:40:03 +0000434
Anders Carlssonce57dd52010-03-03 04:58:02 +0000435 // Merge the new offsets set vector into the old.
436 OffsetVector.insert(NewOffsetVector.begin(), NewOffsetVector.end());
Anders Carlssonb8358d82010-02-12 01:40:03 +0000437 }
438}
439
440void FinalOverriders::ComputeFinalOverriders(BaseSubobject Base,
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000441 bool BaseSubobjectIsVisitedVBase,
Anders Carlssondb4022c2010-03-10 02:33:41 +0000442 uint64_t OffsetInLayoutClass,
Anders Carlssonb8358d82010-02-12 01:40:03 +0000443 SubobjectOffsetsMapTy &Offsets) {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000444 const CXXRecordDecl *RD = Base.getBase();
Anders Carlssonb8358d82010-02-12 01:40:03 +0000445 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000446
Anders Carlssonb8358d82010-02-12 01:40:03 +0000447 SubobjectOffsetsMapTy NewOffsets;
448
449 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
450 E = RD->bases_end(); I != E; ++I) {
451 const CXXRecordDecl *BaseDecl =
452 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
453
Anders Carlssonb828afa2010-02-14 17:05:59 +0000454 // Ignore bases that don't have any virtual member functions.
455 if (!BaseDecl->isPolymorphic())
456 continue;
457
Anders Carlssonbf554f62010-02-25 22:18:35 +0000458 bool IsVisitedVirtualBase = BaseSubobjectIsVisitedVBase;
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000459 uint64_t BaseOffset;
Anders Carlssondb4022c2010-03-10 02:33:41 +0000460 uint64_t BaseOffsetInLayoutClass;
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000461 if (I->isVirtual()) {
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000462 if (!VisitedVirtualBases.insert(BaseDecl))
463 IsVisitedVirtualBase = true;
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000464 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
Anders Carlssondb4022c2010-03-10 02:33:41 +0000465
466 const ASTRecordLayout &LayoutClassLayout =
467 Context.getASTRecordLayout(LayoutClass);
468 BaseOffsetInLayoutClass =
469 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000470 } else {
471 BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
Anders Carlssondb4022c2010-03-10 02:33:41 +0000472 BaseOffsetInLayoutClass = Layout.getBaseClassOffset(BaseDecl) +
473 OffsetInLayoutClass;
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000474 }
475
Anders Carlssonb8358d82010-02-12 01:40:03 +0000476 // Compute the final overriders for this base.
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000477 // We always want to compute the final overriders, even if the base is a
478 // visited virtual base. Consider:
479 //
480 // struct A {
481 // virtual void f();
482 // virtual void g();
483 // };
484 //
485 // struct B : virtual A {
486 // void f();
487 // };
488 //
489 // struct C : virtual A {
490 // void g ();
491 // };
492 //
493 // struct D : B, C { };
494 //
495 // Here, we still want to compute the overriders for A as a base of C,
496 // because otherwise we'll miss that C::g overrides A::f.
497 ComputeFinalOverriders(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssondb4022c2010-03-10 02:33:41 +0000498 IsVisitedVirtualBase, BaseOffsetInLayoutClass,
499 NewOffsets);
Anders Carlssonb8358d82010-02-12 01:40:03 +0000500 }
501
502 /// Now add the overriders for this particular subobject.
Anders Carlssond5c7cca2010-02-17 17:48:25 +0000503 /// (We don't want to do this more than once for a virtual base).
504 if (!BaseSubobjectIsVisitedVBase)
Anders Carlssondb4022c2010-03-10 02:33:41 +0000505 AddOverriders(Base, OffsetInLayoutClass, NewOffsets);
Anders Carlssonb8358d82010-02-12 01:40:03 +0000506
507 // And merge the newly discovered subobject offsets.
508 MergeSubobjectOffsets(NewOffsets, Offsets);
509
510 /// Finally, add the offset for our own subobject.
Anders Carlssonce57dd52010-03-03 04:58:02 +0000511 Offsets[RD].insert(Base.getBaseOffset());
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000512}
513
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000514void FinalOverriders::dump(llvm::raw_ostream &Out, BaseSubobject Base) {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000515 const CXXRecordDecl *RD = Base.getBase();
516 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
517
518 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
519 E = RD->bases_end(); I != E; ++I) {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000520 const CXXRecordDecl *BaseDecl =
521 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
522
Anders Carlssonb828afa2010-02-14 17:05:59 +0000523 // Ignore bases that don't have any virtual member functions.
524 if (!BaseDecl->isPolymorphic())
525 continue;
526
Anders Carlsson9d6f0d52010-02-14 00:37:35 +0000527 uint64_t BaseOffset;
528 if (I->isVirtual()) {
529 if (!VisitedVirtualBases.insert(BaseDecl)) {
530 // We've visited this base before.
531 continue;
532 }
533
534 BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
535 } else {
536 BaseOffset = Layout.getBaseClassOffset(BaseDecl) +
537 Base.getBaseOffset();
538 }
539
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000540 dump(Out, BaseSubobject(BaseDecl, BaseOffset));
541 }
542
543 Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
Anders Carlssondb4022c2010-03-10 02:33:41 +0000544 Out << Base.getBaseOffset() / 8 << ")\n";
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000545
546 // Now dump the overriders for this base subobject.
547 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
548 E = RD->method_end(); I != E; ++I) {
549 const CXXMethodDecl *MD = *I;
550
551 if (!MD->isVirtual())
552 continue;
553
Anders Carlssona7575822010-02-12 16:55:34 +0000554 OverriderInfo Overrider = getOverrider(Base, MD);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000555
Anders Carlssond86e5d82010-03-02 03:44:06 +0000556 Out << " " << MD->getQualifiedNameAsString() << " - (";
Anders Carlsson16b73122010-02-12 17:13:23 +0000557 Out << Overrider.Method->getQualifiedNameAsString();
Anders Carlssoncd0d27f2010-03-12 05:02:01 +0000558 Out << ", " << ", " << Overrider.Offset / 8 << ')';
Anders Carlssond86e5d82010-03-02 03:44:06 +0000559
Benjamin Kramere3d0b1c2010-02-13 09:11:28 +0000560 AdjustmentOffsetsMapTy::const_iterator AI =
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000561 ReturnAdjustments.find(std::make_pair(Base, MD));
Benjamin Kramere3d0b1c2010-02-13 09:11:28 +0000562 if (AI != ReturnAdjustments.end()) {
563 const BaseOffset &Offset = AI->second;
Anders Carlssona4a54172010-02-13 20:41:15 +0000564
565 Out << " [ret-adj: ";
566 if (Offset.VirtualBase)
567 Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000568
Anders Carlssona4a54172010-02-13 20:41:15 +0000569 Out << Offset.NonVirtualOffset << " nv]";
Anders Carlsson0c0eeb22010-02-13 02:02:03 +0000570 }
Anders Carlssondf31af12010-02-13 23:17:31 +0000571
Anders Carlsson16b73122010-02-12 17:13:23 +0000572 Out << "\n";
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000573 }
574}
575
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000576/// VtableComponent - Represents a single component in a vtable.
577class VtableComponent {
578public:
579 enum Kind {
580 CK_VCallOffset,
581 CK_VBaseOffset,
582 CK_OffsetToTop,
583 CK_RTTI,
Anders Carlsson848fa642010-02-11 18:20:28 +0000584 CK_FunctionPointer,
585
586 /// CK_CompleteDtorPointer - A pointer to the complete destructor.
587 CK_CompleteDtorPointer,
588
589 /// CK_DeletingDtorPointer - A pointer to the deleting destructor.
Anders Carlsson1f464662010-02-19 20:08:13 +0000590 CK_DeletingDtorPointer,
591
592 /// CK_UnusedFunctionPointer - In some cases, a vtable function pointer
593 /// will end up never being called. Such vtable function pointers are
594 /// represented as a CK_UnusedFunctionPointer.
595 CK_UnusedFunctionPointer
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000596 };
597
Anders Carlssond9a67042010-02-17 06:07:19 +0000598 static VtableComponent MakeVCallOffset(int64_t Offset) {
599 return VtableComponent(CK_VCallOffset, Offset);
600 }
601
Anders Carlssona661a542010-02-16 04:49:44 +0000602 static VtableComponent MakeVBaseOffset(int64_t Offset) {
603 return VtableComponent(CK_VBaseOffset, Offset);
604 }
605
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000606 static VtableComponent MakeOffsetToTop(int64_t Offset) {
607 return VtableComponent(CK_OffsetToTop, Offset);
608 }
609
610 static VtableComponent MakeRTTI(const CXXRecordDecl *RD) {
611 return VtableComponent(CK_RTTI, reinterpret_cast<uintptr_t>(RD));
612 }
613
614 static VtableComponent MakeFunction(const CXXMethodDecl *MD) {
615 assert(!isa<CXXDestructorDecl>(MD) &&
Anders Carlsson848fa642010-02-11 18:20:28 +0000616 "Don't use MakeFunction with destructors!");
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000617
Anders Carlsson848fa642010-02-11 18:20:28 +0000618 return VtableComponent(CK_FunctionPointer,
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000619 reinterpret_cast<uintptr_t>(MD));
620 }
621
Anders Carlsson848fa642010-02-11 18:20:28 +0000622 static VtableComponent MakeCompleteDtor(const CXXDestructorDecl *DD) {
623 return VtableComponent(CK_CompleteDtorPointer,
624 reinterpret_cast<uintptr_t>(DD));
625 }
626
627 static VtableComponent MakeDeletingDtor(const CXXDestructorDecl *DD) {
628 return VtableComponent(CK_DeletingDtorPointer,
629 reinterpret_cast<uintptr_t>(DD));
630 }
631
Anders Carlsson1f464662010-02-19 20:08:13 +0000632 static VtableComponent MakeUnusedFunction(const CXXMethodDecl *MD) {
633 assert(!isa<CXXDestructorDecl>(MD) &&
634 "Don't use MakeUnusedFunction with destructors!");
635 return VtableComponent(CK_UnusedFunctionPointer,
636 reinterpret_cast<uintptr_t>(MD));
637 }
638
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000639 /// getKind - Get the kind of this vtable component.
640 Kind getKind() const {
641 return (Kind)(Value & 0x7);
642 }
643
Anders Carlssond9a67042010-02-17 06:07:19 +0000644 int64_t getVCallOffset() const {
645 assert(getKind() == CK_VCallOffset && "Invalid component kind!");
646
647 return getOffset();
648 }
649
Anders Carlssona661a542010-02-16 04:49:44 +0000650 int64_t getVBaseOffset() const {
651 assert(getKind() == CK_VBaseOffset && "Invalid component kind!");
652
653 return getOffset();
654 }
655
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000656 int64_t getOffsetToTop() const {
657 assert(getKind() == CK_OffsetToTop && "Invalid component kind!");
658
659 return getOffset();
660 }
661
662 const CXXRecordDecl *getRTTIDecl() const {
663 assert(getKind() == CK_RTTI && "Invalid component kind!");
664
665 return reinterpret_cast<CXXRecordDecl *>(getPointer());
666 }
667
668 const CXXMethodDecl *getFunctionDecl() const {
Anders Carlsson848fa642010-02-11 18:20:28 +0000669 assert(getKind() == CK_FunctionPointer);
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000670
671 return reinterpret_cast<CXXMethodDecl *>(getPointer());
672 }
Anders Carlsson848fa642010-02-11 18:20:28 +0000673
674 const CXXDestructorDecl *getDestructorDecl() const {
675 assert((getKind() == CK_CompleteDtorPointer ||
676 getKind() == CK_DeletingDtorPointer) && "Invalid component kind!");
677
678 return reinterpret_cast<CXXDestructorDecl *>(getPointer());
679 }
680
Anders Carlsson1f464662010-02-19 20:08:13 +0000681 const CXXMethodDecl *getUnusedFunctionDecl() const {
682 assert(getKind() == CK_UnusedFunctionPointer);
683
684 return reinterpret_cast<CXXMethodDecl *>(getPointer());
685 }
686
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000687private:
688 VtableComponent(Kind ComponentKind, int64_t Offset) {
689 assert((ComponentKind == CK_VCallOffset ||
690 ComponentKind == CK_VBaseOffset ||
691 ComponentKind == CK_OffsetToTop) && "Invalid component kind!");
692 assert(Offset <= ((1LL << 56) - 1) && "Offset is too big!");
693
694 Value = ((Offset << 3) | ComponentKind);
695 }
696
697 VtableComponent(Kind ComponentKind, uintptr_t Ptr) {
698 assert((ComponentKind == CK_RTTI ||
Anders Carlsson848fa642010-02-11 18:20:28 +0000699 ComponentKind == CK_FunctionPointer ||
700 ComponentKind == CK_CompleteDtorPointer ||
Anders Carlsson1f464662010-02-19 20:08:13 +0000701 ComponentKind == CK_DeletingDtorPointer ||
702 ComponentKind == CK_UnusedFunctionPointer) &&
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000703 "Invalid component kind!");
704
705 assert((Ptr & 7) == 0 && "Pointer not sufficiently aligned!");
706
707 Value = Ptr | ComponentKind;
708 }
709
710 int64_t getOffset() const {
711 assert((getKind() == CK_VCallOffset || getKind() == CK_VBaseOffset ||
712 getKind() == CK_OffsetToTop) && "Invalid component kind!");
713
714 return Value >> 3;
715 }
716
717 uintptr_t getPointer() const {
Anders Carlsson848fa642010-02-11 18:20:28 +0000718 assert((getKind() == CK_RTTI ||
719 getKind() == CK_FunctionPointer ||
720 getKind() == CK_CompleteDtorPointer ||
Anders Carlsson1f464662010-02-19 20:08:13 +0000721 getKind() == CK_DeletingDtorPointer ||
722 getKind() == CK_UnusedFunctionPointer) &&
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000723 "Invalid component kind!");
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000724
725 return static_cast<uintptr_t>(Value & ~7ULL);
726 }
727
728 /// The kind is stored in the lower 3 bits of the value. For offsets, we
729 /// make use of the facts that classes can't be larger than 2^55 bytes,
730 /// so we store the offset in the lower part of the 61 bytes that remain.
731 /// (The reason that we're not simply using a PointerIntPair here is that we
732 /// need the offsets to be 64-bit, even when on a 32-bit machine).
733 int64_t Value;
734};
735
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000736/// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
737struct VCallOffsetMap {
738
739 typedef std::pair<const CXXMethodDecl *, int64_t> MethodAndOffsetPairTy;
740
741 /// Offsets - Keeps track of methods and their offsets.
742 // FIXME: This should be a real map and not a vector.
743 llvm::SmallVector<MethodAndOffsetPairTy, 16> Offsets;
744
Anders Carlssoneb577d02010-02-18 17:26:40 +0000745 /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
746 /// can share the same vcall offset.
747 static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
748 const CXXMethodDecl *RHS);
749
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000750public:
751 /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
752 /// add was successful, or false if there was already a member function with
753 /// the same signature in the map.
754 bool AddVCallOffset(const CXXMethodDecl *MD, int64_t OffsetOffset);
755
756 /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
757 /// vtable address point) for the given virtual member function.
758 int64_t getVCallOffsetOffset(const CXXMethodDecl *MD);
759
Anders Carlssondba6ef82010-02-25 22:23:13 +0000760 // empty - Return whether the offset map is empty or not.
761 bool empty() const { return Offsets.empty(); }
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000762};
763
John McCall331a03a2010-02-26 20:22:44 +0000764static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
765 const CXXMethodDecl *RHS) {
766 ASTContext &C = LHS->getASTContext(); // TODO: thread this down
767 CanQual<FunctionProtoType>
768 LT = C.getCanonicalType(LHS->getType()).getAs<FunctionProtoType>(),
769 RT = C.getCanonicalType(RHS->getType()).getAs<FunctionProtoType>();
770
771 // Fast-path matches in the canonical types.
772 if (LT == RT) return true;
773
774 // Force the signatures to match. We can't rely on the overrides
775 // list here because there isn't necessarily an inheritance
776 // relationship between the two methods.
777 if (LT.getQualifiers() != RT.getQualifiers() ||
778 LT->getNumArgs() != RT->getNumArgs())
779 return false;
780 for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
781 if (LT->getArgType(I) != RT->getArgType(I))
782 return false;
783 return true;
784}
785
Anders Carlssoneb577d02010-02-18 17:26:40 +0000786bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
787 const CXXMethodDecl *RHS) {
788 assert(LHS->isVirtual() && "LHS must be virtual!");
789 assert(RHS->isVirtual() && "LHS must be virtual!");
790
Anders Carlsson55609692010-02-27 04:12:52 +0000791 // A destructor can share a vcall offset with another destructor.
792 if (isa<CXXDestructorDecl>(LHS))
793 return isa<CXXDestructorDecl>(RHS);
794
Anders Carlssoneb577d02010-02-18 17:26:40 +0000795 // FIXME: We need to check more things here.
796
Anders Carlsson55609692010-02-27 04:12:52 +0000797 // The methods must have the same name.
Anders Carlssoneb577d02010-02-18 17:26:40 +0000798 DeclarationName LHSName = LHS->getDeclName();
799 DeclarationName RHSName = RHS->getDeclName();
John McCall331a03a2010-02-26 20:22:44 +0000800 if (LHSName != RHSName)
Anders Carlssoneb577d02010-02-18 17:26:40 +0000801 return false;
John McCall331a03a2010-02-26 20:22:44 +0000802
Anders Carlsson55609692010-02-27 04:12:52 +0000803 // And the same signatures.
804 return HasSameVirtualSignature(LHS, RHS);
Anders Carlssoneb577d02010-02-18 17:26:40 +0000805}
806
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000807bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
808 int64_t OffsetOffset) {
Anders Carlssoneb577d02010-02-18 17:26:40 +0000809 // Check if we can reuse an offset.
810 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
811 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
812 return false;
813 }
814
815 // Add the offset.
816 Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000817 return true;
818}
819
820int64_t VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
Anders Carlssoneb577d02010-02-18 17:26:40 +0000821 // Look for an offset.
822 for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
823 if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
824 return Offsets[I].second;
825 }
826
827 assert(false && "Should always find a vcall offset offset!");
Anders Carlsson60cc72a2010-02-18 17:00:09 +0000828 return 0;
829}
830
Anders Carlssond68c0832010-02-25 03:45:56 +0000831/// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
832class VCallAndVBaseOffsetBuilder {
Anders Carlssonc89a7cf2010-03-11 16:06:20 +0000833public:
834 typedef llvm::DenseMap<const CXXRecordDecl *, int64_t>
835 VBaseOffsetOffsetsMapTy;
836
837private:
Anders Carlsson530c40c2010-02-28 01:43:58 +0000838 /// MostDerivedClass - The most derived class for which we're building vcall
839 /// and vbase offsets.
Anders Carlssond68c0832010-02-25 03:45:56 +0000840 const CXXRecordDecl *MostDerivedClass;
841
Anders Carlsson0041a642010-02-27 21:09:00 +0000842 /// LayoutClass - The class we're using for layout information. Will be
843 /// different than the most derived class if we're building a construction
844 /// vtable.
845 const CXXRecordDecl *LayoutClass;
846
Anders Carlssond68c0832010-02-25 03:45:56 +0000847 /// Context - The ASTContext which we will use for layout information.
848 ASTContext &Context;
849
850 /// Components - vcall and vbase offset components
851 typedef llvm::SmallVector<VtableComponent, 64> VtableComponentVectorTy;
852 VtableComponentVectorTy Components;
853
854 /// VisitedVirtualBases - Visited virtual bases.
855 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
856
857 /// VCallOffsets - Keeps track of vcall offsets.
858 VCallOffsetMap VCallOffsets;
859
Anders Carlssonbb6305b2010-03-11 06:43:12 +0000860
861 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
862 /// relative to the address point.
863 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
864
Anders Carlssond68c0832010-02-25 03:45:56 +0000865 /// FinalOverriders - The final overriders of the most derived class.
866 /// (Can be null when we're not building a vtable of the most derived class).
867 const FinalOverriders *Overriders;
868
869 /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
870 /// given base subobject.
871 void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
872 uint64_t RealBaseOffset);
873
874 /// AddVCallOffsets - Add vcall offsets for the given base subobject.
875 void AddVCallOffsets(BaseSubobject Base, uint64_t VBaseOffset);
876
877 /// AddVBaseOffsets - Add vbase offsets for the given class.
Anders Carlsson88800662010-03-02 05:40:45 +0000878 void AddVBaseOffsets(const CXXRecordDecl *Base, uint64_t OffsetInLayoutClass);
Anders Carlssond68c0832010-02-25 03:45:56 +0000879
Anders Carlssonbb6305b2010-03-11 06:43:12 +0000880 /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
881 /// bytes, relative to the vtable address point.
882 int64_t getCurrentOffsetOffset() const;
883
Anders Carlssond68c0832010-02-25 03:45:56 +0000884public:
885 VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
Anders Carlsson0041a642010-02-27 21:09:00 +0000886 const CXXRecordDecl *LayoutClass,
Anders Carlssond68c0832010-02-25 03:45:56 +0000887 const FinalOverriders *Overriders,
Anders Carlsson530c40c2010-02-28 01:43:58 +0000888 BaseSubobject Base, bool BaseIsVirtual,
889 uint64_t OffsetInLayoutClass)
890 : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
Anders Carlssond68c0832010-02-25 03:45:56 +0000891 Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
892
893 // Add vcall and vbase offsets.
Anders Carlsson530c40c2010-02-28 01:43:58 +0000894 AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
Anders Carlssond68c0832010-02-25 03:45:56 +0000895 }
896
897 /// Methods for iterating over the components.
898 typedef VtableComponentVectorTy::const_reverse_iterator const_iterator;
899 const_iterator components_begin() const { return Components.rbegin(); }
900 const_iterator components_end() const { return Components.rend(); }
901
Anders Carlssonc89a7cf2010-03-11 16:06:20 +0000902 const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
903 const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
Anders Carlssonbb6305b2010-03-11 06:43:12 +0000904 return VBaseOffsetOffsets;
905 }
Anders Carlssond68c0832010-02-25 03:45:56 +0000906};
907
908void
909VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
910 bool BaseIsVirtual,
911 uint64_t RealBaseOffset) {
912 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
913
914 // Itanium C++ ABI 2.5.2:
915 // ..in classes sharing a virtual table with a primary base class, the vcall
916 // and vbase offsets added by the derived class all come before the vcall
917 // and vbase offsets required by the base class, so that the latter may be
918 // laid out as required by the base class without regard to additions from
919 // the derived class(es).
920
921 // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
922 // emit them for the primary base first).
923 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
924 bool PrimaryBaseIsVirtual = Layout.getPrimaryBaseWasVirtual();
925
926 uint64_t PrimaryBaseOffset;
927
928 // Get the base offset of the primary base.
929 if (PrimaryBaseIsVirtual) {
930 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
931 "Primary vbase should have a zero offset!");
932
933 const ASTRecordLayout &MostDerivedClassLayout =
934 Context.getASTRecordLayout(MostDerivedClass);
935
936 PrimaryBaseOffset =
937 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
938 } else {
939 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
940 "Primary base should have a zero offset!");
941
942 PrimaryBaseOffset = Base.getBaseOffset();
943 }
944
945 AddVCallAndVBaseOffsets(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
946 PrimaryBaseIsVirtual, RealBaseOffset);
947 }
948
Anders Carlsson88800662010-03-02 05:40:45 +0000949 AddVBaseOffsets(Base.getBase(), RealBaseOffset);
Anders Carlssond68c0832010-02-25 03:45:56 +0000950
951 // We only want to add vcall offsets for virtual bases.
952 if (BaseIsVirtual)
953 AddVCallOffsets(Base, RealBaseOffset);
954}
955
Anders Carlssonbb6305b2010-03-11 06:43:12 +0000956int64_t VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
957 // OffsetIndex is the index of this vcall or vbase offset, relative to the
958 // vtable address point. (We subtract 3 to account for the information just
959 // above the address point, the RTTI info, the offset to top, and the
960 // vcall offset itself).
961 int64_t OffsetIndex = -(int64_t)(3 + Components.size());
962
963 // FIXME: We shouldn't use / 8 here.
964 int64_t OffsetOffset = OffsetIndex *
965 (int64_t)Context.Target.getPointerWidth(0) / 8;
966
967 return OffsetOffset;
968}
969
Anders Carlssond68c0832010-02-25 03:45:56 +0000970void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
971 uint64_t VBaseOffset) {
972 const CXXRecordDecl *RD = Base.getBase();
973 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
974
John McCall331a03a2010-02-26 20:22:44 +0000975 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
976
Anders Carlssond68c0832010-02-25 03:45:56 +0000977 // Handle the primary base first.
John McCall331a03a2010-02-26 20:22:44 +0000978 if (PrimaryBase) {
Anders Carlssond68c0832010-02-25 03:45:56 +0000979 uint64_t PrimaryBaseOffset;
980
981 // Get the base offset of the primary base.
982 if (Layout.getPrimaryBaseWasVirtual()) {
983 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
984 "Primary vbase should have a zero offset!");
985
986 const ASTRecordLayout &MostDerivedClassLayout =
987 Context.getASTRecordLayout(MostDerivedClass);
988
989 PrimaryBaseOffset =
990 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
991 } else {
992 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
993 "Primary base should have a zero offset!");
994
995 PrimaryBaseOffset = Base.getBaseOffset();
996 }
997
998 AddVCallOffsets(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
999 VBaseOffset);
1000 }
1001
1002 // Add the vcall offsets.
1003 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1004 E = RD->method_end(); I != E; ++I) {
1005 const CXXMethodDecl *MD = *I;
1006
1007 if (!MD->isVirtual())
1008 continue;
1009
Anders Carlssonbb6305b2010-03-11 06:43:12 +00001010 int64_t OffsetOffset = getCurrentOffsetOffset();
Anders Carlssond68c0832010-02-25 03:45:56 +00001011
1012 // Don't add a vcall offset if we already have one for this member function
1013 // signature.
1014 if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
1015 continue;
1016
1017 int64_t Offset = 0;
1018
1019 if (Overriders) {
1020 // Get the final overrider.
1021 FinalOverriders::OverriderInfo Overrider =
1022 Overriders->getOverrider(Base, MD);
1023
Anders Carlsson438bc422010-02-28 00:10:58 +00001024 /// The vcall offset is the offset from the virtual base to the object
1025 /// where the function was overridden.
Anders Carlssond68c0832010-02-25 03:45:56 +00001026 // FIXME: We should not use / 8 here.
Anders Carlssond86e5d82010-03-02 03:44:06 +00001027 Offset = (int64_t)(Overrider.Offset - VBaseOffset) / 8;
Anders Carlssond68c0832010-02-25 03:45:56 +00001028 }
1029
1030 Components.push_back(VtableComponent::MakeVCallOffset(Offset));
1031 }
1032
1033 // And iterate over all non-virtual bases (ignoring the primary base).
1034 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1035 E = RD->bases_end(); I != E; ++I) {
1036
1037 if (I->isVirtual())
1038 continue;
1039
1040 const CXXRecordDecl *BaseDecl =
1041 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
John McCall331a03a2010-02-26 20:22:44 +00001042 if (BaseDecl == PrimaryBase)
1043 continue;
Anders Carlssond68c0832010-02-25 03:45:56 +00001044
1045 // Get the base offset of this base.
1046 uint64_t BaseOffset = Base.getBaseOffset() +
1047 Layout.getBaseClassOffset(BaseDecl);
1048
1049 AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), VBaseOffset);
1050 }
1051}
1052
Anders Carlssond68c0832010-02-25 03:45:56 +00001053void VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
Anders Carlsson88800662010-03-02 05:40:45 +00001054 uint64_t OffsetInLayoutClass) {
Anders Carlsson0041a642010-02-27 21:09:00 +00001055 const ASTRecordLayout &LayoutClassLayout =
1056 Context.getASTRecordLayout(LayoutClass);
Anders Carlssond68c0832010-02-25 03:45:56 +00001057
1058 // Add vbase offsets.
1059 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1060 E = RD->bases_end(); I != E; ++I) {
1061 const CXXRecordDecl *BaseDecl =
1062 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1063
1064 // Check if this is a virtual base that we haven't visited before.
1065 if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
1066 // FIXME: We shouldn't use / 8 here.
Anders Carlsson88800662010-03-02 05:40:45 +00001067 int64_t Offset =
1068 (int64_t)(LayoutClassLayout.getVBaseClassOffset(BaseDecl) -
1069 OffsetInLayoutClass) / 8;
Anders Carlssonbb6305b2010-03-11 06:43:12 +00001070
1071 // Add the vbase offset offset.
1072 assert(!VBaseOffsetOffsets.count(BaseDecl) &&
1073 "vbase offset offset already exists!");
1074
1075 int64_t VBaseOffsetOffset = getCurrentOffsetOffset();
1076 VBaseOffsetOffsets.insert(std::make_pair(BaseDecl, VBaseOffsetOffset));
1077
Anders Carlssond68c0832010-02-25 03:45:56 +00001078 Components.push_back(VtableComponent::MakeVBaseOffset(Offset));
1079 }
Anders Carlssonbb6305b2010-03-11 06:43:12 +00001080
Anders Carlssond68c0832010-02-25 03:45:56 +00001081 // Check the base class looking for more vbase offsets.
Anders Carlsson88800662010-03-02 05:40:45 +00001082 AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
Anders Carlssond68c0832010-02-25 03:45:56 +00001083 }
1084}
1085
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001086/// VtableBuilder - Class for building vtable layout information.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001087class VtableBuilder {
Anders Carlsson57071e22010-02-12 05:25:12 +00001088public:
Anders Carlssonb9021e92010-02-27 16:18:19 +00001089 /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
1090 /// primary bases.
1091 typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
1092 PrimaryBasesSetVectorTy;
1093
Anders Carlsson57071e22010-02-12 05:25:12 +00001094private:
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001095 /// VtableInfo - Global vtable information.
1096 CGVtableInfo &VtableInfo;
1097
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001098 /// MostDerivedClass - The most derived class for which we're building this
1099 /// vtable.
1100 const CXXRecordDecl *MostDerivedClass;
1101
Anders Carlssond03a3262010-02-27 20:39:05 +00001102 /// MostDerivedClassOffset - If we're building a construction vtable, this
1103 /// holds the offset from the layout class to the most derived class.
1104 const uint64_t MostDerivedClassOffset;
1105
Anders Carlsson5d7af6b2010-02-28 00:36:23 +00001106 /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
1107 /// base. (This only makes sense when building a construction vtable).
1108 bool MostDerivedClassIsVirtual;
1109
Anders Carlssond03a3262010-02-27 20:39:05 +00001110 /// LayoutClass - The class we're using for layout information. Will be
1111 /// different than the most derived class if we're building a construction
1112 /// vtable.
1113 const CXXRecordDecl *LayoutClass;
1114
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001115 /// Context - The ASTContext which we will use for layout information.
Anders Carlsson57071e22010-02-12 05:25:12 +00001116 ASTContext &Context;
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001117
Anders Carlssonbdf73d82010-02-11 21:24:32 +00001118 /// FinalOverriders - The final overriders of the most derived class.
Anders Carlssond68c0832010-02-25 03:45:56 +00001119 const FinalOverriders Overriders;
Anders Carlssonbdf73d82010-02-11 21:24:32 +00001120
Anders Carlssondba6ef82010-02-25 22:23:13 +00001121 /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
1122 /// bases in this vtable.
1123 llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001124
Anders Carlssonbb6305b2010-03-11 06:43:12 +00001125 typedef llvm::DenseMap<const CXXRecordDecl *, int64_t>
1126 VBaseOffsetOffsetsMapTy;
1127
1128 /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
1129 /// the most derived class.
1130 VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
1131
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001132 /// Components - The components of the vtable being built.
1133 llvm::SmallVector<VtableComponent, 64> Components;
1134
Anders Carlsson822307b2010-02-11 17:18:51 +00001135 /// AddressPoints - Address points for the vtable being built.
1136 CGVtableInfo::AddressPointsMapTy AddressPoints;
1137
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001138 /// ReturnAdjustment - A return adjustment.
Anders Carlsson104f45c2010-02-12 17:37:14 +00001139 struct ReturnAdjustment {
1140 /// NonVirtual - The non-virtual adjustment from the derived object to its
1141 /// nearest virtual base.
1142 int64_t NonVirtual;
1143
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001144 /// VBaseOffsetOffset - The offset (in bytes), relative to the address point
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001145 /// of the virtual base class offset.
1146 int64_t VBaseOffsetOffset;
Anders Carlsson104f45c2010-02-12 17:37:14 +00001147
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001148 ReturnAdjustment() : NonVirtual(0), VBaseOffsetOffset(0) { }
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001149
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001150 bool isEmpty() const { return !NonVirtual && !VBaseOffsetOffset; }
Anders Carlsson5e454aa2010-03-17 20:06:32 +00001151
1152 friend bool operator==(const ReturnAdjustment &LHS,
1153 const ReturnAdjustment &RHS) {
1154 return LHS.NonVirtual == RHS.NonVirtual &&
1155 LHS.VBaseOffsetOffset == RHS.VBaseOffsetOffset;
1156 }
Anders Carlsson87e0ac82010-03-22 16:30:44 +00001157
1158 friend bool operator<(const ReturnAdjustment &LHS,
1159 const ReturnAdjustment &RHS) {
1160 if (LHS.NonVirtual < RHS.NonVirtual)
1161 return true;
1162
1163 return LHS.NonVirtual == RHS.NonVirtual &&
1164 LHS.VBaseOffsetOffset < RHS.VBaseOffsetOffset;
1165 }
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001166 };
1167
Anders Carlssonb9021e92010-02-27 16:18:19 +00001168 /// MethodInfo - Contains information about a method in a vtable.
1169 /// (Used for computing 'this' pointer adjustment thunks.
1170 struct MethodInfo {
1171 /// BaseOffset - The base offset of this method.
1172 const uint64_t BaseOffset;
1173
Anders Carlsson2bc1d3a2010-03-10 21:25:37 +00001174 /// BaseOffsetInLayoutClass - The base offset in the layout class of this
1175 /// method.
1176 const uint64_t BaseOffsetInLayoutClass;
1177
Anders Carlssonb9021e92010-02-27 16:18:19 +00001178 /// VtableIndex - The index in the vtable that this method has.
1179 /// (For destructors, this is the index of the complete destructor).
1180 const uint64_t VtableIndex;
1181
Anders Carlsson2bc1d3a2010-03-10 21:25:37 +00001182 MethodInfo(uint64_t BaseOffset, uint64_t BaseOffsetInLayoutClass,
1183 uint64_t VtableIndex)
1184 : BaseOffset(BaseOffset),
1185 BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
1186 VtableIndex(VtableIndex) { }
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001187
Anders Carlsson2bc1d3a2010-03-10 21:25:37 +00001188 MethodInfo() : BaseOffset(0), BaseOffsetInLayoutClass(0), VtableIndex(0) { }
Anders Carlssonb9021e92010-02-27 16:18:19 +00001189 };
1190
1191 typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
1192
1193 /// MethodInfoMap - The information for all methods in the vtable we're
1194 /// currently building.
1195 MethodInfoMapTy MethodInfoMap;
1196
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001197 /// ThisAdjustment - A 'this' pointer adjustment thunk.
1198 struct ThisAdjustment {
1199 /// NonVirtual - The non-virtual adjustment from the derived object to its
1200 /// nearest virtual base.
1201 int64_t NonVirtual;
1202
John McCall331a03a2010-02-26 20:22:44 +00001203 /// VCallOffsetOffset - The offset (in bytes), relative to the address point,
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001204 /// of the virtual call offset.
1205 int64_t VCallOffsetOffset;
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001206
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001207 ThisAdjustment() : NonVirtual(0), VCallOffsetOffset(0) { }
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001208
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001209 bool isEmpty() const { return !NonVirtual && !VCallOffsetOffset; }
Anders Carlsson5e454aa2010-03-17 20:06:32 +00001210
1211 friend bool operator==(const ThisAdjustment &LHS,
1212 const ThisAdjustment &RHS) {
1213 return LHS.NonVirtual == RHS.NonVirtual &&
1214 LHS.VCallOffsetOffset == RHS.VCallOffsetOffset;
1215 }
Anders Carlsson87e0ac82010-03-22 16:30:44 +00001216
1217 friend bool operator<(const ThisAdjustment &LHS,
1218 const ThisAdjustment &RHS) {
1219 if (LHS.NonVirtual < RHS.NonVirtual)
1220 return true;
1221
1222 return LHS.NonVirtual == RHS.NonVirtual &&
1223 LHS.VCallOffsetOffset < RHS.VCallOffsetOffset;
1224 }
1225
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001226 };
1227
Anders Carlssondd366812010-03-12 04:54:20 +00001228 /// ThunkInfo - The 'this' pointer adjustment as well as an optional return
1229 /// adjustment for a thunk.
1230 struct ThunkInfo {
1231 /// This - The 'this' pointer adjustment.
1232 ThisAdjustment This;
1233
1234 /// Return - The return adjustment.
1235 ReturnAdjustment Return;
1236
1237 ThunkInfo() { }
1238
1239 ThunkInfo(const ThisAdjustment &This, const ReturnAdjustment &Return)
1240 : This(This), Return(Return) { }
Anders Carlsson5e454aa2010-03-17 20:06:32 +00001241
1242 friend bool operator==(const ThunkInfo &LHS, const ThunkInfo &RHS) {
1243 return LHS.This == RHS.This && LHS.Return == RHS.Return;
1244 }
1245
Anders Carlsson87e0ac82010-03-22 16:30:44 +00001246 friend bool operator<(const ThunkInfo &LHS, const ThunkInfo &RHS) {
1247 if (LHS.This < RHS.This)
1248 return true;
1249
1250 return LHS.This == RHS.This && LHS.Return < RHS.Return;
1251 }
1252
Anders Carlsson5e454aa2010-03-17 20:06:32 +00001253 bool isEmpty() const { return This.isEmpty() && Return.isEmpty(); }
Anders Carlssondd366812010-03-12 04:54:20 +00001254 };
1255
1256 typedef llvm::DenseMap<uint64_t, ThunkInfo> ThunksInfoMapTy;
1257
1258 /// Thunks - The thunks by vtable index in the vtable currently being built.
1259 ThunksInfoMapTy Thunks;
Anders Carlssonb9021e92010-02-27 16:18:19 +00001260
Anders Carlsson5e454aa2010-03-17 20:06:32 +00001261 typedef llvm::DenseMap<const CXXMethodDecl *,
Anders Carlsson9135a842010-03-18 02:44:19 +00001262 llvm::SmallVector<ThunkInfo, 1> > MethodThunksMapTy;
Anders Carlsson5e454aa2010-03-17 20:06:32 +00001263
Anders Carlsson9135a842010-03-18 02:44:19 +00001264 /// MethodThunks - A map that contains all the thunks needed for all methods
1265 /// in the vtable currently being built.
1266 MethodThunksMapTy MethodThunks;
Anders Carlsson5e454aa2010-03-17 20:06:32 +00001267
1268 /// AddThunk - Add a thunk for the given method.
Anders Carlsson9d734f32010-03-21 20:27:14 +00001269 void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
Anders Carlsson5e454aa2010-03-17 20:06:32 +00001270
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001271 /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
1272 /// part of the vtable we're currently building.
1273 void ComputeThisAdjustments();
1274
Anders Carlssona661a542010-02-16 04:49:44 +00001275 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1276
Anders Carlssonb9021e92010-02-27 16:18:19 +00001277 /// PrimaryVirtualBases - All known virtual bases who are a primary base of
Anders Carlssonaf280c02010-02-23 03:48:14 +00001278 /// some other base.
1279 VisitedVirtualBasesSetTy PrimaryVirtualBases;
1280
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001281 /// ComputeReturnAdjustment - Compute the return adjustment given a return
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001282 /// adjustment base offset.
Anders Carlsson2fca9be2010-02-23 01:34:28 +00001283 ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001284
Anders Carlsson379017f2010-02-27 19:57:44 +00001285 /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
1286 /// the 'this' pointer from the base subobject to the derived subobject.
1287 BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1288 BaseSubobject Derived) const;
1289
Anders Carlsson60cc72a2010-02-18 17:00:09 +00001290 /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
Anders Carlsson617def32010-03-12 05:28:07 +00001291 /// given virtual member function, its offset in the layout class and its
1292 /// final overrider.
1293 ThisAdjustment
1294 ComputeThisAdjustment(const CXXMethodDecl *MD,
1295 uint64_t BaseOffsetInLayoutClass,
1296 FinalOverriders::OverriderInfo Overrider);
1297
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001298 /// AddMethod - Add a single virtual member function to the vtable
1299 /// components vector.
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001300 void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001301
Anders Carlsson464c8f12010-02-23 04:26:39 +00001302 /// IsOverriderUsed - Returns whether the overrider will ever be used in this
1303 /// part of the vtable.
1304 ///
1305 /// Itanium C++ ABI 2.5.2:
1306 ///
1307 /// struct A { virtual void f(); };
1308 /// struct B : virtual public A { int i; };
1309 /// struct C : virtual public A { int j; };
1310 /// struct D : public B, public C {};
1311 ///
1312 /// When B and C are declared, A is a primary base in each case, so although
1313 /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
1314 /// adjustment is required and no thunk is generated. However, inside D
1315 /// objects, A is no longer a primary base of C, so if we allowed calls to
1316 /// C::f() to use the copy of A's vtable in the C subobject, we would need
1317 /// to adjust this from C* to B::A*, which would require a third-party
1318 /// thunk. Since we require that a call to C::f() first convert to A*,
1319 /// C-in-D's copy of A's vtable is never referenced, so this is not
1320 /// necessary.
Anders Carlsson60396612010-03-10 06:51:42 +00001321 bool IsOverriderUsed(const CXXMethodDecl *Overrider,
1322 uint64_t BaseOffsetInLayoutClass,
1323 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1324 uint64_t FirstBaseOffsetInLayoutClass) const;
1325
Anders Carlsson464c8f12010-02-23 04:26:39 +00001326
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001327 /// AddMethods - Add the methods of this base subobject and all its
1328 /// primary bases to the vtable components vector.
Anders Carlsson60396612010-03-10 06:51:42 +00001329 void AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass,
1330 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1331 uint64_t FirstBaseOffsetInLayoutClass,
Anders Carlssonb9021e92010-02-27 16:18:19 +00001332 PrimaryBasesSetVectorTy &PrimaryBases);
Anders Carlsson89ad4212010-02-16 16:26:28 +00001333
Anders Carlsson5d7af6b2010-02-28 00:36:23 +00001334 // LayoutVtable - Layout the vtable for the given base class, including its
Anders Carlsson89ad4212010-02-16 16:26:28 +00001335 // secondary vtables and any vtables for virtual bases.
1336 void LayoutVtable();
1337
Anders Carlsson530c40c2010-02-28 01:43:58 +00001338 /// LayoutPrimaryAndSecondaryVtables - Layout the primary vtable for the
Anders Carlsson89ad4212010-02-16 16:26:28 +00001339 /// given base subobject, as well as all its secondary vtables.
Anders Carlsson530c40c2010-02-28 01:43:58 +00001340 void LayoutPrimaryAndSecondaryVtables(BaseSubobject Base,
1341 bool BaseIsVirtual,
1342 uint64_t OffsetInLayoutClass);
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001343
Anders Carlssonc7b63162010-02-16 16:02:57 +00001344 /// LayoutSecondaryVtables - Layout the secondary vtables for the given base
1345 /// subobject.
Anders Carlssona96a2e92010-03-10 19:39:11 +00001346 ///
1347 /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
1348 /// or a direct or indirect base of a virtual base.
1349 void LayoutSecondaryVtables(BaseSubobject Base, bool BaseIsMorallyVirtual,
1350 uint64_t OffsetInLayoutClass);
Anders Carlsson08c26752010-02-27 04:05:52 +00001351
1352 /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
1353 /// class hierarchy.
1354 void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
Anders Carlssond7fdae52010-03-10 03:02:01 +00001355 uint64_t OffsetInLayoutClass,
Anders Carlsson08c26752010-02-27 04:05:52 +00001356 VisitedVirtualBasesSetTy &VBases);
1357
Anders Carlsson69dc04e2010-02-16 16:49:35 +00001358 /// LayoutVtablesForVirtualBases - Layout vtables for all virtual bases of the
1359 /// given base (excluding any primary bases).
1360 void LayoutVtablesForVirtualBases(const CXXRecordDecl *RD,
1361 VisitedVirtualBasesSetTy &VBases);
1362
Anders Carlsson438bc422010-02-28 00:10:58 +00001363 /// isBuildingConstructionVtable - Return whether this vtable builder is
1364 /// building a construction vtable.
1365 bool isBuildingConstructorVtable() const {
1366 return MostDerivedClass != LayoutClass;
1367 }
1368
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001369public:
Anders Carlssond03a3262010-02-27 20:39:05 +00001370 VtableBuilder(CGVtableInfo &VtableInfo, const CXXRecordDecl *MostDerivedClass,
Anders Carlsson5d7af6b2010-02-28 00:36:23 +00001371 uint64_t MostDerivedClassOffset, bool MostDerivedClassIsVirtual,
Anders Carlssond03a3262010-02-27 20:39:05 +00001372 const CXXRecordDecl *LayoutClass)
1373 : VtableInfo(VtableInfo), MostDerivedClass(MostDerivedClass),
Anders Carlsson5d7af6b2010-02-28 00:36:23 +00001374 MostDerivedClassOffset(MostDerivedClassOffset),
1375 MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
1376 LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
Anders Carlssondb4022c2010-03-10 02:33:41 +00001377 Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001378
Anders Carlsson89ad4212010-02-16 16:26:28 +00001379 LayoutVtable();
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001380 }
1381
1382 /// dumpLayout - Dump the vtable layout.
1383 void dumpLayout(llvm::raw_ostream&);
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001384};
1385
Anders Carlsson9d734f32010-03-21 20:27:14 +00001386void VtableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
Anders Carlsson9135a842010-03-18 02:44:19 +00001387 if (isBuildingConstructorVtable())
1388 return;
1389
1390 llvm::SmallVector<ThunkInfo, 1> &ThunksVector = MethodThunks[MD];
Anders Carlsson5e454aa2010-03-17 20:06:32 +00001391
1392 // Check if we have this thunk already.
1393 if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
1394 ThunksVector.end())
1395 return;
1396
1397 ThunksVector.push_back(Thunk);
1398}
1399
Anders Carlssonc784ba22010-02-27 06:38:03 +00001400/// OverridesMethodInBases - Checks whether whether this virtual member
1401/// function overrides a member function in any of the given bases.
Anders Carlsson57071e22010-02-12 05:25:12 +00001402/// Returns the overridden member function, or null if none was found.
1403static const CXXMethodDecl *
Anders Carlssonc784ba22010-02-27 06:38:03 +00001404OverridesMethodInBases(const CXXMethodDecl *MD,
Anders Carlssonb9021e92010-02-27 16:18:19 +00001405 VtableBuilder::PrimaryBasesSetVectorTy &Bases) {
Anders Carlsson57071e22010-02-12 05:25:12 +00001406 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1407 E = MD->end_overridden_methods(); I != E; ++I) {
1408 const CXXMethodDecl *OverriddenMD = *I;
1409 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
1410 assert(OverriddenMD->isCanonicalDecl() &&
1411 "Should have the canonical decl of the overridden RD!");
1412
Anders Carlssonc784ba22010-02-27 06:38:03 +00001413 if (Bases.count(OverriddenRD))
Anders Carlsson57071e22010-02-12 05:25:12 +00001414 return OverriddenMD;
1415 }
1416
1417 return 0;
1418}
1419
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001420void VtableBuilder::ComputeThisAdjustments() {
1421 // Now go through the method info map and see if any of the methods need
1422 // 'this' pointer adjustments.
1423 for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
1424 E = MethodInfoMap.end(); I != E; ++I) {
1425 const CXXMethodDecl *MD = I->first;
1426 const MethodInfo &MethodInfo = I->second;
1427
Anders Carlsson617def32010-03-12 05:28:07 +00001428 // Ignore adjustments for unused function pointers.
1429 uint64_t VtableIndex = MethodInfo.VtableIndex;
1430 if (Components[VtableIndex].getKind() ==
1431 VtableComponent::CK_UnusedFunctionPointer)
1432 continue;
1433
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001434 // Get the final overrider for this method.
1435 FinalOverriders::OverriderInfo Overrider =
Anders Carlsson2bc1d3a2010-03-10 21:25:37 +00001436 Overriders.getOverrider(BaseSubobject(MD->getParent(),
1437 MethodInfo.BaseOffset), MD);
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001438
Anders Carlsson617def32010-03-12 05:28:07 +00001439 ThisAdjustment ThisAdjustment =
1440 ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
1441
1442 if (ThisAdjustment.isEmpty())
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001443 continue;
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001444
Anders Carlssoncd4e6372010-02-27 18:09:40 +00001445 // Add it.
Anders Carlssondd366812010-03-12 04:54:20 +00001446 Thunks[VtableIndex].This = ThisAdjustment;
Anders Carlsson617def32010-03-12 05:28:07 +00001447
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001448 if (isa<CXXDestructorDecl>(MD)) {
1449 // Add an adjustment for the deleting destructor as well.
Anders Carlssondd366812010-03-12 04:54:20 +00001450 Thunks[VtableIndex + 1].This = ThisAdjustment;
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001451 }
1452 }
1453
1454 /// Clear the method info map.
1455 MethodInfoMap.clear();
Anders Carlsson25394212010-03-22 15:47:01 +00001456
1457 if (isBuildingConstructorVtable()) {
1458 // We don't need to store thunk information for construction vtables.
1459 return;
1460 }
1461
1462 for (ThunksInfoMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
1463 I != E; ++I) {
1464 const VtableComponent &Component = Components[I->first];
1465 const ThunkInfo &Thunk = I->second;
1466
1467 switch (Component.getKind()) {
1468 default:
1469 llvm_unreachable("Unexpected vtable component kind!");
1470 case VtableComponent::CK_FunctionPointer:
1471 AddThunk(Component.getFunctionDecl(), Thunk);
1472 break;
1473 case VtableComponent::CK_CompleteDtorPointer:
1474 AddThunk(Component.getDestructorDecl(), Thunk);
1475 break;
1476 case VtableComponent::CK_DeletingDtorPointer:
1477 // We've already added the thunk when we saw the complete dtor pointer.
1478 break;
1479 }
1480 }
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001481}
1482
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001483VtableBuilder::ReturnAdjustment
Anders Carlsson2fca9be2010-02-23 01:34:28 +00001484VtableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001485 ReturnAdjustment Adjustment;
1486
1487 if (!Offset.isEmpty()) {
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001488 if (Offset.VirtualBase) {
1489 // Get the virtual base offset offset.
Anders Carlsson1972ced2010-03-11 07:00:45 +00001490 if (Offset.DerivedClass == MostDerivedClass) {
1491 // We can get the offset offset directly from our map.
1492 Adjustment.VBaseOffsetOffset =
1493 VBaseOffsetOffsets.lookup(Offset.VirtualBase);
1494 } else {
1495 Adjustment.VBaseOffsetOffset =
Anders Carlssonbba16072010-03-11 07:15:17 +00001496 VtableInfo.getVirtualBaseOffsetOffset(Offset.DerivedClass,
1497 Offset.VirtualBase);
Anders Carlsson1972ced2010-03-11 07:00:45 +00001498 }
1499
Anders Carlssonc89a7cf2010-03-11 16:06:20 +00001500 // FIXME: Once the assert in getVirtualBaseOffsetOffset is back again,
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001501 // we can get rid of this assert.
1502 assert(Adjustment.VBaseOffsetOffset != 0 &&
Anders Carlssonc89a7cf2010-03-11 16:06:20 +00001503 "Invalid vbase offset offset!");
Anders Carlsson60db0ee2010-02-13 21:07:32 +00001504 }
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001505
1506 Adjustment.NonVirtual = Offset.NonVirtualOffset;
1507 }
1508
1509 return Adjustment;
1510}
1511
Anders Carlsson379017f2010-02-27 19:57:44 +00001512BaseOffset
1513VtableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
1514 BaseSubobject Derived) const {
1515 const CXXRecordDecl *BaseRD = Base.getBase();
1516 const CXXRecordDecl *DerivedRD = Derived.getBase();
1517
1518 CXXBasePaths Paths(/*FindAmbiguities=*/true,
1519 /*RecordPaths=*/true, /*DetectVirtual=*/true);
1520
1521 if (!const_cast<CXXRecordDecl *>(DerivedRD)->
1522 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
1523 assert(false && "Class must be derived from the passed in base class!");
1524 return BaseOffset();
1525 }
1526
1527 // We have to go through all the paths, and see which one leads us to the
1528 // right base subobject.
1529 for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
1530 I != E; ++I) {
1531 BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
1532
1533 // FIXME: Should not use * 8 here.
1534 uint64_t OffsetToBaseSubobject = Offset.NonVirtualOffset * 8;
1535
1536 if (Offset.VirtualBase) {
1537 // If we have a virtual base class, the non-virtual offset is relative
1538 // to the virtual base class offset.
Anders Carlsson2bc1d3a2010-03-10 21:25:37 +00001539 const ASTRecordLayout &LayoutClassLayout =
1540 Context.getASTRecordLayout(LayoutClass);
Anders Carlsson379017f2010-02-27 19:57:44 +00001541
1542 /// Get the virtual base offset, relative to the most derived class
1543 /// layout.
1544 OffsetToBaseSubobject +=
Anders Carlsson2bc1d3a2010-03-10 21:25:37 +00001545 LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
Anders Carlsson379017f2010-02-27 19:57:44 +00001546 } else {
1547 // Otherwise, the non-virtual offset is relative to the derived class
1548 // offset.
1549 OffsetToBaseSubobject += Derived.getBaseOffset();
1550 }
1551
1552 // Check if this path gives us the right base subobject.
1553 if (OffsetToBaseSubobject == Base.getBaseOffset()) {
1554 // Since we're going from the base class _to_ the derived class, we'll
1555 // invert the non-virtual offset here.
1556 Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
1557 return Offset;
1558 }
1559 }
1560
1561 return BaseOffset();
1562}
1563
Anders Carlsson617def32010-03-12 05:28:07 +00001564VtableBuilder::ThisAdjustment
1565VtableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
1566 uint64_t BaseOffsetInLayoutClass,
1567 FinalOverriders::OverriderInfo Overrider) {
1568 // Check if we need an adjustment at all.
1569 if (BaseOffsetInLayoutClass == Overrider.Offset)
1570 return ThisAdjustment();
Anders Carlsson379017f2010-02-27 19:57:44 +00001571
Anders Carlsson617def32010-03-12 05:28:07 +00001572 // Ignore adjustments for pure virtual member functions.
1573 if (Overrider.Method->isPure())
1574 return ThisAdjustment();
1575
1576 BaseSubobject OverriddenBaseSubobject(MD->getParent(),
1577 BaseOffsetInLayoutClass);
1578
1579 BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
1580 Overrider.Offset);
1581
1582 // Compute the adjustment offset.
1583 BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
1584 OverriderBaseSubobject);
1585 if (Offset.isEmpty())
1586 return ThisAdjustment();
1587
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001588 ThisAdjustment Adjustment;
1589
Anders Carlsson617def32010-03-12 05:28:07 +00001590 if (Offset.VirtualBase) {
1591 // Get the vcall offset map for this virtual base.
1592 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
Anders Carlssoneb577d02010-02-18 17:26:40 +00001593
Anders Carlsson617def32010-03-12 05:28:07 +00001594 if (VCallOffsets.empty()) {
1595 // We don't have vcall offsets for this virtual base, go ahead and
1596 // build them.
1597 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
1598 /*FinalOverriders=*/0,
1599 BaseSubobject(Offset.VirtualBase, 0),
1600 /*BaseIsVirtual=*/true,
1601 /*OffsetInLayoutClass=*/0);
1602
1603 VCallOffsets = Builder.getVCallOffsets();
1604 }
1605
1606 Adjustment.VCallOffsetOffset = VCallOffsets.getVCallOffsetOffset(MD);
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001607 }
Anders Carlsson617def32010-03-12 05:28:07 +00001608
1609 // Set the non-virtual part of the adjustment.
1610 Adjustment.NonVirtual = Offset.NonVirtualOffset;
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001611
1612 return Adjustment;
1613}
Anders Carlsson617def32010-03-12 05:28:07 +00001614
Anders Carlsson57071e22010-02-12 05:25:12 +00001615void
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001616VtableBuilder::AddMethod(const CXXMethodDecl *MD,
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001617 ReturnAdjustment ReturnAdjustment) {
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001618 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1619 assert(ReturnAdjustment.isEmpty() &&
1620 "Destructor can't have return adjustment!");
Anders Carlsson49bac9a2010-02-13 23:40:17 +00001621
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001622 // Add both the complete destructor and the deleting destructor.
1623 Components.push_back(VtableComponent::MakeCompleteDtor(DD));
1624 Components.push_back(VtableComponent::MakeDeletingDtor(DD));
1625 } else {
1626 // Add the return adjustment if necessary.
1627 if (!ReturnAdjustment.isEmpty())
Anders Carlssondd366812010-03-12 04:54:20 +00001628 Thunks[Components.size()].Return = ReturnAdjustment;
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001629
1630 // Add the function.
1631 Components.push_back(VtableComponent::MakeFunction(MD));
1632 }
1633}
1634
Anders Carlssonc784ba22010-02-27 06:38:03 +00001635/// OverridesIndirectMethodInBase - Return whether the given member function
1636/// overrides any methods in the set of given bases.
1637/// Unlike OverridesMethodInBase, this checks "overriders of overriders".
1638/// For example, if we have:
1639///
1640/// struct A { virtual void f(); }
1641/// struct B : A { virtual void f(); }
1642/// struct C : B { virtual void f(); }
1643///
1644/// OverridesIndirectMethodInBase will return true if given C::f as the method
1645/// and { A } as the set of bases.
1646static bool
1647OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
Anders Carlssonb9021e92010-02-27 16:18:19 +00001648 VtableBuilder::PrimaryBasesSetVectorTy &Bases) {
Anders Carlssonc784ba22010-02-27 06:38:03 +00001649 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1650 E = MD->end_overridden_methods(); I != E; ++I) {
1651 const CXXMethodDecl *OverriddenMD = *I;
1652 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
1653 assert(OverriddenMD->isCanonicalDecl() &&
1654 "Should have the canonical decl of the overridden RD!");
1655
1656 if (Bases.count(OverriddenRD))
1657 return true;
1658
1659 // Check "indirect overriders".
1660 if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
1661 return true;
1662 }
1663
1664 return false;
1665}
1666
Anders Carlsson464c8f12010-02-23 04:26:39 +00001667bool
Anders Carlsson60396612010-03-10 06:51:42 +00001668VtableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
1669 uint64_t BaseOffsetInLayoutClass,
1670 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1671 uint64_t FirstBaseOffsetInLayoutClass) const {
Anders Carlsson464c8f12010-02-23 04:26:39 +00001672 // If the base and the first base in the primary base chain have the same
1673 // offsets, then this overrider will be used.
Anders Carlsson60396612010-03-10 06:51:42 +00001674 if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
Anders Carlssonf9fbc712010-02-23 06:34:44 +00001675 return true;
1676
1677 // We know now that Base (or a direct or indirect base of it) is a primary
1678 // base in part of the class hierarchy, but not a primary base in the most
1679 // derived class.
1680
1681 // If the overrider is the first base in the primary base chain, we know
1682 // that the overrider will be used.
Anders Carlsson60396612010-03-10 06:51:42 +00001683 if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
Anders Carlsson464c8f12010-02-23 04:26:39 +00001684 return true;
1685
Anders Carlssonb9021e92010-02-27 16:18:19 +00001686 VtableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Anders Carlssonf9fbc712010-02-23 06:34:44 +00001687
Anders Carlsson60396612010-03-10 06:51:42 +00001688 const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
Anders Carlssonf9fbc712010-02-23 06:34:44 +00001689 PrimaryBases.insert(RD);
1690
1691 // Now traverse the base chain, starting with the first base, until we find
1692 // the base that is no longer a primary base.
1693 while (true) {
1694 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1695 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1696
1697 if (!PrimaryBase)
1698 break;
1699
1700 if (Layout.getPrimaryBaseWasVirtual()) {
1701 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
1702 "Primary base should always be at offset 0!");
1703
Anders Carlssondad0f992010-02-28 18:37:33 +00001704 const ASTRecordLayout &LayoutClassLayout =
1705 Context.getASTRecordLayout(LayoutClass);
Anders Carlssonf9fbc712010-02-23 06:34:44 +00001706
1707 // Now check if this is the primary base that is not a primary base in the
1708 // most derived class.
Anders Carlssondad0f992010-02-28 18:37:33 +00001709 if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
Anders Carlsson60396612010-03-10 06:51:42 +00001710 FirstBaseOffsetInLayoutClass) {
Anders Carlssonf9fbc712010-02-23 06:34:44 +00001711 // We found it, stop walking the chain.
1712 break;
1713 }
1714 } else {
1715 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
1716 "Primary base should always be at offset 0!");
1717 }
Anders Carlssoncd4e6372010-02-27 18:09:40 +00001718
Anders Carlssonf89bb6c2010-02-27 19:51:04 +00001719 if (!PrimaryBases.insert(PrimaryBase))
1720 assert(false && "Found a duplicate primary base!");
1721
Anders Carlssoncd4e6372010-02-27 18:09:40 +00001722 RD = PrimaryBase;
Anders Carlssonf9fbc712010-02-23 06:34:44 +00001723 }
1724
1725 // If the final overrider is an override of one of the primary bases,
1726 // then we know that it will be used.
Anders Carlsson60396612010-03-10 06:51:42 +00001727 return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
Anders Carlsson464c8f12010-02-23 04:26:39 +00001728}
1729
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001730/// FindNearestOverriddenMethod - Given a method, returns the overridden method
1731/// from the nearest base. Returns null if no method was found.
1732static const CXXMethodDecl *
1733FindNearestOverriddenMethod(const CXXMethodDecl *MD,
1734 VtableBuilder::PrimaryBasesSetVectorTy &Bases) {
1735 for (int I = Bases.size(), E = 0; I != E; --I) {
1736 const CXXRecordDecl *PrimaryBase = Bases[I - 1];
1737
1738 // Now check the overriden methods.
1739 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1740 E = MD->end_overridden_methods(); I != E; ++I) {
1741 const CXXMethodDecl *OverriddenMD = *I;
1742
1743 // We found our overridden method.
1744 if (OverriddenMD->getParent() == PrimaryBase)
1745 return OverriddenMD;
1746 }
1747 }
1748
1749 return 0;
1750}
1751
Anders Carlsson60396612010-03-10 06:51:42 +00001752void
1753VtableBuilder::AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass,
1754 const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
1755 uint64_t FirstBaseOffsetInLayoutClass,
Anders Carlssonb9021e92010-02-27 16:18:19 +00001756 PrimaryBasesSetVectorTy &PrimaryBases) {
Anders Carlsson57071e22010-02-12 05:25:12 +00001757 const CXXRecordDecl *RD = Base.getBase();
Anders Carlsson57071e22010-02-12 05:25:12 +00001758 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1759
1760 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
Anders Carlsson60396612010-03-10 06:51:42 +00001761 uint64_t PrimaryBaseOffset;
1762 uint64_t PrimaryBaseOffsetInLayoutClass;
Anders Carlssonaf280c02010-02-23 03:48:14 +00001763 if (Layout.getPrimaryBaseWasVirtual()) {
1764 assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
1765 "Primary vbase should have a zero offset!");
1766
1767 const ASTRecordLayout &MostDerivedClassLayout =
1768 Context.getASTRecordLayout(MostDerivedClass);
1769
Anders Carlsson60396612010-03-10 06:51:42 +00001770 PrimaryBaseOffset =
1771 MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
1772
1773 const ASTRecordLayout &LayoutClassLayout =
1774 Context.getASTRecordLayout(LayoutClass);
1775
1776 PrimaryBaseOffsetInLayoutClass =
1777 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
Anders Carlssonaf280c02010-02-23 03:48:14 +00001778 } else {
Anders Carlsson57071e22010-02-12 05:25:12 +00001779 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
1780 "Primary base should have a zero offset!");
Anders Carlssonaf280c02010-02-23 03:48:14 +00001781
Anders Carlsson60396612010-03-10 06:51:42 +00001782 PrimaryBaseOffset = Base.getBaseOffset();
1783 PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
Anders Carlssonaf280c02010-02-23 03:48:14 +00001784 }
Anders Carlssondad0f992010-02-28 18:37:33 +00001785
Anders Carlsson60396612010-03-10 06:51:42 +00001786 AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
1787 PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
1788 FirstBaseOffsetInLayoutClass, PrimaryBases);
Anders Carlsson57071e22010-02-12 05:25:12 +00001789
1790 if (!PrimaryBases.insert(PrimaryBase))
1791 assert(false && "Found a duplicate primary base!");
1792 }
Anders Carlsson822307b2010-02-11 17:18:51 +00001793
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001794 // Now go through all virtual member functions and add them.
1795 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1796 E = RD->method_end(); I != E; ++I) {
1797 const CXXMethodDecl *MD = *I;
Anders Carlsson57071e22010-02-12 05:25:12 +00001798
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001799 if (!MD->isVirtual())
1800 continue;
Anders Carlsson57071e22010-02-12 05:25:12 +00001801
1802 // Get the final overrider.
Anders Carlssona7575822010-02-12 16:55:34 +00001803 FinalOverriders::OverriderInfo Overrider =
1804 Overriders.getOverrider(Base, MD);
Anders Carlsson57071e22010-02-12 05:25:12 +00001805
1806 // Check if this virtual member function overrides a method in a primary
1807 // base. If this is the case, and the return type doesn't require adjustment
1808 // then we can just use the member function from the primary base.
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001809 if (const CXXMethodDecl *OverriddenMD =
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001810 FindNearestOverriddenMethod(MD, PrimaryBases)) {
Anders Carlssondf31af12010-02-13 23:17:31 +00001811 if (ComputeReturnAdjustmentBaseOffset(Context, MD,
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001812 OverriddenMD).isEmpty()) {
1813 // Replace the method info of the overridden method with our own
1814 // method.
1815 assert(MethodInfoMap.count(OverriddenMD) &&
1816 "Did not find the overridden method!");
1817 MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
1818
1819 MethodInfo MethodInfo(Base.getBaseOffset(),
Anders Carlsson2bc1d3a2010-03-10 21:25:37 +00001820 BaseOffsetInLayoutClass,
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001821 OverriddenMethodInfo.VtableIndex);
1822
1823 assert(!MethodInfoMap.count(MD) &&
1824 "Should not have method info for this method yet!");
1825
1826 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
1827 MethodInfoMap.erase(OverriddenMD);
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001828 continue;
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001829 }
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001830 }
Anders Carlsson0c0eeb22010-02-13 02:02:03 +00001831
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001832 // Insert the method info for this method.
Anders Carlsson2bc1d3a2010-03-10 21:25:37 +00001833 MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
1834 Components.size());
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001835
1836 assert(!MethodInfoMap.count(MD) &&
1837 "Should not have method info for this method yet!");
1838 MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
Anders Carlssoncd4e6372010-02-27 18:09:40 +00001839
1840 // Check if this overrider is going to be used.
Anders Carlsson60396612010-03-10 06:51:42 +00001841 const CXXMethodDecl *OverriderMD = Overrider.Method;
1842 if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
1843 FirstBaseInPrimaryBaseChain,
1844 FirstBaseOffsetInLayoutClass)) {
Anders Carlssoncd4e6372010-02-27 18:09:40 +00001845 Components.push_back(VtableComponent::MakeUnusedFunction(OverriderMD));
1846 continue;
1847 }
Anders Carlsson464c8f12010-02-23 04:26:39 +00001848
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001849 // Check if this overrider needs a return adjustment.
Anders Carlsson2fca9be2010-02-23 01:34:28 +00001850 BaseOffset ReturnAdjustmentOffset =
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00001851 Overriders.getReturnAdjustmentOffset(Base, MD);
1852
1853 ReturnAdjustment ReturnAdjustment =
1854 ComputeReturnAdjustment(ReturnAdjustmentOffset);
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001855
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001856 AddMethod(Overrider.Method, ReturnAdjustment);
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001857 }
1858}
1859
Anders Carlsson89ad4212010-02-16 16:26:28 +00001860void VtableBuilder::LayoutVtable() {
Anders Carlsson530c40c2010-02-28 01:43:58 +00001861 LayoutPrimaryAndSecondaryVtables(BaseSubobject(MostDerivedClass, 0),
1862 MostDerivedClassIsVirtual,
1863 MostDerivedClassOffset);
Anders Carlsson89ad4212010-02-16 16:26:28 +00001864
Anders Carlsson69dc04e2010-02-16 16:49:35 +00001865 VisitedVirtualBasesSetTy VBases;
Anders Carlsson08c26752010-02-27 04:05:52 +00001866
1867 // Determine the primary virtual bases.
Anders Carlssond7fdae52010-03-10 03:02:01 +00001868 DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
1869 VBases);
Anders Carlsson08c26752010-02-27 04:05:52 +00001870 VBases.clear();
1871
Anders Carlsson69dc04e2010-02-16 16:49:35 +00001872 LayoutVtablesForVirtualBases(MostDerivedClass, VBases);
Anders Carlsson89ad4212010-02-16 16:26:28 +00001873}
1874
Anders Carlsson530c40c2010-02-28 01:43:58 +00001875void
1876VtableBuilder::LayoutPrimaryAndSecondaryVtables(BaseSubobject Base,
1877 bool BaseIsVirtual,
1878 uint64_t OffsetInLayoutClass) {
Chris Lattner04a23112010-02-17 21:42:34 +00001879 assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
Anders Carlssonb828afa2010-02-14 17:05:59 +00001880
Anders Carlsson852213e2010-02-16 04:59:55 +00001881 // Add vcall and vbase offsets for this vtable.
Anders Carlsson530c40c2010-02-28 01:43:58 +00001882 VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
1883 Base, BaseIsVirtual, OffsetInLayoutClass);
Anders Carlssond68c0832010-02-25 03:45:56 +00001884 Components.append(Builder.components_begin(), Builder.components_end());
1885
Anders Carlssondba6ef82010-02-25 22:23:13 +00001886 // Check if we need to add these vcall offsets.
1887 if (BaseIsVirtual && !Builder.getVCallOffsets().empty()) {
1888 VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
1889
1890 if (VCallOffsets.empty())
1891 VCallOffsets = Builder.getVCallOffsets();
1892 }
1893
Anders Carlssonbb6305b2010-03-11 06:43:12 +00001894 // If we're laying out the most derived class we want to keep track of the
1895 // virtual base class offset offsets.
1896 if (Base.getBase() == MostDerivedClass)
1897 VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
1898
Anders Carlsson852213e2010-02-16 04:59:55 +00001899 // Add the offset to top.
Anders Carlssone67dc302010-02-14 00:16:19 +00001900 // FIXME: We should not use / 8 here.
Anders Carlsson530c40c2010-02-28 01:43:58 +00001901 int64_t OffsetToTop = -(int64_t)(OffsetInLayoutClass -
1902 MostDerivedClassOffset) / 8;
Anders Carlsson76f1aa72010-02-13 22:05:23 +00001903 Components.push_back(VtableComponent::MakeOffsetToTop(OffsetToTop));
Anders Carlsson57071e22010-02-12 05:25:12 +00001904
1905 // Next, add the RTTI.
Anders Carlsson76f1aa72010-02-13 22:05:23 +00001906 Components.push_back(VtableComponent::MakeRTTI(MostDerivedClass));
Anders Carlsson57071e22010-02-12 05:25:12 +00001907
Anders Carlsson28cbc8b2010-02-12 07:43:48 +00001908 uint64_t AddressPoint = Components.size();
Anders Carlsson57071e22010-02-12 05:25:12 +00001909
1910 // Now go through all virtual member functions and add them.
Anders Carlssonb9021e92010-02-27 16:18:19 +00001911 PrimaryBasesSetVectorTy PrimaryBases;
Anders Carlsson60396612010-03-10 06:51:42 +00001912 AddMethods(Base, OffsetInLayoutClass, Base.getBase(), OffsetInLayoutClass,
1913 PrimaryBases);
Anders Carlsson57071e22010-02-12 05:25:12 +00001914
Anders Carlsson2ef9d6b2010-02-27 16:52:49 +00001915 // Compute 'this' pointer adjustments.
1916 ComputeThisAdjustments();
1917
Anders Carlsson28cbc8b2010-02-12 07:43:48 +00001918 // Record the address point.
Anders Carlsson530c40c2010-02-28 01:43:58 +00001919 AddressPoints.insert(std::make_pair(BaseSubobject(Base.getBase(),
1920 OffsetInLayoutClass),
1921 AddressPoint));
Anders Carlsson28cbc8b2010-02-12 07:43:48 +00001922
1923 // Record the address points for all primary bases.
Anders Carlssonb9021e92010-02-27 16:18:19 +00001924 for (PrimaryBasesSetVectorTy::const_iterator I = PrimaryBases.begin(),
Anders Carlsson28cbc8b2010-02-12 07:43:48 +00001925 E = PrimaryBases.end(); I != E; ++I) {
1926 const CXXRecordDecl *BaseDecl = *I;
1927
1928 // We know that all the primary bases have the same offset as the base
1929 // subobject.
Anders Carlsson530c40c2010-02-28 01:43:58 +00001930 BaseSubobject PrimaryBase(BaseDecl, OffsetInLayoutClass);
Anders Carlsson28cbc8b2010-02-12 07:43:48 +00001931 AddressPoints.insert(std::make_pair(PrimaryBase, AddressPoint));
1932 }
1933
Anders Carlssona96a2e92010-03-10 19:39:11 +00001934 bool BaseIsMorallyVirtual = BaseIsVirtual;
1935 if (isBuildingConstructorVtable() && Base.getBase() == MostDerivedClass)
1936 BaseIsMorallyVirtual = false;
1937
Anders Carlsson5edcc372010-02-24 16:43:12 +00001938 // Layout secondary vtables.
Anders Carlssona96a2e92010-03-10 19:39:11 +00001939 LayoutSecondaryVtables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
Anders Carlssonc7b63162010-02-16 16:02:57 +00001940}
1941
Anders Carlsson530c40c2010-02-28 01:43:58 +00001942void VtableBuilder::LayoutSecondaryVtables(BaseSubobject Base,
Anders Carlssona96a2e92010-03-10 19:39:11 +00001943 bool BaseIsMorallyVirtual,
Anders Carlsson530c40c2010-02-28 01:43:58 +00001944 uint64_t OffsetInLayoutClass) {
Anders Carlssonc7b63162010-02-16 16:02:57 +00001945 // Itanium C++ ABI 2.5.2:
1946 // Following the primary virtual table of a derived class are secondary
1947 // virtual tables for each of its proper base classes, except any primary
1948 // base(s) with which it shares its primary virtual table.
1949
1950 const CXXRecordDecl *RD = Base.getBase();
Anders Carlsson57071e22010-02-12 05:25:12 +00001951 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1952 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Anders Carlssonc7b63162010-02-16 16:02:57 +00001953
Anders Carlsson57071e22010-02-12 05:25:12 +00001954 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1955 E = RD->bases_end(); I != E; ++I) {
Anders Carlssonc7b63162010-02-16 16:02:57 +00001956 // Ignore virtual bases, we'll emit them later.
1957 if (I->isVirtual())
1958 continue;
1959
Anders Carlsson57071e22010-02-12 05:25:12 +00001960 const CXXRecordDecl *BaseDecl =
1961 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Anders Carlssonb828afa2010-02-14 17:05:59 +00001962
Anders Carlssona661a542010-02-16 04:49:44 +00001963 // Ignore bases that don't have a vtable.
1964 if (!BaseDecl->isDynamicClass())
1965 continue;
Anders Carlssonb828afa2010-02-14 17:05:59 +00001966
Anders Carlssonf2c98ce2010-03-10 19:15:26 +00001967 if (isBuildingConstructorVtable()) {
1968 // Itanium C++ ABI 2.6.4:
1969 // Some of the base class subobjects may not need construction virtual
1970 // tables, which will therefore not be present in the construction
1971 // virtual table group, even though the subobject virtual tables are
1972 // present in the main virtual table group for the complete object.
Anders Carlssona96a2e92010-03-10 19:39:11 +00001973 if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
Anders Carlssonf2c98ce2010-03-10 19:15:26 +00001974 continue;
Anders Carlssonf2c98ce2010-03-10 19:15:26 +00001975 }
1976
Anders Carlsson76f1aa72010-02-13 22:05:23 +00001977 // Get the base offset of this base.
Anders Carlsson530c40c2010-02-28 01:43:58 +00001978 uint64_t RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
1979 uint64_t BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
1980
1981 uint64_t BaseOffsetInLayoutClass = OffsetInLayoutClass + RelativeBaseOffset;
Anders Carlssonc7b63162010-02-16 16:02:57 +00001982
1983 // Don't emit a secondary vtable for a primary base. We might however want
1984 // to emit secondary vtables for other bases of this base.
1985 if (BaseDecl == PrimaryBase) {
Anders Carlsson530c40c2010-02-28 01:43:58 +00001986 LayoutSecondaryVtables(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssona96a2e92010-03-10 19:39:11 +00001987 BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
Anders Carlssonc7b63162010-02-16 16:02:57 +00001988 continue;
1989 }
Anders Carlsson76f1aa72010-02-13 22:05:23 +00001990
Anders Carlsson89ad4212010-02-16 16:26:28 +00001991 // Layout the primary vtable (and any secondary vtables) for this base.
Anders Carlsson530c40c2010-02-28 01:43:58 +00001992 LayoutPrimaryAndSecondaryVtables(BaseSubobject(BaseDecl, BaseOffset),
1993 /*BaseIsVirtual=*/false,
1994 BaseOffsetInLayoutClass);
Anders Carlsson57071e22010-02-12 05:25:12 +00001995 }
1996}
1997
Anders Carlsson69dc04e2010-02-16 16:49:35 +00001998void
Anders Carlssond7fdae52010-03-10 03:02:01 +00001999VtableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
2000 uint64_t OffsetInLayoutClass,
Anders Carlsson08c26752010-02-27 04:05:52 +00002001 VisitedVirtualBasesSetTy &VBases) {
2002 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2003
2004 // Check if this base has a primary base.
2005 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
Anders Carlsson0378bf02010-02-28 18:08:38 +00002006
2007 // Check if it's virtual.
2008 if (Layout.getPrimaryBaseWasVirtual()) {
2009 bool IsPrimaryVirtualBase = true;
2010
2011 if (isBuildingConstructorVtable()) {
2012 // Check if the base is actually a primary base in the class we use for
2013 // layout.
Anders Carlssond7fdae52010-03-10 03:02:01 +00002014 const ASTRecordLayout &LayoutClassLayout =
2015 Context.getASTRecordLayout(LayoutClass);
2016
2017 uint64_t PrimaryBaseOffsetInLayoutClass =
2018 LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
2019
2020 // We know that the base is not a primary base in the layout class if
2021 // the base offsets are different.
2022 if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
Anders Carlsson0378bf02010-02-28 18:08:38 +00002023 IsPrimaryVirtualBase = false;
2024 }
2025
2026 if (IsPrimaryVirtualBase)
2027 PrimaryVirtualBases.insert(PrimaryBase);
2028 }
Anders Carlsson08c26752010-02-27 04:05:52 +00002029 }
2030
2031 // Traverse bases, looking for more primary virtual bases.
2032 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2033 E = RD->bases_end(); I != E; ++I) {
2034 const CXXRecordDecl *BaseDecl =
2035 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2036
Anders Carlssond7fdae52010-03-10 03:02:01 +00002037 uint64_t BaseOffsetInLayoutClass;
2038
2039 if (I->isVirtual()) {
2040 if (!VBases.insert(BaseDecl))
2041 continue;
2042
2043 const ASTRecordLayout &LayoutClassLayout =
2044 Context.getASTRecordLayout(LayoutClass);
Anders Carlsson08c26752010-02-27 04:05:52 +00002045
Anders Carlssond7fdae52010-03-10 03:02:01 +00002046 BaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(BaseDecl);
2047 } else {
2048 BaseOffsetInLayoutClass =
2049 OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
2050 }
2051
2052 DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
Anders Carlsson08c26752010-02-27 04:05:52 +00002053 }
2054}
2055
2056void
Anders Carlsson69dc04e2010-02-16 16:49:35 +00002057VtableBuilder::LayoutVtablesForVirtualBases(const CXXRecordDecl *RD,
2058 VisitedVirtualBasesSetTy &VBases) {
2059 // Itanium C++ ABI 2.5.2:
2060 // Then come the virtual base virtual tables, also in inheritance graph
2061 // order, and again excluding primary bases (which share virtual tables with
2062 // the classes for which they are primary).
Anders Carlsson69dc04e2010-02-16 16:49:35 +00002063 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2064 E = RD->bases_end(); I != E; ++I) {
2065 const CXXRecordDecl *BaseDecl =
2066 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2067
Anders Carlssonaf280c02010-02-23 03:48:14 +00002068 // Check if this base needs a vtable. (If it's virtual, not a primary base
2069 // of some other class, and we haven't visited it before).
Anders Carlsson69dc04e2010-02-16 16:49:35 +00002070 if (I->isVirtual() && BaseDecl->isDynamicClass() &&
Anders Carlsson08c26752010-02-27 04:05:52 +00002071 !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
Anders Carlsson69dc04e2010-02-16 16:49:35 +00002072 const ASTRecordLayout &MostDerivedClassLayout =
2073 Context.getASTRecordLayout(MostDerivedClass);
2074 uint64_t BaseOffset =
2075 MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
2076
Anders Carlsson530c40c2010-02-28 01:43:58 +00002077 const ASTRecordLayout &LayoutClassLayout =
2078 Context.getASTRecordLayout(LayoutClass);
2079 uint64_t BaseOffsetInLayoutClass =
2080 LayoutClassLayout.getVBaseClassOffset(BaseDecl);
2081
2082 LayoutPrimaryAndSecondaryVtables(BaseSubobject(BaseDecl, BaseOffset),
2083 /*BaseIsVirtual=*/true,
2084 BaseOffsetInLayoutClass);
Anders Carlsson69dc04e2010-02-16 16:49:35 +00002085 }
2086
2087 // We only need to check the base for virtual base vtables if it actually
2088 // has virtual bases.
2089 if (BaseDecl->getNumVBases())
2090 LayoutVtablesForVirtualBases(BaseDecl, VBases);
2091 }
2092}
2093
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002094/// dumpLayout - Dump the vtable layout.
2095void VtableBuilder::dumpLayout(llvm::raw_ostream& Out) {
Anders Carlssond03a3262010-02-27 20:39:05 +00002096
Anders Carlssonbb6305b2010-03-11 06:43:12 +00002097 if (isBuildingConstructorVtable()) {
Anders Carlssond03a3262010-02-27 20:39:05 +00002098 Out << "Construction vtable for ('";
2099 Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
2100 // FIXME: Don't use / 8 .
2101 Out << MostDerivedClassOffset / 8 << ") in '";
2102 Out << LayoutClass->getQualifiedNameAsString();
Anders Carlssonbb6305b2010-03-11 06:43:12 +00002103 } else {
2104 Out << "Vtable for '";
2105 Out << MostDerivedClass->getQualifiedNameAsString();
Anders Carlssond03a3262010-02-27 20:39:05 +00002106 }
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002107 Out << "' (" << Components.size() << " entries).\n";
2108
Anders Carlsson822307b2010-02-11 17:18:51 +00002109 // Iterate through the address points and insert them into a new map where
2110 // they are keyed by the index and not the base object.
2111 // Since an address point can be shared by multiple subobjects, we use an
2112 // STL multimap.
2113 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
2114 for (CGVtableInfo::AddressPointsMapTy::const_iterator I =
2115 AddressPoints.begin(), E = AddressPoints.end(); I != E; ++I) {
2116 const BaseSubobject& Base = I->first;
2117 uint64_t Index = I->second;
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002118
Anders Carlsson822307b2010-02-11 17:18:51 +00002119 AddressPointsByIndex.insert(std::make_pair(Index, Base));
2120 }
2121
2122 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
Anders Carlsson28cbc8b2010-02-12 07:43:48 +00002123 uint64_t Index = I;
Anders Carlsson822307b2010-02-11 17:18:51 +00002124
2125 Out << llvm::format("%4d | ", I);
2126
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002127 const VtableComponent &Component = Components[I];
2128
2129 // Dump the component.
2130 switch (Component.getKind()) {
Anders Carlssond9a67042010-02-17 06:07:19 +00002131
2132 case VtableComponent::CK_VCallOffset:
2133 Out << "vcall_offset (" << Component.getVCallOffset() << ")";
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002134 break;
Anders Carlsson852213e2010-02-16 04:59:55 +00002135
2136 case VtableComponent::CK_VBaseOffset:
2137 Out << "vbase_offset (" << Component.getVBaseOffset() << ")";
2138 break;
2139
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002140 case VtableComponent::CK_OffsetToTop:
2141 Out << "offset_to_top (" << Component.getOffsetToTop() << ")";
2142 break;
2143
2144 case VtableComponent::CK_RTTI:
2145 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
2146 break;
2147
Anders Carlsson848fa642010-02-11 18:20:28 +00002148 case VtableComponent::CK_FunctionPointer: {
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002149 const CXXMethodDecl *MD = Component.getFunctionDecl();
2150
Anders Carlsson848fa642010-02-11 18:20:28 +00002151 std::string Str =
2152 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2153 MD);
2154 Out << Str;
Anders Carlsson98241422010-02-12 02:38:13 +00002155 if (MD->isPure())
2156 Out << " [pure]";
2157
Anders Carlssondd366812010-03-12 04:54:20 +00002158 ThunkInfo Thunk = Thunks.lookup(I);
2159 if (!Thunk.isEmpty()) {
2160 // If this function pointer has a return adjustment, dump it.
2161 if (!Thunk.Return.isEmpty()) {
2162 Out << "\n [return adjustment: ";
2163 Out << Thunk.Return.NonVirtual << " non-virtual";
2164
2165 if (Thunk.Return.VBaseOffsetOffset) {
2166 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2167 Out << " vbase offset offset";
2168 }
Anders Carlsson60cc72a2010-02-18 17:00:09 +00002169
Anders Carlssondd366812010-03-12 04:54:20 +00002170 Out << ']';
2171 }
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00002172
Anders Carlssondd366812010-03-12 04:54:20 +00002173 // If this function pointer has a 'this' pointer adjustment, dump it.
2174 if (!Thunk.This.isEmpty()) {
2175 Out << "\n [this adjustment: ";
2176 Out << Thunk.This.NonVirtual << " non-virtual";
2177
2178 if (Thunk.This.VCallOffsetOffset) {
2179 Out << ", " << Thunk.This.VCallOffsetOffset;
2180 Out << " vcall offset offset";
2181 }
Anders Carlsson60cc72a2010-02-18 17:00:09 +00002182
Anders Carlssondd366812010-03-12 04:54:20 +00002183 Out << ']';
2184 }
Anders Carlsson49bac9a2010-02-13 23:40:17 +00002185 }
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00002186
Anders Carlsson848fa642010-02-11 18:20:28 +00002187 break;
2188 }
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002189
Anders Carlsson6065e022010-02-19 06:03:53 +00002190 case VtableComponent::CK_CompleteDtorPointer:
Anders Carlsson848fa642010-02-11 18:20:28 +00002191 case VtableComponent::CK_DeletingDtorPointer: {
Anders Carlsson6065e022010-02-19 06:03:53 +00002192 bool IsComplete =
2193 Component.getKind() == VtableComponent::CK_CompleteDtorPointer;
2194
Anders Carlsson848fa642010-02-11 18:20:28 +00002195 const CXXDestructorDecl *DD = Component.getDestructorDecl();
2196
Anders Carlsson6065e022010-02-19 06:03:53 +00002197 Out << DD->getQualifiedNameAsString();
2198 if (IsComplete)
2199 Out << "() [complete]";
2200 else
2201 Out << "() [deleting]";
2202
Anders Carlsson98241422010-02-12 02:38:13 +00002203 if (DD->isPure())
2204 Out << " [pure]";
2205
Anders Carlssondd366812010-03-12 04:54:20 +00002206 ThunkInfo Thunk = Thunks.lookup(I);
2207 if (!Thunk.isEmpty()) {
2208 // If this destructor has a 'this' pointer adjustment, dump it.
2209 if (!Thunk.This.isEmpty()) {
2210 Out << "\n [this adjustment: ";
2211 Out << Thunk.This.NonVirtual << " non-virtual";
2212
2213 if (Thunk.This.VCallOffsetOffset) {
2214 Out << ", " << Thunk.This.VCallOffsetOffset;
2215 Out << " vcall offset offset";
2216 }
2217
2218 Out << ']';
2219 }
2220 }
Anders Carlsson6065e022010-02-19 06:03:53 +00002221
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002222 break;
2223 }
2224
Anders Carlsson1f464662010-02-19 20:08:13 +00002225 case VtableComponent::CK_UnusedFunctionPointer: {
2226 const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
2227
2228 std::string Str =
2229 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2230 MD);
2231 Out << "[unused] " << Str;
2232 if (MD->isPure())
2233 Out << " [pure]";
2234 }
2235
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002236 }
Anders Carlsson822307b2010-02-11 17:18:51 +00002237
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002238 Out << '\n';
Anders Carlssond2c3a7c2010-02-27 23:58:01 +00002239
2240 // Dump the next address point.
2241 uint64_t NextIndex = Index + 1;
2242 if (AddressPointsByIndex.count(NextIndex)) {
2243 if (AddressPointsByIndex.count(NextIndex) == 1) {
2244 const BaseSubobject &Base =
2245 AddressPointsByIndex.find(NextIndex)->second;
2246
2247 // FIXME: Instead of dividing by 8, we should be using CharUnits.
2248 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
2249 Out << ", " << Base.getBaseOffset() / 8 << ") vtable address --\n";
2250 } else {
2251 uint64_t BaseOffset =
2252 AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
2253
2254 // We store the class names in a set to get a stable order.
2255 std::set<std::string> ClassNames;
2256 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
2257 AddressPointsByIndex.lower_bound(NextIndex), E =
2258 AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
2259 assert(I->second.getBaseOffset() == BaseOffset &&
2260 "Invalid base offset!");
2261 const CXXRecordDecl *RD = I->second.getBase();
2262 ClassNames.insert(RD->getQualifiedNameAsString());
2263 }
2264
2265 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
2266 E = ClassNames.end(); I != E; ++I) {
2267 // FIXME: Instead of dividing by 8, we should be using CharUnits.
2268 Out << " -- (" << *I;
2269 Out << ", " << BaseOffset / 8 << ") vtable address --\n";
2270 }
2271 }
2272 }
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002273 }
Anders Carlssond03a3262010-02-27 20:39:05 +00002274
2275 Out << '\n';
Anders Carlssonbb6305b2010-03-11 06:43:12 +00002276
Anders Carlsson9135a842010-03-18 02:44:19 +00002277 if (isBuildingConstructorVtable())
2278 return;
2279
2280 if (MostDerivedClass->getNumVBases()) {
Anders Carlssonbb6305b2010-03-11 06:43:12 +00002281 // We store the virtual base class names and their offsets in a map to get
2282 // a stable order.
Anders Carlssonbb6305b2010-03-11 06:43:12 +00002283
Anders Carlsson9135a842010-03-18 02:44:19 +00002284 std::map<std::string, int64_t> ClassNamesAndOffsets;
Anders Carlssonbb6305b2010-03-11 06:43:12 +00002285 for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
2286 E = VBaseOffsetOffsets.end(); I != E; ++I) {
2287 std::string ClassName = I->first->getQualifiedNameAsString();
2288 int64_t OffsetOffset = I->second;
2289 ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
2290 }
Anders Carlsson9135a842010-03-18 02:44:19 +00002291
2292 Out << "Virtual base offset offsets for '";
2293 Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
2294 Out << ClassNamesAndOffsets.size();
2295 Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
Anders Carlssonbb6305b2010-03-11 06:43:12 +00002296
2297 for (std::map<std::string, int64_t>::const_iterator I =
2298 ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
2299 I != E; ++I)
2300 Out << " " << I->first << " | " << I->second << '\n';
2301
2302 Out << "\n";
2303 }
Anders Carlsson9135a842010-03-18 02:44:19 +00002304
2305 if (!MethodThunks.empty()) {
2306
2307 // We store the method names in a map to get a stable order.
2308 std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
2309
2310 for (MethodThunksMapTy::const_iterator I = MethodThunks.begin(),
2311 E = MethodThunks.end(); I != E; ++I) {
2312 const CXXMethodDecl *MD = I->first;
2313 std::string MethodName =
2314 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
2315 MD);
2316
2317 MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
2318 }
2319
2320 for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
2321 MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
2322 I != E; ++I) {
2323 const std::string &MethodName = I->first;
2324 const CXXMethodDecl *MD = I->second;
Anders Carlsson87e0ac82010-03-22 16:30:44 +00002325
2326 llvm::SmallVector<ThunkInfo, 1> ThunksVector = MethodThunks[MD];
2327 std::sort(ThunksVector.begin(), ThunksVector.end());
Anders Carlsson9135a842010-03-18 02:44:19 +00002328
2329 Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
2330 Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
2331
2332 for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
2333 const ThunkInfo &Thunk = ThunksVector[I];
2334
2335 Out << llvm::format("%4d | ", I);
2336
Anders Carlsson09daa502010-03-22 16:10:59 +00002337 // If this function pointer has a return pointer adjustment, dump it.
2338 if (!Thunk.Return.isEmpty()) {
2339 Out << "return adjustment: " << Thunk.This.NonVirtual;
2340 Out << " non-virtual";
2341 if (Thunk.Return.VBaseOffsetOffset) {
2342 Out << ", " << Thunk.Return.VBaseOffsetOffset;
2343 Out << " vbase offset offset";
2344 }
2345
2346 if (!Thunk.This.isEmpty())
2347 Out << "\n ";
2348 }
2349
Anders Carlsson9135a842010-03-18 02:44:19 +00002350 // If this function pointer has a 'this' pointer adjustment, dump it.
2351 if (!Thunk.This.isEmpty()) {
Anders Carlsson09daa502010-03-22 16:10:59 +00002352 Out << "this adjustment: ";
2353 Out << Thunk.This.NonVirtual << " non-virtual";
Anders Carlsson9135a842010-03-18 02:44:19 +00002354
2355 if (Thunk.This.VCallOffsetOffset) {
2356 Out << ", " << Thunk.This.VCallOffsetOffset;
Anders Carlsson09daa502010-03-22 16:10:59 +00002357 Out << " vcall offset offset";
Anders Carlsson9135a842010-03-18 02:44:19 +00002358 }
2359 }
2360
2361 Out << '\n';
2362 }
2363 }
2364 }
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002365}
2366
2367}
2368
2369namespace {
2370class OldVtableBuilder {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002371public:
2372 /// Index_t - Vtable index type.
2373 typedef uint64_t Index_t;
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002374 typedef std::vector<std::pair<GlobalDecl,
2375 std::pair<GlobalDecl, ThunkAdjustment> > >
2376 SavedAdjustmentsVectorTy;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002377private:
Anders Carlsson15318f42009-12-04 16:19:30 +00002378
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002379 // VtableComponents - The components of the vtable being built.
2380 typedef llvm::SmallVector<llvm::Constant *, 64> VtableComponentsVectorTy;
2381 VtableComponentsVectorTy VtableComponents;
2382
Eli Friedman152b5b12009-12-05 01:05:03 +00002383 const bool BuildVtable;
2384
Anders Carlssondbd920c2009-10-11 22:13:54 +00002385 llvm::Type *Ptr8Ty;
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00002386
2387 /// MostDerivedClass - The most derived class that this vtable is being
2388 /// built for.
2389 const CXXRecordDecl *MostDerivedClass;
2390
Mike Stumpacfd1e52009-11-13 01:54:23 +00002391 /// LayoutClass - The most derived class used for virtual base layout
2392 /// information.
2393 const CXXRecordDecl *LayoutClass;
Mike Stump4cde6262009-11-13 02:13:54 +00002394 /// LayoutOffset - The offset for Class in LayoutClass.
2395 uint64_t LayoutOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002396 /// BLayout - Layout for the most derived class that this vtable is being
2397 /// built for.
2398 const ASTRecordLayout &BLayout;
2399 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
2400 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
2401 llvm::Constant *rtti;
2402 llvm::LLVMContext &VMContext;
2403 CodeGenModule &CGM; // Per-module state.
Anders Carlsson0e881162009-12-04 03:46:21 +00002404
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002405 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCall;
Anders Carlssona0fdd912009-11-13 17:08:56 +00002406 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stumpd99a4d22010-01-26 03:42:22 +00002407 llvm::DenseMap<GlobalDecl, Index_t> VCallOffsetForVCall;
Mike Stump9e7e3c62009-11-06 23:27:42 +00002408 // This is the offset to the nearest virtual base
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002409 llvm::DenseMap<const CXXMethodDecl *, Index_t> NonVirtualOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002410 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stump94aff932009-10-27 23:46:47 +00002411
Anders Carlsson6d4ccb72009-11-26 19:54:33 +00002412 /// PureVirtualFunction - Points to __cxa_pure_virtual.
2413 llvm::Constant *PureVirtualFn;
2414
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002415 /// VtableMethods - A data structure for keeping track of methods in a vtable.
2416 /// Can add methods, override methods and iterate in vtable order.
2417 class VtableMethods {
2418 // MethodToIndexMap - Maps from a global decl to the index it has in the
2419 // Methods vector.
2420 llvm::DenseMap<GlobalDecl, uint64_t> MethodToIndexMap;
2421
2422 /// Methods - The methods, in vtable order.
2423 typedef llvm::SmallVector<GlobalDecl, 16> MethodsVectorTy;
2424 MethodsVectorTy Methods;
Eli Friedman72649ed2009-12-06 22:01:30 +00002425 MethodsVectorTy OrigMethods;
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002426
2427 public:
2428 /// AddMethod - Add a method to the vtable methods.
2429 void AddMethod(GlobalDecl GD) {
2430 assert(!MethodToIndexMap.count(GD) &&
2431 "Method has already been added!");
2432
2433 MethodToIndexMap[GD] = Methods.size();
2434 Methods.push_back(GD);
Eli Friedman72649ed2009-12-06 22:01:30 +00002435 OrigMethods.push_back(GD);
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002436 }
2437
2438 /// OverrideMethod - Replace a method with another.
2439 void OverrideMethod(GlobalDecl OverriddenGD, GlobalDecl GD) {
2440 llvm::DenseMap<GlobalDecl, uint64_t>::iterator i
2441 = MethodToIndexMap.find(OverriddenGD);
2442 assert(i != MethodToIndexMap.end() && "Did not find entry!");
2443
2444 // Get the index of the old decl.
2445 uint64_t Index = i->second;
2446
2447 // Replace the old decl with the new decl.
2448 Methods[Index] = GD;
2449
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002450 // And add the new.
2451 MethodToIndexMap[GD] = Index;
2452 }
2453
Anders Carlsson77c23e52009-12-04 15:49:02 +00002454 /// getIndex - Gives the index of a passed in GlobalDecl. Returns false if
2455 /// the index couldn't be found.
Benjamin Kramercce9fde2009-12-04 22:45:27 +00002456 bool getIndex(GlobalDecl GD, uint64_t &Index) const {
Anders Carlsson77c23e52009-12-04 15:49:02 +00002457 llvm::DenseMap<GlobalDecl, uint64_t>::const_iterator i
2458 = MethodToIndexMap.find(GD);
Eli Friedman47145832009-12-04 08:34:14 +00002459
Anders Carlsson77c23e52009-12-04 15:49:02 +00002460 if (i == MethodToIndexMap.end())
2461 return false;
Anders Carlssonc0c49932009-12-04 03:41:37 +00002462
Anders Carlsson77c23e52009-12-04 15:49:02 +00002463 Index = i->second;
2464 return true;
Anders Carlssonc0c49932009-12-04 03:41:37 +00002465 }
2466
Eli Friedman72649ed2009-12-06 22:01:30 +00002467 GlobalDecl getOrigMethod(uint64_t Index) const {
2468 return OrigMethods[Index];
2469 }
2470
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002471 MethodsVectorTy::size_type size() const {
2472 return Methods.size();
2473 }
2474
2475 void clear() {
2476 MethodToIndexMap.clear();
2477 Methods.clear();
Eli Friedman72649ed2009-12-06 22:01:30 +00002478 OrigMethods.clear();
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002479 }
2480
Anders Carlssonc0c49932009-12-04 03:41:37 +00002481 GlobalDecl operator[](uint64_t Index) const {
Anders Carlssonc7ab1a82009-12-04 02:01:07 +00002482 return Methods[Index];
2483 }
2484 };
2485
2486 /// Methods - The vtable methods we're currently building.
2487 VtableMethods Methods;
2488
Anders Carlsson98fdb242009-12-04 02:26:15 +00002489 /// ThisAdjustments - For a given index in the vtable, contains the 'this'
2490 /// pointer adjustment needed for a method.
2491 typedef llvm::DenseMap<uint64_t, ThunkAdjustment> ThisAdjustmentsMapTy;
2492 ThisAdjustmentsMapTy ThisAdjustments;
Anders Carlsson5dd730a2009-11-26 19:32:45 +00002493
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002494 SavedAdjustmentsVectorTy SavedAdjustments;
Eli Friedman72649ed2009-12-06 22:01:30 +00002495
Anders Carlssona8756702009-12-04 02:22:02 +00002496 /// BaseReturnTypes - Contains the base return types of methods who have been
2497 /// overridden with methods whose return types require adjustment. Used for
2498 /// generating covariant thunk information.
2499 typedef llvm::DenseMap<uint64_t, CanQualType> BaseReturnTypesMapTy;
2500 BaseReturnTypesMapTy BaseReturnTypes;
Anders Carlsson5dd730a2009-11-26 19:32:45 +00002501
Anders Carlssondbd920c2009-10-11 22:13:54 +00002502 std::vector<Index_t> VCalls;
Mike Stump9840c702009-11-12 20:47:57 +00002503
2504 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stump23a35422009-11-19 20:52:19 +00002505 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
2506 // vtable for use in computing the initializers for the VTT.
2507 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +00002508
Anders Carlsson1bb60992010-01-14 02:29:07 +00002509 /// AddressPoints - Address points for this vtable.
2510 CGVtableInfo::AddressPointsMapTy& AddressPoints;
2511
Anders Carlssondbd920c2009-10-11 22:13:54 +00002512 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002513 const uint32_t LLVMPointerWidth;
2514 Index_t extra;
Mike Stump11dea942009-10-15 02:04:03 +00002515 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stump23a35422009-11-19 20:52:19 +00002516 static llvm::DenseMap<CtorVtable_t, int64_t>&
2517 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
2518 const CXXRecordDecl *c) {
Anders Carlsson21431c52010-01-02 18:02:32 +00002519 CGVtableInfo::AddrMap_t *&oref = cgm.getVtableInfo().AddressPoints[l];
Mike Stump23a35422009-11-19 20:52:19 +00002520 if (oref == 0)
Anders Carlsson21431c52010-01-02 18:02:32 +00002521 oref = new CGVtableInfo::AddrMap_t;
Mike Stump23a35422009-11-19 20:52:19 +00002522
2523 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
2524 if (ref == 0)
2525 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
2526 return *ref;
2527 }
Anders Carlsson6d4ccb72009-11-26 19:54:33 +00002528
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002529 bool DclIsSame(const FunctionDecl *New, const FunctionDecl *Old) {
2530 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
2531 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
2532
2533 // C++ [temp.fct]p2:
2534 // A function template can be overloaded with other function templates
2535 // and with normal (non-template) functions.
2536 if ((OldTemplate == 0) != (NewTemplate == 0))
2537 return false;
2538
2539 // Is the function New an overload of the function Old?
2540 QualType OldQType = CGM.getContext().getCanonicalType(Old->getType());
2541 QualType NewQType = CGM.getContext().getCanonicalType(New->getType());
2542
2543 // Compare the signatures (C++ 1.3.10) of the two functions to
2544 // determine whether they are overloads. If we find any mismatch
2545 // in the signature, they are overloads.
2546
2547 // If either of these functions is a K&R-style function (no
2548 // prototype), then we consider them to have matching signatures.
2549 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
2550 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
2551 return true;
2552
2553 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
2554 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
2555
2556 // The signature of a function includes the types of its
2557 // parameters (C++ 1.3.10), which includes the presence or absence
2558 // of the ellipsis; see C++ DR 357).
2559 if (OldQType != NewQType &&
2560 (OldType->getNumArgs() != NewType->getNumArgs() ||
2561 OldType->isVariadic() != NewType->isVariadic() ||
2562 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2563 NewType->arg_type_begin())))
2564 return false;
2565
2566#if 0
2567 // C++ [temp.over.link]p4:
2568 // The signature of a function template consists of its function
2569 // signature, its return type and its template parameter list. The names
2570 // of the template parameters are significant only for establishing the
2571 // relationship between the template parameters and the rest of the
2572 // signature.
2573 //
2574 // We check the return type and template parameter lists for function
2575 // templates first; the remaining checks follow.
2576 if (NewTemplate &&
2577 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
2578 OldTemplate->getTemplateParameters(),
2579 TPL_TemplateMatch) ||
2580 OldType->getResultType() != NewType->getResultType()))
2581 return false;
2582#endif
2583
2584 // If the function is a class member, its signature includes the
2585 // cv-qualifiers (if any) on the function itself.
2586 //
2587 // As part of this, also check whether one of the member functions
2588 // is static, in which case they are not overloads (C++
2589 // 13.1p2). While not part of the definition of the signature,
2590 // this check is important to determine whether these functions
2591 // can be overloaded.
2592 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
2593 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
2594 if (OldMethod && NewMethod &&
2595 !OldMethod->isStatic() && !NewMethod->isStatic() &&
2596 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
2597 return false;
2598
2599 // The signatures match; this is not an overload.
2600 return true;
2601 }
2602
2603 typedef llvm::DenseMap<const CXXMethodDecl *, const CXXMethodDecl*>
2604 ForwardUnique_t;
2605 ForwardUnique_t ForwardUnique;
2606 llvm::DenseMap<const CXXMethodDecl*, const CXXMethodDecl*> UniqueOverrider;
2607
2608 void BuildUniqueOverrider(const CXXMethodDecl *U, const CXXMethodDecl *MD) {
2609 const CXXMethodDecl *PrevU = UniqueOverrider[MD];
2610 assert(U && "no unique overrider");
2611 if (PrevU == U)
2612 return;
2613 if (PrevU != U && PrevU != 0) {
2614 // If already set, note the two sets as the same
2615 if (0)
2616 printf("%s::%s same as %s::%s\n",
Douglas Gregoraef605d2010-02-22 16:44:27 +00002617 PrevU->getParent()->getNameAsString().c_str(),
2618 PrevU->getNameAsString().c_str(),
2619 U->getParent()->getNameAsString().c_str(),
2620 U->getNameAsString().c_str());
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002621 ForwardUnique[PrevU] = U;
2622 return;
2623 }
2624
2625 // Not set, set it now
2626 if (0)
2627 printf("marking %s::%s %p override as %s::%s\n",
Douglas Gregoraef605d2010-02-22 16:44:27 +00002628 MD->getParent()->getNameAsString().c_str(),
2629 MD->getNameAsString().c_str(),
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002630 (void*)MD,
Douglas Gregoraef605d2010-02-22 16:44:27 +00002631 U->getParent()->getNameAsString().c_str(),
2632 U->getNameAsString().c_str());
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002633 UniqueOverrider[MD] = U;
2634
2635 for (CXXMethodDecl::method_iterator mi = MD->begin_overridden_methods(),
2636 me = MD->end_overridden_methods(); mi != me; ++mi) {
2637 BuildUniqueOverrider(U, *mi);
2638 }
2639 }
2640
2641 void BuildUniqueOverriders(const CXXRecordDecl *RD) {
2642 if (0) printf("walking %s\n", RD->getNameAsCString());
2643 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2644 e = RD->method_end(); i != e; ++i) {
2645 const CXXMethodDecl *MD = *i;
2646 if (!MD->isVirtual())
2647 continue;
2648
2649 if (UniqueOverrider[MD] == 0) {
2650 // Only set this, if it hasn't been set yet.
2651 BuildUniqueOverrider(MD, MD);
2652 if (0)
2653 printf("top set is %s::%s %p\n",
Douglas Gregoraef605d2010-02-22 16:44:27 +00002654 MD->getParent()->getNameAsString().c_str(),
2655 MD->getNameAsString().c_str(),
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002656 (void*)MD);
2657 ForwardUnique[MD] = MD;
2658 }
2659 }
2660 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2661 e = RD->bases_end(); i != e; ++i) {
2662 const CXXRecordDecl *Base =
2663 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2664 BuildUniqueOverriders(Base);
2665 }
2666 }
2667
2668 static int DclCmp(const void *p1, const void *p2) {
John McCall7fe0b9e2010-02-13 01:04:05 +00002669 const CXXMethodDecl *MD1 = *(const CXXMethodDecl *const *)p1;
2670 const CXXMethodDecl *MD2 = *(const CXXMethodDecl *const *)p2;
2671
2672 return (DeclarationName::compare(MD1->getDeclName(), MD2->getDeclName()));
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002673 }
2674
2675 void MergeForwarding() {
2676 typedef llvm::SmallVector<const CXXMethodDecl *, 100> A_t;
2677 A_t A;
2678 for (ForwardUnique_t::iterator I = ForwardUnique.begin(),
2679 E = ForwardUnique.end(); I != E; ++I) {
2680 if (I->first == I->second)
2681 // Only add the roots of all trees
2682 A.push_back(I->first);
2683 }
2684 llvm::array_pod_sort(A.begin(), A.end(), DclCmp);
2685 for (A_t::iterator I = A.begin(),
2686 E = A.end(); I != E; ++I) {
2687 A_t::iterator J = I;
John McCall7fe0b9e2010-02-13 01:04:05 +00002688 while (++J != E && DclCmp(I, J) == 0)
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002689 if (DclIsSame(*I, *J)) {
Douglas Gregoraef605d2010-02-22 16:44:27 +00002690 if (0) printf("connecting %s\n", (*I)->getNameAsString().c_str());
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002691 ForwardUnique[*J] = *I;
2692 }
2693 }
2694 }
2695
2696 const CXXMethodDecl *getUnique(const CXXMethodDecl *MD) {
2697 const CXXMethodDecl *U = UniqueOverrider[MD];
2698 assert(U && "unique overrider not found");
2699 while (ForwardUnique.count(U)) {
2700 const CXXMethodDecl *NU = ForwardUnique[U];
2701 if (NU == U) break;
2702 U = NU;
2703 }
2704 return U;
2705 }
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00002706
2707 GlobalDecl getUnique(GlobalDecl GD) {
2708 const CXXMethodDecl *Unique = getUnique(cast<CXXMethodDecl>(GD.getDecl()));
2709
2710 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Unique))
2711 return GlobalDecl(CD, GD.getCtorType());
2712
2713 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Unique))
2714 return GlobalDecl(DD, GD.getDtorType());
2715
2716 return Unique;
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002717 }
2718
Anders Carlsson6d4ccb72009-11-26 19:54:33 +00002719 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
2720 llvm::Constant* getPureVirtualFn() {
2721 if (!PureVirtualFn) {
2722 const llvm::FunctionType *Ty =
2723 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
2724 /*isVarArg=*/false);
2725 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
2726 }
2727
2728 return PureVirtualFn;
2729 }
2730
Anders Carlssondbd920c2009-10-11 22:13:54 +00002731public:
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002732 OldVtableBuilder(const CXXRecordDecl *MostDerivedClass,
Eli Friedman152b5b12009-12-05 01:05:03 +00002733 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm,
Anders Carlsson1bb60992010-01-14 02:29:07 +00002734 bool build, CGVtableInfo::AddressPointsMapTy& AddressPoints)
Eli Friedman152b5b12009-12-05 01:05:03 +00002735 : BuildVtable(build), MostDerivedClass(MostDerivedClass), LayoutClass(l),
2736 LayoutOffset(lo), BLayout(cgm.getContext().getASTRecordLayout(l)),
2737 rtti(0), VMContext(cgm.getModule().getContext()),CGM(cgm),
2738 PureVirtualFn(0),
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00002739 subAddressPoints(AllocAddressPoint(cgm, l, MostDerivedClass)),
Anders Carlsson1bb60992010-01-14 02:29:07 +00002740 AddressPoints(AddressPoints),
2741 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0))
2742 {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002743 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00002744 if (BuildVtable) {
2745 QualType ClassType = CGM.getContext().getTagDeclType(MostDerivedClass);
2746 rtti = CGM.GetAddrOfRTTIDescriptor(ClassType);
2747 }
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002748 BuildUniqueOverriders(MostDerivedClass);
2749 MergeForwarding();
Anders Carlssondbd920c2009-10-11 22:13:54 +00002750 }
2751
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002752 // getVtableComponents - Returns a reference to the vtable components.
2753 const VtableComponentsVectorTy &getVtableComponents() const {
2754 return VtableComponents;
Anders Carlsson15318f42009-12-04 16:19:30 +00002755 }
2756
Anders Carlssonc997d422010-01-02 01:01:18 +00002757 llvm::DenseMap<const CXXRecordDecl *, uint64_t> &getVBIndex()
Anders Carlssondbd920c2009-10-11 22:13:54 +00002758 { return VBIndex; }
2759
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002760 SavedAdjustmentsVectorTy &getSavedAdjustments()
2761 { return SavedAdjustments; }
Eli Friedman72649ed2009-12-06 22:01:30 +00002762
Anders Carlssondbd920c2009-10-11 22:13:54 +00002763 llvm::Constant *wrap(Index_t i) {
2764 llvm::Constant *m;
2765 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
2766 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
2767 }
2768
2769 llvm::Constant *wrap(llvm::Constant *m) {
2770 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
2771 }
2772
Mike Stumpd6584902010-01-22 02:51:26 +00002773//#define D1(x)
Douglas Gregor12a91092010-02-22 16:48:26 +00002774#define D1(X) do { if (getenv("CLANG_VTABLE_DEBUG")) { X; } } while (0)
Mike Stump6a9612f2009-10-31 20:06:59 +00002775
2776 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stumpab28c132009-10-13 22:54:56 +00002777 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002778 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2779 e = RD->bases_end(); i != e; ++i) {
2780 const CXXRecordDecl *Base =
2781 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpab28c132009-10-13 22:54:56 +00002782 Index_t next_vbindex = current_vbindex;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002783 if (i->isVirtual() && !SeenVBase.count(Base)) {
2784 SeenVBase.insert(Base);
Mike Stumpab28c132009-10-13 22:54:56 +00002785 if (updateVBIndex) {
Mike Stump6a9612f2009-10-31 20:06:59 +00002786 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stumpab28c132009-10-13 22:54:56 +00002787 - 3*LLVMPointerWidth/8);
2788 VBIndex[Base] = next_vbindex;
2789 }
Mike Stump6a9612f2009-10-31 20:06:59 +00002790 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
2791 VCalls.push_back((0?700:0) + BaseOffset);
2792 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
2793 Base->getNameAsCString(),
2794 (int)-VCalls.size()-3, (int)BaseOffset,
Mike Stumpd6584902010-01-22 02:51:26 +00002795 MostDerivedClass->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00002796 }
Mike Stumpab28c132009-10-13 22:54:56 +00002797 // We also record offsets for non-virtual bases to closest enclosing
2798 // virtual base. We do this so that we don't have to search
2799 // for the nearst virtual base class when generating thunks.
2800 if (updateVBIndex && VBIndex.count(Base) == 0)
2801 VBIndex[Base] = next_vbindex;
Mike Stump6a9612f2009-10-31 20:06:59 +00002802 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002803 }
2804 }
2805
2806 void StartNewTable() {
2807 SeenVBase.clear();
2808 }
2809
Mike Stump3425b972009-10-15 09:30:16 +00002810 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
2811 Index_t Offset = 0) {
2812
2813 if (B == D)
2814 return Offset;
2815
2816 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
2817 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
2818 e = D->bases_end(); i != e; ++i) {
2819 const CXXRecordDecl *Base =
2820 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2821 int64_t BaseOffset = 0;
2822 if (!i->isVirtual())
2823 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
2824 int64_t o = getNVOffset_1(Base, B, BaseOffset);
2825 if (o >= 0)
2826 return o;
2827 }
2828
2829 return -1;
2830 }
2831
2832 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
2833 /// derived class D.
2834 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +00002835 qD = qD->getPointeeType();
2836 qB = qB->getPointeeType();
Mike Stump3425b972009-10-15 09:30:16 +00002837 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
2838 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
2839 int64_t o = getNVOffset_1(D, B);
2840 if (o >= 0)
2841 return o;
2842
2843 assert(false && "FIXME: non-virtual base not found");
2844 return 0;
2845 }
2846
Anders Carlssondbd920c2009-10-11 22:13:54 +00002847 /// getVbaseOffset - Returns the index into the vtable for the virtual base
2848 /// offset for the given (B) virtual base of the derived class D.
2849 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +00002850 qD = qD->getPointeeType();
2851 qB = qB->getPointeeType();
Anders Carlssondbd920c2009-10-11 22:13:54 +00002852 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
2853 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00002854 if (D != MostDerivedClass)
Anders Carlssonbba16072010-03-11 07:15:17 +00002855 return CGM.getVtableInfo().getVirtualBaseOffsetOffset(D, B);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002856 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
2857 i = VBIndex.find(B);
2858 if (i != VBIndex.end())
2859 return i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002860
Mike Stumpab28c132009-10-13 22:54:56 +00002861 assert(false && "FIXME: Base not found");
Anders Carlssondbd920c2009-10-11 22:13:54 +00002862 return 0;
2863 }
2864
Eli Friedman367d1222009-12-04 08:40:51 +00002865 bool OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
2866 Index_t OverrideOffset, Index_t Offset,
2867 int64_t CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002868
Anders Carlssonadfa2672009-12-04 02:39:04 +00002869 /// AppendMethods - Append the current methods to the vtable.
Anders Carlssonbf540272009-12-04 02:56:03 +00002870 void AppendMethodsToVtable();
Anders Carlssonadfa2672009-12-04 02:39:04 +00002871
Anders Carlssona0fdd912009-11-13 17:08:56 +00002872 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
2873 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2874
Anders Carlssonecf282b2009-11-24 05:08:52 +00002875 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump1ae31782009-10-27 23:36:26 +00002876
Mike Stumpc085a982009-12-03 16:55:20 +00002877 return wrap(CGM.GetAddrOfFunction(GD, Ty));
Mike Stump1ae31782009-10-27 23:36:26 +00002878 }
2879
Mike Stump9e7e3c62009-11-06 23:27:42 +00002880 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
2881 int64_t CurrentVBaseOffset) {
Mike Stump11dea942009-10-15 02:04:03 +00002882 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlssondbd920c2009-10-11 22:13:54 +00002883 e = Path->rend(); i != e; ++i) {
2884 const CXXRecordDecl *RD = i->first;
Mike Stump3425b972009-10-15 09:30:16 +00002885 int64_t OverrideOffset = i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002886 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
2887 ++mi) {
Anders Carlssona0fdd912009-11-13 17:08:56 +00002888 const CXXMethodDecl *MD = *mi;
2889
2890 if (!MD->isVirtual())
Anders Carlssondbd920c2009-10-11 22:13:54 +00002891 continue;
2892
Anders Carlssona0fdd912009-11-13 17:08:56 +00002893 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2894 // Override both the complete and the deleting destructor.
2895 GlobalDecl CompDtor(DD, Dtor_Complete);
Eli Friedman367d1222009-12-04 08:40:51 +00002896 OverrideMethod(CompDtor, MorallyVirtual, OverrideOffset, Offset,
2897 CurrentVBaseOffset);
2898
Anders Carlssona0fdd912009-11-13 17:08:56 +00002899 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
Eli Friedman367d1222009-12-04 08:40:51 +00002900 OverrideMethod(DeletingDtor, MorallyVirtual, OverrideOffset, Offset,
2901 CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +00002902 } else {
Eli Friedman367d1222009-12-04 08:40:51 +00002903 OverrideMethod(MD, MorallyVirtual, OverrideOffset, Offset,
2904 CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +00002905 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00002906 }
2907 }
2908 }
2909
Anders Carlssona0fdd912009-11-13 17:08:56 +00002910 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman76ed1f72009-11-30 01:19:33 +00002911 int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002912 // If we can find a previously allocated slot for this, reuse it.
Eli Friedman367d1222009-12-04 08:40:51 +00002913 if (OverrideMethod(GD, MorallyVirtual, Offset, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +00002914 CurrentVBaseOffset))
Anders Carlssondbd920c2009-10-11 22:13:54 +00002915 return;
2916
Mike Stump372ade22010-01-22 18:48:47 +00002917 D1(printf(" vfn for %s at %d\n",
Douglas Gregoraef605d2010-02-22 16:44:27 +00002918 dyn_cast<CXXMethodDecl>(GD.getDecl())->getNameAsString().c_str(),
Mike Stump372ade22010-01-22 18:48:47 +00002919 (int)Methods.size()));
2920
Anders Carlssona7f19112009-12-04 02:08:24 +00002921 // We didn't find an entry in the vtable that we could use, add a new
2922 // entry.
2923 Methods.AddMethod(GD);
2924
Mike Stump15189fb2010-01-26 21:35:27 +00002925 VCallOffset[GD] = Offset/8 - CurrentVBaseOffset/8;
2926
Anders Carlssondbd920c2009-10-11 22:13:54 +00002927 if (MorallyVirtual) {
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00002928 GlobalDecl UGD = getUnique(GD);
2929 const CXXMethodDecl *UMD = cast<CXXMethodDecl>(UGD.getDecl());
2930
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002931 assert(UMD && "final overrider not found");
2932
2933 Index_t &idx = VCall[UMD];
Anders Carlssondbd920c2009-10-11 22:13:54 +00002934 // Allocate the first one, after that, we reuse the previous one.
2935 if (idx == 0) {
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00002936 VCallOffsetForVCall[UGD] = Offset/8;
Mike Stump15189fb2010-01-26 21:35:27 +00002937 NonVirtualOffset[UMD] = Offset/8 - CurrentVBaseOffset/8;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002938 idx = VCalls.size()+1;
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002939 VCalls.push_back(Offset/8 - CurrentVBaseOffset/8);
Mike Stump6a9612f2009-10-31 20:06:59 +00002940 D1(printf(" vcall for %s at %d with delta %d\n",
Douglas Gregoraef605d2010-02-22 16:44:27 +00002941 dyn_cast<CXXMethodDecl>(GD.getDecl())->getNameAsString().c_str(),
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00002942 (int)-VCalls.size()-3, (int)VCalls[idx-1]));
Anders Carlssondbd920c2009-10-11 22:13:54 +00002943 }
2944 }
2945 }
2946
2947 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +00002948 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002949 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssona0fdd912009-11-13 17:08:56 +00002950 ++mi) {
2951 const CXXMethodDecl *MD = *mi;
2952 if (!MD->isVirtual())
2953 continue;
2954
2955 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
2956 // For destructors, add both the complete and the deleting destructor
2957 // to the vtable.
2958 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +00002959 CurrentVBaseOffset);
Eli Friedman76ed1f72009-11-30 01:19:33 +00002960 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
2961 CurrentVBaseOffset);
2962 } else
2963 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +00002964 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00002965 }
2966
2967 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
2968 const CXXRecordDecl *PrimaryBase,
2969 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +00002970 int64_t Offset, int64_t CurrentVBaseOffset,
2971 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +00002972 Path->push_back(std::make_pair(RD, Offset));
Anders Carlssondbd920c2009-10-11 22:13:54 +00002973 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2974 e = RD->bases_end(); i != e; ++i) {
2975 if (i->isVirtual())
2976 continue;
2977 const CXXRecordDecl *Base =
2978 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpfc9f16c2010-01-22 06:45:05 +00002979 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
2980 StartNewTable();
2981 GenerateVtableForBase(Base, o, MorallyVirtual, false,
2982 true, Base == PrimaryBase && !PrimaryBaseWasVirtual,
2983 CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002984 }
Mike Stump11dea942009-10-15 02:04:03 +00002985 Path->pop_back();
Anders Carlssondbd920c2009-10-11 22:13:54 +00002986 }
2987
Mike Stump0ca42792009-10-14 18:14:51 +00002988// #define D(X) do { X; } while (0)
2989#define D(X)
2990
2991 void insertVCalls(int InsertionPoint) {
Mike Stump6a9612f2009-10-31 20:06:59 +00002992 D1(printf("============= combining vbase/vcall\n"));
Mike Stump0ca42792009-10-14 18:14:51 +00002993 D(VCalls.insert(VCalls.begin(), 673));
2994 D(VCalls.push_back(672));
Eli Friedman152b5b12009-12-05 01:05:03 +00002995
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002996 VtableComponents.insert(VtableComponents.begin() + InsertionPoint,
2997 VCalls.size(), 0);
Eli Friedman152b5b12009-12-05 01:05:03 +00002998 if (BuildVtable) {
2999 // The vcalls come first...
3000 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
3001 e = VCalls.rend();
3002 i != e; ++i)
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003003 VtableComponents[InsertionPoint++] = wrap((0?600:0) + *i);
Eli Friedman152b5b12009-12-05 01:05:03 +00003004 }
Mike Stump0ca42792009-10-14 18:14:51 +00003005 VCalls.clear();
Mike Stumpfbfb52d2009-11-10 02:30:51 +00003006 VCall.clear();
Mike Stump15189fb2010-01-26 21:35:27 +00003007 VCallOffsetForVCall.clear();
3008 VCallOffset.clear();
3009 NonVirtualOffset.clear();
Mike Stump0ca42792009-10-14 18:14:51 +00003010 }
3011
Mike Stump65d0e282009-11-13 23:13:20 +00003012 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
3013 Index_t AddressPoint) {
3014 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
Mike Stumpd6584902010-01-22 02:51:26 +00003015 RD->getNameAsCString(), MostDerivedClass->getNameAsCString(),
Mike Stump65d0e282009-11-13 23:13:20 +00003016 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +00003017 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Anders Carlsson1bb60992010-01-14 02:29:07 +00003018 AddressPoints[BaseSubobject(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +00003019
3020 // Now also add the address point for all our primary bases.
3021 while (1) {
3022 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3023 RD = Layout.getPrimaryBase();
3024 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
3025 // FIXME: Double check this.
3026 if (RD == 0)
3027 break;
3028 if (PrimaryBaseWasVirtual &&
3029 BLayout.getVBaseClassOffset(RD) != Offset)
3030 break;
3031 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
Mike Stumpd6584902010-01-22 02:51:26 +00003032 RD->getNameAsCString(), MostDerivedClass->getNameAsCString(),
Mike Stump65d0e282009-11-13 23:13:20 +00003033 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +00003034 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Anders Carlsson1bb60992010-01-14 02:29:07 +00003035 AddressPoints[BaseSubobject(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +00003036 }
3037 }
3038
3039
Mike Stump8cc4f102009-12-24 07:29:41 +00003040 void FinishGenerateVtable(const CXXRecordDecl *RD,
3041 const ASTRecordLayout &Layout,
3042 const CXXRecordDecl *PrimaryBase,
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003043 bool ForNPNVBases, bool WasPrimaryBase,
Mike Stump8cc4f102009-12-24 07:29:41 +00003044 bool PrimaryBaseWasVirtual,
3045 bool MorallyVirtual, int64_t Offset,
3046 bool ForVirtualBase, int64_t CurrentVBaseOffset,
3047 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +00003048 bool alloc = false;
3049 if (Path == 0) {
3050 alloc = true;
3051 Path = new Path_t;
3052 }
3053
Anders Carlssondbd920c2009-10-11 22:13:54 +00003054 StartNewTable();
3055 extra = 0;
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003056 Index_t AddressPoint = 0;
3057 int VCallInsertionPoint = 0;
3058 if (!ForNPNVBases || !WasPrimaryBase) {
3059 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
3060 VCallInsertionPoint = VtableComponents.size();
3061 if (!DeferVCalls) {
3062 insertVCalls(VCallInsertionPoint);
3063 } else
3064 // FIXME: just for extra, or for all uses of VCalls.size post this?
3065 extra = -VCalls.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +00003066
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003067 // Add the offset to top.
3068 VtableComponents.push_back(BuildVtable ? wrap(-((Offset-LayoutOffset)/8)) : 0);
Anders Carlsson15318f42009-12-04 16:19:30 +00003069
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003070 // Add the RTTI information.
3071 VtableComponents.push_back(rtti);
Anders Carlsson15318f42009-12-04 16:19:30 +00003072
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003073 AddressPoint = VtableComponents.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +00003074
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003075 AppendMethodsToVtable();
3076 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00003077
3078 // and then the non-virtual bases.
3079 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +00003080 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stump0ca42792009-10-14 18:14:51 +00003081
3082 if (ForVirtualBase) {
Mike Stump9840c702009-11-12 20:47:57 +00003083 // FIXME: We're adding to VCalls in callers, we need to do the overrides
3084 // in the inner part, so that we know the complete set of vcalls during
3085 // the build and don't have to insert into methods. Saving out the
3086 // AddressPoint here, would need to be fixed, if we didn't do that. Also
3087 // retroactively adding vcalls for overrides later wind up in the wrong
3088 // place, the vcall slot has to be alloted during the walk of the base
3089 // when the function is first introduces.
Mike Stump0ca42792009-10-14 18:14:51 +00003090 AddressPoint += VCalls.size();
Mike Stump9840c702009-11-12 20:47:57 +00003091 insertVCalls(VCallInsertionPoint);
Mike Stump0ca42792009-10-14 18:14:51 +00003092 }
3093
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003094 if (!ForNPNVBases || !WasPrimaryBase)
3095 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump9840c702009-11-12 20:47:57 +00003096
Mike Stump11dea942009-10-15 02:04:03 +00003097 if (alloc) {
3098 delete Path;
3099 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00003100 }
3101
Mike Stump6a9612f2009-10-31 20:06:59 +00003102 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
3103 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +00003104 int64_t CurrentVBaseOffset) {
Mike Stump6a9612f2009-10-31 20:06:59 +00003105 if (!RD->isDynamicClass())
3106 return;
3107
3108 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3109 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3110 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
3111
3112 // vtables are composed from the chain of primaries.
Eli Friedmandfe33bb2009-12-04 08:52:11 +00003113 if (PrimaryBase && !PrimaryBaseWasVirtual) {
Mike Stump6a9612f2009-10-31 20:06:59 +00003114 D1(printf(" doing primaries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00003115 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Eli Friedmandfe33bb2009-12-04 08:52:11 +00003116 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
3117 updateVBIndex, current_vbindex, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +00003118 }
3119
3120 D1(printf(" doing vcall entries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00003121 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +00003122
3123 // And add the virtuals for the class to the primary vtable.
Eli Friedman76ed1f72009-11-30 01:19:33 +00003124 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +00003125 }
3126
3127 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
3128 bool updateVBIndex, Index_t current_vbindex,
Mike Stump9e7e3c62009-11-06 23:27:42 +00003129 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman76ed1f72009-11-30 01:19:33 +00003130 bool bottom) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00003131 if (!RD->isDynamicClass())
3132 return;
3133
3134 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3135 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3136 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
3137
3138 // vtables are composed from the chain of primaries.
3139 if (PrimaryBase) {
Mike Stump9e7e3c62009-11-06 23:27:42 +00003140 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
3141 if (PrimaryBaseWasVirtual) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00003142 IndirectPrimary.insert(PrimaryBase);
Mike Stump9e7e3c62009-11-06 23:27:42 +00003143 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
3144 }
Mike Stump6a9612f2009-10-31 20:06:59 +00003145
3146 D1(printf(" doing primaries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00003147 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +00003148
3149 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +00003150 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +00003151 BaseCurrentVBaseOffset, false);
Anders Carlssondbd920c2009-10-11 22:13:54 +00003152 }
3153
Mike Stump6a9612f2009-10-31 20:06:59 +00003154 D1(printf(" doing vbase entries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00003155 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +00003156 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
3157
3158 if (RDisVirtualBase || bottom) {
3159 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +00003160 CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +00003161 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00003162 }
3163
Mike Stump8cc4f102009-12-24 07:29:41 +00003164 void GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
3165 bool MorallyVirtual = false,
3166 bool ForVirtualBase = false,
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003167 bool ForNPNVBases = false,
3168 bool WasPrimaryBase = true,
Mike Stump8cc4f102009-12-24 07:29:41 +00003169 int CurrentVBaseOffset = 0,
3170 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00003171 if (!RD->isDynamicClass())
Mike Stump8cc4f102009-12-24 07:29:41 +00003172 return;
Anders Carlssondbd920c2009-10-11 22:13:54 +00003173
Mike Stump92774d12009-11-13 02:35:38 +00003174 // Construction vtable don't need parts that have no virtual bases and
3175 // aren't morally virtual.
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00003176 if ((LayoutClass != MostDerivedClass) &&
3177 RD->getNumVBases() == 0 && !MorallyVirtual)
Mike Stump8cc4f102009-12-24 07:29:41 +00003178 return;
Mike Stump92774d12009-11-13 02:35:38 +00003179
Anders Carlssondbd920c2009-10-11 22:13:54 +00003180 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3181 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3182 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
3183
Anders Carlssondbd920c2009-10-11 22:13:54 +00003184 extra = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +00003185 D1(printf("building entries for base %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00003186 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00003187
Mike Stump6a9612f2009-10-31 20:06:59 +00003188 if (ForVirtualBase)
3189 extra = VCalls.size();
3190
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003191 if (!ForNPNVBases || !WasPrimaryBase) {
3192 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0,
3193 ForVirtualBase, CurrentVBaseOffset, true);
Anders Carlssondbd920c2009-10-11 22:13:54 +00003194
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003195 if (Path)
3196 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
3197 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00003198
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003199 FinishGenerateVtable(RD, Layout, PrimaryBase, ForNPNVBases, WasPrimaryBase,
3200 PrimaryBaseWasVirtual, MorallyVirtual, Offset,
3201 ForVirtualBase, CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +00003202 }
3203
3204 void GenerateVtableForVBases(const CXXRecordDecl *RD,
3205 int64_t Offset = 0,
Mike Stump11dea942009-10-15 02:04:03 +00003206 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00003207 bool alloc = false;
3208 if (Path == 0) {
3209 alloc = true;
Mike Stump11dea942009-10-15 02:04:03 +00003210 Path = new Path_t;
Anders Carlssondbd920c2009-10-11 22:13:54 +00003211 }
3212 // FIXME: We also need to override using all paths to a virtual base,
3213 // right now, we just process the first path
3214 Path->push_back(std::make_pair(RD, Offset));
3215 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
3216 e = RD->bases_end(); i != e; ++i) {
3217 const CXXRecordDecl *Base =
3218 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
3219 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
3220 // Mark it so we don't output it twice.
3221 IndirectPrimary.insert(Base);
3222 StartNewTable();
Mike Stump0ca42792009-10-14 18:14:51 +00003223 VCall.clear();
Anders Carlssondbd920c2009-10-11 22:13:54 +00003224 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9e7e3c62009-11-06 23:27:42 +00003225 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump6a9612f2009-10-31 20:06:59 +00003226 D1(printf("vtable %s virtual base %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00003227 MostDerivedClass->getNameAsCString(), Base->getNameAsCString()));
Mike Stumpfc9f16c2010-01-22 06:45:05 +00003228 GenerateVtableForBase(Base, BaseOffset, true, true, false,
3229 true, CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +00003230 }
Mike Stump9840c702009-11-12 20:47:57 +00003231 int64_t BaseOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +00003232 if (i->isVirtual())
3233 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9840c702009-11-12 20:47:57 +00003234 else {
3235 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3236 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
3237 }
3238
Mike Stump11dea942009-10-15 02:04:03 +00003239 if (Base->getNumVBases()) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00003240 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump11dea942009-10-15 02:04:03 +00003241 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00003242 }
3243 Path->pop_back();
3244 if (alloc)
3245 delete Path;
3246 }
3247};
Anders Carlsson27682a32009-12-03 01:54:02 +00003248} // end anonymous namespace
3249
Anders Carlsson824d7ea2010-02-11 08:02:13 +00003250bool OldVtableBuilder::OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
Eli Friedman367d1222009-12-04 08:40:51 +00003251 Index_t OverrideOffset, Index_t Offset,
3252 int64_t CurrentVBaseOffset) {
Anders Carlsson27682a32009-12-03 01:54:02 +00003253 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
3254
3255 const bool isPure = MD->isPure();
Anders Carlsson7ca46432009-12-05 17:04:47 +00003256
Anders Carlsson27682a32009-12-03 01:54:02 +00003257 // FIXME: Should OverrideOffset's be Offset?
3258
Anders Carlsson7ca46432009-12-05 17:04:47 +00003259 for (CXXMethodDecl::method_iterator mi = MD->begin_overridden_methods(),
3260 e = MD->end_overridden_methods(); mi != e; ++mi) {
Anders Carlsson27682a32009-12-03 01:54:02 +00003261 GlobalDecl OGD;
Mike Stump15189fb2010-01-26 21:35:27 +00003262 GlobalDecl OGD2;
Anders Carlsson27682a32009-12-03 01:54:02 +00003263
Anders Carlsson3aaf4862009-12-04 05:51:56 +00003264 const CXXMethodDecl *OMD = *mi;
Anders Carlsson27682a32009-12-03 01:54:02 +00003265 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
3266 OGD = GlobalDecl(DD, GD.getDtorType());
3267 else
3268 OGD = OMD;
Eli Friedman47145832009-12-04 08:34:14 +00003269
Eli Friedman72649ed2009-12-06 22:01:30 +00003270 // Check whether this is the method being overridden in this section of
3271 // the vtable.
Anders Carlsson77c23e52009-12-04 15:49:02 +00003272 uint64_t Index;
3273 if (!Methods.getIndex(OGD, Index))
Eli Friedman47145832009-12-04 08:34:14 +00003274 continue;
3275
Mike Stump15189fb2010-01-26 21:35:27 +00003276 OGD2 = OGD;
3277
Eli Friedman72649ed2009-12-06 22:01:30 +00003278 // Get the original method, which we should be computing thunks, etc,
3279 // against.
3280 OGD = Methods.getOrigMethod(Index);
3281 OMD = cast<CXXMethodDecl>(OGD.getDecl());
3282
Eli Friedman47145832009-12-04 08:34:14 +00003283 QualType ReturnType =
3284 MD->getType()->getAs<FunctionType>()->getResultType();
3285 QualType OverriddenReturnType =
3286 OMD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlsson27682a32009-12-03 01:54:02 +00003287
Eli Friedman47145832009-12-04 08:34:14 +00003288 // Check if we need a return type adjustment.
Anders Carlssondf31af12010-02-13 23:17:31 +00003289 if (!ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD,
3290 OMD).isEmpty()) {
Eli Friedman47145832009-12-04 08:34:14 +00003291 CanQualType &BaseReturnType = BaseReturnTypes[Index];
Anders Carlsson27682a32009-12-03 01:54:02 +00003292
Eli Friedman47145832009-12-04 08:34:14 +00003293 // Insert the base return type.
3294 if (BaseReturnType.isNull())
3295 BaseReturnType =
3296 CGM.getContext().getCanonicalType(OverriddenReturnType);
3297 }
Anders Carlssondd454be2009-12-04 03:52:52 +00003298
Eli Friedman47145832009-12-04 08:34:14 +00003299 Methods.OverrideMethod(OGD, GD);
3300
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00003301 GlobalDecl UGD = getUnique(GD);
3302 const CXXMethodDecl *UMD = cast<CXXMethodDecl>(UGD.getDecl());
3303 assert(UGD.getDecl() && "unique overrider not found");
3304 assert(UGD == getUnique(OGD) && "unique overrider not unique");
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00003305
Eli Friedman47145832009-12-04 08:34:14 +00003306 ThisAdjustments.erase(Index);
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00003307 if (MorallyVirtual || VCall.count(UMD)) {
Mike Stump15189fb2010-01-26 21:35:27 +00003308
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00003309 Index_t &idx = VCall[UMD];
Eli Friedman47145832009-12-04 08:34:14 +00003310 if (idx == 0) {
Mike Stump15189fb2010-01-26 21:35:27 +00003311 VCallOffset[GD] = VCallOffset[OGD];
3312 // NonVirtualOffset[UMD] = CurrentVBaseOffset/8 - OverrideOffset/8;
3313 NonVirtualOffset[UMD] = VCallOffset[OGD];
Mike Stumpd99a4d22010-01-26 03:42:22 +00003314 VCallOffsetForVCall[UMD] = OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00003315 idx = VCalls.size()+1;
Mike Stumpd99a4d22010-01-26 03:42:22 +00003316 VCalls.push_back(OverrideOffset/8 - CurrentVBaseOffset/8);
Eli Friedman47145832009-12-04 08:34:14 +00003317 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
3318 MD->getNameAsString().c_str(), (int)-idx-3,
Mike Stumpd6584902010-01-22 02:51:26 +00003319 (int)VCalls[idx-1], MostDerivedClass->getNameAsCString()));
Eli Friedman47145832009-12-04 08:34:14 +00003320 } else {
Mike Stump15189fb2010-01-26 21:35:27 +00003321 VCallOffset[GD] = NonVirtualOffset[UMD];
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00003322 VCalls[idx-1] = -VCallOffsetForVCall[UGD] + OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00003323 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
3324 MD->getNameAsString().c_str(), (int)-idx-3,
Mike Stumpd6584902010-01-22 02:51:26 +00003325 (int)VCalls[idx-1], MostDerivedClass->getNameAsCString()));
Eli Friedman47145832009-12-04 08:34:14 +00003326 }
Mike Stump15189fb2010-01-26 21:35:27 +00003327 int64_t NonVirtualAdjustment = -VCallOffset[OGD];
Mike Stump852f5ce2010-01-26 22:44:01 +00003328 QualType DerivedType = MD->getThisType(CGM.getContext());
3329 QualType BaseType = cast<const CXXMethodDecl>(OGD.getDecl())->getThisType(CGM.getContext());
3330 int64_t NonVirtualAdjustment2 = -(getNVOffset(BaseType, DerivedType)/8);
3331 if (NonVirtualAdjustment2 != NonVirtualAdjustment) {
3332 NonVirtualAdjustment = NonVirtualAdjustment2;
3333 }
Eli Friedman47145832009-12-04 08:34:14 +00003334 int64_t VirtualAdjustment =
3335 -((idx + extra + 2) * LLVMPointerWidth / 8);
Anders Carlsson891bb4b2009-12-03 02:32:59 +00003336
Eli Friedman47145832009-12-04 08:34:14 +00003337 // Optimize out virtual adjustments of 0.
3338 if (VCalls[idx-1] == 0)
3339 VirtualAdjustment = 0;
Anders Carlsson891bb4b2009-12-03 02:32:59 +00003340
Eli Friedman47145832009-12-04 08:34:14 +00003341 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
3342 VirtualAdjustment);
Anders Carlssonbc0e3392009-12-03 02:22:59 +00003343
Eli Friedman72649ed2009-12-06 22:01:30 +00003344 if (!isPure && !ThisAdjustment.isEmpty()) {
Eli Friedman47145832009-12-04 08:34:14 +00003345 ThisAdjustments[Index] = ThisAdjustment;
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003346 SavedAdjustments.push_back(
3347 std::make_pair(GD, std::make_pair(OGD, ThisAdjustment)));
Eli Friedman72649ed2009-12-06 22:01:30 +00003348 }
Anders Carlsson27682a32009-12-03 01:54:02 +00003349 return true;
3350 }
Eli Friedman47145832009-12-04 08:34:14 +00003351
Mike Stump15189fb2010-01-26 21:35:27 +00003352 VCallOffset[GD] = VCallOffset[OGD2] - OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00003353
Mike Stump15189fb2010-01-26 21:35:27 +00003354 int64_t NonVirtualAdjustment = -VCallOffset[GD];
3355 QualType DerivedType = MD->getThisType(CGM.getContext());
3356 QualType BaseType = cast<const CXXMethodDecl>(OGD.getDecl())->getThisType(CGM.getContext());
3357 int64_t NonVirtualAdjustment2 = -(getNVOffset(BaseType, DerivedType)/8);
3358 if (NonVirtualAdjustment2 != NonVirtualAdjustment) {
3359 NonVirtualAdjustment = NonVirtualAdjustment2;
3360 }
3361
Eli Friedman47145832009-12-04 08:34:14 +00003362 if (NonVirtualAdjustment) {
3363 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
3364
Eli Friedmanf062d9d2009-12-06 22:33:51 +00003365 if (!isPure) {
Eli Friedman47145832009-12-04 08:34:14 +00003366 ThisAdjustments[Index] = ThisAdjustment;
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003367 SavedAdjustments.push_back(
3368 std::make_pair(GD, std::make_pair(OGD, ThisAdjustment)));
Eli Friedmanf062d9d2009-12-06 22:33:51 +00003369 }
Eli Friedman47145832009-12-04 08:34:14 +00003370 }
3371 return true;
Anders Carlsson27682a32009-12-03 01:54:02 +00003372 }
3373
3374 return false;
Anders Carlsson27f69d02009-11-27 22:21:51 +00003375}
3376
Anders Carlsson824d7ea2010-02-11 08:02:13 +00003377void OldVtableBuilder::AppendMethodsToVtable() {
Eli Friedman152b5b12009-12-05 01:05:03 +00003378 if (!BuildVtable) {
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003379 VtableComponents.insert(VtableComponents.end(), Methods.size(),
3380 (llvm::Constant *)0);
Eli Friedman152b5b12009-12-05 01:05:03 +00003381 ThisAdjustments.clear();
3382 BaseReturnTypes.clear();
3383 Methods.clear();
3384 return;
3385 }
3386
Anders Carlsson15318f42009-12-04 16:19:30 +00003387 // Reserve room in the vtable for our new methods.
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003388 VtableComponents.reserve(VtableComponents.size() + Methods.size());
Anders Carlsson29202d52009-12-04 03:07:26 +00003389
Anders Carlssonb73ba392009-12-04 02:43:50 +00003390 for (unsigned i = 0, e = Methods.size(); i != e; ++i) {
3391 GlobalDecl GD = Methods[i];
Anders Carlssonea357222009-12-04 02:52:22 +00003392 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
3393
3394 // Get the 'this' pointer adjustment.
Anders Carlssonb73ba392009-12-04 02:43:50 +00003395 ThunkAdjustment ThisAdjustment = ThisAdjustments.lookup(i);
Anders Carlssonea357222009-12-04 02:52:22 +00003396
3397 // Construct the return type adjustment.
3398 ThunkAdjustment ReturnAdjustment;
3399
3400 QualType BaseReturnType = BaseReturnTypes.lookup(i);
3401 if (!BaseReturnType.isNull() && !MD->isPure()) {
3402 QualType DerivedType =
3403 MD->getType()->getAs<FunctionType>()->getResultType();
3404
3405 int64_t NonVirtualAdjustment =
3406 getNVOffset(BaseReturnType, DerivedType) / 8;
3407
3408 int64_t VirtualAdjustment =
3409 getVbaseOffset(BaseReturnType, DerivedType);
3410
3411 ReturnAdjustment = ThunkAdjustment(NonVirtualAdjustment,
3412 VirtualAdjustment);
3413 }
3414
Anders Carlsson2fce2162009-12-04 03:06:03 +00003415 llvm::Constant *Method = 0;
Anders Carlssonea357222009-12-04 02:52:22 +00003416 if (!ReturnAdjustment.isEmpty()) {
3417 // Build a covariant thunk.
3418 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Eli Friedman72649ed2009-12-06 22:01:30 +00003419 Method = wrap(CGM.GetAddrOfCovariantThunk(GD, Adjustment));
Anders Carlssonea357222009-12-04 02:52:22 +00003420 } else if (!ThisAdjustment.isEmpty()) {
3421 // Build a "regular" thunk.
Eli Friedman72649ed2009-12-06 22:01:30 +00003422 Method = wrap(CGM.GetAddrOfThunk(GD, ThisAdjustment));
Anders Carlssonbf540272009-12-04 02:56:03 +00003423 } else if (MD->isPure()) {
3424 // We have a pure virtual method.
Anders Carlsson2fce2162009-12-04 03:06:03 +00003425 Method = getPureVirtualFn();
3426 } else {
3427 // We have a good old regular method.
3428 Method = WrapAddrOf(GD);
Anders Carlssonea357222009-12-04 02:52:22 +00003429 }
Anders Carlsson2fce2162009-12-04 03:06:03 +00003430
3431 // Add the method to the vtable.
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003432 VtableComponents.push_back(Method);
Anders Carlssonb73ba392009-12-04 02:43:50 +00003433 }
3434
Anders Carlsson2fce2162009-12-04 03:06:03 +00003435
Anders Carlssonb73ba392009-12-04 02:43:50 +00003436 ThisAdjustments.clear();
Anders Carlssonea357222009-12-04 02:52:22 +00003437 BaseReturnTypes.clear();
Anders Carlssonb73ba392009-12-04 02:43:50 +00003438
Anders Carlssonadfa2672009-12-04 02:39:04 +00003439 Methods.clear();
Anders Carlssonadfa2672009-12-04 02:39:04 +00003440}
3441
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003442void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
3443
3444 // Itanium C++ ABI 2.5.2:
Anders Carlsson45147d02010-02-02 03:37:46 +00003445 // The order of the virtual function pointers in a virtual table is the
3446 // order of declaration of the corresponding member functions in the class.
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003447 //
Anders Carlsson45147d02010-02-02 03:37:46 +00003448 // There is an entry for any virtual function declared in a class,
3449 // whether it is a new function or overrides a base class function,
3450 // unless it overrides a function from the primary base, and conversion
3451 // between their return types does not require an adjustment.
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003452
3453 int64_t CurrentIndex = 0;
3454
3455 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3456 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3457
3458 if (PrimaryBase) {
Anders Carlsson0121fbd2009-11-30 19:43:26 +00003459 assert(PrimaryBase->isDefinition() &&
3460 "Should have the definition decl of the primary base!");
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003461
3462 // Since the record decl shares its vtable pointer with the primary base
3463 // we need to start counting at the end of the primary base's vtable.
3464 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
3465 }
Eli Friedmanea5ae312009-12-15 03:31:17 +00003466
3467 // Collect all the primary bases, so we can check whether methods override
3468 // a method from the base.
Anders Carlssonb9021e92010-02-27 16:18:19 +00003469 VtableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
Eli Friedmanea5ae312009-12-15 03:31:17 +00003470 for (ASTRecordLayout::primary_base_info_iterator
3471 I = Layout.primary_base_begin(), E = Layout.primary_base_end();
3472 I != E; ++I)
3473 PrimaryBases.insert((*I).getBase());
3474
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003475 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
3476
3477 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
3478 e = RD->method_end(); i != e; ++i) {
3479 const CXXMethodDecl *MD = *i;
3480
3481 // We only want virtual methods.
3482 if (!MD->isVirtual())
3483 continue;
3484
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003485 // Check if this method overrides a method in the primary base.
Anders Carlsson57071e22010-02-12 05:25:12 +00003486 if (const CXXMethodDecl *OverriddenMD =
Anders Carlssonc784ba22010-02-27 06:38:03 +00003487 OverridesMethodInBases(MD, PrimaryBases)) {
Anders Carlsson57071e22010-02-12 05:25:12 +00003488 // Check if converting from the return type of the method to the
3489 // return type of the overridden method requires conversion.
Anders Carlssondf31af12010-02-13 23:17:31 +00003490 if (ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD,
3491 OverriddenMD).isEmpty()) {
Anders Carlsson57071e22010-02-12 05:25:12 +00003492 // This index is shared between the index in the vtable of the primary
3493 // base class.
3494 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3495 const CXXDestructorDecl *OverriddenDD =
3496 cast<CXXDestructorDecl>(OverriddenMD);
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003497
Anders Carlsson57071e22010-02-12 05:25:12 +00003498 // Add both the complete and deleting entries.
3499 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
3500 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
3501 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
3502 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
3503 } else {
3504 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
3505 }
3506
3507 // We don't need to add an entry for this method.
Anders Carlssonc1eec892010-02-12 18:14:46 +00003508 continue;
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003509 }
3510 }
3511
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003512 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3513 if (MD->isImplicit()) {
3514 assert(!ImplicitVirtualDtor &&
3515 "Did already see an implicit virtual dtor!");
3516 ImplicitVirtualDtor = DD;
3517 continue;
3518 }
3519
3520 // Add the complete dtor.
3521 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
3522
3523 // Add the deleting dtor.
3524 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
3525 } else {
3526 // Add the entry.
3527 MethodVtableIndices[MD] = CurrentIndex++;
3528 }
3529 }
3530
3531 if (ImplicitVirtualDtor) {
3532 // Itanium C++ ABI 2.5.2:
Anders Carlssona661a542010-02-16 04:49:44 +00003533 // If a class has an implicitly-defined virtual destructor,
3534 // its entries come after the declared virtual function pointers.
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003535
3536 // Add the complete dtor.
3537 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
3538 CurrentIndex++;
3539
3540 // Add the deleting dtor.
3541 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
3542 CurrentIndex++;
3543 }
3544
3545 NumVirtualFunctionPointers[RD] = CurrentIndex;
3546}
3547
3548uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
3549 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
3550 NumVirtualFunctionPointers.find(RD);
3551 if (I != NumVirtualFunctionPointers.end())
3552 return I->second;
3553
3554 ComputeMethodVtableIndices(RD);
3555
3556 I = NumVirtualFunctionPointers.find(RD);
3557 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
3558 return I->second;
3559}
3560
3561uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssona0fdd912009-11-13 17:08:56 +00003562 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00003563 if (I != MethodVtableIndices.end())
3564 return I->second;
3565
Anders Carlssona0fdd912009-11-13 17:08:56 +00003566 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssond6b07fb2009-11-27 20:47:55 +00003567
3568 ComputeMethodVtableIndices(RD);
3569
Anders Carlssona0fdd912009-11-13 17:08:56 +00003570 I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00003571 assert(I != MethodVtableIndices.end() && "Did not find index!");
3572 return I->second;
3573}
3574
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003575CGVtableInfo::AdjustmentVectorTy*
3576CGVtableInfo::getAdjustments(GlobalDecl GD) {
3577 SavedAdjustmentsTy::iterator I = SavedAdjustments.find(GD);
3578 if (I != SavedAdjustments.end())
3579 return &I->second;
Eli Friedman72649ed2009-12-06 22:01:30 +00003580
3581 const CXXRecordDecl *RD = cast<CXXRecordDecl>(GD.getDecl()->getDeclContext());
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003582 if (!SavedAdjustmentRecords.insert(RD).second)
3583 return 0;
Eli Friedman72649ed2009-12-06 22:01:30 +00003584
Anders Carlsson1bb60992010-01-14 02:29:07 +00003585 AddressPointsMapTy AddressPoints;
Anders Carlsson824d7ea2010-02-11 08:02:13 +00003586 OldVtableBuilder b(RD, RD, 0, CGM, false, AddressPoints);
Eli Friedman72649ed2009-12-06 22:01:30 +00003587 D1(printf("vtable %s\n", RD->getNameAsCString()));
3588 b.GenerateVtableForBase(RD);
3589 b.GenerateVtableForVBases(RD);
Eli Friedman72649ed2009-12-06 22:01:30 +00003590
Anders Carlsson824d7ea2010-02-11 08:02:13 +00003591 for (OldVtableBuilder::SavedAdjustmentsVectorTy::iterator
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003592 i = b.getSavedAdjustments().begin(),
3593 e = b.getSavedAdjustments().end(); i != e; i++)
3594 SavedAdjustments[i->first].push_back(i->second);
Eli Friedman72649ed2009-12-06 22:01:30 +00003595
Eli Friedmanb455f0e2009-12-07 23:56:34 +00003596 I = SavedAdjustments.find(GD);
3597 if (I != SavedAdjustments.end())
3598 return &I->second;
3599
3600 return 0;
Eli Friedman72649ed2009-12-06 22:01:30 +00003601}
3602
Anders Carlssonbba16072010-03-11 07:15:17 +00003603int64_t CGVtableInfo::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
3604 const CXXRecordDecl *VBase) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00003605 ClassPairTy ClassPair(RD, VBase);
3606
Anders Carlssonbba16072010-03-11 07:15:17 +00003607 VirtualBaseClassOffsetOffsetsMapTy::iterator I =
3608 VirtualBaseClassOffsetOffsets.find(ClassPair);
3609 if (I != VirtualBaseClassOffsetOffsets.end())
Anders Carlssondbd920c2009-10-11 22:13:54 +00003610 return I->second;
3611
Anders Carlssonc89a7cf2010-03-11 16:06:20 +00003612 VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
3613 BaseSubobject(RD, 0),
3614 /*BaseIsVirtual=*/false,
3615 /*OffsetInLayoutClass=*/0);
Anders Carlssondbd920c2009-10-11 22:13:54 +00003616
Anders Carlssonc89a7cf2010-03-11 16:06:20 +00003617
3618 for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
3619 Builder.getVBaseOffsetOffsets().begin(),
3620 E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00003621 // Insert all types.
3622 ClassPairTy ClassPair(RD, I->first);
3623
Anders Carlssonbba16072010-03-11 07:15:17 +00003624 VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
Anders Carlssondbd920c2009-10-11 22:13:54 +00003625 }
3626
Anders Carlssonbba16072010-03-11 07:15:17 +00003627 I = VirtualBaseClassOffsetOffsets.find(ClassPair);
Anders Carlssonc89a7cf2010-03-11 16:06:20 +00003628
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00003629 // FIXME: The assertion below assertion currently fails with the old vtable
3630 /// layout code if there is a non-virtual thunk adjustment in a vtable.
3631 // Once the new layout is in place, this return should be removed.
Anders Carlssonbba16072010-03-11 07:15:17 +00003632 if (I == VirtualBaseClassOffsetOffsets.end())
Anders Carlsson7dbf47a2010-02-13 20:11:51 +00003633 return 0;
3634
Anders Carlssonbba16072010-03-11 07:15:17 +00003635 assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
Anders Carlssondbd920c2009-10-11 22:13:54 +00003636
3637 return I->second;
3638}
3639
Anders Carlsson9ac95b92009-12-05 21:03:56 +00003640uint64_t CGVtableInfo::getVtableAddressPoint(const CXXRecordDecl *RD) {
3641 uint64_t AddressPoint =
Anders Carlsson21431c52010-01-02 18:02:32 +00003642 (*(*(CGM.getVtableInfo().AddressPoints[RD]))[RD])[std::make_pair(RD, 0)];
Anders Carlsson9ac95b92009-12-05 21:03:56 +00003643
3644 return AddressPoint;
3645}
3646
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003647llvm::GlobalVariable *
Anders Carlsson35272252009-12-06 00:23:49 +00003648CGVtableInfo::GenerateVtable(llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson5794c972009-12-06 00:53:22 +00003649 bool GenerateDefinition,
Anders Carlsson35272252009-12-06 00:23:49 +00003650 const CXXRecordDecl *LayoutClass,
Anders Carlsson1bb60992010-01-14 02:29:07 +00003651 const CXXRecordDecl *RD, uint64_t Offset,
Anders Carlsson5d7af6b2010-02-28 00:36:23 +00003652 bool IsVirtual,
Anders Carlsson1bb60992010-01-14 02:29:07 +00003653 AddressPointsMapTy& AddressPoints) {
Anders Carlssond03a3262010-02-27 20:39:05 +00003654 if (GenerateDefinition) {
3655 if (LayoutClass == RD) {
Anders Carlsson5d7af6b2010-02-28 00:36:23 +00003656 assert(!IsVirtual &&
Anders Carlssone02fc0a2010-03-11 05:48:21 +00003657 "Can only have a virtual base in construction vtables!");
3658 assert(!Offset &&
3659 "Can only have a base offset in construction vtables!");
Anders Carlssond03a3262010-02-27 20:39:05 +00003660 }
Anders Carlssone02fc0a2010-03-11 05:48:21 +00003661
3662 VtableBuilder Builder(*this, RD, Offset,
Anders Carlsson1ffd79b2010-03-11 06:10:52 +00003663 /*MostDerivedClassIsVirtual=*/IsVirtual,
Anders Carlssone02fc0a2010-03-11 05:48:21 +00003664 LayoutClass);
3665
3666 if (CGM.getLangOptions().DumpVtableLayouts)
3667 Builder.dumpLayout(llvm::errs());
Anders Carlsson0c0eeb22010-02-13 02:02:03 +00003668 }
3669
Anders Carlssondbd920c2009-10-11 22:13:54 +00003670 llvm::SmallString<256> OutName;
Mike Stump9840c702009-11-12 20:47:57 +00003671 if (LayoutClass != RD)
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003672 CGM.getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset / 8,
3673 RD, OutName);
Mike Stump8cfcb522009-11-11 20:26:26 +00003674 else
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003675 CGM.getMangleContext().mangleCXXVtable(RD, OutName);
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00003676 llvm::StringRef Name = OutName.str();
Benjamin Kramer7a9474e2009-10-11 22:57:54 +00003677
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003678 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
Anders Carlsson21431c52010-01-02 18:02:32 +00003679 if (GV == 0 || CGM.getVtableInfo().AddressPoints[LayoutClass] == 0 ||
3680 GV->isDeclaration()) {
Anders Carlsson824d7ea2010-02-11 08:02:13 +00003681 OldVtableBuilder b(RD, LayoutClass, Offset, CGM, GenerateDefinition,
3682 AddressPoints);
Eli Friedman152b5b12009-12-05 01:05:03 +00003683
3684 D1(printf("vtable %s\n", RD->getNameAsCString()));
3685 // First comes the vtables for all the non-virtual bases...
Mike Stump8cc4f102009-12-24 07:29:41 +00003686 b.GenerateVtableForBase(RD, Offset);
Eli Friedman152b5b12009-12-05 01:05:03 +00003687
3688 // then the vtables for all the virtual bases.
3689 b.GenerateVtableForVBases(RD, Offset);
3690
Anders Carlsson152d4dc2009-12-05 22:19:10 +00003691 llvm::Constant *Init = 0;
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003692 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Anders Carlsson152d4dc2009-12-05 22:19:10 +00003693 llvm::ArrayType *ArrayType =
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003694 llvm::ArrayType::get(Int8PtrTy, b.getVtableComponents().size());
Anders Carlssone40477c2009-12-05 21:09:05 +00003695
Anders Carlsson5794c972009-12-06 00:53:22 +00003696 if (GenerateDefinition)
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003697 Init = llvm::ConstantArray::get(ArrayType, &b.getVtableComponents()[0],
3698 b.getVtableComponents().size());
Anders Carlsson5794c972009-12-06 00:53:22 +00003699
Mike Stump85615df2009-11-19 04:04:36 +00003700 llvm::GlobalVariable *OGV = GV;
Anders Carlsson5794c972009-12-06 00:53:22 +00003701
3702 GV = new llvm::GlobalVariable(CGM.getModule(), ArrayType,
3703 /*isConstant=*/true, Linkage, Init, Name);
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00003704 CGM.setGlobalVisibility(GV, RD);
3705
Mike Stump85615df2009-11-19 04:04:36 +00003706 if (OGV) {
3707 GV->takeName(OGV);
Anders Carlsson152d4dc2009-12-05 22:19:10 +00003708 llvm::Constant *NewPtr =
3709 llvm::ConstantExpr::getBitCast(GV, OGV->getType());
Mike Stump85615df2009-11-19 04:04:36 +00003710 OGV->replaceAllUsesWith(NewPtr);
3711 OGV->eraseFromParent();
3712 }
Mike Stump85615df2009-11-19 04:04:36 +00003713 }
Anders Carlssonbb27d862009-12-05 21:28:12 +00003714
3715 return GV;
Anders Carlssondbd920c2009-10-11 22:13:54 +00003716}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00003717
Anders Carlsson5794c972009-12-06 00:53:22 +00003718void CGVtableInfo::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
3719 const CXXRecordDecl *RD) {
Anders Carlssond58987c2009-12-07 07:59:52 +00003720 llvm::GlobalVariable *&Vtable = Vtables[RD];
3721 if (Vtable) {
3722 assert(Vtable->getInitializer() && "Vtable doesn't have a definition!");
3723 return;
3724 }
3725
Anders Carlsson1bb60992010-01-14 02:29:07 +00003726 AddressPointsMapTy AddressPoints;
3727 Vtable = GenerateVtable(Linkage, /*GenerateDefinition=*/true, RD, RD, 0,
Anders Carlsson5d7af6b2010-02-28 00:36:23 +00003728 /*IsVirtual=*/false,
Anders Carlsson1bb60992010-01-14 02:29:07 +00003729 AddressPoints);
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00003730 GenerateVTT(Linkage, /*GenerateDefinition=*/true, RD);
3731
3732 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
3733 e = RD->method_end(); i != e; ++i) {
3734 if (!(*i)->isVirtual())
3735 continue;
3736 if(!(*i)->hasInlineBody() && !(*i)->isImplicit())
3737 continue;
3738
3739 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(*i)) {
3740 CGM.BuildThunksForVirtual(GlobalDecl(DD, Dtor_Complete));
3741 CGM.BuildThunksForVirtual(GlobalDecl(DD, Dtor_Deleting));
3742 } else {
3743 CGM.BuildThunksForVirtual(GlobalDecl(*i));
3744 }
3745 }
Mike Stump58588942009-11-19 01:08:19 +00003746}
3747
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003748llvm::GlobalVariable *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Anders Carlsson5794c972009-12-06 00:53:22 +00003749 llvm::GlobalVariable *Vtable = Vtables.lookup(RD);
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00003750
Anders Carlsson1bb60992010-01-14 02:29:07 +00003751 if (!Vtable) {
3752 AddressPointsMapTy AddressPoints;
Anders Carlsson5794c972009-12-06 00:53:22 +00003753 Vtable = GenerateVtable(llvm::GlobalValue::ExternalLinkage,
Anders Carlsson1bb60992010-01-14 02:29:07 +00003754 /*GenerateDefinition=*/false, RD, RD, 0,
Anders Carlsson5d7af6b2010-02-28 00:36:23 +00003755 /*IsVirtual=*/false, AddressPoints);
Anders Carlsson1bb60992010-01-14 02:29:07 +00003756 }
Mike Stump85615df2009-11-19 04:04:36 +00003757
Anders Carlsson224c3122009-12-05 22:42:54 +00003758 return Vtable;
Mike Stump380dd752009-11-10 07:44:33 +00003759}
Mike Stump8cfcb522009-11-11 20:26:26 +00003760
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003761void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
3762 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
3763 const CXXRecordDecl *RD = MD->getParent();
3764
Anders Carlsson224c3122009-12-05 22:42:54 +00003765 // If the class doesn't have a vtable we don't need to emit one.
3766 if (!RD->isDynamicClass())
3767 return;
3768
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003769 // Get the key function.
Anders Carlssonf53df232009-12-07 04:35:11 +00003770 const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003771
Anders Carlsson224c3122009-12-05 22:42:54 +00003772 if (KeyFunction) {
3773 // We don't have the right key function.
3774 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
3775 return;
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003776 }
3777
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00003778 if (Vtables.count(RD))
3779 return;
Eli Friedman72649ed2009-12-06 22:01:30 +00003780
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00003781 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
3782 if (kind == TSK_ImplicitInstantiation)
3783 CGM.DeferredVtables.push_back(RD);
3784 else
3785 GenerateClassData(CGM.getVtableLinkage(RD), RD);
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00003786}