blob: 93153e31b6b7cbfc76b3a2bf5137e3e5c64835ff [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"
Anders Carlsson28cbc8b2010-02-12 07:43:48 +000019#include "llvm/ADT/StringExtras.h"
Anders Carlsson824d7ea2010-02-11 08:02:13 +000020#include "llvm/Support/Format.h"
Zhongxing Xu7fe26ac2009-11-13 05:46:16 +000021#include <cstdio>
Anders Carlssondbd920c2009-10-11 22:13:54 +000022
23using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson9a140602010-02-11 19:39:49 +000026/// TypeConversionRequiresAdjustment - Returns whether conversion from a
27/// derived type to a base type requires adjustment.
28static bool
29TypeConversionRequiresAdjustment(ASTContext &Ctx,
30 const CXXRecordDecl *DerivedDecl,
31 const CXXRecordDecl *BaseDecl) {
32 CXXBasePaths Paths(/*FindAmbiguities=*/false,
33 /*RecordPaths=*/true, /*DetectVirtual=*/true);
34 if (!const_cast<CXXRecordDecl *>(DerivedDecl)->
35 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseDecl), Paths)) {
36 assert(false && "Class must be derived from the passed in base class!");
37 return false;
38 }
39
40 // If we found a virtual base we always want to require adjustment.
41 if (Paths.getDetectedVirtual())
42 return true;
43
44 const CXXBasePath &Path = Paths.front();
45
46 for (size_t Start = 0, End = Path.size(); Start != End; ++Start) {
47 const CXXBasePathElement &Element = Path[Start];
48
49 // Check the base class offset.
50 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Element.Class);
51
52 const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
53 const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
54
55 if (Layout.getBaseClassOffset(Base) != 0) {
56 // This requires an adjustment.
57 return true;
58 }
59 }
60
61 return false;
62}
63
64static bool
65TypeConversionRequiresAdjustment(ASTContext &Ctx,
66 QualType DerivedType, QualType BaseType) {
67 // Canonicalize the types.
John McCall96058952010-02-12 06:15:07 +000068 CanQualType CanDerivedType = Ctx.getCanonicalType(DerivedType);
69 CanQualType CanBaseType = Ctx.getCanonicalType(BaseType);
Anders Carlsson9a140602010-02-11 19:39:49 +000070
71 assert(CanDerivedType->getTypeClass() == CanBaseType->getTypeClass() &&
72 "Types must have same type class!");
73
74 if (CanDerivedType == CanBaseType) {
75 // No adjustment needed.
76 return false;
77 }
78
John McCall96058952010-02-12 06:15:07 +000079 if (isa<ReferenceType>(CanDerivedType)) {
80 CanDerivedType = CanDerivedType->getAs<ReferenceType>()->getPointeeType();
Anders Carlsson9abb2732010-02-11 19:45:15 +000081 CanBaseType = CanBaseType->getAs<ReferenceType>()->getPointeeType();
John McCall96058952010-02-12 06:15:07 +000082 } else if (isa<PointerType>(CanDerivedType)) {
83 CanDerivedType = CanDerivedType->getAs<PointerType>()->getPointeeType();
Anders Carlsson9abb2732010-02-11 19:45:15 +000084 CanBaseType = CanBaseType->getAs<PointerType>()->getPointeeType();
Anders Carlsson9a140602010-02-11 19:39:49 +000085 } else {
86 assert(false && "Unexpected return type!");
87 }
88
John McCall96058952010-02-12 06:15:07 +000089 // We need to compare unqualified types here; consider
90 // const T *Base::foo();
91 // T *Derived::foo();
92 if (CanDerivedType.getUnqualifiedType() == CanBaseType.getUnqualifiedType()) {
Anders Carlsson9a140602010-02-11 19:39:49 +000093 // No adjustment needed.
94 return false;
95 }
96
97 const CXXRecordDecl *DerivedDecl =
John McCall96058952010-02-12 06:15:07 +000098 cast<CXXRecordDecl>(cast<RecordType>(CanDerivedType)->getDecl());
Anders Carlsson9a140602010-02-11 19:39:49 +000099
100 const CXXRecordDecl *BaseDecl =
John McCall96058952010-02-12 06:15:07 +0000101 cast<CXXRecordDecl>(cast<RecordType>(CanBaseType)->getDecl());
Anders Carlsson9a140602010-02-11 19:39:49 +0000102
103 return TypeConversionRequiresAdjustment(Ctx, DerivedDecl, BaseDecl);
104}
105
Anders Carlsson57071e22010-02-12 05:25:12 +0000106static bool
Anders Carlsson104f45c2010-02-12 17:37:14 +0000107ReturnTypeConversionRequiresAdjustment(const CXXMethodDecl *DerivedMD,
Anders Carlsson57071e22010-02-12 05:25:12 +0000108 const CXXMethodDecl *BaseMD) {
Anders Carlsson104f45c2010-02-12 17:37:14 +0000109 ASTContext &Context = DerivedMD->getASTContext();
110
Anders Carlsson57071e22010-02-12 05:25:12 +0000111 const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
112 const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
113
114 return TypeConversionRequiresAdjustment(Context, DerivedFT->getResultType(),
115 BaseFT->getResultType());
116}
117
Anders Carlsson27f69d02009-11-27 22:21:51 +0000118namespace {
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000119
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000120/// FinalOverriders - Contains the final overrider member functions for all
121/// member functions in the base subobjects of a class.
122class FinalOverriders {
Anders Carlssona7575822010-02-12 16:55:34 +0000123public:
124 /// OverriderInfo - Information about a final overrider.
125 struct OverriderInfo {
126 /// Method - The method decl of the overrider.
127 const CXXMethodDecl *Method;
128
Anders Carlsson16b73122010-02-12 17:13:23 +0000129 /// NeedsReturnAdjustment - Whether this overrider needs to adjust its
130 /// return type.
131 bool NeedsReturnAdjustment;
132
133 OverriderInfo() : Method(0), NeedsReturnAdjustment(false) { }
Anders Carlssona7575822010-02-12 16:55:34 +0000134 };
135
136private:
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000137 /// MostDerivedClass - The most derived class for which the final overriders
138 /// are stored.
139 const CXXRecordDecl *MostDerivedClass;
140
141 ASTContext &Context;
142
143 /// MostDerivedClassLayout - the AST record layout of the most derived class.
144 const ASTRecordLayout &MostDerivedClassLayout;
145
146 typedef llvm::DenseMap<std::pair<BaseSubobject, const CXXMethodDecl *>,
Anders Carlssona7575822010-02-12 16:55:34 +0000147 OverriderInfo> OverridersMapTy;
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000148
149 /// OverridersMap - The final overriders for all virtual member functions of
150 /// all the base subobjects of the most derived class.
151 OverridersMapTy OverridersMap;
152
Anders Carlssonb8358d82010-02-12 01:40:03 +0000153 typedef llvm::SmallVector<uint64_t, 1> OffsetVectorTy;
154
155 /// SubobjectOffsetsMapTy - This map is used for keeping track of all the
156 /// base subobject offsets that a single class declaration might refer to.
157 ///
158 /// For example, in:
159 ///
160 /// struct A { virtual void f(); };
161 /// struct B1 : A { };
162 /// struct B2 : A { };
163 /// struct C : B1, B2 { virtual void f(); };
164 ///
165 /// when we determine that C::f() overrides A::f(), we need to update the
166 /// overriders map for both A-in-B1 and A-in-B2 and the subobject offsets map
167 /// will have the subobject offsets for both A copies.
168 typedef llvm::DenseMap<const CXXRecordDecl *, OffsetVectorTy>
169 SubobjectOffsetsMapTy;
170
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000171 /// ComputeFinalOverriders - Compute the final overriders for a given base
172 /// subobject (and all its direct and indirect bases).
Anders Carlssonb8358d82010-02-12 01:40:03 +0000173 void ComputeFinalOverriders(BaseSubobject Base,
174 SubobjectOffsetsMapTy &Offsets);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000175
176 /// AddOverriders - Add the final overriders for this base subobject to the
177 /// map of final overriders.
Anders Carlssonb8358d82010-02-12 01:40:03 +0000178 void AddOverriders(BaseSubobject Base, SubobjectOffsetsMapTy &Offsets);
179
180 /// PropagateOverrider - Propagate the NewMD overrider to all the functions
181 /// that OldMD overrides. For example, if we have:
182 ///
183 /// struct A { virtual void f(); };
184 /// struct B : A { virtual void f(); };
185 /// struct C : B { virtual void f(); };
186 ///
187 /// and we want to override B::f with C::f, we also need to override A::f with
188 /// C::f.
189 void PropagateOverrider(const CXXMethodDecl *OldMD,
190 const CXXMethodDecl *NewMD,
191 SubobjectOffsetsMapTy &Offsets);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000192
Anders Carlssonb8358d82010-02-12 01:40:03 +0000193 static void MergeSubobjectOffsets(const SubobjectOffsetsMapTy &NewOffsets,
194 SubobjectOffsetsMapTy &Offsets);
195
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000196public:
197 explicit FinalOverriders(const CXXRecordDecl *MostDerivedClass);
198
199 /// getOverrider - Get the final overrider for the given method declaration in
200 /// the given base subobject.
Anders Carlssona7575822010-02-12 16:55:34 +0000201 const OverriderInfo getOverrider(BaseSubobject Base,
202 const CXXMethodDecl *MD) const {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000203 assert(OverridersMap.count(std::make_pair(Base, MD)) &&
204 "Did not find overrider!");
205
206 return OverridersMap.lookup(std::make_pair(Base, MD));
207 }
208
209 /// dump - dump the final overriders.
210 void dump() const {
211 dump(llvm::errs(), BaseSubobject(MostDerivedClass, 0));
212 }
213
214 /// dump - dump the final overriders for a base subobject, and all its direct
215 /// and indirect base subobjects.
216 void dump(llvm::raw_ostream &Out, BaseSubobject Base) const;
217};
218
219FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass)
220 : MostDerivedClass(MostDerivedClass),
221 Context(MostDerivedClass->getASTContext()),
222 MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
223
224 // Compute the final overriders.
Anders Carlssonb8358d82010-02-12 01:40:03 +0000225 SubobjectOffsetsMapTy Offsets;
226 ComputeFinalOverriders(BaseSubobject(MostDerivedClass, 0), Offsets);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000227
228 // And dump them (for now).
229 dump();
230}
231
Anders Carlssonb8358d82010-02-12 01:40:03 +0000232void FinalOverriders::AddOverriders(BaseSubobject Base,
233 SubobjectOffsetsMapTy &Offsets) {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000234 const CXXRecordDecl *RD = Base.getBase();
235
236 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
237 E = RD->method_end(); I != E; ++I) {
238 const CXXMethodDecl *MD = *I;
239
240 if (!MD->isVirtual())
241 continue;
242
Anders Carlssonb8358d82010-02-12 01:40:03 +0000243 // First, propagate the overrider.
244 PropagateOverrider(MD, MD, Offsets);
245
246 // Add the overrider as the final overrider of itself.
Anders Carlssona7575822010-02-12 16:55:34 +0000247 OverriderInfo& Overrider = OverridersMap[std::make_pair(Base, MD)];
248 assert(!Overrider.Method && "Overrider should not exist yet!");
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000249
Anders Carlssona7575822010-02-12 16:55:34 +0000250 Overrider.Method = MD;
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000251 }
252}
253
Anders Carlssonb8358d82010-02-12 01:40:03 +0000254void FinalOverriders::PropagateOverrider(const CXXMethodDecl *OldMD,
255 const CXXMethodDecl *NewMD,
256 SubobjectOffsetsMapTy &Offsets) {
257 for (CXXMethodDecl::method_iterator I = OldMD->begin_overridden_methods(),
258 E = OldMD->end_overridden_methods(); I != E; ++I) {
259 const CXXMethodDecl *OverriddenMD = *I;
260 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
261
262 // We want to override OverriddenMD in all subobjects, for example:
263 //
264 /// struct A { virtual void f(); };
265 /// struct B1 : A { };
266 /// struct B2 : A { };
267 /// struct C : B1, B2 { virtual void f(); };
268 ///
269 /// When overriding A::f with C::f we need to do so in both A subobjects.
270 const OffsetVectorTy &OffsetVector = Offsets[OverriddenRD];
271
272 // Go through all the subobjects.
273 for (unsigned I = 0, E = OffsetVector.size(); I != E; ++I) {
274 uint64_t Offset = OffsetVector[I];
275
Anders Carlssona7575822010-02-12 16:55:34 +0000276 OverriderInfo &Overrider =
Anders Carlssonb8358d82010-02-12 01:40:03 +0000277 OverridersMap[std::make_pair(BaseSubobject(OverriddenRD, Offset),
278 OverriddenMD)];
Anders Carlssona7575822010-02-12 16:55:34 +0000279 assert(Overrider.Method && "Did not find existing overrider!");
Anders Carlssonb8358d82010-02-12 01:40:03 +0000280
Anders Carlsson16b73122010-02-12 17:13:23 +0000281 /// We only need to do the return type check if the overrider doesn't
282 /// already need a return adjustment. Consider:
283 ///
284 /// struct A { virtual V1 *f(); }
285 /// struct B : A { virtual V2 *f(); }
286 /// struct C : B { virtual V2 *f(); }
287 ///
288 /// If we assume that that V2->V1 needs an adjustment, then when we
289 /// know that since A::f -> B::f needs an adjustment, then all classes
290 /// that eventually override B::f (and by transitivity A::f) are going to
291 /// need to have their return types adjusted.
292 if (!Overrider.NeedsReturnAdjustment) {
293 Overrider.NeedsReturnAdjustment =
Anders Carlsson104f45c2010-02-12 17:37:14 +0000294 ReturnTypeConversionRequiresAdjustment(NewMD, OverriddenMD);
Anders Carlsson16b73122010-02-12 17:13:23 +0000295 }
296
Anders Carlssonb8358d82010-02-12 01:40:03 +0000297 // Set the new overrider.
Anders Carlssona7575822010-02-12 16:55:34 +0000298 Overrider.Method = NewMD;
Anders Carlssonb8358d82010-02-12 01:40:03 +0000299
300 // And propagate it further.
301 PropagateOverrider(OverriddenMD, NewMD, Offsets);
302 }
303 }
304}
305
306void
307FinalOverriders::MergeSubobjectOffsets(const SubobjectOffsetsMapTy &NewOffsets,
308 SubobjectOffsetsMapTy &Offsets) {
309 // Iterate over the new offsets.
310 for (SubobjectOffsetsMapTy::const_iterator I = NewOffsets.begin(),
311 E = NewOffsets.end(); I != E; ++I) {
312 const CXXRecordDecl *NewRD = I->first;
313 const OffsetVectorTy& NewOffsetsVector = I->second;
314
315 OffsetVectorTy &OffsetsVector = Offsets[NewRD];
316 if (OffsetsVector.empty()) {
317 // There were no previous offsets in this vector, just insert all entries
318 // from the new offsets vector.
319 OffsetsVector.append(NewOffsetsVector.begin(), NewOffsetsVector.end());
320 continue;
321 }
322
323 assert(false && "FIXME: Handle merging the subobject offsets!");
324 }
325}
326
327void FinalOverriders::ComputeFinalOverriders(BaseSubobject Base,
328 SubobjectOffsetsMapTy &Offsets) {
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000329 const CXXRecordDecl *RD = Base.getBase();
Anders Carlssonb8358d82010-02-12 01:40:03 +0000330 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000331
Anders Carlssonb8358d82010-02-12 01:40:03 +0000332 SubobjectOffsetsMapTy NewOffsets;
333
334 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
335 E = RD->bases_end(); I != E; ++I) {
336 const CXXRecordDecl *BaseDecl =
337 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
338
339 assert(!I->isVirtual() && "FIXME: Handle virtual bases!");
340
341 uint64_t BaseOffset = Layout.getBaseClassOffset(BaseDecl) +
342 Base.getBaseOffset();
343
344 // Compute the final overriders for this base.
345 ComputeFinalOverriders(BaseSubobject(BaseDecl, BaseOffset), NewOffsets);
346 }
347
348 /// Now add the overriders for this particular subobject.
349 AddOverriders(Base, NewOffsets);
350
351 // And merge the newly discovered subobject offsets.
352 MergeSubobjectOffsets(NewOffsets, Offsets);
353
354 /// Finally, add the offset for our own subobject.
355 Offsets[RD].push_back(Base.getBaseOffset());
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000356}
357
358void FinalOverriders::dump(llvm::raw_ostream &Out, BaseSubobject Base) const {
359
360 const CXXRecordDecl *RD = Base.getBase();
361 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
362
363 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
364 E = RD->bases_end(); I != E; ++I) {
365 assert(!I->isVirtual() && "FIXME: Handle virtual bases!");
366
367 const CXXRecordDecl *BaseDecl =
368 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
369
370 uint64_t BaseOffset = Layout.getBaseClassOffset(BaseDecl) +
371 Base.getBaseOffset();
372
373 dump(Out, BaseSubobject(BaseDecl, BaseOffset));
374 }
375
376 Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
377 Out << Base.getBaseOffset() << ")\n";
378
379 // Now dump the overriders for this base subobject.
380 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
381 E = RD->method_end(); I != E; ++I) {
382 const CXXMethodDecl *MD = *I;
383
384 if (!MD->isVirtual())
385 continue;
386
Anders Carlssona7575822010-02-12 16:55:34 +0000387 OverriderInfo Overrider = getOverrider(Base, MD);
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000388
389 Out << " " << MD->getQualifiedNameAsString() << " - ";
Anders Carlsson16b73122010-02-12 17:13:23 +0000390 Out << Overrider.Method->getQualifiedNameAsString();
391 if (Overrider.NeedsReturnAdjustment)
392 Out << " [ret-adj]";
393 Out << "\n";
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000394 }
395}
396
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000397/// VtableComponent - Represents a single component in a vtable.
398class VtableComponent {
399public:
400 enum Kind {
401 CK_VCallOffset,
402 CK_VBaseOffset,
403 CK_OffsetToTop,
404 CK_RTTI,
Anders Carlsson848fa642010-02-11 18:20:28 +0000405 CK_FunctionPointer,
406
407 /// CK_CompleteDtorPointer - A pointer to the complete destructor.
408 CK_CompleteDtorPointer,
409
410 /// CK_DeletingDtorPointer - A pointer to the deleting destructor.
411 CK_DeletingDtorPointer
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000412 };
413
414 /// dump - Dump the contents of this component to the given stream.
415 void dump(llvm::raw_ostream &Out);
416
417 static VtableComponent MakeOffsetToTop(int64_t Offset) {
418 return VtableComponent(CK_OffsetToTop, Offset);
419 }
420
421 static VtableComponent MakeRTTI(const CXXRecordDecl *RD) {
422 return VtableComponent(CK_RTTI, reinterpret_cast<uintptr_t>(RD));
423 }
424
425 static VtableComponent MakeFunction(const CXXMethodDecl *MD) {
426 assert(!isa<CXXDestructorDecl>(MD) &&
Anders Carlsson848fa642010-02-11 18:20:28 +0000427 "Don't use MakeFunction with destructors!");
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000428
Anders Carlsson848fa642010-02-11 18:20:28 +0000429 return VtableComponent(CK_FunctionPointer,
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000430 reinterpret_cast<uintptr_t>(MD));
431 }
432
Anders Carlsson848fa642010-02-11 18:20:28 +0000433 static VtableComponent MakeCompleteDtor(const CXXDestructorDecl *DD) {
434 return VtableComponent(CK_CompleteDtorPointer,
435 reinterpret_cast<uintptr_t>(DD));
436 }
437
438 static VtableComponent MakeDeletingDtor(const CXXDestructorDecl *DD) {
439 return VtableComponent(CK_DeletingDtorPointer,
440 reinterpret_cast<uintptr_t>(DD));
441 }
442
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000443 /// getKind - Get the kind of this vtable component.
444 Kind getKind() const {
445 return (Kind)(Value & 0x7);
446 }
447
448 int64_t getOffsetToTop() const {
449 assert(getKind() == CK_OffsetToTop && "Invalid component kind!");
450
451 return getOffset();
452 }
453
454 const CXXRecordDecl *getRTTIDecl() const {
455 assert(getKind() == CK_RTTI && "Invalid component kind!");
456
457 return reinterpret_cast<CXXRecordDecl *>(getPointer());
458 }
459
460 const CXXMethodDecl *getFunctionDecl() const {
Anders Carlsson848fa642010-02-11 18:20:28 +0000461 assert(getKind() == CK_FunctionPointer);
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000462
463 return reinterpret_cast<CXXMethodDecl *>(getPointer());
464 }
Anders Carlsson848fa642010-02-11 18:20:28 +0000465
466 const CXXDestructorDecl *getDestructorDecl() const {
467 assert((getKind() == CK_CompleteDtorPointer ||
468 getKind() == CK_DeletingDtorPointer) && "Invalid component kind!");
469
470 return reinterpret_cast<CXXDestructorDecl *>(getPointer());
471 }
472
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000473private:
474 VtableComponent(Kind ComponentKind, int64_t Offset) {
475 assert((ComponentKind == CK_VCallOffset ||
476 ComponentKind == CK_VBaseOffset ||
477 ComponentKind == CK_OffsetToTop) && "Invalid component kind!");
478 assert(Offset <= ((1LL << 56) - 1) && "Offset is too big!");
479
480 Value = ((Offset << 3) | ComponentKind);
481 }
482
483 VtableComponent(Kind ComponentKind, uintptr_t Ptr) {
484 assert((ComponentKind == CK_RTTI ||
Anders Carlsson848fa642010-02-11 18:20:28 +0000485 ComponentKind == CK_FunctionPointer ||
486 ComponentKind == CK_CompleteDtorPointer ||
487 ComponentKind == CK_DeletingDtorPointer) &&
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000488 "Invalid component kind!");
489
490 assert((Ptr & 7) == 0 && "Pointer not sufficiently aligned!");
491
492 Value = Ptr | ComponentKind;
493 }
494
495 int64_t getOffset() const {
496 assert((getKind() == CK_VCallOffset || getKind() == CK_VBaseOffset ||
497 getKind() == CK_OffsetToTop) && "Invalid component kind!");
498
499 return Value >> 3;
500 }
501
502 uintptr_t getPointer() const {
Anders Carlsson848fa642010-02-11 18:20:28 +0000503 assert((getKind() == CK_RTTI ||
504 getKind() == CK_FunctionPointer ||
505 getKind() == CK_CompleteDtorPointer ||
506 getKind() == CK_DeletingDtorPointer) &&
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000507 "Invalid component kind!");
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000508
509 return static_cast<uintptr_t>(Value & ~7ULL);
510 }
511
512 /// The kind is stored in the lower 3 bits of the value. For offsets, we
513 /// make use of the facts that classes can't be larger than 2^55 bytes,
514 /// so we store the offset in the lower part of the 61 bytes that remain.
515 /// (The reason that we're not simply using a PointerIntPair here is that we
516 /// need the offsets to be 64-bit, even when on a 32-bit machine).
517 int64_t Value;
518};
519
520/// VtableBuilder - Class for building vtable layout information.
Benjamin Kramer85b45212009-11-28 19:45:26 +0000521class VtableBuilder {
Anders Carlsson57071e22010-02-12 05:25:12 +0000522public:
523 /// PrimaryBasesSetTy - A set of direct and indirect primary bases.
524 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> PrimaryBasesSetTy;
525
526private:
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000527 /// MostDerivedClass - The most derived class for which we're building this
528 /// vtable.
529 const CXXRecordDecl *MostDerivedClass;
530
531 /// Context - The ASTContext which we will use for layout information.
Anders Carlsson57071e22010-02-12 05:25:12 +0000532 ASTContext &Context;
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000533
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000534 /// FinalOverriders - The final overriders of the most derived class.
535 FinalOverriders Overriders;
536
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000537 /// Components - The components of the vtable being built.
538 llvm::SmallVector<VtableComponent, 64> Components;
539
Anders Carlsson822307b2010-02-11 17:18:51 +0000540 /// AddressPoints - Address points for the vtable being built.
541 CGVtableInfo::AddressPointsMapTy AddressPoints;
542
Anders Carlsson104f45c2010-02-12 17:37:14 +0000543 /// ReturnAdjustment - A return adjustment thunk.
544 struct ReturnAdjustment {
545 /// NonVirtual - The non-virtual adjustment from the derived object to its
546 /// nearest virtual base.
547 int64_t NonVirtual;
548
549 /// VBaseOffsetIndex - The index relative to the address point of the
550 /// virtual base class offset.
551 int64_t VBaseOffsetIndex;
552 };
553
Anders Carlsson57071e22010-02-12 05:25:12 +0000554 void layoutVirtualMemberFunctions(BaseSubobject Base,
555 PrimaryBasesSetTy &PrimaryBases);
556
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000557 /// layoutSimpleVtable - A test function that will layout very simple vtables
558 /// without any bases. Just used for testing for now.
Anders Carlsson57071e22010-02-12 05:25:12 +0000559 void layoutSimpleVtable(BaseSubobject Base);
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000560
561public:
562 VtableBuilder(const CXXRecordDecl *MostDerivedClass)
563 : MostDerivedClass(MostDerivedClass),
Anders Carlssonbdf73d82010-02-11 21:24:32 +0000564 Context(MostDerivedClass->getASTContext()), Overriders(MostDerivedClass) {
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000565
Anders Carlsson57071e22010-02-12 05:25:12 +0000566 layoutSimpleVtable(BaseSubobject(MostDerivedClass, 0));
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000567 }
568
569 /// dumpLayout - Dump the vtable layout.
570 void dumpLayout(llvm::raw_ostream&);
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000571};
572
Anders Carlsson57071e22010-02-12 05:25:12 +0000573/// OverridesMethodInPrimaryBase - Checks whether whether this virtual member
574/// function overrides a member function in a direct or indirect primary base.
575/// Returns the overridden member function, or null if none was found.
576static const CXXMethodDecl *
577OverridesMethodInPrimaryBase(const CXXMethodDecl *MD,
578 VtableBuilder::PrimaryBasesSetTy &PrimaryBases) {
579 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
580 E = MD->end_overridden_methods(); I != E; ++I) {
581 const CXXMethodDecl *OverriddenMD = *I;
582 const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
583 assert(OverriddenMD->isCanonicalDecl() &&
584 "Should have the canonical decl of the overridden RD!");
585
586 if (PrimaryBases.count(OverriddenRD))
587 return OverriddenMD;
588 }
589
590 return 0;
591}
592
593void
594VtableBuilder::layoutVirtualMemberFunctions(BaseSubobject Base,
595 PrimaryBasesSetTy &PrimaryBases) {
596 const CXXRecordDecl *RD = Base.getBase();
597
598 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
599
600 if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
601 if (Layout.getPrimaryBaseWasVirtual())
602 assert(false && "FIXME: Handle vbases here.");
603 else
604 assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
605 "Primary base should have a zero offset!");
606
607 layoutVirtualMemberFunctions(BaseSubobject(PrimaryBase, 0), PrimaryBases);
608
609 if (!PrimaryBases.insert(PrimaryBase))
610 assert(false && "Found a duplicate primary base!");
611 }
Anders Carlsson822307b2010-02-11 17:18:51 +0000612
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000613 // Now go through all virtual member functions and add them.
614 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
615 E = RD->method_end(); I != E; ++I) {
616 const CXXMethodDecl *MD = *I;
Anders Carlsson57071e22010-02-12 05:25:12 +0000617
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000618 if (!MD->isVirtual())
619 continue;
Anders Carlsson57071e22010-02-12 05:25:12 +0000620
621 // Get the final overrider.
Anders Carlssona7575822010-02-12 16:55:34 +0000622 FinalOverriders::OverriderInfo Overrider =
623 Overriders.getOverrider(Base, MD);
Anders Carlsson57071e22010-02-12 05:25:12 +0000624
625 // Check if this virtual member function overrides a method in a primary
626 // base. If this is the case, and the return type doesn't require adjustment
627 // then we can just use the member function from the primary base.
Anders Carlsson104f45c2010-02-12 17:37:14 +0000628 if (const CXXMethodDecl *OverriddenMD =
629 OverridesMethodInPrimaryBase(MD, PrimaryBases)) {
630 assert(!ReturnTypeConversionRequiresAdjustment(MD, OverriddenMD)
631 && "FIXME: Handle covariant thunks!");
Anders Carlsson57071e22010-02-12 05:25:12 +0000632
633 continue;
634 }
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000635
Anders Carlsson848fa642010-02-11 18:20:28 +0000636 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
637 // Add both the complete destructor and the deleting destructor.
638 Components.push_back(VtableComponent::MakeCompleteDtor(DD));
639 Components.push_back(VtableComponent::MakeDeletingDtor(DD));
640 } else {
641 // Add the function.
642 Components.push_back(VtableComponent::MakeFunction(MD));
643 }
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000644 }
645}
646
Anders Carlsson57071e22010-02-12 05:25:12 +0000647void VtableBuilder::layoutSimpleVtable(BaseSubobject Base) {
648 const CXXRecordDecl *RD = Base.getBase();
649
650 // First, add the offset to top.
651 Components.push_back(VtableComponent::MakeOffsetToTop(0));
652
653 // Next, add the RTTI.
654 Components.push_back(VtableComponent::MakeRTTI(RD));
655
Anders Carlsson28cbc8b2010-02-12 07:43:48 +0000656 uint64_t AddressPoint = Components.size();
Anders Carlsson57071e22010-02-12 05:25:12 +0000657
658 // Now go through all virtual member functions and add them.
659 PrimaryBasesSetTy PrimaryBases;
660 layoutVirtualMemberFunctions(Base, PrimaryBases);
661
Anders Carlsson28cbc8b2010-02-12 07:43:48 +0000662 // Record the address point.
663 AddressPoints.insert(std::make_pair(Base, AddressPoint));
664
665 // Record the address points for all primary bases.
666 for (PrimaryBasesSetTy::const_iterator I = PrimaryBases.begin(),
667 E = PrimaryBases.end(); I != E; ++I) {
668 const CXXRecordDecl *BaseDecl = *I;
669
670 // We know that all the primary bases have the same offset as the base
671 // subobject.
672 BaseSubobject PrimaryBase(BaseDecl, Base.getBaseOffset());
673 AddressPoints.insert(std::make_pair(PrimaryBase, AddressPoint));
674 }
675
Anders Carlsson57071e22010-02-12 05:25:12 +0000676 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
677 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
678
679 // Traverse bases.
680 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
681 E = RD->bases_end(); I != E; ++I) {
682 const CXXRecordDecl *BaseDecl =
683 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
684
685 // Ignore the primary base.
686 if (BaseDecl == PrimaryBase)
687 continue;
688
689 assert(!I->isVirtual() && "FIXME: Handle virtual bases");
690
691 assert(false && "FIXME: Handle secondary virtual tables!");
692 }
693}
694
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000695/// dumpLayout - Dump the vtable layout.
696void VtableBuilder::dumpLayout(llvm::raw_ostream& Out) {
697
698 Out << "Vtable for '" << MostDerivedClass->getQualifiedNameAsString();
699 Out << "' (" << Components.size() << " entries).\n";
700
Anders Carlsson822307b2010-02-11 17:18:51 +0000701 // Iterate through the address points and insert them into a new map where
702 // they are keyed by the index and not the base object.
703 // Since an address point can be shared by multiple subobjects, we use an
704 // STL multimap.
705 std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
706 for (CGVtableInfo::AddressPointsMapTy::const_iterator I =
707 AddressPoints.begin(), E = AddressPoints.end(); I != E; ++I) {
708 const BaseSubobject& Base = I->first;
709 uint64_t Index = I->second;
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000710
Anders Carlsson822307b2010-02-11 17:18:51 +0000711 AddressPointsByIndex.insert(std::make_pair(Index, Base));
712 }
713
714 for (unsigned I = 0, E = Components.size(); I != E; ++I) {
Anders Carlsson28cbc8b2010-02-12 07:43:48 +0000715 uint64_t Index = I;
716
Anders Carlsson822307b2010-02-11 17:18:51 +0000717 if (AddressPointsByIndex.count(I)) {
Anders Carlsson28cbc8b2010-02-12 07:43:48 +0000718 std::string Str;
719
Anders Carlsson822307b2010-02-11 17:18:51 +0000720
Anders Carlsson28cbc8b2010-02-12 07:43:48 +0000721 if (AddressPointsByIndex.count(Index) == 1) {
722 const BaseSubobject &Base = AddressPointsByIndex.find(Index)->second;
723
724 // FIXME: Instead of dividing by 8, we should be using CharUnits.
725 Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
726 Out << ", " << Base.getBaseOffset() / 8 << ") vtable address --\n";
727 } else {
728 uint64_t BaseOffset =
729 AddressPointsByIndex.lower_bound(Index)->second.getBaseOffset();
730
731 // We store the class names in a set to get a stable order.
732 std::set<std::string> ClassNames;
733 for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
734 AddressPointsByIndex.lower_bound(Index), E =
735 AddressPointsByIndex.upper_bound(Index); I != E; ++I) {
736 assert(I->second.getBaseOffset() == BaseOffset &&
737 "Invalid base offset!");
738 const CXXRecordDecl *RD = I->second.getBase();
739 ClassNames.insert(RD->getQualifiedNameAsString());
740 }
741
742 for (std::set<std::string>::const_iterator I = ClassNames.begin(),
743 E = ClassNames.end(); I != E; ++I) {
744 // FIXME: Instead of dividing by 8, we should be using CharUnits.
745 Out << " -- (" << *I;
746 Out << ", " << BaseOffset / 8 << ") vtable address --\n";
747 }
748 }
Anders Carlsson822307b2010-02-11 17:18:51 +0000749 }
750
751 Out << llvm::format("%4d | ", I);
752
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000753 const VtableComponent &Component = Components[I];
754
755 // Dump the component.
756 switch (Component.getKind()) {
757 // FIXME: Remove this default case.
758 default:
759 assert(false && "Unhandled component kind!");
760 break;
761
762 case VtableComponent::CK_OffsetToTop:
763 Out << "offset_to_top (" << Component.getOffsetToTop() << ")";
764 break;
765
766 case VtableComponent::CK_RTTI:
767 Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
768 break;
769
Anders Carlsson848fa642010-02-11 18:20:28 +0000770 case VtableComponent::CK_FunctionPointer: {
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000771 const CXXMethodDecl *MD = Component.getFunctionDecl();
772
Anders Carlsson848fa642010-02-11 18:20:28 +0000773 std::string Str =
774 PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
775 MD);
776 Out << Str;
Anders Carlsson98241422010-02-12 02:38:13 +0000777 if (MD->isPure())
778 Out << " [pure]";
779
Anders Carlsson848fa642010-02-11 18:20:28 +0000780 break;
781 }
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000782
Anders Carlsson848fa642010-02-11 18:20:28 +0000783 case VtableComponent::CK_CompleteDtorPointer: {
784 const CXXDestructorDecl *DD = Component.getDestructorDecl();
785
786 Out << DD->getQualifiedNameAsString() << "() [complete]";
Anders Carlsson98241422010-02-12 02:38:13 +0000787 if (DD->isPure())
788 Out << " [pure]";
789
Anders Carlsson848fa642010-02-11 18:20:28 +0000790 break;
791 }
792
793 case VtableComponent::CK_DeletingDtorPointer: {
794 const CXXDestructorDecl *DD = Component.getDestructorDecl();
795
796 Out << DD->getQualifiedNameAsString() << "() [deleting]";
Anders Carlsson98241422010-02-12 02:38:13 +0000797 if (DD->isPure())
798 Out << " [pure]";
799
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000800 break;
801 }
802
803 }
Anders Carlsson822307b2010-02-11 17:18:51 +0000804
Anders Carlsson824d7ea2010-02-11 08:02:13 +0000805 Out << '\n';
806 }
807
808}
809
810}
811
812namespace {
813class OldVtableBuilder {
Anders Carlssondbd920c2009-10-11 22:13:54 +0000814public:
815 /// Index_t - Vtable index type.
816 typedef uint64_t Index_t;
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000817 typedef std::vector<std::pair<GlobalDecl,
818 std::pair<GlobalDecl, ThunkAdjustment> > >
819 SavedAdjustmentsVectorTy;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000820private:
Anders Carlsson15318f42009-12-04 16:19:30 +0000821
Anders Carlssonc3a46ef2009-12-06 01:09:21 +0000822 // VtableComponents - The components of the vtable being built.
823 typedef llvm::SmallVector<llvm::Constant *, 64> VtableComponentsVectorTy;
824 VtableComponentsVectorTy VtableComponents;
825
Eli Friedman152b5b12009-12-05 01:05:03 +0000826 const bool BuildVtable;
827
Anders Carlssondbd920c2009-10-11 22:13:54 +0000828 llvm::Type *Ptr8Ty;
Anders Carlssonac3f7bd2009-12-04 18:36:22 +0000829
830 /// MostDerivedClass - The most derived class that this vtable is being
831 /// built for.
832 const CXXRecordDecl *MostDerivedClass;
833
Mike Stumpacfd1e52009-11-13 01:54:23 +0000834 /// LayoutClass - The most derived class used for virtual base layout
835 /// information.
836 const CXXRecordDecl *LayoutClass;
Mike Stump4cde6262009-11-13 02:13:54 +0000837 /// LayoutOffset - The offset for Class in LayoutClass.
838 uint64_t LayoutOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000839 /// BLayout - Layout for the most derived class that this vtable is being
840 /// built for.
841 const ASTRecordLayout &BLayout;
842 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
843 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
844 llvm::Constant *rtti;
845 llvm::LLVMContext &VMContext;
846 CodeGenModule &CGM; // Per-module state.
Anders Carlsson0e881162009-12-04 03:46:21 +0000847
Mike Stumpcf0b9cc2010-01-26 00:05:04 +0000848 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCall;
Anders Carlssona0fdd912009-11-13 17:08:56 +0000849 llvm::DenseMap<GlobalDecl, Index_t> VCallOffset;
Mike Stumpd99a4d22010-01-26 03:42:22 +0000850 llvm::DenseMap<GlobalDecl, Index_t> VCallOffsetForVCall;
Mike Stump9e7e3c62009-11-06 23:27:42 +0000851 // This is the offset to the nearest virtual base
Mike Stumpcf0b9cc2010-01-26 00:05:04 +0000852 llvm::DenseMap<const CXXMethodDecl *, Index_t> NonVirtualOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000853 llvm::DenseMap<const CXXRecordDecl *, Index_t> VBIndex;
Mike Stump94aff932009-10-27 23:46:47 +0000854
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000855 /// PureVirtualFunction - Points to __cxa_pure_virtual.
856 llvm::Constant *PureVirtualFn;
857
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000858 /// VtableMethods - A data structure for keeping track of methods in a vtable.
859 /// Can add methods, override methods and iterate in vtable order.
860 class VtableMethods {
861 // MethodToIndexMap - Maps from a global decl to the index it has in the
862 // Methods vector.
863 llvm::DenseMap<GlobalDecl, uint64_t> MethodToIndexMap;
864
865 /// Methods - The methods, in vtable order.
866 typedef llvm::SmallVector<GlobalDecl, 16> MethodsVectorTy;
867 MethodsVectorTy Methods;
Eli Friedman72649ed2009-12-06 22:01:30 +0000868 MethodsVectorTy OrigMethods;
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000869
870 public:
871 /// AddMethod - Add a method to the vtable methods.
872 void AddMethod(GlobalDecl GD) {
873 assert(!MethodToIndexMap.count(GD) &&
874 "Method has already been added!");
875
876 MethodToIndexMap[GD] = Methods.size();
877 Methods.push_back(GD);
Eli Friedman72649ed2009-12-06 22:01:30 +0000878 OrigMethods.push_back(GD);
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000879 }
880
881 /// OverrideMethod - Replace a method with another.
882 void OverrideMethod(GlobalDecl OverriddenGD, GlobalDecl GD) {
883 llvm::DenseMap<GlobalDecl, uint64_t>::iterator i
884 = MethodToIndexMap.find(OverriddenGD);
885 assert(i != MethodToIndexMap.end() && "Did not find entry!");
886
887 // Get the index of the old decl.
888 uint64_t Index = i->second;
889
890 // Replace the old decl with the new decl.
891 Methods[Index] = GD;
892
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000893 // And add the new.
894 MethodToIndexMap[GD] = Index;
895 }
896
Anders Carlsson77c23e52009-12-04 15:49:02 +0000897 /// getIndex - Gives the index of a passed in GlobalDecl. Returns false if
898 /// the index couldn't be found.
Benjamin Kramercce9fde2009-12-04 22:45:27 +0000899 bool getIndex(GlobalDecl GD, uint64_t &Index) const {
Anders Carlsson77c23e52009-12-04 15:49:02 +0000900 llvm::DenseMap<GlobalDecl, uint64_t>::const_iterator i
901 = MethodToIndexMap.find(GD);
Eli Friedman47145832009-12-04 08:34:14 +0000902
Anders Carlsson77c23e52009-12-04 15:49:02 +0000903 if (i == MethodToIndexMap.end())
904 return false;
Anders Carlssonc0c49932009-12-04 03:41:37 +0000905
Anders Carlsson77c23e52009-12-04 15:49:02 +0000906 Index = i->second;
907 return true;
Anders Carlssonc0c49932009-12-04 03:41:37 +0000908 }
909
Eli Friedman72649ed2009-12-06 22:01:30 +0000910 GlobalDecl getOrigMethod(uint64_t Index) const {
911 return OrigMethods[Index];
912 }
913
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000914 MethodsVectorTy::size_type size() const {
915 return Methods.size();
916 }
917
918 void clear() {
919 MethodToIndexMap.clear();
920 Methods.clear();
Eli Friedman72649ed2009-12-06 22:01:30 +0000921 OrigMethods.clear();
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000922 }
923
Anders Carlssonc0c49932009-12-04 03:41:37 +0000924 GlobalDecl operator[](uint64_t Index) const {
Anders Carlssonc7ab1a82009-12-04 02:01:07 +0000925 return Methods[Index];
926 }
927 };
928
929 /// Methods - The vtable methods we're currently building.
930 VtableMethods Methods;
931
Anders Carlsson98fdb242009-12-04 02:26:15 +0000932 /// ThisAdjustments - For a given index in the vtable, contains the 'this'
933 /// pointer adjustment needed for a method.
934 typedef llvm::DenseMap<uint64_t, ThunkAdjustment> ThisAdjustmentsMapTy;
935 ThisAdjustmentsMapTy ThisAdjustments;
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000936
Eli Friedmanb455f0e2009-12-07 23:56:34 +0000937 SavedAdjustmentsVectorTy SavedAdjustments;
Eli Friedman72649ed2009-12-06 22:01:30 +0000938
Anders Carlssona8756702009-12-04 02:22:02 +0000939 /// BaseReturnTypes - Contains the base return types of methods who have been
940 /// overridden with methods whose return types require adjustment. Used for
941 /// generating covariant thunk information.
942 typedef llvm::DenseMap<uint64_t, CanQualType> BaseReturnTypesMapTy;
943 BaseReturnTypesMapTy BaseReturnTypes;
Anders Carlsson5dd730a2009-11-26 19:32:45 +0000944
Anders Carlssondbd920c2009-10-11 22:13:54 +0000945 std::vector<Index_t> VCalls;
Mike Stump9840c702009-11-12 20:47:57 +0000946
947 typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
Mike Stump23a35422009-11-19 20:52:19 +0000948 // subAddressPoints - Used to hold the AddressPoints (offsets) into the built
949 // vtable for use in computing the initializers for the VTT.
950 llvm::DenseMap<CtorVtable_t, int64_t> &subAddressPoints;
Mike Stump9840c702009-11-12 20:47:57 +0000951
Anders Carlsson1bb60992010-01-14 02:29:07 +0000952 /// AddressPoints - Address points for this vtable.
953 CGVtableInfo::AddressPointsMapTy& AddressPoints;
954
Anders Carlssondbd920c2009-10-11 22:13:54 +0000955 typedef CXXRecordDecl::method_iterator method_iter;
Anders Carlssondbd920c2009-10-11 22:13:54 +0000956 const uint32_t LLVMPointerWidth;
957 Index_t extra;
Mike Stump11dea942009-10-15 02:04:03 +0000958 typedef std::vector<std::pair<const CXXRecordDecl *, int64_t> > Path_t;
Mike Stump23a35422009-11-19 20:52:19 +0000959 static llvm::DenseMap<CtorVtable_t, int64_t>&
960 AllocAddressPoint(CodeGenModule &cgm, const CXXRecordDecl *l,
961 const CXXRecordDecl *c) {
Anders Carlsson21431c52010-01-02 18:02:32 +0000962 CGVtableInfo::AddrMap_t *&oref = cgm.getVtableInfo().AddressPoints[l];
Mike Stump23a35422009-11-19 20:52:19 +0000963 if (oref == 0)
Anders Carlsson21431c52010-01-02 18:02:32 +0000964 oref = new CGVtableInfo::AddrMap_t;
Mike Stump23a35422009-11-19 20:52:19 +0000965
966 llvm::DenseMap<CtorVtable_t, int64_t> *&ref = (*oref)[c];
967 if (ref == 0)
968 ref = new llvm::DenseMap<CtorVtable_t, int64_t>;
969 return *ref;
970 }
Anders Carlsson6d4ccb72009-11-26 19:54:33 +0000971
Mike Stumpcf0b9cc2010-01-26 00:05:04 +0000972 bool DclIsSame(const FunctionDecl *New, const FunctionDecl *Old) {
973 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
974 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
975
976 // C++ [temp.fct]p2:
977 // A function template can be overloaded with other function templates
978 // and with normal (non-template) functions.
979 if ((OldTemplate == 0) != (NewTemplate == 0))
980 return false;
981
982 // Is the function New an overload of the function Old?
983 QualType OldQType = CGM.getContext().getCanonicalType(Old->getType());
984 QualType NewQType = CGM.getContext().getCanonicalType(New->getType());
985
986 // Compare the signatures (C++ 1.3.10) of the two functions to
987 // determine whether they are overloads. If we find any mismatch
988 // in the signature, they are overloads.
989
990 // If either of these functions is a K&R-style function (no
991 // prototype), then we consider them to have matching signatures.
992 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
993 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
994 return true;
995
996 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
997 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
998
999 // The signature of a function includes the types of its
1000 // parameters (C++ 1.3.10), which includes the presence or absence
1001 // of the ellipsis; see C++ DR 357).
1002 if (OldQType != NewQType &&
1003 (OldType->getNumArgs() != NewType->getNumArgs() ||
1004 OldType->isVariadic() != NewType->isVariadic() ||
1005 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1006 NewType->arg_type_begin())))
1007 return false;
1008
1009#if 0
1010 // C++ [temp.over.link]p4:
1011 // The signature of a function template consists of its function
1012 // signature, its return type and its template parameter list. The names
1013 // of the template parameters are significant only for establishing the
1014 // relationship between the template parameters and the rest of the
1015 // signature.
1016 //
1017 // We check the return type and template parameter lists for function
1018 // templates first; the remaining checks follow.
1019 if (NewTemplate &&
1020 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1021 OldTemplate->getTemplateParameters(),
1022 TPL_TemplateMatch) ||
1023 OldType->getResultType() != NewType->getResultType()))
1024 return false;
1025#endif
1026
1027 // If the function is a class member, its signature includes the
1028 // cv-qualifiers (if any) on the function itself.
1029 //
1030 // As part of this, also check whether one of the member functions
1031 // is static, in which case they are not overloads (C++
1032 // 13.1p2). While not part of the definition of the signature,
1033 // this check is important to determine whether these functions
1034 // can be overloaded.
1035 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1036 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1037 if (OldMethod && NewMethod &&
1038 !OldMethod->isStatic() && !NewMethod->isStatic() &&
1039 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
1040 return false;
1041
1042 // The signatures match; this is not an overload.
1043 return true;
1044 }
1045
1046 typedef llvm::DenseMap<const CXXMethodDecl *, const CXXMethodDecl*>
1047 ForwardUnique_t;
1048 ForwardUnique_t ForwardUnique;
1049 llvm::DenseMap<const CXXMethodDecl*, const CXXMethodDecl*> UniqueOverrider;
1050
1051 void BuildUniqueOverrider(const CXXMethodDecl *U, const CXXMethodDecl *MD) {
1052 const CXXMethodDecl *PrevU = UniqueOverrider[MD];
1053 assert(U && "no unique overrider");
1054 if (PrevU == U)
1055 return;
1056 if (PrevU != U && PrevU != 0) {
1057 // If already set, note the two sets as the same
1058 if (0)
1059 printf("%s::%s same as %s::%s\n",
1060 PrevU->getParent()->getNameAsCString(),
1061 PrevU->getNameAsCString(),
1062 U->getParent()->getNameAsCString(),
1063 U->getNameAsCString());
1064 ForwardUnique[PrevU] = U;
1065 return;
1066 }
1067
1068 // Not set, set it now
1069 if (0)
1070 printf("marking %s::%s %p override as %s::%s\n",
1071 MD->getParent()->getNameAsCString(),
1072 MD->getNameAsCString(),
1073 (void*)MD,
1074 U->getParent()->getNameAsCString(),
1075 U->getNameAsCString());
1076 UniqueOverrider[MD] = U;
1077
1078 for (CXXMethodDecl::method_iterator mi = MD->begin_overridden_methods(),
1079 me = MD->end_overridden_methods(); mi != me; ++mi) {
1080 BuildUniqueOverrider(U, *mi);
1081 }
1082 }
1083
1084 void BuildUniqueOverriders(const CXXRecordDecl *RD) {
1085 if (0) printf("walking %s\n", RD->getNameAsCString());
1086 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
1087 e = RD->method_end(); i != e; ++i) {
1088 const CXXMethodDecl *MD = *i;
1089 if (!MD->isVirtual())
1090 continue;
1091
1092 if (UniqueOverrider[MD] == 0) {
1093 // Only set this, if it hasn't been set yet.
1094 BuildUniqueOverrider(MD, MD);
1095 if (0)
1096 printf("top set is %s::%s %p\n",
1097 MD->getParent()->getNameAsCString(),
1098 MD->getNameAsCString(),
1099 (void*)MD);
1100 ForwardUnique[MD] = MD;
1101 }
1102 }
1103 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1104 e = RD->bases_end(); i != e; ++i) {
1105 const CXXRecordDecl *Base =
1106 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1107 BuildUniqueOverriders(Base);
1108 }
1109 }
1110
1111 static int DclCmp(const void *p1, const void *p2) {
1112 const CXXMethodDecl *MD1 = (const CXXMethodDecl *)p1;
1113 const CXXMethodDecl *MD2 = (const CXXMethodDecl *)p2;
1114 return (MD1->getIdentifier() - MD2->getIdentifier());
1115 }
1116
1117 void MergeForwarding() {
1118 typedef llvm::SmallVector<const CXXMethodDecl *, 100> A_t;
1119 A_t A;
1120 for (ForwardUnique_t::iterator I = ForwardUnique.begin(),
1121 E = ForwardUnique.end(); I != E; ++I) {
1122 if (I->first == I->second)
1123 // Only add the roots of all trees
1124 A.push_back(I->first);
1125 }
1126 llvm::array_pod_sort(A.begin(), A.end(), DclCmp);
1127 for (A_t::iterator I = A.begin(),
1128 E = A.end(); I != E; ++I) {
1129 A_t::iterator J = I;
1130 while (++J != E && DclCmp(*I, *J) == 0)
1131 if (DclIsSame(*I, *J)) {
1132 printf("connecting %s\n", (*I)->getNameAsCString());
1133 ForwardUnique[*J] = *I;
1134 }
1135 }
1136 }
1137
1138 const CXXMethodDecl *getUnique(const CXXMethodDecl *MD) {
1139 const CXXMethodDecl *U = UniqueOverrider[MD];
1140 assert(U && "unique overrider not found");
1141 while (ForwardUnique.count(U)) {
1142 const CXXMethodDecl *NU = ForwardUnique[U];
1143 if (NU == U) break;
1144 U = NU;
1145 }
1146 return U;
1147 }
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00001148
1149 GlobalDecl getUnique(GlobalDecl GD) {
1150 const CXXMethodDecl *Unique = getUnique(cast<CXXMethodDecl>(GD.getDecl()));
1151
1152 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Unique))
1153 return GlobalDecl(CD, GD.getCtorType());
1154
1155 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Unique))
1156 return GlobalDecl(DD, GD.getDtorType());
1157
1158 return Unique;
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001159 }
1160
Anders Carlsson6d4ccb72009-11-26 19:54:33 +00001161 /// getPureVirtualFn - Return the __cxa_pure_virtual function.
1162 llvm::Constant* getPureVirtualFn() {
1163 if (!PureVirtualFn) {
1164 const llvm::FunctionType *Ty =
1165 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
1166 /*isVarArg=*/false);
1167 PureVirtualFn = wrap(CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual"));
1168 }
1169
1170 return PureVirtualFn;
1171 }
1172
Anders Carlssondbd920c2009-10-11 22:13:54 +00001173public:
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001174 OldVtableBuilder(const CXXRecordDecl *MostDerivedClass,
Eli Friedman152b5b12009-12-05 01:05:03 +00001175 const CXXRecordDecl *l, uint64_t lo, CodeGenModule &cgm,
Anders Carlsson1bb60992010-01-14 02:29:07 +00001176 bool build, CGVtableInfo::AddressPointsMapTy& AddressPoints)
Eli Friedman152b5b12009-12-05 01:05:03 +00001177 : BuildVtable(build), MostDerivedClass(MostDerivedClass), LayoutClass(l),
1178 LayoutOffset(lo), BLayout(cgm.getContext().getASTRecordLayout(l)),
1179 rtti(0), VMContext(cgm.getModule().getContext()),CGM(cgm),
1180 PureVirtualFn(0),
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00001181 subAddressPoints(AllocAddressPoint(cgm, l, MostDerivedClass)),
Anders Carlsson1bb60992010-01-14 02:29:07 +00001182 AddressPoints(AddressPoints),
1183 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0))
1184 {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001185 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001186 if (BuildVtable) {
1187 QualType ClassType = CGM.getContext().getTagDeclType(MostDerivedClass);
1188 rtti = CGM.GetAddrOfRTTIDescriptor(ClassType);
1189 }
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001190 BuildUniqueOverriders(MostDerivedClass);
1191 MergeForwarding();
Anders Carlssondbd920c2009-10-11 22:13:54 +00001192 }
1193
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001194 // getVtableComponents - Returns a reference to the vtable components.
1195 const VtableComponentsVectorTy &getVtableComponents() const {
1196 return VtableComponents;
Anders Carlsson15318f42009-12-04 16:19:30 +00001197 }
1198
Anders Carlssonc997d422010-01-02 01:01:18 +00001199 llvm::DenseMap<const CXXRecordDecl *, uint64_t> &getVBIndex()
Anders Carlssondbd920c2009-10-11 22:13:54 +00001200 { return VBIndex; }
1201
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001202 SavedAdjustmentsVectorTy &getSavedAdjustments()
1203 { return SavedAdjustments; }
Eli Friedman72649ed2009-12-06 22:01:30 +00001204
Anders Carlssondbd920c2009-10-11 22:13:54 +00001205 llvm::Constant *wrap(Index_t i) {
1206 llvm::Constant *m;
1207 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
1208 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
1209 }
1210
1211 llvm::Constant *wrap(llvm::Constant *m) {
1212 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
1213 }
1214
Mike Stumpd6584902010-01-22 02:51:26 +00001215//#define D1(x)
1216#define D1(X) do { if (getenv("DEBUG")) { X; } } while (0)
Mike Stump6a9612f2009-10-31 20:06:59 +00001217
1218 void GenerateVBaseOffsets(const CXXRecordDecl *RD, uint64_t Offset,
Mike Stumpab28c132009-10-13 22:54:56 +00001219 bool updateVBIndex, Index_t current_vbindex) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001220 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1221 e = RD->bases_end(); i != e; ++i) {
1222 const CXXRecordDecl *Base =
1223 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpab28c132009-10-13 22:54:56 +00001224 Index_t next_vbindex = current_vbindex;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001225 if (i->isVirtual() && !SeenVBase.count(Base)) {
1226 SeenVBase.insert(Base);
Mike Stumpab28c132009-10-13 22:54:56 +00001227 if (updateVBIndex) {
Mike Stump6a9612f2009-10-31 20:06:59 +00001228 next_vbindex = (ssize_t)(-(VCalls.size()*LLVMPointerWidth/8)
Mike Stumpab28c132009-10-13 22:54:56 +00001229 - 3*LLVMPointerWidth/8);
1230 VBIndex[Base] = next_vbindex;
1231 }
Mike Stump6a9612f2009-10-31 20:06:59 +00001232 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
1233 VCalls.push_back((0?700:0) + BaseOffset);
1234 D1(printf(" vbase for %s at %d delta %d most derived %s\n",
1235 Base->getNameAsCString(),
1236 (int)-VCalls.size()-3, (int)BaseOffset,
Mike Stumpd6584902010-01-22 02:51:26 +00001237 MostDerivedClass->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00001238 }
Mike Stumpab28c132009-10-13 22:54:56 +00001239 // We also record offsets for non-virtual bases to closest enclosing
1240 // virtual base. We do this so that we don't have to search
1241 // for the nearst virtual base class when generating thunks.
1242 if (updateVBIndex && VBIndex.count(Base) == 0)
1243 VBIndex[Base] = next_vbindex;
Mike Stump6a9612f2009-10-31 20:06:59 +00001244 GenerateVBaseOffsets(Base, Offset, updateVBIndex, next_vbindex);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001245 }
1246 }
1247
1248 void StartNewTable() {
1249 SeenVBase.clear();
1250 }
1251
Mike Stump3425b972009-10-15 09:30:16 +00001252 Index_t getNVOffset_1(const CXXRecordDecl *D, const CXXRecordDecl *B,
1253 Index_t Offset = 0) {
1254
1255 if (B == D)
1256 return Offset;
1257
1258 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D);
1259 for (CXXRecordDecl::base_class_const_iterator i = D->bases_begin(),
1260 e = D->bases_end(); i != e; ++i) {
1261 const CXXRecordDecl *Base =
1262 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1263 int64_t BaseOffset = 0;
1264 if (!i->isVirtual())
1265 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1266 int64_t o = getNVOffset_1(Base, B, BaseOffset);
1267 if (o >= 0)
1268 return o;
1269 }
1270
1271 return -1;
1272 }
1273
1274 /// getNVOffset - Returns the non-virtual offset for the given (B) base of the
1275 /// derived class D.
1276 Index_t getNVOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +00001277 qD = qD->getPointeeType();
1278 qB = qB->getPointeeType();
Mike Stump3425b972009-10-15 09:30:16 +00001279 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
1280 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
1281 int64_t o = getNVOffset_1(D, B);
1282 if (o >= 0)
1283 return o;
1284
1285 assert(false && "FIXME: non-virtual base not found");
1286 return 0;
1287 }
1288
Anders Carlssondbd920c2009-10-11 22:13:54 +00001289 /// getVbaseOffset - Returns the index into the vtable for the virtual base
1290 /// offset for the given (B) virtual base of the derived class D.
1291 Index_t getVbaseOffset(QualType qB, QualType qD) {
Mike Stump9c212892009-11-03 19:03:17 +00001292 qD = qD->getPointeeType();
1293 qB = qB->getPointeeType();
Anders Carlssondbd920c2009-10-11 22:13:54 +00001294 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
1295 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00001296 if (D != MostDerivedClass)
Eli Friedman76ed1f72009-11-30 01:19:33 +00001297 return CGM.getVtableInfo().getVirtualBaseOffsetIndex(D, B);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001298 llvm::DenseMap<const CXXRecordDecl *, Index_t>::iterator i;
1299 i = VBIndex.find(B);
1300 if (i != VBIndex.end())
1301 return i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001302
Mike Stumpab28c132009-10-13 22:54:56 +00001303 assert(false && "FIXME: Base not found");
Anders Carlssondbd920c2009-10-11 22:13:54 +00001304 return 0;
1305 }
1306
Eli Friedman367d1222009-12-04 08:40:51 +00001307 bool OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
1308 Index_t OverrideOffset, Index_t Offset,
1309 int64_t CurrentVBaseOffset);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001310
Anders Carlssonadfa2672009-12-04 02:39:04 +00001311 /// AppendMethods - Append the current methods to the vtable.
Anders Carlssonbf540272009-12-04 02:56:03 +00001312 void AppendMethodsToVtable();
Anders Carlssonadfa2672009-12-04 02:39:04 +00001313
Anders Carlssona0fdd912009-11-13 17:08:56 +00001314 llvm::Constant *WrapAddrOf(GlobalDecl GD) {
1315 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1316
Anders Carlssonecf282b2009-11-24 05:08:52 +00001317 const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
Mike Stump1ae31782009-10-27 23:36:26 +00001318
Mike Stumpc085a982009-12-03 16:55:20 +00001319 return wrap(CGM.GetAddrOfFunction(GD, Ty));
Mike Stump1ae31782009-10-27 23:36:26 +00001320 }
1321
Mike Stump9e7e3c62009-11-06 23:27:42 +00001322 void OverrideMethods(Path_t *Path, bool MorallyVirtual, int64_t Offset,
1323 int64_t CurrentVBaseOffset) {
Mike Stump11dea942009-10-15 02:04:03 +00001324 for (Path_t::reverse_iterator i = Path->rbegin(),
Anders Carlssondbd920c2009-10-11 22:13:54 +00001325 e = Path->rend(); i != e; ++i) {
1326 const CXXRecordDecl *RD = i->first;
Mike Stump3425b972009-10-15 09:30:16 +00001327 int64_t OverrideOffset = i->second;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001328 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
1329 ++mi) {
Anders Carlssona0fdd912009-11-13 17:08:56 +00001330 const CXXMethodDecl *MD = *mi;
1331
1332 if (!MD->isVirtual())
Anders Carlssondbd920c2009-10-11 22:13:54 +00001333 continue;
1334
Anders Carlssona0fdd912009-11-13 17:08:56 +00001335 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1336 // Override both the complete and the deleting destructor.
1337 GlobalDecl CompDtor(DD, Dtor_Complete);
Eli Friedman367d1222009-12-04 08:40:51 +00001338 OverrideMethod(CompDtor, MorallyVirtual, OverrideOffset, Offset,
1339 CurrentVBaseOffset);
1340
Anders Carlssona0fdd912009-11-13 17:08:56 +00001341 GlobalDecl DeletingDtor(DD, Dtor_Deleting);
Eli Friedman367d1222009-12-04 08:40:51 +00001342 OverrideMethod(DeletingDtor, MorallyVirtual, OverrideOffset, Offset,
1343 CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +00001344 } else {
Eli Friedman367d1222009-12-04 08:40:51 +00001345 OverrideMethod(MD, MorallyVirtual, OverrideOffset, Offset,
1346 CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +00001347 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00001348 }
1349 }
1350 }
1351
Anders Carlssona0fdd912009-11-13 17:08:56 +00001352 void AddMethod(const GlobalDecl GD, bool MorallyVirtual, Index_t Offset,
Eli Friedman76ed1f72009-11-30 01:19:33 +00001353 int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001354 // If we can find a previously allocated slot for this, reuse it.
Eli Friedman367d1222009-12-04 08:40:51 +00001355 if (OverrideMethod(GD, MorallyVirtual, Offset, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +00001356 CurrentVBaseOffset))
Anders Carlssondbd920c2009-10-11 22:13:54 +00001357 return;
1358
Mike Stump372ade22010-01-22 18:48:47 +00001359 D1(printf(" vfn for %s at %d\n",
1360 dyn_cast<CXXMethodDecl>(GD.getDecl())->getNameAsCString(),
1361 (int)Methods.size()));
1362
Anders Carlssona7f19112009-12-04 02:08:24 +00001363 // We didn't find an entry in the vtable that we could use, add a new
1364 // entry.
1365 Methods.AddMethod(GD);
1366
Mike Stump15189fb2010-01-26 21:35:27 +00001367 VCallOffset[GD] = Offset/8 - CurrentVBaseOffset/8;
1368
Anders Carlssondbd920c2009-10-11 22:13:54 +00001369 if (MorallyVirtual) {
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00001370 GlobalDecl UGD = getUnique(GD);
1371 const CXXMethodDecl *UMD = cast<CXXMethodDecl>(UGD.getDecl());
1372
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001373 assert(UMD && "final overrider not found");
1374
1375 Index_t &idx = VCall[UMD];
Anders Carlssondbd920c2009-10-11 22:13:54 +00001376 // Allocate the first one, after that, we reuse the previous one.
1377 if (idx == 0) {
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00001378 VCallOffsetForVCall[UGD] = Offset/8;
Mike Stump15189fb2010-01-26 21:35:27 +00001379 NonVirtualOffset[UMD] = Offset/8 - CurrentVBaseOffset/8;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001380 idx = VCalls.size()+1;
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001381 VCalls.push_back(Offset/8 - CurrentVBaseOffset/8);
Mike Stump6a9612f2009-10-31 20:06:59 +00001382 D1(printf(" vcall for %s at %d with delta %d\n",
Mike Stumpd6584902010-01-22 02:51:26 +00001383 dyn_cast<CXXMethodDecl>(GD.getDecl())->getNameAsCString(),
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001384 (int)-VCalls.size()-3, (int)VCalls[idx-1]));
Anders Carlssondbd920c2009-10-11 22:13:54 +00001385 }
1386 }
1387 }
1388
1389 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +00001390 Index_t Offset, int64_t CurrentVBaseOffset) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001391 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Anders Carlssona0fdd912009-11-13 17:08:56 +00001392 ++mi) {
1393 const CXXMethodDecl *MD = *mi;
1394 if (!MD->isVirtual())
1395 continue;
1396
1397 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1398 // For destructors, add both the complete and the deleting destructor
1399 // to the vtable.
1400 AddMethod(GlobalDecl(DD, Dtor_Complete), MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +00001401 CurrentVBaseOffset);
Eli Friedman76ed1f72009-11-30 01:19:33 +00001402 AddMethod(GlobalDecl(DD, Dtor_Deleting), MorallyVirtual, Offset,
1403 CurrentVBaseOffset);
1404 } else
1405 AddMethod(MD, MorallyVirtual, Offset, CurrentVBaseOffset);
Anders Carlssona0fdd912009-11-13 17:08:56 +00001406 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00001407 }
1408
1409 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
1410 const CXXRecordDecl *PrimaryBase,
1411 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +00001412 int64_t Offset, int64_t CurrentVBaseOffset,
1413 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +00001414 Path->push_back(std::make_pair(RD, Offset));
Anders Carlssondbd920c2009-10-11 22:13:54 +00001415 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1416 e = RD->bases_end(); i != e; ++i) {
1417 if (i->isVirtual())
1418 continue;
1419 const CXXRecordDecl *Base =
1420 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001421 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
1422 StartNewTable();
1423 GenerateVtableForBase(Base, o, MorallyVirtual, false,
1424 true, Base == PrimaryBase && !PrimaryBaseWasVirtual,
1425 CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001426 }
Mike Stump11dea942009-10-15 02:04:03 +00001427 Path->pop_back();
Anders Carlssondbd920c2009-10-11 22:13:54 +00001428 }
1429
Mike Stump0ca42792009-10-14 18:14:51 +00001430// #define D(X) do { X; } while (0)
1431#define D(X)
1432
1433 void insertVCalls(int InsertionPoint) {
Mike Stump6a9612f2009-10-31 20:06:59 +00001434 D1(printf("============= combining vbase/vcall\n"));
Mike Stump0ca42792009-10-14 18:14:51 +00001435 D(VCalls.insert(VCalls.begin(), 673));
1436 D(VCalls.push_back(672));
Eli Friedman152b5b12009-12-05 01:05:03 +00001437
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001438 VtableComponents.insert(VtableComponents.begin() + InsertionPoint,
1439 VCalls.size(), 0);
Eli Friedman152b5b12009-12-05 01:05:03 +00001440 if (BuildVtable) {
1441 // The vcalls come first...
1442 for (std::vector<Index_t>::reverse_iterator i = VCalls.rbegin(),
1443 e = VCalls.rend();
1444 i != e; ++i)
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001445 VtableComponents[InsertionPoint++] = wrap((0?600:0) + *i);
Eli Friedman152b5b12009-12-05 01:05:03 +00001446 }
Mike Stump0ca42792009-10-14 18:14:51 +00001447 VCalls.clear();
Mike Stumpfbfb52d2009-11-10 02:30:51 +00001448 VCall.clear();
Mike Stump15189fb2010-01-26 21:35:27 +00001449 VCallOffsetForVCall.clear();
1450 VCallOffset.clear();
1451 NonVirtualOffset.clear();
Mike Stump0ca42792009-10-14 18:14:51 +00001452 }
1453
Mike Stump65d0e282009-11-13 23:13:20 +00001454 void AddAddressPoints(const CXXRecordDecl *RD, uint64_t Offset,
1455 Index_t AddressPoint) {
1456 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
Mike Stumpd6584902010-01-22 02:51:26 +00001457 RD->getNameAsCString(), MostDerivedClass->getNameAsCString(),
Mike Stump65d0e282009-11-13 23:13:20 +00001458 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +00001459 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Anders Carlsson1bb60992010-01-14 02:29:07 +00001460 AddressPoints[BaseSubobject(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +00001461
1462 // Now also add the address point for all our primary bases.
1463 while (1) {
1464 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1465 RD = Layout.getPrimaryBase();
1466 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1467 // FIXME: Double check this.
1468 if (RD == 0)
1469 break;
1470 if (PrimaryBaseWasVirtual &&
1471 BLayout.getVBaseClassOffset(RD) != Offset)
1472 break;
1473 D1(printf("XXX address point for %s in %s layout %s at offset %d is %d\n",
Mike Stumpd6584902010-01-22 02:51:26 +00001474 RD->getNameAsCString(), MostDerivedClass->getNameAsCString(),
Mike Stump65d0e282009-11-13 23:13:20 +00001475 LayoutClass->getNameAsCString(), (int)Offset, (int)AddressPoint));
Mike Stump23a35422009-11-19 20:52:19 +00001476 subAddressPoints[std::make_pair(RD, Offset)] = AddressPoint;
Anders Carlsson1bb60992010-01-14 02:29:07 +00001477 AddressPoints[BaseSubobject(RD, Offset)] = AddressPoint;
Mike Stump65d0e282009-11-13 23:13:20 +00001478 }
1479 }
1480
1481
Mike Stump8cc4f102009-12-24 07:29:41 +00001482 void FinishGenerateVtable(const CXXRecordDecl *RD,
1483 const ASTRecordLayout &Layout,
1484 const CXXRecordDecl *PrimaryBase,
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001485 bool ForNPNVBases, bool WasPrimaryBase,
Mike Stump8cc4f102009-12-24 07:29:41 +00001486 bool PrimaryBaseWasVirtual,
1487 bool MorallyVirtual, int64_t Offset,
1488 bool ForVirtualBase, int64_t CurrentVBaseOffset,
1489 Path_t *Path) {
Mike Stump11dea942009-10-15 02:04:03 +00001490 bool alloc = false;
1491 if (Path == 0) {
1492 alloc = true;
1493 Path = new Path_t;
1494 }
1495
Anders Carlssondbd920c2009-10-11 22:13:54 +00001496 StartNewTable();
1497 extra = 0;
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001498 Index_t AddressPoint = 0;
1499 int VCallInsertionPoint = 0;
1500 if (!ForNPNVBases || !WasPrimaryBase) {
1501 bool DeferVCalls = MorallyVirtual || ForVirtualBase;
1502 VCallInsertionPoint = VtableComponents.size();
1503 if (!DeferVCalls) {
1504 insertVCalls(VCallInsertionPoint);
1505 } else
1506 // FIXME: just for extra, or for all uses of VCalls.size post this?
1507 extra = -VCalls.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +00001508
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001509 // Add the offset to top.
1510 VtableComponents.push_back(BuildVtable ? wrap(-((Offset-LayoutOffset)/8)) : 0);
Anders Carlsson15318f42009-12-04 16:19:30 +00001511
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001512 // Add the RTTI information.
1513 VtableComponents.push_back(rtti);
Anders Carlsson15318f42009-12-04 16:19:30 +00001514
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001515 AddressPoint = VtableComponents.size();
Anders Carlssondbd920c2009-10-11 22:13:54 +00001516
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001517 AppendMethodsToVtable();
1518 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00001519
1520 // and then the non-virtual bases.
1521 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
Mike Stump9e7e3c62009-11-06 23:27:42 +00001522 MorallyVirtual, Offset, CurrentVBaseOffset, Path);
Mike Stump0ca42792009-10-14 18:14:51 +00001523
1524 if (ForVirtualBase) {
Mike Stump9840c702009-11-12 20:47:57 +00001525 // FIXME: We're adding to VCalls in callers, we need to do the overrides
1526 // in the inner part, so that we know the complete set of vcalls during
1527 // the build and don't have to insert into methods. Saving out the
1528 // AddressPoint here, would need to be fixed, if we didn't do that. Also
1529 // retroactively adding vcalls for overrides later wind up in the wrong
1530 // place, the vcall slot has to be alloted during the walk of the base
1531 // when the function is first introduces.
Mike Stump0ca42792009-10-14 18:14:51 +00001532 AddressPoint += VCalls.size();
Mike Stump9840c702009-11-12 20:47:57 +00001533 insertVCalls(VCallInsertionPoint);
Mike Stump0ca42792009-10-14 18:14:51 +00001534 }
1535
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001536 if (!ForNPNVBases || !WasPrimaryBase)
1537 AddAddressPoints(RD, Offset, AddressPoint);
Mike Stump9840c702009-11-12 20:47:57 +00001538
Mike Stump11dea942009-10-15 02:04:03 +00001539 if (alloc) {
1540 delete Path;
1541 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00001542 }
1543
Mike Stump6a9612f2009-10-31 20:06:59 +00001544 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
1545 bool updateVBIndex, Index_t current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +00001546 int64_t CurrentVBaseOffset) {
Mike Stump6a9612f2009-10-31 20:06:59 +00001547 if (!RD->isDynamicClass())
1548 return;
1549
1550 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1551 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1552 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1553
1554 // vtables are composed from the chain of primaries.
Eli Friedmandfe33bb2009-12-04 08:52:11 +00001555 if (PrimaryBase && !PrimaryBaseWasVirtual) {
Mike Stump6a9612f2009-10-31 20:06:59 +00001556 D1(printf(" doing primaries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00001557 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Eli Friedmandfe33bb2009-12-04 08:52:11 +00001558 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
1559 updateVBIndex, current_vbindex, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +00001560 }
1561
1562 D1(printf(" doing vcall entries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00001563 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +00001564
1565 // And add the virtuals for the class to the primary vtable.
Eli Friedman76ed1f72009-11-30 01:19:33 +00001566 AddMethods(RD, MorallyVirtual, Offset, CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +00001567 }
1568
1569 void VBPrimaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset,
1570 bool updateVBIndex, Index_t current_vbindex,
Mike Stump9e7e3c62009-11-06 23:27:42 +00001571 bool RDisVirtualBase, int64_t CurrentVBaseOffset,
Eli Friedman76ed1f72009-11-30 01:19:33 +00001572 bool bottom) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001573 if (!RD->isDynamicClass())
1574 return;
1575
1576 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1577 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1578 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1579
1580 // vtables are composed from the chain of primaries.
1581 if (PrimaryBase) {
Mike Stump9e7e3c62009-11-06 23:27:42 +00001582 int BaseCurrentVBaseOffset = CurrentVBaseOffset;
1583 if (PrimaryBaseWasVirtual) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001584 IndirectPrimary.insert(PrimaryBase);
Mike Stump9e7e3c62009-11-06 23:27:42 +00001585 BaseCurrentVBaseOffset = BLayout.getVBaseClassOffset(PrimaryBase);
1586 }
Mike Stump6a9612f2009-10-31 20:06:59 +00001587
1588 D1(printf(" doing primaries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00001589 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +00001590
1591 VBPrimaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset,
Mike Stump9e7e3c62009-11-06 23:27:42 +00001592 updateVBIndex, current_vbindex, PrimaryBaseWasVirtual,
Eli Friedman76ed1f72009-11-30 01:19:33 +00001593 BaseCurrentVBaseOffset, false);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001594 }
1595
Mike Stump6a9612f2009-10-31 20:06:59 +00001596 D1(printf(" doing vbase entries for %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00001597 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Mike Stump6a9612f2009-10-31 20:06:59 +00001598 GenerateVBaseOffsets(RD, Offset, updateVBIndex, current_vbindex);
1599
1600 if (RDisVirtualBase || bottom) {
1601 Primaries(RD, MorallyVirtual, Offset, updateVBIndex, current_vbindex,
Eli Friedman76ed1f72009-11-30 01:19:33 +00001602 CurrentVBaseOffset);
Mike Stump6a9612f2009-10-31 20:06:59 +00001603 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00001604 }
1605
Mike Stump8cc4f102009-12-24 07:29:41 +00001606 void GenerateVtableForBase(const CXXRecordDecl *RD, int64_t Offset = 0,
1607 bool MorallyVirtual = false,
1608 bool ForVirtualBase = false,
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001609 bool ForNPNVBases = false,
1610 bool WasPrimaryBase = true,
Mike Stump8cc4f102009-12-24 07:29:41 +00001611 int CurrentVBaseOffset = 0,
1612 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001613 if (!RD->isDynamicClass())
Mike Stump8cc4f102009-12-24 07:29:41 +00001614 return;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001615
Mike Stump92774d12009-11-13 02:35:38 +00001616 // Construction vtable don't need parts that have no virtual bases and
1617 // aren't morally virtual.
Anders Carlssonac3f7bd2009-12-04 18:36:22 +00001618 if ((LayoutClass != MostDerivedClass) &&
1619 RD->getNumVBases() == 0 && !MorallyVirtual)
Mike Stump8cc4f102009-12-24 07:29:41 +00001620 return;
Mike Stump92774d12009-11-13 02:35:38 +00001621
Anders Carlssondbd920c2009-10-11 22:13:54 +00001622 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1623 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1624 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1625
Anders Carlssondbd920c2009-10-11 22:13:54 +00001626 extra = 0;
Mike Stump6a9612f2009-10-31 20:06:59 +00001627 D1(printf("building entries for base %s most derived %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00001628 RD->getNameAsCString(), MostDerivedClass->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00001629
Mike Stump6a9612f2009-10-31 20:06:59 +00001630 if (ForVirtualBase)
1631 extra = VCalls.size();
1632
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001633 if (!ForNPNVBases || !WasPrimaryBase) {
1634 VBPrimaries(RD, MorallyVirtual, Offset, !ForVirtualBase, 0,
1635 ForVirtualBase, CurrentVBaseOffset, true);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001636
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001637 if (Path)
1638 OverrideMethods(Path, MorallyVirtual, Offset, CurrentVBaseOffset);
1639 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00001640
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001641 FinishGenerateVtable(RD, Layout, PrimaryBase, ForNPNVBases, WasPrimaryBase,
1642 PrimaryBaseWasVirtual, MorallyVirtual, Offset,
1643 ForVirtualBase, CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001644 }
1645
1646 void GenerateVtableForVBases(const CXXRecordDecl *RD,
1647 int64_t Offset = 0,
Mike Stump11dea942009-10-15 02:04:03 +00001648 Path_t *Path = 0) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001649 bool alloc = false;
1650 if (Path == 0) {
1651 alloc = true;
Mike Stump11dea942009-10-15 02:04:03 +00001652 Path = new Path_t;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001653 }
1654 // FIXME: We also need to override using all paths to a virtual base,
1655 // right now, we just process the first path
1656 Path->push_back(std::make_pair(RD, Offset));
1657 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1658 e = RD->bases_end(); i != e; ++i) {
1659 const CXXRecordDecl *Base =
1660 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1661 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1662 // Mark it so we don't output it twice.
1663 IndirectPrimary.insert(Base);
1664 StartNewTable();
Mike Stump0ca42792009-10-14 18:14:51 +00001665 VCall.clear();
Anders Carlssondbd920c2009-10-11 22:13:54 +00001666 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9e7e3c62009-11-06 23:27:42 +00001667 int64_t CurrentVBaseOffset = BaseOffset;
Mike Stump6a9612f2009-10-31 20:06:59 +00001668 D1(printf("vtable %s virtual base %s\n",
Mike Stumpd6584902010-01-22 02:51:26 +00001669 MostDerivedClass->getNameAsCString(), Base->getNameAsCString()));
Mike Stumpfc9f16c2010-01-22 06:45:05 +00001670 GenerateVtableForBase(Base, BaseOffset, true, true, false,
1671 true, CurrentVBaseOffset, Path);
Anders Carlssondbd920c2009-10-11 22:13:54 +00001672 }
Mike Stump9840c702009-11-12 20:47:57 +00001673 int64_t BaseOffset;
Anders Carlssondbd920c2009-10-11 22:13:54 +00001674 if (i->isVirtual())
1675 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump9840c702009-11-12 20:47:57 +00001676 else {
1677 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1678 BaseOffset = Offset + Layout.getBaseClassOffset(Base);
1679 }
1680
Mike Stump11dea942009-10-15 02:04:03 +00001681 if (Base->getNumVBases()) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00001682 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stump11dea942009-10-15 02:04:03 +00001683 }
Anders Carlssondbd920c2009-10-11 22:13:54 +00001684 }
1685 Path->pop_back();
1686 if (alloc)
1687 delete Path;
1688 }
1689};
Anders Carlsson27682a32009-12-03 01:54:02 +00001690} // end anonymous namespace
1691
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001692bool OldVtableBuilder::OverrideMethod(GlobalDecl GD, bool MorallyVirtual,
Eli Friedman367d1222009-12-04 08:40:51 +00001693 Index_t OverrideOffset, Index_t Offset,
1694 int64_t CurrentVBaseOffset) {
Anders Carlsson27682a32009-12-03 01:54:02 +00001695 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1696
1697 const bool isPure = MD->isPure();
Anders Carlsson7ca46432009-12-05 17:04:47 +00001698
Anders Carlsson27682a32009-12-03 01:54:02 +00001699 // FIXME: Should OverrideOffset's be Offset?
1700
Anders Carlsson7ca46432009-12-05 17:04:47 +00001701 for (CXXMethodDecl::method_iterator mi = MD->begin_overridden_methods(),
1702 e = MD->end_overridden_methods(); mi != e; ++mi) {
Anders Carlsson27682a32009-12-03 01:54:02 +00001703 GlobalDecl OGD;
Mike Stump15189fb2010-01-26 21:35:27 +00001704 GlobalDecl OGD2;
Anders Carlsson27682a32009-12-03 01:54:02 +00001705
Anders Carlsson3aaf4862009-12-04 05:51:56 +00001706 const CXXMethodDecl *OMD = *mi;
Anders Carlsson27682a32009-12-03 01:54:02 +00001707 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(OMD))
1708 OGD = GlobalDecl(DD, GD.getDtorType());
1709 else
1710 OGD = OMD;
Eli Friedman47145832009-12-04 08:34:14 +00001711
Eli Friedman72649ed2009-12-06 22:01:30 +00001712 // Check whether this is the method being overridden in this section of
1713 // the vtable.
Anders Carlsson77c23e52009-12-04 15:49:02 +00001714 uint64_t Index;
1715 if (!Methods.getIndex(OGD, Index))
Eli Friedman47145832009-12-04 08:34:14 +00001716 continue;
1717
Mike Stump15189fb2010-01-26 21:35:27 +00001718 OGD2 = OGD;
1719
Eli Friedman72649ed2009-12-06 22:01:30 +00001720 // Get the original method, which we should be computing thunks, etc,
1721 // against.
1722 OGD = Methods.getOrigMethod(Index);
1723 OMD = cast<CXXMethodDecl>(OGD.getDecl());
1724
Eli Friedman47145832009-12-04 08:34:14 +00001725 QualType ReturnType =
1726 MD->getType()->getAs<FunctionType>()->getResultType();
1727 QualType OverriddenReturnType =
1728 OMD->getType()->getAs<FunctionType>()->getResultType();
Anders Carlsson27682a32009-12-03 01:54:02 +00001729
Eli Friedman47145832009-12-04 08:34:14 +00001730 // Check if we need a return type adjustment.
1731 if (TypeConversionRequiresAdjustment(CGM.getContext(), ReturnType,
1732 OverriddenReturnType)) {
1733 CanQualType &BaseReturnType = BaseReturnTypes[Index];
Anders Carlsson27682a32009-12-03 01:54:02 +00001734
Eli Friedman47145832009-12-04 08:34:14 +00001735 // Insert the base return type.
1736 if (BaseReturnType.isNull())
1737 BaseReturnType =
1738 CGM.getContext().getCanonicalType(OverriddenReturnType);
1739 }
Anders Carlssondd454be2009-12-04 03:52:52 +00001740
Eli Friedman47145832009-12-04 08:34:14 +00001741 Methods.OverrideMethod(OGD, GD);
1742
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00001743 GlobalDecl UGD = getUnique(GD);
1744 const CXXMethodDecl *UMD = cast<CXXMethodDecl>(UGD.getDecl());
1745 assert(UGD.getDecl() && "unique overrider not found");
1746 assert(UGD == getUnique(OGD) && "unique overrider not unique");
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001747
Eli Friedman47145832009-12-04 08:34:14 +00001748 ThisAdjustments.erase(Index);
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001749 if (MorallyVirtual || VCall.count(UMD)) {
Mike Stump15189fb2010-01-26 21:35:27 +00001750
Mike Stumpcf0b9cc2010-01-26 00:05:04 +00001751 Index_t &idx = VCall[UMD];
Eli Friedman47145832009-12-04 08:34:14 +00001752 if (idx == 0) {
Mike Stump15189fb2010-01-26 21:35:27 +00001753 VCallOffset[GD] = VCallOffset[OGD];
1754 // NonVirtualOffset[UMD] = CurrentVBaseOffset/8 - OverrideOffset/8;
1755 NonVirtualOffset[UMD] = VCallOffset[OGD];
Mike Stumpd99a4d22010-01-26 03:42:22 +00001756 VCallOffsetForVCall[UMD] = OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00001757 idx = VCalls.size()+1;
Mike Stumpd99a4d22010-01-26 03:42:22 +00001758 VCalls.push_back(OverrideOffset/8 - CurrentVBaseOffset/8);
Eli Friedman47145832009-12-04 08:34:14 +00001759 D1(printf(" vcall for %s at %d with delta %d most derived %s\n",
1760 MD->getNameAsString().c_str(), (int)-idx-3,
Mike Stumpd6584902010-01-22 02:51:26 +00001761 (int)VCalls[idx-1], MostDerivedClass->getNameAsCString()));
Eli Friedman47145832009-12-04 08:34:14 +00001762 } else {
Mike Stump15189fb2010-01-26 21:35:27 +00001763 VCallOffset[GD] = NonVirtualOffset[UMD];
Anders Carlsson0f0bbbc2010-01-26 17:36:47 +00001764 VCalls[idx-1] = -VCallOffsetForVCall[UGD] + OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00001765 D1(printf(" vcall patch for %s at %d with delta %d most derived %s\n",
1766 MD->getNameAsString().c_str(), (int)-idx-3,
Mike Stumpd6584902010-01-22 02:51:26 +00001767 (int)VCalls[idx-1], MostDerivedClass->getNameAsCString()));
Eli Friedman47145832009-12-04 08:34:14 +00001768 }
Mike Stump15189fb2010-01-26 21:35:27 +00001769 int64_t NonVirtualAdjustment = -VCallOffset[OGD];
Mike Stump852f5ce2010-01-26 22:44:01 +00001770 QualType DerivedType = MD->getThisType(CGM.getContext());
1771 QualType BaseType = cast<const CXXMethodDecl>(OGD.getDecl())->getThisType(CGM.getContext());
1772 int64_t NonVirtualAdjustment2 = -(getNVOffset(BaseType, DerivedType)/8);
1773 if (NonVirtualAdjustment2 != NonVirtualAdjustment) {
1774 NonVirtualAdjustment = NonVirtualAdjustment2;
1775 }
Eli Friedman47145832009-12-04 08:34:14 +00001776 int64_t VirtualAdjustment =
1777 -((idx + extra + 2) * LLVMPointerWidth / 8);
Anders Carlsson891bb4b2009-12-03 02:32:59 +00001778
Eli Friedman47145832009-12-04 08:34:14 +00001779 // Optimize out virtual adjustments of 0.
1780 if (VCalls[idx-1] == 0)
1781 VirtualAdjustment = 0;
Anders Carlsson891bb4b2009-12-03 02:32:59 +00001782
Eli Friedman47145832009-12-04 08:34:14 +00001783 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment,
1784 VirtualAdjustment);
Anders Carlssonbc0e3392009-12-03 02:22:59 +00001785
Eli Friedman72649ed2009-12-06 22:01:30 +00001786 if (!isPure && !ThisAdjustment.isEmpty()) {
Eli Friedman47145832009-12-04 08:34:14 +00001787 ThisAdjustments[Index] = ThisAdjustment;
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001788 SavedAdjustments.push_back(
1789 std::make_pair(GD, std::make_pair(OGD, ThisAdjustment)));
Eli Friedman72649ed2009-12-06 22:01:30 +00001790 }
Anders Carlsson27682a32009-12-03 01:54:02 +00001791 return true;
1792 }
Eli Friedman47145832009-12-04 08:34:14 +00001793
Mike Stump15189fb2010-01-26 21:35:27 +00001794 VCallOffset[GD] = VCallOffset[OGD2] - OverrideOffset/8;
Eli Friedman47145832009-12-04 08:34:14 +00001795
Mike Stump15189fb2010-01-26 21:35:27 +00001796 int64_t NonVirtualAdjustment = -VCallOffset[GD];
1797 QualType DerivedType = MD->getThisType(CGM.getContext());
1798 QualType BaseType = cast<const CXXMethodDecl>(OGD.getDecl())->getThisType(CGM.getContext());
1799 int64_t NonVirtualAdjustment2 = -(getNVOffset(BaseType, DerivedType)/8);
1800 if (NonVirtualAdjustment2 != NonVirtualAdjustment) {
1801 NonVirtualAdjustment = NonVirtualAdjustment2;
1802 }
1803
Eli Friedman47145832009-12-04 08:34:14 +00001804 if (NonVirtualAdjustment) {
1805 ThunkAdjustment ThisAdjustment(NonVirtualAdjustment, 0);
1806
Eli Friedmanf062d9d2009-12-06 22:33:51 +00001807 if (!isPure) {
Eli Friedman47145832009-12-04 08:34:14 +00001808 ThisAdjustments[Index] = ThisAdjustment;
Eli Friedmanb455f0e2009-12-07 23:56:34 +00001809 SavedAdjustments.push_back(
1810 std::make_pair(GD, std::make_pair(OGD, ThisAdjustment)));
Eli Friedmanf062d9d2009-12-06 22:33:51 +00001811 }
Eli Friedman47145832009-12-04 08:34:14 +00001812 }
1813 return true;
Anders Carlsson27682a32009-12-03 01:54:02 +00001814 }
1815
1816 return false;
Anders Carlsson27f69d02009-11-27 22:21:51 +00001817}
1818
Anders Carlsson824d7ea2010-02-11 08:02:13 +00001819void OldVtableBuilder::AppendMethodsToVtable() {
Eli Friedman152b5b12009-12-05 01:05:03 +00001820 if (!BuildVtable) {
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001821 VtableComponents.insert(VtableComponents.end(), Methods.size(),
1822 (llvm::Constant *)0);
Eli Friedman152b5b12009-12-05 01:05:03 +00001823 ThisAdjustments.clear();
1824 BaseReturnTypes.clear();
1825 Methods.clear();
1826 return;
1827 }
1828
Anders Carlsson15318f42009-12-04 16:19:30 +00001829 // Reserve room in the vtable for our new methods.
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001830 VtableComponents.reserve(VtableComponents.size() + Methods.size());
Anders Carlsson29202d52009-12-04 03:07:26 +00001831
Anders Carlssonb73ba392009-12-04 02:43:50 +00001832 for (unsigned i = 0, e = Methods.size(); i != e; ++i) {
1833 GlobalDecl GD = Methods[i];
Anders Carlssonea357222009-12-04 02:52:22 +00001834 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1835
1836 // Get the 'this' pointer adjustment.
Anders Carlssonb73ba392009-12-04 02:43:50 +00001837 ThunkAdjustment ThisAdjustment = ThisAdjustments.lookup(i);
Anders Carlssonea357222009-12-04 02:52:22 +00001838
1839 // Construct the return type adjustment.
1840 ThunkAdjustment ReturnAdjustment;
1841
1842 QualType BaseReturnType = BaseReturnTypes.lookup(i);
1843 if (!BaseReturnType.isNull() && !MD->isPure()) {
1844 QualType DerivedType =
1845 MD->getType()->getAs<FunctionType>()->getResultType();
1846
1847 int64_t NonVirtualAdjustment =
1848 getNVOffset(BaseReturnType, DerivedType) / 8;
1849
1850 int64_t VirtualAdjustment =
1851 getVbaseOffset(BaseReturnType, DerivedType);
1852
1853 ReturnAdjustment = ThunkAdjustment(NonVirtualAdjustment,
1854 VirtualAdjustment);
1855 }
1856
Anders Carlsson2fce2162009-12-04 03:06:03 +00001857 llvm::Constant *Method = 0;
Anders Carlssonea357222009-12-04 02:52:22 +00001858 if (!ReturnAdjustment.isEmpty()) {
1859 // Build a covariant thunk.
1860 CovariantThunkAdjustment Adjustment(ThisAdjustment, ReturnAdjustment);
Eli Friedman72649ed2009-12-06 22:01:30 +00001861 Method = wrap(CGM.GetAddrOfCovariantThunk(GD, Adjustment));
Anders Carlssonea357222009-12-04 02:52:22 +00001862 } else if (!ThisAdjustment.isEmpty()) {
1863 // Build a "regular" thunk.
Eli Friedman72649ed2009-12-06 22:01:30 +00001864 Method = wrap(CGM.GetAddrOfThunk(GD, ThisAdjustment));
Anders Carlssonbf540272009-12-04 02:56:03 +00001865 } else if (MD->isPure()) {
1866 // We have a pure virtual method.
Anders Carlsson2fce2162009-12-04 03:06:03 +00001867 Method = getPureVirtualFn();
1868 } else {
1869 // We have a good old regular method.
1870 Method = WrapAddrOf(GD);
Anders Carlssonea357222009-12-04 02:52:22 +00001871 }
Anders Carlsson2fce2162009-12-04 03:06:03 +00001872
1873 // Add the method to the vtable.
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00001874 VtableComponents.push_back(Method);
Anders Carlssonb73ba392009-12-04 02:43:50 +00001875 }
1876
Anders Carlsson2fce2162009-12-04 03:06:03 +00001877
Anders Carlssonb73ba392009-12-04 02:43:50 +00001878 ThisAdjustments.clear();
Anders Carlssonea357222009-12-04 02:52:22 +00001879 BaseReturnTypes.clear();
Anders Carlssonb73ba392009-12-04 02:43:50 +00001880
Anders Carlssonadfa2672009-12-04 02:39:04 +00001881 Methods.clear();
Anders Carlssonadfa2672009-12-04 02:39:04 +00001882}
1883
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001884void CGVtableInfo::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
1885
1886 // Itanium C++ ABI 2.5.2:
Anders Carlsson45147d02010-02-02 03:37:46 +00001887 // The order of the virtual function pointers in a virtual table is the
1888 // order of declaration of the corresponding member functions in the class.
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001889 //
Anders Carlsson45147d02010-02-02 03:37:46 +00001890 // There is an entry for any virtual function declared in a class,
1891 // whether it is a new function or overrides a base class function,
1892 // unless it overrides a function from the primary base, and conversion
1893 // between their return types does not require an adjustment.
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001894
1895 int64_t CurrentIndex = 0;
1896
1897 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1898 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1899
1900 if (PrimaryBase) {
Anders Carlsson0121fbd2009-11-30 19:43:26 +00001901 assert(PrimaryBase->isDefinition() &&
1902 "Should have the definition decl of the primary base!");
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001903
1904 // Since the record decl shares its vtable pointer with the primary base
1905 // we need to start counting at the end of the primary base's vtable.
1906 CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
1907 }
Eli Friedmanea5ae312009-12-15 03:31:17 +00001908
1909 // Collect all the primary bases, so we can check whether methods override
1910 // a method from the base.
Anders Carlsson57071e22010-02-12 05:25:12 +00001911 VtableBuilder::PrimaryBasesSetTy PrimaryBases;
Eli Friedmanea5ae312009-12-15 03:31:17 +00001912 for (ASTRecordLayout::primary_base_info_iterator
1913 I = Layout.primary_base_begin(), E = Layout.primary_base_end();
1914 I != E; ++I)
1915 PrimaryBases.insert((*I).getBase());
1916
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001917 const CXXDestructorDecl *ImplicitVirtualDtor = 0;
1918
1919 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
1920 e = RD->method_end(); i != e; ++i) {
1921 const CXXMethodDecl *MD = *i;
1922
1923 // We only want virtual methods.
1924 if (!MD->isVirtual())
1925 continue;
1926
1927 bool ShouldAddEntryForMethod = true;
1928
1929 // Check if this method overrides a method in the primary base.
Anders Carlsson57071e22010-02-12 05:25:12 +00001930 if (const CXXMethodDecl *OverriddenMD =
1931 OverridesMethodInPrimaryBase(MD, PrimaryBases)) {
1932 // Check if converting from the return type of the method to the
1933 // return type of the overridden method requires conversion.
Anders Carlsson104f45c2010-02-12 17:37:14 +00001934 if (!ReturnTypeConversionRequiresAdjustment(MD, OverriddenMD)) {
Anders Carlsson57071e22010-02-12 05:25:12 +00001935 // This index is shared between the index in the vtable of the primary
1936 // base class.
1937 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1938 const CXXDestructorDecl *OverriddenDD =
1939 cast<CXXDestructorDecl>(OverriddenMD);
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001940
Anders Carlsson57071e22010-02-12 05:25:12 +00001941 // Add both the complete and deleting entries.
1942 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] =
1943 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
1944 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] =
1945 getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
1946 } else {
1947 MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
1948 }
1949
1950 // We don't need to add an entry for this method.
1951 ShouldAddEntryForMethod = false;
1952 break;
Anders Carlssond6b07fb2009-11-27 20:47:55 +00001953 }
1954 }
1955
1956 if (!ShouldAddEntryForMethod)
1957 continue;
1958
1959 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1960 if (MD->isImplicit()) {
1961 assert(!ImplicitVirtualDtor &&
1962 "Did already see an implicit virtual dtor!");
1963 ImplicitVirtualDtor = DD;
1964 continue;
1965 }
1966
1967 // Add the complete dtor.
1968 MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
1969
1970 // Add the deleting dtor.
1971 MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
1972 } else {
1973 // Add the entry.
1974 MethodVtableIndices[MD] = CurrentIndex++;
1975 }
1976 }
1977
1978 if (ImplicitVirtualDtor) {
1979 // Itanium C++ ABI 2.5.2:
1980 // If a class has an implicitly-defined virtual destructor,
1981 // its entries come after the declared virtual function pointers.
1982
1983 // Add the complete dtor.
1984 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
1985 CurrentIndex++;
1986
1987 // Add the deleting dtor.
1988 MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
1989 CurrentIndex++;
1990 }
1991
1992 NumVirtualFunctionPointers[RD] = CurrentIndex;
1993}
1994
1995uint64_t CGVtableInfo::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
1996 llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
1997 NumVirtualFunctionPointers.find(RD);
1998 if (I != NumVirtualFunctionPointers.end())
1999 return I->second;
2000
2001 ComputeMethodVtableIndices(RD);
2002
2003 I = NumVirtualFunctionPointers.find(RD);
2004 assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
2005 return I->second;
2006}
2007
2008uint64_t CGVtableInfo::getMethodVtableIndex(GlobalDecl GD) {
Anders Carlssona0fdd912009-11-13 17:08:56 +00002009 MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002010 if (I != MethodVtableIndices.end())
2011 return I->second;
2012
Anders Carlssona0fdd912009-11-13 17:08:56 +00002013 const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
Anders Carlssond6b07fb2009-11-27 20:47:55 +00002014
2015 ComputeMethodVtableIndices(RD);
2016
Anders Carlssona0fdd912009-11-13 17:08:56 +00002017 I = MethodVtableIndices.find(GD);
Anders Carlssondbd920c2009-10-11 22:13:54 +00002018 assert(I != MethodVtableIndices.end() && "Did not find index!");
2019 return I->second;
2020}
2021
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002022CGVtableInfo::AdjustmentVectorTy*
2023CGVtableInfo::getAdjustments(GlobalDecl GD) {
2024 SavedAdjustmentsTy::iterator I = SavedAdjustments.find(GD);
2025 if (I != SavedAdjustments.end())
2026 return &I->second;
Eli Friedman72649ed2009-12-06 22:01:30 +00002027
2028 const CXXRecordDecl *RD = cast<CXXRecordDecl>(GD.getDecl()->getDeclContext());
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002029 if (!SavedAdjustmentRecords.insert(RD).second)
2030 return 0;
Eli Friedman72649ed2009-12-06 22:01:30 +00002031
Anders Carlsson1bb60992010-01-14 02:29:07 +00002032 AddressPointsMapTy AddressPoints;
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002033 OldVtableBuilder b(RD, RD, 0, CGM, false, AddressPoints);
Eli Friedman72649ed2009-12-06 22:01:30 +00002034 D1(printf("vtable %s\n", RD->getNameAsCString()));
2035 b.GenerateVtableForBase(RD);
2036 b.GenerateVtableForVBases(RD);
Eli Friedman72649ed2009-12-06 22:01:30 +00002037
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002038 for (OldVtableBuilder::SavedAdjustmentsVectorTy::iterator
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002039 i = b.getSavedAdjustments().begin(),
2040 e = b.getSavedAdjustments().end(); i != e; i++)
2041 SavedAdjustments[i->first].push_back(i->second);
Eli Friedman72649ed2009-12-06 22:01:30 +00002042
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002043 I = SavedAdjustments.find(GD);
2044 if (I != SavedAdjustments.end())
2045 return &I->second;
2046
2047 return 0;
Eli Friedman72649ed2009-12-06 22:01:30 +00002048}
2049
Anders Carlssondbd920c2009-10-11 22:13:54 +00002050int64_t CGVtableInfo::getVirtualBaseOffsetIndex(const CXXRecordDecl *RD,
2051 const CXXRecordDecl *VBase) {
2052 ClassPairTy ClassPair(RD, VBase);
2053
2054 VirtualBaseClassIndiciesTy::iterator I =
2055 VirtualBaseClassIndicies.find(ClassPair);
2056 if (I != VirtualBaseClassIndicies.end())
2057 return I->second;
2058
Anders Carlssondbd920c2009-10-11 22:13:54 +00002059 // FIXME: This seems expensive. Can we do a partial job to get
2060 // just this data.
Anders Carlsson1bb60992010-01-14 02:29:07 +00002061 AddressPointsMapTy AddressPoints;
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002062 OldVtableBuilder b(RD, RD, 0, CGM, false, AddressPoints);
Mike Stump6a9612f2009-10-31 20:06:59 +00002063 D1(printf("vtable %s\n", RD->getNameAsCString()));
Anders Carlssondbd920c2009-10-11 22:13:54 +00002064 b.GenerateVtableForBase(RD);
2065 b.GenerateVtableForVBases(RD);
2066
2067 for (llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
2068 b.getVBIndex().begin(), E = b.getVBIndex().end(); I != E; ++I) {
2069 // Insert all types.
2070 ClassPairTy ClassPair(RD, I->first);
2071
2072 VirtualBaseClassIndicies.insert(std::make_pair(ClassPair, I->second));
2073 }
2074
2075 I = VirtualBaseClassIndicies.find(ClassPair);
2076 assert(I != VirtualBaseClassIndicies.end() && "Did not find index!");
2077
2078 return I->second;
2079}
2080
Anders Carlsson9ac95b92009-12-05 21:03:56 +00002081uint64_t CGVtableInfo::getVtableAddressPoint(const CXXRecordDecl *RD) {
2082 uint64_t AddressPoint =
Anders Carlsson21431c52010-01-02 18:02:32 +00002083 (*(*(CGM.getVtableInfo().AddressPoints[RD]))[RD])[std::make_pair(RD, 0)];
Anders Carlsson9ac95b92009-12-05 21:03:56 +00002084
2085 return AddressPoint;
2086}
2087
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00002088llvm::GlobalVariable *
Anders Carlsson35272252009-12-06 00:23:49 +00002089CGVtableInfo::GenerateVtable(llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson5794c972009-12-06 00:53:22 +00002090 bool GenerateDefinition,
Anders Carlsson35272252009-12-06 00:23:49 +00002091 const CXXRecordDecl *LayoutClass,
Anders Carlsson1bb60992010-01-14 02:29:07 +00002092 const CXXRecordDecl *RD, uint64_t Offset,
2093 AddressPointsMapTy& AddressPoints) {
Anders Carlssondbd920c2009-10-11 22:13:54 +00002094 llvm::SmallString<256> OutName;
Mike Stump9840c702009-11-12 20:47:57 +00002095 if (LayoutClass != RD)
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00002096 CGM.getMangleContext().mangleCXXCtorVtable(LayoutClass, Offset / 8,
2097 RD, OutName);
Mike Stump8cfcb522009-11-11 20:26:26 +00002098 else
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00002099 CGM.getMangleContext().mangleCXXVtable(RD, OutName);
Daniel Dunbar94fd26d2009-11-21 09:06:22 +00002100 llvm::StringRef Name = OutName.str();
Benjamin Kramer7a9474e2009-10-11 22:57:54 +00002101
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00002102 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
Anders Carlsson21431c52010-01-02 18:02:32 +00002103 if (GV == 0 || CGM.getVtableInfo().AddressPoints[LayoutClass] == 0 ||
2104 GV->isDeclaration()) {
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002105 OldVtableBuilder b(RD, LayoutClass, Offset, CGM, GenerateDefinition,
2106 AddressPoints);
Eli Friedman152b5b12009-12-05 01:05:03 +00002107
2108 D1(printf("vtable %s\n", RD->getNameAsCString()));
2109 // First comes the vtables for all the non-virtual bases...
Mike Stump8cc4f102009-12-24 07:29:41 +00002110 b.GenerateVtableForBase(RD, Offset);
Eli Friedman152b5b12009-12-05 01:05:03 +00002111
2112 // then the vtables for all the virtual bases.
2113 b.GenerateVtableForVBases(RD, Offset);
2114
Anders Carlsson152d4dc2009-12-05 22:19:10 +00002115 llvm::Constant *Init = 0;
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00002116 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Anders Carlsson152d4dc2009-12-05 22:19:10 +00002117 llvm::ArrayType *ArrayType =
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002118 llvm::ArrayType::get(Int8PtrTy, b.getVtableComponents().size());
Anders Carlssone40477c2009-12-05 21:09:05 +00002119
Anders Carlsson5794c972009-12-06 00:53:22 +00002120 if (GenerateDefinition)
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002121 Init = llvm::ConstantArray::get(ArrayType, &b.getVtableComponents()[0],
2122 b.getVtableComponents().size());
Anders Carlsson5794c972009-12-06 00:53:22 +00002123
Mike Stump85615df2009-11-19 04:04:36 +00002124 llvm::GlobalVariable *OGV = GV;
Anders Carlsson5794c972009-12-06 00:53:22 +00002125
2126 GV = new llvm::GlobalVariable(CGM.getModule(), ArrayType,
2127 /*isConstant=*/true, Linkage, Init, Name);
Anders Carlssonc3a46ef2009-12-06 01:09:21 +00002128 CGM.setGlobalVisibility(GV, RD);
2129
Mike Stump85615df2009-11-19 04:04:36 +00002130 if (OGV) {
2131 GV->takeName(OGV);
Anders Carlsson152d4dc2009-12-05 22:19:10 +00002132 llvm::Constant *NewPtr =
2133 llvm::ConstantExpr::getBitCast(GV, OGV->getType());
Mike Stump85615df2009-11-19 04:04:36 +00002134 OGV->replaceAllUsesWith(NewPtr);
2135 OGV->eraseFromParent();
2136 }
Mike Stump85615df2009-11-19 04:04:36 +00002137 }
Anders Carlssonbb27d862009-12-05 21:28:12 +00002138
Anders Carlsson824d7ea2010-02-11 08:02:13 +00002139 if (GenerateDefinition && CGM.getLangOptions().DumpVtableLayouts) {
2140 VtableBuilder Builder(RD);
2141
2142 Builder.dumpLayout(llvm::errs());
2143 }
2144
Anders Carlssonbb27d862009-12-05 21:28:12 +00002145 return GV;
Anders Carlssondbd920c2009-10-11 22:13:54 +00002146}
Mike Stumpfbfb52d2009-11-10 02:30:51 +00002147
Anders Carlsson5794c972009-12-06 00:53:22 +00002148void CGVtableInfo::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
2149 const CXXRecordDecl *RD) {
Anders Carlssond58987c2009-12-07 07:59:52 +00002150 llvm::GlobalVariable *&Vtable = Vtables[RD];
2151 if (Vtable) {
2152 assert(Vtable->getInitializer() && "Vtable doesn't have a definition!");
2153 return;
2154 }
2155
Anders Carlsson1bb60992010-01-14 02:29:07 +00002156 AddressPointsMapTy AddressPoints;
2157 Vtable = GenerateVtable(Linkage, /*GenerateDefinition=*/true, RD, RD, 0,
2158 AddressPoints);
Anders Carlssonc997d422010-01-02 01:01:18 +00002159 GenerateVTT(Linkage, /*GenerateDefinition=*/true, RD);
Mike Stump58588942009-11-19 01:08:19 +00002160}
2161
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00002162llvm::GlobalVariable *CGVtableInfo::getVtable(const CXXRecordDecl *RD) {
Anders Carlsson5794c972009-12-06 00:53:22 +00002163 llvm::GlobalVariable *Vtable = Vtables.lookup(RD);
Anders Carlsson8c2d36f2009-12-06 00:01:05 +00002164
Anders Carlsson1bb60992010-01-14 02:29:07 +00002165 if (!Vtable) {
2166 AddressPointsMapTy AddressPoints;
Anders Carlsson5794c972009-12-06 00:53:22 +00002167 Vtable = GenerateVtable(llvm::GlobalValue::ExternalLinkage,
Anders Carlsson1bb60992010-01-14 02:29:07 +00002168 /*GenerateDefinition=*/false, RD, RD, 0,
2169 AddressPoints);
2170 }
Mike Stump85615df2009-11-19 04:04:36 +00002171
Anders Carlsson224c3122009-12-05 22:42:54 +00002172 return Vtable;
Mike Stump380dd752009-11-10 07:44:33 +00002173}
Mike Stump8cfcb522009-11-11 20:26:26 +00002174
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002175void CGVtableInfo::MaybeEmitVtable(GlobalDecl GD) {
2176 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2177 const CXXRecordDecl *RD = MD->getParent();
2178
Anders Carlsson224c3122009-12-05 22:42:54 +00002179 // If the class doesn't have a vtable we don't need to emit one.
2180 if (!RD->isDynamicClass())
2181 return;
2182
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002183 // Get the key function.
Anders Carlssonf53df232009-12-07 04:35:11 +00002184 const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002185
Anders Carlsson224c3122009-12-05 22:42:54 +00002186 if (KeyFunction) {
2187 // We don't have the right key function.
2188 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
2189 return;
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002190 }
2191
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002192 // Emit the data.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00002193 GenerateClassData(CGM.getVtableLinkage(RD), RD);
Eli Friedman72649ed2009-12-06 22:01:30 +00002194
2195 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2196 e = RD->method_end(); i != e; ++i) {
Eli Friedmanb455f0e2009-12-07 23:56:34 +00002197 if ((*i)->isVirtual() && ((*i)->hasInlineBody() || (*i)->isImplicit())) {
Eli Friedman72649ed2009-12-06 22:01:30 +00002198 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(*i)) {
2199 CGM.BuildThunksForVirtual(GlobalDecl(DD, Dtor_Complete));
2200 CGM.BuildThunksForVirtual(GlobalDecl(DD, Dtor_Deleting));
2201 } else {
2202 CGM.BuildThunksForVirtual(GlobalDecl(*i));
2203 }
2204 }
2205 }
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002206}
2207