blob: 2f5d3f7226b6fa5680207fe15fa8d2e0f80e6713 [file] [log] [blame]
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001//===--- CGVtable.cpp - Emit LLVM Code for C++ vtables --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
Anders Carlssonf942ee02009-11-27 20:47:55 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlsson2bb27f52009-10-11 22:13:54 +000017#include "clang/AST/RecordLayout.h"
Anders Carlssond420a312009-11-26 19:32:45 +000018#include "llvm/ADT/DenseSet.h"
Zhongxing Xu1721ef72009-11-13 05:46:16 +000019#include <cstdio>
Anders Carlsson2bb27f52009-10-11 22:13:54 +000020
21using namespace clang;
22using namespace CodeGen;
23
Anders Carlssond59885022009-11-27 22:21:51 +000024namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000025class VtableBuilder {
Anders Carlsson2bb27f52009-10-11 22:13:54 +000026public:
27 /// Index_t - Vtable index type.
28 typedef uint64_t Index_t;
29private:
30 std::vector<llvm::Constant *> &methods;
31 std::vector<llvm::Constant *> submethods;
32 llvm::Type *Ptr8Ty;
33 /// Class - The most derived class that this vtable is being built for.
34 const CXXRecordDecl *Class;
Mike Stump83066c82009-11-13 01:54:23 +000035 /// LayoutClass - The most derived class used for virtual base layout
36 /// information.
37 const CXXRecordDecl *LayoutClass;
Mike Stump653d0b92009-11-13 02:13:54 +000038 /// LayoutOffset - The offset for Class in LayoutClass.
39 uint64_t LayoutOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000040 /// BLayout - Layout for the most derived class that this vtable is being
41 /// built for.
42 const ASTRecordLayout &BLayout;
43 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
44 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
45 llvm::Constant *rtti;
46 llvm::LLVMContext &VMContext;
47 CodeGenModule &CGM; // Per-module state.
48 /// Index - Maps a method decl into a vtable index. Useful for virtual
49 /// dispatch codegen.
Anders Carlssonfb4dda42009-11-13 17:08:56 +000050 llvm::DenseMap<GlobalDecl, Index_t> Index;
51 llvm::DenseMap<GlobalDecl, Index_t> VCall;
52 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stumpcd6f9ed2009-11-06 23:27:42 +000053 // This is the offset to the nearest virtual base
Anders Carlssonfb4dda42009-11-13 17:08:56 +000054 llvm::DenseMap<GlobalDecl, Index_t> NonVirtualOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +000055 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stumpbb9ff052009-10-27 23:46:47 +000056
Anders Carlsson323bb042009-11-26 19:54:33 +000057 /// PureVirtualFunction - Points to __cxa_pure_virtual.
58 llvm::Constant *PureVirtualFn;
59
Anders Carlssona84b6e82009-12-04 02:01:07 +000060 /// VtableMethods - A data structure for keeping track of methods in a vtable.
61 /// Can add methods, override methods and iterate in vtable order.
62 class VtableMethods {
63 // MethodToIndexMap - Maps from a global decl to the index it has in the
64 // Methods vector.
65 llvm::DenseMap<GlobalDecl, uint64_t> MethodToIndexMap;
66
67 /// Methods - The methods, in vtable order.
68 typedef llvm::SmallVector<GlobalDecl, 16> MethodsVectorTy;
69 MethodsVectorTy Methods;
70
71 public:
72 /// AddMethod - Add a method to the vtable methods.
73 void AddMethod(GlobalDecl GD) {
74 assert(!MethodToIndexMap.count(GD) &&
75 "Method has already been added!");
76
77 MethodToIndexMap[GD] = Methods.size();
78 Methods.push_back(GD);
79 }
80
81 /// OverrideMethod - Replace a method with another.
82 void OverrideMethod(GlobalDecl OverriddenGD, GlobalDecl GD) {
83 llvm::DenseMap<GlobalDecl, uint64_t>::iterator i
84 = MethodToIndexMap.find(OverriddenGD);
85 assert(i != MethodToIndexMap.end() && "Did not find entry!");
86
87 // Get the index of the old decl.
88 uint64_t Index = i->second;
89
90 // Replace the old decl with the new decl.
91 Methods[Index] = GD;
92
93 // Now remove the old decl from the method to index map.
94 MethodToIndexMap.erase(i);
95
96 // And add the new.
97 MethodToIndexMap[GD] = Index;
98 }
99
100 MethodsVectorTy::size_type size() const {
101 return Methods.size();
102 }
103
104 void clear() {
105 MethodToIndexMap.clear();
106 Methods.clear();
107 }
108
109 GlobalDecl operator[](unsigned Index) const {
110 return Methods[Index];
111 }
112 };
113
114 /// Methods - The vtable methods we're currently building.
115 VtableMethods Methods;
116
Anders Carlsson4c837d22009-12-04 02:26:15 +0000117 /// ThisAdjustments - For a given index in the vtable, contains the 'this'
118 /// pointer adjustment needed for a method.
119 typedef llvm::DenseMap<uint64_t, ThunkAdjustment> ThisAdjustmentsMapTy;
120 ThisAdjustmentsMapTy ThisAdjustments;
Anders Carlssond420a312009-11-26 19:32:45 +0000121
Anders Carlssonc521f952009-12-04 02:22:02 +0000122 /// BaseReturnTypes - Contains the base return types of methods who have been
123 /// overridden with methods whose return types require adjustment. Used for
124 /// generating covariant thunk information.
125 typedef llvm::DenseMap<uint64_t, CanQualType> BaseReturnTypesMapTy;
126 BaseReturnTypesMapTy BaseReturnTypes;
Anders Carlssond420a312009-11-26 19:32:45 +0000127
128 /// PureVirtualMethods - Pure virtual methods.
129 typedef llvm::DenseSet<GlobalDecl> PureVirtualMethodsSetTy;
130 PureVirtualMethodsSetTy PureVirtualMethods;
131
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000132 std::vector<Index_t> VCalls;
Mike Stump2cefe382009-11-12 20:47:57 +0000133
134 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stumpcd2b8212009-11-19 20:52:19 +0000135 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
136 // vtable for use in computing the initializers for the VTT.
137 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump2cefe382009-11-12 20:47:57 +0000138
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000139 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000140 const bool Extern;
141 const uint32_t LLVMPointerWidth;
142 Index_t extra;
Mike Stump37dbe962009-10-15 02:04:03 +0000143 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stumpcd2b8212009-11-19 20:52:19 +0000144 static llvm::DenseMap<CtorVtable_t, int64_t>&
145 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
146 const CXXRecordDecl *c) {
147 CodeGenModule::AddrMap_t *&oref = cgm.AddressPoints[l];
148 if (oref == 0)
149 oref = new CodeGenModule::AddrMap_t;
150
151 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
152 if (ref == 0)
153 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
154 return *ref;
155 }
Anders Carlsson323bb042009-11-26 19:54:33 +0000156
157 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
158 llvm::Constant* getPureVirtualFn() {
159 if (!PureVirtualFn) {
160 const llvm::FunctionType *Ty =
161 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
162 /*isVarArg=*/false);
163 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
164 }
165
166 return PureVirtualFn;
167 }
168
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000169public:
Mike Stump653d0b92009-11-13 02:13:54 +0000170 VtableBuilder(std::vector<llvm::Constant *> &meth, const CXXRecordDecl *c,
171 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm)
172 : methods(meth), Class(c), LayoutClass(l), LayoutOffset(lo),
Mike Stump83066c82009-11-13 01:54:23 +0000173 BLayout(cgm.getContext().getASTRecordLayout(l)),
Mike Stumpc01c2b82009-12-02 18:57:08 +0000174 rtti(cgm.GenerateRTTIRef(c)), VMContext(cgm.getModule().getContext()),
Anders Carlsson323bb042009-11-26 19:54:33 +0000175 CGM(cgm), PureVirtualFn(0),subAddressPoints(AllocAddressPoint(cgm, l, c)),
Mike Stump1960b202009-11-19 00:49:05 +0000176 Extern(!l->isInAnonymousNamespace()),
Anders Carlsson323bb042009-11-26 19:54:33 +0000177 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000178 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
179 }
180
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000181 llvm::DenseMap<GlobalDecl, Index_t> &getIndex() { return Index; }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000182 llvm::DenseMap<const CXXRecordDecl *, Index_t> &getVBIndex()
183 { return VBIndex; }
184
185 llvm::Constant *wrap(Index_t i) {
186 llvm::Constant *m;
187 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
188 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
189 }
190
191 llvm::Constant *wrap(llvm::Constant *m) {
192 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
193 }
194
Mike Stump8a96d3a2009-12-02 19:50:41 +0000195#define D1(x)
196//#define D1(X) do { if (getenv("DEBUG")) { X; } } while (0)
Mike Stump75ce5732009-10-31 20:06:59 +0000197
198 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stump28431212009-10-13 22:54:56 +0000199 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000200 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
201 e = RD->bases_end(); i != e; ++i) {
202 const CXXRecordDecl *Base =
203 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stump28431212009-10-13 22:54:56 +0000204 Index_t next_vbindex = current_vbindex;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000205 if (i->isVirtual() && !SeenVBase.count(Base)) {
206 SeenVBase.insert(Base);
Mike Stump28431212009-10-13 22:54:56 +0000207 if (updateVBIndex) {
Mike Stump75ce5732009-10-31 20:06:59 +0000208 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stump28431212009-10-13 22:54:56 +0000209 - 3*LLVMPointerWidth/8);
210 VBIndex[Base] = next_vbindex;
211 }
Mike Stump75ce5732009-10-31 20:06:59 +0000212 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
213 VCalls.push_back((0?700:0) + BaseOffset);
214 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
215 Base->getNameAsCString(),
216 (int)-VCalls.size()-3, (int)BaseOffset,
217 Class->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000218 }
Mike Stump28431212009-10-13 22:54:56 +0000219 // We also record offsets for non-virtual bases to closest enclosing
220 // virtual base. We do this so that we don't have to search
221 // for the nearst virtual base class when generating thunks.
222 if (updateVBIndex && VBIndex.count(Base) == 0)
223 VBIndex[Base] = next_vbindex;
Mike Stump75ce5732009-10-31 20:06:59 +0000224 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000225 }
226 }
227
228 void StartNewTable() {
229 SeenVBase.clear();
230 }
231
Mike Stump8bccbfd2009-10-15 09:30:16 +0000232 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
233 Index_t Offset = 0) {
234
235 if (B == D)
236 return Offset;
237
238 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
239 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
240 e = D->bases_end(); i != e; ++i) {
241 const CXXRecordDecl *Base =
242 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
243 int64_t BaseOffset = 0;
244 if (!i->isVirtual())
245 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
246 int64_t o = getNVOffset_1(Base, B, BaseOffset);
247 if (o >= 0)
248 return o;
249 }
250
251 return -1;
252 }
253
254 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
255 /// derived class D.
256 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump46271322009-11-03 19:03:17 +0000257 qD = qD->getPointeeType();
258 qB = qB->getPointeeType();
Mike Stump8bccbfd2009-10-15 09:30:16 +0000259 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
260 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
261 int64_t o = getNVOffset_1(D, B);
262 if (o >= 0)
263 return o;
264
265 assert(false && "FIXME: non-virtual base not found");
266 return 0;
267 }
268
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000269 /// getVbaseOffset - Returns the index into the vtable for the virtual base
270 /// offset for the given (B) virtual base of the derived class D.
271 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump46271322009-11-03 19:03:17 +0000272 qD = qD->getPointeeType();
273 qB = qB->getPointeeType();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000274 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
275 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
276 if (D != Class)
Eli Friedman03aa2f12009-11-30 01:19:33 +0000277 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000278 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
279 i = VBIndex.find(B);
280 if (i != VBIndex.end())
281 return i->second;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000282
Mike Stump28431212009-10-13 22:54:56 +0000283 assert(false && "FIXME: Base not found");
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000284 return 0;
285 }
286
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000287 bool OverrideMethod(GlobalDecl GD, llvm::Constant *m,
Mike Stump8bccbfd2009-10-15 09:30:16 +0000288 bool MorallyVirtual, Index_t OverrideOffset,
Anders Carlssonca1bf682009-12-03 01:54:02 +0000289 Index_t Offset, int64_t CurrentVBaseOffset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000290
Anders Carlsson495634e2009-12-04 02:39:04 +0000291 /// AppendMethods - Append the current methods to the vtable.
292 void AppendMethods();
293
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000294 void InstallThunks() {
Anders Carlssond420a312009-11-26 19:32:45 +0000295 for (PureVirtualMethodsSetTy::iterator i = PureVirtualMethods.begin(),
296 e = PureVirtualMethods.end(); i != e; ++i) {
297 GlobalDecl GD = *i;
Anders Carlsson323bb042009-11-26 19:54:33 +0000298 submethods[Index[GD]] = getPureVirtualFn();
Mike Stumpbb9ff052009-10-27 23:46:47 +0000299 }
Anders Carlssond420a312009-11-26 19:32:45 +0000300 PureVirtualMethods.clear();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000301 }
302
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000303 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
304 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
305
Anders Carlsson64457732009-11-24 05:08:52 +0000306 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump18e8b472009-10-27 23:36:26 +0000307
Mike Stumpcdeb8002009-12-03 16:55:20 +0000308 return wrap(CGM.GetAddrOfFunction(GD, Ty));
Mike Stump18e8b472009-10-27 23:36:26 +0000309 }
310
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000311 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
312 int64_t CurrentVBaseOffset) {
Mike Stump37dbe962009-10-15 02:04:03 +0000313 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000314 e = Path->rend(); i != e; ++i) {
315 const CXXRecordDecl *RD = i->first;
Mike Stump8bccbfd2009-10-15 09:30:16 +0000316 int64_t OverrideOffset = i->second;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000317 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
318 ++mi) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000319 const CXXMethodDecl *MD = *mi;
320
321 if (!MD->isVirtual())
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000322 continue;
323
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000324 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
325 // Override both the complete and the deleting destructor.
326 GlobalDecl CompDtor(DD, Dtor_Complete);
327 OverrideMethod(CompDtor, WrapAddrOf(CompDtor), MorallyVirtual,
328 OverrideOffset, Offset, CurrentVBaseOffset);
329
330 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
331 OverrideMethod(DeletingDtor, WrapAddrOf(DeletingDtor), MorallyVirtual,
332 OverrideOffset, Offset, CurrentVBaseOffset);
333 } else {
334 OverrideMethod(MD, WrapAddrOf(MD), MorallyVirtual, OverrideOffset,
335 Offset, CurrentVBaseOffset);
336 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000337 }
338 }
339 }
340
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000341 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000342 int64_t CurrentVBaseOffset) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000343 llvm::Constant *m = WrapAddrOf(GD);
Mike Stump18e8b472009-10-27 23:36:26 +0000344
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000345 // If we can find a previously allocated slot for this, reuse it.
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000346 if (OverrideMethod(GD, m, MorallyVirtual, Offset, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000347 CurrentVBaseOffset))
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000348 return;
349
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000350 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
351
Anders Carlssoncdf18982009-12-04 02:08:24 +0000352 // We didn't find an entry in the vtable that we could use, add a new
353 // entry.
354 Methods.AddMethod(GD);
355
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000356 Index[GD] = submethods.size();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000357 submethods.push_back(m);
Mike Stumpc5a332c2009-11-13 23:45:53 +0000358 D1(printf(" vfn for %s at %d\n", MD->getNameAsString().c_str(),
359 (int)Index[GD]));
Mike Stump375faa82009-10-28 00:35:46 +0000360 if (MD->isPure())
Anders Carlssond420a312009-11-26 19:32:45 +0000361 PureVirtualMethods.insert(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000362 if (MorallyVirtual) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000363 VCallOffset[GD] = Offset/8;
364 Index_t &idx = VCall[GD];
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000365 // Allocate the first one, after that, we reuse the previous one.
366 if (idx == 0) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000367 NonVirtualOffset[GD] = CurrentVBaseOffset/8 - Offset/8;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000368 idx = VCalls.size()+1;
369 VCalls.push_back(0);
Mike Stump75ce5732009-10-31 20:06:59 +0000370 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpc5a332c2009-11-13 23:45:53 +0000371 MD->getNameAsString().c_str(), (int)-VCalls.size()-3, 0));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000372 }
373 }
374 }
375
376 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000377 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000378 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000379 ++mi) {
380 const CXXMethodDecl *MD = *mi;
381 if (!MD->isVirtual())
382 continue;
383
384 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
385 // For destructors, add both the complete and the deleting destructor
386 // to the vtable.
387 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000388 CurrentVBaseOffset);
Eli Friedman03aa2f12009-11-30 01:19:33 +0000389 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
390 CurrentVBaseOffset);
391 } else
392 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssonfb4dda42009-11-13 17:08:56 +0000393 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000394 }
395
396 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
397 const CXXRecordDecl *PrimaryBase,
398 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000399 int64_t Offset, int64_t CurrentVBaseOffset,
400 Path_t *Path) {
Mike Stump37dbe962009-10-15 02:04:03 +0000401 Path->push_back(std::make_pair(RD, Offset));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000402 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
403 e = RD->bases_end(); i != e; ++i) {
404 if (i->isVirtual())
405 continue;
406 const CXXRecordDecl *Base =
407 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
408 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
409 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
410 StartNewTable();
Mike Stump653d0b92009-11-13 02:13:54 +0000411 GenerateVtableForBase(Base, o, MorallyVirtual, false,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000412 CurrentVBaseOffset, Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000413 }
414 }
Mike Stump37dbe962009-10-15 02:04:03 +0000415 Path->pop_back();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000416 }
417
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000418// #define D(X) do { X; } while (0)
419#define D(X)
420
421 void insertVCalls(int InsertionPoint) {
422 llvm::Constant *e = 0;
Mike Stump75ce5732009-10-31 20:06:59 +0000423 D1(printf("============= combining vbase/vcall\n"));
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000424 D(VCalls.insert(VCalls.begin(), 673));
425 D(VCalls.push_back(672));
Mike Stump8bccbfd2009-10-15 09:30:16 +0000426 methods.insert(methods.begin() + InsertionPoint, VCalls.size(), e);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000427 // The vcalls come first...
428 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
429 e = VCalls.rend();
430 i != e; ++i)
431 methods[InsertionPoint++] = wrap((0?600:0) + *i);
432 VCalls.clear();
Mike Stump9f23a142009-11-10 02:30:51 +0000433 VCall.clear();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000434 }
435
Mike Stump559387f2009-11-13 23:13:20 +0000436 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
437 Index_t AddressPoint) {
438 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
439 RD->getNameAsCString(), Class->getNameAsCString(),
440 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stumpcd2b8212009-11-19 20:52:19 +0000441 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump559387f2009-11-13 23:13:20 +0000442
443 // Now also add the address point for all our primary bases.
444 while (1) {
445 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
446 RD = Layout.getPrimaryBase();
447 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
448 // FIXME: Double check this.
449 if (RD == 0)
450 break;
451 if (PrimaryBaseWasVirtual &&
452 BLayout.getVBaseClassOffset(RD) != Offset)
453 break;
454 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
455 RD->getNameAsCString(), Class->getNameAsCString(),
456 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stumpcd2b8212009-11-19 20:52:19 +0000457 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Mike Stump559387f2009-11-13 23:13:20 +0000458 }
459 }
460
461
Mike Stump75ce5732009-10-31 20:06:59 +0000462 Index_t end(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
463 const CXXRecordDecl *PrimaryBase, bool PrimaryBaseWasVirtual,
464 bool MorallyVirtual, int64_t Offset, bool ForVirtualBase,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000465 int64_t CurrentVBaseOffset,
Mike Stump75ce5732009-10-31 20:06:59 +0000466 Path_t *Path) {
Mike Stump37dbe962009-10-15 02:04:03 +0000467 bool alloc = false;
468 if (Path == 0) {
469 alloc = true;
470 Path = new Path_t;
471 }
472
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000473 StartNewTable();
474 extra = 0;
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000475 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
476 int VCallInsertionPoint = methods.size();
477 if (!DeferVCalls) {
478 insertVCalls(VCallInsertionPoint);
Mike Stump8bccbfd2009-10-15 09:30:16 +0000479 } else
480 // FIXME: just for extra, or for all uses of VCalls.size post this?
481 extra = -VCalls.size();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000482
Mike Stump653d0b92009-11-13 02:13:54 +0000483 methods.push_back(wrap(-((Offset-LayoutOffset)/8)));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000484 methods.push_back(rtti);
485 Index_t AddressPoint = methods.size();
486
Anders Carlssoncdf18982009-12-04 02:08:24 +0000487 assert(submethods.size() == Methods.size() && "Method size mismatch!");
488
Anders Carlsson495634e2009-12-04 02:39:04 +0000489 AppendMethods();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000490
491 // and then the non-virtual bases.
492 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000493 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000494
495 if (ForVirtualBase) {
Mike Stump2cefe382009-11-12 20:47:57 +0000496 // FIXME: We're adding to VCalls in callers, we need to do the overrides
497 // in the inner part, so that we know the complete set of vcalls during
498 // the build and don't have to insert into methods. Saving out the
499 // AddressPoint here, would need to be fixed, if we didn't do that. Also
500 // retroactively adding vcalls for overrides later wind up in the wrong
501 // place, the vcall slot has to be alloted during the walk of the base
502 // when the function is first introduces.
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000503 AddressPoint += VCalls.size();
Mike Stump2cefe382009-11-12 20:47:57 +0000504 insertVCalls(VCallInsertionPoint);
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000505 }
506
Mike Stump559387f2009-11-13 23:13:20 +0000507 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump2cefe382009-11-12 20:47:57 +0000508
Mike Stump37dbe962009-10-15 02:04:03 +0000509 if (alloc) {
510 delete Path;
511 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000512 return AddressPoint;
513 }
514
Mike Stump75ce5732009-10-31 20:06:59 +0000515 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
516 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000517 int64_t CurrentVBaseOffset) {
Mike Stump75ce5732009-10-31 20:06:59 +0000518 if (!RD->isDynamicClass())
519 return;
520
521 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
522 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
523 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
524
525 // vtables are composed from the chain of primaries.
526 if (PrimaryBase) {
527 D1(printf(" doing primaries for %s most derived %s\n",
528 RD->getNameAsCString(), Class->getNameAsCString()));
529
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000530 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
531 if (PrimaryBaseWasVirtual)
532 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
533
Mike Stump75ce5732009-10-31 20:06:59 +0000534 if (!PrimaryBaseWasVirtual)
535 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000536 updateVBIndex, current_vbindex, BaseCurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000537 }
538
539 D1(printf(" doing vcall entries for %s most derived %s\n",
540 RD->getNameAsCString(), Class->getNameAsCString()));
541
542 // And add the virtuals for the class to the primary vtable.
Eli Friedman03aa2f12009-11-30 01:19:33 +0000543 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000544 }
545
546 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
547 bool updateVBIndex, Index_t current_vbindex,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000548 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000549 bool bottom) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000550 if (!RD->isDynamicClass())
551 return;
552
553 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
554 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
555 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
556
557 // vtables are composed from the chain of primaries.
558 if (PrimaryBase) {
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000559 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
560 if (PrimaryBaseWasVirtual) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000561 IndirectPrimary.insert(PrimaryBase);
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000562 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
563 }
Mike Stump75ce5732009-10-31 20:06:59 +0000564
565 D1(printf(" doing primaries for %s most derived %s\n",
566 RD->getNameAsCString(), Class->getNameAsCString()));
567
568 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000569 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000570 BaseCurrentVBaseOffset, false);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000571 }
572
Mike Stump75ce5732009-10-31 20:06:59 +0000573 D1(printf(" doing vbase entries for %s most derived %s\n",
574 RD->getNameAsCString(), Class->getNameAsCString()));
575 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
576
577 if (RDisVirtualBase || bottom) {
578 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman03aa2f12009-11-30 01:19:33 +0000579 CurrentVBaseOffset);
Mike Stump75ce5732009-10-31 20:06:59 +0000580 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000581 }
582
Mike Stump653d0b92009-11-13 02:13:54 +0000583 int64_t GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
584 bool MorallyVirtual = false,
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000585 bool ForVirtualBase = false,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000586 int CurrentVBaseOffset = 0,
Mike Stump37dbe962009-10-15 02:04:03 +0000587 Path_t *Path = 0) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000588 if (!RD->isDynamicClass())
589 return 0;
590
Mike Stumpfa818082009-11-13 02:35:38 +0000591 // Construction vtable don't need parts that have no virtual bases and
592 // aren't morally virtual.
593 if ((LayoutClass != Class) && RD->getNumVBases() == 0 && !MorallyVirtual)
594 return 0;
595
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000596 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
597 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
598 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
599
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000600 extra = 0;
Mike Stump75ce5732009-10-31 20:06:59 +0000601 D1(printf("building entries for base %s most derived %s\n",
602 RD->getNameAsCString(), Class->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000603
Mike Stump75ce5732009-10-31 20:06:59 +0000604 if (ForVirtualBase)
605 extra = VCalls.size();
606
607 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0, ForVirtualBase,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000608 CurrentVBaseOffset, true);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000609
610 if (Path)
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000611 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000612
Mike Stump75ce5732009-10-31 20:06:59 +0000613 return end(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual, MorallyVirtual,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000614 Offset, ForVirtualBase, CurrentVBaseOffset, Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000615 }
616
617 void GenerateVtableForVBases(const CXXRecordDecl *RD,
618 int64_t Offset = 0,
Mike Stump37dbe962009-10-15 02:04:03 +0000619 Path_t *Path = 0) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000620 bool alloc = false;
621 if (Path == 0) {
622 alloc = true;
Mike Stump37dbe962009-10-15 02:04:03 +0000623 Path = new Path_t;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000624 }
625 // FIXME: We also need to override using all paths to a virtual base,
626 // right now, we just process the first path
627 Path->push_back(std::make_pair(RD, Offset));
628 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
629 e = RD->bases_end(); i != e; ++i) {
630 const CXXRecordDecl *Base =
631 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
632 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
633 // Mark it so we don't output it twice.
634 IndirectPrimary.insert(Base);
635 StartNewTable();
Mike Stumpb21c4ee2009-10-14 18:14:51 +0000636 VCall.clear();
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000637 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000638 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump75ce5732009-10-31 20:06:59 +0000639 D1(printf("vtable %s virtual base %s\n",
640 Class->getNameAsCString(), Base->getNameAsCString()));
Mike Stump653d0b92009-11-13 02:13:54 +0000641 GenerateVtableForBase(Base, BaseOffset, true, true, CurrentVBaseOffset,
Mike Stumpcd6f9ed2009-11-06 23:27:42 +0000642 Path);
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000643 }
Mike Stump2cefe382009-11-12 20:47:57 +0000644 int64_t BaseOffset;
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000645 if (i->isVirtual())
646 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump2cefe382009-11-12 20:47:57 +0000647 else {
648 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
649 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
650 }
651
Mike Stump37dbe962009-10-15 02:04:03 +0000652 if (Base->getNumVBases()) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000653 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump37dbe962009-10-15 02:04:03 +0000654 }
Anders Carlsson2bb27f52009-10-11 22:13:54 +0000655 }
656 Path->pop_back();
657 if (alloc)
658 delete Path;
659 }
660};
Anders Carlssonca1bf682009-12-03 01:54:02 +0000661} // end anonymous namespace
662
Anders Carlsson657f1392009-12-03 02:32:59 +0000663/// TypeConversionRequiresAdjustment - Returns whether conversion from a
664/// derived type to a base type requires adjustment.
665static bool
666TypeConversionRequiresAdjustment(ASTContext &Ctx,
667 const CXXRecordDecl *DerivedDecl,
668 const CXXRecordDecl *BaseDecl) {
669 CXXBasePaths Paths(/*FindAmbiguities=*/false,
670 /*RecordPaths=*/true, /*DetectVirtual=*/true);
671 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
672 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
673 assert(false && "Class must be derived from the passed in base class!");
674 return false;
675 }
676
677 // If we found a virtual base we always want to require adjustment.
678 if (Paths.getDetectedVirtual())
679 return true;
680
681 const CXXBasePath &Path = Paths.front();
682
683 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
684 const CXXBasePathElement &Element = Path[Start];
685
686 // Check the base class offset.
687 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
688
689 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
690 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
691
692 if (Layout.getBaseClassOffset(Base) != 0) {
693 // This requires an adjustment.
694 return true;
695 }
696 }
697
698 return false;
699}
700
701static bool
702TypeConversionRequiresAdjustment(ASTContext &Ctx,
703 QualType DerivedType, QualType BaseType) {
704 // Canonicalize the types.
705 QualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
706 QualType CanBaseType = Ctx.getCanonicalType(BaseType);
707
708 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
709 "Types must have same type class!");
710
711 if (CanDerivedType == CanBaseType) {
712 // No adjustment needed.
713 return false;
714 }
715
716 if (const ReferenceType *RT = dyn_cast<ReferenceType>(CanDerivedType)) {
717 CanDerivedType = RT->getPointeeType();
718 CanBaseType = cast<ReferenceType>(CanBaseType)->getPointeeType();
719 } else if (const PointerType *PT = dyn_cast<PointerType>(CanDerivedType)) {
720 CanDerivedType = PT->getPointeeType();
721 CanBaseType = cast<PointerType>(CanBaseType)->getPointeeType();
722 } else {
723 assert(false && "Unexpected return type!");
724 }
725
726 if (CanDerivedType == CanBaseType) {
727 // No adjustment needed.
728 return false;
729 }
730
731 const CXXRecordDecl *DerivedDecl =
Anders Carlssondabfa3c2009-12-03 03:28:24 +0000732 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
Anders Carlsson657f1392009-12-03 02:32:59 +0000733
734 const CXXRecordDecl *BaseDecl =
735 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
736
737 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
738}
739
Anders Carlssonca1bf682009-12-03 01:54:02 +0000740bool VtableBuilder::OverrideMethod(GlobalDecl GD, llvm::Constant *m,
741 bool MorallyVirtual, Index_t OverrideOffset,
742 Index_t Offset, int64_t CurrentVBaseOffset) {
743 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
744
745 const bool isPure = MD->isPure();
746 typedef CXXMethodDecl::method_iterator meth_iter;
747 // FIXME: Should OverrideOffset's be Offset?
748
749 // FIXME: Don't like the nested loops. For very large inheritance
750 // heirarchies we could have a table on the side with the final overridder
751 // and just replace each instance of an overridden method once. Would be
752 // nice to measure the cost/benefit on real code.
753
754 for (meth_iter mi = MD->begin_overridden_methods(),
755 e = MD->end_overridden_methods();
756 mi != e; ++mi) {
757 GlobalDecl OGD;
758
759 const CXXMethodDecl *OMD = *mi;
760 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
761 OGD = GlobalDecl(DD, GD.getDtorType());
762 else
763 OGD = OMD;
764
765 llvm::Constant *om;
766 om = WrapAddrOf(OGD);
767 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
768
769 for (Index_t i = 0, e = submethods.size();
770 i != e; ++i) {
771 // FIXME: begin_overridden_methods might be too lax, covariance */
772 if (submethods[i] != om)
773 continue;
Anders Carlsson657f1392009-12-03 02:32:59 +0000774
775 QualType ReturnType =
776 MD->getType()->getAs<FunctionType>()->getResultType();
777 QualType OverriddenReturnType =
778 OMD->getType()->getAs<FunctionType>()->getResultType();
779
780 // Check if we need a return type adjustment.
781 if (TypeConversionRequiresAdjustment(CGM.getContext(), ReturnType,
782 OverriddenReturnType)) {
Anders Carlssonc521f952009-12-04 02:22:02 +0000783 CanQualType &BaseReturnType = BaseReturnTypes[i];
Anders Carlsson2ca285f2009-12-03 02:22:59 +0000784
Anders Carlsson657f1392009-12-03 02:32:59 +0000785 // Get the canonical return type.
786 CanQualType CanReturnType =
787 CGM.getContext().getCanonicalType(ReturnType);
788
789 // Insert the base return type.
Anders Carlssonc521f952009-12-04 02:22:02 +0000790 if (BaseReturnType.isNull())
791 BaseReturnType =
Anders Carlsson657f1392009-12-03 02:32:59 +0000792 CGM.getContext().getCanonicalType(OverriddenReturnType);
Anders Carlssonca1bf682009-12-03 01:54:02 +0000793 }
Anders Carlsson657f1392009-12-03 02:32:59 +0000794
Anders Carlssoncdf18982009-12-04 02:08:24 +0000795 Methods.OverrideMethod(OGD, GD);
796
Anders Carlssonca1bf682009-12-03 01:54:02 +0000797 Index[GD] = i;
798 submethods[i] = m;
799 if (isPure)
800 PureVirtualMethods.insert(GD);
801 PureVirtualMethods.erase(OGD);
Anders Carlsson4c837d22009-12-04 02:26:15 +0000802 ThisAdjustments.erase(i);
Anders Carlssonca1bf682009-12-03 01:54:02 +0000803 if (MorallyVirtual || VCall.count(OGD)) {
804 Index_t &idx = VCall[OGD];
805 if (idx == 0) {
806 NonVirtualOffset[GD] = -OverrideOffset/8 + CurrentVBaseOffset/8;
807 VCallOffset[GD] = OverrideOffset/8;
808 idx = VCalls.size()+1;
809 VCalls.push_back(0);
810 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
811 MD->getNameAsString().c_str(), (int)-idx-3,
812 (int)VCalls[idx-1], Class->getNameAsCString()));
813 } else {
814 NonVirtualOffset[GD] = NonVirtualOffset[OGD];
815 VCallOffset[GD] = VCallOffset[OGD];
816 VCalls[idx-1] = -VCallOffset[OGD] + OverrideOffset/8;
817 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
818 MD->getNameAsString().c_str(), (int)-idx-3,
819 (int)VCalls[idx-1], Class->getNameAsCString()));
820 }
821 VCall[GD] = idx;
822 int64_t NonVirtualAdjustment = NonVirtualOffset[GD];
823 int64_t VirtualAdjustment =
824 -((idx + extra + 2) * LLVMPointerWidth / 8);
825
826 // Optimize out virtual adjustments of 0.
827 if (VCalls[idx-1] == 0)
828 VirtualAdjustment = 0;
829
830 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
831 VirtualAdjustment);
832
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000833 if (!isPure && !ThisAdjustment.isEmpty())
Anders Carlsson4c837d22009-12-04 02:26:15 +0000834 ThisAdjustments[i] = ThisAdjustment;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000835 return true;
836 }
837
838 // FIXME: finish off
839 int64_t NonVirtualAdjustment = VCallOffset[OGD] - OverrideOffset/8;
840
Anders Carlsson2ca285f2009-12-03 02:22:59 +0000841 if (NonVirtualAdjustment) {
Anders Carlssonca1bf682009-12-03 01:54:02 +0000842 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
843
Anders Carlsson2bd3c0f2009-12-03 01:58:20 +0000844 if (!isPure)
Anders Carlsson4c837d22009-12-04 02:26:15 +0000845 ThisAdjustments[i] = ThisAdjustment;
Anders Carlssonca1bf682009-12-03 01:54:02 +0000846 }
847 return true;
848 }
849 }
850
851 return false;
Anders Carlssond59885022009-11-27 22:21:51 +0000852}
853
Anders Carlsson495634e2009-12-04 02:39:04 +0000854void VtableBuilder::AppendMethods() {
855 InstallThunks();
Anders Carlsson86809cd2009-12-04 02:43:50 +0000856
857 for (unsigned i = 0, e = Methods.size(); i != e; ++i) {
858 GlobalDecl GD = Methods[i];
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000859 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
860
861 // Get the 'this' pointer adjustment.
Anders Carlsson86809cd2009-12-04 02:43:50 +0000862 ThunkAdjustment ThisAdjustment = ThisAdjustments.lookup(i);
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000863
864 // Construct the return type adjustment.
865 ThunkAdjustment ReturnAdjustment;
866
867 QualType BaseReturnType = BaseReturnTypes.lookup(i);
868 if (!BaseReturnType.isNull() && !MD->isPure()) {
869 QualType DerivedType =
870 MD->getType()->getAs<FunctionType>()->getResultType();
871
872 int64_t NonVirtualAdjustment =
873 getNVOffset(BaseReturnType, DerivedType) / 8;
874
875 int64_t VirtualAdjustment =
876 getVbaseOffset(BaseReturnType, DerivedType);
877
878 ReturnAdjustment = ThunkAdjustment(NonVirtualAdjustment,
879 VirtualAdjustment);
880 }
881
882 if (!ReturnAdjustment.isEmpty()) {
883 // Build a covariant thunk.
884 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
885 submethods[i] = CGM.BuildCovariantThunk(MD, Extern, Adjustment);
886 } else if (!ThisAdjustment.isEmpty()) {
887 // Build a "regular" thunk.
Anders Carlsson86809cd2009-12-04 02:43:50 +0000888 submethods[i] = CGM.BuildThunk(GD, Extern, ThisAdjustment);
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000889 }
Anders Carlsson86809cd2009-12-04 02:43:50 +0000890 }
891
892 ThisAdjustments.clear();
Anders Carlsson5b3ea9b2009-12-04 02:52:22 +0000893 BaseReturnTypes.clear();
Anders Carlsson86809cd2009-12-04 02:43:50 +0000894
Anders Carlsson495634e2009-12-04 02:39:04 +0000895 D1(printf("============= combining methods\n"));
896 methods.insert(methods.end(), submethods.begin(), submethods.end());
897
898 Methods.clear();
899 submethods.clear();
900}
901
Anders Carlssonf942ee02009-11-27 20:47:55 +0000902void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
903
904 // Itanium C++ ABI 2.5.2:
905 // The order of the virtual function pointers in a virtual table is the
906 // order of declaration of the corresponding member functions in the class.
907 //
908 // There is an entry for any virtual function declared in a class,
909 // whether it is a new function or overrides a base class function,
910 // unless it overrides a function from the primary base, and conversion
911 // between their return types does not require an adjustment.
912
913 int64_t CurrentIndex = 0;
914
915 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
916 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
917
918 if (PrimaryBase) {
Anders Carlssonc920fa22009-11-30 19:43:26 +0000919 assert(PrimaryBase->isDefinition() &&
920 "Should have the definition decl of the primary base!");
Anders Carlssonf942ee02009-11-27 20:47:55 +0000921
922 // Since the record decl shares its vtable pointer with the primary base
923 // we need to start counting at the end of the primary base's vtable.
924 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
925 }
926
927 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
928
929 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
930 e = RD->method_end(); i != e; ++i) {
931 const CXXMethodDecl *MD = *i;
932
933 // We only want virtual methods.
934 if (!MD->isVirtual())
935 continue;
936
937 bool ShouldAddEntryForMethod = true;
938
939 // Check if this method overrides a method in the primary base.
940 for (CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
941 e = MD->end_overridden_methods(); i != e; ++i) {
942 const CXXMethodDecl *OverriddenMD = *i;
943 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
944 assert(OverriddenMD->isCanonicalDecl() &&
945 "Should have the canonical decl of the overridden RD!");
946
947 if (OverriddenRD == PrimaryBase) {
948 // Check if converting from the return type of the method to the
949 // return type of the overridden method requires conversion.
950 QualType ReturnType =
951 MD->getType()->getAs<FunctionType>()->getResultType();
952 QualType OverriddenReturnType =
953 OverriddenMD->getType()->getAs<FunctionType>()->getResultType();
954
955 if (!TypeConversionRequiresAdjustment(CGM.getContext(),
956 ReturnType, OverriddenReturnType)) {
957 // This index is shared between the index in the vtable of the primary
958 // base class.
959 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
960 const CXXDestructorDecl *OverriddenDD =
961 cast<CXXDestructorDecl>(OverriddenMD);
962
963 // Add both the complete and deleting entries.
964 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
965 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
966 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
967 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
968 } else {
969 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
970 }
971
972 // We don't need to add an entry for this method.
973 ShouldAddEntryForMethod = false;
974 break;
975 }
976 }
977 }
978
979 if (!ShouldAddEntryForMethod)
980 continue;
981
982 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
983 if (MD->isImplicit()) {
984 assert(!ImplicitVirtualDtor &&
985 "Did already see an implicit virtual dtor!");
986 ImplicitVirtualDtor = DD;
987 continue;
988 }
989
990 // Add the complete dtor.
991 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
992
993 // Add the deleting dtor.
994 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
995 } else {
996 // Add the entry.
997 MethodVtableIndices[MD] = CurrentIndex++;
998 }
999 }
1000
1001 if (ImplicitVirtualDtor) {
1002 // Itanium C++ ABI 2.5.2:
1003 // If a class has an implicitly-defined virtual destructor,
1004 // its entries come after the declared virtual function pointers.
1005
1006 // Add the complete dtor.
1007 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
1008 CurrentIndex++;
1009
1010 // Add the deleting dtor.
1011 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
1012 CurrentIndex++;
1013 }
1014
1015 NumVirtualFunctionPointers[RD] = CurrentIndex;
1016}
1017
1018uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
1019 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1020 NumVirtualFunctionPointers.find(RD);
1021 if (I != NumVirtualFunctionPointers.end())
1022 return I->second;
1023
1024 ComputeMethodVtableIndices(RD);
1025
1026 I = NumVirtualFunctionPointers.find(RD);
1027 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
1028 return I->second;
1029}
1030
1031uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001032 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001033 if (I != MethodVtableIndices.end())
1034 return I->second;
1035
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001036 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssonf942ee02009-11-27 20:47:55 +00001037
1038 ComputeMethodVtableIndices(RD);
1039
Anders Carlssonfb4dda42009-11-13 17:08:56 +00001040 I = MethodVtableIndices.find(GD);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001041 assert(I != MethodVtableIndices.end() && "Did not find index!");
1042 return I->second;
1043}
1044
1045int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
1046 const CXXRecordDecl *VBase) {
1047 ClassPairTy ClassPair(RD, VBase);
1048
1049 VirtualBaseClassIndiciesTy::iterator I =
1050 VirtualBaseClassIndicies.find(ClassPair);
1051 if (I != VirtualBaseClassIndicies.end())
1052 return I->second;
1053
1054 std::vector<llvm::Constant *> methods;
1055 // FIXME: This seems expensive. Can we do a partial job to get
1056 // just this data.
Mike Stump653d0b92009-11-13 02:13:54 +00001057 VtableBuilder b(methods, RD, RD, 0, CGM);
Mike Stump75ce5732009-10-31 20:06:59 +00001058 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001059 b.GenerateVtableForBase(RD);
1060 b.GenerateVtableForVBases(RD);
1061
1062 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1063 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
1064 // Insert all types.
1065 ClassPairTy ClassPair(RD, I->first);
1066
1067 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
1068 }
1069
1070 I = VirtualBaseClassIndicies.find(ClassPair);
1071 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
1072
1073 return I->second;
1074}
1075
Mike Stump2cefe382009-11-12 20:47:57 +00001076llvm::Constant *CodeGenModule::GenerateVtable(const CXXRecordDecl *LayoutClass,
1077 const CXXRecordDecl *RD,
Mike Stumpeac45592009-11-11 20:26:26 +00001078 uint64_t Offset) {
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001079 llvm::SmallString<256> OutName;
Mike Stump2cefe382009-11-12 20:47:57 +00001080 if (LayoutClass != RD)
Daniel Dunbare128dd12009-11-21 09:06:22 +00001081 getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset/8, RD, OutName);
Mike Stumpeac45592009-11-11 20:26:26 +00001082 else
Daniel Dunbare128dd12009-11-21 09:06:22 +00001083 getMangleContext().mangleCXXVtable(RD, OutName);
1084 llvm::StringRef Name = OutName.str();
Benjamin Kramerbb0a07b2009-10-11 22:57:54 +00001085
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001086 std::vector<llvm::Constant *> methods;
1087 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1088 int64_t AddressPoint;
1089
Mike Stumpaa51ad62009-11-19 04:04:36 +00001090 llvm::GlobalVariable *GV = getModule().getGlobalVariable(Name);
Mike Stumpcd2b8212009-11-19 20:52:19 +00001091 if (GV && AddressPoints[LayoutClass] && !GV->isDeclaration()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001092 AddressPoint=(*(*(AddressPoints[LayoutClass]))[RD])[std::make_pair(RD,
1093 Offset)];
Mike Stumpcd2b8212009-11-19 20:52:19 +00001094 // FIXME: We can never have 0 address point. Do this for now so gepping
1095 // retains the same structure. Later, we'll just assert.
1096 if (AddressPoint == 0)
1097 AddressPoint = 1;
1098 } else {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001099 VtableBuilder b(methods, RD, LayoutClass, Offset, *this);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001100
Mike Stumpaa51ad62009-11-19 04:04:36 +00001101 D1(printf("vtable %s\n", RD->getNameAsCString()));
1102 // First comes the vtables for all the non-virtual bases...
1103 AddressPoint = b.GenerateVtableForBase(RD, Offset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001104
Mike Stumpaa51ad62009-11-19 04:04:36 +00001105 // then the vtables for all the virtual bases.
1106 b.GenerateVtableForVBases(RD, Offset);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001107
Mike Stumpaa51ad62009-11-19 04:04:36 +00001108 bool CreateDefinition = true;
1109 if (LayoutClass != RD)
1110 CreateDefinition = true;
1111 else {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001112 const ASTRecordLayout &Layout =
1113 getContext().getASTRecordLayout(LayoutClass);
1114
1115 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001116 if (!KeyFunction->getBody()) {
1117 // If there is a KeyFunction, and it isn't defined, just build a
1118 // reference to the vtable.
1119 CreateDefinition = false;
1120 }
1121 }
1122 }
1123
1124 llvm::Constant *C = 0;
1125 llvm::Type *type = Ptr8Ty;
1126 llvm::GlobalVariable::LinkageTypes linktype
1127 = llvm::GlobalValue::ExternalLinkage;
1128 if (CreateDefinition) {
1129 llvm::ArrayType *ntype = llvm::ArrayType::get(Ptr8Ty, methods.size());
1130 C = llvm::ConstantArray::get(ntype, methods);
1131 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
1132 if (LayoutClass->isInAnonymousNamespace())
1133 linktype = llvm::GlobalValue::InternalLinkage;
1134 type = ntype;
1135 }
1136 llvm::GlobalVariable *OGV = GV;
1137 GV = new llvm::GlobalVariable(getModule(), type, true, linktype, C, Name);
1138 if (OGV) {
1139 GV->takeName(OGV);
1140 llvm::Constant *NewPtr = llvm::ConstantExpr::getBitCast(GV,
1141 OGV->getType());
1142 OGV->replaceAllUsesWith(NewPtr);
1143 OGV->eraseFromParent();
1144 }
1145 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1146 if (Hidden)
1147 GV->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1148 }
Mike Stumpc0f632d2009-11-18 04:00:48 +00001149 llvm::Constant *vtable = llvm::ConstantExpr::getBitCast(GV, Ptr8Ty);
Mike Stumpd846d082009-11-10 07:44:33 +00001150 llvm::Constant *AddressPointC;
1151 uint32_t LLVMPointerWidth = getContext().Target.getPointerWidth(0);
1152 AddressPointC = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1153 AddressPoint*LLVMPointerWidth/8);
Mike Stump2cefe382009-11-12 20:47:57 +00001154 vtable = llvm::ConstantExpr::getInBoundsGetElementPtr(vtable, &AddressPointC,
1155 1);
Mike Stumpd846d082009-11-10 07:44:33 +00001156
Mike Stumpcd2b8212009-11-19 20:52:19 +00001157 assert(vtable->getType() == Ptr8Ty);
Anders Carlsson2bb27f52009-10-11 22:13:54 +00001158 return vtable;
1159}
Mike Stump9f23a142009-11-10 02:30:51 +00001160
Mike Stumpae1b85d2009-12-02 19:07:44 +00001161namespace {
Mike Stump9f23a142009-11-10 02:30:51 +00001162class VTTBuilder {
1163 /// Inits - The list of values built for the VTT.
1164 std::vector<llvm::Constant *> &Inits;
1165 /// Class - The most derived class that this vtable is being built for.
1166 const CXXRecordDecl *Class;
1167 CodeGenModule &CGM; // Per-module state.
Mike Stump8b2d2d02009-11-11 00:35:07 +00001168 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001169 /// BLayout - Layout for the most derived class that this vtable is being
1170 /// built for.
1171 const ASTRecordLayout &BLayout;
Mike Stump83066c82009-11-13 01:54:23 +00001172 CodeGenModule::AddrMap_t &AddressPoints;
Mike Stump2cefe382009-11-12 20:47:57 +00001173 // vtbl - A pointer to the vtable for Class.
1174 llvm::Constant *ClassVtbl;
1175 llvm::LLVMContext &VMContext;
Mike Stump9f23a142009-11-10 02:30:51 +00001176
Mike Stump8677bc22009-11-12 22:56:32 +00001177 /// BuildVtablePtr - Build up a referene to the given secondary vtable
Mike Stump83066c82009-11-13 01:54:23 +00001178 llvm::Constant *BuildVtablePtr(llvm::Constant *vtbl,
1179 const CXXRecordDecl *VtblClass,
1180 const CXXRecordDecl *RD,
Mike Stump8677bc22009-11-12 22:56:32 +00001181 uint64_t Offset) {
1182 int64_t AddressPoint;
Mike Stump83066c82009-11-13 01:54:23 +00001183 AddressPoint = (*AddressPoints[VtblClass])[std::make_pair(RD, Offset)];
Mike Stump2b34bc52009-11-12 23:36:21 +00001184 // FIXME: We can never have 0 address point. Do this for now so gepping
Mike Stumpcd2b8212009-11-19 20:52:19 +00001185 // retains the same structure. Later we'll just assert.
Mike Stump2b34bc52009-11-12 23:36:21 +00001186 if (AddressPoint == 0)
1187 AddressPoint = 1;
Mike Stump83066c82009-11-13 01:54:23 +00001188 D1(printf("XXX address point for %s in %s layout %s at offset %d was %d\n",
1189 RD->getNameAsCString(), VtblClass->getNameAsCString(),
1190 Class->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump8677bc22009-11-12 22:56:32 +00001191 uint32_t LLVMPointerWidth = CGM.getContext().Target.getPointerWidth(0);
1192 llvm::Constant *init;
1193 init = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1194 AddressPoint*LLVMPointerWidth/8);
1195 init = llvm::ConstantExpr::getInBoundsGetElementPtr(vtbl, &init, 1);
1196 return init;
1197 }
1198
Mike Stump2cefe382009-11-12 20:47:57 +00001199 /// Secondary - Add the secondary vtable pointers to Inits. Offset is the
1200 /// current offset in bits to the object we're working on.
Mike Stump8677bc22009-11-12 22:56:32 +00001201 void Secondary(const CXXRecordDecl *RD, llvm::Constant *vtbl,
Mike Stump83066c82009-11-13 01:54:23 +00001202 const CXXRecordDecl *VtblClass, uint64_t Offset=0,
1203 bool MorallyVirtual=false) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001204 if (RD->getNumVBases() == 0 && ! MorallyVirtual)
1205 return;
1206
1207 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1208 e = RD->bases_end(); i != e; ++i) {
1209 const CXXRecordDecl *Base =
1210 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1211 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1212 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1213 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1214 bool NonVirtualPrimaryBase;
1215 NonVirtualPrimaryBase = !PrimaryBaseWasVirtual && Base == PrimaryBase;
1216 bool BaseMorallyVirtual = MorallyVirtual | i->isVirtual();
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001217 uint64_t BaseOffset;
1218 if (!i->isVirtual()) {
1219 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1220 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1221 } else
1222 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump2b34bc52009-11-12 23:36:21 +00001223 llvm::Constant *subvtbl = vtbl;
Mike Stump83066c82009-11-13 01:54:23 +00001224 const CXXRecordDecl *subVtblClass = VtblClass;
Mike Stump8b2d2d02009-11-11 00:35:07 +00001225 if ((Base->getNumVBases() || BaseMorallyVirtual)
1226 && !NonVirtualPrimaryBase) {
1227 // FIXME: Slightly too many of these for __ZTT8test8_B2
Mike Stump8677bc22009-11-12 22:56:32 +00001228 llvm::Constant *init;
Mike Stump2b34bc52009-11-12 23:36:21 +00001229 if (BaseMorallyVirtual)
Mike Stump83066c82009-11-13 01:54:23 +00001230 init = BuildVtablePtr(vtbl, VtblClass, RD, Offset);
Mike Stump2b34bc52009-11-12 23:36:21 +00001231 else {
Mike Stump8677bc22009-11-12 22:56:32 +00001232 init = CGM.getVtableInfo().getCtorVtable(Class, Base, BaseOffset);
Mike Stump2b34bc52009-11-12 23:36:21 +00001233 subvtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump83066c82009-11-13 01:54:23 +00001234 subVtblClass = Base;
Mike Stump2b34bc52009-11-12 23:36:21 +00001235 }
Mike Stump8677bc22009-11-12 22:56:32 +00001236 Inits.push_back(init);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001237 }
Mike Stump83066c82009-11-13 01:54:23 +00001238 Secondary(Base, subvtbl, subVtblClass, BaseOffset, BaseMorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001239 }
1240 }
1241
Mike Stump2cefe382009-11-12 20:47:57 +00001242 /// BuiltVTT - Add the VTT to Inits. Offset is the offset in bits to the
1243 /// currnet object we're working on.
1244 void BuildVTT(const CXXRecordDecl *RD, uint64_t Offset, bool MorallyVirtual) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001245 if (RD->getNumVBases() == 0 && !MorallyVirtual)
1246 return;
1247
Mike Stump2cefe382009-11-12 20:47:57 +00001248 llvm::Constant *init;
Mike Stump83066c82009-11-13 01:54:23 +00001249 const CXXRecordDecl *VtblClass;
1250
Mike Stump8b2d2d02009-11-11 00:35:07 +00001251 // First comes the primary virtual table pointer...
Mike Stump83066c82009-11-13 01:54:23 +00001252 if (MorallyVirtual) {
1253 init = BuildVtablePtr(ClassVtbl, Class, RD, Offset);
1254 VtblClass = Class;
1255 } else {
Mike Stump2cefe382009-11-12 20:47:57 +00001256 init = CGM.getVtableInfo().getCtorVtable(Class, RD, Offset);
Mike Stump83066c82009-11-13 01:54:23 +00001257 VtblClass = RD;
1258 }
Mike Stump8677bc22009-11-12 22:56:32 +00001259 llvm::Constant *vtbl = dyn_cast<llvm::Constant>(init->getOperand(0));
Mike Stump2cefe382009-11-12 20:47:57 +00001260 Inits.push_back(init);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001261
1262 // then the secondary VTTs....
Mike Stump2cefe382009-11-12 20:47:57 +00001263 SecondaryVTTs(RD, Offset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001264
1265 // and last the secondary vtable pointers.
Mike Stump83066c82009-11-13 01:54:23 +00001266 Secondary(RD, vtbl, VtblClass, Offset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001267 }
1268
1269 /// SecondaryVTTs - Add the secondary VTTs to Inits. The secondary VTTs are
1270 /// built from each direct non-virtual proper base that requires a VTT in
1271 /// declaration order.
Mike Stump2cefe382009-11-12 20:47:57 +00001272 void SecondaryVTTs(const CXXRecordDecl *RD, uint64_t Offset=0,
1273 bool MorallyVirtual=false) {
Mike Stump8b2d2d02009-11-11 00:35:07 +00001274 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1275 e = RD->bases_end(); i != e; ++i) {
1276 const CXXRecordDecl *Base =
1277 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1278 if (i->isVirtual())
1279 continue;
Mike Stump2cefe382009-11-12 20:47:57 +00001280 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1281 uint64_t BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1282 BuildVTT(Base, BaseOffset, MorallyVirtual);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001283 }
1284 }
1285
1286 /// VirtualVTTs - Add the VTT for each proper virtual base in inheritance
1287 /// graph preorder.
1288 void VirtualVTTs(const CXXRecordDecl *RD) {
1289 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1290 e = RD->bases_end(); i != e; ++i) {
1291 const CXXRecordDecl *Base =
1292 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1293 if (i->isVirtual() && !SeenVBase.count(Base)) {
1294 SeenVBase.insert(Base);
Mike Stump2cefe382009-11-12 20:47:57 +00001295 uint64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
1296 BuildVTT(Base, BaseOffset, true);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001297 }
1298 VirtualVTTs(Base);
1299 }
1300 }
Mike Stump9f23a142009-11-10 02:30:51 +00001301public:
1302 VTTBuilder(std::vector<llvm::Constant *> &inits, const CXXRecordDecl *c,
Mike Stumpc7b9f5e2009-11-11 03:08:24 +00001303 CodeGenModule &cgm)
1304 : Inits(inits), Class(c), CGM(cgm),
Mike Stump2cefe382009-11-12 20:47:57 +00001305 BLayout(cgm.getContext().getASTRecordLayout(c)),
Mike Stump83066c82009-11-13 01:54:23 +00001306 AddressPoints(*cgm.AddressPoints[c]),
Mike Stump2cefe382009-11-12 20:47:57 +00001307 VMContext(cgm.getModule().getContext()) {
Mike Stumpd846d082009-11-10 07:44:33 +00001308
Mike Stump8b2d2d02009-11-11 00:35:07 +00001309 // First comes the primary virtual table pointer for the complete class...
Mike Stump2cefe382009-11-12 20:47:57 +00001310 ClassVtbl = CGM.getVtableInfo().getVtable(Class);
1311 Inits.push_back(ClassVtbl);
1312 ClassVtbl = dyn_cast<llvm::Constant>(ClassVtbl->getOperand(0));
1313
Mike Stump8b2d2d02009-11-11 00:35:07 +00001314 // then the secondary VTTs...
1315 SecondaryVTTs(Class);
1316
1317 // then the secondary vtable pointers...
Mike Stump83066c82009-11-13 01:54:23 +00001318 Secondary(Class, ClassVtbl, Class);
Mike Stump8b2d2d02009-11-11 00:35:07 +00001319
1320 // and last, the virtual VTTs.
1321 VirtualVTTs(Class);
Mike Stump9f23a142009-11-10 02:30:51 +00001322 }
1323};
Mike Stumpae1b85d2009-12-02 19:07:44 +00001324}
Mike Stump9f23a142009-11-10 02:30:51 +00001325
Mike Stumpd846d082009-11-10 07:44:33 +00001326llvm::Constant *CodeGenModule::GenerateVTT(const CXXRecordDecl *RD) {
Mike Stumpb4722212009-11-10 19:13:04 +00001327 // Only classes that have virtual bases need a VTT.
1328 if (RD->getNumVBases() == 0)
1329 return 0;
1330
Mike Stump9f23a142009-11-10 02:30:51 +00001331 llvm::SmallString<256> OutName;
Daniel Dunbare128dd12009-11-21 09:06:22 +00001332 getMangleContext().mangleCXXVTT(RD, OutName);
1333 llvm::StringRef Name = OutName.str();
Mike Stump9f23a142009-11-10 02:30:51 +00001334
1335 llvm::GlobalVariable::LinkageTypes linktype;
1336 linktype = llvm::GlobalValue::LinkOnceODRLinkage;
Mike Stumpaa51ad62009-11-19 04:04:36 +00001337 if (RD->isInAnonymousNamespace())
1338 linktype = llvm::GlobalValue::InternalLinkage;
Mike Stump9f23a142009-11-10 02:30:51 +00001339 std::vector<llvm::Constant *> inits;
1340 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1341
Mike Stump9f23a142009-11-10 02:30:51 +00001342 D1(printf("vtt %s\n", RD->getNameAsCString()));
1343
Mike Stump8b2d2d02009-11-11 00:35:07 +00001344 VTTBuilder b(inits, RD, *this);
1345
Mike Stump9f23a142009-11-10 02:30:51 +00001346 llvm::Constant *C;
1347 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, inits.size());
1348 C = llvm::ConstantArray::get(type, inits);
Mike Stumpc0f632d2009-11-18 04:00:48 +00001349 llvm::GlobalVariable *vtt = new llvm::GlobalVariable(getModule(), type, true,
Mike Stumpaa51ad62009-11-19 04:04:36 +00001350 linktype, C, Name);
Mike Stumpc0f632d2009-11-18 04:00:48 +00001351 bool Hidden = getDeclVisibilityMode(RD) == LangOptions::Hidden;
1352 if (Hidden)
1353 vtt->setVisibility(llvm::GlobalVariable::HiddenVisibility);
1354 return llvm::ConstantExpr::getBitCast(vtt, Ptr8Ty);
Mike Stump9f23a142009-11-10 02:30:51 +00001355}
Mike Stumpd846d082009-11-10 07:44:33 +00001356
Mike Stump1a139f82009-11-19 01:08:19 +00001357void CGVtableInfo::GenerateClassData(const CXXRecordDecl *RD) {
1358 Vtables[RD] = CGM.GenerateVtable(RD, RD);
Mike Stumpc01c2b82009-12-02 18:57:08 +00001359 CGM.GenerateRTTI(RD);
Mike Stump1a139f82009-11-19 01:08:19 +00001360 CGM.GenerateVTT(RD);
1361}
1362
Mike Stumpeac45592009-11-11 20:26:26 +00001363llvm::Constant *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Mike Stumpd846d082009-11-10 07:44:33 +00001364 llvm::Constant *&vtbl = Vtables[RD];
1365 if (vtbl)
1366 return vtbl;
Mike Stump2cefe382009-11-12 20:47:57 +00001367 vtbl = CGM.GenerateVtable(RD, RD);
Mike Stumpaa51ad62009-11-19 04:04:36 +00001368
1369 bool CreateDefinition = true;
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001370
1371 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1372 if (const CXXMethodDecl *KeyFunction = Layout.getKeyFunction()) {
Mike Stumpaa51ad62009-11-19 04:04:36 +00001373 if (!KeyFunction->getBody()) {
1374 // If there is a KeyFunction, and it isn't defined, just build a
1375 // reference to the vtable.
1376 CreateDefinition = false;
1377 }
1378 }
1379
1380 if (CreateDefinition) {
Mike Stumpc01c2b82009-12-02 18:57:08 +00001381 CGM.GenerateRTTI(RD);
Mike Stumpaa51ad62009-11-19 04:04:36 +00001382 CGM.GenerateVTT(RD);
1383 }
Mike Stumpd846d082009-11-10 07:44:33 +00001384 return vtbl;
1385}
Mike Stumpeac45592009-11-11 20:26:26 +00001386
Mike Stump2cefe382009-11-12 20:47:57 +00001387llvm::Constant *CGVtableInfo::getCtorVtable(const CXXRecordDecl *LayoutClass,
1388 const CXXRecordDecl *RD,
Mike Stumpeac45592009-11-11 20:26:26 +00001389 uint64_t Offset) {
Mike Stump2cefe382009-11-12 20:47:57 +00001390 return CGM.GenerateVtable(LayoutClass, RD, Offset);
Mike Stumpeac45592009-11-11 20:26:26 +00001391}
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001392
1393void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
1394 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1395 const CXXRecordDecl *RD = MD->getParent();
1396
1397 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1398
1399 // Get the key function.
1400 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
1401
1402 if (!KeyFunction) {
1403 // If there's no key function, we don't want to emit the vtable here.
1404 return;
1405 }
1406
1407 // Check if we have the key function.
1408 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
1409 return;
1410
1411 // If the key function is a destructor, we only want to emit the vtable once,
1412 // so do it for the complete destructor.
1413 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Complete)
1414 return;
1415
1416 // Emit the data.
1417 GenerateClassData(RD);
1418}
1419