VTableBuilder.cpp 140 KB

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