VTableBuilder.cpp 141 KB

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