blob: 7c28f006c9570a7662762d8fca1a2e41eb521777 [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;
Eli Friedmanb455f0e2009-12-07 23:56:34 +000029 typedef std::vector<std::pair<GlobalDecl,
30 std::pair<GlobalDecl, ThunkAdjustment> > >
31 SavedAdjustmentsVectorTy;
Anders Carlssondbd920c2009-10-11 22:13:54 +000032private:
Anders Carlsson15318f42009-12-04 16:19:30 +000033
Anders Carlssonc3a46ef2009-12-06 01:09:21 +000034 // VtableComponents - The components of the vtable being built.
35 typedef llvm::SmallVector<llvm::Constant *, 64> VtableComponentsVectorTy;
36 VtableComponentsVectorTy VtableComponents;
37
Eli Friedman152b5b12009-12-05 01:05:03 +000038 const bool BuildVtable;
39
Anders Carlssondbd920c2009-10-11 22:13:54 +000040 llvm::Type *Ptr8Ty;
Anders Carlssonac3f7bd2009-12-04 18:36:22 +000041
42 /// MostDerivedClass - The most derived class that this vtable is being
43 /// built for.
44 const CXXRecordDecl *MostDerivedClass;
45
Mike Stumpacfd1e52009-11-13 01:54:23 +000046 /// LayoutClass - The most derived class used for virtual base layout
47 /// information.
48 const CXXRecordDecl *LayoutClass;
Mike Stump4cde6262009-11-13 02:13:54 +000049 /// LayoutOffset - The offset for Class in LayoutClass.
50 uint64_t LayoutOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +000051 /// BLayout - Layout for the most derived class that this vtable is being
52 /// built for.
53 const ASTRecordLayout &BLayout;
54 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
55 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
56 llvm::Constant *rtti;
57 llvm::LLVMContext &VMContext;
58 CodeGenModule &CGM; // Per-module state.
Anders Carlsson0e881162009-12-04 03:46:21 +000059
Mike Stumpcf0b9cc2010-01-26 00:05:04 +000060 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCall;
Anders Carlssona0fdd912009-11-13 17:08:56 +000061 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stump9e7e3c62009-11-06 23:27:42 +000062 // This is the offset to the nearest virtual base
Mike Stumpcf0b9cc2010-01-26 00:05:04 +000063 llvm::DenseMap<const CXXMethodDecl *, Index_t> NonVirtualOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +000064 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stump94aff932009-10-27 23:46:47 +000065
Anders Carlsson6d4ccb72009-11-26 19:54:33 +000066 /// PureVirtualFunction - Points to __cxa_pure_virtual.
67 llvm::Constant *PureVirtualFn;
68
Anders Carlssonc7ab1a82009-12-04 02:01:07 +000069 /// VtableMethods - A data structure for keeping track of methods in a vtable.
70 /// Can add methods, override methods and iterate in vtable order.
71 class VtableMethods {
72 // MethodToIndexMap - Maps from a global decl to the index it has in the
73 // Methods vector.
74 llvm::DenseMap<GlobalDecl, uint64_t> MethodToIndexMap;
75
76 /// Methods - The methods, in vtable order.
77 typedef llvm::SmallVector<GlobalDecl, 16> MethodsVectorTy;
78 MethodsVectorTy Methods;
Eli Friedman72649ed2009-12-06 22:01:30 +000079 MethodsVectorTy OrigMethods;
Anders Carlssonc7ab1a82009-12-04 02:01:07 +000080
81 public:
82 /// AddMethod - Add a method to the vtable methods.
83 void AddMethod(GlobalDecl GD) {
84 assert(!MethodToIndexMap.count(GD) &&
85 "Method has already been added!");
86
87 MethodToIndexMap[GD] = Methods.size();
88 Methods.push_back(GD);
Eli Friedman72649ed2009-12-06 22:01:30 +000089 OrigMethods.push_back(GD);
Anders Carlssonc7ab1a82009-12-04 02:01:07 +000090 }
91
92 /// OverrideMethod - Replace a method with another.
93 void OverrideMethod(GlobalDecl OverriddenGD, GlobalDecl GD) {
94 llvm::DenseMap<GlobalDecl, uint64_t>::iterator i
95 = MethodToIndexMap.find(OverriddenGD);
96 assert(i != MethodToIndexMap.end() && "Did not find entry!");
97
98 // Get the index of the old decl.
99 uint64_t Index = i->second;
100
101 // Replace the old decl with the new decl.
102 Methods[Index] = GD;
103
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000104 // And add the new.
105 MethodToIndexMap[GD] = Index;
106 }
107
Anders Carlsson77c23e52009-12-04 15:49:02 +0000108 /// getIndex - Gives the index of a passed in GlobalDecl. Returns false if
109 /// the index couldn't be found.
Benjamin Kramercce9fde2009-12-04 22:45:27 +0000110 bool getIndex(GlobalDecl GD, uint64_t &Index) const {
Anders Carlsson77c23e52009-12-04 15:49:02 +0000111 llvm::DenseMap<GlobalDecl, uint64_t>::const_iterator i
112 = MethodToIndexMap.find(GD);
Eli Friedman47145832009-12-04 08:34:14 +0000113
Anders Carlsson77c23e52009-12-04 15:49:02 +0000114 if (i == MethodToIndexMap.end())
115 return false;
Anders Carlssonc0c49932009-12-04 03:41:37 +0000116
Anders Carlsson77c23e52009-12-04 15:49:02 +0000117 Index = i->second;
118 return true;
Anders Carlssonc0c49932009-12-04 03:41:37 +0000119 }
120
Eli Friedman72649ed2009-12-06 22:01:30 +0000121 GlobalDecl getOrigMethod(uint64_t Index) const {
122 return OrigMethods[Index];
123 }
124
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000125 MethodsVectorTy::size_type size() const {
126 return Methods.size();
127 }
128
129 void clear() {
130 MethodToIndexMap.clear();
131 Methods.clear();
Eli Friedman72649ed2009-12-06 22:01:30 +0000132 OrigMethods.clear();
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000133 }
134
Anders Carlssonc0c49932009-12-04 03:41:37 +0000135 GlobalDecl operator[](uint64_t Index) const {
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000136 return Methods[Index];
137 }
138 };
139
140 /// Methods - The vtable methods we're currently building.
141 VtableMethods Methods;
142
Anders Carlsson98fdb242009-12-04 02:26:15 +0000143 /// ThisAdjustments - For a given index in the vtable, contains the 'this'
144 /// pointer adjustment needed for a method.
145 typedef llvm::DenseMap<uint64_t, ThunkAdjustment> ThisAdjustmentsMapTy;
146 ThisAdjustmentsMapTy ThisAdjustments;
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000147
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000148 SavedAdjustmentsVectorTy SavedAdjustments;
Eli Friedman72649ed2009-12-06 22:01:30 +0000149
Anders Carlssona8756702009-12-04 02:22:02 +0000150 /// BaseReturnTypes - Contains the base return types of methods who have been
151 /// overridden with methods whose return types require adjustment. Used for
152 /// generating covariant thunk information.
153 typedef llvm::DenseMap<uint64_t, CanQualType> BaseReturnTypesMapTy;
154 BaseReturnTypesMapTy BaseReturnTypes;
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000155
Anders Carlssondbd920c2009-10-11 22:13:54 +0000156 std::vector<Index_t> VCalls;
Mike Stump9840c702009-11-12 20:47:57 +0000157
158 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stump23a35422009-11-19 20:52:19 +0000159 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
160 // vtable for use in computing the initializers for the VTT.
161 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +0000162
Anders Carlsson1bb60992010-01-14 02:29:07 +0000163 /// AddressPoints - Address points for this vtable.
164 CGVtableInfo::AddressPointsMapTy& AddressPoints;
165
Anders Carlssondbd920c2009-10-11 22:13:54 +0000166 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000167 const uint32_t LLVMPointerWidth;
168 Index_t extra;
Mike Stump11dea942009-10-15 02:04:03 +0000169 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stump23a35422009-11-19 20:52:19 +0000170 static llvm::DenseMap<CtorVtable_t, int64_t>&
171 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
172 const CXXRecordDecl *c) {
Anders Carlsson21431c52010-01-02 18:02:32 +0000173 CGVtableInfo::AddrMap_t *&oref = cgm.getVtableInfo().AddressPoints[l];
Mike Stump23a35422009-11-19 20:52:19 +0000174 if (oref == 0)
Anders Carlsson21431c52010-01-02 18:02:32 +0000175 oref = new CGVtableInfo::AddrMap_t;
Mike Stump23a35422009-11-19 20:52:19 +0000176
177 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
178 if (ref == 0)
179 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
180 return *ref;
181 }
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000182
Mike Stumpcf0b9cc2010-01-26 00:05:04 +0000183#if 0
184 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
185 TemplateParameterList *Old,
186 TemplateParameterListEqualKind Kind) {
187 assert(0 && "template in vtable");
188 if (Old->size() != New->size()) {
189 return false;
190 }
191
192 for (TemplateParameterList::iterator OldParm = Old->begin(),
193 OldParmEnd = Old->end(), NewParm = New->begin();
194 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
195 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
196 return false;
197 }
198
199 if (isa<TemplateTypeParmDecl>(*OldParm)) {
200 // Okay; all template type parameters are equivalent (since we
201 // know we're at the same index).
202 } else if (NonTypeTemplateParmDecl *OldNTTP
203 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
204 // The types of non-type template parameters must agree.
205 NonTypeTemplateParmDecl *NewNTTP
206 = cast<NonTypeTemplateParmDecl>(*NewParm);
207
208 // If we are matching a template template argument to a template
209 // template parameter and one of the non-type template parameter types
210 // is dependent, then we must wait until template instantiation time
211 // to actually compare the arguments.
212 if (Kind == TPL_TemplateTemplateArgumentMatch &&
213 (OldNTTP->getType()->isDependentType() ||
214 NewNTTP->getType()->isDependentType()))
215 continue;
216
217 if (Context.getCanonicalType(OldNTTP->getType()) !=
218 Context.getCanonicalType(NewNTTP->getType())) {
219 return false;
220 }
221 } else {
222 // The template parameter lists of template template
223 // parameters must agree.
224 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
225 "Only template template parameters handled here");
226 TemplateTemplateParmDecl *OldTTP
227 = cast<TemplateTemplateParmDecl>(*OldParm);
228 TemplateTemplateParmDecl *NewTTP
229 = cast<TemplateTemplateParmDecl>(*NewParm);
230 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
231 OldTTP->getTemplateParameters(),
232 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind)))
233 return false;
234 }
235 }
236
237 return true;
238 }
239#endif
240
241 bool DclIsSame(const FunctionDecl *New, const FunctionDecl *Old) {
242 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
243 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
244
245 // C++ [temp.fct]p2:
246 // A function template can be overloaded with other function templates
247 // and with normal (non-template) functions.
248 if ((OldTemplate == 0) != (NewTemplate == 0))
249 return false;
250
251 // Is the function New an overload of the function Old?
252 QualType OldQType = CGM.getContext().getCanonicalType(Old->getType());
253 QualType NewQType = CGM.getContext().getCanonicalType(New->getType());
254
255 // Compare the signatures (C++ 1.3.10) of the two functions to
256 // determine whether they are overloads. If we find any mismatch
257 // in the signature, they are overloads.
258
259 // If either of these functions is a K&R-style function (no
260 // prototype), then we consider them to have matching signatures.
261 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
262 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
263 return true;
264
265 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
266 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
267
268 // The signature of a function includes the types of its
269 // parameters (C++ 1.3.10), which includes the presence or absence
270 // of the ellipsis; see C++ DR 357).
271 if (OldQType != NewQType &&
272 (OldType->getNumArgs() != NewType->getNumArgs() ||
273 OldType->isVariadic() != NewType->isVariadic() ||
274 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
275 NewType->arg_type_begin())))
276 return false;
277
278#if 0
279 // C++ [temp.over.link]p4:
280 // The signature of a function template consists of its function
281 // signature, its return type and its template parameter list. The names
282 // of the template parameters are significant only for establishing the
283 // relationship between the template parameters and the rest of the
284 // signature.
285 //
286 // We check the return type and template parameter lists for function
287 // templates first; the remaining checks follow.
288 if (NewTemplate &&
289 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
290 OldTemplate->getTemplateParameters(),
291 TPL_TemplateMatch) ||
292 OldType->getResultType() != NewType->getResultType()))
293 return false;
294#endif
295
296 // If the function is a class member, its signature includes the
297 // cv-qualifiers (if any) on the function itself.
298 //
299 // As part of this, also check whether one of the member functions
300 // is static, in which case they are not overloads (C++
301 // 13.1p2). While not part of the definition of the signature,
302 // this check is important to determine whether these functions
303 // can be overloaded.
304 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
305 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
306 if (OldMethod && NewMethod &&
307 !OldMethod->isStatic() && !NewMethod->isStatic() &&
308 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
309 return false;
310
311 // The signatures match; this is not an overload.
312 return true;
313 }
314
315 typedef llvm::DenseMap<const CXXMethodDecl *, const CXXMethodDecl*>
316 ForwardUnique_t;
317 ForwardUnique_t ForwardUnique;
318 llvm::DenseMap<const CXXMethodDecl*, const CXXMethodDecl*> UniqueOverrider;
319
320 void BuildUniqueOverrider(const CXXMethodDecl *U, const CXXMethodDecl *MD) {
321 const CXXMethodDecl *PrevU = UniqueOverrider[MD];
322 assert(U && "no unique overrider");
323 if (PrevU == U)
324 return;
325 if (PrevU != U && PrevU != 0) {
326 // If already set, note the two sets as the same
327 if (0)
328 printf("%s::%s same as %s::%s\n",
329 PrevU->getParent()->getNameAsCString(),
330 PrevU->getNameAsCString(),
331 U->getParent()->getNameAsCString(),
332 U->getNameAsCString());
333 ForwardUnique[PrevU] = U;
334 return;
335 }
336
337 // Not set, set it now
338 if (0)
339 printf("marking %s::%s %p override as %s::%s\n",
340 MD->getParent()->getNameAsCString(),
341 MD->getNameAsCString(),
342 (void*)MD,
343 U->getParent()->getNameAsCString(),
344 U->getNameAsCString());
345 UniqueOverrider[MD] = U;
346
347 for (CXXMethodDecl::method_iterator mi = MD->begin_overridden_methods(),
348 me = MD->end_overridden_methods(); mi != me; ++mi) {
349 BuildUniqueOverrider(U, *mi);
350 }
351 }
352
353 void BuildUniqueOverriders(const CXXRecordDecl *RD) {
354 if (0) printf("walking %s\n", RD->getNameAsCString());
355 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
356 e = RD->method_end(); i != e; ++i) {
357 const CXXMethodDecl *MD = *i;
358 if (!MD->isVirtual())
359 continue;
360
361 if (UniqueOverrider[MD] == 0) {
362 // Only set this, if it hasn't been set yet.
363 BuildUniqueOverrider(MD, MD);
364 if (0)
365 printf("top set is %s::%s %p\n",
366 MD->getParent()->getNameAsCString(),
367 MD->getNameAsCString(),
368 (void*)MD);
369 ForwardUnique[MD] = MD;
370 }
371 }
372 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
373 e = RD->bases_end(); i != e; ++i) {
374 const CXXRecordDecl *Base =
375 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
376 BuildUniqueOverriders(Base);
377 }
378 }
379
380 static int DclCmp(const void *p1, const void *p2) {
381 const CXXMethodDecl *MD1 = (const CXXMethodDecl *)p1;
382 const CXXMethodDecl *MD2 = (const CXXMethodDecl *)p2;
383 return (MD1->getIdentifier() - MD2->getIdentifier());
384 }
385
386 void MergeForwarding() {
387 typedef llvm::SmallVector<const CXXMethodDecl *, 100> A_t;
388 A_t A;
389 for (ForwardUnique_t::iterator I = ForwardUnique.begin(),
390 E = ForwardUnique.end(); I != E; ++I) {
391 if (I->first == I->second)
392 // Only add the roots of all trees
393 A.push_back(I->first);
394 }
395 llvm::array_pod_sort(A.begin(), A.end(), DclCmp);
396 for (A_t::iterator I = A.begin(),
397 E = A.end(); I != E; ++I) {
398 A_t::iterator J = I;
399 while (++J != E && DclCmp(*I, *J) == 0)
400 if (DclIsSame(*I, *J)) {
401 printf("connecting %s\n", (*I)->getNameAsCString());
402 ForwardUnique[*J] = *I;
403 }
404 }
405 }
406
407 const CXXMethodDecl *getUnique(const CXXMethodDecl *MD) {
408 const CXXMethodDecl *U = UniqueOverrider[MD];
409 assert(U && "unique overrider not found");
410 while (ForwardUnique.count(U)) {
411 const CXXMethodDecl *NU = ForwardUnique[U];
412 if (NU == U) break;
413 U = NU;
414 }
415 return U;
416 }
417 const CXXMethodDecl *getUnique(GlobalDecl GD) {
418 return getUnique(cast<CXXMethodDecl>(GD.getDecl()));
419 }
420
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000421 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
422 llvm::Constant* getPureVirtualFn() {
423 if (!PureVirtualFn) {
424 const llvm::FunctionType *Ty =
425 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
426 /*isVarArg=*/false);
427 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
428 }
429
430 return PureVirtualFn;
431 }
432
Anders Carlssondbd920c2009-10-11 22:13:54 +0000433public:
Anders Carlssonac3f7bd2009-12-04 18:36:22 +0000434 VtableBuilder(const CXXRecordDecl *MostDerivedClass,
Eli Friedman152b5b12009-12-05 01:05:03 +0000435 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm,
Anders Carlsson1bb60992010-01-14 02:29:07 +0000436 bool build, CGVtableInfo::AddressPointsMapTy& AddressPoints)
Eli Friedman152b5b12009-12-05 01:05:03 +0000437 : BuildVtable(build), MostDerivedClass(MostDerivedClass), LayoutClass(l),
438 LayoutOffset(lo), BLayout(cgm.getContext().getASTRecordLayout(l)),
439 rtti(0), VMContext(cgm.getModule().getContext()),CGM(cgm),
440 PureVirtualFn(0),
Anders Carlssonac3f7bd2009-12-04 18:36:22 +0000441 subAddressPoints(AllocAddressPoint(cgm, l, MostDerivedClass)),
Anders Carlsson1bb60992010-01-14 02:29:07 +0000442 AddressPoints(AddressPoints),
443 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0))
444 {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000445 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000446 if (BuildVtable) {
447 QualType ClassType = CGM.getContext().getTagDeclType(MostDerivedClass);
448 rtti = CGM.GetAddrOfRTTIDescriptor(ClassType);
449 }
Mike Stumpcf0b9cc2010-01-26 00:05:04 +0000450 BuildUniqueOverriders(MostDerivedClass);
451 MergeForwarding();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000452 }
453
Anders Carlssonc3a46ef2009-12-06 01:09:21 +0000454 // getVtableComponents - Returns a reference to the vtable components.
455 const VtableComponentsVectorTy &getVtableComponents() const {
456 return VtableComponents;
Anders Carlsson15318f42009-12-04 16:19:30 +0000457 }
458
Anders Carlssonc997d422010-01-02 01:01:18 +0000459 llvm::DenseMap<const CXXRecordDecl *, uint64_t> &getVBIndex()
Anders Carlssondbd920c2009-10-11 22:13:54 +0000460 { return VBIndex; }
461
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000462 SavedAdjustmentsVectorTy &getSavedAdjustments()
463 { return SavedAdjustments; }
Eli Friedman72649ed2009-12-06 22:01:30 +0000464
Anders Carlssondbd920c2009-10-11 22:13:54 +0000465 llvm::Constant *wrap(Index_t i) {
466 llvm::Constant *m;
467 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
468 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
469 }
470
471 llvm::Constant *wrap(llvm::Constant *m) {
472 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
473 }
474
Mike Stumpd6584902010-01-22 02:51:26 +0000475//#define D1(x)
476#define D1(X) do { if (getenv("DEBUG")) { X; } } while (0)
Mike Stump6a9612f2009-10-31 20:06:59 +0000477
478 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stumpab28c132009-10-13 22:54:56 +0000479 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000480 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
481 e = RD->bases_end(); i != e; ++i) {
482 const CXXRecordDecl *Base =
483 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpab28c132009-10-13 22:54:56 +0000484 Index_t next_vbindex = current_vbindex;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000485 if (i->isVirtual() && !SeenVBase.count(Base)) {
486 SeenVBase.insert(Base);
Mike Stumpab28c132009-10-13 22:54:56 +0000487 if (updateVBIndex) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000488 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stumpab28c132009-10-13 22:54:56 +0000489 - 3*LLVMPointerWidth/8);
490 VBIndex[Base] = next_vbindex;
491 }
Mike Stump6a9612f2009-10-31 20:06:59 +0000492 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
493 VCalls.push_back((0?700:0) + BaseOffset);
494 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
495 Base->getNameAsCString(),
496 (int)-VCalls.size()-3, (int)BaseOffset,
Mike Stumpd6584902010-01-22 02:51:26 +0000497 MostDerivedClass->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000498 }
Mike Stumpab28c132009-10-13 22:54:56 +0000499 // We also record offsets for non-virtual bases to closest enclosing
500 // virtual base. We do this so that we don't have to search
501 // for the nearst virtual base class when generating thunks.
502 if (updateVBIndex && VBIndex.count(Base) == 0)
503 VBIndex[Base] = next_vbindex;
Mike Stump6a9612f2009-10-31 20:06:59 +0000504 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000505 }
506 }
507
508 void StartNewTable() {
509 SeenVBase.clear();
510 }
511
Mike Stump3425b972009-10-15 09:30:16 +0000512 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
513 Index_t Offset = 0) {
514
515 if (B == D)
516 return Offset;
517
518 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
519 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
520 e = D->bases_end(); i != e; ++i) {
521 const CXXRecordDecl *Base =
522 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
523 int64_t BaseOffset = 0;
524 if (!i->isVirtual())
525 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
526 int64_t o = getNVOffset_1(Base, B, BaseOffset);
527 if (o >= 0)
528 return o;
529 }
530
531 return -1;
532 }
533
534 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
535 /// derived class D.
536 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +0000537 qD = qD->getPointeeType();
538 qB = qB->getPointeeType();
Mike Stump3425b972009-10-15 09:30:16 +0000539 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
540 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
541 int64_t o = getNVOffset_1(D, B);
542 if (o >= 0)
543 return o;
544
545 assert(false && "FIXME: non-virtual base not found");
546 return 0;
547 }
548
Anders Carlssondbd920c2009-10-11 22:13:54 +0000549 /// getVbaseOffset - Returns the index into the vtable for the virtual base
550 /// offset for the given (B) virtual base of the derived class D.
551 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +0000552 qD = qD->getPointeeType();
553 qB = qB->getPointeeType();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000554 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
555 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
Anders Carlssonac3f7bd2009-12-04 18:36:22 +0000556 if (D != MostDerivedClass)
Eli Friedman76ed1f72009-11-30 01:19:33 +0000557 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000558 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
559 i = VBIndex.find(B);
560 if (i != VBIndex.end())
561 return i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000562
Mike Stumpab28c132009-10-13 22:54:56 +0000563 assert(false && "FIXME: Base not found");
Anders Carlssondbd920c2009-10-11 22:13:54 +0000564 return 0;
565 }
566
Eli Friedman367d1222009-12-04 08:40:51 +0000567 bool OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
568 Index_t OverrideOffset, Index_t Offset,
569 int64_t CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000570
Anders Carlssonadfa2672009-12-04 02:39:04 +0000571 /// AppendMethods - Append the current methods to the vtable.
Anders Carlssonbf540272009-12-04 02:56:03 +0000572 void AppendMethodsToVtable();
Anders Carlssonadfa2672009-12-04 02:39:04 +0000573
Anders Carlssona0fdd912009-11-13 17:08:56 +0000574 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
575 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
576
Anders Carlssonecf282b2009-11-24 05:08:52 +0000577 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump1ae31782009-10-27 23:36:26 +0000578
Mike Stumpc085a982009-12-03 16:55:20 +0000579 return wrap(CGM.GetAddrOfFunction(GD, Ty));
Mike Stump1ae31782009-10-27 23:36:26 +0000580 }
581
Mike Stump9e7e3c62009-11-06 23:27:42 +0000582 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
583 int64_t CurrentVBaseOffset) {
Mike Stump11dea942009-10-15 02:04:03 +0000584 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlssondbd920c2009-10-11 22:13:54 +0000585 e = Path->rend(); i != e; ++i) {
586 const CXXRecordDecl *RD = i->first;
Mike Stump3425b972009-10-15 09:30:16 +0000587 int64_t OverrideOffset = i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000588 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
589 ++mi) {
Anders Carlssona0fdd912009-11-13 17:08:56 +0000590 const CXXMethodDecl *MD = *mi;
591
592 if (!MD->isVirtual())
Anders Carlssondbd920c2009-10-11 22:13:54 +0000593 continue;
594
Anders Carlssona0fdd912009-11-13 17:08:56 +0000595 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
596 // Override both the complete and the deleting destructor.
597 GlobalDecl CompDtor(DD, Dtor_Complete);
Eli Friedman367d1222009-12-04 08:40:51 +0000598 OverrideMethod(CompDtor, MorallyVirtual, OverrideOffset, Offset,
599 CurrentVBaseOffset);
600
Anders Carlssona0fdd912009-11-13 17:08:56 +0000601 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
Eli Friedman367d1222009-12-04 08:40:51 +0000602 OverrideMethod(DeletingDtor, MorallyVirtual, OverrideOffset, Offset,
603 CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +0000604 } else {
Eli Friedman367d1222009-12-04 08:40:51 +0000605 OverrideMethod(MD, MorallyVirtual, OverrideOffset, Offset,
606 CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +0000607 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000608 }
609 }
610 }
611
Anders Carlssona0fdd912009-11-13 17:08:56 +0000612 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000613 int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000614 // If we can find a previously allocated slot for this, reuse it.
Eli Friedman367d1222009-12-04 08:40:51 +0000615 if (OverrideMethod(GD, MorallyVirtual, Offset, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000616 CurrentVBaseOffset))
Anders Carlssondbd920c2009-10-11 22:13:54 +0000617 return;
618
Mike Stump372ade22010-01-22 18:48:47 +0000619 D1(printf(" vfn for %s at %d\n",
620 dyn_cast<CXXMethodDecl>(GD.getDecl())->getNameAsCString(),
621 (int)Methods.size()));
622
Anders Carlssona7f19112009-12-04 02:08:24 +0000623 // We didn't find an entry in the vtable that we could use, add a new
624 // entry.
625 Methods.AddMethod(GD);
626
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000627 VCallOffset[GD] = Offset/8;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000628 if (MorallyVirtual) {
Mike Stumpcf0b9cc2010-01-26 00:05:04 +0000629 const CXXMethodDecl *UMD = getUnique(GD);
630 assert(UMD && "final overrider not found");
631
632 Index_t &idx = VCall[UMD];
Anders Carlssondbd920c2009-10-11 22:13:54 +0000633 // Allocate the first one, after that, we reuse the previous one.
634 if (idx == 0) {
Mike Stumpcf0b9cc2010-01-26 00:05:04 +0000635 NonVirtualOffset[UMD] = -CurrentVBaseOffset/8 + Offset/8;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000636 idx = VCalls.size()+1;
Mike Stumpcf0b9cc2010-01-26 00:05:04 +0000637 VCalls.push_back(Offset/8 - CurrentVBaseOffset/8);
Mike Stump6a9612f2009-10-31 20:06:59 +0000638 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpd6584902010-01-22 02:51:26 +0000639 dyn_cast<CXXMethodDecl>(GD.getDecl())->getNameAsCString(),
Mike Stumpcf0b9cc2010-01-26 00:05:04 +0000640 (int)-VCalls.size()-3, (int)VCalls[idx-1]));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000641 }
642 }
643 }
644
645 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000646 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000647 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssona0fdd912009-11-13 17:08:56 +0000648 ++mi) {
649 const CXXMethodDecl *MD = *mi;
650 if (!MD->isVirtual())
651 continue;
652
653 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
654 // For destructors, add both the complete and the deleting destructor
655 // to the vtable.
656 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000657 CurrentVBaseOffset);
Eli Friedman76ed1f72009-11-30 01:19:33 +0000658 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
659 CurrentVBaseOffset);
660 } else
661 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +0000662 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000663 }
664
665 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
666 const CXXRecordDecl *PrimaryBase,
667 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000668 int64_t Offset, int64_t CurrentVBaseOffset,
669 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +0000670 Path->push_back(std::make_pair(RD, Offset));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000671 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
672 e = RD->bases_end(); i != e; ++i) {
673 if (i->isVirtual())
674 continue;
675 const CXXRecordDecl *Base =
676 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000677 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
678 StartNewTable();
679 GenerateVtableForBase(Base, o, MorallyVirtual, false,
680 true, Base == PrimaryBase && !PrimaryBaseWasVirtual,
681 CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000682 }
Mike Stump11dea942009-10-15 02:04:03 +0000683 Path->pop_back();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000684 }
685
Mike Stump0ca42792009-10-14 18:14:51 +0000686// #define D(X) do { X; } while (0)
687#define D(X)
688
689 void insertVCalls(int InsertionPoint) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000690 D1(printf("============= combining vbase/vcall\n"));
Mike Stump0ca42792009-10-14 18:14:51 +0000691 D(VCalls.insert(VCalls.begin(), 673));
692 D(VCalls.push_back(672));
Eli Friedman152b5b12009-12-05 01:05:03 +0000693
Anders Carlssonc3a46ef2009-12-06 01:09:21 +0000694 VtableComponents.insert(VtableComponents.begin() + InsertionPoint,
695 VCalls.size(), 0);
Eli Friedman152b5b12009-12-05 01:05:03 +0000696 if (BuildVtable) {
697 // The vcalls come first...
698 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
699 e = VCalls.rend();
700 i != e; ++i)
Anders Carlssonc3a46ef2009-12-06 01:09:21 +0000701 VtableComponents[InsertionPoint++] = wrap((0?600:0) + *i);
Eli Friedman152b5b12009-12-05 01:05:03 +0000702 }
Mike Stump0ca42792009-10-14 18:14:51 +0000703 VCalls.clear();
Mike Stumpfbfb52d2009-11-10 02:30:51 +0000704 VCall.clear();
Mike Stump0ca42792009-10-14 18:14:51 +0000705 }
706
Mike Stump65d0e282009-11-13 23:13:20 +0000707 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
708 Index_t AddressPoint) {
709 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
Mike Stumpd6584902010-01-22 02:51:26 +0000710 RD->getNameAsCString(), MostDerivedClass->getNameAsCString(),
Mike Stump65d0e282009-11-13 23:13:20 +0000711 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +0000712 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Anders Carlsson1bb60992010-01-14 02:29:07 +0000713 AddressPoints[BaseSubobject(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +0000714
715 // Now also add the address point for all our primary bases.
716 while (1) {
717 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
718 RD = Layout.getPrimaryBase();
719 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
720 // FIXME: Double check this.
721 if (RD == 0)
722 break;
723 if (PrimaryBaseWasVirtual &&
724 BLayout.getVBaseClassOffset(RD) != Offset)
725 break;
726 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
Mike Stumpd6584902010-01-22 02:51:26 +0000727 RD->getNameAsCString(), MostDerivedClass->getNameAsCString(),
Mike Stump65d0e282009-11-13 23:13:20 +0000728 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +0000729 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Anders Carlsson1bb60992010-01-14 02:29:07 +0000730 AddressPoints[BaseSubobject(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +0000731 }
732 }
733
734
Mike Stump8cc4f102009-12-24 07:29:41 +0000735 void FinishGenerateVtable(const CXXRecordDecl *RD,
736 const ASTRecordLayout &Layout,
737 const CXXRecordDecl *PrimaryBase,
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000738 bool ForNPNVBases, bool WasPrimaryBase,
Mike Stump8cc4f102009-12-24 07:29:41 +0000739 bool PrimaryBaseWasVirtual,
740 bool MorallyVirtual, int64_t Offset,
741 bool ForVirtualBase, int64_t CurrentVBaseOffset,
742 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +0000743 bool alloc = false;
744 if (Path == 0) {
745 alloc = true;
746 Path = new Path_t;
747 }
748
Anders Carlssondbd920c2009-10-11 22:13:54 +0000749 StartNewTable();
750 extra = 0;
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000751 Index_t AddressPoint = 0;
752 int VCallInsertionPoint = 0;
753 if (!ForNPNVBases || !WasPrimaryBase) {
754 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
755 VCallInsertionPoint = VtableComponents.size();
756 if (!DeferVCalls) {
757 insertVCalls(VCallInsertionPoint);
758 } else
759 // FIXME: just for extra, or for all uses of VCalls.size post this?
760 extra = -VCalls.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000761
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000762 // Add the offset to top.
763 VtableComponents.push_back(BuildVtable ? wrap(-((Offset-LayoutOffset)/8)) : 0);
Anders Carlsson15318f42009-12-04 16:19:30 +0000764
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000765 // Add the RTTI information.
766 VtableComponents.push_back(rtti);
Anders Carlsson15318f42009-12-04 16:19:30 +0000767
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000768 AddressPoint = VtableComponents.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000769
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000770 AppendMethodsToVtable();
771 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000772
773 // and then the non-virtual bases.
774 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000775 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stump0ca42792009-10-14 18:14:51 +0000776
777 if (ForVirtualBase) {
Mike Stump9840c702009-11-12 20:47:57 +0000778 // FIXME: We're adding to VCalls in callers, we need to do the overrides
779 // in the inner part, so that we know the complete set of vcalls during
780 // the build and don't have to insert into methods. Saving out the
781 // AddressPoint here, would need to be fixed, if we didn't do that. Also
782 // retroactively adding vcalls for overrides later wind up in the wrong
783 // place, the vcall slot has to be alloted during the walk of the base
784 // when the function is first introduces.
Mike Stump0ca42792009-10-14 18:14:51 +0000785 AddressPoint += VCalls.size();
Mike Stump9840c702009-11-12 20:47:57 +0000786 insertVCalls(VCallInsertionPoint);
Mike Stump0ca42792009-10-14 18:14:51 +0000787 }
788
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000789 if (!ForNPNVBases || !WasPrimaryBase)
790 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump9840c702009-11-12 20:47:57 +0000791
Mike Stump11dea942009-10-15 02:04:03 +0000792 if (alloc) {
793 delete Path;
794 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000795 }
796
Mike Stump6a9612f2009-10-31 20:06:59 +0000797 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
798 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000799 int64_t CurrentVBaseOffset) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000800 if (!RD->isDynamicClass())
801 return;
802
803 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
804 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
805 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
806
807 // vtables are composed from the chain of primaries.
Eli Friedmandfe33bb2009-12-04 08:52:11 +0000808 if (PrimaryBase && !PrimaryBaseWasVirtual) {
Mike Stump6a9612f2009-10-31 20:06:59 +0000809 D1(printf(" doing primaries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +0000810 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Eli Friedmandfe33bb2009-12-04 08:52:11 +0000811 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
812 updateVBIndex, current_vbindex, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000813 }
814
815 D1(printf(" doing vcall entries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +0000816 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +0000817
818 // And add the virtuals for the class to the primary vtable.
Eli Friedman76ed1f72009-11-30 01:19:33 +0000819 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000820 }
821
822 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
823 bool updateVBIndex, Index_t current_vbindex,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000824 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000825 bool bottom) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000826 if (!RD->isDynamicClass())
827 return;
828
829 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
830 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
831 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
832
833 // vtables are composed from the chain of primaries.
834 if (PrimaryBase) {
Mike Stump9e7e3c62009-11-06 23:27:42 +0000835 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
836 if (PrimaryBaseWasVirtual) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000837 IndirectPrimary.insert(PrimaryBase);
Mike Stump9e7e3c62009-11-06 23:27:42 +0000838 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
839 }
Mike Stump6a9612f2009-10-31 20:06:59 +0000840
841 D1(printf(" doing primaries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +0000842 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +0000843
844 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +0000845 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000846 BaseCurrentVBaseOffset, false);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000847 }
848
Mike Stump6a9612f2009-10-31 20:06:59 +0000849 D1(printf(" doing vbase entries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +0000850 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +0000851 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
852
853 if (RDisVirtualBase || bottom) {
854 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +0000855 CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +0000856 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000857 }
858
Mike Stump8cc4f102009-12-24 07:29:41 +0000859 void GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
860 bool MorallyVirtual = false,
861 bool ForVirtualBase = false,
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000862 bool ForNPNVBases = false,
863 bool WasPrimaryBase = true,
Mike Stump8cc4f102009-12-24 07:29:41 +0000864 int CurrentVBaseOffset = 0,
865 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000866 if (!RD->isDynamicClass())
Mike Stump8cc4f102009-12-24 07:29:41 +0000867 return;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000868
Mike Stump92774d12009-11-13 02:35:38 +0000869 // Construction vtable don't need parts that have no virtual bases and
870 // aren't morally virtual.
Anders Carlssonac3f7bd2009-12-04 18:36:22 +0000871 if ((LayoutClass != MostDerivedClass) &&
872 RD->getNumVBases() == 0 && !MorallyVirtual)
Mike Stump8cc4f102009-12-24 07:29:41 +0000873 return;
Mike Stump92774d12009-11-13 02:35:38 +0000874
Anders Carlssondbd920c2009-10-11 22:13:54 +0000875 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
876 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
877 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
878
Anders Carlssondbd920c2009-10-11 22:13:54 +0000879 extra = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +0000880 D1(printf("building entries for base %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +0000881 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +0000882
Mike Stump6a9612f2009-10-31 20:06:59 +0000883 if (ForVirtualBase)
884 extra = VCalls.size();
885
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000886 if (!ForNPNVBases || !WasPrimaryBase) {
887 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0,
888 ForVirtualBase, CurrentVBaseOffset, true);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000889
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000890 if (Path)
891 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
892 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000893
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000894 FinishGenerateVtable(RD, Layout, PrimaryBase, ForNPNVBases, WasPrimaryBase,
895 PrimaryBaseWasVirtual, MorallyVirtual, Offset,
896 ForVirtualBase, CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000897 }
898
899 void GenerateVtableForVBases(const CXXRecordDecl *RD,
900 int64_t Offset = 0,
Mike Stump11dea942009-10-15 02:04:03 +0000901 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000902 bool alloc = false;
903 if (Path == 0) {
904 alloc = true;
Mike Stump11dea942009-10-15 02:04:03 +0000905 Path = new Path_t;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000906 }
907 // FIXME: We also need to override using all paths to a virtual base,
908 // right now, we just process the first path
909 Path->push_back(std::make_pair(RD, Offset));
910 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
911 e = RD->bases_end(); i != e; ++i) {
912 const CXXRecordDecl *Base =
913 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
914 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
915 // Mark it so we don't output it twice.
916 IndirectPrimary.insert(Base);
917 StartNewTable();
Mike Stump0ca42792009-10-14 18:14:51 +0000918 VCall.clear();
Anders Carlssondbd920c2009-10-11 22:13:54 +0000919 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9e7e3c62009-11-06 23:27:42 +0000920 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump6a9612f2009-10-31 20:06:59 +0000921 D1(printf("vtable %s virtual base %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +0000922 MostDerivedClass->getNameAsCString(), Base->getNameAsCString()));
Mike Stumpfc9f16c2010-01-22 06:45:05 +0000923 GenerateVtableForBase(Base, BaseOffset, true, true, false,
924 true, CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +0000925 }
Mike Stump9840c702009-11-12 20:47:57 +0000926 int64_t BaseOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000927 if (i->isVirtual())
928 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9840c702009-11-12 20:47:57 +0000929 else {
930 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
931 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
932 }
933
Mike Stump11dea942009-10-15 02:04:03 +0000934 if (Base->getNumVBases()) {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000935 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump11dea942009-10-15 02:04:03 +0000936 }
Anders Carlssondbd920c2009-10-11 22:13:54 +0000937 }
938 Path->pop_back();
939 if (alloc)
940 delete Path;
941 }
942};
Anders Carlsson27682a32009-12-03 01:54:02 +0000943} // end anonymous namespace
944
Anders Carlsson891bb4b2009-12-03 02:32:59 +0000945/// TypeConversionRequiresAdjustment - Returns whether conversion from a
946/// derived type to a base type requires adjustment.
947static bool
948TypeConversionRequiresAdjustment(ASTContext &Ctx,
949 const CXXRecordDecl *DerivedDecl,
950 const CXXRecordDecl *BaseDecl) {
951 CXXBasePaths Paths(/*FindAmbiguities=*/false,
952 /*RecordPaths=*/true, /*DetectVirtual=*/true);
953 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
954 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
955 assert(false && "Class must be derived from the passed in base class!");
956 return false;
957 }
958
959 // If we found a virtual base we always want to require adjustment.
960 if (Paths.getDetectedVirtual())
961 return true;
962
963 const CXXBasePath &Path = Paths.front();
964
965 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
966 const CXXBasePathElement &Element = Path[Start];
967
968 // Check the base class offset.
969 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
970
971 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
972 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
973
974 if (Layout.getBaseClassOffset(Base) != 0) {
975 // This requires an adjustment.
976 return true;
977 }
978 }
979
980 return false;
981}
982
983static bool
984TypeConversionRequiresAdjustment(ASTContext &Ctx,
985 QualType DerivedType, QualType BaseType) {
986 // Canonicalize the types.
987 QualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
988 QualType CanBaseType = Ctx.getCanonicalType(BaseType);
989
990 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
991 "Types must have same type class!");
992
993 if (CanDerivedType == CanBaseType) {
994 // No adjustment needed.
995 return false;
996 }
997
998 if (const ReferenceType *RT = dyn_cast<ReferenceType>(CanDerivedType)) {
999 CanDerivedType = RT->getPointeeType();
1000 CanBaseType = cast<ReferenceType>(CanBaseType)->getPointeeType();
1001 } else if (const PointerType *PT = dyn_cast<PointerType>(CanDerivedType)) {
1002 CanDerivedType = PT->getPointeeType();
1003 CanBaseType = cast<PointerType>(CanBaseType)->getPointeeType();
1004 } else {
1005 assert(false && "Unexpected return type!");
1006 }
1007
1008 if (CanDerivedType == CanBaseType) {
1009 // No adjustment needed.
1010 return false;
1011 }
1012
1013 const CXXRecordDecl *DerivedDecl =
Anders Carlsson08148092009-12-30 23:47:56 +00001014 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
Anders Carlsson891bb4b2009-12-03 02:32:59 +00001015
1016 const CXXRecordDecl *BaseDecl =
Anders Carlsson08148092009-12-30 23:47:56 +00001017 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
Anders Carlsson891bb4b2009-12-03 02:32:59 +00001018
1019 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
1020}
1021
Eli Friedman367d1222009-12-04 08:40:51 +00001022bool VtableBuilder::OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
1023 Index_t OverrideOffset, Index_t Offset,
1024 int64_t CurrentVBaseOffset) {
Anders Carlsson27682a32009-12-03 01:54:02 +00001025 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1026
1027 const bool isPure = MD->isPure();
Anders Carlsson7ca46432009-12-05 17:04:47 +00001028
Anders Carlsson27682a32009-12-03 01:54:02 +00001029 // FIXME: Should OverrideOffset's be Offset?
1030
Anders Carlsson7ca46432009-12-05 17:04:47 +00001031 for (CXXMethodDecl::method_iterator mi = MD->begin_overridden_methods(),
1032 e = MD->end_overridden_methods(); mi != e; ++mi) {
Anders Carlsson27682a32009-12-03 01:54:02 +00001033 GlobalDecl OGD;
1034
Anders Carlsson3aaf4862009-12-04 05:51:56 +00001035 const CXXMethodDecl *OMD = *mi;
Anders Carlsson27682a32009-12-03 01:54:02 +00001036 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
1037 OGD = GlobalDecl(DD, GD.getDtorType());
1038 else
1039 OGD = OMD;
Eli Friedman47145832009-12-04 08:34:14 +00001040
Eli Friedman72649ed2009-12-06 22:01:30 +00001041 // Check whether this is the method being overridden in this section of
1042 // the vtable.
Anders Carlsson77c23e52009-12-04 15:49:02 +00001043 uint64_t Index;
1044 if (!Methods.getIndex(OGD, Index))
Eli Friedman47145832009-12-04 08:34:14 +00001045 continue;
1046
Eli Friedman72649ed2009-12-06 22:01:30 +00001047 // Get the original method, which we should be computing thunks, etc,
1048 // against.
1049 OGD = Methods.getOrigMethod(Index);
1050 OMD = cast<CXXMethodDecl>(OGD.getDecl());
1051
Eli Friedman47145832009-12-04 08:34:14 +00001052 QualType ReturnType =
1053 MD->getType()->getAs<FunctionType>()->getResultType();
1054 QualType OverriddenReturnType =
1055 OMD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlsson27682a32009-12-03 01:54:02 +00001056
Eli Friedman47145832009-12-04 08:34:14 +00001057 // Check if we need a return type adjustment.
1058 if (TypeConversionRequiresAdjustment(CGM.getContext(), ReturnType,
1059 OverriddenReturnType)) {
1060 CanQualType &BaseReturnType = BaseReturnTypes[Index];
Anders Carlsson27682a32009-12-03 01:54:02 +00001061
Eli Friedman47145832009-12-04 08:34:14 +00001062 // Insert the base return type.
1063 if (BaseReturnType.isNull())
1064 BaseReturnType =
1065 CGM.getContext().getCanonicalType(OverriddenReturnType);
1066 }
Anders Carlssondd454be2009-12-04 03:52:52 +00001067
Eli Friedman47145832009-12-04 08:34:14 +00001068 Methods.OverrideMethod(OGD, GD);
1069
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001070 const CXXMethodDecl *UMD = getUnique(GD);
1071 assert(UMD && "unique overrider not found");
1072 assert(UMD == getUnique(OGD) && "unique overrider not unique");
1073
Eli Friedman47145832009-12-04 08:34:14 +00001074 ThisAdjustments.erase(Index);
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001075 if (MorallyVirtual || VCall.count(UMD)) {
1076 Index_t &idx = VCall[UMD];
Eli Friedman47145832009-12-04 08:34:14 +00001077 if (idx == 0) {
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001078 NonVirtualOffset[UMD] = CurrentVBaseOffset/8 - OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00001079 VCallOffset[GD] = OverrideOffset/8;
1080 idx = VCalls.size()+1;
1081 VCalls.push_back(0);
1082 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
1083 MD->getNameAsString().c_str(), (int)-idx-3,
Mike Stumpd6584902010-01-22 02:51:26 +00001084 (int)VCalls[idx-1], MostDerivedClass->getNameAsCString()));
Eli Friedman47145832009-12-04 08:34:14 +00001085 } else {
Eli Friedman47145832009-12-04 08:34:14 +00001086 VCallOffset[GD] = VCallOffset[OGD];
1087 VCalls[idx-1] = -VCallOffset[OGD] + OverrideOffset/8;
1088 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
1089 MD->getNameAsString().c_str(), (int)-idx-3,
Mike Stumpd6584902010-01-22 02:51:26 +00001090 (int)VCalls[idx-1], MostDerivedClass->getNameAsCString()));
Eli Friedman47145832009-12-04 08:34:14 +00001091 }
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001092 int64_t NonVirtualAdjustment = NonVirtualOffset[UMD];
Eli Friedman47145832009-12-04 08:34:14 +00001093 int64_t VirtualAdjustment =
1094 -((idx + extra + 2) * LLVMPointerWidth / 8);
Anders Carlsson891bb4b2009-12-03 02:32:59 +00001095
Eli Friedman47145832009-12-04 08:34:14 +00001096 // Optimize out virtual adjustments of 0.
1097 if (VCalls[idx-1] == 0)
1098 VirtualAdjustment = 0;
Anders Carlsson891bb4b2009-12-03 02:32:59 +00001099
Eli Friedman47145832009-12-04 08:34:14 +00001100 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
1101 VirtualAdjustment);
Anders Carlssonbc0e3392009-12-03 02:22:59 +00001102
Eli Friedman72649ed2009-12-06 22:01:30 +00001103 if (!isPure && !ThisAdjustment.isEmpty()) {
Eli Friedman47145832009-12-04 08:34:14 +00001104 ThisAdjustments[Index] = ThisAdjustment;
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001105 SavedAdjustments.push_back(
1106 std::make_pair(GD, std::make_pair(OGD, ThisAdjustment)));
Eli Friedman72649ed2009-12-06 22:01:30 +00001107 }
Anders Carlsson27682a32009-12-03 01:54:02 +00001108 return true;
1109 }
Eli Friedman47145832009-12-04 08:34:14 +00001110
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001111 int64_t NonVirtualAdjustment = -VCallOffset[OGD] + OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00001112
1113 if (NonVirtualAdjustment) {
1114 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
1115
Eli Friedmanf062d9d2009-12-06 22:33:51 +00001116 if (!isPure) {
Eli Friedman47145832009-12-04 08:34:14 +00001117 ThisAdjustments[Index] = ThisAdjustment;
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001118 SavedAdjustments.push_back(
1119 std::make_pair(GD, std::make_pair(OGD, ThisAdjustment)));
Eli Friedmanf062d9d2009-12-06 22:33:51 +00001120 }
Eli Friedman47145832009-12-04 08:34:14 +00001121 }
1122 return true;
Anders Carlsson27682a32009-12-03 01:54:02 +00001123 }
1124
1125 return false;
Anders Carlsson27f69d02009-11-27 22:21:51 +00001126}
1127
Anders Carlssonbf540272009-12-04 02:56:03 +00001128void VtableBuilder::AppendMethodsToVtable() {
Eli Friedman152b5b12009-12-05 01:05:03 +00001129 if (!BuildVtable) {
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001130 VtableComponents.insert(VtableComponents.end(), Methods.size(),
1131 (llvm::Constant *)0);
Eli Friedman152b5b12009-12-05 01:05:03 +00001132 ThisAdjustments.clear();
1133 BaseReturnTypes.clear();
1134 Methods.clear();
1135 return;
1136 }
1137
Anders Carlsson15318f42009-12-04 16:19:30 +00001138 // Reserve room in the vtable for our new methods.
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001139 VtableComponents.reserve(VtableComponents.size() + Methods.size());
Anders Carlsson29202d52009-12-04 03:07:26 +00001140
Anders Carlssonb73ba392009-12-04 02:43:50 +00001141 for (unsigned i = 0, e = Methods.size(); i != e; ++i) {
1142 GlobalDecl GD = Methods[i];
Anders Carlssonea357222009-12-04 02:52:22 +00001143 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1144
1145 // Get the 'this' pointer adjustment.
Anders Carlssonb73ba392009-12-04 02:43:50 +00001146 ThunkAdjustment ThisAdjustment = ThisAdjustments.lookup(i);
Anders Carlssonea357222009-12-04 02:52:22 +00001147
1148 // Construct the return type adjustment.
1149 ThunkAdjustment ReturnAdjustment;
1150
1151 QualType BaseReturnType = BaseReturnTypes.lookup(i);
1152 if (!BaseReturnType.isNull() && !MD->isPure()) {
1153 QualType DerivedType =
1154 MD->getType()->getAs<FunctionType>()->getResultType();
1155
1156 int64_t NonVirtualAdjustment =
1157 getNVOffset(BaseReturnType, DerivedType) / 8;
1158
1159 int64_t VirtualAdjustment =
1160 getVbaseOffset(BaseReturnType, DerivedType);
1161
1162 ReturnAdjustment = ThunkAdjustment(NonVirtualAdjustment,
1163 VirtualAdjustment);
1164 }
1165
Anders Carlsson2fce2162009-12-04 03:06:03 +00001166 llvm::Constant *Method = 0;
Anders Carlssonea357222009-12-04 02:52:22 +00001167 if (!ReturnAdjustment.isEmpty()) {
1168 // Build a covariant thunk.
1169 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Eli Friedman72649ed2009-12-06 22:01:30 +00001170 Method = wrap(CGM.GetAddrOfCovariantThunk(GD, Adjustment));
Anders Carlssonea357222009-12-04 02:52:22 +00001171 } else if (!ThisAdjustment.isEmpty()) {
1172 // Build a "regular" thunk.
Eli Friedman72649ed2009-12-06 22:01:30 +00001173 Method = wrap(CGM.GetAddrOfThunk(GD, ThisAdjustment));
Anders Carlssonbf540272009-12-04 02:56:03 +00001174 } else if (MD->isPure()) {
1175 // We have a pure virtual method.
Anders Carlsson2fce2162009-12-04 03:06:03 +00001176 Method = getPureVirtualFn();
1177 } else {
1178 // We have a good old regular method.
1179 Method = WrapAddrOf(GD);
Anders Carlssonea357222009-12-04 02:52:22 +00001180 }
Anders Carlsson2fce2162009-12-04 03:06:03 +00001181
1182 // Add the method to the vtable.
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001183 VtableComponents.push_back(Method);
Anders Carlssonb73ba392009-12-04 02:43:50 +00001184 }
1185
Anders Carlsson2fce2162009-12-04 03:06:03 +00001186
Anders Carlssonb73ba392009-12-04 02:43:50 +00001187 ThisAdjustments.clear();
Anders Carlssonea357222009-12-04 02:52:22 +00001188 BaseReturnTypes.clear();
Anders Carlssonb73ba392009-12-04 02:43:50 +00001189
Anders Carlssonadfa2672009-12-04 02:39:04 +00001190 Methods.clear();
Anders Carlssonadfa2672009-12-04 02:39:04 +00001191}
1192
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001193void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
1194
1195 // Itanium C++ ABI 2.5.2:
1196 // The order of the virtual function pointers in a virtual table is the
1197 // order of declaration of the corresponding member functions in the class.
1198 //
1199 // There is an entry for any virtual function declared in a class,
1200 // whether it is a new function or overrides a base class function,
1201 // unless it overrides a function from the primary base, and conversion
1202 // between their return types does not require an adjustment.
1203
1204 int64_t CurrentIndex = 0;
1205
1206 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1207 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1208
1209 if (PrimaryBase) {
Anders Carlsson0121fbd2009-11-30 19:43:26 +00001210 assert(PrimaryBase->isDefinition() &&
1211 "Should have the definition decl of the primary base!");
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001212
1213 // Since the record decl shares its vtable pointer with the primary base
1214 // we need to start counting at the end of the primary base's vtable.
1215 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
1216 }
Eli Friedmanea5ae312009-12-15 03:31:17 +00001217
1218 // Collect all the primary bases, so we can check whether methods override
1219 // a method from the base.
1220 llvm::SmallPtrSet<const CXXRecordDecl *, 5> PrimaryBases;
1221 for (ASTRecordLayout::primary_base_info_iterator
1222 I = Layout.primary_base_begin(), E = Layout.primary_base_end();
1223 I != E; ++I)
1224 PrimaryBases.insert((*I).getBase());
1225
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001226 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1227
1228 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
1229 e = RD->method_end(); i != e; ++i) {
1230 const CXXMethodDecl *MD = *i;
1231
1232 // We only want virtual methods.
1233 if (!MD->isVirtual())
1234 continue;
1235
1236 bool ShouldAddEntryForMethod = true;
1237
1238 // Check if this method overrides a method in the primary base.
1239 for (CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
1240 e = MD->end_overridden_methods(); i != e; ++i) {
Anders Carlsson3aaf4862009-12-04 05:51:56 +00001241 const CXXMethodDecl *OverriddenMD = *i;
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001242 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
1243 assert(OverriddenMD->isCanonicalDecl() &&
1244 "Should have the canonical decl of the overridden RD!");
1245
Eli Friedmanea5ae312009-12-15 03:31:17 +00001246 if (PrimaryBases.count(OverriddenRD)) {
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001247 // Check if converting from the return type of the method to the
1248 // return type of the overridden method requires conversion.
1249 QualType ReturnType =
1250 MD->getType()->getAs<FunctionType>()->getResultType();
1251 QualType OverriddenReturnType =
1252 OverriddenMD->getType()->getAs<FunctionType>()->getResultType();
1253
1254 if (!TypeConversionRequiresAdjustment(CGM.getContext(),
1255 ReturnType, OverriddenReturnType)) {
1256 // This index is shared between the index in the vtable of the primary
1257 // base class.
1258 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1259 const CXXDestructorDecl *OverriddenDD =
1260 cast<CXXDestructorDecl>(OverriddenMD);
1261
1262 // Add both the complete and deleting entries.
1263 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
1264 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
1265 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
1266 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
1267 } else {
1268 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
1269 }
1270
1271 // We don't need to add an entry for this method.
1272 ShouldAddEntryForMethod = false;
1273 break;
1274 }
1275 }
1276 }
1277
1278 if (!ShouldAddEntryForMethod)
1279 continue;
1280
1281 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1282 if (MD->isImplicit()) {
1283 assert(!ImplicitVirtualDtor &&
1284 "Did already see an implicit virtual dtor!");
1285 ImplicitVirtualDtor = DD;
1286 continue;
1287 }
1288
1289 // Add the complete dtor.
1290 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
1291
1292 // Add the deleting dtor.
1293 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
1294 } else {
1295 // Add the entry.
1296 MethodVtableIndices[MD] = CurrentIndex++;
1297 }
1298 }
1299
1300 if (ImplicitVirtualDtor) {
1301 // Itanium C++ ABI 2.5.2:
1302 // If a class has an implicitly-defined virtual destructor,
1303 // its entries come after the declared virtual function pointers.
1304
1305 // Add the complete dtor.
1306 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
1307 CurrentIndex++;
1308
1309 // Add the deleting dtor.
1310 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
1311 CurrentIndex++;
1312 }
1313
1314 NumVirtualFunctionPointers[RD] = CurrentIndex;
1315}
1316
1317uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
1318 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1319 NumVirtualFunctionPointers.find(RD);
1320 if (I != NumVirtualFunctionPointers.end())
1321 return I->second;
1322
1323 ComputeMethodVtableIndices(RD);
1324
1325 I = NumVirtualFunctionPointers.find(RD);
1326 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
1327 return I->second;
1328}
1329
1330uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssona0fdd912009-11-13 17:08:56 +00001331 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001332 if (I != MethodVtableIndices.end())
1333 return I->second;
1334
Anders Carlssona0fdd912009-11-13 17:08:56 +00001335 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001336
1337 ComputeMethodVtableIndices(RD);
1338
Anders Carlssona0fdd912009-11-13 17:08:56 +00001339 I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001340 assert(I != MethodVtableIndices.end() && "Did not find index!");
1341 return I->second;
1342}
1343
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001344CGVtableInfo::AdjustmentVectorTy*
1345CGVtableInfo::getAdjustments(GlobalDecl GD) {
1346 SavedAdjustmentsTy::iterator I = SavedAdjustments.find(GD);
1347 if (I != SavedAdjustments.end())
1348 return &I->second;
Eli Friedman72649ed2009-12-06 22:01:30 +00001349
1350 const CXXRecordDecl *RD = cast<CXXRecordDecl>(GD.getDecl()->getDeclContext());
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001351 if (!SavedAdjustmentRecords.insert(RD).second)
1352 return 0;
Eli Friedman72649ed2009-12-06 22:01:30 +00001353
Anders Carlsson1bb60992010-01-14 02:29:07 +00001354 AddressPointsMapTy AddressPoints;
1355 VtableBuilder b(RD, RD, 0, CGM, false, AddressPoints);
Eli Friedman72649ed2009-12-06 22:01:30 +00001356 D1(printf("vtable %s\n", RD->getNameAsCString()));
1357 b.GenerateVtableForBase(RD);
1358 b.GenerateVtableForVBases(RD);
Eli Friedman72649ed2009-12-06 22:01:30 +00001359
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001360 for (VtableBuilder::SavedAdjustmentsVectorTy::iterator
1361 i = b.getSavedAdjustments().begin(),
1362 e = b.getSavedAdjustments().end(); i != e; i++)
1363 SavedAdjustments[i->first].push_back(i->second);
Eli Friedman72649ed2009-12-06 22:01:30 +00001364
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001365 I = SavedAdjustments.find(GD);
1366 if (I != SavedAdjustments.end())
1367 return &I->second;
1368
1369 return 0;
Eli Friedman72649ed2009-12-06 22:01:30 +00001370}
1371
Anders Carlssondbd920c2009-10-11 22:13:54 +00001372int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
1373 const CXXRecordDecl *VBase) {
1374 ClassPairTy ClassPair(RD, VBase);
1375
1376 VirtualBaseClassIndiciesTy::iterator I =
1377 VirtualBaseClassIndicies.find(ClassPair);
1378 if (I != VirtualBaseClassIndicies.end())
1379 return I->second;
1380
Anders Carlssondbd920c2009-10-11 22:13:54 +00001381 // FIXME: This seems expensive. Can we do a partial job to get
1382 // just this data.
Anders Carlsson1bb60992010-01-14 02:29:07 +00001383 AddressPointsMapTy AddressPoints;
1384 VtableBuilder b(RD, RD, 0, CGM, false, AddressPoints);
Mike Stump6a9612f2009-10-31 20:06:59 +00001385 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00001386 b.GenerateVtableForBase(RD);
1387 b.GenerateVtableForVBases(RD);
1388
1389 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1390 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
1391 // Insert all types.
1392 ClassPairTy ClassPair(RD, I->first);
1393
1394 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
1395 }
1396
1397 I = VirtualBaseClassIndicies.find(ClassPair);
1398 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
1399
1400 return I->second;
1401}
1402
Anders Carlsson9ac95b92009-12-05 21:03:56 +00001403uint64_t CGVtableInfo::getVtableAddressPoint(const CXXRecordDecl *RD) {
1404 uint64_t AddressPoint =
Anders Carlsson21431c52010-01-02 18:02:32 +00001405 (*(*(CGM.getVtableInfo().AddressPoints[RD]))[RD])[std::make_pair(RD, 0)];
Anders Carlsson9ac95b92009-12-05 21:03:56 +00001406
1407 return AddressPoint;
1408}
1409
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00001410llvm::GlobalVariable *
Anders Carlsson35272252009-12-06 00:23:49 +00001411CGVtableInfo::GenerateVtable(llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson5794c972009-12-06 00:53:22 +00001412 bool GenerateDefinition,
Anders Carlsson35272252009-12-06 00:23:49 +00001413 const CXXRecordDecl *LayoutClass,
Anders Carlsson1bb60992010-01-14 02:29:07 +00001414 const CXXRecordDecl *RD, uint64_t Offset,
1415 AddressPointsMapTy& AddressPoints) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001416 llvm::SmallString<256> OutName;
Mike Stump9840c702009-11-12 20:47:57 +00001417 if (LayoutClass != RD)
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00001418 CGM.getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset / 8,
1419 RD, OutName);
Mike Stump8cfcb522009-11-11 20:26:26 +00001420 else
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00001421 CGM.getMangleContext().mangleCXXVtable(RD, OutName);
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00001422 llvm::StringRef Name = OutName.str();
Benjamin Kramer7a9474e2009-10-11 22:57:54 +00001423
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00001424 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
Anders Carlsson21431c52010-01-02 18:02:32 +00001425 if (GV == 0 || CGM.getVtableInfo().AddressPoints[LayoutClass] == 0 ||
1426 GV->isDeclaration()) {
Anders Carlsson1bb60992010-01-14 02:29:07 +00001427 VtableBuilder b(RD, LayoutClass, Offset, CGM, GenerateDefinition,
1428 AddressPoints);
Eli Friedman152b5b12009-12-05 01:05:03 +00001429
1430 D1(printf("vtable %s\n", RD->getNameAsCString()));
1431 // First comes the vtables for all the non-virtual bases...
Mike Stump8cc4f102009-12-24 07:29:41 +00001432 b.GenerateVtableForBase(RD, Offset);
Eli Friedman152b5b12009-12-05 01:05:03 +00001433
1434 // then the vtables for all the virtual bases.
1435 b.GenerateVtableForVBases(RD, Offset);
1436
Anders Carlsson152d4dc2009-12-05 22:19:10 +00001437 llvm::Constant *Init = 0;
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00001438 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Anders Carlsson152d4dc2009-12-05 22:19:10 +00001439 llvm::ArrayType *ArrayType =
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001440 llvm::ArrayType::get(Int8PtrTy, b.getVtableComponents().size());
Anders Carlssone40477c2009-12-05 21:09:05 +00001441
Anders Carlsson5794c972009-12-06 00:53:22 +00001442 if (GenerateDefinition)
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001443 Init = llvm::ConstantArray::get(ArrayType, &b.getVtableComponents()[0],
1444 b.getVtableComponents().size());
Anders Carlsson5794c972009-12-06 00:53:22 +00001445
Mike Stump85615df2009-11-19 04:04:36 +00001446 llvm::GlobalVariable *OGV = GV;
Anders Carlsson5794c972009-12-06 00:53:22 +00001447
1448 GV = new llvm::GlobalVariable(CGM.getModule(), ArrayType,
1449 /*isConstant=*/true, Linkage, Init, Name);
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001450 CGM.setGlobalVisibility(GV, RD);
1451
Mike Stump85615df2009-11-19 04:04:36 +00001452 if (OGV) {
1453 GV->takeName(OGV);
Anders Carlsson152d4dc2009-12-05 22:19:10 +00001454 llvm::Constant *NewPtr =
1455 llvm::ConstantExpr::getBitCast(GV, OGV->getType());
Mike Stump85615df2009-11-19 04:04:36 +00001456 OGV->replaceAllUsesWith(NewPtr);
1457 OGV->eraseFromParent();
1458 }
Mike Stump85615df2009-11-19 04:04:36 +00001459 }
Anders Carlssonbb27d862009-12-05 21:28:12 +00001460
1461 return GV;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001462}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001463
Anders Carlsson5794c972009-12-06 00:53:22 +00001464void CGVtableInfo::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
1465 const CXXRecordDecl *RD) {
Anders Carlssond58987c2009-12-07 07:59:52 +00001466 llvm::GlobalVariable *&Vtable = Vtables[RD];
1467 if (Vtable) {
1468 assert(Vtable->getInitializer() && "Vtable doesn't have a definition!");
1469 return;
1470 }
1471
Anders Carlsson1bb60992010-01-14 02:29:07 +00001472 AddressPointsMapTy AddressPoints;
1473 Vtable = GenerateVtable(Linkage, /*GenerateDefinition=*/true, RD, RD, 0,
1474 AddressPoints);
Anders Carlssonc997d422010-01-02 01:01:18 +00001475 GenerateVTT(Linkage, /*GenerateDefinition=*/true, RD);
Mike Stump58588942009-11-19 01:08:19 +00001476}
1477
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00001478llvm::GlobalVariable *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Anders Carlsson5794c972009-12-06 00:53:22 +00001479 llvm::GlobalVariable *Vtable = Vtables.lookup(RD);
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00001480
Anders Carlsson1bb60992010-01-14 02:29:07 +00001481 if (!Vtable) {
1482 AddressPointsMapTy AddressPoints;
Anders Carlsson5794c972009-12-06 00:53:22 +00001483 Vtable = GenerateVtable(llvm::GlobalValue::ExternalLinkage,
Anders Carlsson1bb60992010-01-14 02:29:07 +00001484 /*GenerateDefinition=*/false, RD, RD, 0,
1485 AddressPoints);
1486 }
Mike Stump85615df2009-11-19 04:04:36 +00001487
Anders Carlsson224c3122009-12-05 22:42:54 +00001488 return Vtable;
Mike Stump380dd752009-11-10 07:44:33 +00001489}
Mike Stump8cfcb522009-11-11 20:26:26 +00001490
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001491void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
1492 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1493 const CXXRecordDecl *RD = MD->getParent();
1494
Anders Carlsson224c3122009-12-05 22:42:54 +00001495 // If the class doesn't have a vtable we don't need to emit one.
1496 if (!RD->isDynamicClass())
1497 return;
1498
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001499 // Get the key function.
Anders Carlssonf53df232009-12-07 04:35:11 +00001500 const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001501
Anders Carlsson224c3122009-12-05 22:42:54 +00001502 if (KeyFunction) {
1503 // We don't have the right key function.
1504 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
1505 return;
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001506 }
1507
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001508 // Emit the data.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001509 GenerateClassData(CGM.getVtableLinkage(RD), RD);
Eli Friedman72649ed2009-12-06 22:01:30 +00001510
1511 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
1512 e = RD->method_end(); i != e; ++i) {
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001513 if ((*i)->isVirtual() && ((*i)->hasInlineBody() || (*i)->isImplicit())) {
Eli Friedman72649ed2009-12-06 22:01:30 +00001514 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(*i)) {
1515 CGM.BuildThunksForVirtual(GlobalDecl(DD, Dtor_Complete));
1516 CGM.BuildThunksForVirtual(GlobalDecl(DD, Dtor_Deleting));
1517 } else {
1518 CGM.BuildThunksForVirtual(GlobalDecl(*i));
1519 }
1520 }
1521 }
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00001522}
1523