VTableBuilder.cpp 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754
  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/ASTDiagnostic.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/RecordLayout.h"
  18. #include "clang/Basic/TargetInfo.h"
  19. #include "llvm/ADT/SetOperations.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/Support/Format.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. #include <algorithm>
  24. #include <cstdio>
  25. using namespace clang;
  26. #define DUMP_OVERRIDERS 0
  27. namespace {
  28. /// BaseOffset - Represents an offset from a derived class to a direct or
  29. /// indirect base class.
  30. struct BaseOffset {
  31. /// DerivedClass - The derived class.
  32. const CXXRecordDecl *DerivedClass;
  33. /// VirtualBase - If the path from the derived class to the base class
  34. /// involves virtual base classes, this holds the declaration of the last
  35. /// virtual base in this path (i.e. closest to the base class).
  36. const CXXRecordDecl *VirtualBase;
  37. /// NonVirtualOffset - The offset from the derived class to the base class.
  38. /// (Or the offset from the virtual base class to the base class, if the
  39. /// path from the derived class to the base class involves a virtual base
  40. /// class.
  41. CharUnits NonVirtualOffset;
  42. BaseOffset() : DerivedClass(nullptr), VirtualBase(nullptr),
  43. NonVirtualOffset(CharUnits::Zero()) { }
  44. BaseOffset(const CXXRecordDecl *DerivedClass,
  45. const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
  46. : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
  47. NonVirtualOffset(NonVirtualOffset) { }
  48. bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
  49. };
  50. /// FinalOverriders - Contains the final overrider member functions for all
  51. /// member functions in the base subobjects of a class.
  52. class FinalOverriders {
  53. public:
  54. /// OverriderInfo - Information about a final overrider.
  55. struct OverriderInfo {
  56. /// Method - The method decl of the overrider.
  57. const CXXMethodDecl *Method;
  58. /// VirtualBase - The virtual base class subobject of this overrider.
  59. /// Note that this records the closest derived virtual base class subobject.
  60. const CXXRecordDecl *VirtualBase;
  61. /// Offset - the base offset of the overrider's parent in the layout class.
  62. CharUnits Offset;
  63. OverriderInfo() : Method(nullptr), VirtualBase(nullptr),
  64. Offset(CharUnits::Zero()) { }
  65. };
  66. private:
  67. /// MostDerivedClass - The most derived class for which the final overriders
  68. /// are stored.
  69. const CXXRecordDecl *MostDerivedClass;
  70. /// MostDerivedClassOffset - If we're building final overriders for a
  71. /// construction vtable, this holds the offset from the layout class to the
  72. /// most derived class.
  73. const CharUnits MostDerivedClassOffset;
  74. /// LayoutClass - The class we're using for layout information. Will be
  75. /// different than the most derived class if the final overriders are for a
  76. /// construction vtable.
  77. const CXXRecordDecl *LayoutClass;
  78. ASTContext &Context;
  79. /// MostDerivedClassLayout - the AST record layout of the most derived class.
  80. const ASTRecordLayout &MostDerivedClassLayout;
  81. /// MethodBaseOffsetPairTy - Uniquely identifies a member function
  82. /// in a base subobject.
  83. typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
  84. typedef llvm::DenseMap<MethodBaseOffsetPairTy,
  85. OverriderInfo> OverridersMapTy;
  86. /// OverridersMap - The final overriders for all virtual member functions of
  87. /// all the base subobjects of the most derived class.
  88. OverridersMapTy OverridersMap;
  89. /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
  90. /// as a record decl and a subobject number) and its offsets in the most
  91. /// derived class as well as the layout class.
  92. typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
  93. CharUnits> SubobjectOffsetMapTy;
  94. typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
  95. /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
  96. /// given base.
  97. void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
  98. CharUnits OffsetInLayoutClass,
  99. SubobjectOffsetMapTy &SubobjectOffsets,
  100. SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
  101. SubobjectCountMapTy &SubobjectCounts);
  102. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  103. /// dump - dump the final overriders for a base subobject, and all its direct
  104. /// and indirect base subobjects.
  105. void dump(raw_ostream &Out, BaseSubobject Base,
  106. VisitedVirtualBasesSetTy& VisitedVirtualBases);
  107. public:
  108. FinalOverriders(const CXXRecordDecl *MostDerivedClass,
  109. CharUnits MostDerivedClassOffset,
  110. const CXXRecordDecl *LayoutClass);
  111. /// getOverrider - Get the final overrider for the given method declaration in
  112. /// the subobject with the given base offset.
  113. OverriderInfo getOverrider(const CXXMethodDecl *MD,
  114. CharUnits BaseOffset) const {
  115. assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
  116. "Did not find overrider!");
  117. return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
  118. }
  119. /// dump - dump the final overriders.
  120. void dump() {
  121. VisitedVirtualBasesSetTy VisitedVirtualBases;
  122. dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
  123. VisitedVirtualBases);
  124. }
  125. };
  126. FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
  127. CharUnits MostDerivedClassOffset,
  128. const CXXRecordDecl *LayoutClass)
  129. : MostDerivedClass(MostDerivedClass),
  130. MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
  131. Context(MostDerivedClass->getASTContext()),
  132. MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
  133. // Compute base offsets.
  134. SubobjectOffsetMapTy SubobjectOffsets;
  135. SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
  136. SubobjectCountMapTy SubobjectCounts;
  137. ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
  138. /*IsVirtual=*/false,
  139. MostDerivedClassOffset,
  140. SubobjectOffsets, SubobjectLayoutClassOffsets,
  141. SubobjectCounts);
  142. // Get the final overriders.
  143. CXXFinalOverriderMap FinalOverriders;
  144. MostDerivedClass->getFinalOverriders(FinalOverriders);
  145. for (const auto &Overrider : FinalOverriders) {
  146. const CXXMethodDecl *MD = Overrider.first;
  147. const OverridingMethods &Methods = Overrider.second;
  148. for (const auto &M : Methods) {
  149. unsigned SubobjectNumber = M.first;
  150. assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
  151. SubobjectNumber)) &&
  152. "Did not find subobject offset!");
  153. CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
  154. SubobjectNumber)];
  155. assert(M.second.size() == 1 && "Final overrider is not unique!");
  156. const UniqueVirtualMethod &Method = M.second.front();
  157. const CXXRecordDecl *OverriderRD = Method.Method->getParent();
  158. assert(SubobjectLayoutClassOffsets.count(
  159. std::make_pair(OverriderRD, Method.Subobject))
  160. && "Did not find subobject offset!");
  161. CharUnits OverriderOffset =
  162. SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
  163. Method.Subobject)];
  164. OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
  165. assert(!Overrider.Method && "Overrider should not exist yet!");
  166. Overrider.Offset = OverriderOffset;
  167. Overrider.Method = Method.Method;
  168. Overrider.VirtualBase = Method.InVirtualSubobject;
  169. }
  170. }
  171. #if DUMP_OVERRIDERS
  172. // And dump them (for now).
  173. dump();
  174. #endif
  175. }
  176. static BaseOffset ComputeBaseOffset(const ASTContext &Context,
  177. const CXXRecordDecl *DerivedRD,
  178. const CXXBasePath &Path) {
  179. CharUnits NonVirtualOffset = CharUnits::Zero();
  180. unsigned NonVirtualStart = 0;
  181. const CXXRecordDecl *VirtualBase = nullptr;
  182. // First, look for the virtual base class.
  183. for (int I = Path.size(), E = 0; I != E; --I) {
  184. const CXXBasePathElement &Element = Path[I - 1];
  185. if (Element.Base->isVirtual()) {
  186. NonVirtualStart = I;
  187. QualType VBaseType = Element.Base->getType();
  188. VirtualBase = VBaseType->getAsCXXRecordDecl();
  189. break;
  190. }
  191. }
  192. // Now compute the non-virtual offset.
  193. for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
  194. const CXXBasePathElement &Element = Path[I];
  195. // Check the base class offset.
  196. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
  197. const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
  198. NonVirtualOffset += Layout.getBaseClassOffset(Base);
  199. }
  200. // FIXME: This should probably use CharUnits or something. Maybe we should
  201. // even change the base offsets in ASTRecordLayout to be specified in
  202. // CharUnits.
  203. return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
  204. }
  205. static BaseOffset ComputeBaseOffset(const ASTContext &Context,
  206. const CXXRecordDecl *BaseRD,
  207. const CXXRecordDecl *DerivedRD) {
  208. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  209. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  210. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  211. llvm_unreachable("Class must be derived from the passed in base class!");
  212. return ComputeBaseOffset(Context, DerivedRD, Paths.front());
  213. }
  214. static BaseOffset
  215. ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
  216. const CXXMethodDecl *DerivedMD,
  217. const CXXMethodDecl *BaseMD) {
  218. const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
  219. const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
  220. // Canonicalize the return types.
  221. CanQualType CanDerivedReturnType =
  222. Context.getCanonicalType(DerivedFT->getReturnType());
  223. CanQualType CanBaseReturnType =
  224. Context.getCanonicalType(BaseFT->getReturnType());
  225. assert(CanDerivedReturnType->getTypeClass() ==
  226. CanBaseReturnType->getTypeClass() &&
  227. "Types must have same type class!");
  228. if (CanDerivedReturnType == CanBaseReturnType) {
  229. // No adjustment needed.
  230. return BaseOffset();
  231. }
  232. if (isa<ReferenceType>(CanDerivedReturnType)) {
  233. CanDerivedReturnType =
  234. CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
  235. CanBaseReturnType =
  236. CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
  237. } else if (isa<PointerType>(CanDerivedReturnType)) {
  238. CanDerivedReturnType =
  239. CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
  240. CanBaseReturnType =
  241. CanBaseReturnType->getAs<PointerType>()->getPointeeType();
  242. } else {
  243. llvm_unreachable("Unexpected return type!");
  244. }
  245. // We need to compare unqualified types here; consider
  246. // const T *Base::foo();
  247. // T *Derived::foo();
  248. if (CanDerivedReturnType.getUnqualifiedType() ==
  249. CanBaseReturnType.getUnqualifiedType()) {
  250. // No adjustment needed.
  251. return BaseOffset();
  252. }
  253. const CXXRecordDecl *DerivedRD =
  254. cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
  255. const CXXRecordDecl *BaseRD =
  256. cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
  257. return ComputeBaseOffset(Context, BaseRD, DerivedRD);
  258. }
  259. void
  260. FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
  261. CharUnits OffsetInLayoutClass,
  262. SubobjectOffsetMapTy &SubobjectOffsets,
  263. SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
  264. SubobjectCountMapTy &SubobjectCounts) {
  265. const CXXRecordDecl *RD = Base.getBase();
  266. unsigned SubobjectNumber = 0;
  267. if (!IsVirtual)
  268. SubobjectNumber = ++SubobjectCounts[RD];
  269. // Set up the subobject to offset mapping.
  270. assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
  271. && "Subobject offset already exists!");
  272. assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
  273. && "Subobject offset already exists!");
  274. SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
  275. SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
  276. OffsetInLayoutClass;
  277. // Traverse our bases.
  278. for (const auto &B : RD->bases()) {
  279. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  280. CharUnits BaseOffset;
  281. CharUnits BaseOffsetInLayoutClass;
  282. if (B.isVirtual()) {
  283. // Check if we've visited this virtual base before.
  284. if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
  285. continue;
  286. const ASTRecordLayout &LayoutClassLayout =
  287. Context.getASTRecordLayout(LayoutClass);
  288. BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
  289. BaseOffsetInLayoutClass =
  290. LayoutClassLayout.getVBaseClassOffset(BaseDecl);
  291. } else {
  292. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  293. CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
  294. BaseOffset = Base.getBaseOffset() + Offset;
  295. BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
  296. }
  297. ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
  298. B.isVirtual(), BaseOffsetInLayoutClass,
  299. SubobjectOffsets, SubobjectLayoutClassOffsets,
  300. SubobjectCounts);
  301. }
  302. }
  303. void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
  304. VisitedVirtualBasesSetTy &VisitedVirtualBases) {
  305. const CXXRecordDecl *RD = Base.getBase();
  306. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  307. for (const auto &B : RD->bases()) {
  308. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  309. // Ignore bases that don't have any virtual member functions.
  310. if (!BaseDecl->isPolymorphic())
  311. continue;
  312. CharUnits BaseOffset;
  313. if (B.isVirtual()) {
  314. if (!VisitedVirtualBases.insert(BaseDecl).second) {
  315. // We've visited this base before.
  316. continue;
  317. }
  318. BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
  319. } else {
  320. BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
  321. }
  322. dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
  323. }
  324. Out << "Final overriders for (";
  325. RD->printQualifiedName(Out);
  326. Out << ", ";
  327. Out << Base.getBaseOffset().getQuantity() << ")\n";
  328. // Now dump the overriders for this base subobject.
  329. for (const auto *MD : RD->methods()) {
  330. if (!MD->isVirtual())
  331. continue;
  332. MD = MD->getCanonicalDecl();
  333. OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
  334. Out << " ";
  335. MD->printQualifiedName(Out);
  336. Out << " - (";
  337. Overrider.Method->printQualifiedName(Out);
  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. Offset.VirtualBase->printQualifiedName(Out);
  346. Out << " vbase, ";
  347. }
  348. Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
  349. }
  350. Out << "\n";
  351. }
  352. }
  353. /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
  354. struct VCallOffsetMap {
  355. typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
  356. /// Offsets - Keeps track of methods and their offsets.
  357. // FIXME: This should be a real map and not a vector.
  358. SmallVector<MethodAndOffsetPairTy, 16> Offsets;
  359. /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
  360. /// can share the same vcall offset.
  361. static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
  362. const CXXMethodDecl *RHS);
  363. public:
  364. /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
  365. /// add was successful, or false if there was already a member function with
  366. /// the same signature in the map.
  367. bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
  368. /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
  369. /// vtable address point) for the given virtual member function.
  370. CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
  371. // empty - Return whether the offset map is empty or not.
  372. bool empty() const { return Offsets.empty(); }
  373. };
  374. static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
  375. const CXXMethodDecl *RHS) {
  376. const FunctionProtoType *LT =
  377. cast<FunctionProtoType>(LHS->getType().getCanonicalType());
  378. const FunctionProtoType *RT =
  379. cast<FunctionProtoType>(RHS->getType().getCanonicalType());
  380. // Fast-path matches in the canonical types.
  381. if (LT == RT) return true;
  382. // Force the signatures to match. We can't rely on the overrides
  383. // list here because there isn't necessarily an inheritance
  384. // relationship between the two methods.
  385. if (LT->getTypeQuals() != RT->getTypeQuals())
  386. return false;
  387. return LT->getParamTypes() == RT->getParamTypes();
  388. }
  389. bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
  390. const CXXMethodDecl *RHS) {
  391. assert(LHS->isVirtual() && "LHS must be virtual!");
  392. assert(RHS->isVirtual() && "LHS must be virtual!");
  393. // A destructor can share a vcall offset with another destructor.
  394. if (isa<CXXDestructorDecl>(LHS))
  395. return isa<CXXDestructorDecl>(RHS);
  396. // FIXME: We need to check more things here.
  397. // The methods must have the same name.
  398. DeclarationName LHSName = LHS->getDeclName();
  399. DeclarationName RHSName = RHS->getDeclName();
  400. if (LHSName != RHSName)
  401. return false;
  402. // And the same signatures.
  403. return HasSameVirtualSignature(LHS, RHS);
  404. }
  405. bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
  406. CharUnits OffsetOffset) {
  407. // Check if we can reuse an offset.
  408. for (const auto &OffsetPair : Offsets) {
  409. if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
  410. return false;
  411. }
  412. // Add the offset.
  413. Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
  414. return true;
  415. }
  416. CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
  417. // Look for an offset.
  418. for (const auto &OffsetPair : Offsets) {
  419. if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
  420. return OffsetPair.second;
  421. }
  422. llvm_unreachable("Should always find a vcall offset offset!");
  423. }
  424. /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
  425. class VCallAndVBaseOffsetBuilder {
  426. public:
  427. typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
  428. VBaseOffsetOffsetsMapTy;
  429. private:
  430. /// MostDerivedClass - The most derived class for which we're building vcall
  431. /// and vbase offsets.
  432. const CXXRecordDecl *MostDerivedClass;
  433. /// LayoutClass - The class we're using for layout information. Will be
  434. /// different than the most derived class if we're building a construction
  435. /// vtable.
  436. const CXXRecordDecl *LayoutClass;
  437. /// Context - The ASTContext which we will use for layout information.
  438. ASTContext &Context;
  439. /// Components - vcall and vbase offset components
  440. typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
  441. VTableComponentVectorTy Components;
  442. /// VisitedVirtualBases - Visited virtual bases.
  443. llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
  444. /// VCallOffsets - Keeps track of vcall offsets.
  445. VCallOffsetMap VCallOffsets;
  446. /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
  447. /// relative to the address point.
  448. VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
  449. /// FinalOverriders - The final overriders of the most derived class.
  450. /// (Can be null when we're not building a vtable of the most derived class).
  451. const FinalOverriders *Overriders;
  452. /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
  453. /// given base subobject.
  454. void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
  455. CharUnits RealBaseOffset);
  456. /// AddVCallOffsets - Add vcall offsets for the given base subobject.
  457. void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
  458. /// AddVBaseOffsets - Add vbase offsets for the given class.
  459. void AddVBaseOffsets(const CXXRecordDecl *Base,
  460. CharUnits OffsetInLayoutClass);
  461. /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
  462. /// chars, relative to the vtable address point.
  463. CharUnits getCurrentOffsetOffset() const;
  464. public:
  465. VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
  466. const CXXRecordDecl *LayoutClass,
  467. const FinalOverriders *Overriders,
  468. BaseSubobject Base, bool BaseIsVirtual,
  469. CharUnits OffsetInLayoutClass)
  470. : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
  471. Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
  472. // Add vcall and vbase offsets.
  473. AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
  474. }
  475. /// Methods for iterating over the components.
  476. typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
  477. const_iterator components_begin() const { return Components.rbegin(); }
  478. const_iterator components_end() const { return Components.rend(); }
  479. const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
  480. const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
  481. return VBaseOffsetOffsets;
  482. }
  483. };
  484. void
  485. VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
  486. bool BaseIsVirtual,
  487. CharUnits RealBaseOffset) {
  488. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
  489. // Itanium C++ ABI 2.5.2:
  490. // ..in classes sharing a virtual table with a primary base class, the vcall
  491. // and vbase offsets added by the derived class all come before the vcall
  492. // and vbase offsets required by the base class, so that the latter may be
  493. // laid out as required by the base class without regard to additions from
  494. // the derived class(es).
  495. // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
  496. // emit them for the primary base first).
  497. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  498. bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
  499. CharUnits PrimaryBaseOffset;
  500. // Get the base offset of the primary base.
  501. if (PrimaryBaseIsVirtual) {
  502. assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
  503. "Primary vbase should have a zero offset!");
  504. const ASTRecordLayout &MostDerivedClassLayout =
  505. Context.getASTRecordLayout(MostDerivedClass);
  506. PrimaryBaseOffset =
  507. MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
  508. } else {
  509. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  510. "Primary base should have a zero offset!");
  511. PrimaryBaseOffset = Base.getBaseOffset();
  512. }
  513. AddVCallAndVBaseOffsets(
  514. BaseSubobject(PrimaryBase,PrimaryBaseOffset),
  515. PrimaryBaseIsVirtual, RealBaseOffset);
  516. }
  517. AddVBaseOffsets(Base.getBase(), RealBaseOffset);
  518. // We only want to add vcall offsets for virtual bases.
  519. if (BaseIsVirtual)
  520. AddVCallOffsets(Base, RealBaseOffset);
  521. }
  522. CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
  523. // OffsetIndex is the index of this vcall or vbase offset, relative to the
  524. // vtable address point. (We subtract 3 to account for the information just
  525. // above the address point, the RTTI info, the offset to top, and the
  526. // vcall offset itself).
  527. int64_t OffsetIndex = -(int64_t)(3 + Components.size());
  528. CharUnits PointerWidth =
  529. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  530. CharUnits OffsetOffset = PointerWidth * OffsetIndex;
  531. return OffsetOffset;
  532. }
  533. void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
  534. CharUnits VBaseOffset) {
  535. const CXXRecordDecl *RD = Base.getBase();
  536. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  537. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  538. // Handle the primary base first.
  539. // We only want to add vcall offsets if the base is non-virtual; a virtual
  540. // primary base will have its vcall and vbase offsets emitted already.
  541. if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
  542. // Get the base offset of the primary base.
  543. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  544. "Primary base should have a zero offset!");
  545. AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
  546. VBaseOffset);
  547. }
  548. // Add the vcall offsets.
  549. for (const auto *MD : RD->methods()) {
  550. if (!MD->isVirtual())
  551. continue;
  552. MD = MD->getCanonicalDecl();
  553. CharUnits OffsetOffset = getCurrentOffsetOffset();
  554. // Don't add a vcall offset if we already have one for this member function
  555. // signature.
  556. if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
  557. continue;
  558. CharUnits Offset = CharUnits::Zero();
  559. if (Overriders) {
  560. // Get the final overrider.
  561. FinalOverriders::OverriderInfo Overrider =
  562. Overriders->getOverrider(MD, Base.getBaseOffset());
  563. /// The vcall offset is the offset from the virtual base to the object
  564. /// where the function was overridden.
  565. Offset = Overrider.Offset - VBaseOffset;
  566. }
  567. Components.push_back(
  568. VTableComponent::MakeVCallOffset(Offset));
  569. }
  570. // And iterate over all non-virtual bases (ignoring the primary base).
  571. for (const auto &B : RD->bases()) {
  572. if (B.isVirtual())
  573. continue;
  574. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  575. if (BaseDecl == PrimaryBase)
  576. continue;
  577. // Get the base offset of this base.
  578. CharUnits BaseOffset = Base.getBaseOffset() +
  579. Layout.getBaseClassOffset(BaseDecl);
  580. AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
  581. VBaseOffset);
  582. }
  583. }
  584. void
  585. VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
  586. CharUnits OffsetInLayoutClass) {
  587. const ASTRecordLayout &LayoutClassLayout =
  588. Context.getASTRecordLayout(LayoutClass);
  589. // Add vbase offsets.
  590. for (const auto &B : RD->bases()) {
  591. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  592. // Check if this is a virtual base that we haven't visited before.
  593. if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) {
  594. CharUnits Offset =
  595. LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
  596. // Add the vbase offset offset.
  597. assert(!VBaseOffsetOffsets.count(BaseDecl) &&
  598. "vbase offset offset already exists!");
  599. CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
  600. VBaseOffsetOffsets.insert(
  601. std::make_pair(BaseDecl, VBaseOffsetOffset));
  602. Components.push_back(
  603. VTableComponent::MakeVBaseOffset(Offset));
  604. }
  605. // Check the base class looking for more vbase offsets.
  606. AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
  607. }
  608. }
  609. /// ItaniumVTableBuilder - Class for building vtable layout information.
  610. class ItaniumVTableBuilder {
  611. public:
  612. /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
  613. /// primary bases.
  614. typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
  615. PrimaryBasesSetVectorTy;
  616. typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
  617. VBaseOffsetOffsetsMapTy;
  618. typedef llvm::DenseMap<BaseSubobject, uint64_t>
  619. AddressPointsMapTy;
  620. typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
  621. private:
  622. /// VTables - Global vtable information.
  623. ItaniumVTableContext &VTables;
  624. /// MostDerivedClass - The most derived class for which we're building this
  625. /// vtable.
  626. const CXXRecordDecl *MostDerivedClass;
  627. /// MostDerivedClassOffset - If we're building a construction vtable, this
  628. /// holds the offset from the layout class to the most derived class.
  629. const CharUnits MostDerivedClassOffset;
  630. /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
  631. /// base. (This only makes sense when building a construction vtable).
  632. bool MostDerivedClassIsVirtual;
  633. /// LayoutClass - The class we're using for layout information. Will be
  634. /// different than the most derived class if we're building a construction
  635. /// vtable.
  636. const CXXRecordDecl *LayoutClass;
  637. /// Context - The ASTContext which we will use for layout information.
  638. ASTContext &Context;
  639. /// FinalOverriders - The final overriders of the most derived class.
  640. const FinalOverriders Overriders;
  641. /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
  642. /// bases in this vtable.
  643. llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
  644. /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
  645. /// the most derived class.
  646. VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
  647. /// Components - The components of the vtable being built.
  648. SmallVector<VTableComponent, 64> Components;
  649. /// AddressPoints - Address points for the vtable being built.
  650. AddressPointsMapTy AddressPoints;
  651. /// MethodInfo - Contains information about a method in a vtable.
  652. /// (Used for computing 'this' pointer adjustment thunks.
  653. struct MethodInfo {
  654. /// BaseOffset - The base offset of this method.
  655. const CharUnits BaseOffset;
  656. /// BaseOffsetInLayoutClass - The base offset in the layout class of this
  657. /// method.
  658. const CharUnits BaseOffsetInLayoutClass;
  659. /// VTableIndex - The index in the vtable that this method has.
  660. /// (For destructors, this is the index of the complete destructor).
  661. const uint64_t VTableIndex;
  662. MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
  663. uint64_t VTableIndex)
  664. : BaseOffset(BaseOffset),
  665. BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
  666. VTableIndex(VTableIndex) { }
  667. MethodInfo()
  668. : BaseOffset(CharUnits::Zero()),
  669. BaseOffsetInLayoutClass(CharUnits::Zero()),
  670. VTableIndex(0) { }
  671. };
  672. typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
  673. /// MethodInfoMap - The information for all methods in the vtable we're
  674. /// currently building.
  675. MethodInfoMapTy MethodInfoMap;
  676. /// MethodVTableIndices - Contains the index (relative to the vtable address
  677. /// point) where the function pointer for a virtual function is stored.
  678. MethodVTableIndicesTy MethodVTableIndices;
  679. typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
  680. /// VTableThunks - The thunks by vtable index in the vtable currently being
  681. /// built.
  682. VTableThunksMapTy VTableThunks;
  683. typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
  684. typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
  685. /// Thunks - A map that contains all the thunks needed for all methods in the
  686. /// most derived class for which the vtable is currently being built.
  687. ThunksMapTy Thunks;
  688. /// AddThunk - Add a thunk for the given method.
  689. void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
  690. /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
  691. /// part of the vtable we're currently building.
  692. void ComputeThisAdjustments();
  693. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  694. /// PrimaryVirtualBases - All known virtual bases who are a primary base of
  695. /// some other base.
  696. VisitedVirtualBasesSetTy PrimaryVirtualBases;
  697. /// ComputeReturnAdjustment - Compute the return adjustment given a return
  698. /// adjustment base offset.
  699. ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
  700. /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
  701. /// the 'this' pointer from the base subobject to the derived subobject.
  702. BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
  703. BaseSubobject Derived) const;
  704. /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
  705. /// given virtual member function, its offset in the layout class and its
  706. /// final overrider.
  707. ThisAdjustment
  708. ComputeThisAdjustment(const CXXMethodDecl *MD,
  709. CharUnits BaseOffsetInLayoutClass,
  710. FinalOverriders::OverriderInfo Overrider);
  711. /// AddMethod - Add a single virtual member function to the vtable
  712. /// components vector.
  713. void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
  714. /// IsOverriderUsed - Returns whether the overrider will ever be used in this
  715. /// part of the vtable.
  716. ///
  717. /// Itanium C++ ABI 2.5.2:
  718. ///
  719. /// struct A { virtual void f(); };
  720. /// struct B : virtual public A { int i; };
  721. /// struct C : virtual public A { int j; };
  722. /// struct D : public B, public C {};
  723. ///
  724. /// When B and C are declared, A is a primary base in each case, so although
  725. /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
  726. /// adjustment is required and no thunk is generated. However, inside D
  727. /// objects, A is no longer a primary base of C, so if we allowed calls to
  728. /// C::f() to use the copy of A's vtable in the C subobject, we would need
  729. /// to adjust this from C* to B::A*, which would require a third-party
  730. /// thunk. Since we require that a call to C::f() first convert to A*,
  731. /// C-in-D's copy of A's vtable is never referenced, so this is not
  732. /// necessary.
  733. bool IsOverriderUsed(const CXXMethodDecl *Overrider,
  734. CharUnits BaseOffsetInLayoutClass,
  735. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  736. CharUnits FirstBaseOffsetInLayoutClass) const;
  737. /// AddMethods - Add the methods of this base subobject and all its
  738. /// primary bases to the vtable components vector.
  739. void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
  740. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  741. CharUnits FirstBaseOffsetInLayoutClass,
  742. PrimaryBasesSetVectorTy &PrimaryBases);
  743. // LayoutVTable - Layout the vtable for the given base class, including its
  744. // secondary vtables and any vtables for virtual bases.
  745. void LayoutVTable();
  746. /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
  747. /// given base subobject, as well as all its secondary vtables.
  748. ///
  749. /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
  750. /// or a direct or indirect base of a virtual base.
  751. ///
  752. /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
  753. /// in the layout class.
  754. void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
  755. bool BaseIsMorallyVirtual,
  756. bool BaseIsVirtualInLayoutClass,
  757. CharUnits OffsetInLayoutClass);
  758. /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
  759. /// subobject.
  760. ///
  761. /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
  762. /// or a direct or indirect base of a virtual base.
  763. void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
  764. CharUnits OffsetInLayoutClass);
  765. /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
  766. /// class hierarchy.
  767. void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
  768. CharUnits OffsetInLayoutClass,
  769. VisitedVirtualBasesSetTy &VBases);
  770. /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
  771. /// given base (excluding any primary bases).
  772. void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
  773. VisitedVirtualBasesSetTy &VBases);
  774. /// isBuildingConstructionVTable - Return whether this vtable builder is
  775. /// building a construction vtable.
  776. bool isBuildingConstructorVTable() const {
  777. return MostDerivedClass != LayoutClass;
  778. }
  779. public:
  780. ItaniumVTableBuilder(ItaniumVTableContext &VTables,
  781. const CXXRecordDecl *MostDerivedClass,
  782. CharUnits MostDerivedClassOffset,
  783. bool MostDerivedClassIsVirtual,
  784. const CXXRecordDecl *LayoutClass)
  785. : VTables(VTables), MostDerivedClass(MostDerivedClass),
  786. MostDerivedClassOffset(MostDerivedClassOffset),
  787. MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
  788. LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
  789. Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
  790. assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
  791. LayoutVTable();
  792. if (Context.getLangOpts().DumpVTableLayouts)
  793. dumpLayout(llvm::outs());
  794. }
  795. uint64_t getNumThunks() const {
  796. return Thunks.size();
  797. }
  798. ThunksMapTy::const_iterator thunks_begin() const {
  799. return Thunks.begin();
  800. }
  801. ThunksMapTy::const_iterator thunks_end() const {
  802. return Thunks.end();
  803. }
  804. const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
  805. return VBaseOffsetOffsets;
  806. }
  807. const AddressPointsMapTy &getAddressPoints() const {
  808. return AddressPoints;
  809. }
  810. MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
  811. return MethodVTableIndices.begin();
  812. }
  813. MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
  814. return MethodVTableIndices.end();
  815. }
  816. /// getNumVTableComponents - Return the number of components in the vtable
  817. /// currently built.
  818. uint64_t getNumVTableComponents() const {
  819. return Components.size();
  820. }
  821. const VTableComponent *vtable_component_begin() const {
  822. return Components.begin();
  823. }
  824. const VTableComponent *vtable_component_end() const {
  825. return Components.end();
  826. }
  827. AddressPointsMapTy::const_iterator address_points_begin() const {
  828. return AddressPoints.begin();
  829. }
  830. AddressPointsMapTy::const_iterator address_points_end() const {
  831. return AddressPoints.end();
  832. }
  833. VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
  834. return VTableThunks.begin();
  835. }
  836. VTableThunksMapTy::const_iterator vtable_thunks_end() const {
  837. return VTableThunks.end();
  838. }
  839. /// dumpLayout - Dump the vtable layout.
  840. void dumpLayout(raw_ostream&);
  841. };
  842. void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
  843. const ThunkInfo &Thunk) {
  844. assert(!isBuildingConstructorVTable() &&
  845. "Can't add thunks for construction vtable");
  846. SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
  847. // Check if we have this thunk already.
  848. if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
  849. ThunksVector.end())
  850. return;
  851. ThunksVector.push_back(Thunk);
  852. }
  853. typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
  854. /// Visit all the methods overridden by the given method recursively,
  855. /// in a depth-first pre-order. The Visitor's visitor method returns a bool
  856. /// indicating whether to continue the recursion for the given overridden
  857. /// method (i.e. returning false stops the iteration).
  858. template <class VisitorTy>
  859. static void
  860. visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
  861. assert(MD->isVirtual() && "Method is not virtual!");
  862. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  863. E = MD->end_overridden_methods(); I != E; ++I) {
  864. const CXXMethodDecl *OverriddenMD = *I;
  865. if (!Visitor(OverriddenMD))
  866. continue;
  867. visitAllOverriddenMethods(OverriddenMD, Visitor);
  868. }
  869. }
  870. /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
  871. /// the overridden methods that the function decl overrides.
  872. static void
  873. ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
  874. OverriddenMethodsSetTy& OverriddenMethods) {
  875. auto OverriddenMethodsCollector = [&](const CXXMethodDecl *MD) {
  876. // Don't recurse on this method if we've already collected it.
  877. return OverriddenMethods.insert(MD).second;
  878. };
  879. visitAllOverriddenMethods(MD, OverriddenMethodsCollector);
  880. }
  881. void ItaniumVTableBuilder::ComputeThisAdjustments() {
  882. // Now go through the method info map and see if any of the methods need
  883. // 'this' pointer adjustments.
  884. for (const auto &MI : MethodInfoMap) {
  885. const CXXMethodDecl *MD = MI.first;
  886. const MethodInfo &MethodInfo = MI.second;
  887. // Ignore adjustments for unused function pointers.
  888. uint64_t VTableIndex = MethodInfo.VTableIndex;
  889. if (Components[VTableIndex].getKind() ==
  890. VTableComponent::CK_UnusedFunctionPointer)
  891. continue;
  892. // Get the final overrider for this method.
  893. FinalOverriders::OverriderInfo Overrider =
  894. Overriders.getOverrider(MD, MethodInfo.BaseOffset);
  895. // Check if we need an adjustment at all.
  896. if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
  897. // When a return thunk is needed by a derived class that overrides a
  898. // virtual base, gcc uses a virtual 'this' adjustment as well.
  899. // While the thunk itself might be needed by vtables in subclasses or
  900. // in construction vtables, there doesn't seem to be a reason for using
  901. // the thunk in this vtable. Still, we do so to match gcc.
  902. if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
  903. continue;
  904. }
  905. ThisAdjustment ThisAdjustment =
  906. ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
  907. if (ThisAdjustment.isEmpty())
  908. continue;
  909. // Add it.
  910. VTableThunks[VTableIndex].This = ThisAdjustment;
  911. if (isa<CXXDestructorDecl>(MD)) {
  912. // Add an adjustment for the deleting destructor as well.
  913. VTableThunks[VTableIndex + 1].This = ThisAdjustment;
  914. }
  915. }
  916. /// Clear the method info map.
  917. MethodInfoMap.clear();
  918. if (isBuildingConstructorVTable()) {
  919. // We don't need to store thunk information for construction vtables.
  920. return;
  921. }
  922. for (const auto &TI : VTableThunks) {
  923. const VTableComponent &Component = Components[TI.first];
  924. const ThunkInfo &Thunk = TI.second;
  925. const CXXMethodDecl *MD;
  926. switch (Component.getKind()) {
  927. default:
  928. llvm_unreachable("Unexpected vtable component kind!");
  929. case VTableComponent::CK_FunctionPointer:
  930. MD = Component.getFunctionDecl();
  931. break;
  932. case VTableComponent::CK_CompleteDtorPointer:
  933. MD = Component.getDestructorDecl();
  934. break;
  935. case VTableComponent::CK_DeletingDtorPointer:
  936. // We've already added the thunk when we saw the complete dtor pointer.
  937. continue;
  938. }
  939. if (MD->getParent() == MostDerivedClass)
  940. AddThunk(MD, Thunk);
  941. }
  942. }
  943. ReturnAdjustment
  944. ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
  945. ReturnAdjustment Adjustment;
  946. if (!Offset.isEmpty()) {
  947. if (Offset.VirtualBase) {
  948. // Get the virtual base offset offset.
  949. if (Offset.DerivedClass == MostDerivedClass) {
  950. // We can get the offset offset directly from our map.
  951. Adjustment.Virtual.Itanium.VBaseOffsetOffset =
  952. VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
  953. } else {
  954. Adjustment.Virtual.Itanium.VBaseOffsetOffset =
  955. VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
  956. Offset.VirtualBase).getQuantity();
  957. }
  958. }
  959. Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
  960. }
  961. return Adjustment;
  962. }
  963. BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
  964. BaseSubobject Base, BaseSubobject Derived) const {
  965. const CXXRecordDecl *BaseRD = Base.getBase();
  966. const CXXRecordDecl *DerivedRD = Derived.getBase();
  967. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  968. /*RecordPaths=*/true, /*DetectVirtual=*/true);
  969. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  970. llvm_unreachable("Class must be derived from the passed in base class!");
  971. // We have to go through all the paths, and see which one leads us to the
  972. // right base subobject.
  973. for (const CXXBasePath &Path : Paths) {
  974. BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, Path);
  975. CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
  976. if (Offset.VirtualBase) {
  977. // If we have a virtual base class, the non-virtual offset is relative
  978. // to the virtual base class offset.
  979. const ASTRecordLayout &LayoutClassLayout =
  980. Context.getASTRecordLayout(LayoutClass);
  981. /// Get the virtual base offset, relative to the most derived class
  982. /// layout.
  983. OffsetToBaseSubobject +=
  984. LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
  985. } else {
  986. // Otherwise, the non-virtual offset is relative to the derived class
  987. // offset.
  988. OffsetToBaseSubobject += Derived.getBaseOffset();
  989. }
  990. // Check if this path gives us the right base subobject.
  991. if (OffsetToBaseSubobject == Base.getBaseOffset()) {
  992. // Since we're going from the base class _to_ the derived class, we'll
  993. // invert the non-virtual offset here.
  994. Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
  995. return Offset;
  996. }
  997. }
  998. return BaseOffset();
  999. }
  1000. ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
  1001. const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
  1002. FinalOverriders::OverriderInfo Overrider) {
  1003. // Ignore adjustments for pure virtual member functions.
  1004. if (Overrider.Method->isPure())
  1005. return ThisAdjustment();
  1006. BaseSubobject OverriddenBaseSubobject(MD->getParent(),
  1007. BaseOffsetInLayoutClass);
  1008. BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
  1009. Overrider.Offset);
  1010. // Compute the adjustment offset.
  1011. BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
  1012. OverriderBaseSubobject);
  1013. if (Offset.isEmpty())
  1014. return ThisAdjustment();
  1015. ThisAdjustment Adjustment;
  1016. if (Offset.VirtualBase) {
  1017. // Get the vcall offset map for this virtual base.
  1018. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
  1019. if (VCallOffsets.empty()) {
  1020. // We don't have vcall offsets for this virtual base, go ahead and
  1021. // build them.
  1022. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
  1023. /*FinalOverriders=*/nullptr,
  1024. BaseSubobject(Offset.VirtualBase,
  1025. CharUnits::Zero()),
  1026. /*BaseIsVirtual=*/true,
  1027. /*OffsetInLayoutClass=*/
  1028. CharUnits::Zero());
  1029. VCallOffsets = Builder.getVCallOffsets();
  1030. }
  1031. Adjustment.Virtual.Itanium.VCallOffsetOffset =
  1032. VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
  1033. }
  1034. // Set the non-virtual part of the adjustment.
  1035. Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
  1036. return Adjustment;
  1037. }
  1038. void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
  1039. ReturnAdjustment ReturnAdjustment) {
  1040. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1041. assert(ReturnAdjustment.isEmpty() &&
  1042. "Destructor can't have return adjustment!");
  1043. // Add both the complete destructor and the deleting destructor.
  1044. Components.push_back(VTableComponent::MakeCompleteDtor(DD));
  1045. Components.push_back(VTableComponent::MakeDeletingDtor(DD));
  1046. } else {
  1047. // Add the return adjustment if necessary.
  1048. if (!ReturnAdjustment.isEmpty())
  1049. VTableThunks[Components.size()].Return = ReturnAdjustment;
  1050. // Add the function.
  1051. Components.push_back(VTableComponent::MakeFunction(MD));
  1052. }
  1053. }
  1054. /// OverridesIndirectMethodInBase - Return whether the given member function
  1055. /// overrides any methods in the set of given bases.
  1056. /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
  1057. /// For example, if we have:
  1058. ///
  1059. /// struct A { virtual void f(); }
  1060. /// struct B : A { virtual void f(); }
  1061. /// struct C : B { virtual void f(); }
  1062. ///
  1063. /// OverridesIndirectMethodInBase will return true if given C::f as the method
  1064. /// and { A } as the set of bases.
  1065. static bool OverridesIndirectMethodInBases(
  1066. const CXXMethodDecl *MD,
  1067. ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
  1068. if (Bases.count(MD->getParent()))
  1069. return true;
  1070. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  1071. E = MD->end_overridden_methods(); I != E; ++I) {
  1072. const CXXMethodDecl *OverriddenMD = *I;
  1073. // Check "indirect overriders".
  1074. if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
  1075. return true;
  1076. }
  1077. return false;
  1078. }
  1079. bool ItaniumVTableBuilder::IsOverriderUsed(
  1080. const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
  1081. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  1082. CharUnits FirstBaseOffsetInLayoutClass) const {
  1083. // If the base and the first base in the primary base chain have the same
  1084. // offsets, then this overrider will be used.
  1085. if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
  1086. return true;
  1087. // We know now that Base (or a direct or indirect base of it) is a primary
  1088. // base in part of the class hierarchy, but not a primary base in the most
  1089. // derived class.
  1090. // If the overrider is the first base in the primary base chain, we know
  1091. // that the overrider will be used.
  1092. if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
  1093. return true;
  1094. ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
  1095. const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
  1096. PrimaryBases.insert(RD);
  1097. // Now traverse the base chain, starting with the first base, until we find
  1098. // the base that is no longer a primary base.
  1099. while (true) {
  1100. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1101. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1102. if (!PrimaryBase)
  1103. break;
  1104. if (Layout.isPrimaryBaseVirtual()) {
  1105. assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
  1106. "Primary base should always be at offset 0!");
  1107. const ASTRecordLayout &LayoutClassLayout =
  1108. Context.getASTRecordLayout(LayoutClass);
  1109. // Now check if this is the primary base that is not a primary base in the
  1110. // most derived class.
  1111. if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
  1112. FirstBaseOffsetInLayoutClass) {
  1113. // We found it, stop walking the chain.
  1114. break;
  1115. }
  1116. } else {
  1117. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  1118. "Primary base should always be at offset 0!");
  1119. }
  1120. if (!PrimaryBases.insert(PrimaryBase))
  1121. llvm_unreachable("Found a duplicate primary base!");
  1122. RD = PrimaryBase;
  1123. }
  1124. // If the final overrider is an override of one of the primary bases,
  1125. // then we know that it will be used.
  1126. return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
  1127. }
  1128. typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
  1129. /// FindNearestOverriddenMethod - Given a method, returns the overridden method
  1130. /// from the nearest base. Returns null if no method was found.
  1131. /// The Bases are expected to be sorted in a base-to-derived order.
  1132. static const CXXMethodDecl *
  1133. FindNearestOverriddenMethod(const CXXMethodDecl *MD,
  1134. BasesSetVectorTy &Bases) {
  1135. OverriddenMethodsSetTy OverriddenMethods;
  1136. ComputeAllOverriddenMethods(MD, OverriddenMethods);
  1137. for (const CXXRecordDecl *PrimaryBase :
  1138. llvm::make_range(Bases.rbegin(), Bases.rend())) {
  1139. // Now check the overridden methods.
  1140. for (const CXXMethodDecl *OverriddenMD : OverriddenMethods) {
  1141. // We found our overridden method.
  1142. if (OverriddenMD->getParent() == PrimaryBase)
  1143. return OverriddenMD;
  1144. }
  1145. }
  1146. return nullptr;
  1147. }
  1148. void ItaniumVTableBuilder::AddMethods(
  1149. BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
  1150. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  1151. CharUnits FirstBaseOffsetInLayoutClass,
  1152. PrimaryBasesSetVectorTy &PrimaryBases) {
  1153. // Itanium C++ ABI 2.5.2:
  1154. // The order of the virtual function pointers in a virtual table is the
  1155. // order of declaration of the corresponding member functions in the class.
  1156. //
  1157. // There is an entry for any virtual function declared in a class,
  1158. // whether it is a new function or overrides a base class function,
  1159. // unless it overrides a function from the primary base, and conversion
  1160. // between their return types does not require an adjustment.
  1161. const CXXRecordDecl *RD = Base.getBase();
  1162. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1163. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  1164. CharUnits PrimaryBaseOffset;
  1165. CharUnits PrimaryBaseOffsetInLayoutClass;
  1166. if (Layout.isPrimaryBaseVirtual()) {
  1167. assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
  1168. "Primary vbase should have a zero offset!");
  1169. const ASTRecordLayout &MostDerivedClassLayout =
  1170. Context.getASTRecordLayout(MostDerivedClass);
  1171. PrimaryBaseOffset =
  1172. MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
  1173. const ASTRecordLayout &LayoutClassLayout =
  1174. Context.getASTRecordLayout(LayoutClass);
  1175. PrimaryBaseOffsetInLayoutClass =
  1176. LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
  1177. } else {
  1178. assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
  1179. "Primary base should have a zero offset!");
  1180. PrimaryBaseOffset = Base.getBaseOffset();
  1181. PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
  1182. }
  1183. AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
  1184. PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
  1185. FirstBaseOffsetInLayoutClass, PrimaryBases);
  1186. if (!PrimaryBases.insert(PrimaryBase))
  1187. llvm_unreachable("Found a duplicate primary base!");
  1188. }
  1189. const CXXDestructorDecl *ImplicitVirtualDtor = nullptr;
  1190. typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
  1191. NewVirtualFunctionsTy NewVirtualFunctions;
  1192. // Now go through all virtual member functions and add them.
  1193. for (const auto *MD : RD->methods()) {
  1194. if (!MD->isVirtual())
  1195. continue;
  1196. MD = MD->getCanonicalDecl();
  1197. // Get the final overrider.
  1198. FinalOverriders::OverriderInfo Overrider =
  1199. Overriders.getOverrider(MD, Base.getBaseOffset());
  1200. // Check if this virtual member function overrides a method in a primary
  1201. // base. If this is the case, and the return type doesn't require adjustment
  1202. // then we can just use the member function from the primary base.
  1203. if (const CXXMethodDecl *OverriddenMD =
  1204. FindNearestOverriddenMethod(MD, PrimaryBases)) {
  1205. if (ComputeReturnAdjustmentBaseOffset(Context, MD,
  1206. OverriddenMD).isEmpty()) {
  1207. // Replace the method info of the overridden method with our own
  1208. // method.
  1209. assert(MethodInfoMap.count(OverriddenMD) &&
  1210. "Did not find the overridden method!");
  1211. MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
  1212. MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
  1213. OverriddenMethodInfo.VTableIndex);
  1214. assert(!MethodInfoMap.count(MD) &&
  1215. "Should not have method info for this method yet!");
  1216. MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
  1217. MethodInfoMap.erase(OverriddenMD);
  1218. // If the overridden method exists in a virtual base class or a direct
  1219. // or indirect base class of a virtual base class, we need to emit a
  1220. // thunk if we ever have a class hierarchy where the base class is not
  1221. // a primary base in the complete object.
  1222. if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
  1223. // Compute the this adjustment.
  1224. ThisAdjustment ThisAdjustment =
  1225. ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
  1226. Overrider);
  1227. if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
  1228. Overrider.Method->getParent() == MostDerivedClass) {
  1229. // There's no return adjustment from OverriddenMD and MD,
  1230. // but that doesn't mean there isn't one between MD and
  1231. // the final overrider.
  1232. BaseOffset ReturnAdjustmentOffset =
  1233. ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
  1234. ReturnAdjustment ReturnAdjustment =
  1235. ComputeReturnAdjustment(ReturnAdjustmentOffset);
  1236. // This is a virtual thunk for the most derived class, add it.
  1237. AddThunk(Overrider.Method,
  1238. ThunkInfo(ThisAdjustment, ReturnAdjustment));
  1239. }
  1240. }
  1241. continue;
  1242. }
  1243. }
  1244. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1245. if (MD->isImplicit()) {
  1246. // Itanium C++ ABI 2.5.2:
  1247. // If a class has an implicitly-defined virtual destructor,
  1248. // its entries come after the declared virtual function pointers.
  1249. assert(!ImplicitVirtualDtor &&
  1250. "Did already see an implicit virtual dtor!");
  1251. ImplicitVirtualDtor = DD;
  1252. continue;
  1253. }
  1254. }
  1255. NewVirtualFunctions.push_back(MD);
  1256. }
  1257. if (ImplicitVirtualDtor)
  1258. NewVirtualFunctions.push_back(ImplicitVirtualDtor);
  1259. for (const CXXMethodDecl *MD : NewVirtualFunctions) {
  1260. // Get the final overrider.
  1261. FinalOverriders::OverriderInfo Overrider =
  1262. Overriders.getOverrider(MD, Base.getBaseOffset());
  1263. // Insert the method info for this method.
  1264. MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
  1265. Components.size());
  1266. assert(!MethodInfoMap.count(MD) &&
  1267. "Should not have method info for this method yet!");
  1268. MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
  1269. // Check if this overrider is going to be used.
  1270. const CXXMethodDecl *OverriderMD = Overrider.Method;
  1271. if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
  1272. FirstBaseInPrimaryBaseChain,
  1273. FirstBaseOffsetInLayoutClass)) {
  1274. Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
  1275. continue;
  1276. }
  1277. // Check if this overrider needs a return adjustment.
  1278. // We don't want to do this for pure virtual member functions.
  1279. BaseOffset ReturnAdjustmentOffset;
  1280. if (!OverriderMD->isPure()) {
  1281. ReturnAdjustmentOffset =
  1282. ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
  1283. }
  1284. ReturnAdjustment ReturnAdjustment =
  1285. ComputeReturnAdjustment(ReturnAdjustmentOffset);
  1286. AddMethod(Overrider.Method, ReturnAdjustment);
  1287. }
  1288. }
  1289. void ItaniumVTableBuilder::LayoutVTable() {
  1290. LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
  1291. CharUnits::Zero()),
  1292. /*BaseIsMorallyVirtual=*/false,
  1293. MostDerivedClassIsVirtual,
  1294. MostDerivedClassOffset);
  1295. VisitedVirtualBasesSetTy VBases;
  1296. // Determine the primary virtual bases.
  1297. DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
  1298. VBases);
  1299. VBases.clear();
  1300. LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
  1301. // -fapple-kext adds an extra entry at end of vtbl.
  1302. bool IsAppleKext = Context.getLangOpts().AppleKext;
  1303. if (IsAppleKext)
  1304. Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
  1305. }
  1306. void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
  1307. BaseSubobject Base, bool BaseIsMorallyVirtual,
  1308. bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
  1309. assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
  1310. // Add vcall and vbase offsets for this vtable.
  1311. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
  1312. Base, BaseIsVirtualInLayoutClass,
  1313. OffsetInLayoutClass);
  1314. Components.append(Builder.components_begin(), Builder.components_end());
  1315. // Check if we need to add these vcall offsets.
  1316. if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
  1317. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
  1318. if (VCallOffsets.empty())
  1319. VCallOffsets = Builder.getVCallOffsets();
  1320. }
  1321. // If we're laying out the most derived class we want to keep track of the
  1322. // virtual base class offset offsets.
  1323. if (Base.getBase() == MostDerivedClass)
  1324. VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
  1325. // Add the offset to top.
  1326. CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
  1327. Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
  1328. // Next, add the RTTI.
  1329. Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
  1330. uint64_t AddressPoint = Components.size();
  1331. // Now go through all virtual member functions and add them.
  1332. PrimaryBasesSetVectorTy PrimaryBases;
  1333. AddMethods(Base, OffsetInLayoutClass,
  1334. Base.getBase(), OffsetInLayoutClass,
  1335. PrimaryBases);
  1336. const CXXRecordDecl *RD = Base.getBase();
  1337. if (RD == MostDerivedClass) {
  1338. assert(MethodVTableIndices.empty());
  1339. for (const auto &I : MethodInfoMap) {
  1340. const CXXMethodDecl *MD = I.first;
  1341. const MethodInfo &MI = I.second;
  1342. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1343. MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
  1344. = MI.VTableIndex - AddressPoint;
  1345. MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
  1346. = MI.VTableIndex + 1 - AddressPoint;
  1347. } else {
  1348. MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
  1349. }
  1350. }
  1351. }
  1352. // Compute 'this' pointer adjustments.
  1353. ComputeThisAdjustments();
  1354. // Add all address points.
  1355. while (true) {
  1356. AddressPoints.insert(std::make_pair(
  1357. BaseSubobject(RD, OffsetInLayoutClass),
  1358. AddressPoint));
  1359. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1360. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1361. if (!PrimaryBase)
  1362. break;
  1363. if (Layout.isPrimaryBaseVirtual()) {
  1364. // Check if this virtual primary base is a primary base in the layout
  1365. // class. If it's not, we don't want to add it.
  1366. const ASTRecordLayout &LayoutClassLayout =
  1367. Context.getASTRecordLayout(LayoutClass);
  1368. if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
  1369. OffsetInLayoutClass) {
  1370. // We don't want to add this class (or any of its primary bases).
  1371. break;
  1372. }
  1373. }
  1374. RD = PrimaryBase;
  1375. }
  1376. // Layout secondary vtables.
  1377. LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
  1378. }
  1379. void
  1380. ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
  1381. bool BaseIsMorallyVirtual,
  1382. CharUnits OffsetInLayoutClass) {
  1383. // Itanium C++ ABI 2.5.2:
  1384. // Following the primary virtual table of a derived class are secondary
  1385. // virtual tables for each of its proper base classes, except any primary
  1386. // base(s) with which it shares its primary virtual table.
  1387. const CXXRecordDecl *RD = Base.getBase();
  1388. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1389. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1390. for (const auto &B : RD->bases()) {
  1391. // Ignore virtual bases, we'll emit them later.
  1392. if (B.isVirtual())
  1393. continue;
  1394. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  1395. // Ignore bases that don't have a vtable.
  1396. if (!BaseDecl->isDynamicClass())
  1397. continue;
  1398. if (isBuildingConstructorVTable()) {
  1399. // Itanium C++ ABI 2.6.4:
  1400. // Some of the base class subobjects may not need construction virtual
  1401. // tables, which will therefore not be present in the construction
  1402. // virtual table group, even though the subobject virtual tables are
  1403. // present in the main virtual table group for the complete object.
  1404. if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
  1405. continue;
  1406. }
  1407. // Get the base offset of this base.
  1408. CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
  1409. CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
  1410. CharUnits BaseOffsetInLayoutClass =
  1411. OffsetInLayoutClass + RelativeBaseOffset;
  1412. // Don't emit a secondary vtable for a primary base. We might however want
  1413. // to emit secondary vtables for other bases of this base.
  1414. if (BaseDecl == PrimaryBase) {
  1415. LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
  1416. BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
  1417. continue;
  1418. }
  1419. // Layout the primary vtable (and any secondary vtables) for this base.
  1420. LayoutPrimaryAndSecondaryVTables(
  1421. BaseSubobject(BaseDecl, BaseOffset),
  1422. BaseIsMorallyVirtual,
  1423. /*BaseIsVirtualInLayoutClass=*/false,
  1424. BaseOffsetInLayoutClass);
  1425. }
  1426. }
  1427. void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
  1428. const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
  1429. VisitedVirtualBasesSetTy &VBases) {
  1430. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1431. // Check if this base has a primary base.
  1432. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  1433. // Check if it's virtual.
  1434. if (Layout.isPrimaryBaseVirtual()) {
  1435. bool IsPrimaryVirtualBase = true;
  1436. if (isBuildingConstructorVTable()) {
  1437. // Check if the base is actually a primary base in the class we use for
  1438. // layout.
  1439. const ASTRecordLayout &LayoutClassLayout =
  1440. Context.getASTRecordLayout(LayoutClass);
  1441. CharUnits PrimaryBaseOffsetInLayoutClass =
  1442. LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
  1443. // We know that the base is not a primary base in the layout class if
  1444. // the base offsets are different.
  1445. if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
  1446. IsPrimaryVirtualBase = false;
  1447. }
  1448. if (IsPrimaryVirtualBase)
  1449. PrimaryVirtualBases.insert(PrimaryBase);
  1450. }
  1451. }
  1452. // Traverse bases, looking for more primary virtual bases.
  1453. for (const auto &B : RD->bases()) {
  1454. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  1455. CharUnits BaseOffsetInLayoutClass;
  1456. if (B.isVirtual()) {
  1457. if (!VBases.insert(BaseDecl).second)
  1458. continue;
  1459. const ASTRecordLayout &LayoutClassLayout =
  1460. Context.getASTRecordLayout(LayoutClass);
  1461. BaseOffsetInLayoutClass =
  1462. LayoutClassLayout.getVBaseClassOffset(BaseDecl);
  1463. } else {
  1464. BaseOffsetInLayoutClass =
  1465. OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
  1466. }
  1467. DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
  1468. }
  1469. }
  1470. void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
  1471. const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
  1472. // Itanium C++ ABI 2.5.2:
  1473. // Then come the virtual base virtual tables, also in inheritance graph
  1474. // order, and again excluding primary bases (which share virtual tables with
  1475. // the classes for which they are primary).
  1476. for (const auto &B : RD->bases()) {
  1477. const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
  1478. // Check if this base needs a vtable. (If it's virtual, not a primary base
  1479. // of some other class, and we haven't visited it before).
  1480. if (B.isVirtual() && BaseDecl->isDynamicClass() &&
  1481. !PrimaryVirtualBases.count(BaseDecl) &&
  1482. VBases.insert(BaseDecl).second) {
  1483. const ASTRecordLayout &MostDerivedClassLayout =
  1484. Context.getASTRecordLayout(MostDerivedClass);
  1485. CharUnits BaseOffset =
  1486. MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
  1487. const ASTRecordLayout &LayoutClassLayout =
  1488. Context.getASTRecordLayout(LayoutClass);
  1489. CharUnits BaseOffsetInLayoutClass =
  1490. LayoutClassLayout.getVBaseClassOffset(BaseDecl);
  1491. LayoutPrimaryAndSecondaryVTables(
  1492. BaseSubobject(BaseDecl, BaseOffset),
  1493. /*BaseIsMorallyVirtual=*/true,
  1494. /*BaseIsVirtualInLayoutClass=*/true,
  1495. BaseOffsetInLayoutClass);
  1496. }
  1497. // We only need to check the base for virtual base vtables if it actually
  1498. // has virtual bases.
  1499. if (BaseDecl->getNumVBases())
  1500. LayoutVTablesForVirtualBases(BaseDecl, VBases);
  1501. }
  1502. }
  1503. /// dumpLayout - Dump the vtable layout.
  1504. void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
  1505. // FIXME: write more tests that actually use the dumpLayout output to prevent
  1506. // ItaniumVTableBuilder regressions.
  1507. if (isBuildingConstructorVTable()) {
  1508. Out << "Construction vtable for ('";
  1509. MostDerivedClass->printQualifiedName(Out);
  1510. Out << "', ";
  1511. Out << MostDerivedClassOffset.getQuantity() << ") in '";
  1512. LayoutClass->printQualifiedName(Out);
  1513. } else {
  1514. Out << "Vtable for '";
  1515. MostDerivedClass->printQualifiedName(Out);
  1516. }
  1517. Out << "' (" << Components.size() << " entries).\n";
  1518. // Iterate through the address points and insert them into a new map where
  1519. // they are keyed by the index and not the base object.
  1520. // Since an address point can be shared by multiple subobjects, we use an
  1521. // STL multimap.
  1522. std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
  1523. for (const auto &AP : AddressPoints) {
  1524. const BaseSubobject &Base = AP.first;
  1525. uint64_t Index = AP.second;
  1526. AddressPointsByIndex.insert(std::make_pair(Index, Base));
  1527. }
  1528. for (unsigned I = 0, E = Components.size(); I != E; ++I) {
  1529. uint64_t Index = I;
  1530. Out << llvm::format("%4d | ", I);
  1531. const VTableComponent &Component = Components[I];
  1532. // Dump the component.
  1533. switch (Component.getKind()) {
  1534. case VTableComponent::CK_VCallOffset:
  1535. Out << "vcall_offset ("
  1536. << Component.getVCallOffset().getQuantity()
  1537. << ")";
  1538. break;
  1539. case VTableComponent::CK_VBaseOffset:
  1540. Out << "vbase_offset ("
  1541. << Component.getVBaseOffset().getQuantity()
  1542. << ")";
  1543. break;
  1544. case VTableComponent::CK_OffsetToTop:
  1545. Out << "offset_to_top ("
  1546. << Component.getOffsetToTop().getQuantity()
  1547. << ")";
  1548. break;
  1549. case VTableComponent::CK_RTTI:
  1550. Component.getRTTIDecl()->printQualifiedName(Out);
  1551. Out << " RTTI";
  1552. break;
  1553. case VTableComponent::CK_FunctionPointer: {
  1554. const CXXMethodDecl *MD = Component.getFunctionDecl();
  1555. std::string Str =
  1556. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1557. MD);
  1558. Out << Str;
  1559. if (MD->isPure())
  1560. Out << " [pure]";
  1561. if (MD->isDeleted())
  1562. Out << " [deleted]";
  1563. ThunkInfo Thunk = VTableThunks.lookup(I);
  1564. if (!Thunk.isEmpty()) {
  1565. // If this function pointer has a return adjustment, dump it.
  1566. if (!Thunk.Return.isEmpty()) {
  1567. Out << "\n [return adjustment: ";
  1568. Out << Thunk.Return.NonVirtual << " non-virtual";
  1569. if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
  1570. Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
  1571. Out << " vbase offset offset";
  1572. }
  1573. Out << ']';
  1574. }
  1575. // If this function pointer has a 'this' pointer adjustment, dump it.
  1576. if (!Thunk.This.isEmpty()) {
  1577. Out << "\n [this adjustment: ";
  1578. Out << Thunk.This.NonVirtual << " non-virtual";
  1579. if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
  1580. Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
  1581. Out << " vcall offset offset";
  1582. }
  1583. Out << ']';
  1584. }
  1585. }
  1586. break;
  1587. }
  1588. case VTableComponent::CK_CompleteDtorPointer:
  1589. case VTableComponent::CK_DeletingDtorPointer: {
  1590. bool IsComplete =
  1591. Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
  1592. const CXXDestructorDecl *DD = Component.getDestructorDecl();
  1593. DD->printQualifiedName(Out);
  1594. if (IsComplete)
  1595. Out << "() [complete]";
  1596. else
  1597. Out << "() [deleting]";
  1598. if (DD->isPure())
  1599. Out << " [pure]";
  1600. ThunkInfo Thunk = VTableThunks.lookup(I);
  1601. if (!Thunk.isEmpty()) {
  1602. // If this destructor has a 'this' pointer adjustment, dump it.
  1603. if (!Thunk.This.isEmpty()) {
  1604. Out << "\n [this adjustment: ";
  1605. Out << Thunk.This.NonVirtual << " non-virtual";
  1606. if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
  1607. Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
  1608. Out << " vcall offset offset";
  1609. }
  1610. Out << ']';
  1611. }
  1612. }
  1613. break;
  1614. }
  1615. case VTableComponent::CK_UnusedFunctionPointer: {
  1616. const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
  1617. std::string Str =
  1618. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1619. MD);
  1620. Out << "[unused] " << Str;
  1621. if (MD->isPure())
  1622. Out << " [pure]";
  1623. }
  1624. }
  1625. Out << '\n';
  1626. // Dump the next address point.
  1627. uint64_t NextIndex = Index + 1;
  1628. if (AddressPointsByIndex.count(NextIndex)) {
  1629. if (AddressPointsByIndex.count(NextIndex) == 1) {
  1630. const BaseSubobject &Base =
  1631. AddressPointsByIndex.find(NextIndex)->second;
  1632. Out << " -- (";
  1633. Base.getBase()->printQualifiedName(Out);
  1634. Out << ", " << Base.getBaseOffset().getQuantity();
  1635. Out << ") vtable address --\n";
  1636. } else {
  1637. CharUnits BaseOffset =
  1638. AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
  1639. // We store the class names in a set to get a stable order.
  1640. std::set<std::string> ClassNames;
  1641. for (const auto &I :
  1642. llvm::make_range(AddressPointsByIndex.equal_range(NextIndex))) {
  1643. assert(I.second.getBaseOffset() == BaseOffset &&
  1644. "Invalid base offset!");
  1645. const CXXRecordDecl *RD = I.second.getBase();
  1646. ClassNames.insert(RD->getQualifiedNameAsString());
  1647. }
  1648. for (const std::string &Name : ClassNames) {
  1649. Out << " -- (" << Name;
  1650. Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
  1651. }
  1652. }
  1653. }
  1654. }
  1655. Out << '\n';
  1656. if (isBuildingConstructorVTable())
  1657. return;
  1658. if (MostDerivedClass->getNumVBases()) {
  1659. // We store the virtual base class names and their offsets in a map to get
  1660. // a stable order.
  1661. std::map<std::string, CharUnits> ClassNamesAndOffsets;
  1662. for (const auto &I : VBaseOffsetOffsets) {
  1663. std::string ClassName = I.first->getQualifiedNameAsString();
  1664. CharUnits OffsetOffset = I.second;
  1665. ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
  1666. }
  1667. Out << "Virtual base offset offsets for '";
  1668. MostDerivedClass->printQualifiedName(Out);
  1669. Out << "' (";
  1670. Out << ClassNamesAndOffsets.size();
  1671. Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
  1672. for (const auto &I : ClassNamesAndOffsets)
  1673. Out << " " << I.first << " | " << I.second.getQuantity() << '\n';
  1674. Out << "\n";
  1675. }
  1676. if (!Thunks.empty()) {
  1677. // We store the method names in a map to get a stable order.
  1678. std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
  1679. for (const auto &I : Thunks) {
  1680. const CXXMethodDecl *MD = I.first;
  1681. std::string MethodName =
  1682. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1683. MD);
  1684. MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
  1685. }
  1686. for (const auto &I : MethodNamesAndDecls) {
  1687. const std::string &MethodName = I.first;
  1688. const CXXMethodDecl *MD = I.second;
  1689. ThunkInfoVectorTy ThunksVector = Thunks[MD];
  1690. std::sort(ThunksVector.begin(), ThunksVector.end(),
  1691. [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
  1692. assert(LHS.Method == nullptr && RHS.Method == nullptr);
  1693. return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
  1694. });
  1695. Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
  1696. Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
  1697. for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
  1698. const ThunkInfo &Thunk = ThunksVector[I];
  1699. Out << llvm::format("%4d | ", I);
  1700. // If this function pointer has a return pointer adjustment, dump it.
  1701. if (!Thunk.Return.isEmpty()) {
  1702. Out << "return adjustment: " << Thunk.Return.NonVirtual;
  1703. Out << " non-virtual";
  1704. if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
  1705. Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
  1706. Out << " vbase offset offset";
  1707. }
  1708. if (!Thunk.This.isEmpty())
  1709. Out << "\n ";
  1710. }
  1711. // If this function pointer has a 'this' pointer adjustment, dump it.
  1712. if (!Thunk.This.isEmpty()) {
  1713. Out << "this adjustment: ";
  1714. Out << Thunk.This.NonVirtual << " non-virtual";
  1715. if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
  1716. Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
  1717. Out << " vcall offset offset";
  1718. }
  1719. }
  1720. Out << '\n';
  1721. }
  1722. Out << '\n';
  1723. }
  1724. }
  1725. // Compute the vtable indices for all the member functions.
  1726. // Store them in a map keyed by the index so we'll get a sorted table.
  1727. std::map<uint64_t, std::string> IndicesMap;
  1728. for (const auto *MD : MostDerivedClass->methods()) {
  1729. // We only want virtual member functions.
  1730. if (!MD->isVirtual())
  1731. continue;
  1732. MD = MD->getCanonicalDecl();
  1733. std::string MethodName =
  1734. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1735. MD);
  1736. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1737. GlobalDecl GD(DD, Dtor_Complete);
  1738. assert(MethodVTableIndices.count(GD));
  1739. uint64_t VTableIndex = MethodVTableIndices[GD];
  1740. IndicesMap[VTableIndex] = MethodName + " [complete]";
  1741. IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
  1742. } else {
  1743. assert(MethodVTableIndices.count(MD));
  1744. IndicesMap[MethodVTableIndices[MD]] = MethodName;
  1745. }
  1746. }
  1747. // Print the vtable indices for all the member functions.
  1748. if (!IndicesMap.empty()) {
  1749. Out << "VTable indices for '";
  1750. MostDerivedClass->printQualifiedName(Out);
  1751. Out << "' (" << IndicesMap.size() << " entries).\n";
  1752. for (const auto &I : IndicesMap) {
  1753. uint64_t VTableIndex = I.first;
  1754. const std::string &MethodName = I.second;
  1755. Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
  1756. << '\n';
  1757. }
  1758. }
  1759. Out << '\n';
  1760. }
  1761. }
  1762. VTableLayout::VTableLayout(uint64_t NumVTableComponents,
  1763. const VTableComponent *VTableComponents,
  1764. uint64_t NumVTableThunks,
  1765. const VTableThunkTy *VTableThunks,
  1766. const AddressPointsMapTy &AddressPoints,
  1767. bool IsMicrosoftABI)
  1768. : NumVTableComponents(NumVTableComponents),
  1769. VTableComponents(new VTableComponent[NumVTableComponents]),
  1770. NumVTableThunks(NumVTableThunks),
  1771. VTableThunks(new VTableThunkTy[NumVTableThunks]),
  1772. AddressPoints(AddressPoints),
  1773. IsMicrosoftABI(IsMicrosoftABI) {
  1774. std::copy(VTableComponents, VTableComponents+NumVTableComponents,
  1775. this->VTableComponents.get());
  1776. std::copy(VTableThunks, VTableThunks+NumVTableThunks,
  1777. this->VTableThunks.get());
  1778. std::sort(this->VTableThunks.get(),
  1779. this->VTableThunks.get() + NumVTableThunks,
  1780. [](const VTableLayout::VTableThunkTy &LHS,
  1781. const VTableLayout::VTableThunkTy &RHS) {
  1782. assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
  1783. "Different thunks should have unique indices!");
  1784. return LHS.first < RHS.first;
  1785. });
  1786. }
  1787. VTableLayout::~VTableLayout() { }
  1788. ItaniumVTableContext::ItaniumVTableContext(ASTContext &Context)
  1789. : VTableContextBase(/*MS=*/false) {}
  1790. ItaniumVTableContext::~ItaniumVTableContext() {
  1791. llvm::DeleteContainerSeconds(VTableLayouts);
  1792. }
  1793. uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
  1794. MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
  1795. if (I != MethodVTableIndices.end())
  1796. return I->second;
  1797. const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  1798. computeVTableRelatedInformation(RD);
  1799. I = MethodVTableIndices.find(GD);
  1800. assert(I != MethodVTableIndices.end() && "Did not find index!");
  1801. return I->second;
  1802. }
  1803. CharUnits
  1804. ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
  1805. const CXXRecordDecl *VBase) {
  1806. ClassPairTy ClassPair(RD, VBase);
  1807. VirtualBaseClassOffsetOffsetsMapTy::iterator I =
  1808. VirtualBaseClassOffsetOffsets.find(ClassPair);
  1809. if (I != VirtualBaseClassOffsetOffsets.end())
  1810. return I->second;
  1811. VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/nullptr,
  1812. BaseSubobject(RD, CharUnits::Zero()),
  1813. /*BaseIsVirtual=*/false,
  1814. /*OffsetInLayoutClass=*/CharUnits::Zero());
  1815. for (const auto &I : Builder.getVBaseOffsetOffsets()) {
  1816. // Insert all types.
  1817. ClassPairTy ClassPair(RD, I.first);
  1818. VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
  1819. }
  1820. I = VirtualBaseClassOffsetOffsets.find(ClassPair);
  1821. assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
  1822. return I->second;
  1823. }
  1824. static VTableLayout *CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
  1825. SmallVector<VTableLayout::VTableThunkTy, 1>
  1826. VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
  1827. return new VTableLayout(Builder.getNumVTableComponents(),
  1828. Builder.vtable_component_begin(),
  1829. VTableThunks.size(),
  1830. VTableThunks.data(),
  1831. Builder.getAddressPoints(),
  1832. /*IsMicrosoftABI=*/false);
  1833. }
  1834. void
  1835. ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
  1836. const VTableLayout *&Entry = VTableLayouts[RD];
  1837. // Check if we've computed this information before.
  1838. if (Entry)
  1839. return;
  1840. ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
  1841. /*MostDerivedClassIsVirtual=*/0, RD);
  1842. Entry = CreateVTableLayout(Builder);
  1843. MethodVTableIndices.insert(Builder.vtable_indices_begin(),
  1844. Builder.vtable_indices_end());
  1845. // Add the known thunks.
  1846. Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
  1847. // If we don't have the vbase information for this class, insert it.
  1848. // getVirtualBaseOffsetOffset will compute it separately without computing
  1849. // the rest of the vtable related information.
  1850. if (!RD->getNumVBases())
  1851. return;
  1852. const CXXRecordDecl *VBase =
  1853. RD->vbases_begin()->getType()->getAsCXXRecordDecl();
  1854. if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
  1855. return;
  1856. for (const auto &I : Builder.getVBaseOffsetOffsets()) {
  1857. // Insert all types.
  1858. ClassPairTy ClassPair(RD, I.first);
  1859. VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
  1860. }
  1861. }
  1862. VTableLayout *ItaniumVTableContext::createConstructionVTableLayout(
  1863. const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
  1864. bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
  1865. ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
  1866. MostDerivedClassIsVirtual, LayoutClass);
  1867. return CreateVTableLayout(Builder);
  1868. }
  1869. namespace {
  1870. // Vtables in the Microsoft ABI are different from the Itanium ABI.
  1871. //
  1872. // The main differences are:
  1873. // 1. Separate vftable and vbtable.
  1874. //
  1875. // 2. Each subobject with a vfptr gets its own vftable rather than an address
  1876. // point in a single vtable shared between all the subobjects.
  1877. // Each vftable is represented by a separate section and virtual calls
  1878. // must be done using the vftable which has a slot for the function to be
  1879. // called.
  1880. //
  1881. // 3. Virtual method definitions expect their 'this' parameter to point to the
  1882. // first vfptr whose table provides a compatible overridden method. In many
  1883. // cases, this permits the original vf-table entry to directly call
  1884. // the method instead of passing through a thunk.
  1885. // See example before VFTableBuilder::ComputeThisOffset below.
  1886. //
  1887. // A compatible overridden method is one which does not have a non-trivial
  1888. // covariant-return adjustment.
  1889. //
  1890. // The first vfptr is the one with the lowest offset in the complete-object
  1891. // layout of the defining class, and the method definition will subtract
  1892. // that constant offset from the parameter value to get the real 'this'
  1893. // value. Therefore, if the offset isn't really constant (e.g. if a virtual
  1894. // function defined in a virtual base is overridden in a more derived
  1895. // virtual base and these bases have a reverse order in the complete
  1896. // object), the vf-table may require a this-adjustment thunk.
  1897. //
  1898. // 4. vftables do not contain new entries for overrides that merely require
  1899. // this-adjustment. Together with #3, this keeps vf-tables smaller and
  1900. // eliminates the need for this-adjustment thunks in many cases, at the cost
  1901. // of often requiring redundant work to adjust the "this" pointer.
  1902. //
  1903. // 5. Instead of VTT and constructor vtables, vbtables and vtordisps are used.
  1904. // Vtordisps are emitted into the class layout if a class has
  1905. // a) a user-defined ctor/dtor
  1906. // and
  1907. // b) a method overriding a method in a virtual base.
  1908. //
  1909. // To get a better understanding of this code,
  1910. // you might want to see examples in test/CodeGenCXX/microsoft-abi-vtables-*.cpp
  1911. class VFTableBuilder {
  1912. public:
  1913. typedef MicrosoftVTableContext::MethodVFTableLocation MethodVFTableLocation;
  1914. typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
  1915. MethodVFTableLocationsTy;
  1916. typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
  1917. method_locations_range;
  1918. private:
  1919. /// VTables - Global vtable information.
  1920. MicrosoftVTableContext &VTables;
  1921. /// Context - The ASTContext which we will use for layout information.
  1922. ASTContext &Context;
  1923. /// MostDerivedClass - The most derived class for which we're building this
  1924. /// vtable.
  1925. const CXXRecordDecl *MostDerivedClass;
  1926. const ASTRecordLayout &MostDerivedClassLayout;
  1927. const VPtrInfo &WhichVFPtr;
  1928. /// FinalOverriders - The final overriders of the most derived class.
  1929. const FinalOverriders Overriders;
  1930. /// Components - The components of the vftable being built.
  1931. SmallVector<VTableComponent, 64> Components;
  1932. MethodVFTableLocationsTy MethodVFTableLocations;
  1933. /// \brief Does this class have an RTTI component?
  1934. bool HasRTTIComponent;
  1935. /// MethodInfo - Contains information about a method in a vtable.
  1936. /// (Used for computing 'this' pointer adjustment thunks.
  1937. struct MethodInfo {
  1938. /// VBTableIndex - The nonzero index in the vbtable that
  1939. /// this method's base has, or zero.
  1940. const uint64_t VBTableIndex;
  1941. /// VFTableIndex - The index in the vftable that this method has.
  1942. const uint64_t VFTableIndex;
  1943. /// Shadowed - Indicates if this vftable slot is shadowed by
  1944. /// a slot for a covariant-return override. If so, it shouldn't be printed
  1945. /// or used for vcalls in the most derived class.
  1946. bool Shadowed;
  1947. /// UsesExtraSlot - Indicates if this vftable slot was created because
  1948. /// any of the overridden slots required a return adjusting thunk.
  1949. bool UsesExtraSlot;
  1950. MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex,
  1951. bool UsesExtraSlot = false)
  1952. : VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
  1953. Shadowed(false), UsesExtraSlot(UsesExtraSlot) {}
  1954. MethodInfo()
  1955. : VBTableIndex(0), VFTableIndex(0), Shadowed(false),
  1956. UsesExtraSlot(false) {}
  1957. };
  1958. typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
  1959. /// MethodInfoMap - The information for all methods in the vftable we're
  1960. /// currently building.
  1961. MethodInfoMapTy MethodInfoMap;
  1962. typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
  1963. /// VTableThunks - The thunks by vftable index in the vftable currently being
  1964. /// built.
  1965. VTableThunksMapTy VTableThunks;
  1966. typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
  1967. typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
  1968. /// Thunks - A map that contains all the thunks needed for all methods in the
  1969. /// most derived class for which the vftable is currently being built.
  1970. ThunksMapTy Thunks;
  1971. /// AddThunk - Add a thunk for the given method.
  1972. void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
  1973. SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
  1974. // Check if we have this thunk already.
  1975. if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
  1976. ThunksVector.end())
  1977. return;
  1978. ThunksVector.push_back(Thunk);
  1979. }
  1980. /// ComputeThisOffset - Returns the 'this' argument offset for the given
  1981. /// method, relative to the beginning of the MostDerivedClass.
  1982. CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
  1983. void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
  1984. CharUnits ThisOffset, ThisAdjustment &TA);
  1985. /// AddMethod - Add a single virtual member function to the vftable
  1986. /// components vector.
  1987. void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
  1988. if (!TI.isEmpty()) {
  1989. VTableThunks[Components.size()] = TI;
  1990. AddThunk(MD, TI);
  1991. }
  1992. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1993. assert(TI.Return.isEmpty() &&
  1994. "Destructor can't have return adjustment!");
  1995. Components.push_back(VTableComponent::MakeDeletingDtor(DD));
  1996. } else {
  1997. Components.push_back(VTableComponent::MakeFunction(MD));
  1998. }
  1999. }
  2000. /// AddMethods - Add the methods of this base subobject and the relevant
  2001. /// subbases to the vftable we're currently laying out.
  2002. void AddMethods(BaseSubobject Base, unsigned BaseDepth,
  2003. const CXXRecordDecl *LastVBase,
  2004. BasesSetVectorTy &VisitedBases);
  2005. void LayoutVFTable() {
  2006. // RTTI data goes before all other entries.
  2007. if (HasRTTIComponent)
  2008. Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
  2009. BasesSetVectorTy VisitedBases;
  2010. AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, nullptr,
  2011. VisitedBases);
  2012. assert((HasRTTIComponent ? Components.size() - 1 : Components.size()) &&
  2013. "vftable can't be empty");
  2014. assert(MethodVFTableLocations.empty());
  2015. for (const auto &I : MethodInfoMap) {
  2016. const CXXMethodDecl *MD = I.first;
  2017. const MethodInfo &MI = I.second;
  2018. // Skip the methods that the MostDerivedClass didn't override
  2019. // and the entries shadowed by return adjusting thunks.
  2020. if (MD->getParent() != MostDerivedClass || MI.Shadowed)
  2021. continue;
  2022. MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
  2023. WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
  2024. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  2025. MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
  2026. } else {
  2027. MethodVFTableLocations[MD] = Loc;
  2028. }
  2029. }
  2030. }
  2031. public:
  2032. VFTableBuilder(MicrosoftVTableContext &VTables,
  2033. const CXXRecordDecl *MostDerivedClass, const VPtrInfo *Which)
  2034. : VTables(VTables),
  2035. Context(MostDerivedClass->getASTContext()),
  2036. MostDerivedClass(MostDerivedClass),
  2037. MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
  2038. WhichVFPtr(*Which),
  2039. Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
  2040. // Only include the RTTI component if we know that we will provide a
  2041. // definition of the vftable.
  2042. HasRTTIComponent = Context.getLangOpts().RTTIData &&
  2043. !MostDerivedClass->hasAttr<DLLImportAttr>() &&
  2044. MostDerivedClass->getTemplateSpecializationKind() !=
  2045. TSK_ExplicitInstantiationDeclaration;
  2046. LayoutVFTable();
  2047. if (Context.getLangOpts().DumpVTableLayouts)
  2048. dumpLayout(llvm::outs());
  2049. }
  2050. uint64_t getNumThunks() const { return Thunks.size(); }
  2051. ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
  2052. ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
  2053. method_locations_range vtable_locations() const {
  2054. return method_locations_range(MethodVFTableLocations.begin(),
  2055. MethodVFTableLocations.end());
  2056. }
  2057. uint64_t getNumVTableComponents() const { return Components.size(); }
  2058. const VTableComponent *vtable_component_begin() const {
  2059. return Components.begin();
  2060. }
  2061. const VTableComponent *vtable_component_end() const {
  2062. return Components.end();
  2063. }
  2064. VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
  2065. return VTableThunks.begin();
  2066. }
  2067. VTableThunksMapTy::const_iterator vtable_thunks_end() const {
  2068. return VTableThunks.end();
  2069. }
  2070. void dumpLayout(raw_ostream &);
  2071. };
  2072. } // end namespace
  2073. // Let's study one class hierarchy as an example:
  2074. // struct A {
  2075. // virtual void f();
  2076. // int x;
  2077. // };
  2078. //
  2079. // struct B : virtual A {
  2080. // virtual void f();
  2081. // };
  2082. //
  2083. // Record layouts:
  2084. // struct A:
  2085. // 0 | (A vftable pointer)
  2086. // 4 | int x
  2087. //
  2088. // struct B:
  2089. // 0 | (B vbtable pointer)
  2090. // 4 | struct A (virtual base)
  2091. // 4 | (A vftable pointer)
  2092. // 8 | int x
  2093. //
  2094. // Let's assume we have a pointer to the A part of an object of dynamic type B:
  2095. // B b;
  2096. // A *a = (A*)&b;
  2097. // a->f();
  2098. //
  2099. // In this hierarchy, f() belongs to the vftable of A, so B::f() expects
  2100. // "this" parameter to point at the A subobject, which is B+4.
  2101. // In the B::f() prologue, it adjusts "this" back to B by subtracting 4,
  2102. // performed as a *static* adjustment.
  2103. //
  2104. // Interesting thing happens when we alter the relative placement of A and B
  2105. // subobjects in a class:
  2106. // struct C : virtual B { };
  2107. //
  2108. // C c;
  2109. // A *a = (A*)&c;
  2110. // a->f();
  2111. //
  2112. // Respective record layout is:
  2113. // 0 | (C vbtable pointer)
  2114. // 4 | struct A (virtual base)
  2115. // 4 | (A vftable pointer)
  2116. // 8 | int x
  2117. // 12 | struct B (virtual base)
  2118. // 12 | (B vbtable pointer)
  2119. //
  2120. // The final overrider of f() in class C is still B::f(), so B+4 should be
  2121. // passed as "this" to that code. However, "a" points at B-8, so the respective
  2122. // vftable entry should hold a thunk that adds 12 to the "this" argument before
  2123. // performing a tail call to B::f().
  2124. //
  2125. // With this example in mind, we can now calculate the 'this' argument offset
  2126. // for the given method, relative to the beginning of the MostDerivedClass.
  2127. CharUnits
  2128. VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
  2129. BasesSetVectorTy Bases;
  2130. {
  2131. // Find the set of least derived bases that define the given method.
  2132. OverriddenMethodsSetTy VisitedOverriddenMethods;
  2133. auto InitialOverriddenDefinitionCollector = [&](
  2134. const CXXMethodDecl *OverriddenMD) {
  2135. if (OverriddenMD->size_overridden_methods() == 0)
  2136. Bases.insert(OverriddenMD->getParent());
  2137. // Don't recurse on this method if we've already collected it.
  2138. return VisitedOverriddenMethods.insert(OverriddenMD).second;
  2139. };
  2140. visitAllOverriddenMethods(Overrider.Method,
  2141. InitialOverriddenDefinitionCollector);
  2142. }
  2143. // If there are no overrides then 'this' is located
  2144. // in the base that defines the method.
  2145. if (Bases.size() == 0)
  2146. return Overrider.Offset;
  2147. CXXBasePaths Paths;
  2148. Overrider.Method->getParent()->lookupInBases(
  2149. [&Bases](const CXXBaseSpecifier *Specifier, CXXBasePath &) {
  2150. return Bases.count(Specifier->getType()->getAsCXXRecordDecl());
  2151. },
  2152. Paths);
  2153. // This will hold the smallest this offset among overridees of MD.
  2154. // This implies that an offset of a non-virtual base will dominate an offset
  2155. // of a virtual base to potentially reduce the number of thunks required
  2156. // in the derived classes that inherit this method.
  2157. CharUnits Ret;
  2158. bool First = true;
  2159. const ASTRecordLayout &OverriderRDLayout =
  2160. Context.getASTRecordLayout(Overrider.Method->getParent());
  2161. for (const CXXBasePath &Path : Paths) {
  2162. CharUnits ThisOffset = Overrider.Offset;
  2163. CharUnits LastVBaseOffset;
  2164. // For each path from the overrider to the parents of the overridden
  2165. // methods, traverse the path, calculating the this offset in the most
  2166. // derived class.
  2167. for (const CXXBasePathElement &Element : Path) {
  2168. QualType CurTy = Element.Base->getType();
  2169. const CXXRecordDecl *PrevRD = Element.Class,
  2170. *CurRD = CurTy->getAsCXXRecordDecl();
  2171. const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
  2172. if (Element.Base->isVirtual()) {
  2173. // The interesting things begin when you have virtual inheritance.
  2174. // The final overrider will use a static adjustment equal to the offset
  2175. // of the vbase in the final overrider class.
  2176. // For example, if the final overrider is in a vbase B of the most
  2177. // derived class and it overrides a method of the B's own vbase A,
  2178. // it uses A* as "this". In its prologue, it can cast A* to B* with
  2179. // a static offset. This offset is used regardless of the actual
  2180. // offset of A from B in the most derived class, requiring an
  2181. // this-adjusting thunk in the vftable if A and B are laid out
  2182. // differently in the most derived class.
  2183. LastVBaseOffset = ThisOffset =
  2184. Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
  2185. } else {
  2186. ThisOffset += Layout.getBaseClassOffset(CurRD);
  2187. }
  2188. }
  2189. if (isa<CXXDestructorDecl>(Overrider.Method)) {
  2190. if (LastVBaseOffset.isZero()) {
  2191. // If a "Base" class has at least one non-virtual base with a virtual
  2192. // destructor, the "Base" virtual destructor will take the address
  2193. // of the "Base" subobject as the "this" argument.
  2194. ThisOffset = Overrider.Offset;
  2195. } else {
  2196. // A virtual destructor of a virtual base takes the address of the
  2197. // virtual base subobject as the "this" argument.
  2198. ThisOffset = LastVBaseOffset;
  2199. }
  2200. }
  2201. if (Ret > ThisOffset || First) {
  2202. First = false;
  2203. Ret = ThisOffset;
  2204. }
  2205. }
  2206. assert(!First && "Method not found in the given subobject?");
  2207. return Ret;
  2208. }
  2209. // Things are getting even more complex when the "this" adjustment has to
  2210. // use a dynamic offset instead of a static one, or even two dynamic offsets.
  2211. // This is sometimes required when a virtual call happens in the middle of
  2212. // a non-most-derived class construction or destruction.
  2213. //
  2214. // Let's take a look at the following example:
  2215. // struct A {
  2216. // virtual void f();
  2217. // };
  2218. //
  2219. // void foo(A *a) { a->f(); } // Knows nothing about siblings of A.
  2220. //
  2221. // struct B : virtual A {
  2222. // virtual void f();
  2223. // B() {
  2224. // foo(this);
  2225. // }
  2226. // };
  2227. //
  2228. // struct C : virtual B {
  2229. // virtual void f();
  2230. // };
  2231. //
  2232. // Record layouts for these classes are:
  2233. // struct A
  2234. // 0 | (A vftable pointer)
  2235. //
  2236. // struct B
  2237. // 0 | (B vbtable pointer)
  2238. // 4 | (vtordisp for vbase A)
  2239. // 8 | struct A (virtual base)
  2240. // 8 | (A vftable pointer)
  2241. //
  2242. // struct C
  2243. // 0 | (C vbtable pointer)
  2244. // 4 | (vtordisp for vbase A)
  2245. // 8 | struct A (virtual base) // A precedes B!
  2246. // 8 | (A vftable pointer)
  2247. // 12 | struct B (virtual base)
  2248. // 12 | (B vbtable pointer)
  2249. //
  2250. // When one creates an object of type C, the C constructor:
  2251. // - initializes all the vbptrs, then
  2252. // - calls the A subobject constructor
  2253. // (initializes A's vfptr with an address of A vftable), then
  2254. // - calls the B subobject constructor
  2255. // (initializes A's vfptr with an address of B vftable and vtordisp for A),
  2256. // that in turn calls foo(), then
  2257. // - initializes A's vfptr with an address of C vftable and zeroes out the
  2258. // vtordisp
  2259. // FIXME: if a structor knows it belongs to MDC, why doesn't it use a vftable
  2260. // without vtordisp thunks?
  2261. // FIXME: how are vtordisp handled in the presence of nooverride/final?
  2262. //
  2263. // When foo() is called, an object with a layout of class C has a vftable
  2264. // referencing B::f() that assumes a B layout, so the "this" adjustments are
  2265. // incorrect, unless an extra adjustment is done. This adjustment is called
  2266. // "vtordisp adjustment". Vtordisp basically holds the difference between the
  2267. // actual location of a vbase in the layout class and the location assumed by
  2268. // the vftable of the class being constructed/destructed. Vtordisp is only
  2269. // needed if "this" escapes a
  2270. // structor (or we can't prove otherwise).
  2271. // [i.e. vtordisp is a dynamic adjustment for a static adjustment, which is an
  2272. // estimation of a dynamic adjustment]
  2273. //
  2274. // foo() gets a pointer to the A vbase and doesn't know anything about B or C,
  2275. // so it just passes that pointer as "this" in a virtual call.
  2276. // If there was no vtordisp, that would just dispatch to B::f().
  2277. // However, B::f() assumes B+8 is passed as "this",
  2278. // yet the pointer foo() passes along is B-4 (i.e. C+8).
  2279. // An extra adjustment is needed, so we emit a thunk into the B vftable.
  2280. // This vtordisp thunk subtracts the value of vtordisp
  2281. // from the "this" argument (-12) before making a tailcall to B::f().
  2282. //
  2283. // Let's consider an even more complex example:
  2284. // struct D : virtual B, virtual C {
  2285. // D() {
  2286. // foo(this);
  2287. // }
  2288. // };
  2289. //
  2290. // struct D
  2291. // 0 | (D vbtable pointer)
  2292. // 4 | (vtordisp for vbase A)
  2293. // 8 | struct A (virtual base) // A precedes both B and C!
  2294. // 8 | (A vftable pointer)
  2295. // 12 | struct B (virtual base) // B precedes C!
  2296. // 12 | (B vbtable pointer)
  2297. // 16 | struct C (virtual base)
  2298. // 16 | (C vbtable pointer)
  2299. //
  2300. // When D::D() calls foo(), we find ourselves in a thunk that should tailcall
  2301. // to C::f(), which assumes C+8 as its "this" parameter. This time, foo()
  2302. // passes along A, which is C-8. The A vtordisp holds
  2303. // "D.vbptr[index_of_A] - offset_of_A_in_D"
  2304. // and we statically know offset_of_A_in_D, so can get a pointer to D.
  2305. // When we know it, we can make an extra vbtable lookup to locate the C vbase
  2306. // and one extra static adjustment to calculate the expected value of C+8.
  2307. void VFTableBuilder::CalculateVtordispAdjustment(
  2308. FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
  2309. ThisAdjustment &TA) {
  2310. const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
  2311. MostDerivedClassLayout.getVBaseOffsetsMap();
  2312. const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
  2313. VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
  2314. assert(VBaseMapEntry != VBaseMap.end());
  2315. // If there's no vtordisp or the final overrider is defined in the same vbase
  2316. // as the initial declaration, we don't need any vtordisp adjustment.
  2317. if (!VBaseMapEntry->second.hasVtorDisp() ||
  2318. Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
  2319. return;
  2320. // OK, now we know we need to use a vtordisp thunk.
  2321. // The implicit vtordisp field is located right before the vbase.
  2322. CharUnits OffsetOfVBaseWithVFPtr = VBaseMapEntry->second.VBaseOffset;
  2323. TA.Virtual.Microsoft.VtordispOffset =
  2324. (OffsetOfVBaseWithVFPtr - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
  2325. // A simple vtordisp thunk will suffice if the final overrider is defined
  2326. // in either the most derived class or its non-virtual base.
  2327. if (Overrider.Method->getParent() == MostDerivedClass ||
  2328. !Overrider.VirtualBase)
  2329. return;
  2330. // Otherwise, we need to do use the dynamic offset of the final overrider
  2331. // in order to get "this" adjustment right.
  2332. TA.Virtual.Microsoft.VBPtrOffset =
  2333. (OffsetOfVBaseWithVFPtr + WhichVFPtr.NonVirtualOffset -
  2334. MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
  2335. TA.Virtual.Microsoft.VBOffsetOffset =
  2336. Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
  2337. VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
  2338. TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
  2339. }
  2340. static void GroupNewVirtualOverloads(
  2341. const CXXRecordDecl *RD,
  2342. SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
  2343. // Put the virtual methods into VirtualMethods in the proper order:
  2344. // 1) Group overloads by declaration name. New groups are added to the
  2345. // vftable in the order of their first declarations in this class
  2346. // (including overrides and non-virtual methods).
  2347. // 2) In each group, new overloads appear in the reverse order of declaration.
  2348. typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
  2349. SmallVector<MethodGroup, 10> Groups;
  2350. typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
  2351. VisitedGroupIndicesTy VisitedGroupIndices;
  2352. for (const auto *MD : RD->methods()) {
  2353. MD = MD->getCanonicalDecl();
  2354. VisitedGroupIndicesTy::iterator J;
  2355. bool Inserted;
  2356. std::tie(J, Inserted) = VisitedGroupIndices.insert(
  2357. std::make_pair(MD->getDeclName(), Groups.size()));
  2358. if (Inserted)
  2359. Groups.push_back(MethodGroup());
  2360. if (MD->isVirtual())
  2361. Groups[J->second].push_back(MD);
  2362. }
  2363. for (const MethodGroup &Group : Groups)
  2364. VirtualMethods.append(Group.rbegin(), Group.rend());
  2365. }
  2366. static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
  2367. for (const auto &B : RD->bases()) {
  2368. if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
  2369. return true;
  2370. }
  2371. return false;
  2372. }
  2373. void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
  2374. const CXXRecordDecl *LastVBase,
  2375. BasesSetVectorTy &VisitedBases) {
  2376. const CXXRecordDecl *RD = Base.getBase();
  2377. if (!RD->isPolymorphic())
  2378. return;
  2379. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2380. // See if this class expands a vftable of the base we look at, which is either
  2381. // the one defined by the vfptr base path or the primary base of the current
  2382. // class.
  2383. const CXXRecordDecl *NextBase = nullptr, *NextLastVBase = LastVBase;
  2384. CharUnits NextBaseOffset;
  2385. if (BaseDepth < WhichVFPtr.PathToBaseWithVPtr.size()) {
  2386. NextBase = WhichVFPtr.PathToBaseWithVPtr[BaseDepth];
  2387. if (isDirectVBase(NextBase, RD)) {
  2388. NextLastVBase = NextBase;
  2389. NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
  2390. } else {
  2391. NextBaseOffset =
  2392. Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
  2393. }
  2394. } else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  2395. assert(!Layout.isPrimaryBaseVirtual() &&
  2396. "No primary virtual bases in this ABI");
  2397. NextBase = PrimaryBase;
  2398. NextBaseOffset = Base.getBaseOffset();
  2399. }
  2400. if (NextBase) {
  2401. AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
  2402. NextLastVBase, VisitedBases);
  2403. if (!VisitedBases.insert(NextBase))
  2404. llvm_unreachable("Found a duplicate primary base!");
  2405. }
  2406. SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
  2407. // Put virtual methods in the proper order.
  2408. GroupNewVirtualOverloads(RD, VirtualMethods);
  2409. // Now go through all virtual member functions and add them to the current
  2410. // vftable. This is done by
  2411. // - replacing overridden methods in their existing slots, as long as they
  2412. // don't require return adjustment; calculating This adjustment if needed.
  2413. // - adding new slots for methods of the current base not present in any
  2414. // sub-bases;
  2415. // - adding new slots for methods that require Return adjustment.
  2416. // We keep track of the methods visited in the sub-bases in MethodInfoMap.
  2417. for (const CXXMethodDecl *MD : VirtualMethods) {
  2418. FinalOverriders::OverriderInfo FinalOverrider =
  2419. Overriders.getOverrider(MD, Base.getBaseOffset());
  2420. const CXXMethodDecl *FinalOverriderMD = FinalOverrider.Method;
  2421. const CXXMethodDecl *OverriddenMD =
  2422. FindNearestOverriddenMethod(MD, VisitedBases);
  2423. ThisAdjustment ThisAdjustmentOffset;
  2424. bool ReturnAdjustingThunk = false, ForceReturnAdjustmentMangling = false;
  2425. CharUnits ThisOffset = ComputeThisOffset(FinalOverrider);
  2426. ThisAdjustmentOffset.NonVirtual =
  2427. (ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
  2428. if ((OverriddenMD || FinalOverriderMD != MD) &&
  2429. WhichVFPtr.getVBaseWithVPtr())
  2430. CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
  2431. ThisAdjustmentOffset);
  2432. if (OverriddenMD) {
  2433. // If MD overrides anything in this vftable, we need to update the
  2434. // entries.
  2435. MethodInfoMapTy::iterator OverriddenMDIterator =
  2436. MethodInfoMap.find(OverriddenMD);
  2437. // If the overridden method went to a different vftable, skip it.
  2438. if (OverriddenMDIterator == MethodInfoMap.end())
  2439. continue;
  2440. MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
  2441. // Let's check if the overrider requires any return adjustments.
  2442. // We must create a new slot if the MD's return type is not trivially
  2443. // convertible to the OverriddenMD's one.
  2444. // Once a chain of method overrides adds a return adjusting vftable slot,
  2445. // all subsequent overrides will also use an extra method slot.
  2446. ReturnAdjustingThunk = !ComputeReturnAdjustmentBaseOffset(
  2447. Context, MD, OverriddenMD).isEmpty() ||
  2448. OverriddenMethodInfo.UsesExtraSlot;
  2449. if (!ReturnAdjustingThunk) {
  2450. // No return adjustment needed - just replace the overridden method info
  2451. // with the current info.
  2452. MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
  2453. OverriddenMethodInfo.VFTableIndex);
  2454. MethodInfoMap.erase(OverriddenMDIterator);
  2455. assert(!MethodInfoMap.count(MD) &&
  2456. "Should not have method info for this method yet!");
  2457. MethodInfoMap.insert(std::make_pair(MD, MI));
  2458. continue;
  2459. }
  2460. // In case we need a return adjustment, we'll add a new slot for
  2461. // the overrider. Mark the overriden method as shadowed by the new slot.
  2462. OverriddenMethodInfo.Shadowed = true;
  2463. // Force a special name mangling for a return-adjusting thunk
  2464. // unless the method is the final overrider without this adjustment.
  2465. ForceReturnAdjustmentMangling =
  2466. !(MD == FinalOverriderMD && ThisAdjustmentOffset.isEmpty());
  2467. } else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
  2468. MD->size_overridden_methods()) {
  2469. // Skip methods that don't belong to the vftable of the current class,
  2470. // e.g. each method that wasn't seen in any of the visited sub-bases
  2471. // but overrides multiple methods of other sub-bases.
  2472. continue;
  2473. }
  2474. // If we got here, MD is a method not seen in any of the sub-bases or
  2475. // it requires return adjustment. Insert the method info for this method.
  2476. unsigned VBIndex =
  2477. LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
  2478. MethodInfo MI(VBIndex,
  2479. HasRTTIComponent ? Components.size() - 1 : Components.size(),
  2480. ReturnAdjustingThunk);
  2481. assert(!MethodInfoMap.count(MD) &&
  2482. "Should not have method info for this method yet!");
  2483. MethodInfoMap.insert(std::make_pair(MD, MI));
  2484. // Check if this overrider needs a return adjustment.
  2485. // We don't want to do this for pure virtual member functions.
  2486. BaseOffset ReturnAdjustmentOffset;
  2487. ReturnAdjustment ReturnAdjustment;
  2488. if (!FinalOverriderMD->isPure()) {
  2489. ReturnAdjustmentOffset =
  2490. ComputeReturnAdjustmentBaseOffset(Context, FinalOverriderMD, MD);
  2491. }
  2492. if (!ReturnAdjustmentOffset.isEmpty()) {
  2493. ForceReturnAdjustmentMangling = true;
  2494. ReturnAdjustment.NonVirtual =
  2495. ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
  2496. if (ReturnAdjustmentOffset.VirtualBase) {
  2497. const ASTRecordLayout &DerivedLayout =
  2498. Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
  2499. ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
  2500. DerivedLayout.getVBPtrOffset().getQuantity();
  2501. ReturnAdjustment.Virtual.Microsoft.VBIndex =
  2502. VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
  2503. ReturnAdjustmentOffset.VirtualBase);
  2504. }
  2505. }
  2506. AddMethod(FinalOverriderMD,
  2507. ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
  2508. ForceReturnAdjustmentMangling ? MD : nullptr));
  2509. }
  2510. }
  2511. static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
  2512. for (const CXXRecordDecl *Elem :
  2513. llvm::make_range(Path.rbegin(), Path.rend())) {
  2514. Out << "'";
  2515. Elem->printQualifiedName(Out);
  2516. Out << "' in ";
  2517. }
  2518. }
  2519. static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
  2520. bool ContinueFirstLine) {
  2521. const ReturnAdjustment &R = TI.Return;
  2522. bool Multiline = false;
  2523. const char *LinePrefix = "\n ";
  2524. if (!R.isEmpty() || TI.Method) {
  2525. if (!ContinueFirstLine)
  2526. Out << LinePrefix;
  2527. Out << "[return adjustment (to type '"
  2528. << TI.Method->getReturnType().getCanonicalType().getAsString()
  2529. << "'): ";
  2530. if (R.Virtual.Microsoft.VBPtrOffset)
  2531. Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
  2532. if (R.Virtual.Microsoft.VBIndex)
  2533. Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
  2534. Out << R.NonVirtual << " non-virtual]";
  2535. Multiline = true;
  2536. }
  2537. const ThisAdjustment &T = TI.This;
  2538. if (!T.isEmpty()) {
  2539. if (Multiline || !ContinueFirstLine)
  2540. Out << LinePrefix;
  2541. Out << "[this adjustment: ";
  2542. if (!TI.This.Virtual.isEmpty()) {
  2543. assert(T.Virtual.Microsoft.VtordispOffset < 0);
  2544. Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
  2545. if (T.Virtual.Microsoft.VBPtrOffset) {
  2546. Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
  2547. << " to the left,";
  2548. assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
  2549. Out << LinePrefix << " vboffset at "
  2550. << T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
  2551. }
  2552. }
  2553. Out << T.NonVirtual << " non-virtual]";
  2554. }
  2555. }
  2556. void VFTableBuilder::dumpLayout(raw_ostream &Out) {
  2557. Out << "VFTable for ";
  2558. PrintBasePath(WhichVFPtr.PathToBaseWithVPtr, Out);
  2559. Out << "'";
  2560. MostDerivedClass->printQualifiedName(Out);
  2561. Out << "' (" << Components.size()
  2562. << (Components.size() == 1 ? " entry" : " entries") << ").\n";
  2563. for (unsigned I = 0, E = Components.size(); I != E; ++I) {
  2564. Out << llvm::format("%4d | ", I);
  2565. const VTableComponent &Component = Components[I];
  2566. // Dump the component.
  2567. switch (Component.getKind()) {
  2568. case VTableComponent::CK_RTTI:
  2569. Component.getRTTIDecl()->printQualifiedName(Out);
  2570. Out << " RTTI";
  2571. break;
  2572. case VTableComponent::CK_FunctionPointer: {
  2573. const CXXMethodDecl *MD = Component.getFunctionDecl();
  2574. // FIXME: Figure out how to print the real thunk type, since they can
  2575. // differ in the return type.
  2576. std::string Str = PredefinedExpr::ComputeName(
  2577. PredefinedExpr::PrettyFunctionNoVirtual, MD);
  2578. Out << Str;
  2579. if (MD->isPure())
  2580. Out << " [pure]";
  2581. if (MD->isDeleted())
  2582. Out << " [deleted]";
  2583. ThunkInfo Thunk = VTableThunks.lookup(I);
  2584. if (!Thunk.isEmpty())
  2585. dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
  2586. break;
  2587. }
  2588. case VTableComponent::CK_DeletingDtorPointer: {
  2589. const CXXDestructorDecl *DD = Component.getDestructorDecl();
  2590. DD->printQualifiedName(Out);
  2591. Out << "() [scalar deleting]";
  2592. if (DD->isPure())
  2593. Out << " [pure]";
  2594. ThunkInfo Thunk = VTableThunks.lookup(I);
  2595. if (!Thunk.isEmpty()) {
  2596. assert(Thunk.Return.isEmpty() &&
  2597. "No return adjustment needed for destructors!");
  2598. dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/false);
  2599. }
  2600. break;
  2601. }
  2602. default:
  2603. DiagnosticsEngine &Diags = Context.getDiagnostics();
  2604. unsigned DiagID = Diags.getCustomDiagID(
  2605. DiagnosticsEngine::Error,
  2606. "Unexpected vftable component type %0 for component number %1");
  2607. Diags.Report(MostDerivedClass->getLocation(), DiagID)
  2608. << I << Component.getKind();
  2609. }
  2610. Out << '\n';
  2611. }
  2612. Out << '\n';
  2613. if (!Thunks.empty()) {
  2614. // We store the method names in a map to get a stable order.
  2615. std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
  2616. for (const auto &I : Thunks) {
  2617. const CXXMethodDecl *MD = I.first;
  2618. std::string MethodName = PredefinedExpr::ComputeName(
  2619. PredefinedExpr::PrettyFunctionNoVirtual, MD);
  2620. MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
  2621. }
  2622. for (const auto &MethodNameAndDecl : MethodNamesAndDecls) {
  2623. const std::string &MethodName = MethodNameAndDecl.first;
  2624. const CXXMethodDecl *MD = MethodNameAndDecl.second;
  2625. ThunkInfoVectorTy ThunksVector = Thunks[MD];
  2626. std::stable_sort(ThunksVector.begin(), ThunksVector.end(),
  2627. [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
  2628. // Keep different thunks with the same adjustments in the order they
  2629. // were put into the vector.
  2630. return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
  2631. });
  2632. Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
  2633. Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
  2634. for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
  2635. const ThunkInfo &Thunk = ThunksVector[I];
  2636. Out << llvm::format("%4d | ", I);
  2637. dumpMicrosoftThunkAdjustment(Thunk, Out, /*ContinueFirstLine=*/true);
  2638. Out << '\n';
  2639. }
  2640. Out << '\n';
  2641. }
  2642. }
  2643. Out.flush();
  2644. }
  2645. static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
  2646. ArrayRef<const CXXRecordDecl *> B) {
  2647. for (const CXXRecordDecl *Decl : B) {
  2648. if (A.count(Decl))
  2649. return true;
  2650. }
  2651. return false;
  2652. }
  2653. static bool rebucketPaths(VPtrInfoVector &Paths);
  2654. /// Produces MSVC-compatible vbtable data. The symbols produced by this
  2655. /// algorithm match those produced by MSVC 2012 and newer, which is different
  2656. /// from MSVC 2010.
  2657. ///
  2658. /// MSVC 2012 appears to minimize the vbtable names using the following
  2659. /// algorithm. First, walk the class hierarchy in the usual order, depth first,
  2660. /// left to right, to find all of the subobjects which contain a vbptr field.
  2661. /// Visiting each class node yields a list of inheritance paths to vbptrs. Each
  2662. /// record with a vbptr creates an initially empty path.
  2663. ///
  2664. /// To combine paths from child nodes, the paths are compared to check for
  2665. /// ambiguity. Paths are "ambiguous" if multiple paths have the same set of
  2666. /// components in the same order. Each group of ambiguous paths is extended by
  2667. /// appending the class of the base from which it came. If the current class
  2668. /// node produced an ambiguous path, its path is extended with the current class.
  2669. /// After extending paths, MSVC again checks for ambiguity, and extends any
  2670. /// ambiguous path which wasn't already extended. Because each node yields an
  2671. /// unambiguous set of paths, MSVC doesn't need to extend any path more than once
  2672. /// to produce an unambiguous set of paths.
  2673. ///
  2674. /// TODO: Presumably vftables use the same algorithm.
  2675. void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
  2676. const CXXRecordDecl *RD,
  2677. VPtrInfoVector &Paths) {
  2678. assert(Paths.empty());
  2679. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2680. // Base case: this subobject has its own vptr.
  2681. if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
  2682. Paths.push_back(new VPtrInfo(RD));
  2683. // Recursive case: get all the vbtables from our bases and remove anything
  2684. // that shares a virtual base.
  2685. llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
  2686. for (const auto &B : RD->bases()) {
  2687. const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
  2688. if (B.isVirtual() && VBasesSeen.count(Base))
  2689. continue;
  2690. if (!Base->isDynamicClass())
  2691. continue;
  2692. const VPtrInfoVector &BasePaths =
  2693. ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
  2694. for (VPtrInfo *BaseInfo : BasePaths) {
  2695. // Don't include the path if it goes through a virtual base that we've
  2696. // already included.
  2697. if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
  2698. continue;
  2699. // Copy the path and adjust it as necessary.
  2700. VPtrInfo *P = new VPtrInfo(*BaseInfo);
  2701. // We mangle Base into the path if the path would've been ambiguous and it
  2702. // wasn't already extended with Base.
  2703. if (P->MangledPath.empty() || P->MangledPath.back() != Base)
  2704. P->NextBaseToMangle = Base;
  2705. // Keep track of which vtable the derived class is going to extend with
  2706. // new methods or bases. We append to either the vftable of our primary
  2707. // base, or the first non-virtual base that has a vbtable.
  2708. if (P->ReusingBase == Base &&
  2709. Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
  2710. : Layout.getPrimaryBase()))
  2711. P->ReusingBase = RD;
  2712. // Keep track of the full adjustment from the MDC to this vtable. The
  2713. // adjustment is captured by an optional vbase and a non-virtual offset.
  2714. if (B.isVirtual())
  2715. P->ContainingVBases.push_back(Base);
  2716. else if (P->ContainingVBases.empty())
  2717. P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
  2718. // Update the full offset in the MDC.
  2719. P->FullOffsetInMDC = P->NonVirtualOffset;
  2720. if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
  2721. P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
  2722. Paths.push_back(P);
  2723. }
  2724. if (B.isVirtual())
  2725. VBasesSeen.insert(Base);
  2726. // After visiting any direct base, we've transitively visited all of its
  2727. // morally virtual bases.
  2728. for (const auto &VB : Base->vbases())
  2729. VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
  2730. }
  2731. // Sort the paths into buckets, and if any of them are ambiguous, extend all
  2732. // paths in ambiguous buckets.
  2733. bool Changed = true;
  2734. while (Changed)
  2735. Changed = rebucketPaths(Paths);
  2736. }
  2737. static bool extendPath(VPtrInfo *P) {
  2738. if (P->NextBaseToMangle) {
  2739. P->MangledPath.push_back(P->NextBaseToMangle);
  2740. P->NextBaseToMangle = nullptr;// Prevent the path from being extended twice.
  2741. return true;
  2742. }
  2743. return false;
  2744. }
  2745. static bool rebucketPaths(VPtrInfoVector &Paths) {
  2746. // What we're essentially doing here is bucketing together ambiguous paths.
  2747. // Any bucket with more than one path in it gets extended by NextBase, which
  2748. // is usually the direct base of the inherited the vbptr. This code uses a
  2749. // sorted vector to implement a multiset to form the buckets. Note that the
  2750. // ordering is based on pointers, but it doesn't change our output order. The
  2751. // current algorithm is designed to match MSVC 2012's names.
  2752. VPtrInfoVector PathsSorted(Paths);
  2753. std::sort(PathsSorted.begin(), PathsSorted.end(),
  2754. [](const VPtrInfo *LHS, const VPtrInfo *RHS) {
  2755. return LHS->MangledPath < RHS->MangledPath;
  2756. });
  2757. bool Changed = false;
  2758. for (size_t I = 0, E = PathsSorted.size(); I != E;) {
  2759. // Scan forward to find the end of the bucket.
  2760. size_t BucketStart = I;
  2761. do {
  2762. ++I;
  2763. } while (I != E && PathsSorted[BucketStart]->MangledPath ==
  2764. PathsSorted[I]->MangledPath);
  2765. // If this bucket has multiple paths, extend them all.
  2766. if (I - BucketStart > 1) {
  2767. for (size_t II = BucketStart; II != I; ++II)
  2768. Changed |= extendPath(PathsSorted[II]);
  2769. assert(Changed && "no paths were extended to fix ambiguity");
  2770. }
  2771. }
  2772. return Changed;
  2773. }
  2774. MicrosoftVTableContext::~MicrosoftVTableContext() {
  2775. for (auto &P : VFPtrLocations)
  2776. llvm::DeleteContainerPointers(*P.second);
  2777. llvm::DeleteContainerSeconds(VFPtrLocations);
  2778. llvm::DeleteContainerSeconds(VFTableLayouts);
  2779. llvm::DeleteContainerSeconds(VBaseInfo);
  2780. }
  2781. namespace {
  2782. typedef llvm::SetVector<BaseSubobject, std::vector<BaseSubobject>,
  2783. llvm::DenseSet<BaseSubobject>> FullPathTy;
  2784. }
  2785. // This recursive function finds all paths from a subobject centered at
  2786. // (RD, Offset) to the subobject located at BaseWithVPtr.
  2787. static void findPathsToSubobject(ASTContext &Context,
  2788. const ASTRecordLayout &MostDerivedLayout,
  2789. const CXXRecordDecl *RD, CharUnits Offset,
  2790. BaseSubobject BaseWithVPtr,
  2791. FullPathTy &FullPath,
  2792. std::list<FullPathTy> &Paths) {
  2793. if (BaseSubobject(RD, Offset) == BaseWithVPtr) {
  2794. Paths.push_back(FullPath);
  2795. return;
  2796. }
  2797. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2798. for (const CXXBaseSpecifier &BS : RD->bases()) {
  2799. const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
  2800. CharUnits NewOffset = BS.isVirtual()
  2801. ? MostDerivedLayout.getVBaseClassOffset(Base)
  2802. : Offset + Layout.getBaseClassOffset(Base);
  2803. FullPath.insert(BaseSubobject(Base, NewOffset));
  2804. findPathsToSubobject(Context, MostDerivedLayout, Base, NewOffset,
  2805. BaseWithVPtr, FullPath, Paths);
  2806. FullPath.pop_back();
  2807. }
  2808. }
  2809. // Return the paths which are not subsets of other paths.
  2810. static void removeRedundantPaths(std::list<FullPathTy> &FullPaths) {
  2811. FullPaths.remove_if([&](const FullPathTy &SpecificPath) {
  2812. for (const FullPathTy &OtherPath : FullPaths) {
  2813. if (&SpecificPath == &OtherPath)
  2814. continue;
  2815. if (std::all_of(SpecificPath.begin(), SpecificPath.end(),
  2816. [&](const BaseSubobject &BSO) {
  2817. return OtherPath.count(BSO) != 0;
  2818. })) {
  2819. return true;
  2820. }
  2821. }
  2822. return false;
  2823. });
  2824. }
  2825. static CharUnits getOffsetOfFullPath(ASTContext &Context,
  2826. const CXXRecordDecl *RD,
  2827. const FullPathTy &FullPath) {
  2828. const ASTRecordLayout &MostDerivedLayout =
  2829. Context.getASTRecordLayout(RD);
  2830. CharUnits Offset = CharUnits::fromQuantity(-1);
  2831. for (const BaseSubobject &BSO : FullPath) {
  2832. const CXXRecordDecl *Base = BSO.getBase();
  2833. // The first entry in the path is always the most derived record, skip it.
  2834. if (Base == RD) {
  2835. assert(Offset.getQuantity() == -1);
  2836. Offset = CharUnits::Zero();
  2837. continue;
  2838. }
  2839. assert(Offset.getQuantity() != -1);
  2840. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2841. // While we know which base has to be traversed, we don't know if that base
  2842. // was a virtual base.
  2843. const CXXBaseSpecifier *BaseBS = std::find_if(
  2844. RD->bases_begin(), RD->bases_end(), [&](const CXXBaseSpecifier &BS) {
  2845. return BS.getType()->getAsCXXRecordDecl() == Base;
  2846. });
  2847. Offset = BaseBS->isVirtual() ? MostDerivedLayout.getVBaseClassOffset(Base)
  2848. : Offset + Layout.getBaseClassOffset(Base);
  2849. RD = Base;
  2850. }
  2851. return Offset;
  2852. }
  2853. // We want to select the path which introduces the most covariant overrides. If
  2854. // two paths introduce overrides which the other path doesn't contain, issue a
  2855. // diagnostic.
  2856. static const FullPathTy *selectBestPath(ASTContext &Context,
  2857. const CXXRecordDecl *RD, VPtrInfo *Info,
  2858. std::list<FullPathTy> &FullPaths) {
  2859. // Handle some easy cases first.
  2860. if (FullPaths.empty())
  2861. return nullptr;
  2862. if (FullPaths.size() == 1)
  2863. return &FullPaths.front();
  2864. const FullPathTy *BestPath = nullptr;
  2865. typedef std::set<const CXXMethodDecl *> OverriderSetTy;
  2866. OverriderSetTy LastOverrides;
  2867. for (const FullPathTy &SpecificPath : FullPaths) {
  2868. assert(!SpecificPath.empty());
  2869. OverriderSetTy CurrentOverrides;
  2870. const CXXRecordDecl *TopLevelRD = SpecificPath.begin()->getBase();
  2871. // Find the distance from the start of the path to the subobject with the
  2872. // VPtr.
  2873. CharUnits BaseOffset =
  2874. getOffsetOfFullPath(Context, TopLevelRD, SpecificPath);
  2875. FinalOverriders Overriders(TopLevelRD, CharUnits::Zero(), TopLevelRD);
  2876. for (const CXXMethodDecl *MD : Info->BaseWithVPtr->methods()) {
  2877. if (!MD->isVirtual())
  2878. continue;
  2879. FinalOverriders::OverriderInfo OI =
  2880. Overriders.getOverrider(MD->getCanonicalDecl(), BaseOffset);
  2881. const CXXMethodDecl *OverridingMethod = OI.Method;
  2882. // Only overriders which have a return adjustment introduce problematic
  2883. // thunks.
  2884. if (ComputeReturnAdjustmentBaseOffset(Context, OverridingMethod, MD)
  2885. .isEmpty())
  2886. continue;
  2887. // It's possible that the overrider isn't in this path. If so, skip it
  2888. // because this path didn't introduce it.
  2889. const CXXRecordDecl *OverridingParent = OverridingMethod->getParent();
  2890. if (std::none_of(SpecificPath.begin(), SpecificPath.end(),
  2891. [&](const BaseSubobject &BSO) {
  2892. return BSO.getBase() == OverridingParent;
  2893. }))
  2894. continue;
  2895. CurrentOverrides.insert(OverridingMethod);
  2896. }
  2897. OverriderSetTy NewOverrides =
  2898. llvm::set_difference(CurrentOverrides, LastOverrides);
  2899. if (NewOverrides.empty())
  2900. continue;
  2901. OverriderSetTy MissingOverrides =
  2902. llvm::set_difference(LastOverrides, CurrentOverrides);
  2903. if (MissingOverrides.empty()) {
  2904. // This path is a strict improvement over the last path, let's use it.
  2905. BestPath = &SpecificPath;
  2906. std::swap(CurrentOverrides, LastOverrides);
  2907. } else {
  2908. // This path introduces an overrider with a conflicting covariant thunk.
  2909. DiagnosticsEngine &Diags = Context.getDiagnostics();
  2910. const CXXMethodDecl *CovariantMD = *NewOverrides.begin();
  2911. const CXXMethodDecl *ConflictMD = *MissingOverrides.begin();
  2912. Diags.Report(RD->getLocation(), diag::err_vftable_ambiguous_component)
  2913. << RD;
  2914. Diags.Report(CovariantMD->getLocation(), diag::note_covariant_thunk)
  2915. << CovariantMD;
  2916. Diags.Report(ConflictMD->getLocation(), diag::note_covariant_thunk)
  2917. << ConflictMD;
  2918. }
  2919. }
  2920. // Go with the path that introduced the most covariant overrides. If there is
  2921. // no such path, pick the first path.
  2922. return BestPath ? BestPath : &FullPaths.front();
  2923. }
  2924. static void computeFullPathsForVFTables(ASTContext &Context,
  2925. const CXXRecordDecl *RD,
  2926. VPtrInfoVector &Paths) {
  2927. const ASTRecordLayout &MostDerivedLayout = Context.getASTRecordLayout(RD);
  2928. FullPathTy FullPath;
  2929. std::list<FullPathTy> FullPaths;
  2930. for (VPtrInfo *Info : Paths) {
  2931. findPathsToSubobject(
  2932. Context, MostDerivedLayout, RD, CharUnits::Zero(),
  2933. BaseSubobject(Info->BaseWithVPtr, Info->FullOffsetInMDC), FullPath,
  2934. FullPaths);
  2935. FullPath.clear();
  2936. removeRedundantPaths(FullPaths);
  2937. Info->PathToBaseWithVPtr.clear();
  2938. if (const FullPathTy *BestPath =
  2939. selectBestPath(Context, RD, Info, FullPaths))
  2940. for (const BaseSubobject &BSO : *BestPath)
  2941. Info->PathToBaseWithVPtr.push_back(BSO.getBase());
  2942. FullPaths.clear();
  2943. }
  2944. }
  2945. void MicrosoftVTableContext::computeVTableRelatedInformation(
  2946. const CXXRecordDecl *RD) {
  2947. assert(RD->isDynamicClass());
  2948. // Check if we've computed this information before.
  2949. if (VFPtrLocations.count(RD))
  2950. return;
  2951. const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
  2952. VPtrInfoVector *VFPtrs = new VPtrInfoVector();
  2953. computeVTablePaths(/*ForVBTables=*/false, RD, *VFPtrs);
  2954. computeFullPathsForVFTables(Context, RD, *VFPtrs);
  2955. VFPtrLocations[RD] = VFPtrs;
  2956. MethodVFTableLocationsTy NewMethodLocations;
  2957. for (const VPtrInfo *VFPtr : *VFPtrs) {
  2958. VFTableBuilder Builder(*this, RD, VFPtr);
  2959. VFTableIdTy id(RD, VFPtr->FullOffsetInMDC);
  2960. assert(VFTableLayouts.count(id) == 0);
  2961. SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
  2962. Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
  2963. VFTableLayouts[id] = new VTableLayout(
  2964. Builder.getNumVTableComponents(), Builder.vtable_component_begin(),
  2965. VTableThunks.size(), VTableThunks.data(), EmptyAddressPointsMap, true);
  2966. Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
  2967. for (const auto &Loc : Builder.vtable_locations()) {
  2968. GlobalDecl GD = Loc.first;
  2969. MethodVFTableLocation NewLoc = Loc.second;
  2970. auto M = NewMethodLocations.find(GD);
  2971. if (M == NewMethodLocations.end() || NewLoc < M->second)
  2972. NewMethodLocations[GD] = NewLoc;
  2973. }
  2974. }
  2975. MethodVFTableLocations.insert(NewMethodLocations.begin(),
  2976. NewMethodLocations.end());
  2977. if (Context.getLangOpts().DumpVTableLayouts)
  2978. dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
  2979. }
  2980. void MicrosoftVTableContext::dumpMethodLocations(
  2981. const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
  2982. raw_ostream &Out) {
  2983. // Compute the vtable indices for all the member functions.
  2984. // Store them in a map keyed by the location so we'll get a sorted table.
  2985. std::map<MethodVFTableLocation, std::string> IndicesMap;
  2986. bool HasNonzeroOffset = false;
  2987. for (const auto &I : NewMethods) {
  2988. const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I.first.getDecl());
  2989. assert(MD->isVirtual());
  2990. std::string MethodName = PredefinedExpr::ComputeName(
  2991. PredefinedExpr::PrettyFunctionNoVirtual, MD);
  2992. if (isa<CXXDestructorDecl>(MD)) {
  2993. IndicesMap[I.second] = MethodName + " [scalar deleting]";
  2994. } else {
  2995. IndicesMap[I.second] = MethodName;
  2996. }
  2997. if (!I.second.VFPtrOffset.isZero() || I.second.VBTableIndex != 0)
  2998. HasNonzeroOffset = true;
  2999. }
  3000. // Print the vtable indices for all the member functions.
  3001. if (!IndicesMap.empty()) {
  3002. Out << "VFTable indices for ";
  3003. Out << "'";
  3004. RD->printQualifiedName(Out);
  3005. Out << "' (" << IndicesMap.size()
  3006. << (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
  3007. CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
  3008. uint64_t LastVBIndex = 0;
  3009. for (const auto &I : IndicesMap) {
  3010. CharUnits VFPtrOffset = I.first.VFPtrOffset;
  3011. uint64_t VBIndex = I.first.VBTableIndex;
  3012. if (HasNonzeroOffset &&
  3013. (VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
  3014. assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
  3015. Out << " -- accessible via ";
  3016. if (VBIndex)
  3017. Out << "vbtable index " << VBIndex << ", ";
  3018. Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
  3019. LastVFPtrOffset = VFPtrOffset;
  3020. LastVBIndex = VBIndex;
  3021. }
  3022. uint64_t VTableIndex = I.first.Index;
  3023. const std::string &MethodName = I.second;
  3024. Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
  3025. }
  3026. Out << '\n';
  3027. }
  3028. Out.flush();
  3029. }
  3030. const VirtualBaseInfo *MicrosoftVTableContext::computeVBTableRelatedInformation(
  3031. const CXXRecordDecl *RD) {
  3032. VirtualBaseInfo *VBI;
  3033. {
  3034. // Get or create a VBI for RD. Don't hold a reference to the DenseMap cell,
  3035. // as it may be modified and rehashed under us.
  3036. VirtualBaseInfo *&Entry = VBaseInfo[RD];
  3037. if (Entry)
  3038. return Entry;
  3039. Entry = VBI = new VirtualBaseInfo();
  3040. }
  3041. computeVTablePaths(/*ForVBTables=*/true, RD, VBI->VBPtrPaths);
  3042. // First, see if the Derived class shared the vbptr with a non-virtual base.
  3043. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  3044. if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
  3045. // If the Derived class shares the vbptr with a non-virtual base, the shared
  3046. // virtual bases come first so that the layout is the same.
  3047. const VirtualBaseInfo *BaseInfo =
  3048. computeVBTableRelatedInformation(VBPtrBase);
  3049. VBI->VBTableIndices.insert(BaseInfo->VBTableIndices.begin(),
  3050. BaseInfo->VBTableIndices.end());
  3051. }
  3052. // New vbases are added to the end of the vbtable.
  3053. // Skip the self entry and vbases visited in the non-virtual base, if any.
  3054. unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
  3055. for (const auto &VB : RD->vbases()) {
  3056. const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
  3057. if (!VBI->VBTableIndices.count(CurVBase))
  3058. VBI->VBTableIndices[CurVBase] = VBTableIndex++;
  3059. }
  3060. return VBI;
  3061. }
  3062. unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
  3063. const CXXRecordDecl *VBase) {
  3064. const VirtualBaseInfo *VBInfo = computeVBTableRelatedInformation(Derived);
  3065. assert(VBInfo->VBTableIndices.count(VBase));
  3066. return VBInfo->VBTableIndices.find(VBase)->second;
  3067. }
  3068. const VPtrInfoVector &
  3069. MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
  3070. return computeVBTableRelatedInformation(RD)->VBPtrPaths;
  3071. }
  3072. const VPtrInfoVector &
  3073. MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
  3074. computeVTableRelatedInformation(RD);
  3075. assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
  3076. return *VFPtrLocations[RD];
  3077. }
  3078. const VTableLayout &
  3079. MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
  3080. CharUnits VFPtrOffset) {
  3081. computeVTableRelatedInformation(RD);
  3082. VFTableIdTy id(RD, VFPtrOffset);
  3083. assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
  3084. return *VFTableLayouts[id];
  3085. }
  3086. const MicrosoftVTableContext::MethodVFTableLocation &
  3087. MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
  3088. assert(cast<CXXMethodDecl>(GD.getDecl())->isVirtual() &&
  3089. "Only use this method for virtual methods or dtors");
  3090. if (isa<CXXDestructorDecl>(GD.getDecl()))
  3091. assert(GD.getDtorType() == Dtor_Deleting);
  3092. MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
  3093. if (I != MethodVFTableLocations.end())
  3094. return I->second;
  3095. const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  3096. computeVTableRelatedInformation(RD);
  3097. I = MethodVFTableLocations.find(GD);
  3098. assert(I != MethodVFTableLocations.end() && "Did not find index!");
  3099. return I->second;
  3100. }