blob: e76ae834af9ed0d8d553fc6a5c4d1e3fa9d7db1a [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:
30 std::vector<llvm::Constant *> &methods;
31 std::vector<llvm::Constant *> submethods;
32 llvm::Type *Ptr8Ty;
33 /// Class - The most derived class that this vtable is being built for.
34 const CXXRecordDecl *Class;
Mike Stump83066c82009-11-13 01:54:23 +000035 /// LayoutClass - The most derived class used for virtual base layout
36 /// information.
37 const CXXRecordDecl *LayoutClass;
Mike Stump653d0b92009-11-13 02:13:54 +000038 /// LayoutOffset - The offset for Class in LayoutClass.
39 uint64_t LayoutOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000040 /// BLayout - Layout for the most derived class that this vtable is being
41 /// built for.
42 const ASTRecordLayout &BLayout;
43 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
44 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
45 llvm::Constant *rtti;
46 llvm::LLVMContext &VMContext;
47 CodeGenModule &CGM; // Per-module state.
48 /// Index - Maps a method decl into a vtable index. Useful for virtual
49 /// dispatch codegen.
Anders Carlssonfb4dda42009-11-13 17:08:56 +000050 llvm::DenseMap<GlobalDecl, Index_t> Index;
51 llvm::DenseMap<GlobalDecl, Index_t> VCall;
52 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stumpcd6f9ed2009-11-06 23:27:42 +000053 // This is the offset to the nearest virtual base
Anders Carlssonfb4dda42009-11-13 17:08:56 +000054 llvm::DenseMap<GlobalDecl, Index_t> NonVirtualOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000055 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stumpbb9ff052009-10-27 23:46:47 +000056
Anders Carlsson323bb042009-11-26 19:54:33 +000057 /// PureVirtualFunction - Points to __cxa_pure_virtual.
58 llvm::Constant *PureVirtualFn;
59
Anders Carlsson6d771bc2009-11-26 03:25:13 +000060 /// Thunk - Represents a single thunk.
61 struct Thunk {
62 Thunk()
63 : Index(0) { }
64
Anders Carlsson0e1e7632009-12-03 02:36:40 +000065 Thunk(uint64_t Index, GlobalDecl GD, const ThunkAdjustment &Adjustment)
66 : Index(Index), GD(GD), Adjustment(Adjustment) { }
Anders Carlsson6d771bc2009-11-26 03:25:13 +000067
68 /// Index - The index in the vtable.
69 uint64_t Index;
Anders Carlsson0e1e7632009-12-03 02:36:40 +000070
71 GlobalDecl GD;
72
Anders Carlssond420a312009-11-26 19:32:45 +000073 /// Adjustment - The thunk adjustment.
Anders Carlsson6d771bc2009-11-26 03:25:13 +000074 ThunkAdjustment Adjustment;
75 };
Anders Carlssond420a312009-11-26 19:32:45 +000076
77 /// Thunks - The thunks in a vtable.
Anders Carlsson29a1f752009-12-03 02:39:59 +000078 typedef llvm::DenseMap<uint64_t, Thunk> ThunksMapTy;
Anders Carlsson6d771bc2009-11-26 03:25:13 +000079 ThunksMapTy Thunks;
Anders Carlssond420a312009-11-26 19:32:45 +000080
81 /// CovariantThunk - Represents a single covariant thunk.
82 struct CovariantThunk {
Anders Carlsson1157e8f2009-12-03 02:20:26 +000083 CovariantThunk() { }
84
Anders Carlsson9f98f7a2009-12-03 02:34:59 +000085 CovariantThunk(GlobalDecl GD, CanQualType ReturnType)
86 : GD(GD), ReturnType(ReturnType) { }
Anders Carlsson06c14b62009-12-03 02:16:14 +000087
Anders Carlssonc38b40a2009-12-03 02:03:29 +000088 GlobalDecl GD;
89
Anders Carlssond420a312009-11-26 19:32:45 +000090 /// ReturnType - The return type of the function.
91 CanQualType ReturnType;
92 };
Anders Carlsson6d771bc2009-11-26 03:25:13 +000093
Anders Carlssond420a312009-11-26 19:32:45 +000094 /// CovariantThunks - The covariant thunks in a vtable.
Anders Carlsson73295f92009-12-03 02:12:03 +000095 typedef llvm::DenseMap<uint64_t, CovariantThunk> CovariantThunksMapTy;
Anders Carlssond420a312009-11-26 19:32:45 +000096 CovariantThunksMapTy CovariantThunks;
97
98 /// PureVirtualMethods - Pure virtual methods.
99 typedef llvm::DenseSet<GlobalDecl> PureVirtualMethodsSetTy;
100 PureVirtualMethodsSetTy PureVirtualMethods;
101
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000102 std::vector<Index_t> VCalls;
Mike Stump2cefe382009-11-12 20:47:57 +0000103
104 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stumpcd2b8212009-11-19 20:52:19 +0000105 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
106 // vtable for use in computing the initializers for the VTT.
107 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump2cefe382009-11-12 20:47:57 +0000108
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000109 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000110 const bool Extern;
111 const uint32_t LLVMPointerWidth;
112 Index_t extra;
Mike Stump37dbe962009-10-15 02:04:03 +0000113 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stumpcd2b8212009-11-19 20:52:19 +0000114 static llvm::DenseMap<CtorVtable_t, int64_t>&
115 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
116 const CXXRecordDecl *c) {
117 CodeGenModule::AddrMap_t *&oref = cgm.AddressPoints[l];
118 if (oref == 0)
119 oref = new CodeGenModule::AddrMap_t;
120
121 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
122 if (ref == 0)
123 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
124 return *ref;
125 }
Anders Carlsson323bb042009-11-26 19:54:33 +0000126
127 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
128 llvm::Constant* getPureVirtualFn() {
129 if (!PureVirtualFn) {
130 const llvm::FunctionType *Ty =
131 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
132 /*isVarArg=*/false);
133 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
134 }
135
136 return PureVirtualFn;
137 }
138
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000139public:
Mike Stump653d0b92009-11-13 02:13:54 +0000140 VtableBuilder(std::vector<llvm::Constant *> &meth, const CXXRecordDecl *c,
141 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm)
142 : methods(meth), Class(c), LayoutClass(l), LayoutOffset(lo),
Mike Stump83066c82009-11-13 01:54:23 +0000143 BLayout(cgm.getContext().getASTRecordLayout(l)),
Mike Stumpc01c2b82009-12-02 18:57:08 +0000144 rtti(cgm.GenerateRTTIRef(c)), VMContext(cgm.getModule().getContext()),
Anders Carlsson323bb042009-11-26 19:54:33 +0000145 CGM(cgm), PureVirtualFn(0),subAddressPoints(AllocAddressPoint(cgm, l, c)),
Mike Stump1960b202009-11-19 00:49:05 +0000146 Extern(!l->isInAnonymousNamespace()),
Anders Carlsson323bb042009-11-26 19:54:33 +0000147 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000148 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
149 }
150
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000151 llvm::DenseMap<GlobalDecl, Index_t> &getIndex() { return Index; }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000152 llvm::DenseMap<const CXXRecordDecl *, Index_t> &getVBIndex()
153 { return VBIndex; }
154
155 llvm::Constant *wrap(Index_t i) {
156 llvm::Constant *m;
157 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
158 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
159 }
160
161 llvm::Constant *wrap(llvm::Constant *m) {
162 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
163 }
164
Mike Stump8a96d3a2009-12-02 19:50:41 +0000165#define D1(x)
166//#define D1(X) do { if (getenv("DEBUG")) { X; } } while (0)
Mike Stump75ce5732009-10-31 20:06:59 +0000167
168 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stump28431212009-10-13 22:54:56 +0000169 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000170 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
171 e = RD->bases_end(); i != e; ++i) {
172 const CXXRecordDecl *Base =
173 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stump28431212009-10-13 22:54:56 +0000174 Index_t next_vbindex = current_vbindex;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000175 if (i->isVirtual() && !SeenVBase.count(Base)) {
176 SeenVBase.insert(Base);
Mike Stump28431212009-10-13 22:54:56 +0000177 if (updateVBIndex) {
Mike Stump75ce5732009-10-31 20:06:59 +0000178 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stump28431212009-10-13 22:54:56 +0000179 - 3*LLVMPointerWidth/8);
180 VBIndex[Base] = next_vbindex;
181 }
Mike Stump75ce5732009-10-31 20:06:59 +0000182 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
183 VCalls.push_back((0?700:0) + BaseOffset);
184 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
185 Base->getNameAsCString(),
186 (int)-VCalls.size()-3, (int)BaseOffset,
187 Class->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000188 }
Mike Stump28431212009-10-13 22:54:56 +0000189 // We also record offsets for non-virtual bases to closest enclosing
190 // virtual base. We do this so that we don't have to search
191 // for the nearst virtual base class when generating thunks.
192 if (updateVBIndex && VBIndex.count(Base) == 0)
193 VBIndex[Base] = next_vbindex;
Mike Stump75ce5732009-10-31 20:06:59 +0000194 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000195 }
196 }
197
198 void StartNewTable() {
199 SeenVBase.clear();
200 }
201
Mike Stump8bccbfd2009-10-15 09:30:16 +0000202 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
203 Index_t Offset = 0) {
204
205 if (B == D)
206 return Offset;
207
208 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
209 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
210 e = D->bases_end(); i != e; ++i) {
211 const CXXRecordDecl *Base =
212 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
213 int64_t BaseOffset = 0;
214 if (!i->isVirtual())
215 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
216 int64_t o = getNVOffset_1(Base, B, BaseOffset);
217 if (o >= 0)
218 return o;
219 }
220
221 return -1;
222 }
223
224 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
225 /// derived class D.
226 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump46271322009-11-03 19:03:17 +0000227 qD = qD->getPointeeType();
228 qB = qB->getPointeeType();
Mike Stump8bccbfd2009-10-15 09:30:16 +0000229 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
230 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
231 int64_t o = getNVOffset_1(D, B);
232 if (o >= 0)
233 return o;
234
235 assert(false && "FIXME: non-virtual base not found");
236 return 0;
237 }
238
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000239 /// getVbaseOffset - Returns the index into the vtable for the virtual base
240 /// offset for the given (B) virtual base of the derived class D.
241 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump46271322009-11-03 19:03:17 +0000242 qD = qD->getPointeeType();
243 qB = qB->getPointeeType();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000244 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
245 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
246 if (D != Class)
Eli Friedman03aa2f12009-11-30 01:19:33 +0000247 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000248 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
249 i = VBIndex.find(B);
250 if (i != VBIndex.end())
251 return i->second;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000252
Mike Stump28431212009-10-13 22:54:56 +0000253 assert(false && "FIXME: Base not found");
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000254 return 0;
255 }
256
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000257 bool OverrideMethod(GlobalDecl GD, llvm::Constant *m,
Mike Stump8bccbfd2009-10-15 09:30:16 +0000258 bool MorallyVirtual, Index_t OverrideOffset,
Anders Carlssonca1bf682009-12-03 01:54:02 +0000259 Index_t Offset, int64_t CurrentVBaseOffset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000260
261 void InstallThunks() {
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000262 for (CovariantThunksMapTy::const_iterator i = CovariantThunks.begin(),
263 e = CovariantThunks.end(); i != e; ++i) {
Anders Carlsson73295f92009-12-03 02:12:03 +0000264 GlobalDecl GD = i->second.GD;
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000265 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
266 if (MD->isPure())
267 continue;
268
Anders Carlsson06c14b62009-12-03 02:16:14 +0000269 uint64_t Index = i->first;
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000270 const CovariantThunk &Thunk = i->second;
Anders Carlsson06c14b62009-12-03 02:16:14 +0000271 assert(Index == VtableBuilder::Index[GD] && "Thunk index mismatch!");
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000272
273 // Check if there is an adjustment for the 'this' pointer.
274 ThunkAdjustment ThisAdjustment;
Anders Carlsson29a1f752009-12-03 02:39:59 +0000275 ThunksMapTy::iterator i = Thunks.find(Index);
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000276 if (i != Thunks.end()) {
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000277 ThisAdjustment = i->second.Adjustment;
278
279 Thunks.erase(i);
280 }
Anders Carlsson657f1392009-12-03 02:32:59 +0000281
282 // Construct the return adjustment.
283 QualType DerivedType =
284 MD->getType()->getAs<FunctionType>()->getResultType();
285
286 int64_t NonVirtualAdjustment =
287 getNVOffset(Thunk.ReturnType, DerivedType) / 8;
288
289 int64_t VirtualAdjustment =
290 getVbaseOffset(Thunk.ReturnType, DerivedType);
291
292 ThunkAdjustment ReturnAdjustment(NonVirtualAdjustment, VirtualAdjustment);
293
294 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Anders Carlsson06c14b62009-12-03 02:16:14 +0000295 submethods[Index] = CGM.BuildCovariantThunk(MD, Extern, Adjustment);
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000296 }
297 CovariantThunks.clear();
Anders Carlssonc38b40a2009-12-03 02:03:29 +0000298
Anders Carlsson6d771bc2009-11-26 03:25:13 +0000299 for (ThunksMapTy::const_iterator i = Thunks.begin(), e = Thunks.end();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000300 i != e; ++i) {
Anders Carlsson29a1f752009-12-03 02:39:59 +0000301 GlobalDecl GD = i->second.GD;
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000302 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson6d771bc2009-11-26 03:25:13 +0000303 assert(!MD->isPure() && "Can't thunk pure virtual methods!");
304
305 const Thunk& Thunk = i->second;
Anders Carlsson29a1f752009-12-03 02:39:59 +0000306 uint64_t Index = Thunk.Index;
307
308 assert(Index == VtableBuilder::Index[GD] && "Thunk index mismatch!");
Anders Carlsson6d771bc2009-11-26 03:25:13 +0000309
310 submethods[Thunk.Index] = CGM.BuildThunk(MD, Extern, Thunk.Adjustment);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000311 }
312 Thunks.clear();
Anders Carlsson6d771bc2009-11-26 03:25:13 +0000313
Anders Carlssond420a312009-11-26 19:32:45 +0000314 for (PureVirtualMethodsSetTy::iterator i = PureVirtualMethods.begin(),
315 e = PureVirtualMethods.end(); i != e; ++i) {
316 GlobalDecl GD = *i;
Anders Carlsson323bb042009-11-26 19:54:33 +0000317 submethods[Index[GD]] = getPureVirtualFn();
Mike Stumpbb9ff052009-10-27 23:46:47 +0000318 }
Anders Carlssond420a312009-11-26 19:32:45 +0000319 PureVirtualMethods.clear();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000320 }
321
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000322 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
323 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
324
Mike Stump18e8b472009-10-27 23:36:26 +0000325 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD))
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000326 return wrap(CGM.GetAddrOfCXXDestructor(Dtor, GD.getDtorType()));
Mike Stump18e8b472009-10-27 23:36:26 +0000327
Anders Carlsson64457732009-11-24 05:08:52 +0000328 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump18e8b472009-10-27 23:36:26 +0000329
330 return wrap(CGM.GetAddrOfFunction(MD, Ty));
331 }
332
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000333 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
334 int64_t CurrentVBaseOffset) {
Mike Stump37dbe962009-10-15 02:04:03 +0000335 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000336 e = Path->rend(); i != e; ++i) {
337 const CXXRecordDecl *RD = i->first;
Mike Stump8bccbfd2009-10-15 09:30:16 +0000338 int64_t OverrideOffset = i->second;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000339 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
340 ++mi) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000341 const CXXMethodDecl *MD = *mi;
342
343 if (!MD->isVirtual())
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000344 continue;
345
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000346 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
347 // Override both the complete and the deleting destructor.
348 GlobalDecl CompDtor(DD, Dtor_Complete);
349 OverrideMethod(CompDtor, WrapAddrOf(CompDtor), MorallyVirtual,
350 OverrideOffset, Offset, CurrentVBaseOffset);
351
352 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
353 OverrideMethod(DeletingDtor, WrapAddrOf(DeletingDtor), MorallyVirtual,
354 OverrideOffset, Offset, CurrentVBaseOffset);
355 } else {
356 OverrideMethod(MD, WrapAddrOf(MD), MorallyVirtual, OverrideOffset,
357 Offset, CurrentVBaseOffset);
358 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000359 }
360 }
361 }
362
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000363 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000364 int64_t CurrentVBaseOffset) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000365 llvm::Constant *m = WrapAddrOf(GD);
Mike Stump18e8b472009-10-27 23:36:26 +0000366
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000367 // If we can find a previously allocated slot for this, reuse it.
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000368 if (OverrideMethod(GD, m, MorallyVirtual, Offset, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000369 CurrentVBaseOffset))
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000370 return;
371
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000372 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
373
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000374 // else allocate a new slot.
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000375 Index[GD] = submethods.size();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000376 submethods.push_back(m);
Mike Stumpc5a332c2009-11-13 23:45:53 +0000377 D1(printf(" vfn for %s at %d\n", MD->getNameAsString().c_str(),
378 (int)Index[GD]));
Mike Stump375faa82009-10-28 00:35:46 +0000379 if (MD->isPure())
Anders Carlssond420a312009-11-26 19:32:45 +0000380 PureVirtualMethods.insert(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000381 if (MorallyVirtual) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000382 VCallOffset[GD] = Offset/8;
383 Index_t &idx = VCall[GD];
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000384 // Allocate the first one, after that, we reuse the previous one.
385 if (idx == 0) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000386 NonVirtualOffset[GD] = CurrentVBaseOffset/8 - Offset/8;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000387 idx = VCalls.size()+1;
388 VCalls.push_back(0);
Mike Stump75ce5732009-10-31 20:06:59 +0000389 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpc5a332c2009-11-13 23:45:53 +0000390 MD->getNameAsString().c_str(), (int)-VCalls.size()-3, 0));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000391 }
392 }
393 }
394
395 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000396 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000397 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000398 ++mi) {
399 const CXXMethodDecl *MD = *mi;
400 if (!MD->isVirtual())
401 continue;
402
403 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
404 // For destructors, add both the complete and the deleting destructor
405 // to the vtable.
406 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000407 CurrentVBaseOffset);
Eli Friedman03aa2f12009-11-30 01:19:33 +0000408 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
409 CurrentVBaseOffset);
410 } else
411 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000412 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000413 }
414
415 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
416 const CXXRecordDecl *PrimaryBase,
417 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000418 int64_t Offset, int64_t CurrentVBaseOffset,
419 Path_t *Path) {
Mike Stump37dbe962009-10-15 02:04:03 +0000420 Path->push_back(std::make_pair(RD, Offset));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000421 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
422 e = RD->bases_end(); i != e; ++i) {
423 if (i->isVirtual())
424 continue;
425 const CXXRecordDecl *Base =
426 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
427 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
428 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
429 StartNewTable();
Mike Stump653d0b92009-11-13 02:13:54 +0000430 GenerateVtableForBase(Base, o, MorallyVirtual, false,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000431 CurrentVBaseOffset, Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000432 }
433 }
Mike Stump37dbe962009-10-15 02:04:03 +0000434 Path->pop_back();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000435 }
436
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000437// #define D(X) do { X; } while (0)
438#define D(X)
439
440 void insertVCalls(int InsertionPoint) {
441 llvm::Constant *e = 0;
Mike Stump75ce5732009-10-31 20:06:59 +0000442 D1(printf("============= combining vbase/vcall\n"));
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000443 D(VCalls.insert(VCalls.begin(), 673));
444 D(VCalls.push_back(672));
Mike Stump8bccbfd2009-10-15 09:30:16 +0000445 methods.insert(methods.begin() + InsertionPoint, VCalls.size(), e);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000446 // The vcalls come first...
447 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
448 e = VCalls.rend();
449 i != e; ++i)
450 methods[InsertionPoint++] = wrap((0?600:0) + *i);
451 VCalls.clear();
Mike Stump9f23a142009-11-10 02:30:51 +0000452 VCall.clear();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000453 }
454
Mike Stump559387f2009-11-13 23:13:20 +0000455 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
456 Index_t AddressPoint) {
457 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
458 RD->getNameAsCString(), Class->getNameAsCString(),
459 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stumpcd2b8212009-11-19 20:52:19 +0000460 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump559387f2009-11-13 23:13:20 +0000461
462 // Now also add the address point for all our primary bases.
463 while (1) {
464 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
465 RD = Layout.getPrimaryBase();
466 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
467 // FIXME: Double check this.
468 if (RD == 0)
469 break;
470 if (PrimaryBaseWasVirtual &&
471 BLayout.getVBaseClassOffset(RD) != Offset)
472 break;
473 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
474 RD->getNameAsCString(), Class->getNameAsCString(),
475 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stumpcd2b8212009-11-19 20:52:19 +0000476 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump559387f2009-11-13 23:13:20 +0000477 }
478 }
479
480
Mike Stump75ce5732009-10-31 20:06:59 +0000481 Index_t end(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
482 const CXXRecordDecl *PrimaryBase, bool PrimaryBaseWasVirtual,
483 bool MorallyVirtual, int64_t Offset, bool ForVirtualBase,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000484 int64_t CurrentVBaseOffset,
Mike Stump75ce5732009-10-31 20:06:59 +0000485 Path_t *Path) {
Mike Stump37dbe962009-10-15 02:04:03 +0000486 bool alloc = false;
487 if (Path == 0) {
488 alloc = true;
489 Path = new Path_t;
490 }
491
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000492 StartNewTable();
493 extra = 0;
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000494 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
495 int VCallInsertionPoint = methods.size();
496 if (!DeferVCalls) {
497 insertVCalls(VCallInsertionPoint);
Mike Stump8bccbfd2009-10-15 09:30:16 +0000498 } else
499 // FIXME: just for extra, or for all uses of VCalls.size post this?
500 extra = -VCalls.size();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000501
Mike Stump653d0b92009-11-13 02:13:54 +0000502 methods.push_back(wrap(-((Offset-LayoutOffset)/8)));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000503 methods.push_back(rtti);
504 Index_t AddressPoint = methods.size();
505
506 InstallThunks();
Mike Stump75ce5732009-10-31 20:06:59 +0000507 D1(printf("============= combining methods\n"));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000508 methods.insert(methods.end(), submethods.begin(), submethods.end());
509 submethods.clear();
510
511 // and then the non-virtual bases.
512 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000513 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000514
515 if (ForVirtualBase) {
Mike Stump2cefe382009-11-12 20:47:57 +0000516 // FIXME: We're adding to VCalls in callers, we need to do the overrides
517 // in the inner part, so that we know the complete set of vcalls during
518 // the build and don't have to insert into methods. Saving out the
519 // AddressPoint here, would need to be fixed, if we didn't do that. Also
520 // retroactively adding vcalls for overrides later wind up in the wrong
521 // place, the vcall slot has to be alloted during the walk of the base
522 // when the function is first introduces.
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000523 AddressPoint += VCalls.size();
Mike Stump2cefe382009-11-12 20:47:57 +0000524 insertVCalls(VCallInsertionPoint);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000525 }
526
Mike Stump559387f2009-11-13 23:13:20 +0000527 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump2cefe382009-11-12 20:47:57 +0000528
Mike Stump37dbe962009-10-15 02:04:03 +0000529 if (alloc) {
530 delete Path;
531 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000532 return AddressPoint;
533 }
534
Mike Stump75ce5732009-10-31 20:06:59 +0000535 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
536 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000537 int64_t CurrentVBaseOffset) {
Mike Stump75ce5732009-10-31 20:06:59 +0000538 if (!RD->isDynamicClass())
539 return;
540
541 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
542 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
543 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
544
545 // vtables are composed from the chain of primaries.
546 if (PrimaryBase) {
547 D1(printf(" doing primaries for %s most derived %s\n",
548 RD->getNameAsCString(), Class->getNameAsCString()));
549
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000550 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
551 if (PrimaryBaseWasVirtual)
552 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
553
Mike Stump75ce5732009-10-31 20:06:59 +0000554 if (!PrimaryBaseWasVirtual)
555 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000556 updateVBIndex, current_vbindex, BaseCurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000557 }
558
559 D1(printf(" doing vcall entries for %s most derived %s\n",
560 RD->getNameAsCString(), Class->getNameAsCString()));
561
562 // And add the virtuals for the class to the primary vtable.
Eli Friedman03aa2f12009-11-30 01:19:33 +0000563 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000564 }
565
566 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
567 bool updateVBIndex, Index_t current_vbindex,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000568 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000569 bool bottom) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000570 if (!RD->isDynamicClass())
571 return;
572
573 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
574 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
575 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
576
577 // vtables are composed from the chain of primaries.
578 if (PrimaryBase) {
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000579 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
580 if (PrimaryBaseWasVirtual) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000581 IndirectPrimary.insert(PrimaryBase);
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000582 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
583 }
Mike Stump75ce5732009-10-31 20:06:59 +0000584
585 D1(printf(" doing primaries for %s most derived %s\n",
586 RD->getNameAsCString(), Class->getNameAsCString()));
587
588 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000589 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000590 BaseCurrentVBaseOffset, false);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000591 }
592
Mike Stump75ce5732009-10-31 20:06:59 +0000593 D1(printf(" doing vbase entries for %s most derived %s\n",
594 RD->getNameAsCString(), Class->getNameAsCString()));
595 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
596
597 if (RDisVirtualBase || bottom) {
598 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000599 CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000600 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000601 }
602
Mike Stump653d0b92009-11-13 02:13:54 +0000603 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
604 bool MorallyVirtual = false,
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000605 bool ForVirtualBase = false,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000606 int CurrentVBaseOffset = 0,
Mike Stump37dbe962009-10-15 02:04:03 +0000607 Path_t *Path = 0) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000608 if (!RD->isDynamicClass())
609 return 0;
610
Mike Stumpfa818082009-11-13 02:35:38 +0000611 // Construction vtable don't need parts that have no virtual bases and
612 // aren't morally virtual.
613 if ((LayoutClass != Class) && RD->getNumVBases() == 0 && !MorallyVirtual)
614 return 0;
615
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000616 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
617 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
618 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
619
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000620 extra = 0;
Mike Stump75ce5732009-10-31 20:06:59 +0000621 D1(printf("building entries for base %s most derived %s\n",
622 RD->getNameAsCString(), Class->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000623
Mike Stump75ce5732009-10-31 20:06:59 +0000624 if (ForVirtualBase)
625 extra = VCalls.size();
626
627 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0, ForVirtualBase,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000628 CurrentVBaseOffset, true);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000629
630 if (Path)
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000631 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000632
Mike Stump75ce5732009-10-31 20:06:59 +0000633 return end(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual, MorallyVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000634 Offset, ForVirtualBase, CurrentVBaseOffset, Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000635 }
636
637 void GenerateVtableForVBases(const CXXRecordDecl *RD,
638 int64_t Offset = 0,
Mike Stump37dbe962009-10-15 02:04:03 +0000639 Path_t *Path = 0) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000640 bool alloc = false;
641 if (Path == 0) {
642 alloc = true;
Mike Stump37dbe962009-10-15 02:04:03 +0000643 Path = new Path_t;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000644 }
645 // FIXME: We also need to override using all paths to a virtual base,
646 // right now, we just process the first path
647 Path->push_back(std::make_pair(RD, Offset));
648 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
649 e = RD->bases_end(); i != e; ++i) {
650 const CXXRecordDecl *Base =
651 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
652 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
653 // Mark it so we don't output it twice.
654 IndirectPrimary.insert(Base);
655 StartNewTable();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000656 VCall.clear();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000657 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000658 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump75ce5732009-10-31 20:06:59 +0000659 D1(printf("vtable %s virtual base %s\n",
660 Class->getNameAsCString(), Base->getNameAsCString()));
Mike Stump653d0b92009-11-13 02:13:54 +0000661 GenerateVtableForBase(Base, BaseOffset, true, true, CurrentVBaseOffset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000662 Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000663 }
Mike Stump2cefe382009-11-12 20:47:57 +0000664 int64_t BaseOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000665 if (i->isVirtual())
666 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump2cefe382009-11-12 20:47:57 +0000667 else {
668 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
669 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
670 }
671
Mike Stump37dbe962009-10-15 02:04:03 +0000672 if (Base->getNumVBases()) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000673 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump37dbe962009-10-15 02:04:03 +0000674 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000675 }
676 Path->pop_back();
677 if (alloc)
678 delete Path;
679 }
680};
Anders Carlssonca1bf682009-12-03 01:54:02 +0000681} // end anonymous namespace
682
Anders Carlsson657f1392009-12-03 02:32:59 +0000683/// TypeConversionRequiresAdjustment - Returns whether conversion from a
684/// derived type to a base type requires adjustment.
685static bool
686TypeConversionRequiresAdjustment(ASTContext &Ctx,
687 const CXXRecordDecl *DerivedDecl,
688 const CXXRecordDecl *BaseDecl) {
689 CXXBasePaths Paths(/*FindAmbiguities=*/false,
690 /*RecordPaths=*/true, /*DetectVirtual=*/true);
691 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
692 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
693 assert(false && "Class must be derived from the passed in base class!");
694 return false;
695 }
696
697 // If we found a virtual base we always want to require adjustment.
698 if (Paths.getDetectedVirtual())
699 return true;
700
701 const CXXBasePath &Path = Paths.front();
702
703 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
704 const CXXBasePathElement &Element = Path[Start];
705
706 // Check the base class offset.
707 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
708
709 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
710 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
711
712 if (Layout.getBaseClassOffset(Base) != 0) {
713 // This requires an adjustment.
714 return true;
715 }
716 }
717
718 return false;
719}
720
721static bool
722TypeConversionRequiresAdjustment(ASTContext &Ctx,
723 QualType DerivedType, QualType BaseType) {
724 // Canonicalize the types.
725 QualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
726 QualType CanBaseType = Ctx.getCanonicalType(BaseType);
727
728 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
729 "Types must have same type class!");
730
731 if (CanDerivedType == CanBaseType) {
732 // No adjustment needed.
733 return false;
734 }
735
736 if (const ReferenceType *RT = dyn_cast<ReferenceType>(CanDerivedType)) {
737 CanDerivedType = RT->getPointeeType();
738 CanBaseType = cast<ReferenceType>(CanBaseType)->getPointeeType();
739 } else if (const PointerType *PT = dyn_cast<PointerType>(CanDerivedType)) {
740 CanDerivedType = PT->getPointeeType();
741 CanBaseType = cast<PointerType>(CanBaseType)->getPointeeType();
742 } else {
743 assert(false && "Unexpected return type!");
744 }
745
746 if (CanDerivedType == CanBaseType) {
747 // No adjustment needed.
748 return false;
749 }
750
751 const CXXRecordDecl *DerivedDecl =
752 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
753
754 const CXXRecordDecl *BaseDecl =
755 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
756
757 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
758}
759
Anders Carlssonca1bf682009-12-03 01:54:02 +0000760bool VtableBuilder::OverrideMethod(GlobalDecl GD, llvm::Constant *m,
761 bool MorallyVirtual, Index_t OverrideOffset,
762 Index_t Offset, int64_t CurrentVBaseOffset) {
763 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
764
765 const bool isPure = MD->isPure();
766 typedef CXXMethodDecl::method_iterator meth_iter;
767 // FIXME: Should OverrideOffset's be Offset?
768
769 // FIXME: Don't like the nested loops. For very large inheritance
770 // heirarchies we could have a table on the side with the final overridder
771 // and just replace each instance of an overridden method once. Would be
772 // nice to measure the cost/benefit on real code.
773
774 for (meth_iter mi = MD->begin_overridden_methods(),
775 e = MD->end_overridden_methods();
776 mi != e; ++mi) {
777 GlobalDecl OGD;
778
779 const CXXMethodDecl *OMD = *mi;
780 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
781 OGD = GlobalDecl(DD, GD.getDtorType());
782 else
783 OGD = OMD;
784
785 llvm::Constant *om;
786 om = WrapAddrOf(OGD);
787 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
788
789 for (Index_t i = 0, e = submethods.size();
790 i != e; ++i) {
791 // FIXME: begin_overridden_methods might be too lax, covariance */
792 if (submethods[i] != om)
793 continue;
Anders Carlsson657f1392009-12-03 02:32:59 +0000794
795 QualType ReturnType =
796 MD->getType()->getAs<FunctionType>()->getResultType();
797 QualType OverriddenReturnType =
798 OMD->getType()->getAs<FunctionType>()->getResultType();
799
800 // Check if we need a return type adjustment.
801 if (TypeConversionRequiresAdjustment(CGM.getContext(), ReturnType,
802 OverriddenReturnType)) {
803 CovariantThunk &Adjustment = CovariantThunks[i];
Anders Carlsson2ca285f2009-12-03 02:22:59 +0000804
Anders Carlsson657f1392009-12-03 02:32:59 +0000805 // Get the canonical return type.
806 CanQualType CanReturnType =
807 CGM.getContext().getCanonicalType(ReturnType);
808
809 // Insert the base return type.
810 if (Adjustment.ReturnType.isNull())
811 Adjustment.ReturnType =
812 CGM.getContext().getCanonicalType(OverriddenReturnType);
813
814 Adjustment.GD = GD;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000815 }
Anders Carlsson657f1392009-12-03 02:32:59 +0000816
Anders Carlssonca1bf682009-12-03 01:54:02 +0000817 Index[GD] = i;
818 submethods[i] = m;
819 if (isPure)
820 PureVirtualMethods.insert(GD);
821 PureVirtualMethods.erase(OGD);
Anders Carlsson29a1f752009-12-03 02:39:59 +0000822 Thunks.erase(i);
Anders Carlssonca1bf682009-12-03 01:54:02 +0000823 if (MorallyVirtual || VCall.count(OGD)) {
824 Index_t &idx = VCall[OGD];
825 if (idx == 0) {
826 NonVirtualOffset[GD] = -OverrideOffset/8 + CurrentVBaseOffset/8;
827 VCallOffset[GD] = OverrideOffset/8;
828 idx = VCalls.size()+1;
829 VCalls.push_back(0);
830 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
831 MD->getNameAsString().c_str(), (int)-idx-3,
832 (int)VCalls[idx-1], Class->getNameAsCString()));
833 } else {
834 NonVirtualOffset[GD] = NonVirtualOffset[OGD];
835 VCallOffset[GD] = VCallOffset[OGD];
836 VCalls[idx-1] = -VCallOffset[OGD] + OverrideOffset/8;
837 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
838 MD->getNameAsString().c_str(), (int)-idx-3,
839 (int)VCalls[idx-1], Class->getNameAsCString()));
840 }
841 VCall[GD] = idx;
842 int64_t NonVirtualAdjustment = NonVirtualOffset[GD];
843 int64_t VirtualAdjustment =
844 -((idx + extra + 2) * LLVMPointerWidth / 8);
845
846 // Optimize out virtual adjustments of 0.
847 if (VCalls[idx-1] == 0)
848 VirtualAdjustment = 0;
849
850 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
851 VirtualAdjustment);
852
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000853 if (!isPure && !ThisAdjustment.isEmpty())
Anders Carlsson29a1f752009-12-03 02:39:59 +0000854 Thunks[i] = Thunk(i, GD, ThisAdjustment);
Anders Carlssonca1bf682009-12-03 01:54:02 +0000855 return true;
856 }
857
858 // FIXME: finish off
859 int64_t NonVirtualAdjustment = VCallOffset[OGD] - OverrideOffset/8;
860
Anders Carlsson2ca285f2009-12-03 02:22:59 +0000861 if (NonVirtualAdjustment) {
Anders Carlssonca1bf682009-12-03 01:54:02 +0000862 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
863
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000864 if (!isPure)
Anders Carlsson29a1f752009-12-03 02:39:59 +0000865 Thunks[i] = Thunk(i, GD, ThisAdjustment);
Anders Carlssonca1bf682009-12-03 01:54:02 +0000866 }
867 return true;
868 }
869 }
870
871 return false;
Anders Carlssond59885022009-11-27 22:21:51 +0000872}
873
Anders Carlssonf942ee02009-11-27 20:47:55 +0000874void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
875
876 // Itanium C++ ABI 2.5.2:
877 // The order of the virtual function pointers in a virtual table is the
878 // order of declaration of the corresponding member functions in the class.
879 //
880 // There is an entry for any virtual function declared in a class,
881 // whether it is a new function or overrides a base class function,
882 // unless it overrides a function from the primary base, and conversion
883 // between their return types does not require an adjustment.
884
885 int64_t CurrentIndex = 0;
886
887 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
888 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
889
890 if (PrimaryBase) {
Anders Carlssonc920fa22009-11-30 19:43:26 +0000891 assert(PrimaryBase->isDefinition() &&
892 "Should have the definition decl of the primary base!");
Anders Carlssonf942ee02009-11-27 20:47:55 +0000893
894 // Since the record decl shares its vtable pointer with the primary base
895 // we need to start counting at the end of the primary base's vtable.
896 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
897 }
898
899 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
900
901 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
902 e = RD->method_end(); i != e; ++i) {
903 const CXXMethodDecl *MD = *i;
904
905 // We only want virtual methods.
906 if (!MD->isVirtual())
907 continue;
908
909 bool ShouldAddEntryForMethod = true;
910
911 // Check if this method overrides a method in the primary base.
912 for (CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
913 e = MD->end_overridden_methods(); i != e; ++i) {
914 const CXXMethodDecl *OverriddenMD = *i;
915 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
916 assert(OverriddenMD->isCanonicalDecl() &&
917 "Should have the canonical decl of the overridden RD!");
918
919 if (OverriddenRD == PrimaryBase) {
920 // Check if converting from the return type of the method to the
921 // return type of the overridden method requires conversion.
922 QualType ReturnType =
923 MD->getType()->getAs<FunctionType>()->getResultType();
924 QualType OverriddenReturnType =
925 OverriddenMD->getType()->getAs<FunctionType>()->getResultType();
926
927 if (!TypeConversionRequiresAdjustment(CGM.getContext(),
928 ReturnType, OverriddenReturnType)) {
929 // This index is shared between the index in the vtable of the primary
930 // base class.
931 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
932 const CXXDestructorDecl *OverriddenDD =
933 cast<CXXDestructorDecl>(OverriddenMD);
934
935 // Add both the complete and deleting entries.
936 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
937 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
938 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
939 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
940 } else {
941 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
942 }
943
944 // We don't need to add an entry for this method.
945 ShouldAddEntryForMethod = false;
946 break;
947 }
948 }
949 }
950
951 if (!ShouldAddEntryForMethod)
952 continue;
953
954 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
955 if (MD->isImplicit()) {
956 assert(!ImplicitVirtualDtor &&
957 "Did already see an implicit virtual dtor!");
958 ImplicitVirtualDtor = DD;
959 continue;
960 }
961
962 // Add the complete dtor.
963 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
964
965 // Add the deleting dtor.
966 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
967 } else {
968 // Add the entry.
969 MethodVtableIndices[MD] = CurrentIndex++;
970 }
971 }
972
973 if (ImplicitVirtualDtor) {
974 // Itanium C++ ABI 2.5.2:
975 // If a class has an implicitly-defined virtual destructor,
976 // its entries come after the declared virtual function pointers.
977
978 // Add the complete dtor.
979 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
980 CurrentIndex++;
981
982 // Add the deleting dtor.
983 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
984 CurrentIndex++;
985 }
986
987 NumVirtualFunctionPointers[RD] = CurrentIndex;
988}
989
990uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
991 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
992 NumVirtualFunctionPointers.find(RD);
993 if (I != NumVirtualFunctionPointers.end())
994 return I->second;
995
996 ComputeMethodVtableIndices(RD);
997
998 I = NumVirtualFunctionPointers.find(RD);
999 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
1000 return I->second;
1001}
1002
1003uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001004 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001005 if (I != MethodVtableIndices.end())
1006 return I->second;
1007
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001008 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001009
1010 ComputeMethodVtableIndices(RD);
1011
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001012 I = MethodVtableIndices.find(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001013 assert(I != MethodVtableIndices.end() && "Did not find index!");
1014 return I->second;
1015}
1016
1017int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
1018 const CXXRecordDecl *VBase) {
1019 ClassPairTy ClassPair(RD, VBase);
1020
1021 VirtualBaseClassIndiciesTy::iterator I =
1022 VirtualBaseClassIndicies.find(ClassPair);
1023 if (I != VirtualBaseClassIndicies.end())
1024 return I->second;
1025
1026 std::vector<llvm::Constant *> methods;
1027 // FIXME: This seems expensive. Can we do a partial job to get
1028 // just this data.
Mike Stump653d0b92009-11-13 02:13:54 +00001029 VtableBuilder b(methods, RD, RD, 0, CGM);
Mike Stump75ce5732009-10-31 20:06:59 +00001030 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001031 b.GenerateVtableForBase(RD);
1032 b.GenerateVtableForVBases(RD);
1033
1034 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1035 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
1036 // Insert all types.
1037 ClassPairTy ClassPair(RD, I->first);
1038
1039 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
1040 }
1041
1042 I = VirtualBaseClassIndicies.find(ClassPair);
1043 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
1044
1045 return I->second;
1046}
1047
Mike Stump2cefe382009-11-12 20:47:57 +00001048llvm::Constant *CodeGenModule::GenerateVtable(const CXXRecordDecl *LayoutClass,
1049 const CXXRecordDecl *RD,
Mike Stumpeac45592009-11-11 20:26:26 +00001050 uint64_t Offset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001051 llvm::SmallString<256> OutName;
Mike Stump2cefe382009-11-12 20:47:57 +00001052 if (LayoutClass != RD)
Daniel Dunbare128dd12009-11-21 09:06:22 +00001053 getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset/8, RD, OutName);
Mike Stumpeac45592009-11-11 20:26:26 +00001054 else
Daniel Dunbare128dd12009-11-21 09:06:22 +00001055 getMangleContext().mangleCXXVtable(RD, OutName);
1056 llvm::StringRef Name = OutName.str();
Benjamin Kramerbb0a07b2009-10-11 22:57:54 +00001057
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001058 std::vector<llvm::Constant *> methods;
1059 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1060 int64_t AddressPoint;
1061
Mike Stumpaa51ad62009-11-19 04:04:36 +00001062 llvm::GlobalVariable *GV = getModule().getGlobalVariable(Name);
Mike Stumpcd2b8212009-11-19 20:52:19 +00001063 if (GV && AddressPoints[LayoutClass] && !GV->isDeclaration()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001064 AddressPoint=(*(*(AddressPoints[LayoutClass]))[RD])[std::make_pair(RD,
1065 Offset)];
Mike Stumpcd2b8212009-11-19 20:52:19 +00001066 // FIXME: We can never have 0 address point. Do this for now so gepping
1067 // retains the same structure. Later, we'll just assert.
1068 if (AddressPoint == 0)
1069 AddressPoint = 1;
1070 } else {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001071 VtableBuilder b(methods, RD, LayoutClass, Offset, *this);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001072
Mike Stumpaa51ad62009-11-19 04:04:36 +00001073 D1(printf("vtable %s\n", RD->getNameAsCString()));
1074 // First comes the vtables for all the non-virtual bases...
1075 AddressPoint = b.GenerateVtableForBase(RD, Offset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001076
Mike Stumpaa51ad62009-11-19 04:04:36 +00001077 // then the vtables for all the virtual bases.
1078 b.GenerateVtableForVBases(RD, Offset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001079
Mike Stumpaa51ad62009-11-19 04:04:36 +00001080 bool CreateDefinition = true;
1081 if (LayoutClass != RD)
1082 CreateDefinition = true;
1083 else {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001084 const ASTRecordLayout &Layout =
1085 getContext().getASTRecordLayout(LayoutClass);
1086
1087 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001088 if (!KeyFunction->getBody()) {
1089 // If there is a KeyFunction, and it isn't defined, just build a
1090 // reference to the vtable.
1091 CreateDefinition = false;
1092 }
1093 }
1094 }
1095
1096 llvm::Constant *C = 0;
1097 llvm::Type *type = Ptr8Ty;
1098 llvm::GlobalVariable::LinkageTypes linktype
1099 = llvm::GlobalValue::ExternalLinkage;
1100 if (CreateDefinition) {
1101 llvm::ArrayType *ntype = llvm::ArrayType::get(Ptr8Ty, methods.size());
1102 C = llvm::ConstantArray::get(ntype, methods);
1103 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
1104 if (LayoutClass->isInAnonymousNamespace())
1105 linktype = llvm::GlobalValue::InternalLinkage;
1106 type = ntype;
1107 }
1108 llvm::GlobalVariable *OGV = GV;
1109 GV = new llvm::GlobalVariable(getModule(), type, true, linktype, C, Name);
1110 if (OGV) {
1111 GV->takeName(OGV);
1112 llvm::Constant *NewPtr = llvm::ConstantExpr::getBitCast(GV,
1113 OGV->getType());
1114 OGV->replaceAllUsesWith(NewPtr);
1115 OGV->eraseFromParent();
1116 }
1117 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1118 if (Hidden)
1119 GV->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1120 }
Mike Stumpc0f632d2009-11-18 04:00:48 +00001121 llvm::Constant *vtable = llvm::ConstantExpr::getBitCast(GV, Ptr8Ty);
Mike Stumpd846d082009-11-10 07:44:33 +00001122 llvm::Constant *AddressPointC;
1123 uint32_t LLVMPointerWidth = getContext().Target.getPointerWidth(0);
1124 AddressPointC = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1125 AddressPoint*LLVMPointerWidth/8);
Mike Stump2cefe382009-11-12 20:47:57 +00001126 vtable = llvm::ConstantExpr::getInBoundsGetElementPtr(vtable, &AddressPointC,
1127 1);
Mike Stumpd846d082009-11-10 07:44:33 +00001128
Mike Stumpcd2b8212009-11-19 20:52:19 +00001129 assert(vtable->getType() == Ptr8Ty);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001130 return vtable;
1131}
Mike Stump9f23a142009-11-10 02:30:51 +00001132
Mike Stumpae1b85d2009-12-02 19:07:44 +00001133namespace {
Mike Stump9f23a142009-11-10 02:30:51 +00001134class VTTBuilder {
1135 /// Inits - The list of values built for the VTT.
1136 std::vector<llvm::Constant *> &Inits;
1137 /// Class - The most derived class that this vtable is being built for.
1138 const CXXRecordDecl *Class;
1139 CodeGenModule &CGM; // Per-module state.
Mike Stump8b2d2d02009-11-11 00:35:07 +00001140 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001141 /// BLayout - Layout for the most derived class that this vtable is being
1142 /// built for.
1143 const ASTRecordLayout &BLayout;
Mike Stump83066c82009-11-13 01:54:23 +00001144 CodeGenModule::AddrMap_t &AddressPoints;
Mike Stump2cefe382009-11-12 20:47:57 +00001145 // vtbl - A pointer to the vtable for Class.
1146 llvm::Constant *ClassVtbl;
1147 llvm::LLVMContext &VMContext;
Mike Stump9f23a142009-11-10 02:30:51 +00001148
Mike Stump8677bc22009-11-12 22:56:32 +00001149 /// BuildVtablePtr - Build up a referene to the given secondary vtable
Mike Stump83066c82009-11-13 01:54:23 +00001150 llvm::Constant *BuildVtablePtr(llvm::Constant *vtbl,
1151 const CXXRecordDecl *VtblClass,
1152 const CXXRecordDecl *RD,
Mike Stump8677bc22009-11-12 22:56:32 +00001153 uint64_t Offset) {
1154 int64_t AddressPoint;
Mike Stump83066c82009-11-13 01:54:23 +00001155 AddressPoint = (*AddressPoints[VtblClass])[std::make_pair(RD, Offset)];
Mike Stump2b34bc52009-11-12 23:36:21 +00001156 // FIXME: We can never have 0 address point. Do this for now so gepping
Mike Stumpcd2b8212009-11-19 20:52:19 +00001157 // retains the same structure. Later we'll just assert.
Mike Stump2b34bc52009-11-12 23:36:21 +00001158 if (AddressPoint == 0)
1159 AddressPoint = 1;
Mike Stump83066c82009-11-13 01:54:23 +00001160 D1(printf("XXX address point for %s in %s layout %s at offset %d was %d\n",
1161 RD->getNameAsCString(), VtblClass->getNameAsCString(),
1162 Class->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump8677bc22009-11-12 22:56:32 +00001163 uint32_t LLVMPointerWidth = CGM.getContext().Target.getPointerWidth(0);
1164 llvm::Constant *init;
1165 init = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1166 AddressPoint*LLVMPointerWidth/8);
1167 init = llvm::ConstantExpr::getInBoundsGetElementPtr(vtbl, &init, 1);
1168 return init;
1169 }
1170
Mike Stump2cefe382009-11-12 20:47:57 +00001171 /// Secondary - Add the secondary vtable pointers to Inits. Offset is the
1172 /// current offset in bits to the object we're working on.
Mike Stump8677bc22009-11-12 22:56:32 +00001173 void Secondary(const CXXRecordDecl *RD, llvm::Constant *vtbl,
Mike Stump83066c82009-11-13 01:54:23 +00001174 const CXXRecordDecl *VtblClass, uint64_t Offset=0,
1175 bool MorallyVirtual=false) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001176 if (RD->getNumVBases() == 0 && ! MorallyVirtual)
1177 return;
1178
1179 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1180 e = RD->bases_end(); i != e; ++i) {
1181 const CXXRecordDecl *Base =
1182 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1183 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1184 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1185 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1186 bool NonVirtualPrimaryBase;
1187 NonVirtualPrimaryBase = !PrimaryBaseWasVirtual && Base == PrimaryBase;
1188 bool BaseMorallyVirtual = MorallyVirtual | i->isVirtual();
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001189 uint64_t BaseOffset;
1190 if (!i->isVirtual()) {
1191 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1192 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1193 } else
1194 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump2b34bc52009-11-12 23:36:21 +00001195 llvm::Constant *subvtbl = vtbl;
Mike Stump83066c82009-11-13 01:54:23 +00001196 const CXXRecordDecl *subVtblClass = VtblClass;
Mike Stump8b2d2d02009-11-11 00:35:07 +00001197 if ((Base->getNumVBases() || BaseMorallyVirtual)
1198 && !NonVirtualPrimaryBase) {
1199 // FIXME: Slightly too many of these for __ZTT8test8_B2
Mike Stump8677bc22009-11-12 22:56:32 +00001200 llvm::Constant *init;
Mike Stump2b34bc52009-11-12 23:36:21 +00001201 if (BaseMorallyVirtual)
Mike Stump83066c82009-11-13 01:54:23 +00001202 init = BuildVtablePtr(vtbl, VtblClass, RD, Offset);
Mike Stump2b34bc52009-11-12 23:36:21 +00001203 else {
Mike Stump8677bc22009-11-12 22:56:32 +00001204 init = CGM.getVtableInfo().getCtorVtable(Class, Base, BaseOffset);
Mike Stump2b34bc52009-11-12 23:36:21 +00001205 subvtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump83066c82009-11-13 01:54:23 +00001206 subVtblClass = Base;
Mike Stump2b34bc52009-11-12 23:36:21 +00001207 }
Mike Stump8677bc22009-11-12 22:56:32 +00001208 Inits.push_back(init);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001209 }
Mike Stump83066c82009-11-13 01:54:23 +00001210 Secondary(Base, subvtbl, subVtblClass, BaseOffset, BaseMorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001211 }
1212 }
1213
Mike Stump2cefe382009-11-12 20:47:57 +00001214 /// BuiltVTT - Add the VTT to Inits. Offset is the offset in bits to the
1215 /// currnet object we're working on.
1216 void BuildVTT(const CXXRecordDecl *RD, uint64_t Offset, bool MorallyVirtual) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001217 if (RD->getNumVBases() == 0 && !MorallyVirtual)
1218 return;
1219
Mike Stump2cefe382009-11-12 20:47:57 +00001220 llvm::Constant *init;
Mike Stump83066c82009-11-13 01:54:23 +00001221 const CXXRecordDecl *VtblClass;
1222
Mike Stump8b2d2d02009-11-11 00:35:07 +00001223 // First comes the primary virtual table pointer...
Mike Stump83066c82009-11-13 01:54:23 +00001224 if (MorallyVirtual) {
1225 init = BuildVtablePtr(ClassVtbl, Class, RD, Offset);
1226 VtblClass = Class;
1227 } else {
Mike Stump2cefe382009-11-12 20:47:57 +00001228 init = CGM.getVtableInfo().getCtorVtable(Class, RD, Offset);
Mike Stump83066c82009-11-13 01:54:23 +00001229 VtblClass = RD;
1230 }
Mike Stump8677bc22009-11-12 22:56:32 +00001231 llvm::Constant *vtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump2cefe382009-11-12 20:47:57 +00001232 Inits.push_back(init);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001233
1234 // then the secondary VTTs....
Mike Stump2cefe382009-11-12 20:47:57 +00001235 SecondaryVTTs(RD, Offset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001236
1237 // and last the secondary vtable pointers.
Mike Stump83066c82009-11-13 01:54:23 +00001238 Secondary(RD, vtbl, VtblClass, Offset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001239 }
1240
1241 /// SecondaryVTTs - Add the secondary VTTs to Inits. The secondary VTTs are
1242 /// built from each direct non-virtual proper base that requires a VTT in
1243 /// declaration order.
Mike Stump2cefe382009-11-12 20:47:57 +00001244 void SecondaryVTTs(const CXXRecordDecl *RD, uint64_t Offset=0,
1245 bool MorallyVirtual=false) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001246 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1247 e = RD->bases_end(); i != e; ++i) {
1248 const CXXRecordDecl *Base =
1249 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1250 if (i->isVirtual())
1251 continue;
Mike Stump2cefe382009-11-12 20:47:57 +00001252 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1253 uint64_t BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1254 BuildVTT(Base, BaseOffset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001255 }
1256 }
1257
1258 /// VirtualVTTs - Add the VTT for each proper virtual base in inheritance
1259 /// graph preorder.
1260 void VirtualVTTs(const CXXRecordDecl *RD) {
1261 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1262 e = RD->bases_end(); i != e; ++i) {
1263 const CXXRecordDecl *Base =
1264 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1265 if (i->isVirtual() && !SeenVBase.count(Base)) {
1266 SeenVBase.insert(Base);
Mike Stump2cefe382009-11-12 20:47:57 +00001267 uint64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
1268 BuildVTT(Base, BaseOffset, true);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001269 }
1270 VirtualVTTs(Base);
1271 }
1272 }
Mike Stump9f23a142009-11-10 02:30:51 +00001273public:
1274 VTTBuilder(std::vector<llvm::Constant *> &inits, const CXXRecordDecl *c,
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001275 CodeGenModule &cgm)
1276 : Inits(inits), Class(c), CGM(cgm),
Mike Stump2cefe382009-11-12 20:47:57 +00001277 BLayout(cgm.getContext().getASTRecordLayout(c)),
Mike Stump83066c82009-11-13 01:54:23 +00001278 AddressPoints(*cgm.AddressPoints[c]),
Mike Stump2cefe382009-11-12 20:47:57 +00001279 VMContext(cgm.getModule().getContext()) {
Mike Stumpd846d082009-11-10 07:44:33 +00001280
Mike Stump8b2d2d02009-11-11 00:35:07 +00001281 // First comes the primary virtual table pointer for the complete class...
Mike Stump2cefe382009-11-12 20:47:57 +00001282 ClassVtbl = CGM.getVtableInfo().getVtable(Class);
1283 Inits.push_back(ClassVtbl);
1284 ClassVtbl = dyn_cast<llvm::Constant>(ClassVtbl->getOperand(0));
1285
Mike Stump8b2d2d02009-11-11 00:35:07 +00001286 // then the secondary VTTs...
1287 SecondaryVTTs(Class);
1288
1289 // then the secondary vtable pointers...
Mike Stump83066c82009-11-13 01:54:23 +00001290 Secondary(Class, ClassVtbl, Class);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001291
1292 // and last, the virtual VTTs.
1293 VirtualVTTs(Class);
Mike Stump9f23a142009-11-10 02:30:51 +00001294 }
1295};
Mike Stumpae1b85d2009-12-02 19:07:44 +00001296}
Mike Stump9f23a142009-11-10 02:30:51 +00001297
Mike Stumpd846d082009-11-10 07:44:33 +00001298llvm::Constant *CodeGenModule::GenerateVTT(const CXXRecordDecl *RD) {
Mike Stumpb4722212009-11-10 19:13:04 +00001299 // Only classes that have virtual bases need a VTT.
1300 if (RD->getNumVBases() == 0)
1301 return 0;
1302
Mike Stump9f23a142009-11-10 02:30:51 +00001303 llvm::SmallString<256> OutName;
Daniel Dunbare128dd12009-11-21 09:06:22 +00001304 getMangleContext().mangleCXXVTT(RD, OutName);
1305 llvm::StringRef Name = OutName.str();
Mike Stump9f23a142009-11-10 02:30:51 +00001306
1307 llvm::GlobalVariable::LinkageTypes linktype;
1308 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
Mike Stumpaa51ad62009-11-19 04:04:36 +00001309 if (RD->isInAnonymousNamespace())
1310 linktype = llvm::GlobalValue::InternalLinkage;
Mike Stump9f23a142009-11-10 02:30:51 +00001311 std::vector<llvm::Constant *> inits;
1312 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1313
Mike Stump9f23a142009-11-10 02:30:51 +00001314 D1(printf("vtt %s\n", RD->getNameAsCString()));
1315
Mike Stump8b2d2d02009-11-11 00:35:07 +00001316 VTTBuilder b(inits, RD, *this);
1317
Mike Stump9f23a142009-11-10 02:30:51 +00001318 llvm::Constant *C;
1319 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, inits.size());
1320 C = llvm::ConstantArray::get(type, inits);
Mike Stumpc0f632d2009-11-18 04:00:48 +00001321 llvm::GlobalVariable *vtt = new llvm::GlobalVariable(getModule(), type, true,
Mike Stumpaa51ad62009-11-19 04:04:36 +00001322 linktype, C, Name);
Mike Stumpc0f632d2009-11-18 04:00:48 +00001323 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1324 if (Hidden)
1325 vtt->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1326 return llvm::ConstantExpr::getBitCast(vtt, Ptr8Ty);
Mike Stump9f23a142009-11-10 02:30:51 +00001327}
Mike Stumpd846d082009-11-10 07:44:33 +00001328
Mike Stump1a139f82009-11-19 01:08:19 +00001329void CGVtableInfo::GenerateClassData(const CXXRecordDecl *RD) {
1330 Vtables[RD] = CGM.GenerateVtable(RD, RD);
Mike Stumpc01c2b82009-12-02 18:57:08 +00001331 CGM.GenerateRTTI(RD);
Mike Stump1a139f82009-11-19 01:08:19 +00001332 CGM.GenerateVTT(RD);
1333}
1334
Mike Stumpeac45592009-11-11 20:26:26 +00001335llvm::Constant *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Mike Stumpd846d082009-11-10 07:44:33 +00001336 llvm::Constant *&vtbl = Vtables[RD];
1337 if (vtbl)
1338 return vtbl;
Mike Stump2cefe382009-11-12 20:47:57 +00001339 vtbl = CGM.GenerateVtable(RD, RD);
Mike Stumpaa51ad62009-11-19 04:04:36 +00001340
1341 bool CreateDefinition = true;
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001342
1343 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1344 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001345 if (!KeyFunction->getBody()) {
1346 // If there is a KeyFunction, and it isn't defined, just build a
1347 // reference to the vtable.
1348 CreateDefinition = false;
1349 }
1350 }
1351
1352 if (CreateDefinition) {
Mike Stumpc01c2b82009-12-02 18:57:08 +00001353 CGM.GenerateRTTI(RD);
Mike Stumpaa51ad62009-11-19 04:04:36 +00001354 CGM.GenerateVTT(RD);
1355 }
Mike Stumpd846d082009-11-10 07:44:33 +00001356 return vtbl;
1357}
Mike Stumpeac45592009-11-11 20:26:26 +00001358
Mike Stump2cefe382009-11-12 20:47:57 +00001359llvm::Constant *CGVtableInfo::getCtorVtable(const CXXRecordDecl *LayoutClass,
1360 const CXXRecordDecl *RD,
Mike Stumpeac45592009-11-11 20:26:26 +00001361 uint64_t Offset) {
Mike Stump2cefe382009-11-12 20:47:57 +00001362 return CGM.GenerateVtable(LayoutClass, RD, Offset);
Mike Stumpeac45592009-11-11 20:26:26 +00001363}
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001364
1365void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
1366 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1367 const CXXRecordDecl *RD = MD->getParent();
1368
1369 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1370
1371 // Get the key function.
1372 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
1373
1374 if (!KeyFunction) {
1375 // If there's no key function, we don't want to emit the vtable here.
1376 return;
1377 }
1378
1379 // Check if we have the key function.
1380 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
1381 return;
1382
1383 // If the key function is a destructor, we only want to emit the vtable once,
1384 // so do it for the complete destructor.
1385 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Complete)
1386 return;
1387
1388 // Emit the data.
1389 GenerateClassData(RD);
1390}
1391