blob: 5cd0d329ab3c7d01a346443bbf042362c99d1757 [file] [log] [blame]
Anders Carlsson2bb27f52009-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 Carlssonf942ee02009-11-27 20:47:55 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlsson2bb27f52009-10-11 22:13:54 +000017#include "clang/AST/RecordLayout.h"
Anders Carlssond420a312009-11-26 19:32:45 +000018#include "llvm/ADT/DenseSet.h"
Zhongxing Xu1721ef72009-11-13 05:46:16 +000019#include <cstdio>
Anders Carlsson2bb27f52009-10-11 22:13:54 +000020
21using namespace clang;
22using namespace CodeGen;
23
Anders Carlssond59885022009-11-27 22:21:51 +000024namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000025class VtableBuilder {
Anders Carlsson2bb27f52009-10-11 22:13:54 +000026public:
27 /// Index_t - Vtable index type.
28 typedef uint64_t Index_t;
29private:
Anders Carlsson472404f2009-12-04 16:19:30 +000030
31 // Vtable - The components of the vtable being built.
Anders Carlsson19462d62009-12-04 16:24:46 +000032 typedef llvm::SmallVector<llvm::Constant *, 64> VtableVectorTy;
33 VtableVectorTy Vtable;
Anders Carlsson472404f2009-12-04 16:19:30 +000034
Anders Carlsson2bb27f52009-10-11 22:13:54 +000035 llvm::Type *Ptr8Ty;
Anders Carlssonbad80eb2009-12-04 18:36:22 +000036
37 /// MostDerivedClass - The most derived class that this vtable is being
38 /// built for.
39 const CXXRecordDecl *MostDerivedClass;
40
Mike Stump83066c82009-11-13 01:54:23 +000041 /// LayoutClass - The most derived class used for virtual base layout
42 /// information.
43 const CXXRecordDecl *LayoutClass;
Mike Stump653d0b92009-11-13 02:13:54 +000044 /// LayoutOffset - The offset for Class in LayoutClass.
45 uint64_t LayoutOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000046 /// BLayout - Layout for the most derived class that this vtable is being
47 /// built for.
48 const ASTRecordLayout &BLayout;
49 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
50 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
51 llvm::Constant *rtti;
52 llvm::LLVMContext &VMContext;
53 CodeGenModule &CGM; // Per-module state.
Anders Carlssonf2f31f42009-12-04 03:46:21 +000054
Anders Carlssonfb4dda42009-11-13 17:08:56 +000055 llvm::DenseMap<GlobalDecl, Index_t> VCall;
56 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stumpcd6f9ed2009-11-06 23:27:42 +000057 // This is the offset to the nearest virtual base
Anders Carlssonfb4dda42009-11-13 17:08:56 +000058 llvm::DenseMap<GlobalDecl, Index_t> NonVirtualOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000059 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stumpbb9ff052009-10-27 23:46:47 +000060
Anders Carlsson323bb042009-11-26 19:54:33 +000061 /// PureVirtualFunction - Points to __cxa_pure_virtual.
62 llvm::Constant *PureVirtualFn;
63
Anders Carlssona84b6e82009-12-04 02:01:07 +000064 /// VtableMethods - A data structure for keeping track of methods in a vtable.
65 /// Can add methods, override methods and iterate in vtable order.
66 class VtableMethods {
67 // MethodToIndexMap - Maps from a global decl to the index it has in the
68 // Methods vector.
69 llvm::DenseMap<GlobalDecl, uint64_t> MethodToIndexMap;
70
71 /// Methods - The methods, in vtable order.
72 typedef llvm::SmallVector<GlobalDecl, 16> MethodsVectorTy;
73 MethodsVectorTy Methods;
74
75 public:
76 /// AddMethod - Add a method to the vtable methods.
77 void AddMethod(GlobalDecl GD) {
78 assert(!MethodToIndexMap.count(GD) &&
79 "Method has already been added!");
80
81 MethodToIndexMap[GD] = Methods.size();
82 Methods.push_back(GD);
83 }
84
85 /// OverrideMethod - Replace a method with another.
86 void OverrideMethod(GlobalDecl OverriddenGD, GlobalDecl GD) {
87 llvm::DenseMap<GlobalDecl, uint64_t>::iterator i
88 = MethodToIndexMap.find(OverriddenGD);
89 assert(i != MethodToIndexMap.end() && "Did not find entry!");
90
91 // Get the index of the old decl.
92 uint64_t Index = i->second;
93
94 // Replace the old decl with the new decl.
95 Methods[Index] = GD;
96
Anders Carlssona84b6e82009-12-04 02:01:07 +000097 // And add the new.
98 MethodToIndexMap[GD] = Index;
99 }
100
Anders Carlsson7bb70762009-12-04 15:49:02 +0000101 /// getIndex - Gives the index of a passed in GlobalDecl. Returns false if
102 /// the index couldn't be found.
103 uint64_t getIndex(GlobalDecl GD, uint64_t &Index) const {
104 llvm::DenseMap<GlobalDecl, uint64_t>::const_iterator i
105 = MethodToIndexMap.find(GD);
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000106
Anders Carlsson7bb70762009-12-04 15:49:02 +0000107 if (i == MethodToIndexMap.end())
108 return false;
Anders Carlssone6096362009-12-04 03:41:37 +0000109
Anders Carlsson7bb70762009-12-04 15:49:02 +0000110 Index = i->second;
111 return true;
Anders Carlssone6096362009-12-04 03:41:37 +0000112 }
113
Anders Carlssona84b6e82009-12-04 02:01:07 +0000114 MethodsVectorTy::size_type size() const {
115 return Methods.size();
116 }
117
118 void clear() {
119 MethodToIndexMap.clear();
120 Methods.clear();
121 }
122
Anders Carlssone6096362009-12-04 03:41:37 +0000123 GlobalDecl operator[](uint64_t Index) const {
Anders Carlssona84b6e82009-12-04 02:01:07 +0000124 return Methods[Index];
125 }
126 };
127
128 /// Methods - The vtable methods we're currently building.
129 VtableMethods Methods;
130
Anders Carlsson4c837d22009-12-04 02:26:15 +0000131 /// ThisAdjustments - For a given index in the vtable, contains the 'this'
132 /// pointer adjustment needed for a method.
133 typedef llvm::DenseMap<uint64_t, ThunkAdjustment> ThisAdjustmentsMapTy;
134 ThisAdjustmentsMapTy ThisAdjustments;
Anders Carlssond420a312009-11-26 19:32:45 +0000135
Anders Carlssonc521f952009-12-04 02:22:02 +0000136 /// BaseReturnTypes - Contains the base return types of methods who have been
137 /// overridden with methods whose return types require adjustment. Used for
138 /// generating covariant thunk information.
139 typedef llvm::DenseMap<uint64_t, CanQualType> BaseReturnTypesMapTy;
140 BaseReturnTypesMapTy BaseReturnTypes;
Anders Carlssond420a312009-11-26 19:32:45 +0000141
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000142 std::vector<Index_t> VCalls;
Mike Stump2cefe382009-11-12 20:47:57 +0000143
144 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stumpcd2b8212009-11-19 20:52:19 +0000145 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
146 // vtable for use in computing the initializers for the VTT.
147 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump2cefe382009-11-12 20:47:57 +0000148
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000149 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000150 const bool Extern;
151 const uint32_t LLVMPointerWidth;
152 Index_t extra;
Mike Stump37dbe962009-10-15 02:04:03 +0000153 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stumpcd2b8212009-11-19 20:52:19 +0000154 static llvm::DenseMap<CtorVtable_t, int64_t>&
155 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
156 const CXXRecordDecl *c) {
157 CodeGenModule::AddrMap_t *&oref = cgm.AddressPoints[l];
158 if (oref == 0)
159 oref = new CodeGenModule::AddrMap_t;
160
161 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
162 if (ref == 0)
163 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
164 return *ref;
165 }
Anders Carlsson323bb042009-11-26 19:54:33 +0000166
167 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
168 llvm::Constant* getPureVirtualFn() {
169 if (!PureVirtualFn) {
170 const llvm::FunctionType *Ty =
171 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
172 /*isVarArg=*/false);
173 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
174 }
175
176 return PureVirtualFn;
177 }
178
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000179public:
Anders Carlssonbad80eb2009-12-04 18:36:22 +0000180 VtableBuilder(const CXXRecordDecl *MostDerivedClass,
Mike Stump653d0b92009-11-13 02:13:54 +0000181 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm)
Anders Carlssonbad80eb2009-12-04 18:36:22 +0000182 : MostDerivedClass(MostDerivedClass), LayoutClass(l), LayoutOffset(lo),
Mike Stump83066c82009-11-13 01:54:23 +0000183 BLayout(cgm.getContext().getASTRecordLayout(l)),
Anders Carlssonbad80eb2009-12-04 18:36:22 +0000184 rtti(cgm.GenerateRTTIRef(MostDerivedClass)),
185 VMContext(cgm.getModule().getContext()),CGM(cgm), PureVirtualFn(0),
186 subAddressPoints(AllocAddressPoint(cgm, l, MostDerivedClass)),
Mike Stump1960b202009-11-19 00:49:05 +0000187 Extern(!l->isInAnonymousNamespace()),
Anders Carlsson323bb042009-11-26 19:54:33 +0000188 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000189 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
190 }
191
Anders Carlsson472404f2009-12-04 16:19:30 +0000192 // getVtable - Returns a reference to the vtable components.
Anders Carlsson19462d62009-12-04 16:24:46 +0000193 const VtableVectorTy &getVtable() const {
Anders Carlsson472404f2009-12-04 16:19:30 +0000194 return Vtable;
195 }
196
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000197 llvm::DenseMap<const CXXRecordDecl *, Index_t> &getVBIndex()
198 { return VBIndex; }
199
200 llvm::Constant *wrap(Index_t i) {
201 llvm::Constant *m;
202 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
203 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
204 }
205
206 llvm::Constant *wrap(llvm::Constant *m) {
207 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
208 }
209
Mike Stump8a96d3a2009-12-02 19:50:41 +0000210#define D1(x)
211//#define D1(X) do { if (getenv("DEBUG")) { X; } } while (0)
Mike Stump75ce5732009-10-31 20:06:59 +0000212
213 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stump28431212009-10-13 22:54:56 +0000214 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000215 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
216 e = RD->bases_end(); i != e; ++i) {
217 const CXXRecordDecl *Base =
218 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stump28431212009-10-13 22:54:56 +0000219 Index_t next_vbindex = current_vbindex;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000220 if (i->isVirtual() && !SeenVBase.count(Base)) {
221 SeenVBase.insert(Base);
Mike Stump28431212009-10-13 22:54:56 +0000222 if (updateVBIndex) {
Mike Stump75ce5732009-10-31 20:06:59 +0000223 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stump28431212009-10-13 22:54:56 +0000224 - 3*LLVMPointerWidth/8);
225 VBIndex[Base] = next_vbindex;
226 }
Mike Stump75ce5732009-10-31 20:06:59 +0000227 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
228 VCalls.push_back((0?700:0) + BaseOffset);
229 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
230 Base->getNameAsCString(),
231 (int)-VCalls.size()-3, (int)BaseOffset,
232 Class->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000233 }
Mike Stump28431212009-10-13 22:54:56 +0000234 // We also record offsets for non-virtual bases to closest enclosing
235 // virtual base. We do this so that we don't have to search
236 // for the nearst virtual base class when generating thunks.
237 if (updateVBIndex && VBIndex.count(Base) == 0)
238 VBIndex[Base] = next_vbindex;
Mike Stump75ce5732009-10-31 20:06:59 +0000239 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000240 }
241 }
242
243 void StartNewTable() {
244 SeenVBase.clear();
245 }
246
Mike Stump8bccbfd2009-10-15 09:30:16 +0000247 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
248 Index_t Offset = 0) {
249
250 if (B == D)
251 return Offset;
252
253 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
254 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
255 e = D->bases_end(); i != e; ++i) {
256 const CXXRecordDecl *Base =
257 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
258 int64_t BaseOffset = 0;
259 if (!i->isVirtual())
260 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
261 int64_t o = getNVOffset_1(Base, B, BaseOffset);
262 if (o >= 0)
263 return o;
264 }
265
266 return -1;
267 }
268
269 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
270 /// derived class D.
271 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump46271322009-11-03 19:03:17 +0000272 qD = qD->getPointeeType();
273 qB = qB->getPointeeType();
Mike Stump8bccbfd2009-10-15 09:30:16 +0000274 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
275 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
276 int64_t o = getNVOffset_1(D, B);
277 if (o >= 0)
278 return o;
279
280 assert(false && "FIXME: non-virtual base not found");
281 return 0;
282 }
283
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000284 /// getVbaseOffset - Returns the index into the vtable for the virtual base
285 /// offset for the given (B) virtual base of the derived class D.
286 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump46271322009-11-03 19:03:17 +0000287 qD = qD->getPointeeType();
288 qB = qB->getPointeeType();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000289 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
290 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
Anders Carlssonbad80eb2009-12-04 18:36:22 +0000291 if (D != MostDerivedClass)
Eli Friedman03aa2f12009-11-30 01:19:33 +0000292 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000293 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
294 i = VBIndex.find(B);
295 if (i != VBIndex.end())
296 return i->second;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000297
Mike Stump28431212009-10-13 22:54:56 +0000298 assert(false && "FIXME: Base not found");
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000299 return 0;
300 }
301
Eli Friedman81fb0d22009-12-04 08:40:51 +0000302 bool OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
303 Index_t OverrideOffset, Index_t Offset,
304 int64_t CurrentVBaseOffset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000305
Anders Carlsson495634e2009-12-04 02:39:04 +0000306 /// AppendMethods - Append the current methods to the vtable.
Anders Carlssonddf42c82009-12-04 02:56:03 +0000307 void AppendMethodsToVtable();
Anders Carlsson495634e2009-12-04 02:39:04 +0000308
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000309 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
310 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
311
Anders Carlsson64457732009-11-24 05:08:52 +0000312 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump18e8b472009-10-27 23:36:26 +0000313
Mike Stumpcdeb8002009-12-03 16:55:20 +0000314 return wrap(CGM.GetAddrOfFunction(GD, Ty));
Mike Stump18e8b472009-10-27 23:36:26 +0000315 }
316
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000317 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
318 int64_t CurrentVBaseOffset) {
Mike Stump37dbe962009-10-15 02:04:03 +0000319 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000320 e = Path->rend(); i != e; ++i) {
321 const CXXRecordDecl *RD = i->first;
Mike Stump8bccbfd2009-10-15 09:30:16 +0000322 int64_t OverrideOffset = i->second;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000323 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
324 ++mi) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000325 const CXXMethodDecl *MD = *mi;
326
327 if (!MD->isVirtual())
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000328 continue;
329
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000330 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
331 // Override both the complete and the deleting destructor.
332 GlobalDecl CompDtor(DD, Dtor_Complete);
Eli Friedman81fb0d22009-12-04 08:40:51 +0000333 OverrideMethod(CompDtor, MorallyVirtual, OverrideOffset, Offset,
334 CurrentVBaseOffset);
335
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000336 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
Eli Friedman81fb0d22009-12-04 08:40:51 +0000337 OverrideMethod(DeletingDtor, MorallyVirtual, OverrideOffset, Offset,
338 CurrentVBaseOffset);
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000339 } else {
Eli Friedman81fb0d22009-12-04 08:40:51 +0000340 OverrideMethod(MD, MorallyVirtual, OverrideOffset, Offset,
341 CurrentVBaseOffset);
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000342 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000343 }
344 }
345 }
346
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000347 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000348 int64_t CurrentVBaseOffset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000349 // If we can find a previously allocated slot for this, reuse it.
Eli Friedman81fb0d22009-12-04 08:40:51 +0000350 if (OverrideMethod(GD, MorallyVirtual, Offset, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000351 CurrentVBaseOffset))
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000352 return;
353
Anders Carlssoncdf18982009-12-04 02:08:24 +0000354 // We didn't find an entry in the vtable that we could use, add a new
355 // entry.
356 Methods.AddMethod(GD);
357
Mike Stumpc5a332c2009-11-13 23:45:53 +0000358 D1(printf(" vfn for %s at %d\n", MD->getNameAsString().c_str(),
359 (int)Index[GD]));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000360 if (MorallyVirtual) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000361 VCallOffset[GD] = Offset/8;
362 Index_t &idx = VCall[GD];
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000363 // Allocate the first one, after that, we reuse the previous one.
364 if (idx == 0) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000365 NonVirtualOffset[GD] = CurrentVBaseOffset/8 - Offset/8;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000366 idx = VCalls.size()+1;
367 VCalls.push_back(0);
Mike Stump75ce5732009-10-31 20:06:59 +0000368 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpc5a332c2009-11-13 23:45:53 +0000369 MD->getNameAsString().c_str(), (int)-VCalls.size()-3, 0));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000370 }
371 }
372 }
373
374 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000375 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000376 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000377 ++mi) {
378 const CXXMethodDecl *MD = *mi;
379 if (!MD->isVirtual())
380 continue;
381
382 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
383 // For destructors, add both the complete and the deleting destructor
384 // to the vtable.
385 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000386 CurrentVBaseOffset);
Eli Friedman03aa2f12009-11-30 01:19:33 +0000387 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
388 CurrentVBaseOffset);
389 } else
390 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000391 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000392 }
393
394 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
395 const CXXRecordDecl *PrimaryBase,
396 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000397 int64_t Offset, int64_t CurrentVBaseOffset,
398 Path_t *Path) {
Mike Stump37dbe962009-10-15 02:04:03 +0000399 Path->push_back(std::make_pair(RD, Offset));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000400 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
401 e = RD->bases_end(); i != e; ++i) {
402 if (i->isVirtual())
403 continue;
404 const CXXRecordDecl *Base =
405 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
406 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
407 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
408 StartNewTable();
Mike Stump653d0b92009-11-13 02:13:54 +0000409 GenerateVtableForBase(Base, o, MorallyVirtual, false,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000410 CurrentVBaseOffset, Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000411 }
412 }
Mike Stump37dbe962009-10-15 02:04:03 +0000413 Path->pop_back();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000414 }
415
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000416// #define D(X) do { X; } while (0)
417#define D(X)
418
419 void insertVCalls(int InsertionPoint) {
Mike Stump75ce5732009-10-31 20:06:59 +0000420 D1(printf("============= combining vbase/vcall\n"));
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000421 D(VCalls.insert(VCalls.begin(), 673));
422 D(VCalls.push_back(672));
Anders Carlsson472404f2009-12-04 16:19:30 +0000423
424 Vtable.insert(Vtable.begin() + InsertionPoint, VCalls.size(), 0);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000425 // The vcalls come first...
426 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
427 e = VCalls.rend();
428 i != e; ++i)
Anders Carlsson472404f2009-12-04 16:19:30 +0000429 Vtable[InsertionPoint++] = wrap((0?600:0) + *i);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000430 VCalls.clear();
Mike Stump9f23a142009-11-10 02:30:51 +0000431 VCall.clear();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000432 }
433
Mike Stump559387f2009-11-13 23:13:20 +0000434 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
435 Index_t AddressPoint) {
436 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
437 RD->getNameAsCString(), Class->getNameAsCString(),
438 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stumpcd2b8212009-11-19 20:52:19 +0000439 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump559387f2009-11-13 23:13:20 +0000440
441 // Now also add the address point for all our primary bases.
442 while (1) {
443 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
444 RD = Layout.getPrimaryBase();
445 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
446 // FIXME: Double check this.
447 if (RD == 0)
448 break;
449 if (PrimaryBaseWasVirtual &&
450 BLayout.getVBaseClassOffset(RD) != Offset)
451 break;
452 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
453 RD->getNameAsCString(), Class->getNameAsCString(),
454 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stumpcd2b8212009-11-19 20:52:19 +0000455 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump559387f2009-11-13 23:13:20 +0000456 }
457 }
458
459
Eli Friedmanb05eb962009-12-04 03:54:56 +0000460 Index_t FinishGenerateVtable(const CXXRecordDecl *RD,
461 const ASTRecordLayout &Layout,
462 const CXXRecordDecl *PrimaryBase,
463 bool PrimaryBaseWasVirtual,
464 bool MorallyVirtual, int64_t Offset,
465 bool ForVirtualBase, int64_t CurrentVBaseOffset,
466 Path_t *Path) {
Mike Stump37dbe962009-10-15 02:04:03 +0000467 bool alloc = false;
468 if (Path == 0) {
469 alloc = true;
470 Path = new Path_t;
471 }
472
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000473 StartNewTable();
474 extra = 0;
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000475 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
Anders Carlsson472404f2009-12-04 16:19:30 +0000476 int VCallInsertionPoint = Vtable.size();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000477 if (!DeferVCalls) {
478 insertVCalls(VCallInsertionPoint);
Mike Stump8bccbfd2009-10-15 09:30:16 +0000479 } else
480 // FIXME: just for extra, or for all uses of VCalls.size post this?
481 extra = -VCalls.size();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000482
Anders Carlsson472404f2009-12-04 16:19:30 +0000483 // Add the offset to top.
484 Vtable.push_back(wrap(-((Offset-LayoutOffset)/8)));
485
486 // Add the RTTI information.
487 Vtable.push_back(rtti);
488
489 Index_t AddressPoint = Vtable.size();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000490
Anders Carlssonddf42c82009-12-04 02:56:03 +0000491 AppendMethodsToVtable();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000492
493 // and then the non-virtual bases.
494 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000495 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000496
497 if (ForVirtualBase) {
Mike Stump2cefe382009-11-12 20:47:57 +0000498 // FIXME: We're adding to VCalls in callers, we need to do the overrides
499 // in the inner part, so that we know the complete set of vcalls during
500 // the build and don't have to insert into methods. Saving out the
501 // AddressPoint here, would need to be fixed, if we didn't do that. Also
502 // retroactively adding vcalls for overrides later wind up in the wrong
503 // place, the vcall slot has to be alloted during the walk of the base
504 // when the function is first introduces.
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000505 AddressPoint += VCalls.size();
Mike Stump2cefe382009-11-12 20:47:57 +0000506 insertVCalls(VCallInsertionPoint);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000507 }
508
Mike Stump559387f2009-11-13 23:13:20 +0000509 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump2cefe382009-11-12 20:47:57 +0000510
Mike Stump37dbe962009-10-15 02:04:03 +0000511 if (alloc) {
512 delete Path;
513 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000514 return AddressPoint;
515 }
516
Mike Stump75ce5732009-10-31 20:06:59 +0000517 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
518 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000519 int64_t CurrentVBaseOffset) {
Mike Stump75ce5732009-10-31 20:06:59 +0000520 if (!RD->isDynamicClass())
521 return;
522
523 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
524 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
525 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
526
527 // vtables are composed from the chain of primaries.
Eli Friedman65d87222009-12-04 08:52:11 +0000528 if (PrimaryBase && !PrimaryBaseWasVirtual) {
Mike Stump75ce5732009-10-31 20:06:59 +0000529 D1(printf(" doing primaries for %s most derived %s\n",
530 RD->getNameAsCString(), Class->getNameAsCString()));
Eli Friedman65d87222009-12-04 08:52:11 +0000531 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
532 updateVBIndex, current_vbindex, CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000533 }
534
535 D1(printf(" doing vcall entries for %s most derived %s\n",
536 RD->getNameAsCString(), Class->getNameAsCString()));
537
538 // And add the virtuals for the class to the primary vtable.
Eli Friedman03aa2f12009-11-30 01:19:33 +0000539 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000540 }
541
542 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
543 bool updateVBIndex, Index_t current_vbindex,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000544 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000545 bool bottom) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000546 if (!RD->isDynamicClass())
547 return;
548
549 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
550 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
551 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
552
553 // vtables are composed from the chain of primaries.
554 if (PrimaryBase) {
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000555 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
556 if (PrimaryBaseWasVirtual) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000557 IndirectPrimary.insert(PrimaryBase);
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000558 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
559 }
Mike Stump75ce5732009-10-31 20:06:59 +0000560
561 D1(printf(" doing primaries for %s most derived %s\n",
562 RD->getNameAsCString(), Class->getNameAsCString()));
563
564 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000565 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000566 BaseCurrentVBaseOffset, false);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000567 }
568
Mike Stump75ce5732009-10-31 20:06:59 +0000569 D1(printf(" doing vbase entries for %s most derived %s\n",
570 RD->getNameAsCString(), Class->getNameAsCString()));
571 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
572
573 if (RDisVirtualBase || bottom) {
574 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000575 CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000576 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000577 }
578
Mike Stump653d0b92009-11-13 02:13:54 +0000579 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
580 bool MorallyVirtual = false,
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000581 bool ForVirtualBase = false,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000582 int CurrentVBaseOffset = 0,
Mike Stump37dbe962009-10-15 02:04:03 +0000583 Path_t *Path = 0) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000584 if (!RD->isDynamicClass())
585 return 0;
586
Mike Stumpfa818082009-11-13 02:35:38 +0000587 // Construction vtable don't need parts that have no virtual bases and
588 // aren't morally virtual.
Anders Carlssonbad80eb2009-12-04 18:36:22 +0000589 if ((LayoutClass != MostDerivedClass) &&
590 RD->getNumVBases() == 0 && !MorallyVirtual)
Mike Stumpfa818082009-11-13 02:35:38 +0000591 return 0;
592
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000593 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
594 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
595 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
596
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000597 extra = 0;
Mike Stump75ce5732009-10-31 20:06:59 +0000598 D1(printf("building entries for base %s most derived %s\n",
599 RD->getNameAsCString(), Class->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000600
Mike Stump75ce5732009-10-31 20:06:59 +0000601 if (ForVirtualBase)
602 extra = VCalls.size();
603
604 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0, ForVirtualBase,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000605 CurrentVBaseOffset, true);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000606
607 if (Path)
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000608 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000609
Eli Friedmanb05eb962009-12-04 03:54:56 +0000610 return FinishGenerateVtable(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
611 MorallyVirtual, Offset, ForVirtualBase,
612 CurrentVBaseOffset, Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000613 }
614
615 void GenerateVtableForVBases(const CXXRecordDecl *RD,
616 int64_t Offset = 0,
Mike Stump37dbe962009-10-15 02:04:03 +0000617 Path_t *Path = 0) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000618 bool alloc = false;
619 if (Path == 0) {
620 alloc = true;
Mike Stump37dbe962009-10-15 02:04:03 +0000621 Path = new Path_t;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000622 }
623 // FIXME: We also need to override using all paths to a virtual base,
624 // right now, we just process the first path
625 Path->push_back(std::make_pair(RD, Offset));
626 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
627 e = RD->bases_end(); i != e; ++i) {
628 const CXXRecordDecl *Base =
629 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
630 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
631 // Mark it so we don't output it twice.
632 IndirectPrimary.insert(Base);
633 StartNewTable();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000634 VCall.clear();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000635 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000636 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump75ce5732009-10-31 20:06:59 +0000637 D1(printf("vtable %s virtual base %s\n",
638 Class->getNameAsCString(), Base->getNameAsCString()));
Mike Stump653d0b92009-11-13 02:13:54 +0000639 GenerateVtableForBase(Base, BaseOffset, true, true, CurrentVBaseOffset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000640 Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000641 }
Mike Stump2cefe382009-11-12 20:47:57 +0000642 int64_t BaseOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000643 if (i->isVirtual())
644 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump2cefe382009-11-12 20:47:57 +0000645 else {
646 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
647 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
648 }
649
Mike Stump37dbe962009-10-15 02:04:03 +0000650 if (Base->getNumVBases()) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000651 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump37dbe962009-10-15 02:04:03 +0000652 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000653 }
654 Path->pop_back();
655 if (alloc)
656 delete Path;
657 }
658};
Anders Carlssonca1bf682009-12-03 01:54:02 +0000659} // end anonymous namespace
660
Anders Carlsson657f1392009-12-03 02:32:59 +0000661/// TypeConversionRequiresAdjustment - Returns whether conversion from a
662/// derived type to a base type requires adjustment.
663static bool
664TypeConversionRequiresAdjustment(ASTContext &Ctx,
665 const CXXRecordDecl *DerivedDecl,
666 const CXXRecordDecl *BaseDecl) {
667 CXXBasePaths Paths(/*FindAmbiguities=*/false,
668 /*RecordPaths=*/true, /*DetectVirtual=*/true);
669 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
670 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
671 assert(false && "Class must be derived from the passed in base class!");
672 return false;
673 }
674
675 // If we found a virtual base we always want to require adjustment.
676 if (Paths.getDetectedVirtual())
677 return true;
678
679 const CXXBasePath &Path = Paths.front();
680
681 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
682 const CXXBasePathElement &Element = Path[Start];
683
684 // Check the base class offset.
685 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
686
687 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
688 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
689
690 if (Layout.getBaseClassOffset(Base) != 0) {
691 // This requires an adjustment.
692 return true;
693 }
694 }
695
696 return false;
697}
698
699static bool
700TypeConversionRequiresAdjustment(ASTContext &Ctx,
701 QualType DerivedType, QualType BaseType) {
702 // Canonicalize the types.
703 QualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
704 QualType CanBaseType = Ctx.getCanonicalType(BaseType);
705
706 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
707 "Types must have same type class!");
708
709 if (CanDerivedType == CanBaseType) {
710 // No adjustment needed.
711 return false;
712 }
713
714 if (const ReferenceType *RT = dyn_cast<ReferenceType>(CanDerivedType)) {
715 CanDerivedType = RT->getPointeeType();
716 CanBaseType = cast<ReferenceType>(CanBaseType)->getPointeeType();
717 } else if (const PointerType *PT = dyn_cast<PointerType>(CanDerivedType)) {
718 CanDerivedType = PT->getPointeeType();
719 CanBaseType = cast<PointerType>(CanBaseType)->getPointeeType();
720 } else {
721 assert(false && "Unexpected return type!");
722 }
723
724 if (CanDerivedType == CanBaseType) {
725 // No adjustment needed.
726 return false;
727 }
728
729 const CXXRecordDecl *DerivedDecl =
Anders Carlssondabfa3c2009-12-03 03:28:24 +0000730 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
Anders Carlsson657f1392009-12-03 02:32:59 +0000731
732 const CXXRecordDecl *BaseDecl =
733 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
734
735 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
736}
737
Eli Friedman81fb0d22009-12-04 08:40:51 +0000738bool VtableBuilder::OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
739 Index_t OverrideOffset, Index_t Offset,
740 int64_t CurrentVBaseOffset) {
Anders Carlssonca1bf682009-12-03 01:54:02 +0000741 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
742
743 const bool isPure = MD->isPure();
744 typedef CXXMethodDecl::method_iterator meth_iter;
745 // FIXME: Should OverrideOffset's be Offset?
746
747 // FIXME: Don't like the nested loops. For very large inheritance
748 // heirarchies we could have a table on the side with the final overridder
749 // and just replace each instance of an overridden method once. Would be
750 // nice to measure the cost/benefit on real code.
751
752 for (meth_iter mi = MD->begin_overridden_methods(),
753 e = MD->end_overridden_methods();
754 mi != e; ++mi) {
755 GlobalDecl OGD;
756
Anders Carlssonf3935b42009-12-04 05:51:56 +0000757 const CXXMethodDecl *OMD = *mi;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000758 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
759 OGD = GlobalDecl(DD, GD.getDtorType());
760 else
761 OGD = OMD;
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000762
763 // FIXME: Explain why this is necessary!
Anders Carlsson7bb70762009-12-04 15:49:02 +0000764 uint64_t Index;
765 if (!Methods.getIndex(OGD, Index))
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000766 continue;
767
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000768 QualType ReturnType =
769 MD->getType()->getAs<FunctionType>()->getResultType();
770 QualType OverriddenReturnType =
771 OMD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonca1bf682009-12-03 01:54:02 +0000772
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000773 // Check if we need a return type adjustment.
774 if (TypeConversionRequiresAdjustment(CGM.getContext(), ReturnType,
775 OverriddenReturnType)) {
776 CanQualType &BaseReturnType = BaseReturnTypes[Index];
Anders Carlssonca1bf682009-12-03 01:54:02 +0000777
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000778 // Get the canonical return type.
779 CanQualType CanReturnType =
780 CGM.getContext().getCanonicalType(ReturnType);
Anders Carlssone6096362009-12-04 03:41:37 +0000781
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000782 // Insert the base return type.
783 if (BaseReturnType.isNull())
784 BaseReturnType =
785 CGM.getContext().getCanonicalType(OverriddenReturnType);
786 }
Anders Carlssona93e9802009-12-04 03:52:52 +0000787
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000788 Methods.OverrideMethod(OGD, GD);
789
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000790 ThisAdjustments.erase(Index);
791 if (MorallyVirtual || VCall.count(OGD)) {
792 Index_t &idx = VCall[OGD];
793 if (idx == 0) {
794 NonVirtualOffset[GD] = -OverrideOffset/8 + CurrentVBaseOffset/8;
795 VCallOffset[GD] = OverrideOffset/8;
796 idx = VCalls.size()+1;
797 VCalls.push_back(0);
798 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
799 MD->getNameAsString().c_str(), (int)-idx-3,
800 (int)VCalls[idx-1], Class->getNameAsCString()));
801 } else {
802 NonVirtualOffset[GD] = NonVirtualOffset[OGD];
803 VCallOffset[GD] = VCallOffset[OGD];
804 VCalls[idx-1] = -VCallOffset[OGD] + OverrideOffset/8;
805 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
806 MD->getNameAsString().c_str(), (int)-idx-3,
807 (int)VCalls[idx-1], Class->getNameAsCString()));
808 }
809 VCall[GD] = idx;
810 int64_t NonVirtualAdjustment = NonVirtualOffset[GD];
811 int64_t VirtualAdjustment =
812 -((idx + extra + 2) * LLVMPointerWidth / 8);
Anders Carlsson657f1392009-12-03 02:32:59 +0000813
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000814 // Optimize out virtual adjustments of 0.
815 if (VCalls[idx-1] == 0)
816 VirtualAdjustment = 0;
Anders Carlsson657f1392009-12-03 02:32:59 +0000817
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000818 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
819 VirtualAdjustment);
Anders Carlsson2ca285f2009-12-03 02:22:59 +0000820
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000821 if (!isPure && !ThisAdjustment.isEmpty())
822 ThisAdjustments[Index] = ThisAdjustment;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000823 return true;
824 }
Eli Friedman3d2e9de2009-12-04 08:34:14 +0000825
826 // FIXME: finish off
827 int64_t NonVirtualAdjustment = VCallOffset[OGD] - OverrideOffset/8;
828
829 if (NonVirtualAdjustment) {
830 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
831
832 if (!isPure)
833 ThisAdjustments[Index] = ThisAdjustment;
834 }
835 return true;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000836 }
837
838 return false;
Anders Carlssond59885022009-11-27 22:21:51 +0000839}
840
Anders Carlssonddf42c82009-12-04 02:56:03 +0000841void VtableBuilder::AppendMethodsToVtable() {
Anders Carlsson472404f2009-12-04 16:19:30 +0000842 // Reserve room in the vtable for our new methods.
843 Vtable.reserve(Vtable.size() + Methods.size());
Anders Carlssonb07567c2009-12-04 03:07:26 +0000844
Anders Carlsson86809cd2009-12-04 02:43:50 +0000845 for (unsigned i = 0, e = Methods.size(); i != e; ++i) {
846 GlobalDecl GD = Methods[i];
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000847 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
848
849 // Get the 'this' pointer adjustment.
Anders Carlsson86809cd2009-12-04 02:43:50 +0000850 ThunkAdjustment ThisAdjustment = ThisAdjustments.lookup(i);
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000851
852 // Construct the return type adjustment.
853 ThunkAdjustment ReturnAdjustment;
854
855 QualType BaseReturnType = BaseReturnTypes.lookup(i);
856 if (!BaseReturnType.isNull() && !MD->isPure()) {
857 QualType DerivedType =
858 MD->getType()->getAs<FunctionType>()->getResultType();
859
860 int64_t NonVirtualAdjustment =
861 getNVOffset(BaseReturnType, DerivedType) / 8;
862
863 int64_t VirtualAdjustment =
864 getVbaseOffset(BaseReturnType, DerivedType);
865
866 ReturnAdjustment = ThunkAdjustment(NonVirtualAdjustment,
867 VirtualAdjustment);
868 }
869
Anders Carlsson50f14742009-12-04 03:06:03 +0000870 llvm::Constant *Method = 0;
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000871 if (!ReturnAdjustment.isEmpty()) {
872 // Build a covariant thunk.
873 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Anders Carlsson50f14742009-12-04 03:06:03 +0000874 Method = CGM.BuildCovariantThunk(MD, Extern, Adjustment);
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000875 } else if (!ThisAdjustment.isEmpty()) {
876 // Build a "regular" thunk.
Anders Carlsson50f14742009-12-04 03:06:03 +0000877 Method = CGM.BuildThunk(GD, Extern, ThisAdjustment);
Anders Carlssonddf42c82009-12-04 02:56:03 +0000878 } else if (MD->isPure()) {
879 // We have a pure virtual method.
Anders Carlsson50f14742009-12-04 03:06:03 +0000880 Method = getPureVirtualFn();
881 } else {
882 // We have a good old regular method.
883 Method = WrapAddrOf(GD);
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000884 }
Anders Carlsson50f14742009-12-04 03:06:03 +0000885
886 // Add the method to the vtable.
Anders Carlsson472404f2009-12-04 16:19:30 +0000887 Vtable.push_back(Method);
Anders Carlsson86809cd2009-12-04 02:43:50 +0000888 }
889
Anders Carlsson50f14742009-12-04 03:06:03 +0000890
Anders Carlsson86809cd2009-12-04 02:43:50 +0000891 ThisAdjustments.clear();
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000892 BaseReturnTypes.clear();
Anders Carlsson86809cd2009-12-04 02:43:50 +0000893
Anders Carlsson495634e2009-12-04 02:39:04 +0000894 Methods.clear();
Anders Carlsson495634e2009-12-04 02:39:04 +0000895}
896
Anders Carlssonf942ee02009-11-27 20:47:55 +0000897void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
898
899 // Itanium C++ ABI 2.5.2:
900 // The order of the virtual function pointers in a virtual table is the
901 // order of declaration of the corresponding member functions in the class.
902 //
903 // There is an entry for any virtual function declared in a class,
904 // whether it is a new function or overrides a base class function,
905 // unless it overrides a function from the primary base, and conversion
906 // between their return types does not require an adjustment.
907
908 int64_t CurrentIndex = 0;
909
910 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
911 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
912
913 if (PrimaryBase) {
Anders Carlssonc920fa22009-11-30 19:43:26 +0000914 assert(PrimaryBase->isDefinition() &&
915 "Should have the definition decl of the primary base!");
Anders Carlssonf942ee02009-11-27 20:47:55 +0000916
917 // Since the record decl shares its vtable pointer with the primary base
918 // we need to start counting at the end of the primary base's vtable.
919 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
920 }
921
922 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
923
924 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
925 e = RD->method_end(); i != e; ++i) {
926 const CXXMethodDecl *MD = *i;
927
928 // We only want virtual methods.
929 if (!MD->isVirtual())
930 continue;
931
932 bool ShouldAddEntryForMethod = true;
933
934 // Check if this method overrides a method in the primary base.
935 for (CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
936 e = MD->end_overridden_methods(); i != e; ++i) {
Anders Carlssonf3935b42009-12-04 05:51:56 +0000937 const CXXMethodDecl *OverriddenMD = *i;
Anders Carlssonf942ee02009-11-27 20:47:55 +0000938 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
939 assert(OverriddenMD->isCanonicalDecl() &&
940 "Should have the canonical decl of the overridden RD!");
941
942 if (OverriddenRD == PrimaryBase) {
943 // Check if converting from the return type of the method to the
944 // return type of the overridden method requires conversion.
945 QualType ReturnType =
946 MD->getType()->getAs<FunctionType>()->getResultType();
947 QualType OverriddenReturnType =
948 OverriddenMD->getType()->getAs<FunctionType>()->getResultType();
949
950 if (!TypeConversionRequiresAdjustment(CGM.getContext(),
951 ReturnType, OverriddenReturnType)) {
952 // This index is shared between the index in the vtable of the primary
953 // base class.
954 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
955 const CXXDestructorDecl *OverriddenDD =
956 cast<CXXDestructorDecl>(OverriddenMD);
957
958 // Add both the complete and deleting entries.
959 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
960 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
961 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
962 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
963 } else {
964 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
965 }
966
967 // We don't need to add an entry for this method.
968 ShouldAddEntryForMethod = false;
969 break;
970 }
971 }
972 }
973
974 if (!ShouldAddEntryForMethod)
975 continue;
976
977 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
978 if (MD->isImplicit()) {
979 assert(!ImplicitVirtualDtor &&
980 "Did already see an implicit virtual dtor!");
981 ImplicitVirtualDtor = DD;
982 continue;
983 }
984
985 // Add the complete dtor.
986 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
987
988 // Add the deleting dtor.
989 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
990 } else {
991 // Add the entry.
992 MethodVtableIndices[MD] = CurrentIndex++;
993 }
994 }
995
996 if (ImplicitVirtualDtor) {
997 // Itanium C++ ABI 2.5.2:
998 // If a class has an implicitly-defined virtual destructor,
999 // its entries come after the declared virtual function pointers.
1000
1001 // Add the complete dtor.
1002 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
1003 CurrentIndex++;
1004
1005 // Add the deleting dtor.
1006 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
1007 CurrentIndex++;
1008 }
1009
1010 NumVirtualFunctionPointers[RD] = CurrentIndex;
1011}
1012
1013uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
1014 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1015 NumVirtualFunctionPointers.find(RD);
1016 if (I != NumVirtualFunctionPointers.end())
1017 return I->second;
1018
1019 ComputeMethodVtableIndices(RD);
1020
1021 I = NumVirtualFunctionPointers.find(RD);
1022 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
1023 return I->second;
1024}
1025
1026uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001027 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001028 if (I != MethodVtableIndices.end())
1029 return I->second;
1030
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001031 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001032
1033 ComputeMethodVtableIndices(RD);
1034
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001035 I = MethodVtableIndices.find(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001036 assert(I != MethodVtableIndices.end() && "Did not find index!");
1037 return I->second;
1038}
1039
1040int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
1041 const CXXRecordDecl *VBase) {
1042 ClassPairTy ClassPair(RD, VBase);
1043
1044 VirtualBaseClassIndiciesTy::iterator I =
1045 VirtualBaseClassIndicies.find(ClassPair);
1046 if (I != VirtualBaseClassIndicies.end())
1047 return I->second;
1048
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001049 // FIXME: This seems expensive. Can we do a partial job to get
1050 // just this data.
Anders Carlsson472404f2009-12-04 16:19:30 +00001051 VtableBuilder b(RD, RD, 0, CGM);
Mike Stump75ce5732009-10-31 20:06:59 +00001052 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001053 b.GenerateVtableForBase(RD);
1054 b.GenerateVtableForVBases(RD);
1055
1056 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1057 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
1058 // Insert all types.
1059 ClassPairTy ClassPair(RD, I->first);
1060
1061 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
1062 }
1063
1064 I = VirtualBaseClassIndicies.find(ClassPair);
1065 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
1066
1067 return I->second;
1068}
1069
Mike Stump2cefe382009-11-12 20:47:57 +00001070llvm::Constant *CodeGenModule::GenerateVtable(const CXXRecordDecl *LayoutClass,
1071 const CXXRecordDecl *RD,
Mike Stumpeac45592009-11-11 20:26:26 +00001072 uint64_t Offset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001073 llvm::SmallString<256> OutName;
Mike Stump2cefe382009-11-12 20:47:57 +00001074 if (LayoutClass != RD)
Daniel Dunbare128dd12009-11-21 09:06:22 +00001075 getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset/8, RD, OutName);
Mike Stumpeac45592009-11-11 20:26:26 +00001076 else
Daniel Dunbare128dd12009-11-21 09:06:22 +00001077 getMangleContext().mangleCXXVtable(RD, OutName);
1078 llvm::StringRef Name = OutName.str();
Benjamin Kramerbb0a07b2009-10-11 22:57:54 +00001079
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001080 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1081 int64_t AddressPoint;
1082
Mike Stumpaa51ad62009-11-19 04:04:36 +00001083 llvm::GlobalVariable *GV = getModule().getGlobalVariable(Name);
Mike Stumpcd2b8212009-11-19 20:52:19 +00001084 if (GV && AddressPoints[LayoutClass] && !GV->isDeclaration()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001085 AddressPoint=(*(*(AddressPoints[LayoutClass]))[RD])[std::make_pair(RD,
1086 Offset)];
Mike Stumpcd2b8212009-11-19 20:52:19 +00001087 // FIXME: We can never have 0 address point. Do this for now so gepping
1088 // retains the same structure. Later, we'll just assert.
1089 if (AddressPoint == 0)
1090 AddressPoint = 1;
1091 } else {
Anders Carlsson472404f2009-12-04 16:19:30 +00001092 VtableBuilder b(RD, LayoutClass, Offset, *this);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001093
Mike Stumpaa51ad62009-11-19 04:04:36 +00001094 D1(printf("vtable %s\n", RD->getNameAsCString()));
1095 // First comes the vtables for all the non-virtual bases...
1096 AddressPoint = b.GenerateVtableForBase(RD, Offset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001097
Mike Stumpaa51ad62009-11-19 04:04:36 +00001098 // then the vtables for all the virtual bases.
1099 b.GenerateVtableForVBases(RD, Offset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001100
Mike Stumpaa51ad62009-11-19 04:04:36 +00001101 bool CreateDefinition = true;
1102 if (LayoutClass != RD)
1103 CreateDefinition = true;
1104 else {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001105 const ASTRecordLayout &Layout =
1106 getContext().getASTRecordLayout(LayoutClass);
1107
1108 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001109 if (!KeyFunction->getBody()) {
1110 // If there is a KeyFunction, and it isn't defined, just build a
1111 // reference to the vtable.
1112 CreateDefinition = false;
1113 }
1114 }
1115 }
1116
1117 llvm::Constant *C = 0;
1118 llvm::Type *type = Ptr8Ty;
1119 llvm::GlobalVariable::LinkageTypes linktype
1120 = llvm::GlobalValue::ExternalLinkage;
1121 if (CreateDefinition) {
Anders Carlsson472404f2009-12-04 16:19:30 +00001122 llvm::ArrayType *ntype =
1123 llvm::ArrayType::get(Ptr8Ty, b.getVtable().size());
Anders Carlsson4e1d75f2009-12-04 16:22:27 +00001124 C = llvm::ConstantArray::get(ntype, &b.getVtable()[0],
1125 b.getVtable().size());
Mike Stumpaa51ad62009-11-19 04:04:36 +00001126 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
1127 if (LayoutClass->isInAnonymousNamespace())
1128 linktype = llvm::GlobalValue::InternalLinkage;
1129 type = ntype;
1130 }
1131 llvm::GlobalVariable *OGV = GV;
1132 GV = new llvm::GlobalVariable(getModule(), type, true, linktype, C, Name);
1133 if (OGV) {
1134 GV->takeName(OGV);
1135 llvm::Constant *NewPtr = llvm::ConstantExpr::getBitCast(GV,
1136 OGV->getType());
1137 OGV->replaceAllUsesWith(NewPtr);
1138 OGV->eraseFromParent();
1139 }
1140 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1141 if (Hidden)
1142 GV->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1143 }
Mike Stumpc0f632d2009-11-18 04:00:48 +00001144 llvm::Constant *vtable = llvm::ConstantExpr::getBitCast(GV, Ptr8Ty);
Mike Stumpd846d082009-11-10 07:44:33 +00001145 llvm::Constant *AddressPointC;
1146 uint32_t LLVMPointerWidth = getContext().Target.getPointerWidth(0);
1147 AddressPointC = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1148 AddressPoint*LLVMPointerWidth/8);
Mike Stump2cefe382009-11-12 20:47:57 +00001149 vtable = llvm::ConstantExpr::getInBoundsGetElementPtr(vtable, &AddressPointC,
1150 1);
Mike Stumpd846d082009-11-10 07:44:33 +00001151
Mike Stumpcd2b8212009-11-19 20:52:19 +00001152 assert(vtable->getType() == Ptr8Ty);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001153 return vtable;
1154}
Mike Stump9f23a142009-11-10 02:30:51 +00001155
Mike Stumpae1b85d2009-12-02 19:07:44 +00001156namespace {
Mike Stump9f23a142009-11-10 02:30:51 +00001157class VTTBuilder {
1158 /// Inits - The list of values built for the VTT.
1159 std::vector<llvm::Constant *> &Inits;
1160 /// Class - The most derived class that this vtable is being built for.
1161 const CXXRecordDecl *Class;
1162 CodeGenModule &CGM; // Per-module state.
Mike Stump8b2d2d02009-11-11 00:35:07 +00001163 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001164 /// BLayout - Layout for the most derived class that this vtable is being
1165 /// built for.
1166 const ASTRecordLayout &BLayout;
Mike Stump83066c82009-11-13 01:54:23 +00001167 CodeGenModule::AddrMap_t &AddressPoints;
Mike Stump2cefe382009-11-12 20:47:57 +00001168 // vtbl - A pointer to the vtable for Class.
1169 llvm::Constant *ClassVtbl;
1170 llvm::LLVMContext &VMContext;
Mike Stump9f23a142009-11-10 02:30:51 +00001171
Mike Stump8677bc22009-11-12 22:56:32 +00001172 /// BuildVtablePtr - Build up a referene to the given secondary vtable
Mike Stump83066c82009-11-13 01:54:23 +00001173 llvm::Constant *BuildVtablePtr(llvm::Constant *vtbl,
1174 const CXXRecordDecl *VtblClass,
1175 const CXXRecordDecl *RD,
Mike Stump8677bc22009-11-12 22:56:32 +00001176 uint64_t Offset) {
1177 int64_t AddressPoint;
Mike Stump83066c82009-11-13 01:54:23 +00001178 AddressPoint = (*AddressPoints[VtblClass])[std::make_pair(RD, Offset)];
Mike Stump2b34bc52009-11-12 23:36:21 +00001179 // FIXME: We can never have 0 address point. Do this for now so gepping
Mike Stumpcd2b8212009-11-19 20:52:19 +00001180 // retains the same structure. Later we'll just assert.
Mike Stump2b34bc52009-11-12 23:36:21 +00001181 if (AddressPoint == 0)
1182 AddressPoint = 1;
Mike Stump83066c82009-11-13 01:54:23 +00001183 D1(printf("XXX address point for %s in %s layout %s at offset %d was %d\n",
1184 RD->getNameAsCString(), VtblClass->getNameAsCString(),
1185 Class->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump8677bc22009-11-12 22:56:32 +00001186 uint32_t LLVMPointerWidth = CGM.getContext().Target.getPointerWidth(0);
1187 llvm::Constant *init;
1188 init = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1189 AddressPoint*LLVMPointerWidth/8);
1190 init = llvm::ConstantExpr::getInBoundsGetElementPtr(vtbl, &init, 1);
1191 return init;
1192 }
1193
Mike Stump2cefe382009-11-12 20:47:57 +00001194 /// Secondary - Add the secondary vtable pointers to Inits. Offset is the
1195 /// current offset in bits to the object we're working on.
Mike Stump8677bc22009-11-12 22:56:32 +00001196 void Secondary(const CXXRecordDecl *RD, llvm::Constant *vtbl,
Mike Stump83066c82009-11-13 01:54:23 +00001197 const CXXRecordDecl *VtblClass, uint64_t Offset=0,
1198 bool MorallyVirtual=false) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001199 if (RD->getNumVBases() == 0 && ! MorallyVirtual)
1200 return;
1201
1202 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1203 e = RD->bases_end(); i != e; ++i) {
1204 const CXXRecordDecl *Base =
1205 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1206 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1207 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1208 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1209 bool NonVirtualPrimaryBase;
1210 NonVirtualPrimaryBase = !PrimaryBaseWasVirtual && Base == PrimaryBase;
1211 bool BaseMorallyVirtual = MorallyVirtual | i->isVirtual();
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001212 uint64_t BaseOffset;
1213 if (!i->isVirtual()) {
1214 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1215 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1216 } else
1217 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump2b34bc52009-11-12 23:36:21 +00001218 llvm::Constant *subvtbl = vtbl;
Mike Stump83066c82009-11-13 01:54:23 +00001219 const CXXRecordDecl *subVtblClass = VtblClass;
Mike Stump8b2d2d02009-11-11 00:35:07 +00001220 if ((Base->getNumVBases() || BaseMorallyVirtual)
1221 && !NonVirtualPrimaryBase) {
1222 // FIXME: Slightly too many of these for __ZTT8test8_B2
Mike Stump8677bc22009-11-12 22:56:32 +00001223 llvm::Constant *init;
Mike Stump2b34bc52009-11-12 23:36:21 +00001224 if (BaseMorallyVirtual)
Mike Stump83066c82009-11-13 01:54:23 +00001225 init = BuildVtablePtr(vtbl, VtblClass, RD, Offset);
Mike Stump2b34bc52009-11-12 23:36:21 +00001226 else {
Mike Stump8677bc22009-11-12 22:56:32 +00001227 init = CGM.getVtableInfo().getCtorVtable(Class, Base, BaseOffset);
Mike Stump2b34bc52009-11-12 23:36:21 +00001228 subvtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump83066c82009-11-13 01:54:23 +00001229 subVtblClass = Base;
Mike Stump2b34bc52009-11-12 23:36:21 +00001230 }
Mike Stump8677bc22009-11-12 22:56:32 +00001231 Inits.push_back(init);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001232 }
Mike Stump83066c82009-11-13 01:54:23 +00001233 Secondary(Base, subvtbl, subVtblClass, BaseOffset, BaseMorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001234 }
1235 }
1236
Mike Stump2cefe382009-11-12 20:47:57 +00001237 /// BuiltVTT - Add the VTT to Inits. Offset is the offset in bits to the
1238 /// currnet object we're working on.
1239 void BuildVTT(const CXXRecordDecl *RD, uint64_t Offset, bool MorallyVirtual) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001240 if (RD->getNumVBases() == 0 && !MorallyVirtual)
1241 return;
1242
Mike Stump2cefe382009-11-12 20:47:57 +00001243 llvm::Constant *init;
Mike Stump83066c82009-11-13 01:54:23 +00001244 const CXXRecordDecl *VtblClass;
1245
Mike Stump8b2d2d02009-11-11 00:35:07 +00001246 // First comes the primary virtual table pointer...
Mike Stump83066c82009-11-13 01:54:23 +00001247 if (MorallyVirtual) {
1248 init = BuildVtablePtr(ClassVtbl, Class, RD, Offset);
1249 VtblClass = Class;
1250 } else {
Mike Stump2cefe382009-11-12 20:47:57 +00001251 init = CGM.getVtableInfo().getCtorVtable(Class, RD, Offset);
Mike Stump83066c82009-11-13 01:54:23 +00001252 VtblClass = RD;
1253 }
Mike Stump8677bc22009-11-12 22:56:32 +00001254 llvm::Constant *vtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump2cefe382009-11-12 20:47:57 +00001255 Inits.push_back(init);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001256
1257 // then the secondary VTTs....
Mike Stump2cefe382009-11-12 20:47:57 +00001258 SecondaryVTTs(RD, Offset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001259
1260 // and last the secondary vtable pointers.
Mike Stump83066c82009-11-13 01:54:23 +00001261 Secondary(RD, vtbl, VtblClass, Offset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001262 }
1263
1264 /// SecondaryVTTs - Add the secondary VTTs to Inits. The secondary VTTs are
1265 /// built from each direct non-virtual proper base that requires a VTT in
1266 /// declaration order.
Mike Stump2cefe382009-11-12 20:47:57 +00001267 void SecondaryVTTs(const CXXRecordDecl *RD, uint64_t Offset=0,
1268 bool MorallyVirtual=false) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001269 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1270 e = RD->bases_end(); i != e; ++i) {
1271 const CXXRecordDecl *Base =
1272 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1273 if (i->isVirtual())
1274 continue;
Mike Stump2cefe382009-11-12 20:47:57 +00001275 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1276 uint64_t BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1277 BuildVTT(Base, BaseOffset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001278 }
1279 }
1280
1281 /// VirtualVTTs - Add the VTT for each proper virtual base in inheritance
1282 /// graph preorder.
1283 void VirtualVTTs(const CXXRecordDecl *RD) {
1284 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1285 e = RD->bases_end(); i != e; ++i) {
1286 const CXXRecordDecl *Base =
1287 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1288 if (i->isVirtual() && !SeenVBase.count(Base)) {
1289 SeenVBase.insert(Base);
Mike Stump2cefe382009-11-12 20:47:57 +00001290 uint64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
1291 BuildVTT(Base, BaseOffset, true);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001292 }
1293 VirtualVTTs(Base);
1294 }
1295 }
Mike Stump9f23a142009-11-10 02:30:51 +00001296public:
1297 VTTBuilder(std::vector<llvm::Constant *> &inits, const CXXRecordDecl *c,
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001298 CodeGenModule &cgm)
1299 : Inits(inits), Class(c), CGM(cgm),
Mike Stump2cefe382009-11-12 20:47:57 +00001300 BLayout(cgm.getContext().getASTRecordLayout(c)),
Mike Stump83066c82009-11-13 01:54:23 +00001301 AddressPoints(*cgm.AddressPoints[c]),
Mike Stump2cefe382009-11-12 20:47:57 +00001302 VMContext(cgm.getModule().getContext()) {
Mike Stumpd846d082009-11-10 07:44:33 +00001303
Mike Stump8b2d2d02009-11-11 00:35:07 +00001304 // First comes the primary virtual table pointer for the complete class...
Mike Stump2cefe382009-11-12 20:47:57 +00001305 ClassVtbl = CGM.getVtableInfo().getVtable(Class);
1306 Inits.push_back(ClassVtbl);
1307 ClassVtbl = dyn_cast<llvm::Constant>(ClassVtbl->getOperand(0));
1308
Mike Stump8b2d2d02009-11-11 00:35:07 +00001309 // then the secondary VTTs...
1310 SecondaryVTTs(Class);
1311
1312 // then the secondary vtable pointers...
Mike Stump83066c82009-11-13 01:54:23 +00001313 Secondary(Class, ClassVtbl, Class);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001314
1315 // and last, the virtual VTTs.
1316 VirtualVTTs(Class);
Mike Stump9f23a142009-11-10 02:30:51 +00001317 }
1318};
Mike Stumpae1b85d2009-12-02 19:07:44 +00001319}
Mike Stump9f23a142009-11-10 02:30:51 +00001320
Mike Stumpd846d082009-11-10 07:44:33 +00001321llvm::Constant *CodeGenModule::GenerateVTT(const CXXRecordDecl *RD) {
Mike Stumpb4722212009-11-10 19:13:04 +00001322 // Only classes that have virtual bases need a VTT.
1323 if (RD->getNumVBases() == 0)
1324 return 0;
1325
Mike Stump9f23a142009-11-10 02:30:51 +00001326 llvm::SmallString<256> OutName;
Daniel Dunbare128dd12009-11-21 09:06:22 +00001327 getMangleContext().mangleCXXVTT(RD, OutName);
1328 llvm::StringRef Name = OutName.str();
Mike Stump9f23a142009-11-10 02:30:51 +00001329
1330 llvm::GlobalVariable::LinkageTypes linktype;
1331 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
Mike Stumpaa51ad62009-11-19 04:04:36 +00001332 if (RD->isInAnonymousNamespace())
1333 linktype = llvm::GlobalValue::InternalLinkage;
Mike Stump9f23a142009-11-10 02:30:51 +00001334 std::vector<llvm::Constant *> inits;
1335 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1336
Mike Stump9f23a142009-11-10 02:30:51 +00001337 D1(printf("vtt %s\n", RD->getNameAsCString()));
1338
Mike Stump8b2d2d02009-11-11 00:35:07 +00001339 VTTBuilder b(inits, RD, *this);
1340
Mike Stump9f23a142009-11-10 02:30:51 +00001341 llvm::Constant *C;
1342 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, inits.size());
1343 C = llvm::ConstantArray::get(type, inits);
Mike Stumpc0f632d2009-11-18 04:00:48 +00001344 llvm::GlobalVariable *vtt = new llvm::GlobalVariable(getModule(), type, true,
Mike Stumpaa51ad62009-11-19 04:04:36 +00001345 linktype, C, Name);
Mike Stumpc0f632d2009-11-18 04:00:48 +00001346 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1347 if (Hidden)
1348 vtt->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1349 return llvm::ConstantExpr::getBitCast(vtt, Ptr8Ty);
Mike Stump9f23a142009-11-10 02:30:51 +00001350}
Mike Stumpd846d082009-11-10 07:44:33 +00001351
Mike Stump1a139f82009-11-19 01:08:19 +00001352void CGVtableInfo::GenerateClassData(const CXXRecordDecl *RD) {
1353 Vtables[RD] = CGM.GenerateVtable(RD, RD);
Mike Stumpc01c2b82009-12-02 18:57:08 +00001354 CGM.GenerateRTTI(RD);
Mike Stump1a139f82009-11-19 01:08:19 +00001355 CGM.GenerateVTT(RD);
1356}
1357
Mike Stumpeac45592009-11-11 20:26:26 +00001358llvm::Constant *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Mike Stumpd846d082009-11-10 07:44:33 +00001359 llvm::Constant *&vtbl = Vtables[RD];
1360 if (vtbl)
1361 return vtbl;
Mike Stump2cefe382009-11-12 20:47:57 +00001362 vtbl = CGM.GenerateVtable(RD, RD);
Mike Stumpaa51ad62009-11-19 04:04:36 +00001363
1364 bool CreateDefinition = true;
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001365
1366 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1367 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001368 if (!KeyFunction->getBody()) {
1369 // If there is a KeyFunction, and it isn't defined, just build a
1370 // reference to the vtable.
1371 CreateDefinition = false;
1372 }
1373 }
1374
1375 if (CreateDefinition) {
Mike Stumpc01c2b82009-12-02 18:57:08 +00001376 CGM.GenerateRTTI(RD);
Mike Stumpaa51ad62009-11-19 04:04:36 +00001377 CGM.GenerateVTT(RD);
1378 }
Mike Stumpd846d082009-11-10 07:44:33 +00001379 return vtbl;
1380}
Mike Stumpeac45592009-11-11 20:26:26 +00001381
Mike Stump2cefe382009-11-12 20:47:57 +00001382llvm::Constant *CGVtableInfo::getCtorVtable(const CXXRecordDecl *LayoutClass,
1383 const CXXRecordDecl *RD,
Mike Stumpeac45592009-11-11 20:26:26 +00001384 uint64_t Offset) {
Mike Stump2cefe382009-11-12 20:47:57 +00001385 return CGM.GenerateVtable(LayoutClass, RD, Offset);
Mike Stumpeac45592009-11-11 20:26:26 +00001386}
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001387
1388void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
1389 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1390 const CXXRecordDecl *RD = MD->getParent();
1391
1392 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1393
1394 // Get the key function.
1395 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
1396
1397 if (!KeyFunction) {
1398 // If there's no key function, we don't want to emit the vtable here.
1399 return;
1400 }
1401
1402 // Check if we have the key function.
1403 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
1404 return;
1405
1406 // If the key function is a destructor, we only want to emit the vtable once,
1407 // so do it for the complete destructor.
1408 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Complete)
1409 return;
1410
1411 // Emit the data.
1412 GenerateClassData(RD);
1413}
1414