VTableBuilder.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  1. //===--- VTableBuilder.cpp - C++ vtable layout builder --------------------===//
  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 generation of the layout of virtual tables.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/VTableBuilder.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/RecordLayout.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "llvm/Support/Format.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. #include <algorithm>
  21. #include <cstdio>
  22. using namespace clang;
  23. #define DUMP_OVERRIDERS 0
  24. namespace {
  25. /// BaseOffset - Represents an offset from a derived class to a direct or
  26. /// indirect base class.
  27. struct BaseOffset {
  28. /// DerivedClass - The derived class.
  29. const CXXRecordDecl *DerivedClass;
  30. /// VirtualBase - If the path from the derived class to the base class
  31. /// involves a virtual base class, this holds its declaration.
  32. const CXXRecordDecl *VirtualBase;
  33. /// NonVirtualOffset - The offset from the derived class to the base class.
  34. /// (Or the offset from the virtual base class to the base class, if the
  35. /// path from the derived class to the base class involves a virtual base
  36. /// class.
  37. CharUnits NonVirtualOffset;
  38. BaseOffset() : DerivedClass(0), VirtualBase(0),
  39. NonVirtualOffset(CharUnits::Zero()) { }
  40. BaseOffset(const CXXRecordDecl *DerivedClass,
  41. const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
  42. : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
  43. NonVirtualOffset(NonVirtualOffset) { }
  44. bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
  45. };
  46. /// FinalOverriders - Contains the final overrider member functions for all
  47. /// member functions in the base subobjects of a class.
  48. class FinalOverriders {
  49. public:
  50. /// OverriderInfo - Information about a final overrider.
  51. struct OverriderInfo {
  52. /// Method - The method decl of the overrider.
  53. const CXXMethodDecl *Method;
  54. /// Offset - the base offset of the overrider in the layout class.
  55. CharUnits Offset;
  56. OverriderInfo() : Method(0), Offset(CharUnits::Zero()) { }
  57. };
  58. private:
  59. /// MostDerivedClass - The most derived class for which the final overriders
  60. /// are stored.
  61. const CXXRecordDecl *MostDerivedClass;
  62. /// MostDerivedClassOffset - If we're building final overriders for a
  63. /// construction vtable, this holds the offset from the layout class to the
  64. /// most derived class.
  65. const CharUnits MostDerivedClassOffset;
  66. /// LayoutClass - The class we're using for layout information. Will be
  67. /// different than the most derived class if the final overriders are for a
  68. /// construction vtable.
  69. const CXXRecordDecl *LayoutClass;
  70. ASTContext &Context;
  71. /// MostDerivedClassLayout - the AST record layout of the most derived class.
  72. const ASTRecordLayout &MostDerivedClassLayout;
  73. /// MethodBaseOffsetPairTy - Uniquely identifies a member function
  74. /// in a base subobject.
  75. typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
  76. typedef llvm::DenseMap<MethodBaseOffsetPairTy,
  77. OverriderInfo> OverridersMapTy;
  78. /// OverridersMap - The final overriders for all virtual member functions of
  79. /// all the base subobjects of the most derived class.
  80. OverridersMapTy OverridersMap;
  81. /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
  82. /// as a record decl and a subobject number) and its offsets in the most
  83. /// derived class as well as the layout class.
  84. typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
  85. CharUnits> SubobjectOffsetMapTy;
  86. typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
  87. /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
  88. /// given base.
  89. void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
  90. CharUnits OffsetInLayoutClass,
  91. SubobjectOffsetMapTy &SubobjectOffsets,
  92. SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
  93. SubobjectCountMapTy &SubobjectCounts);
  94. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  95. /// dump - dump the final overriders for a base subobject, and all its direct
  96. /// and indirect base subobjects.
  97. void dump(raw_ostream &Out, BaseSubobject Base,
  98. VisitedVirtualBasesSetTy& VisitedVirtualBases);
  99. public:
  100. FinalOverriders(const CXXRecordDecl *MostDerivedClass,
  101. CharUnits MostDerivedClassOffset,
  102. const CXXRecordDecl *LayoutClass);
  103. /// getOverrider - Get the final overrider for the given method declaration in
  104. /// the subobject with the given base offset.
  105. OverriderInfo getOverrider(const CXXMethodDecl *MD,
  106. CharUnits BaseOffset) const {
  107. assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
  108. "Did not find overrider!");
  109. return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
  110. }
  111. /// dump - dump the final overriders.
  112. void dump() {
  113. VisitedVirtualBasesSetTy VisitedVirtualBases;
  114. dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
  115. VisitedVirtualBases);
  116. }
  117. };
  118. #define DUMP_OVERRIDERS 0
  119. FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
  120. CharUnits MostDerivedClassOffset,
  121. const CXXRecordDecl *LayoutClass)
  122. : MostDerivedClass(MostDerivedClass),
  123. MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
  124. Context(MostDerivedClass->getASTContext()),
  125. MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
  126. // Compute base offsets.
  127. SubobjectOffsetMapTy SubobjectOffsets;
  128. SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
  129. SubobjectCountMapTy SubobjectCounts;
  130. ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
  131. /*IsVirtual=*/false,
  132. MostDerivedClassOffset,
  133. SubobjectOffsets, SubobjectLayoutClassOffsets,
  134. SubobjectCounts);
  135. // Get the final overriders.
  136. CXXFinalOverriderMap FinalOverriders;
  137. MostDerivedClass->getFinalOverriders(FinalOverriders);
  138. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  139. E = FinalOverriders.end(); I != E; ++I) {
  140. const CXXMethodDecl *MD = I->first;
  141. const OverridingMethods& Methods = I->second;
  142. for (OverridingMethods::const_iterator I = Methods.begin(),
  143. E = Methods.end(); I != E; ++I) {
  144. unsigned SubobjectNumber = I->first;
  145. assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
  146. SubobjectNumber)) &&
  147. "Did not find subobject offset!");
  148. CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
  149. SubobjectNumber)];
  150. assert(I->second.size() == 1 && "Final overrider is not unique!");
  151. const UniqueVirtualMethod &Method = I->second.front();
  152. const CXXRecordDecl *OverriderRD = Method.Method->getParent();
  153. assert(SubobjectLayoutClassOffsets.count(
  154. std::make_pair(OverriderRD, Method.Subobject))
  155. && "Did not find subobject offset!");
  156. CharUnits OverriderOffset =
  157. SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
  158. Method.Subobject)];
  159. OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
  160. assert(!Overrider.Method && "Overrider should not exist yet!");
  161. Overrider.Offset = OverriderOffset;
  162. Overrider.Method = Method.Method;
  163. }
  164. }
  165. #if DUMP_OVERRIDERS
  166. // And dump them (for now).
  167. dump();
  168. #endif
  169. }
  170. static BaseOffset ComputeBaseOffset(ASTContext &Context,
  171. const CXXRecordDecl *DerivedRD,
  172. const CXXBasePath &Path) {
  173. CharUnits NonVirtualOffset = CharUnits::Zero();
  174. unsigned NonVirtualStart = 0;
  175. const CXXRecordDecl *VirtualBase = 0;
  176. // First, look for the virtual base class.
  177. for (unsigned I = 0, E = Path.size(); I != E; ++I) {
  178. const CXXBasePathElement &Element = Path[I];
  179. if (Element.Base->isVirtual()) {
  180. // FIXME: Can we break when we find the first virtual base?
  181. // (If we can't, can't we just iterate over the path in reverse order?)
  182. NonVirtualStart = I + 1;
  183. QualType VBaseType = Element.Base->getType();
  184. VirtualBase =
  185. cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
  186. }
  187. }
  188. // Now compute the non-virtual offset.
  189. for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
  190. const CXXBasePathElement &Element = Path[I];
  191. // Check the base class offset.
  192. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
  193. const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
  194. const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
  195. NonVirtualOffset += Layout.getBaseClassOffset(Base);
  196. }
  197. // FIXME: This should probably use CharUnits or something. Maybe we should
  198. // even change the base offsets in ASTRecordLayout to be specified in
  199. // CharUnits.
  200. return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
  201. }
  202. static BaseOffset ComputeBaseOffset(ASTContext &Context,
  203. const CXXRecordDecl *BaseRD,
  204. const CXXRecordDecl *DerivedRD) {
  205. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  206. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  207. if (!const_cast<CXXRecordDecl *>(DerivedRD)->
  208. isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
  209. llvm_unreachable("Class must be derived from the passed in base class!");
  210. }
  211. return ComputeBaseOffset(Context, DerivedRD, Paths.front());
  212. }
  213. static BaseOffset
  214. ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
  215. const CXXMethodDecl *DerivedMD,
  216. const CXXMethodDecl *BaseMD) {
  217. const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
  218. const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
  219. // Canonicalize the return types.
  220. CanQualType CanDerivedReturnType =
  221. Context.getCanonicalType(DerivedFT->getResultType());
  222. CanQualType CanBaseReturnType =
  223. Context.getCanonicalType(BaseFT->getResultType());
  224. assert(CanDerivedReturnType->getTypeClass() ==
  225. CanBaseReturnType->getTypeClass() &&
  226. "Types must have same type class!");
  227. if (CanDerivedReturnType == CanBaseReturnType) {
  228. // No adjustment needed.
  229. return BaseOffset();
  230. }
  231. if (isa<ReferenceType>(CanDerivedReturnType)) {
  232. CanDerivedReturnType =
  233. CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
  234. CanBaseReturnType =
  235. CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
  236. } else if (isa<PointerType>(CanDerivedReturnType)) {
  237. CanDerivedReturnType =
  238. CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
  239. CanBaseReturnType =
  240. CanBaseReturnType->getAs<PointerType>()->getPointeeType();
  241. } else {
  242. llvm_unreachable("Unexpected return type!");
  243. }
  244. // We need to compare unqualified types here; consider
  245. // const T *Base::foo();
  246. // T *Derived::foo();
  247. if (CanDerivedReturnType.getUnqualifiedType() ==
  248. CanBaseReturnType.getUnqualifiedType()) {
  249. // No adjustment needed.
  250. return BaseOffset();
  251. }
  252. const CXXRecordDecl *DerivedRD =
  253. cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
  254. const CXXRecordDecl *BaseRD =
  255. cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
  256. return ComputeBaseOffset(Context, BaseRD, DerivedRD);
  257. }
  258. void
  259. FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
  260. CharUnits OffsetInLayoutClass,
  261. SubobjectOffsetMapTy &SubobjectOffsets,
  262. SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
  263. SubobjectCountMapTy &SubobjectCounts) {
  264. const CXXRecordDecl *RD = Base.getBase();
  265. unsigned SubobjectNumber = 0;
  266. if (!IsVirtual)
  267. SubobjectNumber = ++SubobjectCounts[RD];
  268. // Set up the subobject to offset mapping.
  269. assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
  270. && "Subobject offset already exists!");
  271. assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
  272. && "Subobject offset already exists!");
  273. SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
  274. SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
  275. OffsetInLayoutClass;
  276. // Traverse our bases.
  277. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  278. E = RD->bases_end(); I != E; ++I) {
  279. const CXXRecordDecl *BaseDecl =
  280. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  281. CharUnits BaseOffset;
  282. CharUnits BaseOffsetInLayoutClass;
  283. if (I->isVirtual()) {
  284. // Check if we've visited this virtual base before.
  285. if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
  286. continue;
  287. const ASTRecordLayout &LayoutClassLayout =
  288. Context.getASTRecordLayout(LayoutClass);
  289. BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
  290. BaseOffsetInLayoutClass =
  291. LayoutClassLayout.getVBaseClassOffset(BaseDecl);
  292. } else {
  293. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  294. CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
  295. BaseOffset = Base.getBaseOffset() + Offset;
  296. BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
  297. }
  298. ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
  299. I->isVirtual(), BaseOffsetInLayoutClass,
  300. SubobjectOffsets, SubobjectLayoutClassOffsets,
  301. SubobjectCounts);
  302. }
  303. }
  304. void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
  305. VisitedVirtualBasesSetTy &VisitedVirtualBases) {
  306. const CXXRecordDecl *RD = Base.getBase();
  307. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  308. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  309. E = RD->bases_end(); I != E; ++I) {
  310. const CXXRecordDecl *BaseDecl =
  311. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  312. // Ignore bases that don't have any virtual member functions.
  313. if (!BaseDecl->isPolymorphic())
  314. continue;
  315. CharUnits BaseOffset;
  316. if (I->isVirtual()) {
  317. if (!VisitedVirtualBases.insert(BaseDecl)) {
  318. // We've visited this base before.
  319. continue;
  320. }
  321. BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
  322. } else {
  323. BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
  324. }
  325. dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
  326. }
  327. Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
  328. Out << Base.getBaseOffset().getQuantity() << ")\n";
  329. // Now dump the overriders for this base subobject.
  330. for (CXXRecordDecl::method_iterator I = RD->method_begin(),
  331. E = RD->method_end(); I != E; ++I) {
  332. const CXXMethodDecl *MD = *I;
  333. if (!MD->isVirtual())
  334. continue;
  335. OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
  336. Out << " " << MD->getQualifiedNameAsString() << " - (";
  337. Out << Overrider.Method->getQualifiedNameAsString();
  338. Out << ", " << ", " << Overrider.Offset.getQuantity() << ')';
  339. BaseOffset Offset;
  340. if (!Overrider.Method->isPure())
  341. Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
  342. if (!Offset.isEmpty()) {
  343. Out << " [ret-adj: ";
  344. if (Offset.VirtualBase)
  345. Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
  346. Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
  347. }
  348. Out << "\n";
  349. }
  350. }
  351. /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
  352. struct VCallOffsetMap {
  353. typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
  354. /// Offsets - Keeps track of methods and their offsets.
  355. // FIXME: This should be a real map and not a vector.
  356. SmallVector<MethodAndOffsetPairTy, 16> Offsets;
  357. /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
  358. /// can share the same vcall offset.
  359. static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
  360. const CXXMethodDecl *RHS);
  361. public:
  362. /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
  363. /// add was successful, or false if there was already a member function with
  364. /// the same signature in the map.
  365. bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
  366. /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
  367. /// vtable address point) for the given virtual member function.
  368. CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
  369. // empty - Return whether the offset map is empty or not.
  370. bool empty() const { return Offsets.empty(); }
  371. };
  372. static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
  373. const CXXMethodDecl *RHS) {
  374. const FunctionProtoType *LT =
  375. cast<FunctionProtoType>(LHS->getType().getCanonicalType());
  376. const FunctionProtoType *RT =
  377. cast<FunctionProtoType>(RHS->getType().getCanonicalType());
  378. // Fast-path matches in the canonical types.
  379. if (LT == RT) return true;
  380. // Force the signatures to match. We can't rely on the overrides
  381. // list here because there isn't necessarily an inheritance
  382. // relationship between the two methods.
  383. if (LT->getTypeQuals() != RT->getTypeQuals() ||
  384. LT->getNumArgs() != RT->getNumArgs())
  385. return false;
  386. for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
  387. if (LT->getArgType(I) != RT->getArgType(I))
  388. return false;
  389. return true;
  390. }
  391. bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
  392. const CXXMethodDecl *RHS) {
  393. assert(LHS->isVirtual() && "LHS must be virtual!");
  394. assert(RHS->isVirtual() && "LHS must be virtual!");
  395. // A destructor can share a vcall offset with another destructor.
  396. if (isa<CXXDestructorDecl>(LHS))
  397. return isa<CXXDestructorDecl>(RHS);
  398. // FIXME: We need to check more things here.
  399. // The methods must have the same name.
  400. DeclarationName LHSName = LHS->getDeclName();
  401. DeclarationName RHSName = RHS->getDeclName();
  402. if (LHSName != RHSName)
  403. return false;
  404. // And the same signatures.
  405. return HasSameVirtualSignature(LHS, RHS);
  406. }
  407. bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
  408. CharUnits OffsetOffset) {
  409. // Check if we can reuse an offset.
  410. for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
  411. if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
  412. return false;
  413. }
  414. // Add the offset.
  415. Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
  416. return true;
  417. }
  418. CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
  419. // Look for an offset.
  420. for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
  421. if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
  422. return Offsets[I].second;
  423. }
  424. llvm_unreachable("Should always find a vcall offset offset!");
  425. }
  426. /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
  427. class VCallAndVBaseOffsetBuilder {
  428. public:
  429. typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
  430. VBaseOffsetOffsetsMapTy;
  431. private:
  432. /// MostDerivedClass - The most derived class for which we're building vcall
  433. /// and vbase offsets.
  434. const CXXRecordDecl *MostDerivedClass;
  435. /// LayoutClass - The class we're using for layout information. Will be
  436. /// different than the most derived class if we're building a construction
  437. /// vtable.
  438. const CXXRecordDecl *LayoutClass;
  439. /// Context - The ASTContext which we will use for layout information.
  440. ASTContext &Context;
  441. /// Components - vcall and vbase offset components
  442. typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
  443. VTableComponentVectorTy Components;
  444. /// VisitedVirtualBases - Visited virtual bases.
  445. llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
  446. /// VCallOffsets - Keeps track of vcall offsets.
  447. VCallOffsetMap VCallOffsets;
  448. /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
  449. /// relative to the address point.
  450. VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
  451. /// FinalOverriders - The final overriders of the most derived class.
  452. /// (Can be null when we're not building a vtable of the most derived class).
  453. const FinalOverriders *Overriders;
  454. /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
  455. /// given base subobject.
  456. void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
  457. CharUnits RealBaseOffset);
  458. /// AddVCallOffsets - Add vcall offsets for the given base subobject.
  459. void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
  460. /// AddVBaseOffsets - Add vbase offsets for the given class.
  461. void AddVBaseOffsets(const CXXRecordDecl *Base,
  462. CharUnits OffsetInLayoutClass);
  463. /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
  464. /// chars, relative to the vtable address point.
  465. CharUnits getCurrentOffsetOffset() const;
  466. public:
  467. VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
  468. const CXXRecordDecl *LayoutClass,
  469. const FinalOverriders *Overriders,
  470. BaseSubobject Base, bool BaseIsVirtual,
  471. CharUnits OffsetInLayoutClass)
  472. : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
  473. Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
  474. // Add vcall and vbase offsets.
  475. AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
  476. }
  477. /// Methods for iterating over the components.
  478. typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
  479. const_iterator components_begin() const { return Components.rbegin(); }
  480. const_iterator components_end() const { return Components.rend(); }
  481. const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
  482. const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
  483. return VBaseOffsetOffsets;
  484. }
  485. };
  486. void
  487. VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
  488. bool BaseIsVirtual,
  489. CharUnits RealBaseOffset) {
  490. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
  491. // Itanium C++ ABI 2.5.2:
  492. // ..in classes sharing a virtual table with a primary base class, the vcall
  493. // and vbase offsets added by the derived class all come before the vcall
  494. // and vbase offsets required by the base class, so that the latter may be
  495. // laid out as required by the base class without regard to additions from
  496. // the derived class(es).
  497. // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
  498. // emit them for the primary base first).
  499. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  500. bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
  501. CharUnits PrimaryBaseOffset;
  502. // Get the base offset of the primary base.
  503. if (PrimaryBaseIsVirtual) {
  504. assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
  505. "Primary vbase should have a zero offset!");
  506. const ASTRecordLayout &MostDerivedClassLayout =
  507. Context.getASTRecordLayout(MostDerivedClass);
  508. PrimaryBaseOffset =
  509. MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
  510. } else {
  511. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  512. "Primary base should have a zero offset!");
  513. PrimaryBaseOffset = Base.getBaseOffset();
  514. }
  515. AddVCallAndVBaseOffsets(
  516. BaseSubobject(PrimaryBase,PrimaryBaseOffset),
  517. PrimaryBaseIsVirtual, RealBaseOffset);
  518. }
  519. AddVBaseOffsets(Base.getBase(), RealBaseOffset);
  520. // We only want to add vcall offsets for virtual bases.
  521. if (BaseIsVirtual)
  522. AddVCallOffsets(Base, RealBaseOffset);
  523. }
  524. CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
  525. // OffsetIndex is the index of this vcall or vbase offset, relative to the
  526. // vtable address point. (We subtract 3 to account for the information just
  527. // above the address point, the RTTI info, the offset to top, and the
  528. // vcall offset itself).
  529. int64_t OffsetIndex = -(int64_t)(3 + Components.size());
  530. CharUnits PointerWidth =
  531. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  532. CharUnits OffsetOffset = PointerWidth * OffsetIndex;
  533. return OffsetOffset;
  534. }
  535. void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
  536. CharUnits VBaseOffset) {
  537. const CXXRecordDecl *RD = Base.getBase();
  538. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  539. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  540. // Handle the primary base first.
  541. // We only want to add vcall offsets if the base is non-virtual; a virtual
  542. // primary base will have its vcall and vbase offsets emitted already.
  543. if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
  544. // Get the base offset of the primary base.
  545. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  546. "Primary base should have a zero offset!");
  547. AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
  548. VBaseOffset);
  549. }
  550. // Add the vcall offsets.
  551. for (CXXRecordDecl::method_iterator I = RD->method_begin(),
  552. E = RD->method_end(); I != E; ++I) {
  553. const CXXMethodDecl *MD = *I;
  554. if (!MD->isVirtual())
  555. continue;
  556. CharUnits OffsetOffset = getCurrentOffsetOffset();
  557. // Don't add a vcall offset if we already have one for this member function
  558. // signature.
  559. if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
  560. continue;
  561. CharUnits Offset = CharUnits::Zero();
  562. if (Overriders) {
  563. // Get the final overrider.
  564. FinalOverriders::OverriderInfo Overrider =
  565. Overriders->getOverrider(MD, Base.getBaseOffset());
  566. /// The vcall offset is the offset from the virtual base to the object
  567. /// where the function was overridden.
  568. Offset = Overrider.Offset - VBaseOffset;
  569. }
  570. Components.push_back(
  571. VTableComponent::MakeVCallOffset(Offset));
  572. }
  573. // And iterate over all non-virtual bases (ignoring the primary base).
  574. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  575. E = RD->bases_end(); I != E; ++I) {
  576. if (I->isVirtual())
  577. continue;
  578. const CXXRecordDecl *BaseDecl =
  579. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  580. if (BaseDecl == PrimaryBase)
  581. continue;
  582. // Get the base offset of this base.
  583. CharUnits BaseOffset = Base.getBaseOffset() +
  584. Layout.getBaseClassOffset(BaseDecl);
  585. AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
  586. VBaseOffset);
  587. }
  588. }
  589. void
  590. VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
  591. CharUnits OffsetInLayoutClass) {
  592. const ASTRecordLayout &LayoutClassLayout =
  593. Context.getASTRecordLayout(LayoutClass);
  594. // Add vbase offsets.
  595. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  596. E = RD->bases_end(); I != E; ++I) {
  597. const CXXRecordDecl *BaseDecl =
  598. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  599. // Check if this is a virtual base that we haven't visited before.
  600. if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
  601. CharUnits Offset =
  602. LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
  603. // Add the vbase offset offset.
  604. assert(!VBaseOffsetOffsets.count(BaseDecl) &&
  605. "vbase offset offset already exists!");
  606. CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
  607. VBaseOffsetOffsets.insert(
  608. std::make_pair(BaseDecl, VBaseOffsetOffset));
  609. Components.push_back(
  610. VTableComponent::MakeVBaseOffset(Offset));
  611. }
  612. // Check the base class looking for more vbase offsets.
  613. AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
  614. }
  615. }
  616. /// VTableBuilder - Class for building vtable layout information.
  617. class VTableBuilder {
  618. public:
  619. /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
  620. /// primary bases.
  621. typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
  622. PrimaryBasesSetVectorTy;
  623. typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
  624. VBaseOffsetOffsetsMapTy;
  625. typedef llvm::DenseMap<BaseSubobject, uint64_t>
  626. AddressPointsMapTy;
  627. private:
  628. /// VTables - Global vtable information.
  629. VTableContext &VTables;
  630. /// MostDerivedClass - The most derived class for which we're building this
  631. /// vtable.
  632. const CXXRecordDecl *MostDerivedClass;
  633. /// MostDerivedClassOffset - If we're building a construction vtable, this
  634. /// holds the offset from the layout class to the most derived class.
  635. const CharUnits MostDerivedClassOffset;
  636. /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
  637. /// base. (This only makes sense when building a construction vtable).
  638. bool MostDerivedClassIsVirtual;
  639. /// LayoutClass - The class we're using for layout information. Will be
  640. /// different than the most derived class if we're building a construction
  641. /// vtable.
  642. const CXXRecordDecl *LayoutClass;
  643. /// Context - The ASTContext which we will use for layout information.
  644. ASTContext &Context;
  645. /// FinalOverriders - The final overriders of the most derived class.
  646. const FinalOverriders Overriders;
  647. /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
  648. /// bases in this vtable.
  649. llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
  650. /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
  651. /// the most derived class.
  652. VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
  653. /// Components - The components of the vtable being built.
  654. SmallVector<VTableComponent, 64> Components;
  655. /// AddressPoints - Address points for the vtable being built.
  656. AddressPointsMapTy AddressPoints;
  657. /// MethodInfo - Contains information about a method in a vtable.
  658. /// (Used for computing 'this' pointer adjustment thunks.
  659. struct MethodInfo {
  660. /// BaseOffset - The base offset of this method.
  661. const CharUnits BaseOffset;
  662. /// BaseOffsetInLayoutClass - The base offset in the layout class of this
  663. /// method.
  664. const CharUnits BaseOffsetInLayoutClass;
  665. /// VTableIndex - The index in the vtable that this method has.
  666. /// (For destructors, this is the index of the complete destructor).
  667. const uint64_t VTableIndex;
  668. MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
  669. uint64_t VTableIndex)
  670. : BaseOffset(BaseOffset),
  671. BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
  672. VTableIndex(VTableIndex) { }
  673. MethodInfo()
  674. : BaseOffset(CharUnits::Zero()),
  675. BaseOffsetInLayoutClass(CharUnits::Zero()),
  676. VTableIndex(0) { }
  677. };
  678. typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
  679. /// MethodInfoMap - The information for all methods in the vtable we're
  680. /// currently building.
  681. MethodInfoMapTy MethodInfoMap;
  682. typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
  683. /// VTableThunks - The thunks by vtable index in the vtable currently being
  684. /// built.
  685. VTableThunksMapTy VTableThunks;
  686. typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
  687. typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
  688. /// Thunks - A map that contains all the thunks needed for all methods in the
  689. /// most derived class for which the vtable is currently being built.
  690. ThunksMapTy Thunks;
  691. /// AddThunk - Add a thunk for the given method.
  692. void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
  693. /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
  694. /// part of the vtable we're currently building.
  695. void ComputeThisAdjustments();
  696. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  697. /// PrimaryVirtualBases - All known virtual bases who are a primary base of
  698. /// some other base.
  699. VisitedVirtualBasesSetTy PrimaryVirtualBases;
  700. /// ComputeReturnAdjustment - Compute the return adjustment given a return
  701. /// adjustment base offset.
  702. ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
  703. /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
  704. /// the 'this' pointer from the base subobject to the derived subobject.
  705. BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
  706. BaseSubobject Derived) const;
  707. /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
  708. /// given virtual member function, its offset in the layout class and its
  709. /// final overrider.
  710. ThisAdjustment
  711. ComputeThisAdjustment(const CXXMethodDecl *MD,
  712. CharUnits BaseOffsetInLayoutClass,
  713. FinalOverriders::OverriderInfo Overrider);
  714. /// AddMethod - Add a single virtual member function to the vtable
  715. /// components vector.
  716. void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
  717. /// IsOverriderUsed - Returns whether the overrider will ever be used in this
  718. /// part of the vtable.
  719. ///
  720. /// Itanium C++ ABI 2.5.2:
  721. ///
  722. /// struct A { virtual void f(); };
  723. /// struct B : virtual public A { int i; };
  724. /// struct C : virtual public A { int j; };
  725. /// struct D : public B, public C {};
  726. ///
  727. /// When B and C are declared, A is a primary base in each case, so although
  728. /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
  729. /// adjustment is required and no thunk is generated. However, inside D
  730. /// objects, A is no longer a primary base of C, so if we allowed calls to
  731. /// C::f() to use the copy of A's vtable in the C subobject, we would need
  732. /// to adjust this from C* to B::A*, which would require a third-party
  733. /// thunk. Since we require that a call to C::f() first convert to A*,
  734. /// C-in-D's copy of A's vtable is never referenced, so this is not
  735. /// necessary.
  736. bool IsOverriderUsed(const CXXMethodDecl *Overrider,
  737. CharUnits BaseOffsetInLayoutClass,
  738. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  739. CharUnits FirstBaseOffsetInLayoutClass) const;
  740. /// AddMethods - Add the methods of this base subobject and all its
  741. /// primary bases to the vtable components vector.
  742. void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
  743. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  744. CharUnits FirstBaseOffsetInLayoutClass,
  745. PrimaryBasesSetVectorTy &PrimaryBases);
  746. // LayoutVTable - Layout the vtable for the given base class, including its
  747. // secondary vtables and any vtables for virtual bases.
  748. void LayoutVTable();
  749. /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
  750. /// given base subobject, as well as all its secondary vtables.
  751. ///
  752. /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
  753. /// or a direct or indirect base of a virtual base.
  754. ///
  755. /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
  756. /// in the layout class.
  757. void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
  758. bool BaseIsMorallyVirtual,
  759. bool BaseIsVirtualInLayoutClass,
  760. CharUnits OffsetInLayoutClass);
  761. /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
  762. /// subobject.
  763. ///
  764. /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
  765. /// or a direct or indirect base of a virtual base.
  766. void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
  767. CharUnits OffsetInLayoutClass);
  768. /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
  769. /// class hierarchy.
  770. void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
  771. CharUnits OffsetInLayoutClass,
  772. VisitedVirtualBasesSetTy &VBases);
  773. /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
  774. /// given base (excluding any primary bases).
  775. void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
  776. VisitedVirtualBasesSetTy &VBases);
  777. /// isBuildingConstructionVTable - Return whether this vtable builder is
  778. /// building a construction vtable.
  779. bool isBuildingConstructorVTable() const {
  780. return MostDerivedClass != LayoutClass;
  781. }
  782. public:
  783. VTableBuilder(VTableContext &VTables, const CXXRecordDecl *MostDerivedClass,
  784. CharUnits MostDerivedClassOffset,
  785. bool MostDerivedClassIsVirtual, const
  786. CXXRecordDecl *LayoutClass)
  787. : VTables(VTables), MostDerivedClass(MostDerivedClass),
  788. MostDerivedClassOffset(MostDerivedClassOffset),
  789. MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
  790. LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
  791. Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
  792. LayoutVTable();
  793. if (Context.getLangOpts().DumpVTableLayouts)
  794. dumpLayout(llvm::errs());
  795. }
  796. uint64_t getNumThunks() const {
  797. return Thunks.size();
  798. }
  799. ThunksMapTy::const_iterator thunks_begin() const {
  800. return Thunks.begin();
  801. }
  802. ThunksMapTy::const_iterator thunks_end() const {
  803. return Thunks.end();
  804. }
  805. const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
  806. return VBaseOffsetOffsets;
  807. }
  808. const AddressPointsMapTy &getAddressPoints() const {
  809. return AddressPoints;
  810. }
  811. /// getNumVTableComponents - Return the number of components in the vtable
  812. /// currently built.
  813. uint64_t getNumVTableComponents() const {
  814. return Components.size();
  815. }
  816. const VTableComponent *vtable_component_begin() const {
  817. return Components.begin();
  818. }
  819. const VTableComponent *vtable_component_end() const {
  820. return Components.end();
  821. }
  822. AddressPointsMapTy::const_iterator address_points_begin() const {
  823. return AddressPoints.begin();
  824. }
  825. AddressPointsMapTy::const_iterator address_points_end() const {
  826. return AddressPoints.end();
  827. }
  828. VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
  829. return VTableThunks.begin();
  830. }
  831. VTableThunksMapTy::const_iterator vtable_thunks_end() const {
  832. return VTableThunks.end();
  833. }
  834. /// dumpLayout - Dump the vtable layout.
  835. void dumpLayout(raw_ostream&);
  836. };
  837. void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
  838. assert(!isBuildingConstructorVTable() &&
  839. "Can't add thunks for construction vtable");
  840. SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
  841. // Check if we have this thunk already.
  842. if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
  843. ThunksVector.end())
  844. return;
  845. ThunksVector.push_back(Thunk);
  846. }
  847. typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
  848. /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
  849. /// the overridden methods that the function decl overrides.
  850. static void
  851. ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
  852. OverriddenMethodsSetTy& OverriddenMethods) {
  853. assert(MD->isVirtual() && "Method is not virtual!");
  854. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  855. E = MD->end_overridden_methods(); I != E; ++I) {
  856. const CXXMethodDecl *OverriddenMD = *I;
  857. OverriddenMethods.insert(OverriddenMD);
  858. ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
  859. }
  860. }
  861. void VTableBuilder::ComputeThisAdjustments() {
  862. // Now go through the method info map and see if any of the methods need
  863. // 'this' pointer adjustments.
  864. for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
  865. E = MethodInfoMap.end(); I != E; ++I) {
  866. const CXXMethodDecl *MD = I->first;
  867. const MethodInfo &MethodInfo = I->second;
  868. // Ignore adjustments for unused function pointers.
  869. uint64_t VTableIndex = MethodInfo.VTableIndex;
  870. if (Components[VTableIndex].getKind() ==
  871. VTableComponent::CK_UnusedFunctionPointer)
  872. continue;
  873. // Get the final overrider for this method.
  874. FinalOverriders::OverriderInfo Overrider =
  875. Overriders.getOverrider(MD, MethodInfo.BaseOffset);
  876. // Check if we need an adjustment at all.
  877. if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
  878. // When a return thunk is needed by a derived class that overrides a
  879. // virtual base, gcc uses a virtual 'this' adjustment as well.
  880. // While the thunk itself might be needed by vtables in subclasses or
  881. // in construction vtables, there doesn't seem to be a reason for using
  882. // the thunk in this vtable. Still, we do so to match gcc.
  883. if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
  884. continue;
  885. }
  886. ThisAdjustment ThisAdjustment =
  887. ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
  888. if (ThisAdjustment.isEmpty())
  889. continue;
  890. // Add it.
  891. VTableThunks[VTableIndex].This = ThisAdjustment;
  892. if (isa<CXXDestructorDecl>(MD)) {
  893. // Add an adjustment for the deleting destructor as well.
  894. VTableThunks[VTableIndex + 1].This = ThisAdjustment;
  895. }
  896. }
  897. /// Clear the method info map.
  898. MethodInfoMap.clear();
  899. if (isBuildingConstructorVTable()) {
  900. // We don't need to store thunk information for construction vtables.
  901. return;
  902. }
  903. for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
  904. E = VTableThunks.end(); I != E; ++I) {
  905. const VTableComponent &Component = Components[I->first];
  906. const ThunkInfo &Thunk = I->second;
  907. const CXXMethodDecl *MD;
  908. switch (Component.getKind()) {
  909. default:
  910. llvm_unreachable("Unexpected vtable component kind!");
  911. case VTableComponent::CK_FunctionPointer:
  912. MD = Component.getFunctionDecl();
  913. break;
  914. case VTableComponent::CK_CompleteDtorPointer:
  915. MD = Component.getDestructorDecl();
  916. break;
  917. case VTableComponent::CK_DeletingDtorPointer:
  918. // We've already added the thunk when we saw the complete dtor pointer.
  919. continue;
  920. }
  921. if (MD->getParent() == MostDerivedClass)
  922. AddThunk(MD, Thunk);
  923. }
  924. }
  925. ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
  926. ReturnAdjustment Adjustment;
  927. if (!Offset.isEmpty()) {
  928. if (Offset.VirtualBase) {
  929. // Get the virtual base offset offset.
  930. if (Offset.DerivedClass == MostDerivedClass) {
  931. // We can get the offset offset directly from our map.
  932. Adjustment.VBaseOffsetOffset =
  933. VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
  934. } else {
  935. Adjustment.VBaseOffsetOffset =
  936. VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
  937. Offset.VirtualBase).getQuantity();
  938. }
  939. }
  940. Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
  941. }
  942. return Adjustment;
  943. }
  944. BaseOffset
  945. VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
  946. BaseSubobject Derived) const {
  947. const CXXRecordDecl *BaseRD = Base.getBase();
  948. const CXXRecordDecl *DerivedRD = Derived.getBase();
  949. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  950. /*RecordPaths=*/true, /*DetectVirtual=*/true);
  951. if (!const_cast<CXXRecordDecl *>(DerivedRD)->
  952. isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
  953. llvm_unreachable("Class must be derived from the passed in base class!");
  954. }
  955. // We have to go through all the paths, and see which one leads us to the
  956. // right base subobject.
  957. for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
  958. I != E; ++I) {
  959. BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
  960. CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
  961. if (Offset.VirtualBase) {
  962. // If we have a virtual base class, the non-virtual offset is relative
  963. // to the virtual base class offset.
  964. const ASTRecordLayout &LayoutClassLayout =
  965. Context.getASTRecordLayout(LayoutClass);
  966. /// Get the virtual base offset, relative to the most derived class
  967. /// layout.
  968. OffsetToBaseSubobject +=
  969. LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
  970. } else {
  971. // Otherwise, the non-virtual offset is relative to the derived class
  972. // offset.
  973. OffsetToBaseSubobject += Derived.getBaseOffset();
  974. }
  975. // Check if this path gives us the right base subobject.
  976. if (OffsetToBaseSubobject == Base.getBaseOffset()) {
  977. // Since we're going from the base class _to_ the derived class, we'll
  978. // invert the non-virtual offset here.
  979. Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
  980. return Offset;
  981. }
  982. }
  983. return BaseOffset();
  984. }
  985. ThisAdjustment
  986. VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
  987. CharUnits BaseOffsetInLayoutClass,
  988. FinalOverriders::OverriderInfo Overrider) {
  989. // Ignore adjustments for pure virtual member functions.
  990. if (Overrider.Method->isPure())
  991. return ThisAdjustment();
  992. BaseSubobject OverriddenBaseSubobject(MD->getParent(),
  993. BaseOffsetInLayoutClass);
  994. BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
  995. Overrider.Offset);
  996. // Compute the adjustment offset.
  997. BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
  998. OverriderBaseSubobject);
  999. if (Offset.isEmpty())
  1000. return ThisAdjustment();
  1001. ThisAdjustment Adjustment;
  1002. if (Offset.VirtualBase) {
  1003. // Get the vcall offset map for this virtual base.
  1004. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
  1005. if (VCallOffsets.empty()) {
  1006. // We don't have vcall offsets for this virtual base, go ahead and
  1007. // build them.
  1008. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
  1009. /*FinalOverriders=*/0,
  1010. BaseSubobject(Offset.VirtualBase,
  1011. CharUnits::Zero()),
  1012. /*BaseIsVirtual=*/true,
  1013. /*OffsetInLayoutClass=*/
  1014. CharUnits::Zero());
  1015. VCallOffsets = Builder.getVCallOffsets();
  1016. }
  1017. Adjustment.VCallOffsetOffset =
  1018. VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
  1019. }
  1020. // Set the non-virtual part of the adjustment.
  1021. Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
  1022. return Adjustment;
  1023. }
  1024. void
  1025. VTableBuilder::AddMethod(const CXXMethodDecl *MD,
  1026. ReturnAdjustment ReturnAdjustment) {
  1027. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1028. assert(ReturnAdjustment.isEmpty() &&
  1029. "Destructor can't have return adjustment!");
  1030. // Add both the complete destructor and the deleting destructor.
  1031. Components.push_back(VTableComponent::MakeCompleteDtor(DD));
  1032. Components.push_back(VTableComponent::MakeDeletingDtor(DD));
  1033. } else {
  1034. // Add the return adjustment if necessary.
  1035. if (!ReturnAdjustment.isEmpty())
  1036. VTableThunks[Components.size()].Return = ReturnAdjustment;
  1037. // Add the function.
  1038. Components.push_back(VTableComponent::MakeFunction(MD));
  1039. }
  1040. }
  1041. /// OverridesIndirectMethodInBase - Return whether the given member function
  1042. /// overrides any methods in the set of given bases.
  1043. /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
  1044. /// For example, if we have:
  1045. ///
  1046. /// struct A { virtual void f(); }
  1047. /// struct B : A { virtual void f(); }
  1048. /// struct C : B { virtual void f(); }
  1049. ///
  1050. /// OverridesIndirectMethodInBase will return true if given C::f as the method
  1051. /// and { A } as the set of bases.
  1052. static bool
  1053. OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
  1054. VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
  1055. if (Bases.count(MD->getParent()))
  1056. return true;
  1057. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  1058. E = MD->end_overridden_methods(); I != E; ++I) {
  1059. const CXXMethodDecl *OverriddenMD = *I;
  1060. // Check "indirect overriders".
  1061. if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
  1062. return true;
  1063. }
  1064. return false;
  1065. }
  1066. bool
  1067. VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
  1068. CharUnits BaseOffsetInLayoutClass,
  1069. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  1070. CharUnits FirstBaseOffsetInLayoutClass) const {
  1071. // If the base and the first base in the primary base chain have the same
  1072. // offsets, then this overrider will be used.
  1073. if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
  1074. return true;
  1075. // We know now that Base (or a direct or indirect base of it) is a primary
  1076. // base in part of the class hierarchy, but not a primary base in the most
  1077. // derived class.
  1078. // If the overrider is the first base in the primary base chain, we know
  1079. // that the overrider will be used.
  1080. if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
  1081. return true;
  1082. VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
  1083. const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
  1084. PrimaryBases.insert(RD);
  1085. // Now traverse the base chain, starting with the first base, until we find
  1086. // the base that is no longer a primary base.
  1087. while (true) {
  1088. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1089. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1090. if (!PrimaryBase)
  1091. break;
  1092. if (Layout.isPrimaryBaseVirtual()) {
  1093. assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
  1094. "Primary base should always be at offset 0!");
  1095. const ASTRecordLayout &LayoutClassLayout =
  1096. Context.getASTRecordLayout(LayoutClass);
  1097. // Now check if this is the primary base that is not a primary base in the
  1098. // most derived class.
  1099. if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
  1100. FirstBaseOffsetInLayoutClass) {
  1101. // We found it, stop walking the chain.
  1102. break;
  1103. }
  1104. } else {
  1105. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  1106. "Primary base should always be at offset 0!");
  1107. }
  1108. if (!PrimaryBases.insert(PrimaryBase))
  1109. llvm_unreachable("Found a duplicate primary base!");
  1110. RD = PrimaryBase;
  1111. }
  1112. // If the final overrider is an override of one of the primary bases,
  1113. // then we know that it will be used.
  1114. return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
  1115. }
  1116. /// FindNearestOverriddenMethod - Given a method, returns the overridden method
  1117. /// from the nearest base. Returns null if no method was found.
  1118. static const CXXMethodDecl *
  1119. FindNearestOverriddenMethod(const CXXMethodDecl *MD,
  1120. VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
  1121. OverriddenMethodsSetTy OverriddenMethods;
  1122. ComputeAllOverriddenMethods(MD, OverriddenMethods);
  1123. for (int I = Bases.size(), E = 0; I != E; --I) {
  1124. const CXXRecordDecl *PrimaryBase = Bases[I - 1];
  1125. // Now check the overriden methods.
  1126. for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
  1127. E = OverriddenMethods.end(); I != E; ++I) {
  1128. const CXXMethodDecl *OverriddenMD = *I;
  1129. // We found our overridden method.
  1130. if (OverriddenMD->getParent() == PrimaryBase)
  1131. return OverriddenMD;
  1132. }
  1133. }
  1134. return 0;
  1135. }
  1136. void
  1137. VTableBuilder::AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
  1138. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  1139. CharUnits FirstBaseOffsetInLayoutClass,
  1140. PrimaryBasesSetVectorTy &PrimaryBases) {
  1141. const CXXRecordDecl *RD = Base.getBase();
  1142. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1143. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  1144. CharUnits PrimaryBaseOffset;
  1145. CharUnits PrimaryBaseOffsetInLayoutClass;
  1146. if (Layout.isPrimaryBaseVirtual()) {
  1147. assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
  1148. "Primary vbase should have a zero offset!");
  1149. const ASTRecordLayout &MostDerivedClassLayout =
  1150. Context.getASTRecordLayout(MostDerivedClass);
  1151. PrimaryBaseOffset =
  1152. MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
  1153. const ASTRecordLayout &LayoutClassLayout =
  1154. Context.getASTRecordLayout(LayoutClass);
  1155. PrimaryBaseOffsetInLayoutClass =
  1156. LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
  1157. } else {
  1158. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  1159. "Primary base should have a zero offset!");
  1160. PrimaryBaseOffset = Base.getBaseOffset();
  1161. PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
  1162. }
  1163. AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
  1164. PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
  1165. FirstBaseOffsetInLayoutClass, PrimaryBases);
  1166. if (!PrimaryBases.insert(PrimaryBase))
  1167. llvm_unreachable("Found a duplicate primary base!");
  1168. }
  1169. // Now go through all virtual member functions and add them.
  1170. for (CXXRecordDecl::method_iterator I = RD->method_begin(),
  1171. E = RD->method_end(); I != E; ++I) {
  1172. const CXXMethodDecl *MD = *I;
  1173. if (!MD->isVirtual())
  1174. continue;
  1175. // Get the final overrider.
  1176. FinalOverriders::OverriderInfo Overrider =
  1177. Overriders.getOverrider(MD, Base.getBaseOffset());
  1178. // Check if this virtual member function overrides a method in a primary
  1179. // base. If this is the case, and the return type doesn't require adjustment
  1180. // then we can just use the member function from the primary base.
  1181. if (const CXXMethodDecl *OverriddenMD =
  1182. FindNearestOverriddenMethod(MD, PrimaryBases)) {
  1183. if (ComputeReturnAdjustmentBaseOffset(Context, MD,
  1184. OverriddenMD).isEmpty()) {
  1185. // Replace the method info of the overridden method with our own
  1186. // method.
  1187. assert(MethodInfoMap.count(OverriddenMD) &&
  1188. "Did not find the overridden method!");
  1189. MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
  1190. MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
  1191. OverriddenMethodInfo.VTableIndex);
  1192. assert(!MethodInfoMap.count(MD) &&
  1193. "Should not have method info for this method yet!");
  1194. MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
  1195. MethodInfoMap.erase(OverriddenMD);
  1196. // If the overridden method exists in a virtual base class or a direct
  1197. // or indirect base class of a virtual base class, we need to emit a
  1198. // thunk if we ever have a class hierarchy where the base class is not
  1199. // a primary base in the complete object.
  1200. if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
  1201. // Compute the this adjustment.
  1202. ThisAdjustment ThisAdjustment =
  1203. ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
  1204. Overrider);
  1205. if (ThisAdjustment.VCallOffsetOffset &&
  1206. Overrider.Method->getParent() == MostDerivedClass) {
  1207. // There's no return adjustment from OverriddenMD and MD,
  1208. // but that doesn't mean there isn't one between MD and
  1209. // the final overrider.
  1210. BaseOffset ReturnAdjustmentOffset =
  1211. ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
  1212. ReturnAdjustment ReturnAdjustment =
  1213. ComputeReturnAdjustment(ReturnAdjustmentOffset);
  1214. // This is a virtual thunk for the most derived class, add it.
  1215. AddThunk(Overrider.Method,
  1216. ThunkInfo(ThisAdjustment, ReturnAdjustment));
  1217. }
  1218. }
  1219. continue;
  1220. }
  1221. }
  1222. // Insert the method info for this method.
  1223. MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
  1224. Components.size());
  1225. assert(!MethodInfoMap.count(MD) &&
  1226. "Should not have method info for this method yet!");
  1227. MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
  1228. // Check if this overrider is going to be used.
  1229. const CXXMethodDecl *OverriderMD = Overrider.Method;
  1230. if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
  1231. FirstBaseInPrimaryBaseChain,
  1232. FirstBaseOffsetInLayoutClass)) {
  1233. Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
  1234. continue;
  1235. }
  1236. // Check if this overrider needs a return adjustment.
  1237. // We don't want to do this for pure virtual member functions.
  1238. BaseOffset ReturnAdjustmentOffset;
  1239. if (!OverriderMD->isPure()) {
  1240. ReturnAdjustmentOffset =
  1241. ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
  1242. }
  1243. ReturnAdjustment ReturnAdjustment =
  1244. ComputeReturnAdjustment(ReturnAdjustmentOffset);
  1245. AddMethod(Overrider.Method, ReturnAdjustment);
  1246. }
  1247. }
  1248. void VTableBuilder::LayoutVTable() {
  1249. LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
  1250. CharUnits::Zero()),
  1251. /*BaseIsMorallyVirtual=*/false,
  1252. MostDerivedClassIsVirtual,
  1253. MostDerivedClassOffset);
  1254. VisitedVirtualBasesSetTy VBases;
  1255. // Determine the primary virtual bases.
  1256. DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
  1257. VBases);
  1258. VBases.clear();
  1259. LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
  1260. // -fapple-kext adds an extra entry at end of vtbl.
  1261. bool IsAppleKext = Context.getLangOpts().AppleKext;
  1262. if (IsAppleKext)
  1263. Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
  1264. }
  1265. void
  1266. VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
  1267. bool BaseIsMorallyVirtual,
  1268. bool BaseIsVirtualInLayoutClass,
  1269. CharUnits OffsetInLayoutClass) {
  1270. assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
  1271. // Add vcall and vbase offsets for this vtable.
  1272. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
  1273. Base, BaseIsVirtualInLayoutClass,
  1274. OffsetInLayoutClass);
  1275. Components.append(Builder.components_begin(), Builder.components_end());
  1276. // Check if we need to add these vcall offsets.
  1277. if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
  1278. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
  1279. if (VCallOffsets.empty())
  1280. VCallOffsets = Builder.getVCallOffsets();
  1281. }
  1282. // If we're laying out the most derived class we want to keep track of the
  1283. // virtual base class offset offsets.
  1284. if (Base.getBase() == MostDerivedClass)
  1285. VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
  1286. // Add the offset to top.
  1287. CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
  1288. Components.push_back(
  1289. VTableComponent::MakeOffsetToTop(OffsetToTop));
  1290. // Next, add the RTTI.
  1291. Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
  1292. uint64_t AddressPoint = Components.size();
  1293. // Now go through all virtual member functions and add them.
  1294. PrimaryBasesSetVectorTy PrimaryBases;
  1295. AddMethods(Base, OffsetInLayoutClass,
  1296. Base.getBase(), OffsetInLayoutClass,
  1297. PrimaryBases);
  1298. // Compute 'this' pointer adjustments.
  1299. ComputeThisAdjustments();
  1300. // Add all address points.
  1301. const CXXRecordDecl *RD = Base.getBase();
  1302. while (true) {
  1303. AddressPoints.insert(std::make_pair(
  1304. BaseSubobject(RD, OffsetInLayoutClass),
  1305. AddressPoint));
  1306. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1307. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1308. if (!PrimaryBase)
  1309. break;
  1310. if (Layout.isPrimaryBaseVirtual()) {
  1311. // Check if this virtual primary base is a primary base in the layout
  1312. // class. If it's not, we don't want to add it.
  1313. const ASTRecordLayout &LayoutClassLayout =
  1314. Context.getASTRecordLayout(LayoutClass);
  1315. if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
  1316. OffsetInLayoutClass) {
  1317. // We don't want to add this class (or any of its primary bases).
  1318. break;
  1319. }
  1320. }
  1321. RD = PrimaryBase;
  1322. }
  1323. // Layout secondary vtables.
  1324. LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
  1325. }
  1326. void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
  1327. bool BaseIsMorallyVirtual,
  1328. CharUnits OffsetInLayoutClass) {
  1329. // Itanium C++ ABI 2.5.2:
  1330. // Following the primary virtual table of a derived class are secondary
  1331. // virtual tables for each of its proper base classes, except any primary
  1332. // base(s) with which it shares its primary virtual table.
  1333. const CXXRecordDecl *RD = Base.getBase();
  1334. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1335. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1336. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1337. E = RD->bases_end(); I != E; ++I) {
  1338. // Ignore virtual bases, we'll emit them later.
  1339. if (I->isVirtual())
  1340. continue;
  1341. const CXXRecordDecl *BaseDecl =
  1342. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1343. // Ignore bases that don't have a vtable.
  1344. if (!BaseDecl->isDynamicClass())
  1345. continue;
  1346. if (isBuildingConstructorVTable()) {
  1347. // Itanium C++ ABI 2.6.4:
  1348. // Some of the base class subobjects may not need construction virtual
  1349. // tables, which will therefore not be present in the construction
  1350. // virtual table group, even though the subobject virtual tables are
  1351. // present in the main virtual table group for the complete object.
  1352. if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
  1353. continue;
  1354. }
  1355. // Get the base offset of this base.
  1356. CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
  1357. CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
  1358. CharUnits BaseOffsetInLayoutClass =
  1359. OffsetInLayoutClass + RelativeBaseOffset;
  1360. // Don't emit a secondary vtable for a primary base. We might however want
  1361. // to emit secondary vtables for other bases of this base.
  1362. if (BaseDecl == PrimaryBase) {
  1363. LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
  1364. BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
  1365. continue;
  1366. }
  1367. // Layout the primary vtable (and any secondary vtables) for this base.
  1368. LayoutPrimaryAndSecondaryVTables(
  1369. BaseSubobject(BaseDecl, BaseOffset),
  1370. BaseIsMorallyVirtual,
  1371. /*BaseIsVirtualInLayoutClass=*/false,
  1372. BaseOffsetInLayoutClass);
  1373. }
  1374. }
  1375. void
  1376. VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
  1377. CharUnits OffsetInLayoutClass,
  1378. VisitedVirtualBasesSetTy &VBases) {
  1379. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1380. // Check if this base has a primary base.
  1381. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  1382. // Check if it's virtual.
  1383. if (Layout.isPrimaryBaseVirtual()) {
  1384. bool IsPrimaryVirtualBase = true;
  1385. if (isBuildingConstructorVTable()) {
  1386. // Check if the base is actually a primary base in the class we use for
  1387. // layout.
  1388. const ASTRecordLayout &LayoutClassLayout =
  1389. Context.getASTRecordLayout(LayoutClass);
  1390. CharUnits PrimaryBaseOffsetInLayoutClass =
  1391. LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
  1392. // We know that the base is not a primary base in the layout class if
  1393. // the base offsets are different.
  1394. if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
  1395. IsPrimaryVirtualBase = false;
  1396. }
  1397. if (IsPrimaryVirtualBase)
  1398. PrimaryVirtualBases.insert(PrimaryBase);
  1399. }
  1400. }
  1401. // Traverse bases, looking for more primary virtual bases.
  1402. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1403. E = RD->bases_end(); I != E; ++I) {
  1404. const CXXRecordDecl *BaseDecl =
  1405. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1406. CharUnits BaseOffsetInLayoutClass;
  1407. if (I->isVirtual()) {
  1408. if (!VBases.insert(BaseDecl))
  1409. continue;
  1410. const ASTRecordLayout &LayoutClassLayout =
  1411. Context.getASTRecordLayout(LayoutClass);
  1412. BaseOffsetInLayoutClass =
  1413. LayoutClassLayout.getVBaseClassOffset(BaseDecl);
  1414. } else {
  1415. BaseOffsetInLayoutClass =
  1416. OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
  1417. }
  1418. DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
  1419. }
  1420. }
  1421. void
  1422. VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
  1423. VisitedVirtualBasesSetTy &VBases) {
  1424. // Itanium C++ ABI 2.5.2:
  1425. // Then come the virtual base virtual tables, also in inheritance graph
  1426. // order, and again excluding primary bases (which share virtual tables with
  1427. // the classes for which they are primary).
  1428. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1429. E = RD->bases_end(); I != E; ++I) {
  1430. const CXXRecordDecl *BaseDecl =
  1431. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1432. // Check if this base needs a vtable. (If it's virtual, not a primary base
  1433. // of some other class, and we haven't visited it before).
  1434. if (I->isVirtual() && BaseDecl->isDynamicClass() &&
  1435. !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
  1436. const ASTRecordLayout &MostDerivedClassLayout =
  1437. Context.getASTRecordLayout(MostDerivedClass);
  1438. CharUnits BaseOffset =
  1439. MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
  1440. const ASTRecordLayout &LayoutClassLayout =
  1441. Context.getASTRecordLayout(LayoutClass);
  1442. CharUnits BaseOffsetInLayoutClass =
  1443. LayoutClassLayout.getVBaseClassOffset(BaseDecl);
  1444. LayoutPrimaryAndSecondaryVTables(
  1445. BaseSubobject(BaseDecl, BaseOffset),
  1446. /*BaseIsMorallyVirtual=*/true,
  1447. /*BaseIsVirtualInLayoutClass=*/true,
  1448. BaseOffsetInLayoutClass);
  1449. }
  1450. // We only need to check the base for virtual base vtables if it actually
  1451. // has virtual bases.
  1452. if (BaseDecl->getNumVBases())
  1453. LayoutVTablesForVirtualBases(BaseDecl, VBases);
  1454. }
  1455. }
  1456. /// dumpLayout - Dump the vtable layout.
  1457. void VTableBuilder::dumpLayout(raw_ostream& Out) {
  1458. if (isBuildingConstructorVTable()) {
  1459. Out << "Construction vtable for ('";
  1460. Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
  1461. Out << MostDerivedClassOffset.getQuantity() << ") in '";
  1462. Out << LayoutClass->getQualifiedNameAsString();
  1463. } else {
  1464. Out << "Vtable for '";
  1465. Out << MostDerivedClass->getQualifiedNameAsString();
  1466. }
  1467. Out << "' (" << Components.size() << " entries).\n";
  1468. // Iterate through the address points and insert them into a new map where
  1469. // they are keyed by the index and not the base object.
  1470. // Since an address point can be shared by multiple subobjects, we use an
  1471. // STL multimap.
  1472. std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
  1473. for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
  1474. E = AddressPoints.end(); I != E; ++I) {
  1475. const BaseSubobject& Base = I->first;
  1476. uint64_t Index = I->second;
  1477. AddressPointsByIndex.insert(std::make_pair(Index, Base));
  1478. }
  1479. for (unsigned I = 0, E = Components.size(); I != E; ++I) {
  1480. uint64_t Index = I;
  1481. Out << llvm::format("%4d | ", I);
  1482. const VTableComponent &Component = Components[I];
  1483. // Dump the component.
  1484. switch (Component.getKind()) {
  1485. case VTableComponent::CK_VCallOffset:
  1486. Out << "vcall_offset ("
  1487. << Component.getVCallOffset().getQuantity()
  1488. << ")";
  1489. break;
  1490. case VTableComponent::CK_VBaseOffset:
  1491. Out << "vbase_offset ("
  1492. << Component.getVBaseOffset().getQuantity()
  1493. << ")";
  1494. break;
  1495. case VTableComponent::CK_OffsetToTop:
  1496. Out << "offset_to_top ("
  1497. << Component.getOffsetToTop().getQuantity()
  1498. << ")";
  1499. break;
  1500. case VTableComponent::CK_RTTI:
  1501. Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
  1502. break;
  1503. case VTableComponent::CK_FunctionPointer: {
  1504. const CXXMethodDecl *MD = Component.getFunctionDecl();
  1505. std::string Str =
  1506. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1507. MD);
  1508. Out << Str;
  1509. if (MD->isPure())
  1510. Out << " [pure]";
  1511. if (MD->isDeleted())
  1512. Out << " [deleted]";
  1513. ThunkInfo Thunk = VTableThunks.lookup(I);
  1514. if (!Thunk.isEmpty()) {
  1515. // If this function pointer has a return adjustment, dump it.
  1516. if (!Thunk.Return.isEmpty()) {
  1517. Out << "\n [return adjustment: ";
  1518. Out << Thunk.Return.NonVirtual << " non-virtual";
  1519. if (Thunk.Return.VBaseOffsetOffset) {
  1520. Out << ", " << Thunk.Return.VBaseOffsetOffset;
  1521. Out << " vbase offset offset";
  1522. }
  1523. Out << ']';
  1524. }
  1525. // If this function pointer has a 'this' pointer adjustment, dump it.
  1526. if (!Thunk.This.isEmpty()) {
  1527. Out << "\n [this adjustment: ";
  1528. Out << Thunk.This.NonVirtual << " non-virtual";
  1529. if (Thunk.This.VCallOffsetOffset) {
  1530. Out << ", " << Thunk.This.VCallOffsetOffset;
  1531. Out << " vcall offset offset";
  1532. }
  1533. Out << ']';
  1534. }
  1535. }
  1536. break;
  1537. }
  1538. case VTableComponent::CK_CompleteDtorPointer:
  1539. case VTableComponent::CK_DeletingDtorPointer: {
  1540. bool IsComplete =
  1541. Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
  1542. const CXXDestructorDecl *DD = Component.getDestructorDecl();
  1543. Out << DD->getQualifiedNameAsString();
  1544. if (IsComplete)
  1545. Out << "() [complete]";
  1546. else
  1547. Out << "() [deleting]";
  1548. if (DD->isPure())
  1549. Out << " [pure]";
  1550. ThunkInfo Thunk = VTableThunks.lookup(I);
  1551. if (!Thunk.isEmpty()) {
  1552. // If this destructor has a 'this' pointer adjustment, dump it.
  1553. if (!Thunk.This.isEmpty()) {
  1554. Out << "\n [this adjustment: ";
  1555. Out << Thunk.This.NonVirtual << " non-virtual";
  1556. if (Thunk.This.VCallOffsetOffset) {
  1557. Out << ", " << Thunk.This.VCallOffsetOffset;
  1558. Out << " vcall offset offset";
  1559. }
  1560. Out << ']';
  1561. }
  1562. }
  1563. break;
  1564. }
  1565. case VTableComponent::CK_UnusedFunctionPointer: {
  1566. const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
  1567. std::string Str =
  1568. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1569. MD);
  1570. Out << "[unused] " << Str;
  1571. if (MD->isPure())
  1572. Out << " [pure]";
  1573. }
  1574. }
  1575. Out << '\n';
  1576. // Dump the next address point.
  1577. uint64_t NextIndex = Index + 1;
  1578. if (AddressPointsByIndex.count(NextIndex)) {
  1579. if (AddressPointsByIndex.count(NextIndex) == 1) {
  1580. const BaseSubobject &Base =
  1581. AddressPointsByIndex.find(NextIndex)->second;
  1582. Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
  1583. Out << ", " << Base.getBaseOffset().getQuantity();
  1584. Out << ") vtable address --\n";
  1585. } else {
  1586. CharUnits BaseOffset =
  1587. AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
  1588. // We store the class names in a set to get a stable order.
  1589. std::set<std::string> ClassNames;
  1590. for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
  1591. AddressPointsByIndex.lower_bound(NextIndex), E =
  1592. AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
  1593. assert(I->second.getBaseOffset() == BaseOffset &&
  1594. "Invalid base offset!");
  1595. const CXXRecordDecl *RD = I->second.getBase();
  1596. ClassNames.insert(RD->getQualifiedNameAsString());
  1597. }
  1598. for (std::set<std::string>::const_iterator I = ClassNames.begin(),
  1599. E = ClassNames.end(); I != E; ++I) {
  1600. Out << " -- (" << *I;
  1601. Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
  1602. }
  1603. }
  1604. }
  1605. }
  1606. Out << '\n';
  1607. if (isBuildingConstructorVTable())
  1608. return;
  1609. if (MostDerivedClass->getNumVBases()) {
  1610. // We store the virtual base class names and their offsets in a map to get
  1611. // a stable order.
  1612. std::map<std::string, CharUnits> ClassNamesAndOffsets;
  1613. for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
  1614. E = VBaseOffsetOffsets.end(); I != E; ++I) {
  1615. std::string ClassName = I->first->getQualifiedNameAsString();
  1616. CharUnits OffsetOffset = I->second;
  1617. ClassNamesAndOffsets.insert(
  1618. std::make_pair(ClassName, OffsetOffset));
  1619. }
  1620. Out << "Virtual base offset offsets for '";
  1621. Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
  1622. Out << ClassNamesAndOffsets.size();
  1623. Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
  1624. for (std::map<std::string, CharUnits>::const_iterator I =
  1625. ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
  1626. I != E; ++I)
  1627. Out << " " << I->first << " | " << I->second.getQuantity() << '\n';
  1628. Out << "\n";
  1629. }
  1630. if (!Thunks.empty()) {
  1631. // We store the method names in a map to get a stable order.
  1632. std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
  1633. for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
  1634. I != E; ++I) {
  1635. const CXXMethodDecl *MD = I->first;
  1636. std::string MethodName =
  1637. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1638. MD);
  1639. MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
  1640. }
  1641. for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
  1642. MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
  1643. I != E; ++I) {
  1644. const std::string &MethodName = I->first;
  1645. const CXXMethodDecl *MD = I->second;
  1646. ThunkInfoVectorTy ThunksVector = Thunks[MD];
  1647. std::sort(ThunksVector.begin(), ThunksVector.end());
  1648. Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
  1649. Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
  1650. for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
  1651. const ThunkInfo &Thunk = ThunksVector[I];
  1652. Out << llvm::format("%4d | ", I);
  1653. // If this function pointer has a return pointer adjustment, dump it.
  1654. if (!Thunk.Return.isEmpty()) {
  1655. Out << "return adjustment: " << Thunk.This.NonVirtual;
  1656. Out << " non-virtual";
  1657. if (Thunk.Return.VBaseOffsetOffset) {
  1658. Out << ", " << Thunk.Return.VBaseOffsetOffset;
  1659. Out << " vbase offset offset";
  1660. }
  1661. if (!Thunk.This.isEmpty())
  1662. Out << "\n ";
  1663. }
  1664. // If this function pointer has a 'this' pointer adjustment, dump it.
  1665. if (!Thunk.This.isEmpty()) {
  1666. Out << "this adjustment: ";
  1667. Out << Thunk.This.NonVirtual << " non-virtual";
  1668. if (Thunk.This.VCallOffsetOffset) {
  1669. Out << ", " << Thunk.This.VCallOffsetOffset;
  1670. Out << " vcall offset offset";
  1671. }
  1672. }
  1673. Out << '\n';
  1674. }
  1675. Out << '\n';
  1676. }
  1677. }
  1678. // Compute the vtable indices for all the member functions.
  1679. // Store them in a map keyed by the index so we'll get a sorted table.
  1680. std::map<uint64_t, std::string> IndicesMap;
  1681. for (CXXRecordDecl::method_iterator i = MostDerivedClass->method_begin(),
  1682. e = MostDerivedClass->method_end(); i != e; ++i) {
  1683. const CXXMethodDecl *MD = *i;
  1684. // We only want virtual member functions.
  1685. if (!MD->isVirtual())
  1686. continue;
  1687. std::string MethodName =
  1688. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1689. MD);
  1690. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1691. IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Complete))] =
  1692. MethodName + " [complete]";
  1693. IndicesMap[VTables.getMethodVTableIndex(GlobalDecl(DD, Dtor_Deleting))] =
  1694. MethodName + " [deleting]";
  1695. } else {
  1696. IndicesMap[VTables.getMethodVTableIndex(MD)] = MethodName;
  1697. }
  1698. }
  1699. // Print the vtable indices for all the member functions.
  1700. if (!IndicesMap.empty()) {
  1701. Out << "VTable indices for '";
  1702. Out << MostDerivedClass->getQualifiedNameAsString();
  1703. Out << "' (" << IndicesMap.size() << " entries).\n";
  1704. for (std::map<uint64_t, std::string>::const_iterator I = IndicesMap.begin(),
  1705. E = IndicesMap.end(); I != E; ++I) {
  1706. uint64_t VTableIndex = I->first;
  1707. const std::string &MethodName = I->second;
  1708. Out << llvm::format(" %4" PRIu64 " | ", VTableIndex) << MethodName
  1709. << '\n';
  1710. }
  1711. }
  1712. Out << '\n';
  1713. }
  1714. }
  1715. VTableLayout::VTableLayout(uint64_t NumVTableComponents,
  1716. const VTableComponent *VTableComponents,
  1717. uint64_t NumVTableThunks,
  1718. const VTableThunkTy *VTableThunks,
  1719. const AddressPointsMapTy &AddressPoints)
  1720. : NumVTableComponents(NumVTableComponents),
  1721. VTableComponents(new VTableComponent[NumVTableComponents]),
  1722. NumVTableThunks(NumVTableThunks),
  1723. VTableThunks(new VTableThunkTy[NumVTableThunks]),
  1724. AddressPoints(AddressPoints) {
  1725. std::copy(VTableComponents, VTableComponents+NumVTableComponents,
  1726. this->VTableComponents.get());
  1727. std::copy(VTableThunks, VTableThunks+NumVTableThunks,
  1728. this->VTableThunks.get());
  1729. }
  1730. VTableLayout::~VTableLayout() { }
  1731. VTableContext::~VTableContext() {
  1732. llvm::DeleteContainerSeconds(VTableLayouts);
  1733. }
  1734. static void
  1735. CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
  1736. VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
  1737. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1738. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1739. if (!PrimaryBase)
  1740. return;
  1741. CollectPrimaryBases(PrimaryBase, Context, PrimaryBases);
  1742. if (!PrimaryBases.insert(PrimaryBase))
  1743. llvm_unreachable("Found a duplicate primary base!");
  1744. }
  1745. void VTableContext::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
  1746. // Itanium C++ ABI 2.5.2:
  1747. // The order of the virtual function pointers in a virtual table is the
  1748. // order of declaration of the corresponding member functions in the class.
  1749. //
  1750. // There is an entry for any virtual function declared in a class,
  1751. // whether it is a new function or overrides a base class function,
  1752. // unless it overrides a function from the primary base, and conversion
  1753. // between their return types does not require an adjustment.
  1754. int64_t CurrentIndex = 0;
  1755. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1756. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1757. if (PrimaryBase) {
  1758. assert(PrimaryBase->isCompleteDefinition() &&
  1759. "Should have the definition decl of the primary base!");
  1760. // Since the record decl shares its vtable pointer with the primary base
  1761. // we need to start counting at the end of the primary base's vtable.
  1762. CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
  1763. }
  1764. // Collect all the primary bases, so we can check whether methods override
  1765. // a method from the base.
  1766. VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
  1767. CollectPrimaryBases(RD, Context, PrimaryBases);
  1768. const CXXDestructorDecl *ImplicitVirtualDtor = 0;
  1769. for (CXXRecordDecl::method_iterator i = RD->method_begin(),
  1770. e = RD->method_end(); i != e; ++i) {
  1771. const CXXMethodDecl *MD = *i;
  1772. // We only want virtual methods.
  1773. if (!MD->isVirtual())
  1774. continue;
  1775. // Check if this method overrides a method in the primary base.
  1776. if (const CXXMethodDecl *OverriddenMD =
  1777. FindNearestOverriddenMethod(MD, PrimaryBases)) {
  1778. // Check if converting from the return type of the method to the
  1779. // return type of the overridden method requires conversion.
  1780. if (ComputeReturnAdjustmentBaseOffset(Context, MD,
  1781. OverriddenMD).isEmpty()) {
  1782. // This index is shared between the index in the vtable of the primary
  1783. // base class.
  1784. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1785. const CXXDestructorDecl *OverriddenDD =
  1786. cast<CXXDestructorDecl>(OverriddenMD);
  1787. // Add both the complete and deleting entries.
  1788. MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
  1789. getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
  1790. MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
  1791. getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
  1792. } else {
  1793. MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
  1794. }
  1795. // We don't need to add an entry for this method.
  1796. continue;
  1797. }
  1798. }
  1799. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1800. if (MD->isImplicit()) {
  1801. assert(!ImplicitVirtualDtor &&
  1802. "Did already see an implicit virtual dtor!");
  1803. ImplicitVirtualDtor = DD;
  1804. continue;
  1805. }
  1806. // Add the complete dtor.
  1807. MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
  1808. // Add the deleting dtor.
  1809. MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
  1810. } else {
  1811. // Add the entry.
  1812. MethodVTableIndices[MD] = CurrentIndex++;
  1813. }
  1814. }
  1815. if (ImplicitVirtualDtor) {
  1816. // Itanium C++ ABI 2.5.2:
  1817. // If a class has an implicitly-defined virtual destructor,
  1818. // its entries come after the declared virtual function pointers.
  1819. // Add the complete dtor.
  1820. MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
  1821. CurrentIndex++;
  1822. // Add the deleting dtor.
  1823. MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
  1824. CurrentIndex++;
  1825. }
  1826. NumVirtualFunctionPointers[RD] = CurrentIndex;
  1827. }
  1828. uint64_t VTableContext::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
  1829. llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
  1830. NumVirtualFunctionPointers.find(RD);
  1831. if (I != NumVirtualFunctionPointers.end())
  1832. return I->second;
  1833. ComputeMethodVTableIndices(RD);
  1834. I = NumVirtualFunctionPointers.find(RD);
  1835. assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
  1836. return I->second;
  1837. }
  1838. uint64_t VTableContext::getMethodVTableIndex(GlobalDecl GD) {
  1839. MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
  1840. if (I != MethodVTableIndices.end())
  1841. return I->second;
  1842. const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  1843. ComputeMethodVTableIndices(RD);
  1844. I = MethodVTableIndices.find(GD);
  1845. assert(I != MethodVTableIndices.end() && "Did not find index!");
  1846. return I->second;
  1847. }
  1848. CharUnits
  1849. VTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
  1850. const CXXRecordDecl *VBase) {
  1851. ClassPairTy ClassPair(RD, VBase);
  1852. VirtualBaseClassOffsetOffsetsMapTy::iterator I =
  1853. VirtualBaseClassOffsetOffsets.find(ClassPair);
  1854. if (I != VirtualBaseClassOffsetOffsets.end())
  1855. return I->second;
  1856. VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
  1857. BaseSubobject(RD, CharUnits::Zero()),
  1858. /*BaseIsVirtual=*/false,
  1859. /*OffsetInLayoutClass=*/CharUnits::Zero());
  1860. for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
  1861. Builder.getVBaseOffsetOffsets().begin(),
  1862. E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
  1863. // Insert all types.
  1864. ClassPairTy ClassPair(RD, I->first);
  1865. VirtualBaseClassOffsetOffsets.insert(
  1866. std::make_pair(ClassPair, I->second));
  1867. }
  1868. I = VirtualBaseClassOffsetOffsets.find(ClassPair);
  1869. assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
  1870. return I->second;
  1871. }
  1872. static VTableLayout *CreateVTableLayout(const VTableBuilder &Builder) {
  1873. SmallVector<VTableLayout::VTableThunkTy, 1>
  1874. VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
  1875. std::sort(VTableThunks.begin(), VTableThunks.end());
  1876. return new VTableLayout(Builder.getNumVTableComponents(),
  1877. Builder.vtable_component_begin(),
  1878. VTableThunks.size(),
  1879. VTableThunks.data(),
  1880. Builder.getAddressPoints());
  1881. }
  1882. void VTableContext::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
  1883. const VTableLayout *&Entry = VTableLayouts[RD];
  1884. // Check if we've computed this information before.
  1885. if (Entry)
  1886. return;
  1887. VTableBuilder Builder(*this, RD, CharUnits::Zero(),
  1888. /*MostDerivedClassIsVirtual=*/0, RD);
  1889. Entry = CreateVTableLayout(Builder);
  1890. // Add the known thunks.
  1891. Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
  1892. // If we don't have the vbase information for this class, insert it.
  1893. // getVirtualBaseOffsetOffset will compute it separately without computing
  1894. // the rest of the vtable related information.
  1895. if (!RD->getNumVBases())
  1896. return;
  1897. const RecordType *VBaseRT =
  1898. RD->vbases_begin()->getType()->getAs<RecordType>();
  1899. const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
  1900. if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
  1901. return;
  1902. for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
  1903. Builder.getVBaseOffsetOffsets().begin(),
  1904. E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
  1905. // Insert all types.
  1906. ClassPairTy ClassPair(RD, I->first);
  1907. VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
  1908. }
  1909. }
  1910. VTableLayout *VTableContext::createConstructionVTableLayout(
  1911. const CXXRecordDecl *MostDerivedClass,
  1912. CharUnits MostDerivedClassOffset,
  1913. bool MostDerivedClassIsVirtual,
  1914. const CXXRecordDecl *LayoutClass) {
  1915. VTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
  1916. MostDerivedClassIsVirtual, LayoutClass);
  1917. return CreateVTableLayout(Builder);
  1918. }