blob: 869bcc0e6a6f33efb37aa3e9b5740e096b8c13fa [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.
Anders Carlsson0e881162009-12-04 03:46:21 +000048
Anders Carlssona0fdd912009-11-13 17:08:56 +000049 llvm::DenseMap<GlobalDecl, Index_t> VCall;
50 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stump9e7e3c62009-11-06 23:27:42 +000051 // This is the offset to the nearest virtual base
Anders Carlssona0fdd912009-11-13 17:08:56 +000052 llvm::DenseMap<GlobalDecl, Index_t> NonVirtualOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +000053 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stump94aff932009-10-27 23:46:47 +000054
Anders Carlsson6d4ccb72009-11-26 19:54:33 +000055 /// PureVirtualFunction - Points to __cxa_pure_virtual.
56 llvm::Constant *PureVirtualFn;
57
Anders Carlssonc7ab1a82009-12-04 02:01:07 +000058 /// VtableMethods - A data structure for keeping track of methods in a vtable.
59 /// Can add methods, override methods and iterate in vtable order.
60 class VtableMethods {
61 // MethodToIndexMap - Maps from a global decl to the index it has in the
62 // Methods vector.
63 llvm::DenseMap<GlobalDecl, uint64_t> MethodToIndexMap;
64
65 /// Methods - The methods, in vtable order.
66 typedef llvm::SmallVector<GlobalDecl, 16> MethodsVectorTy;
67 MethodsVectorTy Methods;
68
69 public:
70 /// AddMethod - Add a method to the vtable methods.
71 void AddMethod(GlobalDecl GD) {
72 assert(!MethodToIndexMap.count(GD) &&
73 "Method has already been added!");
74
75 MethodToIndexMap[GD] = Methods.size();
76 Methods.push_back(GD);
77 }
78
79 /// OverrideMethod - Replace a method with another.
80 void OverrideMethod(GlobalDecl OverriddenGD, GlobalDecl GD) {
81 llvm::DenseMap<GlobalDecl, uint64_t>::iterator i
82 = MethodToIndexMap.find(OverriddenGD);
83 assert(i != MethodToIndexMap.end() && "Did not find entry!");
84
85 // Get the index of the old decl.
86 uint64_t Index = i->second;
87
88 // Replace the old decl with the new decl.
89 Methods[Index] = GD;
90
Anders Carlssonc7ab1a82009-12-04 02:01:07 +000091 // And add the new.
92 MethodToIndexMap[GD] = Index;
93 }
94
Anders Carlssonc0c49932009-12-04 03:41:37 +000095 /// getIndex - Returns the index of the given method.
96 uint64_t getIndex(GlobalDecl GD) const {
97 assert(MethodToIndexMap.count(GD) && "Did not find method!");
98
99 return MethodToIndexMap.lookup(GD);
100 }
101
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000102 MethodsVectorTy::size_type size() const {
103 return Methods.size();
104 }
105
106 void clear() {
107 MethodToIndexMap.clear();
108 Methods.clear();
109 }
110
Anders Carlssonc0c49932009-12-04 03:41:37 +0000111 GlobalDecl operator[](uint64_t Index) const {
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000112 return Methods[Index];
113 }
114 };
115
116 /// Methods - The vtable methods we're currently building.
117 VtableMethods Methods;
118
Anders Carlsson98fdb242009-12-04 02:26:15 +0000119 /// ThisAdjustments - For a given index in the vtable, contains the 'this'
120 /// pointer adjustment needed for a method.
121 typedef llvm::DenseMap<uint64_t, ThunkAdjustment> ThisAdjustmentsMapTy;
122 ThisAdjustmentsMapTy ThisAdjustments;
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000123
Anders Carlssona8756702009-12-04 02:22:02 +0000124 /// BaseReturnTypes - Contains the base return types of methods who have been
125 /// overridden with methods whose return types require adjustment. Used for
126 /// generating covariant thunk information.
127 typedef llvm::DenseMap<uint64_t, CanQualType> BaseReturnTypesMapTy;
128 BaseReturnTypesMapTy BaseReturnTypes;
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000129
Anders Carlssondbd920c2009-10-11 22:13:54 +0000130 std::vector<Index_t> VCalls;
Mike Stump9840c702009-11-12 20:47:57 +0000131
132 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stump23a35422009-11-19 20:52:19 +0000133 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
134 // vtable for use in computing the initializers for the VTT.
135 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +0000136
Anders Carlssondbd920c2009-10-11 22:13:54 +0000137 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000138 const bool Extern;
139 const uint32_t LLVMPointerWidth;
140 Index_t extra;
Mike Stump11dea942009-10-15 02:04:03 +0000141 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stump23a35422009-11-19 20:52:19 +0000142 static llvm::DenseMap<CtorVtable_t, int64_t>&
143 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
144 const CXXRecordDecl *c) {
145 CodeGenModule::AddrMap_t *&oref = cgm.AddressPoints[l];
146 if (oref == 0)
147 oref = new CodeGenModule::AddrMap_t;
148
149 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
150 if (ref == 0)
151 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
152 return *ref;
153 }
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000154
155 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
156 llvm::Constant* getPureVirtualFn() {
157 if (!PureVirtualFn) {
158 const llvm::FunctionType *Ty =
159 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
160 /*isVarArg=*/false);
161 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
162 }
163
164 return PureVirtualFn;
165 }
166
Anders Carlssondbd920c2009-10-11 22:13:54 +0000167public:
Mike Stump4cde6262009-11-13 02:13:54 +0000168 VtableBuilder(std::vector<llvm::Constant *> &meth, const CXXRecordDecl *c,
169 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm)
170 : methods(meth), Class(c), LayoutClass(l), LayoutOffset(lo),
Mike Stumpacfd1e52009-11-13 01:54:23 +0000171 BLayout(cgm.getContext().getASTRecordLayout(l)),
Mike Stumpde050572009-12-02 18:57:08 +0000172 rtti(cgm.GenerateRTTIRef(c)), VMContext(cgm.getModule().getContext()),
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000173 CGM(cgm), PureVirtualFn(0),subAddressPoints(AllocAddressPoint(cgm, l, c)),
Mike Stump6be2b172009-11-19 00:49:05 +0000174 Extern(!l->isInAnonymousNamespace()),
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000175 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000176 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
177 }
178
Anders Carlssondbd920c2009-10-11 22:13:54 +0000179 llvm::DenseMap<const CXXRecordDecl *, Index_t> &getVBIndex()
180 { return VBIndex; }
181
182 llvm::Constant *wrap(Index_t i) {
183 llvm::Constant *m;
184 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
185 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
186 }
187
188 llvm::Constant *wrap(llvm::Constant *m) {
189 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
190 }
191
Mike Stump79336282009-12-02 19:50:41 +0000192#define D1(x)
193//#define D1(X) do { if (getenv("DEBUG")) { X; } } while (0)
Mike Stump6a9612f2009-10-31 20:06:59 +0000194
195 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stumpab28c132009-10-13 22:54:56 +0000196 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000197 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
198 e = RD->bases_end(); i != e; ++i) {
199 const CXXRecordDecl *Base =
200 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpab28c132009-10-13 22:54:56 +0000201 Index_t next_vbindex = current_vbindex;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000202 if (i->isVirtual() && !SeenVBase.count(Base)) {
203 SeenVBase.insert(Base);
Mike Stumpab28c132009-10-13 22:54:56 +0000204 if (updateVBIndex) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000205 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stumpab28c132009-10-13 22:54:56 +0000206 - 3*LLVMPointerWidth/8);
207 VBIndex[Base] = next_vbindex;
208 }
Mike Stump6a9612f2009-10-31 20:06:59 +0000209 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
210 VCalls.push_back((0?700:0) + BaseOffset);
211 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
212 Base->getNameAsCString(),
213 (int)-VCalls.size()-3, (int)BaseOffset,
214 Class->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000215 }
Mike Stumpab28c132009-10-13 22:54:56 +0000216 // We also record offsets for non-virtual bases to closest enclosing
217 // virtual base. We do this so that we don't have to search
218 // for the nearst virtual base class when generating thunks.
219 if (updateVBIndex && VBIndex.count(Base) == 0)
220 VBIndex[Base] = next_vbindex;
Mike Stump6a9612f2009-10-31 20:06:59 +0000221 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000222 }
223 }
224
225 void StartNewTable() {
226 SeenVBase.clear();
227 }
228
Mike Stump3425b972009-10-15 09:30:16 +0000229 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
230 Index_t Offset = 0) {
231
232 if (B == D)
233 return Offset;
234
235 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
236 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
237 e = D->bases_end(); i != e; ++i) {
238 const CXXRecordDecl *Base =
239 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
240 int64_t BaseOffset = 0;
241 if (!i->isVirtual())
242 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
243 int64_t o = getNVOffset_1(Base, B, BaseOffset);
244 if (o >= 0)
245 return o;
246 }
247
248 return -1;
249 }
250
251 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
252 /// derived class D.
253 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +0000254 qD = qD->getPointeeType();
255 qB = qB->getPointeeType();
Mike Stump3425b972009-10-15 09:30:16 +0000256 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
257 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
258 int64_t o = getNVOffset_1(D, B);
259 if (o >= 0)
260 return o;
261
262 assert(false && "FIXME: non-virtual base not found");
263 return 0;
264 }
265
Anders Carlssondbd920c2009-10-11 22:13:54 +0000266 /// getVbaseOffset - Returns the index into the vtable for the virtual base
267 /// offset for the given (B) virtual base of the derived class D.
268 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +0000269 qD = qD->getPointeeType();
270 qB = qB->getPointeeType();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000271 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
272 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
273 if (D != Class)
Eli Friedman76ed1f72009-11-30 01:19:33 +0000274 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000275 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
276 i = VBIndex.find(B);
277 if (i != VBIndex.end())
278 return i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000279
Mike Stumpab28c132009-10-13 22:54:56 +0000280 assert(false && "FIXME: Base not found");
Anders Carlssondbd920c2009-10-11 22:13:54 +0000281 return 0;
282 }
283
Anders Carlssona0fdd912009-11-13 17:08:56 +0000284 bool OverrideMethod(GlobalDecl GD, llvm::Constant *m,
Mike Stump3425b972009-10-15 09:30:16 +0000285 bool MorallyVirtual, Index_t OverrideOffset,
Anders Carlsson27682a32009-12-03 01:54:02 +0000286 Index_t Offset, int64_t CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000287
Anders Carlssonadfa2672009-12-04 02:39:04 +0000288 /// AppendMethods - Append the current methods to the vtable.
Anders Carlssonbf540272009-12-04 02:56:03 +0000289 void AppendMethodsToVtable();
Anders Carlssonadfa2672009-12-04 02:39:04 +0000290
Anders Carlssona0fdd912009-11-13 17:08:56 +0000291 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
292 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
293
Anders Carlssonecf282b2009-11-24 05:08:52 +0000294 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump1ae31782009-10-27 23:36:26 +0000295
Mike Stumpc085a982009-12-03 16:55:20 +0000296 return wrap(CGM.GetAddrOfFunction(GD, Ty));
Mike Stump1ae31782009-10-27 23:36:26 +0000297 }
298
Mike Stump9e7e3c62009-11-06 23:27:42 +0000299 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
300 int64_t CurrentVBaseOffset) {
Mike Stump11dea942009-10-15 02:04:03 +0000301 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlssondbd920c2009-10-11 22:13:54 +0000302 e = Path->rend(); i != e; ++i) {
303 const CXXRecordDecl *RD = i->first;
Mike Stump3425b972009-10-15 09:30:16 +0000304 int64_t OverrideOffset = i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000305 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
306 ++mi) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000307 const CXXMethodDecl *MD = *mi;
308
309 if (!MD->isVirtual())
Anders Carlssondbd920c2009-10-11 22:13:54 +0000310 continue;
311
Anders Carlssona0fdd912009-11-13 17:08:56 +0000312 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
313 // Override both the complete and the deleting destructor.
314 GlobalDecl CompDtor(DD, Dtor_Complete);
315 OverrideMethod(CompDtor, WrapAddrOf(CompDtor), MorallyVirtual,
316 OverrideOffset, Offset, CurrentVBaseOffset);
317
318 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
319 OverrideMethod(DeletingDtor, WrapAddrOf(DeletingDtor), MorallyVirtual,
320 OverrideOffset, Offset, CurrentVBaseOffset);
321 } else {
322 OverrideMethod(MD, WrapAddrOf(MD), MorallyVirtual, OverrideOffset,
323 Offset, CurrentVBaseOffset);
324 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000325 }
326 }
327 }
328
Anders Carlssona0fdd912009-11-13 17:08:56 +0000329 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000330 int64_t CurrentVBaseOffset) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000331 llvm::Constant *m = WrapAddrOf(GD);
Mike Stump1ae31782009-10-27 23:36:26 +0000332
Anders Carlssondbd920c2009-10-11 22:13:54 +0000333 // If we can find a previously allocated slot for this, reuse it.
Anders Carlssona0fdd912009-11-13 17:08:56 +0000334 if (OverrideMethod(GD, m, MorallyVirtual, Offset, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000335 CurrentVBaseOffset))
Anders Carlssondbd920c2009-10-11 22:13:54 +0000336 return;
337
Anders Carlssona7f19112009-12-04 02:08:24 +0000338 // We didn't find an entry in the vtable that we could use, add a new
339 // entry.
340 Methods.AddMethod(GD);
341
Anders Carlssondbd920c2009-10-11 22:13:54 +0000342 submethods.push_back(m);
Mike Stumpe99cc452009-11-13 23:45:53 +0000343 D1(printf(" vfn for %s at %d\n", MD->getNameAsString().c_str(),
344 (int)Index[GD]));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000345 if (MorallyVirtual) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000346 VCallOffset[GD] = Offset/8;
347 Index_t &idx = VCall[GD];
Anders Carlssondbd920c2009-10-11 22:13:54 +0000348 // Allocate the first one, after that, we reuse the previous one.
349 if (idx == 0) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000350 NonVirtualOffset[GD] = CurrentVBaseOffset/8 - Offset/8;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000351 idx = VCalls.size()+1;
352 VCalls.push_back(0);
Mike Stump6a9612f2009-10-31 20:06:59 +0000353 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpe99cc452009-11-13 23:45:53 +0000354 MD->getNameAsString().c_str(), (int)-VCalls.size()-3, 0));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000355 }
356 }
357 }
358
359 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000360 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000361 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssona0fdd912009-11-13 17:08:56 +0000362 ++mi) {
363 const CXXMethodDecl *MD = *mi;
364 if (!MD->isVirtual())
365 continue;
366
367 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
368 // For destructors, add both the complete and the deleting destructor
369 // to the vtable.
370 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000371 CurrentVBaseOffset);
Eli Friedman76ed1f72009-11-30 01:19:33 +0000372 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
373 CurrentVBaseOffset);
374 } else
375 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +0000376 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000377 }
378
379 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
380 const CXXRecordDecl *PrimaryBase,
381 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000382 int64_t Offset, int64_t CurrentVBaseOffset,
383 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +0000384 Path->push_back(std::make_pair(RD, Offset));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000385 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
386 e = RD->bases_end(); i != e; ++i) {
387 if (i->isVirtual())
388 continue;
389 const CXXRecordDecl *Base =
390 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
391 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
392 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
393 StartNewTable();
Mike Stump4cde6262009-11-13 02:13:54 +0000394 GenerateVtableForBase(Base, o, MorallyVirtual, false,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000395 CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000396 }
397 }
Mike Stump11dea942009-10-15 02:04:03 +0000398 Path->pop_back();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000399 }
400
Mike Stump0ca42792009-10-14 18:14:51 +0000401// #define D(X) do { X; } while (0)
402#define D(X)
403
404 void insertVCalls(int InsertionPoint) {
405 llvm::Constant *e = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +0000406 D1(printf("============= combining vbase/vcall\n"));
Mike Stump0ca42792009-10-14 18:14:51 +0000407 D(VCalls.insert(VCalls.begin(), 673));
408 D(VCalls.push_back(672));
Mike Stump3425b972009-10-15 09:30:16 +0000409 methods.insert(methods.begin() + InsertionPoint, VCalls.size(), e);
Mike Stump0ca42792009-10-14 18:14:51 +0000410 // The vcalls come first...
411 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
412 e = VCalls.rend();
413 i != e; ++i)
414 methods[InsertionPoint++] = wrap((0?600:0) + *i);
415 VCalls.clear();
Mike Stumpfbfb52d2009-11-10 02:30:51 +0000416 VCall.clear();
Mike Stump0ca42792009-10-14 18:14:51 +0000417 }
418
Mike Stump65d0e282009-11-13 23:13:20 +0000419 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
420 Index_t AddressPoint) {
421 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
422 RD->getNameAsCString(), Class->getNameAsCString(),
423 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +0000424 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +0000425
426 // Now also add the address point for all our primary bases.
427 while (1) {
428 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
429 RD = Layout.getPrimaryBase();
430 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
431 // FIXME: Double check this.
432 if (RD == 0)
433 break;
434 if (PrimaryBaseWasVirtual &&
435 BLayout.getVBaseClassOffset(RD) != Offset)
436 break;
437 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
438 RD->getNameAsCString(), Class->getNameAsCString(),
439 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +0000440 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +0000441 }
442 }
443
444
Eli Friedmand6a3e672009-12-04 03:54:56 +0000445 Index_t FinishGenerateVtable(const CXXRecordDecl *RD,
446 const ASTRecordLayout &Layout,
447 const CXXRecordDecl *PrimaryBase,
448 bool PrimaryBaseWasVirtual,
449 bool MorallyVirtual, int64_t Offset,
450 bool ForVirtualBase, int64_t CurrentVBaseOffset,
451 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +0000452 bool alloc = false;
453 if (Path == 0) {
454 alloc = true;
455 Path = new Path_t;
456 }
457
Anders Carlssondbd920c2009-10-11 22:13:54 +0000458 StartNewTable();
459 extra = 0;
Mike Stump0ca42792009-10-14 18:14:51 +0000460 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
461 int VCallInsertionPoint = methods.size();
462 if (!DeferVCalls) {
463 insertVCalls(VCallInsertionPoint);
Mike Stump3425b972009-10-15 09:30:16 +0000464 } else
465 // FIXME: just for extra, or for all uses of VCalls.size post this?
466 extra = -VCalls.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000467
Mike Stump4cde6262009-11-13 02:13:54 +0000468 methods.push_back(wrap(-((Offset-LayoutOffset)/8)));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000469 methods.push_back(rtti);
470 Index_t AddressPoint = methods.size();
471
Anders Carlssona7f19112009-12-04 02:08:24 +0000472 assert(submethods.size() == Methods.size() && "Method size mismatch!");
473
Anders Carlssonbf540272009-12-04 02:56:03 +0000474 AppendMethodsToVtable();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000475
476 // and then the non-virtual bases.
477 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000478 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stump0ca42792009-10-14 18:14:51 +0000479
480 if (ForVirtualBase) {
Mike Stump9840c702009-11-12 20:47:57 +0000481 // FIXME: We're adding to VCalls in callers, we need to do the overrides
482 // in the inner part, so that we know the complete set of vcalls during
483 // the build and don't have to insert into methods. Saving out the
484 // AddressPoint here, would need to be fixed, if we didn't do that. Also
485 // retroactively adding vcalls for overrides later wind up in the wrong
486 // place, the vcall slot has to be alloted during the walk of the base
487 // when the function is first introduces.
Mike Stump0ca42792009-10-14 18:14:51 +0000488 AddressPoint += VCalls.size();
Mike Stump9840c702009-11-12 20:47:57 +0000489 insertVCalls(VCallInsertionPoint);
Mike Stump0ca42792009-10-14 18:14:51 +0000490 }
491
Mike Stump65d0e282009-11-13 23:13:20 +0000492 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump9840c702009-11-12 20:47:57 +0000493
Mike Stump11dea942009-10-15 02:04:03 +0000494 if (alloc) {
495 delete Path;
496 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000497 return AddressPoint;
498 }
499
Mike Stump6a9612f2009-10-31 20:06:59 +0000500 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
501 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000502 int64_t CurrentVBaseOffset) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000503 if (!RD->isDynamicClass())
504 return;
505
506 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
507 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
508 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
509
510 // vtables are composed from the chain of primaries.
511 if (PrimaryBase) {
512 D1(printf(" doing primaries for %s most derived %s\n",
513 RD->getNameAsCString(), Class->getNameAsCString()));
514
Mike Stump9e7e3c62009-11-06 23:27:42 +0000515 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
516 if (PrimaryBaseWasVirtual)
517 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
518
Mike Stump6a9612f2009-10-31 20:06:59 +0000519 if (!PrimaryBaseWasVirtual)
520 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000521 updateVBIndex, current_vbindex, BaseCurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000522 }
523
524 D1(printf(" doing vcall entries for %s most derived %s\n",
525 RD->getNameAsCString(), Class->getNameAsCString()));
526
527 // And add the virtuals for the class to the primary vtable.
Eli Friedman76ed1f72009-11-30 01:19:33 +0000528 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000529 }
530
531 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
532 bool updateVBIndex, Index_t current_vbindex,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000533 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000534 bool bottom) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000535 if (!RD->isDynamicClass())
536 return;
537
538 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
539 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
540 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
541
542 // vtables are composed from the chain of primaries.
543 if (PrimaryBase) {
Mike Stump9e7e3c62009-11-06 23:27:42 +0000544 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
545 if (PrimaryBaseWasVirtual) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000546 IndirectPrimary.insert(PrimaryBase);
Mike Stump9e7e3c62009-11-06 23:27:42 +0000547 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
548 }
Mike Stump6a9612f2009-10-31 20:06:59 +0000549
550 D1(printf(" doing primaries for %s most derived %s\n",
551 RD->getNameAsCString(), Class->getNameAsCString()));
552
553 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000554 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000555 BaseCurrentVBaseOffset, false);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000556 }
557
Mike Stump6a9612f2009-10-31 20:06:59 +0000558 D1(printf(" doing vbase entries for %s most derived %s\n",
559 RD->getNameAsCString(), Class->getNameAsCString()));
560 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
561
562 if (RDisVirtualBase || bottom) {
563 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000564 CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000565 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000566 }
567
Mike Stump4cde6262009-11-13 02:13:54 +0000568 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
569 bool MorallyVirtual = false,
Anders Carlssondbd920c2009-10-11 22:13:54 +0000570 bool ForVirtualBase = false,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000571 int CurrentVBaseOffset = 0,
Mike Stump11dea942009-10-15 02:04:03 +0000572 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000573 if (!RD->isDynamicClass())
574 return 0;
575
Mike Stump92774d12009-11-13 02:35:38 +0000576 // Construction vtable don't need parts that have no virtual bases and
577 // aren't morally virtual.
578 if ((LayoutClass != Class) && RD->getNumVBases() == 0 && !MorallyVirtual)
579 return 0;
580
Anders Carlssondbd920c2009-10-11 22:13:54 +0000581 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
582 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
583 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
584
Anders Carlssondbd920c2009-10-11 22:13:54 +0000585 extra = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +0000586 D1(printf("building entries for base %s most derived %s\n",
587 RD->getNameAsCString(), Class->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000588
Mike Stump6a9612f2009-10-31 20:06:59 +0000589 if (ForVirtualBase)
590 extra = VCalls.size();
591
592 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0, ForVirtualBase,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000593 CurrentVBaseOffset, true);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000594
595 if (Path)
Mike Stump9e7e3c62009-11-06 23:27:42 +0000596 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000597
Eli Friedmand6a3e672009-12-04 03:54:56 +0000598 return FinishGenerateVtable(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
599 MorallyVirtual, Offset, ForVirtualBase,
600 CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000601 }
602
603 void GenerateVtableForVBases(const CXXRecordDecl *RD,
604 int64_t Offset = 0,
Mike Stump11dea942009-10-15 02:04:03 +0000605 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000606 bool alloc = false;
607 if (Path == 0) {
608 alloc = true;
Mike Stump11dea942009-10-15 02:04:03 +0000609 Path = new Path_t;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000610 }
611 // FIXME: We also need to override using all paths to a virtual base,
612 // right now, we just process the first path
613 Path->push_back(std::make_pair(RD, Offset));
614 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
615 e = RD->bases_end(); i != e; ++i) {
616 const CXXRecordDecl *Base =
617 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
618 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
619 // Mark it so we don't output it twice.
620 IndirectPrimary.insert(Base);
621 StartNewTable();
Mike Stump0ca42792009-10-14 18:14:51 +0000622 VCall.clear();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000623 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9e7e3c62009-11-06 23:27:42 +0000624 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump6a9612f2009-10-31 20:06:59 +0000625 D1(printf("vtable %s virtual base %s\n",
626 Class->getNameAsCString(), Base->getNameAsCString()));
Mike Stump4cde6262009-11-13 02:13:54 +0000627 GenerateVtableForBase(Base, BaseOffset, true, true, CurrentVBaseOffset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000628 Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000629 }
Mike Stump9840c702009-11-12 20:47:57 +0000630 int64_t BaseOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000631 if (i->isVirtual())
632 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9840c702009-11-12 20:47:57 +0000633 else {
634 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
635 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
636 }
637
Mike Stump11dea942009-10-15 02:04:03 +0000638 if (Base->getNumVBases()) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000639 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump11dea942009-10-15 02:04:03 +0000640 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000641 }
642 Path->pop_back();
643 if (alloc)
644 delete Path;
645 }
646};
Anders Carlsson27682a32009-12-03 01:54:02 +0000647} // end anonymous namespace
648
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000649/// TypeConversionRequiresAdjustment - Returns whether conversion from a
650/// derived type to a base type requires adjustment.
651static bool
652TypeConversionRequiresAdjustment(ASTContext &Ctx,
653 const CXXRecordDecl *DerivedDecl,
654 const CXXRecordDecl *BaseDecl) {
655 CXXBasePaths Paths(/*FindAmbiguities=*/false,
656 /*RecordPaths=*/true, /*DetectVirtual=*/true);
657 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
658 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
659 assert(false && "Class must be derived from the passed in base class!");
660 return false;
661 }
662
663 // If we found a virtual base we always want to require adjustment.
664 if (Paths.getDetectedVirtual())
665 return true;
666
667 const CXXBasePath &Path = Paths.front();
668
669 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
670 const CXXBasePathElement &Element = Path[Start];
671
672 // Check the base class offset.
673 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
674
675 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
676 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
677
678 if (Layout.getBaseClassOffset(Base) != 0) {
679 // This requires an adjustment.
680 return true;
681 }
682 }
683
684 return false;
685}
686
687static bool
688TypeConversionRequiresAdjustment(ASTContext &Ctx,
689 QualType DerivedType, QualType BaseType) {
690 // Canonicalize the types.
691 QualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
692 QualType CanBaseType = Ctx.getCanonicalType(BaseType);
693
694 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
695 "Types must have same type class!");
696
697 if (CanDerivedType == CanBaseType) {
698 // No adjustment needed.
699 return false;
700 }
701
702 if (const ReferenceType *RT = dyn_cast<ReferenceType>(CanDerivedType)) {
703 CanDerivedType = RT->getPointeeType();
704 CanBaseType = cast<ReferenceType>(CanBaseType)->getPointeeType();
705 } else if (const PointerType *PT = dyn_cast<PointerType>(CanDerivedType)) {
706 CanDerivedType = PT->getPointeeType();
707 CanBaseType = cast<PointerType>(CanBaseType)->getPointeeType();
708 } else {
709 assert(false && "Unexpected return type!");
710 }
711
712 if (CanDerivedType == CanBaseType) {
713 // No adjustment needed.
714 return false;
715 }
716
717 const CXXRecordDecl *DerivedDecl =
Anders Carlsson1750b4f2009-12-03 03:28:24 +0000718 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000719
720 const CXXRecordDecl *BaseDecl =
721 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
722
723 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
724}
725
Anders Carlsson27682a32009-12-03 01:54:02 +0000726bool VtableBuilder::OverrideMethod(GlobalDecl GD, llvm::Constant *m,
727 bool MorallyVirtual, Index_t OverrideOffset,
728 Index_t Offset, int64_t CurrentVBaseOffset) {
729 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
730
731 const bool isPure = MD->isPure();
732 typedef CXXMethodDecl::method_iterator meth_iter;
733 // FIXME: Should OverrideOffset's be Offset?
734
735 // FIXME: Don't like the nested loops. For very large inheritance
736 // heirarchies we could have a table on the side with the final overridder
737 // and just replace each instance of an overridden method once. Would be
738 // nice to measure the cost/benefit on real code.
739
740 for (meth_iter mi = MD->begin_overridden_methods(),
741 e = MD->end_overridden_methods();
742 mi != e; ++mi) {
743 GlobalDecl OGD;
744
745 const CXXMethodDecl *OMD = *mi;
746 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
747 OGD = GlobalDecl(DD, GD.getDtorType());
748 else
749 OGD = OMD;
750
751 llvm::Constant *om;
752 om = WrapAddrOf(OGD);
753 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
754
755 for (Index_t i = 0, e = submethods.size();
756 i != e; ++i) {
Anders Carlsson27682a32009-12-03 01:54:02 +0000757 if (submethods[i] != om)
758 continue;
Anders Carlssonc0c49932009-12-04 03:41:37 +0000759
Anders Carlssondd454be2009-12-04 03:52:52 +0000760 uint64_t Index = Methods.getIndex(OGD);
761
762 assert(i == Index);
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000763
764 QualType ReturnType =
765 MD->getType()->getAs<FunctionType>()->getResultType();
766 QualType OverriddenReturnType =
767 OMD->getType()->getAs<FunctionType>()->getResultType();
768
769 // Check if we need a return type adjustment.
770 if (TypeConversionRequiresAdjustment(CGM.getContext(), ReturnType,
771 OverriddenReturnType)) {
Anders Carlssona8756702009-12-04 02:22:02 +0000772 CanQualType &BaseReturnType = BaseReturnTypes[i];
Anders Carlssonbc0e3392009-12-03 02:22:59 +0000773
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000774 // Get the canonical return type.
775 CanQualType CanReturnType =
776 CGM.getContext().getCanonicalType(ReturnType);
777
778 // Insert the base return type.
Anders Carlssona8756702009-12-04 02:22:02 +0000779 if (BaseReturnType.isNull())
780 BaseReturnType =
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000781 CGM.getContext().getCanonicalType(OverriddenReturnType);
Anders Carlsson27682a32009-12-03 01:54:02 +0000782 }
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000783
Anders Carlssona7f19112009-12-04 02:08:24 +0000784 Methods.OverrideMethod(OGD, GD);
785
Anders Carlssondd454be2009-12-04 03:52:52 +0000786 submethods[Index] = m;
Anders Carlsson98fdb242009-12-04 02:26:15 +0000787 ThisAdjustments.erase(i);
Anders Carlsson27682a32009-12-03 01:54:02 +0000788 if (MorallyVirtual || VCall.count(OGD)) {
789 Index_t &idx = VCall[OGD];
790 if (idx == 0) {
791 NonVirtualOffset[GD] = -OverrideOffset/8 + CurrentVBaseOffset/8;
792 VCallOffset[GD] = OverrideOffset/8;
793 idx = VCalls.size()+1;
794 VCalls.push_back(0);
795 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
796 MD->getNameAsString().c_str(), (int)-idx-3,
797 (int)VCalls[idx-1], Class->getNameAsCString()));
798 } else {
799 NonVirtualOffset[GD] = NonVirtualOffset[OGD];
800 VCallOffset[GD] = VCallOffset[OGD];
801 VCalls[idx-1] = -VCallOffset[OGD] + OverrideOffset/8;
802 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
803 MD->getNameAsString().c_str(), (int)-idx-3,
804 (int)VCalls[idx-1], Class->getNameAsCString()));
805 }
806 VCall[GD] = idx;
807 int64_t NonVirtualAdjustment = NonVirtualOffset[GD];
808 int64_t VirtualAdjustment =
809 -((idx + extra + 2) * LLVMPointerWidth / 8);
810
811 // Optimize out virtual adjustments of 0.
812 if (VCalls[idx-1] == 0)
813 VirtualAdjustment = 0;
814
815 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
816 VirtualAdjustment);
817
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000818 if (!isPure && !ThisAdjustment.isEmpty())
Anders Carlssondd454be2009-12-04 03:52:52 +0000819 ThisAdjustments[Index] = ThisAdjustment;
Anders Carlsson27682a32009-12-03 01:54:02 +0000820 return true;
821 }
822
823 // FIXME: finish off
824 int64_t NonVirtualAdjustment = VCallOffset[OGD] - OverrideOffset/8;
825
Anders Carlssonbc0e3392009-12-03 02:22:59 +0000826 if (NonVirtualAdjustment) {
Anders Carlsson27682a32009-12-03 01:54:02 +0000827 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
828
Anders Carlssond8ddffc2009-12-03 01:58:20 +0000829 if (!isPure)
Anders Carlssondd454be2009-12-04 03:52:52 +0000830 ThisAdjustments[Index] = ThisAdjustment;
Anders Carlsson27682a32009-12-03 01:54:02 +0000831 }
832 return true;
833 }
834 }
835
836 return false;
Anders Carlsson27f69d02009-11-27 22:21:51 +0000837}
838
Anders Carlssonbf540272009-12-04 02:56:03 +0000839void VtableBuilder::AppendMethodsToVtable() {
Anders Carlsson29202d52009-12-04 03:07:26 +0000840 // Reserve room for our new methods.
841 methods.reserve(methods.size() + Methods.size());
842
Anders Carlssonb73ba392009-12-04 02:43:50 +0000843 for (unsigned i = 0, e = Methods.size(); i != e; ++i) {
844 GlobalDecl GD = Methods[i];
Anders Carlssonea357222009-12-04 02:52:22 +0000845 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
846
847 // Get the 'this' pointer adjustment.
Anders Carlssonb73ba392009-12-04 02:43:50 +0000848 ThunkAdjustment ThisAdjustment = ThisAdjustments.lookup(i);
Anders Carlssonea357222009-12-04 02:52:22 +0000849
850 // Construct the return type adjustment.
851 ThunkAdjustment ReturnAdjustment;
852
853 QualType BaseReturnType = BaseReturnTypes.lookup(i);
854 if (!BaseReturnType.isNull() && !MD->isPure()) {
855 QualType DerivedType =
856 MD->getType()->getAs<FunctionType>()->getResultType();
857
858 int64_t NonVirtualAdjustment =
859 getNVOffset(BaseReturnType, DerivedType) / 8;
860
861 int64_t VirtualAdjustment =
862 getVbaseOffset(BaseReturnType, DerivedType);
863
864 ReturnAdjustment = ThunkAdjustment(NonVirtualAdjustment,
865 VirtualAdjustment);
866 }
867
Anders Carlsson2fce2162009-12-04 03:06:03 +0000868 llvm::Constant *Method = 0;
Anders Carlssonea357222009-12-04 02:52:22 +0000869 if (!ReturnAdjustment.isEmpty()) {
870 // Build a covariant thunk.
871 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Anders Carlsson2fce2162009-12-04 03:06:03 +0000872 Method = CGM.BuildCovariantThunk(MD, Extern, Adjustment);
Anders Carlssonea357222009-12-04 02:52:22 +0000873 } else if (!ThisAdjustment.isEmpty()) {
874 // Build a "regular" thunk.
Anders Carlsson2fce2162009-12-04 03:06:03 +0000875 Method = CGM.BuildThunk(GD, Extern, ThisAdjustment);
Anders Carlssonbf540272009-12-04 02:56:03 +0000876 } else if (MD->isPure()) {
877 // We have a pure virtual method.
Anders Carlsson2fce2162009-12-04 03:06:03 +0000878 Method = getPureVirtualFn();
879 } else {
880 // We have a good old regular method.
881 Method = WrapAddrOf(GD);
Anders Carlssonea357222009-12-04 02:52:22 +0000882 }
Anders Carlsson2fce2162009-12-04 03:06:03 +0000883
884 // Add the method to the vtable.
885 methods.push_back(Method);
Anders Carlssonb73ba392009-12-04 02:43:50 +0000886 }
887
Anders Carlsson2fce2162009-12-04 03:06:03 +0000888
Anders Carlssonb73ba392009-12-04 02:43:50 +0000889 ThisAdjustments.clear();
Anders Carlssonea357222009-12-04 02:52:22 +0000890 BaseReturnTypes.clear();
Anders Carlssonb73ba392009-12-04 02:43:50 +0000891
Anders Carlssonadfa2672009-12-04 02:39:04 +0000892 Methods.clear();
893 submethods.clear();
894}
895
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000896void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
897
898 // Itanium C++ ABI 2.5.2:
899 // The order of the virtual function pointers in a virtual table is the
900 // order of declaration of the corresponding member functions in the class.
901 //
902 // There is an entry for any virtual function declared in a class,
903 // whether it is a new function or overrides a base class function,
904 // unless it overrides a function from the primary base, and conversion
905 // between their return types does not require an adjustment.
906
907 int64_t CurrentIndex = 0;
908
909 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
910 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
911
912 if (PrimaryBase) {
Anders Carlsson0121fbd2009-11-30 19:43:26 +0000913 assert(PrimaryBase->isDefinition() &&
914 "Should have the definition decl of the primary base!");
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000915
916 // Since the record decl shares its vtable pointer with the primary base
917 // we need to start counting at the end of the primary base's vtable.
918 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
919 }
920
921 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
922
923 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
924 e = RD->method_end(); i != e; ++i) {
925 const CXXMethodDecl *MD = *i;
926
927 // We only want virtual methods.
928 if (!MD->isVirtual())
929 continue;
930
931 bool ShouldAddEntryForMethod = true;
932
933 // Check if this method overrides a method in the primary base.
934 for (CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
935 e = MD->end_overridden_methods(); i != e; ++i) {
936 const CXXMethodDecl *OverriddenMD = *i;
937 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
938 assert(OverriddenMD->isCanonicalDecl() &&
939 "Should have the canonical decl of the overridden RD!");
940
941 if (OverriddenRD == PrimaryBase) {
942 // Check if converting from the return type of the method to the
943 // return type of the overridden method requires conversion.
944 QualType ReturnType =
945 MD->getType()->getAs<FunctionType>()->getResultType();
946 QualType OverriddenReturnType =
947 OverriddenMD->getType()->getAs<FunctionType>()->getResultType();
948
949 if (!TypeConversionRequiresAdjustment(CGM.getContext(),
950 ReturnType, OverriddenReturnType)) {
951 // This index is shared between the index in the vtable of the primary
952 // base class.
953 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
954 const CXXDestructorDecl *OverriddenDD =
955 cast<CXXDestructorDecl>(OverriddenMD);
956
957 // Add both the complete and deleting entries.
958 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
959 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
960 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
961 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
962 } else {
963 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
964 }
965
966 // We don't need to add an entry for this method.
967 ShouldAddEntryForMethod = false;
968 break;
969 }
970 }
971 }
972
973 if (!ShouldAddEntryForMethod)
974 continue;
975
976 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
977 if (MD->isImplicit()) {
978 assert(!ImplicitVirtualDtor &&
979 "Did already see an implicit virtual dtor!");
980 ImplicitVirtualDtor = DD;
981 continue;
982 }
983
984 // Add the complete dtor.
985 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
986
987 // Add the deleting dtor.
988 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
989 } else {
990 // Add the entry.
991 MethodVtableIndices[MD] = CurrentIndex++;
992 }
993 }
994
995 if (ImplicitVirtualDtor) {
996 // Itanium C++ ABI 2.5.2:
997 // If a class has an implicitly-defined virtual destructor,
998 // its entries come after the declared virtual function pointers.
999
1000 // Add the complete dtor.
1001 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
1002 CurrentIndex++;
1003
1004 // Add the deleting dtor.
1005 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
1006 CurrentIndex++;
1007 }
1008
1009 NumVirtualFunctionPointers[RD] = CurrentIndex;
1010}
1011
1012uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
1013 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1014 NumVirtualFunctionPointers.find(RD);
1015 if (I != NumVirtualFunctionPointers.end())
1016 return I->second;
1017
1018 ComputeMethodVtableIndices(RD);
1019
1020 I = NumVirtualFunctionPointers.find(RD);
1021 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
1022 return I->second;
1023}
1024
1025uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssona0fdd912009-11-13 17:08:56 +00001026 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001027 if (I != MethodVtableIndices.end())
1028 return I->second;
1029
Anders Carlssona0fdd912009-11-13 17:08:56 +00001030 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001031
1032 ComputeMethodVtableIndices(RD);
1033
Anders Carlssona0fdd912009-11-13 17:08:56 +00001034 I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001035 assert(I != MethodVtableIndices.end() && "Did not find index!");
1036 return I->second;
1037}
1038
1039int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
1040 const CXXRecordDecl *VBase) {
1041 ClassPairTy ClassPair(RD, VBase);
1042
1043 VirtualBaseClassIndiciesTy::iterator I =
1044 VirtualBaseClassIndicies.find(ClassPair);
1045 if (I != VirtualBaseClassIndicies.end())
1046 return I->second;
1047
1048 std::vector<llvm::Constant *> methods;
1049 // FIXME: This seems expensive. Can we do a partial job to get
1050 // just this data.
Mike Stump4cde6262009-11-13 02:13:54 +00001051 VtableBuilder b(methods, RD, RD, 0, CGM);
Mike Stump6a9612f2009-10-31 20:06:59 +00001052 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00001053 b.GenerateVtableForBase(RD);
1054 b.GenerateVtableForVBases(RD);
1055
1056 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1057 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
1058 // Insert all types.
1059 ClassPairTy ClassPair(RD, I->first);
1060
1061 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
1062 }
1063
1064 I = VirtualBaseClassIndicies.find(ClassPair);
1065 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
1066
1067 return I->second;
1068}
1069
Mike Stump9840c702009-11-12 20:47:57 +00001070llvm::Constant *CodeGenModule::GenerateVtable(const CXXRecordDecl *LayoutClass,
1071 const CXXRecordDecl *RD,
Mike Stump8cfcb522009-11-11 20:26:26 +00001072 uint64_t Offset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001073 llvm::SmallString<256> OutName;
Mike Stump9840c702009-11-12 20:47:57 +00001074 if (LayoutClass != RD)
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001075 getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset/8, RD, OutName);
Mike Stump8cfcb522009-11-11 20:26:26 +00001076 else
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001077 getMangleContext().mangleCXXVtable(RD, OutName);
1078 llvm::StringRef Name = OutName.str();
Benjamin Kramer7a9474e2009-10-11 22:57:54 +00001079
Anders Carlssondbd920c2009-10-11 22:13:54 +00001080 std::vector<llvm::Constant *> methods;
1081 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1082 int64_t AddressPoint;
1083
Mike Stump85615df2009-11-19 04:04:36 +00001084 llvm::GlobalVariable *GV = getModule().getGlobalVariable(Name);
Mike Stump23a35422009-11-19 20:52:19 +00001085 if (GV && AddressPoints[LayoutClass] && !GV->isDeclaration()) {
Mike Stump85615df2009-11-19 04:04:36 +00001086 AddressPoint=(*(*(AddressPoints[LayoutClass]))[RD])[std::make_pair(RD,
1087 Offset)];
Mike Stump23a35422009-11-19 20:52:19 +00001088 // FIXME: We can never have 0 address point. Do this for now so gepping
1089 // retains the same structure. Later, we'll just assert.
1090 if (AddressPoint == 0)
1091 AddressPoint = 1;
1092 } else {
Mike Stump85615df2009-11-19 04:04:36 +00001093 VtableBuilder b(methods, RD, LayoutClass, Offset, *this);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001094
Mike Stump85615df2009-11-19 04:04:36 +00001095 D1(printf("vtable %s\n", RD->getNameAsCString()));
1096 // First comes the vtables for all the non-virtual bases...
1097 AddressPoint = b.GenerateVtableForBase(RD, Offset);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001098
Mike Stump85615df2009-11-19 04:04:36 +00001099 // then the vtables for all the virtual bases.
1100 b.GenerateVtableForVBases(RD, Offset);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001101
Mike Stump85615df2009-11-19 04:04:36 +00001102 bool CreateDefinition = true;
1103 if (LayoutClass != RD)
1104 CreateDefinition = true;
1105 else {
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001106 const ASTRecordLayout &Layout =
1107 getContext().getASTRecordLayout(LayoutClass);
1108
1109 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stump85615df2009-11-19 04:04:36 +00001110 if (!KeyFunction->getBody()) {
1111 // If there is a KeyFunction, and it isn't defined, just build a
1112 // reference to the vtable.
1113 CreateDefinition = false;
1114 }
1115 }
1116 }
1117
1118 llvm::Constant *C = 0;
1119 llvm::Type *type = Ptr8Ty;
1120 llvm::GlobalVariable::LinkageTypes linktype
1121 = llvm::GlobalValue::ExternalLinkage;
1122 if (CreateDefinition) {
1123 llvm::ArrayType *ntype = llvm::ArrayType::get(Ptr8Ty, methods.size());
1124 C = llvm::ConstantArray::get(ntype, methods);
1125 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
1126 if (LayoutClass->isInAnonymousNamespace())
1127 linktype = llvm::GlobalValue::InternalLinkage;
1128 type = ntype;
1129 }
1130 llvm::GlobalVariable *OGV = GV;
1131 GV = new llvm::GlobalVariable(getModule(), type, true, linktype, C, Name);
1132 if (OGV) {
1133 GV->takeName(OGV);
1134 llvm::Constant *NewPtr = llvm::ConstantExpr::getBitCast(GV,
1135 OGV->getType());
1136 OGV->replaceAllUsesWith(NewPtr);
1137 OGV->eraseFromParent();
1138 }
1139 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1140 if (Hidden)
1141 GV->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1142 }
Mike Stumpe56ceca2009-11-18 04:00:48 +00001143 llvm::Constant *vtable = llvm::ConstantExpr::getBitCast(GV, Ptr8Ty);
Mike Stump380dd752009-11-10 07:44:33 +00001144 llvm::Constant *AddressPointC;
1145 uint32_t LLVMPointerWidth = getContext().Target.getPointerWidth(0);
1146 AddressPointC = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1147 AddressPoint*LLVMPointerWidth/8);
Mike Stump9840c702009-11-12 20:47:57 +00001148 vtable = llvm::ConstantExpr::getInBoundsGetElementPtr(vtable, &AddressPointC,
1149 1);
Mike Stump380dd752009-11-10 07:44:33 +00001150
Mike Stump23a35422009-11-19 20:52:19 +00001151 assert(vtable->getType() == Ptr8Ty);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001152 return vtable;
1153}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001154
Mike Stump92f2fe22009-12-02 19:07:44 +00001155namespace {
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001156class VTTBuilder {
1157 /// Inits - The list of values built for the VTT.
1158 std::vector<llvm::Constant *> &Inits;
1159 /// Class - The most derived class that this vtable is being built for.
1160 const CXXRecordDecl *Class;
1161 CodeGenModule &CGM; // Per-module state.
Mike Stump971977f2009-11-11 00:35:07 +00001162 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpaee8de32009-11-11 03:08:24 +00001163 /// BLayout - Layout for the most derived class that this vtable is being
1164 /// built for.
1165 const ASTRecordLayout &BLayout;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001166 CodeGenModule::AddrMap_t &AddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +00001167 // vtbl - A pointer to the vtable for Class.
1168 llvm::Constant *ClassVtbl;
1169 llvm::LLVMContext &VMContext;
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001170
Mike Stump28f7ce12009-11-12 22:56:32 +00001171 /// BuildVtablePtr - Build up a referene to the given secondary vtable
Mike Stumpacfd1e52009-11-13 01:54:23 +00001172 llvm::Constant *BuildVtablePtr(llvm::Constant *vtbl,
1173 const CXXRecordDecl *VtblClass,
1174 const CXXRecordDecl *RD,
Mike Stump28f7ce12009-11-12 22:56:32 +00001175 uint64_t Offset) {
1176 int64_t AddressPoint;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001177 AddressPoint = (*AddressPoints[VtblClass])[std::make_pair(RD, Offset)];
Mike Stump80ac2352009-11-12 23:36:21 +00001178 // FIXME: We can never have 0 address point. Do this for now so gepping
Mike Stump23a35422009-11-19 20:52:19 +00001179 // retains the same structure. Later we'll just assert.
Mike Stump80ac2352009-11-12 23:36:21 +00001180 if (AddressPoint == 0)
1181 AddressPoint = 1;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001182 D1(printf("XXX address point for %s in %s layout %s at offset %d was %d\n",
1183 RD->getNameAsCString(), VtblClass->getNameAsCString(),
1184 Class->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump28f7ce12009-11-12 22:56:32 +00001185 uint32_t LLVMPointerWidth = CGM.getContext().Target.getPointerWidth(0);
1186 llvm::Constant *init;
1187 init = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1188 AddressPoint*LLVMPointerWidth/8);
1189 init = llvm::ConstantExpr::getInBoundsGetElementPtr(vtbl, &init, 1);
1190 return init;
1191 }
1192
Mike Stump9840c702009-11-12 20:47:57 +00001193 /// Secondary - Add the secondary vtable pointers to Inits. Offset is the
1194 /// current offset in bits to the object we're working on.
Mike Stump28f7ce12009-11-12 22:56:32 +00001195 void Secondary(const CXXRecordDecl *RD, llvm::Constant *vtbl,
Mike Stumpacfd1e52009-11-13 01:54:23 +00001196 const CXXRecordDecl *VtblClass, uint64_t Offset=0,
1197 bool MorallyVirtual=false) {
Mike Stump971977f2009-11-11 00:35:07 +00001198 if (RD->getNumVBases() == 0 && ! MorallyVirtual)
1199 return;
1200
1201 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1202 e = RD->bases_end(); i != e; ++i) {
1203 const CXXRecordDecl *Base =
1204 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1205 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1206 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1207 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1208 bool NonVirtualPrimaryBase;
1209 NonVirtualPrimaryBase = !PrimaryBaseWasVirtual && Base == PrimaryBase;
1210 bool BaseMorallyVirtual = MorallyVirtual | i->isVirtual();
Mike Stumpaee8de32009-11-11 03:08:24 +00001211 uint64_t BaseOffset;
1212 if (!i->isVirtual()) {
1213 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1214 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1215 } else
1216 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump80ac2352009-11-12 23:36:21 +00001217 llvm::Constant *subvtbl = vtbl;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001218 const CXXRecordDecl *subVtblClass = VtblClass;
Mike Stump971977f2009-11-11 00:35:07 +00001219 if ((Base->getNumVBases() || BaseMorallyVirtual)
1220 && !NonVirtualPrimaryBase) {
1221 // FIXME: Slightly too many of these for __ZTT8test8_B2
Mike Stump28f7ce12009-11-12 22:56:32 +00001222 llvm::Constant *init;
Mike Stump80ac2352009-11-12 23:36:21 +00001223 if (BaseMorallyVirtual)
Mike Stumpacfd1e52009-11-13 01:54:23 +00001224 init = BuildVtablePtr(vtbl, VtblClass, RD, Offset);
Mike Stump80ac2352009-11-12 23:36:21 +00001225 else {
Mike Stump28f7ce12009-11-12 22:56:32 +00001226 init = CGM.getVtableInfo().getCtorVtable(Class, Base, BaseOffset);
Mike Stump80ac2352009-11-12 23:36:21 +00001227 subvtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stumpacfd1e52009-11-13 01:54:23 +00001228 subVtblClass = Base;
Mike Stump80ac2352009-11-12 23:36:21 +00001229 }
Mike Stump28f7ce12009-11-12 22:56:32 +00001230 Inits.push_back(init);
Mike Stump971977f2009-11-11 00:35:07 +00001231 }
Mike Stumpacfd1e52009-11-13 01:54:23 +00001232 Secondary(Base, subvtbl, subVtblClass, BaseOffset, BaseMorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001233 }
1234 }
1235
Mike Stump9840c702009-11-12 20:47:57 +00001236 /// BuiltVTT - Add the VTT to Inits. Offset is the offset in bits to the
1237 /// currnet object we're working on.
1238 void BuildVTT(const CXXRecordDecl *RD, uint64_t Offset, bool MorallyVirtual) {
Mike Stump971977f2009-11-11 00:35:07 +00001239 if (RD->getNumVBases() == 0 && !MorallyVirtual)
1240 return;
1241
Mike Stump9840c702009-11-12 20:47:57 +00001242 llvm::Constant *init;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001243 const CXXRecordDecl *VtblClass;
1244
Mike Stump971977f2009-11-11 00:35:07 +00001245 // First comes the primary virtual table pointer...
Mike Stumpacfd1e52009-11-13 01:54:23 +00001246 if (MorallyVirtual) {
1247 init = BuildVtablePtr(ClassVtbl, Class, RD, Offset);
1248 VtblClass = Class;
1249 } else {
Mike Stump9840c702009-11-12 20:47:57 +00001250 init = CGM.getVtableInfo().getCtorVtable(Class, RD, Offset);
Mike Stumpacfd1e52009-11-13 01:54:23 +00001251 VtblClass = RD;
1252 }
Mike Stump28f7ce12009-11-12 22:56:32 +00001253 llvm::Constant *vtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump9840c702009-11-12 20:47:57 +00001254 Inits.push_back(init);
Mike Stump971977f2009-11-11 00:35:07 +00001255
1256 // then the secondary VTTs....
Mike Stump9840c702009-11-12 20:47:57 +00001257 SecondaryVTTs(RD, Offset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001258
1259 // and last the secondary vtable pointers.
Mike Stumpacfd1e52009-11-13 01:54:23 +00001260 Secondary(RD, vtbl, VtblClass, Offset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001261 }
1262
1263 /// SecondaryVTTs - Add the secondary VTTs to Inits. The secondary VTTs are
1264 /// built from each direct non-virtual proper base that requires a VTT in
1265 /// declaration order.
Mike Stump9840c702009-11-12 20:47:57 +00001266 void SecondaryVTTs(const CXXRecordDecl *RD, uint64_t Offset=0,
1267 bool MorallyVirtual=false) {
Mike Stump971977f2009-11-11 00:35:07 +00001268 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1269 e = RD->bases_end(); i != e; ++i) {
1270 const CXXRecordDecl *Base =
1271 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1272 if (i->isVirtual())
1273 continue;
Mike Stump9840c702009-11-12 20:47:57 +00001274 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1275 uint64_t BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1276 BuildVTT(Base, BaseOffset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001277 }
1278 }
1279
1280 /// VirtualVTTs - Add the VTT for each proper virtual base in inheritance
1281 /// graph preorder.
1282 void VirtualVTTs(const CXXRecordDecl *RD) {
1283 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1284 e = RD->bases_end(); i != e; ++i) {
1285 const CXXRecordDecl *Base =
1286 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1287 if (i->isVirtual() && !SeenVBase.count(Base)) {
1288 SeenVBase.insert(Base);
Mike Stump9840c702009-11-12 20:47:57 +00001289 uint64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
1290 BuildVTT(Base, BaseOffset, true);
Mike Stump971977f2009-11-11 00:35:07 +00001291 }
1292 VirtualVTTs(Base);
1293 }
1294 }
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001295public:
1296 VTTBuilder(std::vector<llvm::Constant *> &inits, const CXXRecordDecl *c,
Mike Stumpaee8de32009-11-11 03:08:24 +00001297 CodeGenModule &cgm)
1298 : Inits(inits), Class(c), CGM(cgm),
Mike Stump9840c702009-11-12 20:47:57 +00001299 BLayout(cgm.getContext().getASTRecordLayout(c)),
Mike Stumpacfd1e52009-11-13 01:54:23 +00001300 AddressPoints(*cgm.AddressPoints[c]),
Mike Stump9840c702009-11-12 20:47:57 +00001301 VMContext(cgm.getModule().getContext()) {
Mike Stump380dd752009-11-10 07:44:33 +00001302
Mike Stump971977f2009-11-11 00:35:07 +00001303 // First comes the primary virtual table pointer for the complete class...
Mike Stump9840c702009-11-12 20:47:57 +00001304 ClassVtbl = CGM.getVtableInfo().getVtable(Class);
1305 Inits.push_back(ClassVtbl);
1306 ClassVtbl = dyn_cast<llvm::Constant>(ClassVtbl->getOperand(0));
1307
Mike Stump971977f2009-11-11 00:35:07 +00001308 // then the secondary VTTs...
1309 SecondaryVTTs(Class);
1310
1311 // then the secondary vtable pointers...
Mike Stumpacfd1e52009-11-13 01:54:23 +00001312 Secondary(Class, ClassVtbl, Class);
Mike Stump971977f2009-11-11 00:35:07 +00001313
1314 // and last, the virtual VTTs.
1315 VirtualVTTs(Class);
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001316 }
1317};
Mike Stump92f2fe22009-12-02 19:07:44 +00001318}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001319
Mike Stump380dd752009-11-10 07:44:33 +00001320llvm::Constant *CodeGenModule::GenerateVTT(const CXXRecordDecl *RD) {
Mike Stumpf1c03332009-11-10 19:13:04 +00001321 // Only classes that have virtual bases need a VTT.
1322 if (RD->getNumVBases() == 0)
1323 return 0;
1324
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001325 llvm::SmallString<256> OutName;
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001326 getMangleContext().mangleCXXVTT(RD, OutName);
1327 llvm::StringRef Name = OutName.str();
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001328
1329 llvm::GlobalVariable::LinkageTypes linktype;
1330 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
Mike Stump85615df2009-11-19 04:04:36 +00001331 if (RD->isInAnonymousNamespace())
1332 linktype = llvm::GlobalValue::InternalLinkage;
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001333 std::vector<llvm::Constant *> inits;
1334 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1335
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001336 D1(printf("vtt %s\n", RD->getNameAsCString()));
1337
Mike Stump971977f2009-11-11 00:35:07 +00001338 VTTBuilder b(inits, RD, *this);
1339
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001340 llvm::Constant *C;
1341 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, inits.size());
1342 C = llvm::ConstantArray::get(type, inits);
Mike Stumpe56ceca2009-11-18 04:00:48 +00001343 llvm::GlobalVariable *vtt = new llvm::GlobalVariable(getModule(), type, true,
Mike Stump85615df2009-11-19 04:04:36 +00001344 linktype, C, Name);
Mike Stumpe56ceca2009-11-18 04:00:48 +00001345 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1346 if (Hidden)
1347 vtt->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1348 return llvm::ConstantExpr::getBitCast(vtt, Ptr8Ty);
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001349}
Mike Stump380dd752009-11-10 07:44:33 +00001350
Mike Stump58588942009-11-19 01:08:19 +00001351void CGVtableInfo::GenerateClassData(const CXXRecordDecl *RD) {
1352 Vtables[RD] = CGM.GenerateVtable(RD, RD);
Mike Stumpde050572009-12-02 18:57:08 +00001353 CGM.GenerateRTTI(RD);
Mike Stump58588942009-11-19 01:08:19 +00001354 CGM.GenerateVTT(RD);
1355}
1356
Mike Stump8cfcb522009-11-11 20:26:26 +00001357llvm::Constant *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Mike Stump380dd752009-11-10 07:44:33 +00001358 llvm::Constant *&vtbl = Vtables[RD];
1359 if (vtbl)
1360 return vtbl;
Mike Stump9840c702009-11-12 20:47:57 +00001361 vtbl = CGM.GenerateVtable(RD, RD);
Mike Stump85615df2009-11-19 04:04:36 +00001362
1363 bool CreateDefinition = true;
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001364
1365 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1366 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stump85615df2009-11-19 04:04:36 +00001367 if (!KeyFunction->getBody()) {
1368 // If there is a KeyFunction, and it isn't defined, just build a
1369 // reference to the vtable.
1370 CreateDefinition = false;
1371 }
1372 }
1373
1374 if (CreateDefinition) {
Mike Stumpde050572009-12-02 18:57:08 +00001375 CGM.GenerateRTTI(RD);
Mike Stump85615df2009-11-19 04:04:36 +00001376 CGM.GenerateVTT(RD);
1377 }
Mike Stump380dd752009-11-10 07:44:33 +00001378 return vtbl;
1379}
Mike Stump8cfcb522009-11-11 20:26:26 +00001380
Mike Stump9840c702009-11-12 20:47:57 +00001381llvm::Constant *CGVtableInfo::getCtorVtable(const CXXRecordDecl *LayoutClass,
1382 const CXXRecordDecl *RD,
Mike Stump8cfcb522009-11-11 20:26:26 +00001383 uint64_t Offset) {
Mike Stump9840c702009-11-12 20:47:57 +00001384 return CGM.GenerateVtable(LayoutClass, RD, Offset);
Mike Stump8cfcb522009-11-11 20:26:26 +00001385}
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001386
1387void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
1388 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1389 const CXXRecordDecl *RD = MD->getParent();
1390
1391 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1392
1393 // Get the key function.
1394 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
1395
1396 if (!KeyFunction) {
1397 // If there's no key function, we don't want to emit the vtable here.
1398 return;
1399 }
1400
1401 // Check if we have the key function.
1402 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
1403 return;
1404
1405 // If the key function is a destructor, we only want to emit the vtable once,
1406 // so do it for the complete destructor.
1407 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Complete)
1408 return;
1409
1410 // Emit the data.
1411 GenerateClassData(RD);
1412}
1413