blob: 2ff3e70ea80935118330665fc8527cc0dc401087 [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:
Anders Carlsson15318f42009-12-04 16:19:30 +000030
31 // Vtable - The components of the vtable being built.
Anders Carlssona22fd852009-12-04 16:24:46 +000032 typedef llvm::SmallVector<llvm::Constant *, 64> VtableVectorTy;
33 VtableVectorTy Vtable;
Eli Friedman152b5b12009-12-05 01:05:03 +000034 const bool BuildVtable;
35
Anders Carlssondbd920c2009-10-11 22:13:54 +000036 llvm::Type *Ptr8Ty;
Anders Carlssonac3f7bd2009-12-04 18:36:22 +000037
38 /// MostDerivedClass - The most derived class that this vtable is being
39 /// built for.
40 const CXXRecordDecl *MostDerivedClass;
41
Mike Stumpacfd1e52009-11-13 01:54:23 +000042 /// LayoutClass - The most derived class used for virtual base layout
43 /// information.
44 const CXXRecordDecl *LayoutClass;
Mike Stump4cde6262009-11-13 02:13:54 +000045 /// LayoutOffset - The offset for Class in LayoutClass.
46 uint64_t LayoutOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +000047 /// BLayout - Layout for the most derived class that this vtable is being
48 /// built for.
49 const ASTRecordLayout &BLayout;
50 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
51 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
52 llvm::Constant *rtti;
53 llvm::LLVMContext &VMContext;
54 CodeGenModule &CGM; // Per-module state.
Anders Carlsson0e881162009-12-04 03:46:21 +000055
Anders Carlssona0fdd912009-11-13 17:08:56 +000056 llvm::DenseMap<GlobalDecl, Index_t> VCall;
57 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stump9e7e3c62009-11-06 23:27:42 +000058 // This is the offset to the nearest virtual base
Anders Carlssona0fdd912009-11-13 17:08:56 +000059 llvm::DenseMap<GlobalDecl, Index_t> NonVirtualOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +000060 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stump94aff932009-10-27 23:46:47 +000061
Anders Carlsson6d4ccb72009-11-26 19:54:33 +000062 /// PureVirtualFunction - Points to __cxa_pure_virtual.
63 llvm::Constant *PureVirtualFn;
64
Anders Carlssonc7ab1a82009-12-04 02:01:07 +000065 /// VtableMethods - A data structure for keeping track of methods in a vtable.
66 /// Can add methods, override methods and iterate in vtable order.
67 class VtableMethods {
68 // MethodToIndexMap - Maps from a global decl to the index it has in the
69 // Methods vector.
70 llvm::DenseMap<GlobalDecl, uint64_t> MethodToIndexMap;
71
72 /// Methods - The methods, in vtable order.
73 typedef llvm::SmallVector<GlobalDecl, 16> MethodsVectorTy;
74 MethodsVectorTy Methods;
75
76 public:
77 /// AddMethod - Add a method to the vtable methods.
78 void AddMethod(GlobalDecl GD) {
79 assert(!MethodToIndexMap.count(GD) &&
80 "Method has already been added!");
81
82 MethodToIndexMap[GD] = Methods.size();
83 Methods.push_back(GD);
84 }
85
86 /// OverrideMethod - Replace a method with another.
87 void OverrideMethod(GlobalDecl OverriddenGD, GlobalDecl GD) {
88 llvm::DenseMap<GlobalDecl, uint64_t>::iterator i
89 = MethodToIndexMap.find(OverriddenGD);
90 assert(i != MethodToIndexMap.end() && "Did not find entry!");
91
92 // Get the index of the old decl.
93 uint64_t Index = i->second;
94
95 // Replace the old decl with the new decl.
96 Methods[Index] = GD;
97
Anders Carlssonc7ab1a82009-12-04 02:01:07 +000098 // And add the new.
99 MethodToIndexMap[GD] = Index;
100 }
101
Anders Carlsson77c23e52009-12-04 15:49:02 +0000102 /// getIndex - Gives the index of a passed in GlobalDecl. Returns false if
103 /// the index couldn't be found.
Benjamin Kramercce9fde2009-12-04 22:45:27 +0000104 bool getIndex(GlobalDecl GD, uint64_t &Index) const {
Anders Carlsson77c23e52009-12-04 15:49:02 +0000105 llvm::DenseMap<GlobalDecl, uint64_t>::const_iterator i
106 = MethodToIndexMap.find(GD);
Eli Friedman47145832009-12-04 08:34:14 +0000107
Anders Carlsson77c23e52009-12-04 15:49:02 +0000108 if (i == MethodToIndexMap.end())
109 return false;
Anders Carlssonc0c49932009-12-04 03:41:37 +0000110
Anders Carlsson77c23e52009-12-04 15:49:02 +0000111 Index = i->second;
112 return true;
Anders Carlssonc0c49932009-12-04 03:41:37 +0000113 }
114
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000115 MethodsVectorTy::size_type size() const {
116 return Methods.size();
117 }
118
119 void clear() {
120 MethodToIndexMap.clear();
121 Methods.clear();
122 }
123
Anders Carlssonc0c49932009-12-04 03:41:37 +0000124 GlobalDecl operator[](uint64_t Index) const {
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000125 return Methods[Index];
126 }
127 };
128
129 /// Methods - The vtable methods we're currently building.
130 VtableMethods Methods;
131
Anders Carlsson98fdb242009-12-04 02:26:15 +0000132 /// ThisAdjustments - For a given index in the vtable, contains the 'this'
133 /// pointer adjustment needed for a method.
134 typedef llvm::DenseMap<uint64_t, ThunkAdjustment> ThisAdjustmentsMapTy;
135 ThisAdjustmentsMapTy ThisAdjustments;
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000136
Anders Carlssona8756702009-12-04 02:22:02 +0000137 /// BaseReturnTypes - Contains the base return types of methods who have been
138 /// overridden with methods whose return types require adjustment. Used for
139 /// generating covariant thunk information.
140 typedef llvm::DenseMap<uint64_t, CanQualType> BaseReturnTypesMapTy;
141 BaseReturnTypesMapTy BaseReturnTypes;
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000142
Anders Carlssondbd920c2009-10-11 22:13:54 +0000143 std::vector<Index_t> VCalls;
Mike Stump9840c702009-11-12 20:47:57 +0000144
145 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stump23a35422009-11-19 20:52:19 +0000146 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
147 // vtable for use in computing the initializers for the VTT.
148 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +0000149
Anders Carlssondbd920c2009-10-11 22:13:54 +0000150 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000151 const bool Extern;
152 const uint32_t LLVMPointerWidth;
153 Index_t extra;
Mike Stump11dea942009-10-15 02:04:03 +0000154 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stump23a35422009-11-19 20:52:19 +0000155 static llvm::DenseMap<CtorVtable_t, int64_t>&
156 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
157 const CXXRecordDecl *c) {
158 CodeGenModule::AddrMap_t *&oref = cgm.AddressPoints[l];
159 if (oref == 0)
160 oref = new CodeGenModule::AddrMap_t;
161
162 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
163 if (ref == 0)
164 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
165 return *ref;
166 }
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000167
168 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
169 llvm::Constant* getPureVirtualFn() {
170 if (!PureVirtualFn) {
171 const llvm::FunctionType *Ty =
172 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
173 /*isVarArg=*/false);
174 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
175 }
176
177 return PureVirtualFn;
178 }
179
Anders Carlssondbd920c2009-10-11 22:13:54 +0000180public:
Anders Carlssonac3f7bd2009-12-04 18:36:22 +0000181 VtableBuilder(const CXXRecordDecl *MostDerivedClass,
Eli Friedman152b5b12009-12-05 01:05:03 +0000182 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm,
183 bool build)
184 : BuildVtable(build), MostDerivedClass(MostDerivedClass), LayoutClass(l),
185 LayoutOffset(lo), BLayout(cgm.getContext().getASTRecordLayout(l)),
186 rtti(0), VMContext(cgm.getModule().getContext()),CGM(cgm),
187 PureVirtualFn(0),
Anders Carlssonac3f7bd2009-12-04 18:36:22 +0000188 subAddressPoints(AllocAddressPoint(cgm, l, MostDerivedClass)),
Mike Stump6be2b172009-11-19 00:49:05 +0000189 Extern(!l->isInAnonymousNamespace()),
Eli Friedman152b5b12009-12-05 01:05:03 +0000190 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000191 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Eli Friedman152b5b12009-12-05 01:05:03 +0000192 if (BuildVtable)
193 rtti = cgm.GenerateRTTIRef(MostDerivedClass);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000194 }
195
Anders Carlsson15318f42009-12-04 16:19:30 +0000196 // getVtable - Returns a reference to the vtable components.
Anders Carlssona22fd852009-12-04 16:24:46 +0000197 const VtableVectorTy &getVtable() const {
Anders Carlsson15318f42009-12-04 16:19:30 +0000198 return Vtable;
199 }
200
Anders Carlssondbd920c2009-10-11 22:13:54 +0000201 llvm::DenseMap<const CXXRecordDecl *, Index_t> &getVBIndex()
202 { return VBIndex; }
203
204 llvm::Constant *wrap(Index_t i) {
205 llvm::Constant *m;
206 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
207 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
208 }
209
210 llvm::Constant *wrap(llvm::Constant *m) {
211 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
212 }
213
Mike Stump79336282009-12-02 19:50:41 +0000214#define D1(x)
215//#define D1(X) do { if (getenv("DEBUG")) { X; } } while (0)
Mike Stump6a9612f2009-10-31 20:06:59 +0000216
217 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stumpab28c132009-10-13 22:54:56 +0000218 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000219 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
220 e = RD->bases_end(); i != e; ++i) {
221 const CXXRecordDecl *Base =
222 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpab28c132009-10-13 22:54:56 +0000223 Index_t next_vbindex = current_vbindex;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000224 if (i->isVirtual() && !SeenVBase.count(Base)) {
225 SeenVBase.insert(Base);
Mike Stumpab28c132009-10-13 22:54:56 +0000226 if (updateVBIndex) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000227 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stumpab28c132009-10-13 22:54:56 +0000228 - 3*LLVMPointerWidth/8);
229 VBIndex[Base] = next_vbindex;
230 }
Mike Stump6a9612f2009-10-31 20:06:59 +0000231 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
232 VCalls.push_back((0?700:0) + BaseOffset);
233 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
234 Base->getNameAsCString(),
235 (int)-VCalls.size()-3, (int)BaseOffset,
236 Class->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000237 }
Mike Stumpab28c132009-10-13 22:54:56 +0000238 // We also record offsets for non-virtual bases to closest enclosing
239 // virtual base. We do this so that we don't have to search
240 // for the nearst virtual base class when generating thunks.
241 if (updateVBIndex && VBIndex.count(Base) == 0)
242 VBIndex[Base] = next_vbindex;
Mike Stump6a9612f2009-10-31 20:06:59 +0000243 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000244 }
245 }
246
247 void StartNewTable() {
248 SeenVBase.clear();
249 }
250
Mike Stump3425b972009-10-15 09:30:16 +0000251 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
252 Index_t Offset = 0) {
253
254 if (B == D)
255 return Offset;
256
257 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
258 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
259 e = D->bases_end(); i != e; ++i) {
260 const CXXRecordDecl *Base =
261 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
262 int64_t BaseOffset = 0;
263 if (!i->isVirtual())
264 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
265 int64_t o = getNVOffset_1(Base, B, BaseOffset);
266 if (o >= 0)
267 return o;
268 }
269
270 return -1;
271 }
272
273 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
274 /// derived class D.
275 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +0000276 qD = qD->getPointeeType();
277 qB = qB->getPointeeType();
Mike Stump3425b972009-10-15 09:30:16 +0000278 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
279 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
280 int64_t o = getNVOffset_1(D, B);
281 if (o >= 0)
282 return o;
283
284 assert(false && "FIXME: non-virtual base not found");
285 return 0;
286 }
287
Anders Carlssondbd920c2009-10-11 22:13:54 +0000288 /// getVbaseOffset - Returns the index into the vtable for the virtual base
289 /// offset for the given (B) virtual base of the derived class D.
290 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +0000291 qD = qD->getPointeeType();
292 qB = qB->getPointeeType();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000293 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
294 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
Anders Carlssonac3f7bd2009-12-04 18:36:22 +0000295 if (D != MostDerivedClass)
Eli Friedman76ed1f72009-11-30 01:19:33 +0000296 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000297 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
298 i = VBIndex.find(B);
299 if (i != VBIndex.end())
300 return i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000301
Mike Stumpab28c132009-10-13 22:54:56 +0000302 assert(false && "FIXME: Base not found");
Anders Carlssondbd920c2009-10-11 22:13:54 +0000303 return 0;
304 }
305
Eli Friedman367d1222009-12-04 08:40:51 +0000306 bool OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
307 Index_t OverrideOffset, Index_t Offset,
308 int64_t CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000309
Anders Carlssonadfa2672009-12-04 02:39:04 +0000310 /// AppendMethods - Append the current methods to the vtable.
Anders Carlssonbf540272009-12-04 02:56:03 +0000311 void AppendMethodsToVtable();
Anders Carlssonadfa2672009-12-04 02:39:04 +0000312
Anders Carlssona0fdd912009-11-13 17:08:56 +0000313 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
314 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
315
Anders Carlssonecf282b2009-11-24 05:08:52 +0000316 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump1ae31782009-10-27 23:36:26 +0000317
Mike Stumpc085a982009-12-03 16:55:20 +0000318 return wrap(CGM.GetAddrOfFunction(GD, Ty));
Mike Stump1ae31782009-10-27 23:36:26 +0000319 }
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);
Eli Friedman367d1222009-12-04 08:40:51 +0000337 OverrideMethod(CompDtor, MorallyVirtual, OverrideOffset, Offset,
338 CurrentVBaseOffset);
339
Anders Carlssona0fdd912009-11-13 17:08:56 +0000340 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
Eli Friedman367d1222009-12-04 08:40:51 +0000341 OverrideMethod(DeletingDtor, MorallyVirtual, OverrideOffset, Offset,
342 CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +0000343 } else {
Eli Friedman367d1222009-12-04 08:40:51 +0000344 OverrideMethod(MD, MorallyVirtual, OverrideOffset, Offset,
345 CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +0000346 }
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 Carlssondbd920c2009-10-11 22:13:54 +0000353 // If we can find a previously allocated slot for this, reuse it.
Eli Friedman367d1222009-12-04 08:40:51 +0000354 if (OverrideMethod(GD, MorallyVirtual, Offset, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000355 CurrentVBaseOffset))
Anders Carlssondbd920c2009-10-11 22:13:54 +0000356 return;
357
Anders Carlssona7f19112009-12-04 02:08:24 +0000358 // We didn't find an entry in the vtable that we could use, add a new
359 // entry.
360 Methods.AddMethod(GD);
361
Mike Stumpe99cc452009-11-13 23:45:53 +0000362 D1(printf(" vfn for %s at %d\n", MD->getNameAsString().c_str(),
363 (int)Index[GD]));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000364 if (MorallyVirtual) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000365 VCallOffset[GD] = Offset/8;
366 Index_t &idx = VCall[GD];
Anders Carlssondbd920c2009-10-11 22:13:54 +0000367 // Allocate the first one, after that, we reuse the previous one.
368 if (idx == 0) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000369 NonVirtualOffset[GD] = CurrentVBaseOffset/8 - Offset/8;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000370 idx = VCalls.size()+1;
371 VCalls.push_back(0);
Mike Stump6a9612f2009-10-31 20:06:59 +0000372 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpe99cc452009-11-13 23:45:53 +0000373 MD->getNameAsString().c_str(), (int)-VCalls.size()-3, 0));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000374 }
375 }
376 }
377
378 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000379 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000380 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssona0fdd912009-11-13 17:08:56 +0000381 ++mi) {
382 const CXXMethodDecl *MD = *mi;
383 if (!MD->isVirtual())
384 continue;
385
386 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
387 // For destructors, add both the complete and the deleting destructor
388 // to the vtable.
389 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000390 CurrentVBaseOffset);
Eli Friedman76ed1f72009-11-30 01:19:33 +0000391 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
392 CurrentVBaseOffset);
393 } else
394 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +0000395 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000396 }
397
398 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
399 const CXXRecordDecl *PrimaryBase,
400 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000401 int64_t Offset, int64_t CurrentVBaseOffset,
402 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +0000403 Path->push_back(std::make_pair(RD, Offset));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000404 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
405 e = RD->bases_end(); i != e; ++i) {
406 if (i->isVirtual())
407 continue;
408 const CXXRecordDecl *Base =
409 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
410 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
411 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
412 StartNewTable();
Mike Stump4cde6262009-11-13 02:13:54 +0000413 GenerateVtableForBase(Base, o, MorallyVirtual, false,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000414 CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000415 }
416 }
Mike Stump11dea942009-10-15 02:04:03 +0000417 Path->pop_back();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000418 }
419
Mike Stump0ca42792009-10-14 18:14:51 +0000420// #define D(X) do { X; } while (0)
421#define D(X)
422
423 void insertVCalls(int InsertionPoint) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000424 D1(printf("============= combining vbase/vcall\n"));
Mike Stump0ca42792009-10-14 18:14:51 +0000425 D(VCalls.insert(VCalls.begin(), 673));
426 D(VCalls.push_back(672));
Eli Friedman152b5b12009-12-05 01:05:03 +0000427
Anders Carlsson15318f42009-12-04 16:19:30 +0000428 Vtable.insert(Vtable.begin() + InsertionPoint, VCalls.size(), 0);
Eli Friedman152b5b12009-12-05 01:05:03 +0000429 if (BuildVtable) {
430 // The vcalls come first...
431 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
432 e = VCalls.rend();
433 i != e; ++i)
434 Vtable[InsertionPoint++] = wrap((0?600:0) + *i);
435 }
Mike Stump0ca42792009-10-14 18:14:51 +0000436 VCalls.clear();
Mike Stumpfbfb52d2009-11-10 02:30:51 +0000437 VCall.clear();
Mike Stump0ca42792009-10-14 18:14:51 +0000438 }
439
Mike Stump65d0e282009-11-13 23:13:20 +0000440 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
441 Index_t AddressPoint) {
442 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
443 RD->getNameAsCString(), Class->getNameAsCString(),
444 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +0000445 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +0000446
447 // Now also add the address point for all our primary bases.
448 while (1) {
449 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
450 RD = Layout.getPrimaryBase();
451 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
452 // FIXME: Double check this.
453 if (RD == 0)
454 break;
455 if (PrimaryBaseWasVirtual &&
456 BLayout.getVBaseClassOffset(RD) != Offset)
457 break;
458 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
459 RD->getNameAsCString(), Class->getNameAsCString(),
460 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +0000461 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +0000462 }
463 }
464
465
Eli Friedmand6a3e672009-12-04 03:54:56 +0000466 Index_t FinishGenerateVtable(const CXXRecordDecl *RD,
467 const ASTRecordLayout &Layout,
468 const CXXRecordDecl *PrimaryBase,
469 bool PrimaryBaseWasVirtual,
470 bool MorallyVirtual, int64_t Offset,
471 bool ForVirtualBase, int64_t CurrentVBaseOffset,
472 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +0000473 bool alloc = false;
474 if (Path == 0) {
475 alloc = true;
476 Path = new Path_t;
477 }
478
Anders Carlssondbd920c2009-10-11 22:13:54 +0000479 StartNewTable();
480 extra = 0;
Mike Stump0ca42792009-10-14 18:14:51 +0000481 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
Anders Carlsson15318f42009-12-04 16:19:30 +0000482 int VCallInsertionPoint = Vtable.size();
Mike Stump0ca42792009-10-14 18:14:51 +0000483 if (!DeferVCalls) {
484 insertVCalls(VCallInsertionPoint);
Mike Stump3425b972009-10-15 09:30:16 +0000485 } else
486 // FIXME: just for extra, or for all uses of VCalls.size post this?
487 extra = -VCalls.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000488
Anders Carlsson15318f42009-12-04 16:19:30 +0000489 // Add the offset to top.
Eli Friedman152b5b12009-12-05 01:05:03 +0000490 Vtable.push_back(BuildVtable ? wrap(-((Offset-LayoutOffset)/8)) : 0);
Anders Carlsson15318f42009-12-04 16:19:30 +0000491
492 // Add the RTTI information.
493 Vtable.push_back(rtti);
494
495 Index_t AddressPoint = Vtable.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000496
Anders Carlssonbf540272009-12-04 02:56:03 +0000497 AppendMethodsToVtable();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000498
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.
Eli Friedmandfe33bb2009-12-04 08:52:11 +0000534 if (PrimaryBase && !PrimaryBaseWasVirtual) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000535 D1(printf(" doing primaries for %s most derived %s\n",
536 RD->getNameAsCString(), Class->getNameAsCString()));
Eli Friedmandfe33bb2009-12-04 08:52:11 +0000537 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
538 updateVBIndex, current_vbindex, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000539 }
540
541 D1(printf(" doing vcall entries for %s most derived %s\n",
542 RD->getNameAsCString(), Class->getNameAsCString()));
543
544 // And add the virtuals for the class to the primary vtable.
Eli Friedman76ed1f72009-11-30 01:19:33 +0000545 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000546 }
547
548 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
549 bool updateVBIndex, Index_t current_vbindex,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000550 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000551 bool bottom) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000552 if (!RD->isDynamicClass())
553 return;
554
555 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
556 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
557 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
558
559 // vtables are composed from the chain of primaries.
560 if (PrimaryBase) {
Mike Stump9e7e3c62009-11-06 23:27:42 +0000561 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
562 if (PrimaryBaseWasVirtual) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000563 IndirectPrimary.insert(PrimaryBase);
Mike Stump9e7e3c62009-11-06 23:27:42 +0000564 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
565 }
Mike Stump6a9612f2009-10-31 20:06:59 +0000566
567 D1(printf(" doing primaries for %s most derived %s\n",
568 RD->getNameAsCString(), Class->getNameAsCString()));
569
570 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000571 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000572 BaseCurrentVBaseOffset, false);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000573 }
574
Mike Stump6a9612f2009-10-31 20:06:59 +0000575 D1(printf(" doing vbase entries for %s most derived %s\n",
576 RD->getNameAsCString(), Class->getNameAsCString()));
577 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
578
579 if (RDisVirtualBase || bottom) {
580 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000581 CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000582 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000583 }
584
Mike Stump4cde6262009-11-13 02:13:54 +0000585 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
586 bool MorallyVirtual = false,
Anders Carlssondbd920c2009-10-11 22:13:54 +0000587 bool ForVirtualBase = false,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000588 int CurrentVBaseOffset = 0,
Mike Stump11dea942009-10-15 02:04:03 +0000589 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000590 if (!RD->isDynamicClass())
591 return 0;
592
Mike Stump92774d12009-11-13 02:35:38 +0000593 // Construction vtable don't need parts that have no virtual bases and
594 // aren't morally virtual.
Anders Carlssonac3f7bd2009-12-04 18:36:22 +0000595 if ((LayoutClass != MostDerivedClass) &&
596 RD->getNumVBases() == 0 && !MorallyVirtual)
Mike Stump92774d12009-11-13 02:35:38 +0000597 return 0;
598
Anders Carlssondbd920c2009-10-11 22:13:54 +0000599 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
600 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
601 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
602
Anders Carlssondbd920c2009-10-11 22:13:54 +0000603 extra = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +0000604 D1(printf("building entries for base %s most derived %s\n",
605 RD->getNameAsCString(), Class->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000606
Mike Stump6a9612f2009-10-31 20:06:59 +0000607 if (ForVirtualBase)
608 extra = VCalls.size();
609
610 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0, ForVirtualBase,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000611 CurrentVBaseOffset, true);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000612
613 if (Path)
Mike Stump9e7e3c62009-11-06 23:27:42 +0000614 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000615
Eli Friedmand6a3e672009-12-04 03:54:56 +0000616 return FinishGenerateVtable(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
617 MorallyVirtual, Offset, ForVirtualBase,
618 CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000619 }
620
621 void GenerateVtableForVBases(const CXXRecordDecl *RD,
622 int64_t Offset = 0,
Mike Stump11dea942009-10-15 02:04:03 +0000623 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000624 bool alloc = false;
625 if (Path == 0) {
626 alloc = true;
Mike Stump11dea942009-10-15 02:04:03 +0000627 Path = new Path_t;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000628 }
629 // FIXME: We also need to override using all paths to a virtual base,
630 // right now, we just process the first path
631 Path->push_back(std::make_pair(RD, Offset));
632 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
633 e = RD->bases_end(); i != e; ++i) {
634 const CXXRecordDecl *Base =
635 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
636 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
637 // Mark it so we don't output it twice.
638 IndirectPrimary.insert(Base);
639 StartNewTable();
Mike Stump0ca42792009-10-14 18:14:51 +0000640 VCall.clear();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000641 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9e7e3c62009-11-06 23:27:42 +0000642 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump6a9612f2009-10-31 20:06:59 +0000643 D1(printf("vtable %s virtual base %s\n",
644 Class->getNameAsCString(), Base->getNameAsCString()));
Mike Stump4cde6262009-11-13 02:13:54 +0000645 GenerateVtableForBase(Base, BaseOffset, true, true, CurrentVBaseOffset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000646 Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000647 }
Mike Stump9840c702009-11-12 20:47:57 +0000648 int64_t BaseOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000649 if (i->isVirtual())
650 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9840c702009-11-12 20:47:57 +0000651 else {
652 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
653 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
654 }
655
Mike Stump11dea942009-10-15 02:04:03 +0000656 if (Base->getNumVBases()) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000657 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump11dea942009-10-15 02:04:03 +0000658 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000659 }
660 Path->pop_back();
661 if (alloc)
662 delete Path;
663 }
664};
Anders Carlsson27682a32009-12-03 01:54:02 +0000665} // end anonymous namespace
666
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000667/// TypeConversionRequiresAdjustment - Returns whether conversion from a
668/// derived type to a base type requires adjustment.
669static bool
670TypeConversionRequiresAdjustment(ASTContext &Ctx,
671 const CXXRecordDecl *DerivedDecl,
672 const CXXRecordDecl *BaseDecl) {
673 CXXBasePaths Paths(/*FindAmbiguities=*/false,
674 /*RecordPaths=*/true, /*DetectVirtual=*/true);
675 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
676 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
677 assert(false && "Class must be derived from the passed in base class!");
678 return false;
679 }
680
681 // If we found a virtual base we always want to require adjustment.
682 if (Paths.getDetectedVirtual())
683 return true;
684
685 const CXXBasePath &Path = Paths.front();
686
687 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
688 const CXXBasePathElement &Element = Path[Start];
689
690 // Check the base class offset.
691 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
692
693 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
694 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
695
696 if (Layout.getBaseClassOffset(Base) != 0) {
697 // This requires an adjustment.
698 return true;
699 }
700 }
701
702 return false;
703}
704
705static bool
706TypeConversionRequiresAdjustment(ASTContext &Ctx,
707 QualType DerivedType, QualType BaseType) {
708 // Canonicalize the types.
709 QualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
710 QualType CanBaseType = Ctx.getCanonicalType(BaseType);
711
712 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
713 "Types must have same type class!");
714
715 if (CanDerivedType == CanBaseType) {
716 // No adjustment needed.
717 return false;
718 }
719
720 if (const ReferenceType *RT = dyn_cast<ReferenceType>(CanDerivedType)) {
721 CanDerivedType = RT->getPointeeType();
722 CanBaseType = cast<ReferenceType>(CanBaseType)->getPointeeType();
723 } else if (const PointerType *PT = dyn_cast<PointerType>(CanDerivedType)) {
724 CanDerivedType = PT->getPointeeType();
725 CanBaseType = cast<PointerType>(CanBaseType)->getPointeeType();
726 } else {
727 assert(false && "Unexpected return type!");
728 }
729
730 if (CanDerivedType == CanBaseType) {
731 // No adjustment needed.
732 return false;
733 }
734
735 const CXXRecordDecl *DerivedDecl =
Anders Carlsson1750b4f2009-12-03 03:28:24 +0000736 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000737
738 const CXXRecordDecl *BaseDecl =
739 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
740
741 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
742}
743
Eli Friedman367d1222009-12-04 08:40:51 +0000744bool VtableBuilder::OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
745 Index_t OverrideOffset, Index_t Offset,
746 int64_t CurrentVBaseOffset) {
Anders Carlsson27682a32009-12-03 01:54:02 +0000747 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
748
749 const bool isPure = MD->isPure();
Anders Carlsson7ca46432009-12-05 17:04:47 +0000750
Anders Carlsson27682a32009-12-03 01:54:02 +0000751 // FIXME: Should OverrideOffset's be Offset?
752
Anders Carlsson7ca46432009-12-05 17:04:47 +0000753 for (CXXMethodDecl::method_iterator mi = MD->begin_overridden_methods(),
754 e = MD->end_overridden_methods(); mi != e; ++mi) {
Anders Carlsson27682a32009-12-03 01:54:02 +0000755 GlobalDecl OGD;
756
Anders Carlsson3aaf4862009-12-04 05:51:56 +0000757 const CXXMethodDecl *OMD = *mi;
Anders Carlsson27682a32009-12-03 01:54:02 +0000758 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
759 OGD = GlobalDecl(DD, GD.getDtorType());
760 else
761 OGD = OMD;
Eli Friedman47145832009-12-04 08:34:14 +0000762
763 // FIXME: Explain why this is necessary!
Anders Carlsson77c23e52009-12-04 15:49:02 +0000764 uint64_t Index;
765 if (!Methods.getIndex(OGD, Index))
Eli Friedman47145832009-12-04 08:34:14 +0000766 continue;
767
Eli Friedman47145832009-12-04 08:34:14 +0000768 QualType ReturnType =
769 MD->getType()->getAs<FunctionType>()->getResultType();
770 QualType OverriddenReturnType =
771 OMD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlsson27682a32009-12-03 01:54:02 +0000772
Eli Friedman47145832009-12-04 08:34:14 +0000773 // Check if we need a return type adjustment.
774 if (TypeConversionRequiresAdjustment(CGM.getContext(), ReturnType,
775 OverriddenReturnType)) {
776 CanQualType &BaseReturnType = BaseReturnTypes[Index];
Anders Carlsson27682a32009-12-03 01:54:02 +0000777
Eli Friedman47145832009-12-04 08:34:14 +0000778 // Get the canonical return type.
779 CanQualType CanReturnType =
780 CGM.getContext().getCanonicalType(ReturnType);
Anders Carlssonc0c49932009-12-04 03:41:37 +0000781
Eli Friedman47145832009-12-04 08:34:14 +0000782 // Insert the base return type.
783 if (BaseReturnType.isNull())
784 BaseReturnType =
785 CGM.getContext().getCanonicalType(OverriddenReturnType);
786 }
Anders Carlssondd454be2009-12-04 03:52:52 +0000787
Eli Friedman47145832009-12-04 08:34:14 +0000788 Methods.OverrideMethod(OGD, GD);
789
Eli Friedman47145832009-12-04 08:34:14 +0000790 ThisAdjustments.erase(Index);
791 if (MorallyVirtual || VCall.count(OGD)) {
792 Index_t &idx = VCall[OGD];
793 if (idx == 0) {
794 NonVirtualOffset[GD] = -OverrideOffset/8 + CurrentVBaseOffset/8;
795 VCallOffset[GD] = OverrideOffset/8;
796 idx = VCalls.size()+1;
797 VCalls.push_back(0);
798 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
799 MD->getNameAsString().c_str(), (int)-idx-3,
800 (int)VCalls[idx-1], Class->getNameAsCString()));
801 } else {
802 NonVirtualOffset[GD] = NonVirtualOffset[OGD];
803 VCallOffset[GD] = VCallOffset[OGD];
804 VCalls[idx-1] = -VCallOffset[OGD] + OverrideOffset/8;
805 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
806 MD->getNameAsString().c_str(), (int)-idx-3,
807 (int)VCalls[idx-1], Class->getNameAsCString()));
808 }
809 VCall[GD] = idx;
810 int64_t NonVirtualAdjustment = NonVirtualOffset[GD];
811 int64_t VirtualAdjustment =
812 -((idx + extra + 2) * LLVMPointerWidth / 8);
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000813
Eli Friedman47145832009-12-04 08:34:14 +0000814 // Optimize out virtual adjustments of 0.
815 if (VCalls[idx-1] == 0)
816 VirtualAdjustment = 0;
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000817
Eli Friedman47145832009-12-04 08:34:14 +0000818 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
819 VirtualAdjustment);
Anders Carlssonbc0e3392009-12-03 02:22:59 +0000820
Eli Friedman47145832009-12-04 08:34:14 +0000821 if (!isPure && !ThisAdjustment.isEmpty())
822 ThisAdjustments[Index] = ThisAdjustment;
Anders Carlsson27682a32009-12-03 01:54:02 +0000823 return true;
824 }
Eli Friedman47145832009-12-04 08:34:14 +0000825
826 // FIXME: finish off
827 int64_t NonVirtualAdjustment = VCallOffset[OGD] - OverrideOffset/8;
828
829 if (NonVirtualAdjustment) {
830 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
831
832 if (!isPure)
833 ThisAdjustments[Index] = ThisAdjustment;
834 }
835 return true;
Anders Carlsson27682a32009-12-03 01:54:02 +0000836 }
837
838 return false;
Anders Carlsson27f69d02009-11-27 22:21:51 +0000839}
840
Anders Carlssonbf540272009-12-04 02:56:03 +0000841void VtableBuilder::AppendMethodsToVtable() {
Eli Friedman152b5b12009-12-05 01:05:03 +0000842 if (!BuildVtable) {
843 Vtable.insert(Vtable.end(), Methods.size(), (llvm::Constant*)0);
844 ThisAdjustments.clear();
845 BaseReturnTypes.clear();
846 Methods.clear();
847 return;
848 }
849
Anders Carlsson15318f42009-12-04 16:19:30 +0000850 // Reserve room in the vtable for our new methods.
851 Vtable.reserve(Vtable.size() + Methods.size());
Anders Carlsson29202d52009-12-04 03:07:26 +0000852
Anders Carlssonb73ba392009-12-04 02:43:50 +0000853 for (unsigned i = 0, e = Methods.size(); i != e; ++i) {
854 GlobalDecl GD = Methods[i];
Anders Carlssonea357222009-12-04 02:52:22 +0000855 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
856
857 // Get the 'this' pointer adjustment.
Anders Carlssonb73ba392009-12-04 02:43:50 +0000858 ThunkAdjustment ThisAdjustment = ThisAdjustments.lookup(i);
Anders Carlssonea357222009-12-04 02:52:22 +0000859
860 // Construct the return type adjustment.
861 ThunkAdjustment ReturnAdjustment;
862
863 QualType BaseReturnType = BaseReturnTypes.lookup(i);
864 if (!BaseReturnType.isNull() && !MD->isPure()) {
865 QualType DerivedType =
866 MD->getType()->getAs<FunctionType>()->getResultType();
867
868 int64_t NonVirtualAdjustment =
869 getNVOffset(BaseReturnType, DerivedType) / 8;
870
871 int64_t VirtualAdjustment =
872 getVbaseOffset(BaseReturnType, DerivedType);
873
874 ReturnAdjustment = ThunkAdjustment(NonVirtualAdjustment,
875 VirtualAdjustment);
876 }
877
Anders Carlsson2fce2162009-12-04 03:06:03 +0000878 llvm::Constant *Method = 0;
Anders Carlssonea357222009-12-04 02:52:22 +0000879 if (!ReturnAdjustment.isEmpty()) {
880 // Build a covariant thunk.
881 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Anders Carlsson2fce2162009-12-04 03:06:03 +0000882 Method = CGM.BuildCovariantThunk(MD, Extern, Adjustment);
Anders Carlssonea357222009-12-04 02:52:22 +0000883 } else if (!ThisAdjustment.isEmpty()) {
884 // Build a "regular" thunk.
Anders Carlsson2fce2162009-12-04 03:06:03 +0000885 Method = CGM.BuildThunk(GD, Extern, ThisAdjustment);
Anders Carlssonbf540272009-12-04 02:56:03 +0000886 } else if (MD->isPure()) {
887 // We have a pure virtual method.
Anders Carlsson2fce2162009-12-04 03:06:03 +0000888 Method = getPureVirtualFn();
889 } else {
890 // We have a good old regular method.
891 Method = WrapAddrOf(GD);
Anders Carlssonea357222009-12-04 02:52:22 +0000892 }
Anders Carlsson2fce2162009-12-04 03:06:03 +0000893
894 // Add the method to the vtable.
Anders Carlsson15318f42009-12-04 16:19:30 +0000895 Vtable.push_back(Method);
Anders Carlssonb73ba392009-12-04 02:43:50 +0000896 }
897
Anders Carlsson2fce2162009-12-04 03:06:03 +0000898
Anders Carlssonb73ba392009-12-04 02:43:50 +0000899 ThisAdjustments.clear();
Anders Carlssonea357222009-12-04 02:52:22 +0000900 BaseReturnTypes.clear();
Anders Carlssonb73ba392009-12-04 02:43:50 +0000901
Anders Carlssonadfa2672009-12-04 02:39:04 +0000902 Methods.clear();
Anders Carlssonadfa2672009-12-04 02:39:04 +0000903}
904
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000905void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
906
907 // Itanium C++ ABI 2.5.2:
908 // The order of the virtual function pointers in a virtual table is the
909 // order of declaration of the corresponding member functions in the class.
910 //
911 // There is an entry for any virtual function declared in a class,
912 // whether it is a new function or overrides a base class function,
913 // unless it overrides a function from the primary base, and conversion
914 // between their return types does not require an adjustment.
915
916 int64_t CurrentIndex = 0;
917
918 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
919 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
920
921 if (PrimaryBase) {
Anders Carlsson0121fbd2009-11-30 19:43:26 +0000922 assert(PrimaryBase->isDefinition() &&
923 "Should have the definition decl of the primary base!");
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000924
925 // Since the record decl shares its vtable pointer with the primary base
926 // we need to start counting at the end of the primary base's vtable.
927 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
928 }
929
930 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
931
932 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
933 e = RD->method_end(); i != e; ++i) {
934 const CXXMethodDecl *MD = *i;
935
936 // We only want virtual methods.
937 if (!MD->isVirtual())
938 continue;
939
940 bool ShouldAddEntryForMethod = true;
941
942 // Check if this method overrides a method in the primary base.
943 for (CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
944 e = MD->end_overridden_methods(); i != e; ++i) {
Anders Carlsson3aaf4862009-12-04 05:51:56 +0000945 const CXXMethodDecl *OverriddenMD = *i;
Anders Carlssond6b07fb2009-11-27 20:47:55 +0000946 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
947 assert(OverriddenMD->isCanonicalDecl() &&
948 "Should have the canonical decl of the overridden RD!");
949
950 if (OverriddenRD == PrimaryBase) {
951 // Check if converting from the return type of the method to the
952 // return type of the overridden method requires conversion.
953 QualType ReturnType =
954 MD->getType()->getAs<FunctionType>()->getResultType();
955 QualType OverriddenReturnType =
956 OverriddenMD->getType()->getAs<FunctionType>()->getResultType();
957
958 if (!TypeConversionRequiresAdjustment(CGM.getContext(),
959 ReturnType, OverriddenReturnType)) {
960 // This index is shared between the index in the vtable of the primary
961 // base class.
962 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
963 const CXXDestructorDecl *OverriddenDD =
964 cast<CXXDestructorDecl>(OverriddenMD);
965
966 // Add both the complete and deleting entries.
967 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
968 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
969 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
970 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
971 } else {
972 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
973 }
974
975 // We don't need to add an entry for this method.
976 ShouldAddEntryForMethod = false;
977 break;
978 }
979 }
980 }
981
982 if (!ShouldAddEntryForMethod)
983 continue;
984
985 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
986 if (MD->isImplicit()) {
987 assert(!ImplicitVirtualDtor &&
988 "Did already see an implicit virtual dtor!");
989 ImplicitVirtualDtor = DD;
990 continue;
991 }
992
993 // Add the complete dtor.
994 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
995
996 // Add the deleting dtor.
997 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
998 } else {
999 // Add the entry.
1000 MethodVtableIndices[MD] = CurrentIndex++;
1001 }
1002 }
1003
1004 if (ImplicitVirtualDtor) {
1005 // Itanium C++ ABI 2.5.2:
1006 // If a class has an implicitly-defined virtual destructor,
1007 // its entries come after the declared virtual function pointers.
1008
1009 // Add the complete dtor.
1010 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
1011 CurrentIndex++;
1012
1013 // Add the deleting dtor.
1014 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
1015 CurrentIndex++;
1016 }
1017
1018 NumVirtualFunctionPointers[RD] = CurrentIndex;
1019}
1020
1021uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
1022 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1023 NumVirtualFunctionPointers.find(RD);
1024 if (I != NumVirtualFunctionPointers.end())
1025 return I->second;
1026
1027 ComputeMethodVtableIndices(RD);
1028
1029 I = NumVirtualFunctionPointers.find(RD);
1030 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
1031 return I->second;
1032}
1033
1034uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssona0fdd912009-11-13 17:08:56 +00001035 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001036 if (I != MethodVtableIndices.end())
1037 return I->second;
1038
Anders Carlssona0fdd912009-11-13 17:08:56 +00001039 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001040
1041 ComputeMethodVtableIndices(RD);
1042
Anders Carlssona0fdd912009-11-13 17:08:56 +00001043 I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001044 assert(I != MethodVtableIndices.end() && "Did not find index!");
1045 return I->second;
1046}
1047
1048int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
1049 const CXXRecordDecl *VBase) {
1050 ClassPairTy ClassPair(RD, VBase);
1051
1052 VirtualBaseClassIndiciesTy::iterator I =
1053 VirtualBaseClassIndicies.find(ClassPair);
1054 if (I != VirtualBaseClassIndicies.end())
1055 return I->second;
1056
Anders Carlssondbd920c2009-10-11 22:13:54 +00001057 // FIXME: This seems expensive. Can we do a partial job to get
1058 // just this data.
Eli Friedman152b5b12009-12-05 01:05:03 +00001059 VtableBuilder b(RD, RD, 0, CGM, false);
Mike Stump6a9612f2009-10-31 20:06:59 +00001060 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00001061 b.GenerateVtableForBase(RD);
1062 b.GenerateVtableForVBases(RD);
1063
1064 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1065 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
1066 // Insert all types.
1067 ClassPairTy ClassPair(RD, I->first);
1068
1069 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
1070 }
1071
1072 I = VirtualBaseClassIndicies.find(ClassPair);
1073 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
1074
1075 return I->second;
1076}
1077
Anders Carlsson9ac95b92009-12-05 21:03:56 +00001078uint64_t CGVtableInfo::getVtableAddressPoint(const CXXRecordDecl *RD) {
1079 uint64_t AddressPoint =
1080 (*(*(CGM.AddressPoints[RD]))[RD])[std::make_pair(RD, 0)];
1081
1082 return AddressPoint;
1083}
1084
Anders Carlsson152d4dc2009-12-05 22:19:10 +00001085/// createGlobalVariable - Create a global variable to be used for storing
1086/// either a vtable, a construction vtable or a VTT. The returned global
1087// variable will have the correct linkage set based on the given record decl.
1088static llvm::GlobalVariable *
1089createGlobalVariable(CodeGenModule &CGM, const CXXRecordDecl *RD,
1090 const llvm::Type *Type, llvm::Constant *Init,
1091 const llvm::Twine &Name) {
1092
1093 // Figure out the right linkage.
1094 llvm::GlobalVariable::LinkageTypes Linkage =
Anders Carlsson891c8b72009-12-05 22:24:38 +00001095 llvm::GlobalValue::WeakODRLinkage;
Anders Carlsson152d4dc2009-12-05 22:19:10 +00001096 if (!Init)
1097 Linkage = llvm::GlobalValue::ExternalLinkage;
1098 else if (RD->isInAnonymousNamespace())
1099 Linkage = llvm::GlobalValue::InternalLinkage;
1100
1101 // Create the variable.
1102 llvm::GlobalVariable *V =
1103 new llvm::GlobalVariable(CGM.getModule(), Type, /*isConstant=*/true,
1104 Linkage, Init, Name);
1105
1106
1107 bool Hidden = CGM.getDeclVisibilityMode(RD) == LangOptions::Hidden;
1108 if (Hidden)
1109 V->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1110
1111 return V;
1112}
1113
Mike Stump9840c702009-11-12 20:47:57 +00001114llvm::Constant *CodeGenModule::GenerateVtable(const CXXRecordDecl *LayoutClass,
1115 const CXXRecordDecl *RD,
Mike Stump8cfcb522009-11-11 20:26:26 +00001116 uint64_t Offset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001117 llvm::SmallString<256> OutName;
Mike Stump9840c702009-11-12 20:47:57 +00001118 if (LayoutClass != RD)
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001119 getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset/8, RD, OutName);
Mike Stump8cfcb522009-11-11 20:26:26 +00001120 else
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001121 getMangleContext().mangleCXXVtable(RD, OutName);
1122 llvm::StringRef Name = OutName.str();
Benjamin Kramer7a9474e2009-10-11 22:57:54 +00001123
Anders Carlssondbd920c2009-10-11 22:13:54 +00001124 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1125 int64_t AddressPoint;
1126
Mike Stump85615df2009-11-19 04:04:36 +00001127 llvm::GlobalVariable *GV = getModule().getGlobalVariable(Name);
Mike Stump23a35422009-11-19 20:52:19 +00001128 if (GV && AddressPoints[LayoutClass] && !GV->isDeclaration()) {
Mike Stump85615df2009-11-19 04:04:36 +00001129 AddressPoint=(*(*(AddressPoints[LayoutClass]))[RD])[std::make_pair(RD,
1130 Offset)];
Mike Stump23a35422009-11-19 20:52:19 +00001131 // FIXME: We can never have 0 address point. Do this for now so gepping
1132 // retains the same structure. Later, we'll just assert.
1133 if (AddressPoint == 0)
1134 AddressPoint = 1;
1135 } else {
Mike Stump85615df2009-11-19 04:04:36 +00001136 bool CreateDefinition = true;
1137 if (LayoutClass != RD)
1138 CreateDefinition = true;
1139 else {
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001140 const ASTRecordLayout &Layout =
1141 getContext().getASTRecordLayout(LayoutClass);
1142
1143 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stump85615df2009-11-19 04:04:36 +00001144 if (!KeyFunction->getBody()) {
1145 // If there is a KeyFunction, and it isn't defined, just build a
1146 // reference to the vtable.
1147 CreateDefinition = false;
1148 }
1149 }
1150 }
1151
Eli Friedman152b5b12009-12-05 01:05:03 +00001152 VtableBuilder b(RD, LayoutClass, Offset, *this, CreateDefinition);
1153
1154 D1(printf("vtable %s\n", RD->getNameAsCString()));
1155 // First comes the vtables for all the non-virtual bases...
1156 AddressPoint = b.GenerateVtableForBase(RD, Offset);
1157
1158 // then the vtables for all the virtual bases.
1159 b.GenerateVtableForVBases(RD, Offset);
1160
Anders Carlsson152d4dc2009-12-05 22:19:10 +00001161 llvm::Constant *Init = 0;
1162 llvm::ArrayType *ArrayType =
Anders Carlssone40477c2009-12-05 21:09:05 +00001163 llvm::ArrayType::get(Ptr8Ty, b.getVtable().size());
1164
Mike Stump85615df2009-11-19 04:04:36 +00001165 if (CreateDefinition) {
Anders Carlsson152d4dc2009-12-05 22:19:10 +00001166 Init = llvm::ConstantArray::get(ArrayType, &b.getVtable()[0],
1167 b.getVtable().size());
Mike Stump85615df2009-11-19 04:04:36 +00001168 }
1169 llvm::GlobalVariable *OGV = GV;
Anders Carlsson891c8b72009-12-05 22:24:38 +00001170 GV = createGlobalVariable(*this, LayoutClass, ArrayType, Init, Name);
Mike Stump85615df2009-11-19 04:04:36 +00001171 if (OGV) {
1172 GV->takeName(OGV);
Anders Carlsson152d4dc2009-12-05 22:19:10 +00001173 llvm::Constant *NewPtr =
1174 llvm::ConstantExpr::getBitCast(GV, OGV->getType());
Mike Stump85615df2009-11-19 04:04:36 +00001175 OGV->replaceAllUsesWith(NewPtr);
1176 OGV->eraseFromParent();
1177 }
Mike Stump85615df2009-11-19 04:04:36 +00001178 }
Anders Carlssonbb27d862009-12-05 21:28:12 +00001179
1180 return GV;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001181}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001182
Mike Stump92f2fe22009-12-02 19:07:44 +00001183namespace {
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001184class VTTBuilder {
1185 /// Inits - The list of values built for the VTT.
1186 std::vector<llvm::Constant *> &Inits;
1187 /// Class - The most derived class that this vtable is being built for.
1188 const CXXRecordDecl *Class;
1189 CodeGenModule &CGM; // Per-module state.
Mike Stump971977f2009-11-11 00:35:07 +00001190 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpaee8de32009-11-11 03:08:24 +00001191 /// BLayout - Layout for the most derived class that this vtable is being
1192 /// built for.
1193 const ASTRecordLayout &BLayout;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001194 CodeGenModule::AddrMap_t &AddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +00001195 // vtbl - A pointer to the vtable for Class.
1196 llvm::Constant *ClassVtbl;
1197 llvm::LLVMContext &VMContext;
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001198
Mike Stump28f7ce12009-11-12 22:56:32 +00001199 /// BuildVtablePtr - Build up a referene to the given secondary vtable
Anders Carlssonbb27d862009-12-05 21:28:12 +00001200 llvm::Constant *BuildVtablePtr(llvm::Constant *Vtable,
1201 const CXXRecordDecl *VtableClass,
Mike Stumpacfd1e52009-11-13 01:54:23 +00001202 const CXXRecordDecl *RD,
Mike Stump28f7ce12009-11-12 22:56:32 +00001203 uint64_t Offset) {
Anders Carlssonbb27d862009-12-05 21:28:12 +00001204 int64_t AddressPoint =
1205 (*AddressPoints[VtableClass])[std::make_pair(RD, Offset)];
1206
Mike Stump80ac2352009-11-12 23:36:21 +00001207 // FIXME: We can never have 0 address point. Do this for now so gepping
Mike Stump23a35422009-11-19 20:52:19 +00001208 // retains the same structure. Later we'll just assert.
Mike Stump80ac2352009-11-12 23:36:21 +00001209 if (AddressPoint == 0)
1210 AddressPoint = 1;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001211 D1(printf("XXX address point for %s in %s layout %s at offset %d was %d\n",
1212 RD->getNameAsCString(), VtblClass->getNameAsCString(),
1213 Class->getNameAsCString(), (int)Offset, (int)AddressPoint));
Anders Carlssonbb27d862009-12-05 21:28:12 +00001214
1215 llvm::Value *Idxs[] = {
1216 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 0),
1217 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), AddressPoint)
1218 };
1219
1220 llvm::Constant *Init =
1221 llvm::ConstantExpr::getInBoundsGetElementPtr(Vtable, Idxs, 2);
1222
1223 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
1224 return llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Mike Stump28f7ce12009-11-12 22:56:32 +00001225 }
1226
Mike Stump9840c702009-11-12 20:47:57 +00001227 /// Secondary - Add the secondary vtable pointers to Inits. Offset is the
1228 /// current offset in bits to the object we're working on.
Mike Stump28f7ce12009-11-12 22:56:32 +00001229 void Secondary(const CXXRecordDecl *RD, llvm::Constant *vtbl,
Mike Stumpacfd1e52009-11-13 01:54:23 +00001230 const CXXRecordDecl *VtblClass, uint64_t Offset=0,
1231 bool MorallyVirtual=false) {
Mike Stump971977f2009-11-11 00:35:07 +00001232 if (RD->getNumVBases() == 0 && ! MorallyVirtual)
1233 return;
1234
1235 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1236 e = RD->bases_end(); i != e; ++i) {
1237 const CXXRecordDecl *Base =
1238 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1239 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1240 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1241 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1242 bool NonVirtualPrimaryBase;
1243 NonVirtualPrimaryBase = !PrimaryBaseWasVirtual && Base == PrimaryBase;
1244 bool BaseMorallyVirtual = MorallyVirtual | i->isVirtual();
Mike Stumpaee8de32009-11-11 03:08:24 +00001245 uint64_t BaseOffset;
1246 if (!i->isVirtual()) {
1247 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1248 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1249 } else
1250 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump80ac2352009-11-12 23:36:21 +00001251 llvm::Constant *subvtbl = vtbl;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001252 const CXXRecordDecl *subVtblClass = VtblClass;
Mike Stump971977f2009-11-11 00:35:07 +00001253 if ((Base->getNumVBases() || BaseMorallyVirtual)
1254 && !NonVirtualPrimaryBase) {
1255 // FIXME: Slightly too many of these for __ZTT8test8_B2
Mike Stump28f7ce12009-11-12 22:56:32 +00001256 llvm::Constant *init;
Mike Stump80ac2352009-11-12 23:36:21 +00001257 if (BaseMorallyVirtual)
Mike Stumpacfd1e52009-11-13 01:54:23 +00001258 init = BuildVtablePtr(vtbl, VtblClass, RD, Offset);
Mike Stump80ac2352009-11-12 23:36:21 +00001259 else {
Mike Stump28f7ce12009-11-12 22:56:32 +00001260 init = CGM.getVtableInfo().getCtorVtable(Class, Base, BaseOffset);
Anders Carlssonbe58b392009-12-05 20:42:53 +00001261
1262 subvtbl = init;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001263 subVtblClass = Base;
Anders Carlssonbe58b392009-12-05 20:42:53 +00001264
1265 init = BuildVtablePtr(init, Class, Base, BaseOffset);
Mike Stump80ac2352009-11-12 23:36:21 +00001266 }
Mike Stump28f7ce12009-11-12 22:56:32 +00001267 Inits.push_back(init);
Mike Stump971977f2009-11-11 00:35:07 +00001268 }
Mike Stumpacfd1e52009-11-13 01:54:23 +00001269 Secondary(Base, subvtbl, subVtblClass, BaseOffset, BaseMorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001270 }
1271 }
1272
Mike Stump9840c702009-11-12 20:47:57 +00001273 /// BuiltVTT - Add the VTT to Inits. Offset is the offset in bits to the
1274 /// currnet object we're working on.
1275 void BuildVTT(const CXXRecordDecl *RD, uint64_t Offset, bool MorallyVirtual) {
Mike Stump971977f2009-11-11 00:35:07 +00001276 if (RD->getNumVBases() == 0 && !MorallyVirtual)
1277 return;
1278
Anders Carlsson4282edf2009-12-05 21:02:25 +00001279 llvm::Constant *Vtable;
1280 const CXXRecordDecl *VtableClass;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001281
Mike Stump971977f2009-11-11 00:35:07 +00001282 // First comes the primary virtual table pointer...
Mike Stumpacfd1e52009-11-13 01:54:23 +00001283 if (MorallyVirtual) {
Anders Carlsson4282edf2009-12-05 21:02:25 +00001284 Vtable = ClassVtbl;
1285 VtableClass = Class;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001286 } else {
Anders Carlsson4282edf2009-12-05 21:02:25 +00001287 Vtable = CGM.getVtableInfo().getCtorVtable(Class, RD, Offset);
1288 VtableClass = RD;
Mike Stumpacfd1e52009-11-13 01:54:23 +00001289 }
Anders Carlsson4282edf2009-12-05 21:02:25 +00001290
1291 llvm::Constant *Init = BuildVtablePtr(Vtable, VtableClass, RD, Offset);
1292 Inits.push_back(Init);
Mike Stump971977f2009-11-11 00:35:07 +00001293
1294 // then the secondary VTTs....
Mike Stump9840c702009-11-12 20:47:57 +00001295 SecondaryVTTs(RD, Offset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001296
1297 // and last the secondary vtable pointers.
Anders Carlsson4282edf2009-12-05 21:02:25 +00001298 Secondary(RD, Vtable, VtableClass, Offset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001299 }
1300
1301 /// SecondaryVTTs - Add the secondary VTTs to Inits. The secondary VTTs are
1302 /// built from each direct non-virtual proper base that requires a VTT in
1303 /// declaration order.
Mike Stump9840c702009-11-12 20:47:57 +00001304 void SecondaryVTTs(const CXXRecordDecl *RD, uint64_t Offset=0,
1305 bool MorallyVirtual=false) {
Mike Stump971977f2009-11-11 00:35:07 +00001306 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1307 e = RD->bases_end(); i != e; ++i) {
1308 const CXXRecordDecl *Base =
1309 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1310 if (i->isVirtual())
1311 continue;
Mike Stump9840c702009-11-12 20:47:57 +00001312 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1313 uint64_t BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1314 BuildVTT(Base, BaseOffset, MorallyVirtual);
Mike Stump971977f2009-11-11 00:35:07 +00001315 }
1316 }
1317
1318 /// VirtualVTTs - Add the VTT for each proper virtual base in inheritance
1319 /// graph preorder.
1320 void VirtualVTTs(const CXXRecordDecl *RD) {
1321 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1322 e = RD->bases_end(); i != e; ++i) {
1323 const CXXRecordDecl *Base =
1324 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1325 if (i->isVirtual() && !SeenVBase.count(Base)) {
1326 SeenVBase.insert(Base);
Mike Stump9840c702009-11-12 20:47:57 +00001327 uint64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
1328 BuildVTT(Base, BaseOffset, true);
Mike Stump971977f2009-11-11 00:35:07 +00001329 }
1330 VirtualVTTs(Base);
1331 }
1332 }
Anders Carlssonbe58b392009-12-05 20:42:53 +00001333
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001334public:
1335 VTTBuilder(std::vector<llvm::Constant *> &inits, const CXXRecordDecl *c,
Mike Stumpaee8de32009-11-11 03:08:24 +00001336 CodeGenModule &cgm)
1337 : Inits(inits), Class(c), CGM(cgm),
Mike Stump9840c702009-11-12 20:47:57 +00001338 BLayout(cgm.getContext().getASTRecordLayout(c)),
Mike Stumpacfd1e52009-11-13 01:54:23 +00001339 AddressPoints(*cgm.AddressPoints[c]),
Mike Stump9840c702009-11-12 20:47:57 +00001340 VMContext(cgm.getModule().getContext()) {
Mike Stump380dd752009-11-10 07:44:33 +00001341
Mike Stump971977f2009-11-11 00:35:07 +00001342 // First comes the primary virtual table pointer for the complete class...
Anders Carlssonbb27d862009-12-05 21:28:12 +00001343 ClassVtbl = CGM.getVtableInfo().getVtable(Class);
Anders Carlsson2e32aae2009-12-05 20:58:49 +00001344 Inits.push_back(BuildVtablePtr(ClassVtbl, Class, Class, 0));
Mike Stump9840c702009-11-12 20:47:57 +00001345
Mike Stump971977f2009-11-11 00:35:07 +00001346 // then the secondary VTTs...
1347 SecondaryVTTs(Class);
1348
1349 // then the secondary vtable pointers...
Mike Stumpacfd1e52009-11-13 01:54:23 +00001350 Secondary(Class, ClassVtbl, Class);
Mike Stump971977f2009-11-11 00:35:07 +00001351
1352 // and last, the virtual VTTs.
1353 VirtualVTTs(Class);
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001354 }
1355};
Mike Stump92f2fe22009-12-02 19:07:44 +00001356}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001357
Mike Stump380dd752009-11-10 07:44:33 +00001358llvm::Constant *CodeGenModule::GenerateVTT(const CXXRecordDecl *RD) {
Mike Stumpf1c03332009-11-10 19:13:04 +00001359 // Only classes that have virtual bases need a VTT.
1360 if (RD->getNumVBases() == 0)
1361 return 0;
1362
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001363 llvm::SmallString<256> OutName;
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001364 getMangleContext().mangleCXXVTT(RD, OutName);
1365 llvm::StringRef Name = OutName.str();
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001366
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001367
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001368 D1(printf("vtt %s\n", RD->getNameAsCString()));
1369
Anders Carlsson7ca46432009-12-05 17:04:47 +00001370 std::vector<llvm::Constant *> inits;
Mike Stump971977f2009-11-11 00:35:07 +00001371 VTTBuilder b(inits, RD, *this);
1372
Anders Carlsson7ca46432009-12-05 17:04:47 +00001373 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
1374 const llvm::ArrayType *Type = llvm::ArrayType::get(Int8PtrTy, inits.size());
1375
1376 llvm::Constant *Init = llvm::ConstantArray::get(Type, inits);
1377
1378 llvm::GlobalVariable *VTT =
1379 createGlobalVariable(*this, RD, Type, Init, Name);
1380
1381 return llvm::ConstantExpr::getBitCast(VTT, Int8PtrTy);
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001382}
Mike Stump380dd752009-11-10 07:44:33 +00001383
Mike Stump58588942009-11-19 01:08:19 +00001384void CGVtableInfo::GenerateClassData(const CXXRecordDecl *RD) {
1385 Vtables[RD] = CGM.GenerateVtable(RD, RD);
Mike Stumpde050572009-12-02 18:57:08 +00001386 CGM.GenerateRTTI(RD);
Mike Stump58588942009-11-19 01:08:19 +00001387 CGM.GenerateVTT(RD);
1388}
1389
Mike Stump8cfcb522009-11-11 20:26:26 +00001390llvm::Constant *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Anders Carlsson224c3122009-12-05 22:42:54 +00001391 llvm::Constant *&Vtable = Vtables[RD];
1392 if (!Vtable)
1393 Vtable = CGM.GenerateVtable(RD, RD);
Mike Stump85615df2009-11-19 04:04:36 +00001394
Anders Carlsson224c3122009-12-05 22:42:54 +00001395 return Vtable;
Mike Stump380dd752009-11-10 07:44:33 +00001396}
Mike Stump8cfcb522009-11-11 20:26:26 +00001397
Mike Stump9840c702009-11-12 20:47:57 +00001398llvm::Constant *CGVtableInfo::getCtorVtable(const CXXRecordDecl *LayoutClass,
1399 const CXXRecordDecl *RD,
Mike Stump8cfcb522009-11-11 20:26:26 +00001400 uint64_t Offset) {
Anders Carlssonbb27d862009-12-05 21:28:12 +00001401 return CGM.GenerateVtable(LayoutClass, RD, Offset);
Mike Stump8cfcb522009-11-11 20:26:26 +00001402}
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001403
1404void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
1405 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1406 const CXXRecordDecl *RD = MD->getParent();
1407
Anders Carlsson224c3122009-12-05 22:42:54 +00001408 // If the class doesn't have a vtable we don't need to emit one.
1409 if (!RD->isDynamicClass())
1410 return;
1411
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001412 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1413
1414 // Get the key function.
1415 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
1416
Anders Carlsson224c3122009-12-05 22:42:54 +00001417 if (KeyFunction) {
1418 // We don't have the right key function.
1419 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
1420 return;
1421
1422 // If the key function is a destructor, we only want to emit the vtable
1423 // once, so do it for the complete destructor.
1424 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Complete)
1425 return;
1426 } else {
1427 // If there is no key function, we only want to emit the vtable if we are
1428 // emitting a constructor.
1429 if (!isa<CXXConstructorDecl>(MD) || GD.getCtorType() != Ctor_Complete)
1430 return;
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001431 }
1432
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001433 // Emit the data.
1434 GenerateClassData(RD);
1435}
1436