blob: c010f74b2d899b77bc4a0869ae201ef14d0be8f0 [file] [log] [blame]
Anders Carlssondbd920c2009-10-11 22:13:54 +00001//===--- CGVtable.cpp - Emit LLVM Code for C++ vtables --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
Anders Carlssond6b07fb2009-11-27 20:47:55 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlssondbd920c2009-10-11 22:13:54 +000017#include "clang/AST/RecordLayout.h"
Anders Carlsson5dd730a2009-11-26 19:32:45 +000018#include "llvm/ADT/DenseSet.h"
Zhongxing Xu7fe26ac2009-11-13 05:46:16 +000019#include <cstdio>
Anders Carlssondbd920c2009-10-11 22:13:54 +000020
21using namespace clang;
22using namespace CodeGen;
23
Anders Carlsson27f69d02009-11-27 22:21:51 +000024namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000025class VtableBuilder {
Anders Carlssondbd920c2009-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 Stumpacfd1e52009-11-13 01:54:23 +000035 /// LayoutClass - The most derived class used for virtual base layout
36 /// information.
37 const CXXRecordDecl *LayoutClass;
Mike Stump4cde6262009-11-13 02:13:54 +000038 /// LayoutOffset - The offset for Class in LayoutClass.
39 uint64_t LayoutOffset;
Anders Carlssondbd920c2009-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 Carlssona0fdd912009-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 Stump9e7e3c62009-11-06 23:27:42 +000053 // This is the offset to the nearest virtual base
Anders Carlssona0fdd912009-11-13 17:08:56 +000054 llvm::DenseMap<GlobalDecl, Index_t> NonVirtualOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +000055 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stump94aff932009-10-27 23:46:47 +000056
Anders Carlsson6d4ccb72009-11-26 19:54:33 +000057 /// PureVirtualFunction - Points to __cxa_pure_virtual.
58 llvm::Constant *PureVirtualFn;
59
Anders Carlssondb131512009-11-26 03:25:13 +000060 /// Thunk - Represents a single thunk.
61 struct Thunk {
62 Thunk()
63 : Index(0) { }
64
65 Thunk(uint64_t Index, const ThunkAdjustment &Adjustment)
66 : Index(Index), Adjustment(Adjustment) { }
67
68 /// Index - The index in the vtable.
69 uint64_t Index;
70
Anders Carlsson5dd730a2009-11-26 19:32:45 +000071 /// Adjustment - The thunk adjustment.
Anders Carlssondb131512009-11-26 03:25:13 +000072 ThunkAdjustment Adjustment;
73 };
Anders Carlsson5dd730a2009-11-26 19:32:45 +000074
75 /// Thunks - The thunks in a vtable.
Anders Carlssondb131512009-11-26 03:25:13 +000076 typedef llvm::DenseMap<GlobalDecl, Thunk> ThunksMapTy;
77 ThunksMapTy Thunks;
Anders Carlsson5dd730a2009-11-26 19:32:45 +000078
79 /// CovariantThunk - Represents a single covariant thunk.
80 struct CovariantThunk {
Anders Carlsson5f96bc12009-12-03 02:16:14 +000081 CovariantThunk(GlobalDecl GD, const ThunkAdjustment &ReturnAdjustment,
Anders Carlsson5dd730a2009-11-26 19:32:45 +000082 CanQualType ReturnType)
Anders Carlsson5f96bc12009-12-03 02:16:14 +000083 : GD(GD), ReturnAdjustment(ReturnAdjustment),
Anders Carlsson5dd730a2009-11-26 19:32:45 +000084 ReturnType(ReturnType) { }
Anders Carlsson5f96bc12009-12-03 02:16:14 +000085
Anders Carlssonbdd8e382009-12-03 02:03:29 +000086 GlobalDecl GD;
87
Anders Carlssond8ddffc2009-12-03 01:58:20 +000088 /// ReturnAdjustment - The covariant thunk return adjustment.
89 ThunkAdjustment ReturnAdjustment;
Anders Carlsson5dd730a2009-11-26 19:32:45 +000090
91 /// ReturnType - The return type of the function.
92 CanQualType ReturnType;
93 };
Anders Carlssondb131512009-11-26 03:25:13 +000094
Anders Carlsson5dd730a2009-11-26 19:32:45 +000095 /// CovariantThunks - The covariant thunks in a vtable.
Anders Carlssond6f7af52009-12-03 02:12:03 +000096 typedef llvm::DenseMap<uint64_t, CovariantThunk> CovariantThunksMapTy;
Anders Carlsson5dd730a2009-11-26 19:32:45 +000097 CovariantThunksMapTy CovariantThunks;
98
99 /// PureVirtualMethods - Pure virtual methods.
100 typedef llvm::DenseSet<GlobalDecl> PureVirtualMethodsSetTy;
101 PureVirtualMethodsSetTy PureVirtualMethods;
102
Anders Carlssondbd920c2009-10-11 22:13:54 +0000103 std::vector<Index_t> VCalls;
Mike Stump9840c702009-11-12 20:47:57 +0000104
105 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stump23a35422009-11-19 20:52:19 +0000106 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
107 // vtable for use in computing the initializers for the VTT.
108 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +0000109
Anders Carlssondbd920c2009-10-11 22:13:54 +0000110 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000111 const bool Extern;
112 const uint32_t LLVMPointerWidth;
113 Index_t extra;
Mike Stump11dea942009-10-15 02:04:03 +0000114 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stump23a35422009-11-19 20:52:19 +0000115 static llvm::DenseMap<CtorVtable_t, int64_t>&
116 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
117 const CXXRecordDecl *c) {
118 CodeGenModule::AddrMap_t *&oref = cgm.AddressPoints[l];
119 if (oref == 0)
120 oref = new CodeGenModule::AddrMap_t;
121
122 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
123 if (ref == 0)
124 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
125 return *ref;
126 }
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000127
128 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
129 llvm::Constant* getPureVirtualFn() {
130 if (!PureVirtualFn) {
131 const llvm::FunctionType *Ty =
132 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
133 /*isVarArg=*/false);
134 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
135 }
136
137 return PureVirtualFn;
138 }
139
Anders Carlssondbd920c2009-10-11 22:13:54 +0000140public:
Mike Stump4cde6262009-11-13 02:13:54 +0000141 VtableBuilder(std::vector<llvm::Constant *> &meth, const CXXRecordDecl *c,
142 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm)
143 : methods(meth), Class(c), LayoutClass(l), LayoutOffset(lo),
Mike Stumpacfd1e52009-11-13 01:54:23 +0000144 BLayout(cgm.getContext().getASTRecordLayout(l)),
Mike Stumpde050572009-12-02 18:57:08 +0000145 rtti(cgm.GenerateRTTIRef(c)), VMContext(cgm.getModule().getContext()),
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000146 CGM(cgm), PureVirtualFn(0),subAddressPoints(AllocAddressPoint(cgm, l, c)),
Mike Stump6be2b172009-11-19 00:49:05 +0000147 Extern(!l->isInAnonymousNamespace()),
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000148 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000149 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
150 }
151
Anders Carlssona0fdd912009-11-13 17:08:56 +0000152 llvm::DenseMap<GlobalDecl, Index_t> &getIndex() { return Index; }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000153 llvm::DenseMap<const CXXRecordDecl *, Index_t> &getVBIndex()
154 { return VBIndex; }
155
156 llvm::Constant *wrap(Index_t i) {
157 llvm::Constant *m;
158 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
159 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
160 }
161
162 llvm::Constant *wrap(llvm::Constant *m) {
163 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
164 }
165
Mike Stump79336282009-12-02 19:50:41 +0000166#define D1(x)
167//#define D1(X) do { if (getenv("DEBUG")) { X; } } while (0)
Mike Stump6a9612f2009-10-31 20:06:59 +0000168
169 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stumpab28c132009-10-13 22:54:56 +0000170 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000171 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
172 e = RD->bases_end(); i != e; ++i) {
173 const CXXRecordDecl *Base =
174 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpab28c132009-10-13 22:54:56 +0000175 Index_t next_vbindex = current_vbindex;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000176 if (i->isVirtual() && !SeenVBase.count(Base)) {
177 SeenVBase.insert(Base);
Mike Stumpab28c132009-10-13 22:54:56 +0000178 if (updateVBIndex) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000179 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stumpab28c132009-10-13 22:54:56 +0000180 - 3*LLVMPointerWidth/8);
181 VBIndex[Base] = next_vbindex;
182 }
Mike Stump6a9612f2009-10-31 20:06:59 +0000183 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
184 VCalls.push_back((0?700:0) + BaseOffset);
185 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
186 Base->getNameAsCString(),
187 (int)-VCalls.size()-3, (int)BaseOffset,
188 Class->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000189 }
Mike Stumpab28c132009-10-13 22:54:56 +0000190 // We also record offsets for non-virtual bases to closest enclosing
191 // virtual base. We do this so that we don't have to search
192 // for the nearst virtual base class when generating thunks.
193 if (updateVBIndex && VBIndex.count(Base) == 0)
194 VBIndex[Base] = next_vbindex;
Mike Stump6a9612f2009-10-31 20:06:59 +0000195 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000196 }
197 }
198
199 void StartNewTable() {
200 SeenVBase.clear();
201 }
202
Mike Stump3425b972009-10-15 09:30:16 +0000203 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
204 Index_t Offset = 0) {
205
206 if (B == D)
207 return Offset;
208
209 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
210 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
211 e = D->bases_end(); i != e; ++i) {
212 const CXXRecordDecl *Base =
213 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
214 int64_t BaseOffset = 0;
215 if (!i->isVirtual())
216 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
217 int64_t o = getNVOffset_1(Base, B, BaseOffset);
218 if (o >= 0)
219 return o;
220 }
221
222 return -1;
223 }
224
225 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
226 /// derived class D.
227 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +0000228 qD = qD->getPointeeType();
229 qB = qB->getPointeeType();
Mike Stump3425b972009-10-15 09:30:16 +0000230 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
231 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
232 int64_t o = getNVOffset_1(D, B);
233 if (o >= 0)
234 return o;
235
236 assert(false && "FIXME: non-virtual base not found");
237 return 0;
238 }
239
Anders Carlssondbd920c2009-10-11 22:13:54 +0000240 /// getVbaseOffset - Returns the index into the vtable for the virtual base
241 /// offset for the given (B) virtual base of the derived class D.
242 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +0000243 qD = qD->getPointeeType();
244 qB = qB->getPointeeType();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000245 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
246 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
247 if (D != Class)
Eli Friedman76ed1f72009-11-30 01:19:33 +0000248 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000249 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
250 i = VBIndex.find(B);
251 if (i != VBIndex.end())
252 return i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000253
Mike Stumpab28c132009-10-13 22:54:56 +0000254 assert(false && "FIXME: Base not found");
Anders Carlssondbd920c2009-10-11 22:13:54 +0000255 return 0;
256 }
257
Anders Carlssona0fdd912009-11-13 17:08:56 +0000258 bool OverrideMethod(GlobalDecl GD, llvm::Constant *m,
Mike Stump3425b972009-10-15 09:30:16 +0000259 bool MorallyVirtual, Index_t OverrideOffset,
Anders Carlsson27682a32009-12-03 01:54:02 +0000260 Index_t Offset, int64_t CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000261
262 void InstallThunks() {
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000263 for (CovariantThunksMapTy::const_iterator i = CovariantThunks.begin(),
264 e = CovariantThunks.end(); i != e; ++i) {
Anders Carlssond6f7af52009-12-03 02:12:03 +0000265 GlobalDecl GD = i->second.GD;
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000266 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
267 if (MD->isPure())
268 continue;
269
Anders Carlsson5f96bc12009-12-03 02:16:14 +0000270 uint64_t Index = i->first;
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000271 const CovariantThunk &Thunk = i->second;
Anders Carlsson5f96bc12009-12-03 02:16:14 +0000272 assert(Index == VtableBuilder::Index[GD] && "Thunk index mismatch!");
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000273
274 // Check if there is an adjustment for the 'this' pointer.
275 ThunkAdjustment ThisAdjustment;
276 ThunksMapTy::iterator i = Thunks.find(GD);
277 if (i != Thunks.end()) {
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000278 ThisAdjustment = i->second.Adjustment;
279
280 Thunks.erase(i);
281 }
282
283 CovariantThunkAdjustment Adjustment(ThisAdjustment,
284 Thunk.ReturnAdjustment);
Anders Carlsson5f96bc12009-12-03 02:16:14 +0000285 submethods[Index] = CGM.BuildCovariantThunk(MD, Extern, Adjustment);
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000286 }
287 CovariantThunks.clear();
Anders Carlssonbdd8e382009-12-03 02:03:29 +0000288
Anders Carlssondb131512009-11-26 03:25:13 +0000289 for (ThunksMapTy::const_iterator i = Thunks.begin(), e = Thunks.end();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000290 i != e; ++i) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000291 GlobalDecl GD = i->first;
292 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssondb131512009-11-26 03:25:13 +0000293 assert(!MD->isPure() && "Can't thunk pure virtual methods!");
294
295 const Thunk& Thunk = i->second;
296 assert(Thunk.Index == Index[GD] && "Thunk index mismatch!");
297
298 submethods[Thunk.Index] = CGM.BuildThunk(MD, Extern, Thunk.Adjustment);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000299 }
300 Thunks.clear();
Anders Carlssondb131512009-11-26 03:25:13 +0000301
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000302 for (PureVirtualMethodsSetTy::iterator i = PureVirtualMethods.begin(),
303 e = PureVirtualMethods.end(); i != e; ++i) {
304 GlobalDecl GD = *i;
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000305 submethods[Index[GD]] = getPureVirtualFn();
Mike Stump94aff932009-10-27 23:46:47 +0000306 }
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000307 PureVirtualMethods.clear();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000308 }
309
Anders Carlssona0fdd912009-11-13 17:08:56 +0000310 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
311 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
312
Mike Stump1ae31782009-10-27 23:36:26 +0000313 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD))
Anders Carlssona0fdd912009-11-13 17:08:56 +0000314 return wrap(CGM.GetAddrOfCXXDestructor(Dtor, GD.getDtorType()));
Mike Stump1ae31782009-10-27 23:36:26 +0000315
Anders Carlssonecf282b2009-11-24 05:08:52 +0000316 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump1ae31782009-10-27 23:36:26 +0000317
318 return wrap(CGM.GetAddrOfFunction(MD, Ty));
319 }
320
Mike Stump9e7e3c62009-11-06 23:27:42 +0000321 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
322 int64_t CurrentVBaseOffset) {
Mike Stump11dea942009-10-15 02:04:03 +0000323 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlssondbd920c2009-10-11 22:13:54 +0000324 e = Path->rend(); i != e; ++i) {
325 const CXXRecordDecl *RD = i->first;
Mike Stump3425b972009-10-15 09:30:16 +0000326 int64_t OverrideOffset = i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000327 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
328 ++mi) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000329 const CXXMethodDecl *MD = *mi;
330
331 if (!MD->isVirtual())
Anders Carlssondbd920c2009-10-11 22:13:54 +0000332 continue;
333
Anders Carlssona0fdd912009-11-13 17:08:56 +0000334 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
335 // Override both the complete and the deleting destructor.
336 GlobalDecl CompDtor(DD, Dtor_Complete);
337 OverrideMethod(CompDtor, WrapAddrOf(CompDtor), MorallyVirtual,
338 OverrideOffset, Offset, CurrentVBaseOffset);
339
340 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
341 OverrideMethod(DeletingDtor, WrapAddrOf(DeletingDtor), MorallyVirtual,
342 OverrideOffset, Offset, CurrentVBaseOffset);
343 } else {
344 OverrideMethod(MD, WrapAddrOf(MD), MorallyVirtual, OverrideOffset,
345 Offset, CurrentVBaseOffset);
346 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000347 }
348 }
349 }
350
Anders Carlssona0fdd912009-11-13 17:08:56 +0000351 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000352 int64_t CurrentVBaseOffset) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000353 llvm::Constant *m = WrapAddrOf(GD);
Mike Stump1ae31782009-10-27 23:36:26 +0000354
Anders Carlssondbd920c2009-10-11 22:13:54 +0000355 // If we can find a previously allocated slot for this, reuse it.
Anders Carlssona0fdd912009-11-13 17:08:56 +0000356 if (OverrideMethod(GD, m, MorallyVirtual, Offset, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000357 CurrentVBaseOffset))
Anders Carlssondbd920c2009-10-11 22:13:54 +0000358 return;
359
Anders Carlssona0fdd912009-11-13 17:08:56 +0000360 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
361
Anders Carlssondbd920c2009-10-11 22:13:54 +0000362 // else allocate a new slot.
Anders Carlssona0fdd912009-11-13 17:08:56 +0000363 Index[GD] = submethods.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000364 submethods.push_back(m);
Mike Stumpe99cc452009-11-13 23:45:53 +0000365 D1(printf(" vfn for %s at %d\n", MD->getNameAsString().c_str(),
366 (int)Index[GD]));
Mike Stump7809e0d2009-10-28 00:35:46 +0000367 if (MD->isPure())
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000368 PureVirtualMethods.insert(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000369 if (MorallyVirtual) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000370 VCallOffset[GD] = Offset/8;
371 Index_t &idx = VCall[GD];
Anders Carlssondbd920c2009-10-11 22:13:54 +0000372 // Allocate the first one, after that, we reuse the previous one.
373 if (idx == 0) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000374 NonVirtualOffset[GD] = CurrentVBaseOffset/8 - Offset/8;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000375 idx = VCalls.size()+1;
376 VCalls.push_back(0);
Mike Stump6a9612f2009-10-31 20:06:59 +0000377 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpe99cc452009-11-13 23:45:53 +0000378 MD->getNameAsString().c_str(), (int)-VCalls.size()-3, 0));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000379 }
380 }
381 }
382
383 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000384 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000385 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssona0fdd912009-11-13 17:08:56 +0000386 ++mi) {
387 const CXXMethodDecl *MD = *mi;
388 if (!MD->isVirtual())
389 continue;
390
391 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
392 // For destructors, add both the complete and the deleting destructor
393 // to the vtable.
394 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000395 CurrentVBaseOffset);
Eli Friedman76ed1f72009-11-30 01:19:33 +0000396 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
397 CurrentVBaseOffset);
398 } else
399 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +0000400 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000401 }
402
403 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
404 const CXXRecordDecl *PrimaryBase,
405 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000406 int64_t Offset, int64_t CurrentVBaseOffset,
407 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +0000408 Path->push_back(std::make_pair(RD, Offset));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000409 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
410 e = RD->bases_end(); i != e; ++i) {
411 if (i->isVirtual())
412 continue;
413 const CXXRecordDecl *Base =
414 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
415 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
416 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
417 StartNewTable();
Mike Stump4cde6262009-11-13 02:13:54 +0000418 GenerateVtableForBase(Base, o, MorallyVirtual, false,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000419 CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000420 }
421 }
Mike Stump11dea942009-10-15 02:04:03 +0000422 Path->pop_back();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000423 }
424
Mike Stump0ca42792009-10-14 18:14:51 +0000425// #define D(X) do { X; } while (0)
426#define D(X)
427
428 void insertVCalls(int InsertionPoint) {
429 llvm::Constant *e = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +0000430 D1(printf("============= combining vbase/vcall\n"));
Mike Stump0ca42792009-10-14 18:14:51 +0000431 D(VCalls.insert(VCalls.begin(), 673));
432 D(VCalls.push_back(672));
Mike Stump3425b972009-10-15 09:30:16 +0000433 methods.insert(methods.begin() + InsertionPoint, VCalls.size(), e);
Mike Stump0ca42792009-10-14 18:14:51 +0000434 // The vcalls come first...
435 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
436 e = VCalls.rend();
437 i != e; ++i)
438 methods[InsertionPoint++] = wrap((0?600:0) + *i);
439 VCalls.clear();
Mike Stumpfbfb52d2009-11-10 02:30:51 +0000440 VCall.clear();
Mike Stump0ca42792009-10-14 18:14:51 +0000441 }
442
Mike Stump65d0e282009-11-13 23:13:20 +0000443 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
444 Index_t AddressPoint) {
445 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
446 RD->getNameAsCString(), Class->getNameAsCString(),
447 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +0000448 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +0000449
450 // Now also add the address point for all our primary bases.
451 while (1) {
452 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
453 RD = Layout.getPrimaryBase();
454 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
455 // FIXME: Double check this.
456 if (RD == 0)
457 break;
458 if (PrimaryBaseWasVirtual &&
459 BLayout.getVBaseClassOffset(RD) != Offset)
460 break;
461 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
462 RD->getNameAsCString(), Class->getNameAsCString(),
463 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +0000464 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +0000465 }
466 }
467
468
Mike Stump6a9612f2009-10-31 20:06:59 +0000469 Index_t end(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
470 const CXXRecordDecl *PrimaryBase, bool PrimaryBaseWasVirtual,
471 bool MorallyVirtual, int64_t Offset, bool ForVirtualBase,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000472 int64_t CurrentVBaseOffset,
Mike Stump6a9612f2009-10-31 20:06:59 +0000473 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +0000474 bool alloc = false;
475 if (Path == 0) {
476 alloc = true;
477 Path = new Path_t;
478 }
479
Anders Carlssondbd920c2009-10-11 22:13:54 +0000480 StartNewTable();
481 extra = 0;
Mike Stump0ca42792009-10-14 18:14:51 +0000482 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
483 int VCallInsertionPoint = methods.size();
484 if (!DeferVCalls) {
485 insertVCalls(VCallInsertionPoint);
Mike Stump3425b972009-10-15 09:30:16 +0000486 } else
487 // FIXME: just for extra, or for all uses of VCalls.size post this?
488 extra = -VCalls.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000489
Mike Stump4cde6262009-11-13 02:13:54 +0000490 methods.push_back(wrap(-((Offset-LayoutOffset)/8)));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000491 methods.push_back(rtti);
492 Index_t AddressPoint = methods.size();
493
494 InstallThunks();
Mike Stump6a9612f2009-10-31 20:06:59 +0000495 D1(printf("============= combining methods\n"));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000496 methods.insert(methods.end(), submethods.begin(), submethods.end());
497 submethods.clear();
498
499 // and then the non-virtual bases.
500 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000501 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stump0ca42792009-10-14 18:14:51 +0000502
503 if (ForVirtualBase) {
Mike Stump9840c702009-11-12 20:47:57 +0000504 // FIXME: We're adding to VCalls in callers, we need to do the overrides
505 // in the inner part, so that we know the complete set of vcalls during
506 // the build and don't have to insert into methods. Saving out the
507 // AddressPoint here, would need to be fixed, if we didn't do that. Also
508 // retroactively adding vcalls for overrides later wind up in the wrong
509 // place, the vcall slot has to be alloted during the walk of the base
510 // when the function is first introduces.
Mike Stump0ca42792009-10-14 18:14:51 +0000511 AddressPoint += VCalls.size();
Mike Stump9840c702009-11-12 20:47:57 +0000512 insertVCalls(VCallInsertionPoint);
Mike Stump0ca42792009-10-14 18:14:51 +0000513 }
514
Mike Stump65d0e282009-11-13 23:13:20 +0000515 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump9840c702009-11-12 20:47:57 +0000516
Mike Stump11dea942009-10-15 02:04:03 +0000517 if (alloc) {
518 delete Path;
519 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000520 return AddressPoint;
521 }
522
Mike Stump6a9612f2009-10-31 20:06:59 +0000523 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
524 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000525 int64_t CurrentVBaseOffset) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000526 if (!RD->isDynamicClass())
527 return;
528
529 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
530 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
531 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
532
533 // vtables are composed from the chain of primaries.
534 if (PrimaryBase) {
535 D1(printf(" doing primaries for %s most derived %s\n",
536 RD->getNameAsCString(), Class->getNameAsCString()));
537
Mike Stump9e7e3c62009-11-06 23:27:42 +0000538 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
539 if (PrimaryBaseWasVirtual)
540 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
541
Mike Stump6a9612f2009-10-31 20:06:59 +0000542 if (!PrimaryBaseWasVirtual)
543 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000544 updateVBIndex, current_vbindex, BaseCurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000545 }
546
547 D1(printf(" doing vcall entries for %s most derived %s\n",
548 RD->getNameAsCString(), Class->getNameAsCString()));
549
550 // And add the virtuals for the class to the primary vtable.
Eli Friedman76ed1f72009-11-30 01:19:33 +0000551 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000552 }
553
554 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
555 bool updateVBIndex, Index_t current_vbindex,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000556 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000557 bool bottom) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000558 if (!RD->isDynamicClass())
559 return;
560
561 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
562 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
563 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
564
565 // vtables are composed from the chain of primaries.
566 if (PrimaryBase) {
Mike Stump9e7e3c62009-11-06 23:27:42 +0000567 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
568 if (PrimaryBaseWasVirtual) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000569 IndirectPrimary.insert(PrimaryBase);
Mike Stump9e7e3c62009-11-06 23:27:42 +0000570 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
571 }
Mike Stump6a9612f2009-10-31 20:06:59 +0000572
573 D1(printf(" doing primaries for %s most derived %s\n",
574 RD->getNameAsCString(), Class->getNameAsCString()));
575
576 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000577 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000578 BaseCurrentVBaseOffset, false);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000579 }
580
Mike Stump6a9612f2009-10-31 20:06:59 +0000581 D1(printf(" doing vbase entries for %s most derived %s\n",
582 RD->getNameAsCString(), Class->getNameAsCString()));
583 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
584
585 if (RDisVirtualBase || bottom) {
586 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000587 CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000588 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000589 }
590
Mike Stump4cde6262009-11-13 02:13:54 +0000591 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
592 bool MorallyVirtual = false,
Anders Carlssondbd920c2009-10-11 22:13:54 +0000593 bool ForVirtualBase = false,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000594 int CurrentVBaseOffset = 0,
Mike Stump11dea942009-10-15 02:04:03 +0000595 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000596 if (!RD->isDynamicClass())
597 return 0;
598
Mike Stump92774d12009-11-13 02:35:38 +0000599 // Construction vtable don't need parts that have no virtual bases and
600 // aren't morally virtual.
601 if ((LayoutClass != Class) && RD->getNumVBases() == 0 && !MorallyVirtual)
602 return 0;
603
Anders Carlssondbd920c2009-10-11 22:13:54 +0000604 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
605 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
606 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
607
Anders Carlssondbd920c2009-10-11 22:13:54 +0000608 extra = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +0000609 D1(printf("building entries for base %s most derived %s\n",
610 RD->getNameAsCString(), Class->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000611
Mike Stump6a9612f2009-10-31 20:06:59 +0000612 if (ForVirtualBase)
613 extra = VCalls.size();
614
615 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0, ForVirtualBase,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000616 CurrentVBaseOffset, true);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000617
618 if (Path)
Mike Stump9e7e3c62009-11-06 23:27:42 +0000619 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000620
Mike Stump6a9612f2009-10-31 20:06:59 +0000621 return end(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual, MorallyVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000622 Offset, ForVirtualBase, CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000623 }
624
625 void GenerateVtableForVBases(const CXXRecordDecl *RD,
626 int64_t Offset = 0,
Mike Stump11dea942009-10-15 02:04:03 +0000627 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000628 bool alloc = false;
629 if (Path == 0) {
630 alloc = true;
Mike Stump11dea942009-10-15 02:04:03 +0000631 Path = new Path_t;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000632 }
633 // FIXME: We also need to override using all paths to a virtual base,
634 // right now, we just process the first path
635 Path->push_back(std::make_pair(RD, Offset));
636 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
637 e = RD->bases_end(); i != e; ++i) {
638 const CXXRecordDecl *Base =
639 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
640 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
641 // Mark it so we don't output it twice.
642 IndirectPrimary.insert(Base);
643 StartNewTable();
Mike Stump0ca42792009-10-14 18:14:51 +0000644 VCall.clear();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000645 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9e7e3c62009-11-06 23:27:42 +0000646 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump6a9612f2009-10-31 20:06:59 +0000647 D1(printf("vtable %s virtual base %s\n",
648 Class->getNameAsCString(), Base->getNameAsCString()));
Mike Stump4cde6262009-11-13 02:13:54 +0000649 GenerateVtableForBase(Base, BaseOffset, true, true, CurrentVBaseOffset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000650 Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000651 }
Mike Stump9840c702009-11-12 20:47:57 +0000652 int64_t BaseOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000653 if (i->isVirtual())
654 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9840c702009-11-12 20:47:57 +0000655 else {
656 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
657 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
658 }
659
Mike Stump11dea942009-10-15 02:04:03 +0000660 if (Base->getNumVBases()) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000661 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump11dea942009-10-15 02:04:03 +0000662 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000663 }
664 Path->pop_back();
665 if (alloc)
666 delete Path;
667 }
668};
Anders Carlsson27682a32009-12-03 01:54:02 +0000669} // end anonymous namespace
670
671bool VtableBuilder::OverrideMethod(GlobalDecl GD, llvm::Constant *m,
672 bool MorallyVirtual, Index_t OverrideOffset,
673 Index_t Offset, int64_t CurrentVBaseOffset) {
674 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
675
676 const bool isPure = MD->isPure();
677 typedef CXXMethodDecl::method_iterator meth_iter;
678 // FIXME: Should OverrideOffset's be Offset?
679
680 // FIXME: Don't like the nested loops. For very large inheritance
681 // heirarchies we could have a table on the side with the final overridder
682 // and just replace each instance of an overridden method once. Would be
683 // nice to measure the cost/benefit on real code.
684
685 for (meth_iter mi = MD->begin_overridden_methods(),
686 e = MD->end_overridden_methods();
687 mi != e; ++mi) {
688 GlobalDecl OGD;
689
690 const CXXMethodDecl *OMD = *mi;
691 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
692 OGD = GlobalDecl(DD, GD.getDtorType());
693 else
694 OGD = OMD;
695
696 llvm::Constant *om;
697 om = WrapAddrOf(OGD);
698 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
699
700 for (Index_t i = 0, e = submethods.size();
701 i != e; ++i) {
702 // FIXME: begin_overridden_methods might be too lax, covariance */
703 if (submethods[i] != om)
704 continue;
705 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
706 CanQualType oret = CGM.getContext().getCanonicalType(nc_oret);
707 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
708 CanQualType ret = CGM.getContext().getCanonicalType(nc_ret);
709 ThunkAdjustment ReturnAdjustment;
710 if (oret != ret) {
711 // FIXME: calculate offsets for covariance
Anders Carlssond6f7af52009-12-03 02:12:03 +0000712 CovariantThunksMapTy::iterator it = CovariantThunks.find(i);
713 if (it != CovariantThunks.end()) {
714 oret = it->second.ReturnType;
715 CovariantThunks.erase(it);
Anders Carlsson27682a32009-12-03 01:54:02 +0000716 }
717 // FIXME: Double check oret
718 Index_t nv = getNVOffset(oret, ret)/8;
719 ReturnAdjustment = ThunkAdjustment(nv, getVbaseOffset(oret, ret));
720 }
721 Index[GD] = i;
722 submethods[i] = m;
723 if (isPure)
724 PureVirtualMethods.insert(GD);
725 PureVirtualMethods.erase(OGD);
726 Thunks.erase(OGD);
727 if (MorallyVirtual || VCall.count(OGD)) {
728 Index_t &idx = VCall[OGD];
729 if (idx == 0) {
730 NonVirtualOffset[GD] = -OverrideOffset/8 + CurrentVBaseOffset/8;
731 VCallOffset[GD] = OverrideOffset/8;
732 idx = VCalls.size()+1;
733 VCalls.push_back(0);
734 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
735 MD->getNameAsString().c_str(), (int)-idx-3,
736 (int)VCalls[idx-1], Class->getNameAsCString()));
737 } else {
738 NonVirtualOffset[GD] = NonVirtualOffset[OGD];
739 VCallOffset[GD] = VCallOffset[OGD];
740 VCalls[idx-1] = -VCallOffset[OGD] + OverrideOffset/8;
741 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
742 MD->getNameAsString().c_str(), (int)-idx-3,
743 (int)VCalls[idx-1], Class->getNameAsCString()));
744 }
745 VCall[GD] = idx;
746 int64_t NonVirtualAdjustment = NonVirtualOffset[GD];
747 int64_t VirtualAdjustment =
748 -((idx + extra + 2) * LLVMPointerWidth / 8);
749
750 // Optimize out virtual adjustments of 0.
751 if (VCalls[idx-1] == 0)
752 VirtualAdjustment = 0;
753
754 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
755 VirtualAdjustment);
756
757 // FIXME: Do we always have to build a covariant thunk to save oret,
758 // which is the containing virtual base class?
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000759 if (!ReturnAdjustment.isEmpty())
Anders Carlssond6f7af52009-12-03 02:12:03 +0000760 CovariantThunks[i] = CovariantThunk(i, GD, ReturnAdjustment, oret);
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000761
762 if (!isPure && !ThisAdjustment.isEmpty())
Anders Carlsson27682a32009-12-03 01:54:02 +0000763 Thunks[GD] = Thunk(i, ThisAdjustment);
764 return true;
765 }
766
767 // FIXME: finish off
768 int64_t NonVirtualAdjustment = VCallOffset[OGD] - OverrideOffset/8;
769
770 if (NonVirtualAdjustment || !ReturnAdjustment.isEmpty()) {
771 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
772
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000773 if (!ReturnAdjustment.isEmpty())
Anders Carlssond6f7af52009-12-03 02:12:03 +0000774 CovariantThunks[i] =
Anders Carlssonbdd8e382009-12-03 02:03:29 +0000775 CovariantThunk(i, GD, ReturnAdjustment, oret);
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000776
777 if (!isPure)
Anders Carlsson27682a32009-12-03 01:54:02 +0000778 Thunks[GD] = Thunk(i, ThisAdjustment);
779 }
780 return true;
781 }
782 }
783
784 return false;
Anders Carlsson27f69d02009-11-27 22:21:51 +0000785}
786
Anders Carlsson27682a32009-12-03 01:54:02 +0000787
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000788/// TypeConversionRequiresAdjustment - Returns whether conversion from a
789/// derived type to a base type requires adjustment.
790static bool
791TypeConversionRequiresAdjustment(ASTContext &Ctx,
792 const CXXRecordDecl *DerivedDecl,
793 const CXXRecordDecl *BaseDecl) {
794 CXXBasePaths Paths(/*FindAmbiguities=*/false,
795 /*RecordPaths=*/true, /*DetectVirtual=*/true);
796 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
797 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
798 assert(false && "Class must be derived from the passed in base class!");
799 return false;
800 }
801
Anders Carlsson724e3e22009-11-28 03:03:52 +0000802 // If we found a virtual base we always want to require adjustment.
803 if (Paths.getDetectedVirtual())
804 return true;
805
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000806 const CXXBasePath &Path = Paths.front();
807
Anders Carlsson724e3e22009-11-28 03:03:52 +0000808 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000809 const CXXBasePathElement &Element = Path[Start];
810
811 // Check the base class offset.
812 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
813
814 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
815 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
816
817 if (Layout.getBaseClassOffset(Base) != 0) {
818 // This requires an adjustment.
819 return true;
820 }
821 }
822
823 return false;
824}
825
826static bool
827TypeConversionRequiresAdjustment(ASTContext &Ctx,
828 QualType DerivedType, QualType BaseType) {
829 // Canonicalize the types.
830 QualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
831 QualType CanBaseType = Ctx.getCanonicalType(BaseType);
832
833 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
834 "Types must have same type class!");
835
836 if (CanDerivedType == CanBaseType) {
837 // No adjustment needed.
838 return false;
839 }
840
841 if (const ReferenceType *RT = dyn_cast<ReferenceType>(CanDerivedType)) {
842 CanDerivedType = RT->getPointeeType();
843 CanBaseType = cast<ReferenceType>(CanBaseType)->getPointeeType();
844 } else if (const PointerType *PT = dyn_cast<PointerType>(CanDerivedType)) {
845 CanDerivedType = PT->getPointeeType();
846 CanBaseType = cast<PointerType>(CanBaseType)->getPointeeType();
847 } else {
848 assert(false && "Unexpected return type!");
849 }
850
851 if (CanDerivedType == CanBaseType) {
852 // No adjustment needed.
853 return false;
854 }
855
856 const CXXRecordDecl *DerivedDecl =
857 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
858
859 const CXXRecordDecl *BaseDecl =
860 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
861
862 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
863}
864
865void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
866
867 // Itanium C++ ABI 2.5.2:
868 // The order of the virtual function pointers in a virtual table is the
869 // order of declaration of the corresponding member functions in the class.
870 //
871 // There is an entry for any virtual function declared in a class,
872 // whether it is a new function or overrides a base class function,
873 // unless it overrides a function from the primary base, and conversion
874 // between their return types does not require an adjustment.
875
876 int64_t CurrentIndex = 0;
877
878 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
879 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
880
881 if (PrimaryBase) {
Anders Carlsson0121fbd2009-11-30 19:43:26 +0000882 assert(PrimaryBase->isDefinition() &&
883 "Should have the definition decl of the primary base!");
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000884
885 // Since the record decl shares its vtable pointer with the primary base
886 // we need to start counting at the end of the primary base's vtable.
887 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
888 }
889
890 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
891
892 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
893 e = RD->method_end(); i != e; ++i) {
894 const CXXMethodDecl *MD = *i;
895
896 // We only want virtual methods.
897 if (!MD->isVirtual())
898 continue;
899
900 bool ShouldAddEntryForMethod = true;
901
902 // Check if this method overrides a method in the primary base.
903 for (CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
904 e = MD->end_overridden_methods(); i != e; ++i) {
905 const CXXMethodDecl *OverriddenMD = *i;
906 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
907 assert(OverriddenMD->isCanonicalDecl() &&
908 "Should have the canonical decl of the overridden RD!");
909
910 if (OverriddenRD == PrimaryBase) {
911 // Check if converting from the return type of the method to the
912 // return type of the overridden method requires conversion.
913 QualType ReturnType =
914 MD->getType()->getAs<FunctionType>()->getResultType();
915 QualType OverriddenReturnType =
916 OverriddenMD->getType()->getAs<FunctionType>()->getResultType();
917
918 if (!TypeConversionRequiresAdjustment(CGM.getContext(),
919 ReturnType, OverriddenReturnType)) {
920 // This index is shared between the index in the vtable of the primary
921 // base class.
922 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
923 const CXXDestructorDecl *OverriddenDD =
924 cast<CXXDestructorDecl>(OverriddenMD);
925
926 // Add both the complete and deleting entries.
927 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
928 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
929 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
930 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
931 } else {
932 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
933 }
934
935 // We don't need to add an entry for this method.
936 ShouldAddEntryForMethod = false;
937 break;
938 }
939 }
940 }
941
942 if (!ShouldAddEntryForMethod)
943 continue;
944
945 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
946 if (MD->isImplicit()) {
947 assert(!ImplicitVirtualDtor &&
948 "Did already see an implicit virtual dtor!");
949 ImplicitVirtualDtor = DD;
950 continue;
951 }
952
953 // Add the complete dtor.
954 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
955
956 // Add the deleting dtor.
957 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
958 } else {
959 // Add the entry.
960 MethodVtableIndices[MD] = CurrentIndex++;
961 }
962 }
963
964 if (ImplicitVirtualDtor) {
965 // Itanium C++ ABI 2.5.2:
966 // If a class has an implicitly-defined virtual destructor,
967 // its entries come after the declared virtual function pointers.
968
969 // Add the complete dtor.
970 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
971 CurrentIndex++;
972
973 // Add the deleting dtor.
974 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
975 CurrentIndex++;
976 }
977
978 NumVirtualFunctionPointers[RD] = CurrentIndex;
979}
980
981uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
982 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
983 NumVirtualFunctionPointers.find(RD);
984 if (I != NumVirtualFunctionPointers.end())
985 return I->second;
986
987 ComputeMethodVtableIndices(RD);
988
989 I = NumVirtualFunctionPointers.find(RD);
990 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
991 return I->second;
992}
993
994uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000995 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000996 if (I != MethodVtableIndices.end())
997 return I->second;
998
Anders Carlssona0fdd912009-11-13 17:08:56 +0000999 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001000
1001 ComputeMethodVtableIndices(RD);
1002
Anders Carlssona0fdd912009-11-13 17:08:56 +00001003 I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001004 assert(I != MethodVtableIndices.end() && "Did not find index!");
1005 return I->second;
1006}
1007
1008int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
1009 const CXXRecordDecl *VBase) {
1010 ClassPairTy ClassPair(RD, VBase);
1011
1012 VirtualBaseClassIndiciesTy::iterator I =
1013 VirtualBaseClassIndicies.find(ClassPair);
1014 if (I != VirtualBaseClassIndicies.end())
1015 return I->second;
1016
1017 std::vector<llvm::Constant *> methods;
1018 // FIXME: This seems expensive. Can we do a partial job to get
1019 // just this data.
Mike Stump4cde6262009-11-13 02:13:54 +00001020 VtableBuilder b(methods, RD, RD, 0, CGM);
Mike Stump6a9612f2009-10-31 20:06:59 +00001021 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00001022 b.GenerateVtableForBase(RD);
1023 b.GenerateVtableForVBases(RD);
1024
1025 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1026 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
1027 // Insert all types.
1028 ClassPairTy ClassPair(RD, I->first);
1029
1030 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
1031 }
1032
1033 I = VirtualBaseClassIndicies.find(ClassPair);
1034 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
1035
1036 return I->second;
1037}
1038
Mike Stump9840c702009-11-12 20:47:57 +00001039llvm::Constant *CodeGenModule::GenerateVtable(const CXXRecordDecl *LayoutClass,
1040 const CXXRecordDecl *RD,
Mike Stump8cfcb522009-11-11 20:26:26 +00001041 uint64_t Offset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001042 llvm::SmallString<256> OutName;
Mike Stump9840c702009-11-12 20:47:57 +00001043 if (LayoutClass != RD)
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001044 getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset/8, RD, OutName);
Mike Stump8cfcb522009-11-11 20:26:26 +00001045 else
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001046 getMangleContext().mangleCXXVtable(RD, OutName);
1047 llvm::StringRef Name = OutName.str();
Benjamin Kramer7a9474e2009-10-11 22:57:54 +00001048
Anders Carlssondbd920c2009-10-11 22:13:54 +00001049 std::vector<llvm::Constant *> methods;
1050 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1051 int64_t AddressPoint;
1052
Mike Stump85615df2009-11-19 04:04:36 +00001053 llvm::GlobalVariable *GV = getModule().getGlobalVariable(Name);
Mike Stump23a35422009-11-19 20:52:19 +00001054 if (GV && AddressPoints[LayoutClass] && !GV->isDeclaration()) {
Mike Stump85615df2009-11-19 04:04:36 +00001055 AddressPoint=(*(*(AddressPoints[LayoutClass]))[RD])[std::make_pair(RD,
1056 Offset)];
Mike Stump23a35422009-11-19 20:52:19 +00001057 // FIXME: We can never have 0 address point. Do this for now so gepping
1058 // retains the same structure. Later, we'll just assert.
1059 if (AddressPoint == 0)
1060 AddressPoint = 1;
1061 } else {
Mike Stump85615df2009-11-19 04:04:36 +00001062 VtableBuilder b(methods, RD, LayoutClass, Offset, *this);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001063
Mike Stump85615df2009-11-19 04:04:36 +00001064 D1(printf("vtable %s\n", RD->getNameAsCString()));
1065 // First comes the vtables for all the non-virtual bases...
1066 AddressPoint = b.GenerateVtableForBase(RD, Offset);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001067
Mike Stump85615df2009-11-19 04:04:36 +00001068 // then the vtables for all the virtual bases.
1069 b.GenerateVtableForVBases(RD, Offset);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001070
Mike Stump85615df2009-11-19 04:04:36 +00001071 bool CreateDefinition = true;
1072 if (LayoutClass != RD)
1073 CreateDefinition = true;
1074 else {
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001075 const ASTRecordLayout &Layout =
1076 getContext().getASTRecordLayout(LayoutClass);
1077
1078 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stump85615df2009-11-19 04:04:36 +00001079 if (!KeyFunction->getBody()) {
1080 // If there is a KeyFunction, and it isn't defined, just build a
1081 // reference to the vtable.
1082 CreateDefinition = false;
1083 }
1084 }
1085 }
1086
1087 llvm::Constant *C = 0;
1088 llvm::Type *type = Ptr8Ty;
1089 llvm::GlobalVariable::LinkageTypes linktype
1090 = llvm::GlobalValue::ExternalLinkage;
1091 if (CreateDefinition) {
1092 llvm::ArrayType *ntype = llvm::ArrayType::get(Ptr8Ty, methods.size());
1093 C = llvm::ConstantArray::get(ntype, methods);
1094 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
1095 if (LayoutClass->isInAnonymousNamespace())
1096 linktype = llvm::GlobalValue::InternalLinkage;
1097 type = ntype;
1098 }
1099 llvm::GlobalVariable *OGV = GV;
1100 GV = new llvm::GlobalVariable(getModule(), type, true, linktype, C, Name);
1101 if (OGV) {
1102 GV->takeName(OGV);
1103 llvm::Constant *NewPtr = llvm::ConstantExpr::getBitCast(GV,
1104 OGV->getType());
1105 OGV->replaceAllUsesWith(NewPtr);
1106 OGV->eraseFromParent();
1107 }
1108 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1109 if (Hidden)
1110 GV->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1111 }
Mike Stumpe56ceca2009-11-18 04:00:48 +00001112 llvm::Constant *vtable = llvm::ConstantExpr::getBitCast(GV, Ptr8Ty);
Mike Stump380dd752009-11-10 07:44:33 +00001113 llvm::Constant *AddressPointC;
1114 uint32_t LLVMPointerWidth = getContext().Target.getPointerWidth(0);
1115 AddressPointC = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1116 AddressPoint*LLVMPointerWidth/8);
Mike Stump9840c702009-11-12 20:47:57 +00001117 vtable = llvm::ConstantExpr::getInBoundsGetElementPtr(vtable, &AddressPointC,
1118 1);
Mike Stump380dd752009-11-10 07:44:33 +00001119
Mike Stump23a35422009-11-19 20:52:19 +00001120 assert(vtable->getType() == Ptr8Ty);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001121 return vtable;
1122}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001123
Mike Stump92f2fe22009-12-02 19:07:44 +00001124namespace {
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001125class VTTBuilder {
1126 /// Inits - The list of values built for the VTT.
1127 std::vector<llvm::Constant *> &Inits;
1128 /// Class - The most derived class that this vtable is being built for.
1129 const CXXRecordDecl *Class;
1130 CodeGenModule &CGM; // Per-module state.
Mike Stump971977f2009-11-11 00:35:07 +00001131 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpaee8de32009-11-11 03:08:24 +00001132 /// BLayout - Layout for the most derived class that this vtable is being
1133 /// built for.
1134 const ASTRecordLayout &BLayout;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001135 CodeGenModule::AddrMap_t &AddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +00001136 // vtbl - A pointer to the vtable for Class.
1137 llvm::Constant *ClassVtbl;
1138 llvm::LLVMContext &VMContext;
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001139
Mike Stump28f7ce12009-11-12 22:56:32 +00001140 /// BuildVtablePtr - Build up a referene to the given secondary vtable
Mike Stumpacfd1e52009-11-13 01:54:23 +00001141 llvm::Constant *BuildVtablePtr(llvm::Constant *vtbl,
1142 const CXXRecordDecl *VtblClass,
1143 const CXXRecordDecl *RD,
Mike Stump28f7ce12009-11-12 22:56:32 +00001144 uint64_t Offset) {
1145 int64_t AddressPoint;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001146 AddressPoint = (*AddressPoints[VtblClass])[std::make_pair(RD, Offset)];
Mike Stump80ac2352009-11-12 23:36:21 +00001147 // FIXME: We can never have 0 address point. Do this for now so gepping
Mike Stump23a35422009-11-19 20:52:19 +00001148 // retains the same structure. Later we'll just assert.
Mike Stump80ac2352009-11-12 23:36:21 +00001149 if (AddressPoint == 0)
1150 AddressPoint = 1;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001151 D1(printf("XXX address point for %s in %s layout %s at offset %d was %d\n",
1152 RD->getNameAsCString(), VtblClass->getNameAsCString(),
1153 Class->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump28f7ce12009-11-12 22:56:32 +00001154 uint32_t LLVMPointerWidth = CGM.getContext().Target.getPointerWidth(0);
1155 llvm::Constant *init;
1156 init = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1157 AddressPoint*LLVMPointerWidth/8);
1158 init = llvm::ConstantExpr::getInBoundsGetElementPtr(vtbl, &init, 1);
1159 return init;
1160 }
1161
Mike Stump9840c702009-11-12 20:47:57 +00001162 /// Secondary - Add the secondary vtable pointers to Inits. Offset is the
1163 /// current offset in bits to the object we're working on.
Mike Stump28f7ce12009-11-12 22:56:32 +00001164 void Secondary(const CXXRecordDecl *RD, llvm::Constant *vtbl,
Mike Stumpacfd1e52009-11-13 01:54:23 +00001165 const CXXRecordDecl *VtblClass, uint64_t Offset=0,
1166 bool MorallyVirtual=false) {
Mike Stump971977f2009-11-11 00:35:07 +00001167 if (RD->getNumVBases() == 0 && ! MorallyVirtual)
1168 return;
1169
1170 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1171 e = RD->bases_end(); i != e; ++i) {
1172 const CXXRecordDecl *Base =
1173 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1174 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1175 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1176 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1177 bool NonVirtualPrimaryBase;
1178 NonVirtualPrimaryBase = !PrimaryBaseWasVirtual && Base == PrimaryBase;
1179 bool BaseMorallyVirtual = MorallyVirtual | i->isVirtual();
Mike Stumpaee8de32009-11-11 03:08:24 +00001180 uint64_t BaseOffset;
1181 if (!i->isVirtual()) {
1182 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1183 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1184 } else
1185 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump80ac2352009-11-12 23:36:21 +00001186 llvm::Constant *subvtbl = vtbl;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001187 const CXXRecordDecl *subVtblClass = VtblClass;
Mike Stump971977f2009-11-11 00:35:07 +00001188 if ((Base->getNumVBases() || BaseMorallyVirtual)
1189 && !NonVirtualPrimaryBase) {
1190 // FIXME: Slightly too many of these for __ZTT8test8_B2
Mike Stump28f7ce12009-11-12 22:56:32 +00001191 llvm::Constant *init;
Mike Stump80ac2352009-11-12 23:36:21 +00001192 if (BaseMorallyVirtual)
Mike Stumpacfd1e52009-11-13 01:54:23 +00001193 init = BuildVtablePtr(vtbl, VtblClass, RD, Offset);
Mike Stump80ac2352009-11-12 23:36:21 +00001194 else {
Mike Stump28f7ce12009-11-12 22:56:32 +00001195 init = CGM.getVtableInfo().getCtorVtable(Class, Base, BaseOffset);
Mike Stump80ac2352009-11-12 23:36:21 +00001196 subvtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stumpacfd1e52009-11-13 01:54:23 +00001197 subVtblClass = Base;
Mike Stump80ac2352009-11-12 23:36:21 +00001198 }
Mike Stump28f7ce12009-11-12 22:56:32 +00001199 Inits.push_back(init);
Mike Stump971977f2009-11-11 00:35:07 +00001200 }
Mike Stumpacfd1e52009-11-13 01:54:23 +00001201 Secondary(Base, subvtbl, subVtblClass, BaseOffset, BaseMorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001202 }
1203 }
1204
Mike Stump9840c702009-11-12 20:47:57 +00001205 /// BuiltVTT - Add the VTT to Inits. Offset is the offset in bits to the
1206 /// currnet object we're working on.
1207 void BuildVTT(const CXXRecordDecl *RD, uint64_t Offset, bool MorallyVirtual) {
Mike Stump971977f2009-11-11 00:35:07 +00001208 if (RD->getNumVBases() == 0 && !MorallyVirtual)
1209 return;
1210
Mike Stump9840c702009-11-12 20:47:57 +00001211 llvm::Constant *init;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001212 const CXXRecordDecl *VtblClass;
1213
Mike Stump971977f2009-11-11 00:35:07 +00001214 // First comes the primary virtual table pointer...
Mike Stumpacfd1e52009-11-13 01:54:23 +00001215 if (MorallyVirtual) {
1216 init = BuildVtablePtr(ClassVtbl, Class, RD, Offset);
1217 VtblClass = Class;
1218 } else {
Mike Stump9840c702009-11-12 20:47:57 +00001219 init = CGM.getVtableInfo().getCtorVtable(Class, RD, Offset);
Mike Stumpacfd1e52009-11-13 01:54:23 +00001220 VtblClass = RD;
1221 }
Mike Stump28f7ce12009-11-12 22:56:32 +00001222 llvm::Constant *vtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump9840c702009-11-12 20:47:57 +00001223 Inits.push_back(init);
Mike Stump971977f2009-11-11 00:35:07 +00001224
1225 // then the secondary VTTs....
Mike Stump9840c702009-11-12 20:47:57 +00001226 SecondaryVTTs(RD, Offset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001227
1228 // and last the secondary vtable pointers.
Mike Stumpacfd1e52009-11-13 01:54:23 +00001229 Secondary(RD, vtbl, VtblClass, Offset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001230 }
1231
1232 /// SecondaryVTTs - Add the secondary VTTs to Inits. The secondary VTTs are
1233 /// built from each direct non-virtual proper base that requires a VTT in
1234 /// declaration order.
Mike Stump9840c702009-11-12 20:47:57 +00001235 void SecondaryVTTs(const CXXRecordDecl *RD, uint64_t Offset=0,
1236 bool MorallyVirtual=false) {
Mike Stump971977f2009-11-11 00:35:07 +00001237 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1238 e = RD->bases_end(); i != e; ++i) {
1239 const CXXRecordDecl *Base =
1240 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1241 if (i->isVirtual())
1242 continue;
Mike Stump9840c702009-11-12 20:47:57 +00001243 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1244 uint64_t BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1245 BuildVTT(Base, BaseOffset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001246 }
1247 }
1248
1249 /// VirtualVTTs - Add the VTT for each proper virtual base in inheritance
1250 /// graph preorder.
1251 void VirtualVTTs(const CXXRecordDecl *RD) {
1252 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1253 e = RD->bases_end(); i != e; ++i) {
1254 const CXXRecordDecl *Base =
1255 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1256 if (i->isVirtual() && !SeenVBase.count(Base)) {
1257 SeenVBase.insert(Base);
Mike Stump9840c702009-11-12 20:47:57 +00001258 uint64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
1259 BuildVTT(Base, BaseOffset, true);
Mike Stump971977f2009-11-11 00:35:07 +00001260 }
1261 VirtualVTTs(Base);
1262 }
1263 }
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001264public:
1265 VTTBuilder(std::vector<llvm::Constant *> &inits, const CXXRecordDecl *c,
Mike Stumpaee8de32009-11-11 03:08:24 +00001266 CodeGenModule &cgm)
1267 : Inits(inits), Class(c), CGM(cgm),
Mike Stump9840c702009-11-12 20:47:57 +00001268 BLayout(cgm.getContext().getASTRecordLayout(c)),
Mike Stumpacfd1e52009-11-13 01:54:23 +00001269 AddressPoints(*cgm.AddressPoints[c]),
Mike Stump9840c702009-11-12 20:47:57 +00001270 VMContext(cgm.getModule().getContext()) {
Mike Stump380dd752009-11-10 07:44:33 +00001271
Mike Stump971977f2009-11-11 00:35:07 +00001272 // First comes the primary virtual table pointer for the complete class...
Mike Stump9840c702009-11-12 20:47:57 +00001273 ClassVtbl = CGM.getVtableInfo().getVtable(Class);
1274 Inits.push_back(ClassVtbl);
1275 ClassVtbl = dyn_cast<llvm::Constant>(ClassVtbl->getOperand(0));
1276
Mike Stump971977f2009-11-11 00:35:07 +00001277 // then the secondary VTTs...
1278 SecondaryVTTs(Class);
1279
1280 // then the secondary vtable pointers...
Mike Stumpacfd1e52009-11-13 01:54:23 +00001281 Secondary(Class, ClassVtbl, Class);
Mike Stump971977f2009-11-11 00:35:07 +00001282
1283 // and last, the virtual VTTs.
1284 VirtualVTTs(Class);
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001285 }
1286};
Mike Stump92f2fe22009-12-02 19:07:44 +00001287}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001288
Mike Stump380dd752009-11-10 07:44:33 +00001289llvm::Constant *CodeGenModule::GenerateVTT(const CXXRecordDecl *RD) {
Mike Stumpf1c03332009-11-10 19:13:04 +00001290 // Only classes that have virtual bases need a VTT.
1291 if (RD->getNumVBases() == 0)
1292 return 0;
1293
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001294 llvm::SmallString<256> OutName;
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001295 getMangleContext().mangleCXXVTT(RD, OutName);
1296 llvm::StringRef Name = OutName.str();
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001297
1298 llvm::GlobalVariable::LinkageTypes linktype;
1299 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
Mike Stump85615df2009-11-19 04:04:36 +00001300 if (RD->isInAnonymousNamespace())
1301 linktype = llvm::GlobalValue::InternalLinkage;
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001302 std::vector<llvm::Constant *> inits;
1303 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1304
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001305 D1(printf("vtt %s\n", RD->getNameAsCString()));
1306
Mike Stump971977f2009-11-11 00:35:07 +00001307 VTTBuilder b(inits, RD, *this);
1308
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001309 llvm::Constant *C;
1310 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, inits.size());
1311 C = llvm::ConstantArray::get(type, inits);
Mike Stumpe56ceca2009-11-18 04:00:48 +00001312 llvm::GlobalVariable *vtt = new llvm::GlobalVariable(getModule(), type, true,
Mike Stump85615df2009-11-19 04:04:36 +00001313 linktype, C, Name);
Mike Stumpe56ceca2009-11-18 04:00:48 +00001314 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1315 if (Hidden)
1316 vtt->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1317 return llvm::ConstantExpr::getBitCast(vtt, Ptr8Ty);
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001318}
Mike Stump380dd752009-11-10 07:44:33 +00001319
Mike Stump58588942009-11-19 01:08:19 +00001320void CGVtableInfo::GenerateClassData(const CXXRecordDecl *RD) {
1321 Vtables[RD] = CGM.GenerateVtable(RD, RD);
Mike Stumpde050572009-12-02 18:57:08 +00001322 CGM.GenerateRTTI(RD);
Mike Stump58588942009-11-19 01:08:19 +00001323 CGM.GenerateVTT(RD);
1324}
1325
Mike Stump8cfcb522009-11-11 20:26:26 +00001326llvm::Constant *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Mike Stump380dd752009-11-10 07:44:33 +00001327 llvm::Constant *&vtbl = Vtables[RD];
1328 if (vtbl)
1329 return vtbl;
Mike Stump9840c702009-11-12 20:47:57 +00001330 vtbl = CGM.GenerateVtable(RD, RD);
Mike Stump85615df2009-11-19 04:04:36 +00001331
1332 bool CreateDefinition = true;
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001333
1334 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1335 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stump85615df2009-11-19 04:04:36 +00001336 if (!KeyFunction->getBody()) {
1337 // If there is a KeyFunction, and it isn't defined, just build a
1338 // reference to the vtable.
1339 CreateDefinition = false;
1340 }
1341 }
1342
1343 if (CreateDefinition) {
Mike Stumpde050572009-12-02 18:57:08 +00001344 CGM.GenerateRTTI(RD);
Mike Stump85615df2009-11-19 04:04:36 +00001345 CGM.GenerateVTT(RD);
1346 }
Mike Stump380dd752009-11-10 07:44:33 +00001347 return vtbl;
1348}
Mike Stump8cfcb522009-11-11 20:26:26 +00001349
Mike Stump9840c702009-11-12 20:47:57 +00001350llvm::Constant *CGVtableInfo::getCtorVtable(const CXXRecordDecl *LayoutClass,
1351 const CXXRecordDecl *RD,
Mike Stump8cfcb522009-11-11 20:26:26 +00001352 uint64_t Offset) {
Mike Stump9840c702009-11-12 20:47:57 +00001353 return CGM.GenerateVtable(LayoutClass, RD, Offset);
Mike Stump8cfcb522009-11-11 20:26:26 +00001354}
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001355
1356void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
1357 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1358 const CXXRecordDecl *RD = MD->getParent();
1359
1360 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1361
1362 // Get the key function.
1363 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
1364
1365 if (!KeyFunction) {
1366 // If there's no key function, we don't want to emit the vtable here.
1367 return;
1368 }
1369
1370 // Check if we have the key function.
1371 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
1372 return;
1373
1374 // If the key function is a destructor, we only want to emit the vtable once,
1375 // so do it for the complete destructor.
1376 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Complete)
1377 return;
1378
1379 // Emit the data.
1380 GenerateClassData(RD);
1381}
1382