CGVTables.cpp 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070
  1. //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code dealing with C++ code generation of virtual tables.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CodeGenFunction.h"
  15. #include "CGCXXABI.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/RecordLayout.h"
  18. #include "clang/Frontend/CodeGenOptions.h"
  19. #include "llvm/ADT/DenseSet.h"
  20. #include "llvm/ADT/SetVector.h"
  21. #include "llvm/Support/Compiler.h"
  22. #include "llvm/Support/Format.h"
  23. #include <algorithm>
  24. #include <cstdio>
  25. using namespace clang;
  26. using namespace CodeGen;
  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 a virtual base class, this holds its declaration.
  35. const CXXRecordDecl *VirtualBase;
  36. /// NonVirtualOffset - The offset from the derived class to the base class.
  37. /// (Or the offset from the virtual base class to the base class, if the
  38. /// path from the derived class to the base class involves a virtual base
  39. /// class.
  40. int64_t NonVirtualOffset;
  41. BaseOffset() : DerivedClass(0), VirtualBase(0), NonVirtualOffset(0) { }
  42. BaseOffset(const CXXRecordDecl *DerivedClass,
  43. const CXXRecordDecl *VirtualBase, int64_t NonVirtualOffset)
  44. : DerivedClass(DerivedClass), VirtualBase(VirtualBase),
  45. NonVirtualOffset(NonVirtualOffset) { }
  46. bool isEmpty() const { return !NonVirtualOffset && !VirtualBase; }
  47. };
  48. /// FinalOverriders - Contains the final overrider member functions for all
  49. /// member functions in the base subobjects of a class.
  50. class FinalOverriders {
  51. public:
  52. /// OverriderInfo - Information about a final overrider.
  53. struct OverriderInfo {
  54. /// Method - The method decl of the overrider.
  55. const CXXMethodDecl *Method;
  56. /// Offset - the base offset of the overrider in the layout class.
  57. uint64_t Offset;
  58. OverriderInfo() : Method(0), Offset(0) { }
  59. };
  60. private:
  61. /// MostDerivedClass - The most derived class for which the final overriders
  62. /// are stored.
  63. const CXXRecordDecl *MostDerivedClass;
  64. /// MostDerivedClassOffset - If we're building final overriders for a
  65. /// construction vtable, this holds the offset from the layout class to the
  66. /// most derived class.
  67. const uint64_t MostDerivedClassOffset;
  68. /// LayoutClass - The class we're using for layout information. Will be
  69. /// different than the most derived class if the final overriders are for a
  70. /// construction vtable.
  71. const CXXRecordDecl *LayoutClass;
  72. ASTContext &Context;
  73. /// MostDerivedClassLayout - the AST record layout of the most derived class.
  74. const ASTRecordLayout &MostDerivedClassLayout;
  75. /// MethodBaseOffsetPairTy - Uniquely identifies a member function
  76. /// in a base subobject.
  77. typedef std::pair<const CXXMethodDecl *, uint64_t> MethodBaseOffsetPairTy;
  78. typedef llvm::DenseMap<MethodBaseOffsetPairTy,
  79. OverriderInfo> OverridersMapTy;
  80. /// OverridersMap - The final overriders for all virtual member functions of
  81. /// all the base subobjects of the most derived class.
  82. OverridersMapTy OverridersMap;
  83. /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented
  84. /// as a record decl and a subobject number) and its offsets in the most
  85. /// derived class as well as the layout class.
  86. typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
  87. uint64_t> SubobjectOffsetMapTy;
  88. typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
  89. /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the
  90. /// given base.
  91. void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
  92. uint64_t OffsetInLayoutClass,
  93. SubobjectOffsetMapTy &SubobjectOffsets,
  94. SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
  95. SubobjectCountMapTy &SubobjectCounts);
  96. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  97. /// dump - dump the final overriders for a base subobject, and all its direct
  98. /// and indirect base subobjects.
  99. void dump(llvm::raw_ostream &Out, BaseSubobject Base,
  100. VisitedVirtualBasesSetTy& VisitedVirtualBases);
  101. public:
  102. FinalOverriders(const CXXRecordDecl *MostDerivedClass,
  103. uint64_t MostDerivedClassOffset,
  104. const CXXRecordDecl *LayoutClass);
  105. /// getOverrider - Get the final overrider for the given method declaration in
  106. /// the subobject with the given base offset.
  107. OverriderInfo getOverrider(const CXXMethodDecl *MD,
  108. uint64_t BaseOffset) const {
  109. assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
  110. "Did not find overrider!");
  111. return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
  112. }
  113. /// dump - dump the final overriders.
  114. void dump() {
  115. VisitedVirtualBasesSetTy VisitedVirtualBases;
  116. dump(llvm::errs(), BaseSubobject(MostDerivedClass, 0), VisitedVirtualBases);
  117. }
  118. };
  119. #define DUMP_OVERRIDERS 0
  120. FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
  121. uint64_t MostDerivedClassOffset,
  122. const CXXRecordDecl *LayoutClass)
  123. : MostDerivedClass(MostDerivedClass),
  124. MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
  125. Context(MostDerivedClass->getASTContext()),
  126. MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
  127. // Compute base offsets.
  128. SubobjectOffsetMapTy SubobjectOffsets;
  129. SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
  130. SubobjectCountMapTy SubobjectCounts;
  131. ComputeBaseOffsets(BaseSubobject(MostDerivedClass, 0), /*IsVirtual=*/false,
  132. MostDerivedClassOffset, SubobjectOffsets,
  133. SubobjectLayoutClassOffsets, SubobjectCounts);
  134. // Get the the final overriders.
  135. CXXFinalOverriderMap FinalOverriders;
  136. MostDerivedClass->getFinalOverriders(FinalOverriders);
  137. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  138. E = FinalOverriders.end(); I != E; ++I) {
  139. const CXXMethodDecl *MD = I->first;
  140. const OverridingMethods& Methods = I->second;
  141. for (OverridingMethods::const_iterator I = Methods.begin(),
  142. E = Methods.end(); I != E; ++I) {
  143. unsigned SubobjectNumber = I->first;
  144. assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
  145. SubobjectNumber)) &&
  146. "Did not find subobject offset!");
  147. uint64_t BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
  148. SubobjectNumber)];
  149. assert(I->second.size() == 1 && "Final overrider is not unique!");
  150. const UniqueVirtualMethod &Method = I->second.front();
  151. const CXXRecordDecl *OverriderRD = Method.Method->getParent();
  152. assert(SubobjectLayoutClassOffsets.count(
  153. std::make_pair(OverriderRD, Method.Subobject))
  154. && "Did not find subobject offset!");
  155. uint64_t OverriderOffset =
  156. SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
  157. Method.Subobject)];
  158. OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
  159. assert(!Overrider.Method && "Overrider should not exist yet!");
  160. Overrider.Offset = OverriderOffset;
  161. Overrider.Method = Method.Method;
  162. }
  163. }
  164. #if DUMP_OVERRIDERS
  165. // And dump them (for now).
  166. dump();
  167. #endif
  168. }
  169. static BaseOffset ComputeBaseOffset(ASTContext &Context,
  170. const CXXRecordDecl *DerivedRD,
  171. const CXXBasePath &Path) {
  172. int64_t NonVirtualOffset = 0;
  173. unsigned NonVirtualStart = 0;
  174. const CXXRecordDecl *VirtualBase = 0;
  175. // First, look for the virtual base class.
  176. for (unsigned I = 0, E = Path.size(); I != E; ++I) {
  177. const CXXBasePathElement &Element = Path[I];
  178. if (Element.Base->isVirtual()) {
  179. // FIXME: Can we break when we find the first virtual base?
  180. // (If we can't, can't we just iterate over the path in reverse order?)
  181. NonVirtualStart = I + 1;
  182. QualType VBaseType = Element.Base->getType();
  183. VirtualBase =
  184. cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
  185. }
  186. }
  187. // Now compute the non-virtual offset.
  188. for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
  189. const CXXBasePathElement &Element = Path[I];
  190. // Check the base class offset.
  191. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
  192. const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
  193. const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
  194. NonVirtualOffset += Layout.getBaseClassOffsetInBits(Base);
  195. }
  196. // FIXME: This should probably use CharUnits or something. Maybe we should
  197. // even change the base offsets in ASTRecordLayout to be specified in
  198. // CharUnits.
  199. return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset / 8);
  200. }
  201. static BaseOffset ComputeBaseOffset(ASTContext &Context,
  202. const CXXRecordDecl *BaseRD,
  203. const CXXRecordDecl *DerivedRD) {
  204. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  205. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  206. if (!const_cast<CXXRecordDecl *>(DerivedRD)->
  207. isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
  208. assert(false && "Class must be derived from the passed in base class!");
  209. return BaseOffset();
  210. }
  211. return ComputeBaseOffset(Context, DerivedRD, Paths.front());
  212. }
  213. static BaseOffset
  214. ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
  215. const CXXMethodDecl *DerivedMD,
  216. const CXXMethodDecl *BaseMD) {
  217. const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
  218. const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
  219. // Canonicalize the return types.
  220. CanQualType CanDerivedReturnType =
  221. Context.getCanonicalType(DerivedFT->getResultType());
  222. CanQualType CanBaseReturnType =
  223. Context.getCanonicalType(BaseFT->getResultType());
  224. assert(CanDerivedReturnType->getTypeClass() ==
  225. CanBaseReturnType->getTypeClass() &&
  226. "Types must have same type class!");
  227. if (CanDerivedReturnType == CanBaseReturnType) {
  228. // No adjustment needed.
  229. return BaseOffset();
  230. }
  231. if (isa<ReferenceType>(CanDerivedReturnType)) {
  232. CanDerivedReturnType =
  233. CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
  234. CanBaseReturnType =
  235. CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
  236. } else if (isa<PointerType>(CanDerivedReturnType)) {
  237. CanDerivedReturnType =
  238. CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
  239. CanBaseReturnType =
  240. CanBaseReturnType->getAs<PointerType>()->getPointeeType();
  241. } else {
  242. assert(false && "Unexpected return type!");
  243. }
  244. // We need to compare unqualified types here; consider
  245. // const T *Base::foo();
  246. // T *Derived::foo();
  247. if (CanDerivedReturnType.getUnqualifiedType() ==
  248. CanBaseReturnType.getUnqualifiedType()) {
  249. // No adjustment needed.
  250. return BaseOffset();
  251. }
  252. const CXXRecordDecl *DerivedRD =
  253. cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
  254. const CXXRecordDecl *BaseRD =
  255. cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
  256. return ComputeBaseOffset(Context, BaseRD, DerivedRD);
  257. }
  258. void
  259. FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
  260. uint64_t OffsetInLayoutClass,
  261. SubobjectOffsetMapTy &SubobjectOffsets,
  262. SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
  263. SubobjectCountMapTy &SubobjectCounts) {
  264. const CXXRecordDecl *RD = Base.getBase();
  265. unsigned SubobjectNumber = 0;
  266. if (!IsVirtual)
  267. SubobjectNumber = ++SubobjectCounts[RD];
  268. // Set up the subobject to offset mapping.
  269. assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
  270. && "Subobject offset already exists!");
  271. assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
  272. && "Subobject offset already exists!");
  273. SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] =
  274. Base.getBaseOffset();
  275. SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
  276. OffsetInLayoutClass;
  277. // Traverse our bases.
  278. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  279. E = RD->bases_end(); I != E; ++I) {
  280. const CXXRecordDecl *BaseDecl =
  281. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  282. uint64_t BaseOffset;
  283. uint64_t BaseOffsetInLayoutClass;
  284. if (I->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.getVBaseClassOffsetInBits(BaseDecl);
  291. BaseOffsetInLayoutClass =
  292. LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl);
  293. } else {
  294. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  295. uint64_t Offset = Layout.getBaseClassOffsetInBits(BaseDecl);
  296. BaseOffset = Base.getBaseOffset() + Offset;
  297. BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
  298. }
  299. ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset), I->isVirtual(),
  300. BaseOffsetInLayoutClass, SubobjectOffsets,
  301. SubobjectLayoutClassOffsets, SubobjectCounts);
  302. }
  303. }
  304. void FinalOverriders::dump(llvm::raw_ostream &Out, BaseSubobject Base,
  305. VisitedVirtualBasesSetTy &VisitedVirtualBases) {
  306. const CXXRecordDecl *RD = Base.getBase();
  307. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  308. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  309. E = RD->bases_end(); I != E; ++I) {
  310. const CXXRecordDecl *BaseDecl =
  311. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  312. // Ignore bases that don't have any virtual member functions.
  313. if (!BaseDecl->isPolymorphic())
  314. continue;
  315. uint64_t BaseOffset;
  316. if (I->isVirtual()) {
  317. if (!VisitedVirtualBases.insert(BaseDecl)) {
  318. // We've visited this base before.
  319. continue;
  320. }
  321. BaseOffset = MostDerivedClassLayout.getVBaseClassOffsetInBits(BaseDecl);
  322. } else {
  323. BaseOffset = Layout.getBaseClassOffsetInBits(BaseDecl) +
  324. Base.getBaseOffset();
  325. }
  326. dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
  327. }
  328. Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
  329. Out << Base.getBaseOffset() / 8 << ")\n";
  330. // Now dump the overriders for this base subobject.
  331. for (CXXRecordDecl::method_iterator I = RD->method_begin(),
  332. E = RD->method_end(); I != E; ++I) {
  333. const CXXMethodDecl *MD = *I;
  334. if (!MD->isVirtual())
  335. continue;
  336. OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
  337. Out << " " << MD->getQualifiedNameAsString() << " - (";
  338. Out << Overrider.Method->getQualifiedNameAsString();
  339. Out << ", " << ", " << Overrider.Offset / 8 << ')';
  340. BaseOffset Offset;
  341. if (!Overrider.Method->isPure())
  342. Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
  343. if (!Offset.isEmpty()) {
  344. Out << " [ret-adj: ";
  345. if (Offset.VirtualBase)
  346. Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
  347. Out << Offset.NonVirtualOffset << " nv]";
  348. }
  349. Out << "\n";
  350. }
  351. }
  352. /// VTableComponent - Represents a single component in a vtable.
  353. class VTableComponent {
  354. public:
  355. enum Kind {
  356. CK_VCallOffset,
  357. CK_VBaseOffset,
  358. CK_OffsetToTop,
  359. CK_RTTI,
  360. CK_FunctionPointer,
  361. /// CK_CompleteDtorPointer - A pointer to the complete destructor.
  362. CK_CompleteDtorPointer,
  363. /// CK_DeletingDtorPointer - A pointer to the deleting destructor.
  364. CK_DeletingDtorPointer,
  365. /// CK_UnusedFunctionPointer - In some cases, a vtable function pointer
  366. /// will end up never being called. Such vtable function pointers are
  367. /// represented as a CK_UnusedFunctionPointer.
  368. CK_UnusedFunctionPointer
  369. };
  370. static VTableComponent MakeVCallOffset(int64_t Offset) {
  371. return VTableComponent(CK_VCallOffset, Offset);
  372. }
  373. static VTableComponent MakeVBaseOffset(int64_t Offset) {
  374. return VTableComponent(CK_VBaseOffset, Offset);
  375. }
  376. static VTableComponent MakeOffsetToTop(int64_t Offset) {
  377. return VTableComponent(CK_OffsetToTop, Offset);
  378. }
  379. static VTableComponent MakeRTTI(const CXXRecordDecl *RD) {
  380. return VTableComponent(CK_RTTI, reinterpret_cast<uintptr_t>(RD));
  381. }
  382. static VTableComponent MakeFunction(const CXXMethodDecl *MD) {
  383. assert(!isa<CXXDestructorDecl>(MD) &&
  384. "Don't use MakeFunction with destructors!");
  385. return VTableComponent(CK_FunctionPointer,
  386. reinterpret_cast<uintptr_t>(MD));
  387. }
  388. static VTableComponent MakeCompleteDtor(const CXXDestructorDecl *DD) {
  389. return VTableComponent(CK_CompleteDtorPointer,
  390. reinterpret_cast<uintptr_t>(DD));
  391. }
  392. static VTableComponent MakeDeletingDtor(const CXXDestructorDecl *DD) {
  393. return VTableComponent(CK_DeletingDtorPointer,
  394. reinterpret_cast<uintptr_t>(DD));
  395. }
  396. static VTableComponent MakeUnusedFunction(const CXXMethodDecl *MD) {
  397. assert(!isa<CXXDestructorDecl>(MD) &&
  398. "Don't use MakeUnusedFunction with destructors!");
  399. return VTableComponent(CK_UnusedFunctionPointer,
  400. reinterpret_cast<uintptr_t>(MD));
  401. }
  402. static VTableComponent getFromOpaqueInteger(uint64_t I) {
  403. return VTableComponent(I);
  404. }
  405. /// getKind - Get the kind of this vtable component.
  406. Kind getKind() const {
  407. return (Kind)(Value & 0x7);
  408. }
  409. int64_t getVCallOffset() const {
  410. assert(getKind() == CK_VCallOffset && "Invalid component kind!");
  411. return getOffset();
  412. }
  413. int64_t getVBaseOffset() const {
  414. assert(getKind() == CK_VBaseOffset && "Invalid component kind!");
  415. return getOffset();
  416. }
  417. int64_t getOffsetToTop() const {
  418. assert(getKind() == CK_OffsetToTop && "Invalid component kind!");
  419. return getOffset();
  420. }
  421. const CXXRecordDecl *getRTTIDecl() const {
  422. assert(getKind() == CK_RTTI && "Invalid component kind!");
  423. return reinterpret_cast<CXXRecordDecl *>(getPointer());
  424. }
  425. const CXXMethodDecl *getFunctionDecl() const {
  426. assert(getKind() == CK_FunctionPointer);
  427. return reinterpret_cast<CXXMethodDecl *>(getPointer());
  428. }
  429. const CXXDestructorDecl *getDestructorDecl() const {
  430. assert((getKind() == CK_CompleteDtorPointer ||
  431. getKind() == CK_DeletingDtorPointer) && "Invalid component kind!");
  432. return reinterpret_cast<CXXDestructorDecl *>(getPointer());
  433. }
  434. const CXXMethodDecl *getUnusedFunctionDecl() const {
  435. assert(getKind() == CK_UnusedFunctionPointer);
  436. return reinterpret_cast<CXXMethodDecl *>(getPointer());
  437. }
  438. private:
  439. VTableComponent(Kind ComponentKind, int64_t Offset) {
  440. assert((ComponentKind == CK_VCallOffset ||
  441. ComponentKind == CK_VBaseOffset ||
  442. ComponentKind == CK_OffsetToTop) && "Invalid component kind!");
  443. assert(Offset <= ((1LL << 56) - 1) && "Offset is too big!");
  444. Value = ((Offset << 3) | ComponentKind);
  445. }
  446. VTableComponent(Kind ComponentKind, uintptr_t Ptr) {
  447. assert((ComponentKind == CK_RTTI ||
  448. ComponentKind == CK_FunctionPointer ||
  449. ComponentKind == CK_CompleteDtorPointer ||
  450. ComponentKind == CK_DeletingDtorPointer ||
  451. ComponentKind == CK_UnusedFunctionPointer) &&
  452. "Invalid component kind!");
  453. assert((Ptr & 7) == 0 && "Pointer not sufficiently aligned!");
  454. Value = Ptr | ComponentKind;
  455. }
  456. int64_t getOffset() const {
  457. assert((getKind() == CK_VCallOffset || getKind() == CK_VBaseOffset ||
  458. getKind() == CK_OffsetToTop) && "Invalid component kind!");
  459. return Value >> 3;
  460. }
  461. uintptr_t getPointer() const {
  462. assert((getKind() == CK_RTTI ||
  463. getKind() == CK_FunctionPointer ||
  464. getKind() == CK_CompleteDtorPointer ||
  465. getKind() == CK_DeletingDtorPointer ||
  466. getKind() == CK_UnusedFunctionPointer) &&
  467. "Invalid component kind!");
  468. return static_cast<uintptr_t>(Value & ~7ULL);
  469. }
  470. explicit VTableComponent(uint64_t Value)
  471. : Value(Value) { }
  472. /// The kind is stored in the lower 3 bits of the value. For offsets, we
  473. /// make use of the facts that classes can't be larger than 2^55 bytes,
  474. /// so we store the offset in the lower part of the 61 bytes that remain.
  475. /// (The reason that we're not simply using a PointerIntPair here is that we
  476. /// need the offsets to be 64-bit, even when on a 32-bit machine).
  477. int64_t Value;
  478. };
  479. /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
  480. struct VCallOffsetMap {
  481. typedef std::pair<const CXXMethodDecl *, int64_t> MethodAndOffsetPairTy;
  482. /// Offsets - Keeps track of methods and their offsets.
  483. // FIXME: This should be a real map and not a vector.
  484. llvm::SmallVector<MethodAndOffsetPairTy, 16> Offsets;
  485. /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
  486. /// can share the same vcall offset.
  487. static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
  488. const CXXMethodDecl *RHS);
  489. public:
  490. /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
  491. /// add was successful, or false if there was already a member function with
  492. /// the same signature in the map.
  493. bool AddVCallOffset(const CXXMethodDecl *MD, int64_t OffsetOffset);
  494. /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
  495. /// vtable address point) for the given virtual member function.
  496. int64_t getVCallOffsetOffset(const CXXMethodDecl *MD);
  497. // empty - Return whether the offset map is empty or not.
  498. bool empty() const { return Offsets.empty(); }
  499. };
  500. static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
  501. const CXXMethodDecl *RHS) {
  502. ASTContext &C = LHS->getASTContext(); // TODO: thread this down
  503. CanQual<FunctionProtoType>
  504. LT = C.getCanonicalType(LHS->getType()).getAs<FunctionProtoType>(),
  505. RT = C.getCanonicalType(RHS->getType()).getAs<FunctionProtoType>();
  506. // Fast-path matches in the canonical types.
  507. if (LT == RT) return true;
  508. // Force the signatures to match. We can't rely on the overrides
  509. // list here because there isn't necessarily an inheritance
  510. // relationship between the two methods.
  511. if (LT.getQualifiers() != RT.getQualifiers() ||
  512. LT->getNumArgs() != RT->getNumArgs())
  513. return false;
  514. for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
  515. if (LT->getArgType(I) != RT->getArgType(I))
  516. return false;
  517. return true;
  518. }
  519. bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
  520. const CXXMethodDecl *RHS) {
  521. assert(LHS->isVirtual() && "LHS must be virtual!");
  522. assert(RHS->isVirtual() && "LHS must be virtual!");
  523. // A destructor can share a vcall offset with another destructor.
  524. if (isa<CXXDestructorDecl>(LHS))
  525. return isa<CXXDestructorDecl>(RHS);
  526. // FIXME: We need to check more things here.
  527. // The methods must have the same name.
  528. DeclarationName LHSName = LHS->getDeclName();
  529. DeclarationName RHSName = RHS->getDeclName();
  530. if (LHSName != RHSName)
  531. return false;
  532. // And the same signatures.
  533. return HasSameVirtualSignature(LHS, RHS);
  534. }
  535. bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
  536. int64_t OffsetOffset) {
  537. // Check if we can reuse an offset.
  538. for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
  539. if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
  540. return false;
  541. }
  542. // Add the offset.
  543. Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
  544. return true;
  545. }
  546. int64_t VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
  547. // Look for an offset.
  548. for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
  549. if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
  550. return Offsets[I].second;
  551. }
  552. assert(false && "Should always find a vcall offset offset!");
  553. return 0;
  554. }
  555. /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
  556. class VCallAndVBaseOffsetBuilder {
  557. public:
  558. typedef llvm::DenseMap<const CXXRecordDecl *, int64_t>
  559. VBaseOffsetOffsetsMapTy;
  560. private:
  561. /// MostDerivedClass - The most derived class for which we're building vcall
  562. /// and vbase offsets.
  563. const CXXRecordDecl *MostDerivedClass;
  564. /// LayoutClass - The class we're using for layout information. Will be
  565. /// different than the most derived class if we're building a construction
  566. /// vtable.
  567. const CXXRecordDecl *LayoutClass;
  568. /// Context - The ASTContext which we will use for layout information.
  569. ASTContext &Context;
  570. /// Components - vcall and vbase offset components
  571. typedef llvm::SmallVector<VTableComponent, 64> VTableComponentVectorTy;
  572. VTableComponentVectorTy Components;
  573. /// VisitedVirtualBases - Visited virtual bases.
  574. llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
  575. /// VCallOffsets - Keeps track of vcall offsets.
  576. VCallOffsetMap VCallOffsets;
  577. /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
  578. /// relative to the address point.
  579. VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
  580. /// FinalOverriders - The final overriders of the most derived class.
  581. /// (Can be null when we're not building a vtable of the most derived class).
  582. const FinalOverriders *Overriders;
  583. /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
  584. /// given base subobject.
  585. void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
  586. uint64_t RealBaseOffset);
  587. /// AddVCallOffsets - Add vcall offsets for the given base subobject.
  588. void AddVCallOffsets(BaseSubobject Base, uint64_t VBaseOffset);
  589. /// AddVBaseOffsets - Add vbase offsets for the given class.
  590. void AddVBaseOffsets(const CXXRecordDecl *Base, uint64_t OffsetInLayoutClass);
  591. /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
  592. /// bytes, relative to the vtable address point.
  593. int64_t getCurrentOffsetOffset() const;
  594. public:
  595. VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
  596. const CXXRecordDecl *LayoutClass,
  597. const FinalOverriders *Overriders,
  598. BaseSubobject Base, bool BaseIsVirtual,
  599. uint64_t OffsetInLayoutClass)
  600. : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass),
  601. Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
  602. // Add vcall and vbase offsets.
  603. AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
  604. }
  605. /// Methods for iterating over the components.
  606. typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
  607. const_iterator components_begin() const { return Components.rbegin(); }
  608. const_iterator components_end() const { return Components.rend(); }
  609. const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
  610. const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
  611. return VBaseOffsetOffsets;
  612. }
  613. };
  614. void
  615. VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
  616. bool BaseIsVirtual,
  617. uint64_t RealBaseOffset) {
  618. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
  619. // Itanium C++ ABI 2.5.2:
  620. // ..in classes sharing a virtual table with a primary base class, the vcall
  621. // and vbase offsets added by the derived class all come before the vcall
  622. // and vbase offsets required by the base class, so that the latter may be
  623. // laid out as required by the base class without regard to additions from
  624. // the derived class(es).
  625. // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
  626. // emit them for the primary base first).
  627. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  628. bool PrimaryBaseIsVirtual = Layout.getPrimaryBaseWasVirtual();
  629. uint64_t PrimaryBaseOffset;
  630. // Get the base offset of the primary base.
  631. if (PrimaryBaseIsVirtual) {
  632. assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
  633. "Primary vbase should have a zero offset!");
  634. const ASTRecordLayout &MostDerivedClassLayout =
  635. Context.getASTRecordLayout(MostDerivedClass);
  636. PrimaryBaseOffset =
  637. MostDerivedClassLayout.getVBaseClassOffsetInBits(PrimaryBase);
  638. } else {
  639. assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
  640. "Primary base should have a zero offset!");
  641. PrimaryBaseOffset = Base.getBaseOffset();
  642. }
  643. AddVCallAndVBaseOffsets(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
  644. PrimaryBaseIsVirtual, RealBaseOffset);
  645. }
  646. AddVBaseOffsets(Base.getBase(), RealBaseOffset);
  647. // We only want to add vcall offsets for virtual bases.
  648. if (BaseIsVirtual)
  649. AddVCallOffsets(Base, RealBaseOffset);
  650. }
  651. int64_t VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
  652. // OffsetIndex is the index of this vcall or vbase offset, relative to the
  653. // vtable address point. (We subtract 3 to account for the information just
  654. // above the address point, the RTTI info, the offset to top, and the
  655. // vcall offset itself).
  656. int64_t OffsetIndex = -(int64_t)(3 + Components.size());
  657. // FIXME: We shouldn't use / 8 here.
  658. int64_t OffsetOffset = OffsetIndex *
  659. (int64_t)Context.Target.getPointerWidth(0) / 8;
  660. return OffsetOffset;
  661. }
  662. void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
  663. uint64_t VBaseOffset) {
  664. const CXXRecordDecl *RD = Base.getBase();
  665. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  666. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  667. // Handle the primary base first.
  668. // We only want to add vcall offsets if the base is non-virtual; a virtual
  669. // primary base will have its vcall and vbase offsets emitted already.
  670. if (PrimaryBase && !Layout.getPrimaryBaseWasVirtual()) {
  671. // Get the base offset of the primary base.
  672. assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
  673. "Primary base should have a zero offset!");
  674. AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
  675. VBaseOffset);
  676. }
  677. // Add the vcall offsets.
  678. for (CXXRecordDecl::method_iterator I = RD->method_begin(),
  679. E = RD->method_end(); I != E; ++I) {
  680. const CXXMethodDecl *MD = *I;
  681. if (!MD->isVirtual())
  682. continue;
  683. int64_t OffsetOffset = getCurrentOffsetOffset();
  684. // Don't add a vcall offset if we already have one for this member function
  685. // signature.
  686. if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
  687. continue;
  688. int64_t Offset = 0;
  689. if (Overriders) {
  690. // Get the final overrider.
  691. FinalOverriders::OverriderInfo Overrider =
  692. Overriders->getOverrider(MD, Base.getBaseOffset());
  693. /// The vcall offset is the offset from the virtual base to the object
  694. /// where the function was overridden.
  695. // FIXME: We should not use / 8 here.
  696. Offset = (int64_t)(Overrider.Offset - VBaseOffset) / 8;
  697. }
  698. Components.push_back(VTableComponent::MakeVCallOffset(Offset));
  699. }
  700. // And iterate over all non-virtual bases (ignoring the primary base).
  701. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  702. E = RD->bases_end(); I != E; ++I) {
  703. if (I->isVirtual())
  704. continue;
  705. const CXXRecordDecl *BaseDecl =
  706. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  707. if (BaseDecl == PrimaryBase)
  708. continue;
  709. // Get the base offset of this base.
  710. uint64_t BaseOffset = Base.getBaseOffset() +
  711. Layout.getBaseClassOffsetInBits(BaseDecl);
  712. AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), VBaseOffset);
  713. }
  714. }
  715. void VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
  716. uint64_t OffsetInLayoutClass) {
  717. const ASTRecordLayout &LayoutClassLayout =
  718. Context.getASTRecordLayout(LayoutClass);
  719. // Add vbase offsets.
  720. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  721. E = RD->bases_end(); I != E; ++I) {
  722. const CXXRecordDecl *BaseDecl =
  723. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  724. // Check if this is a virtual base that we haven't visited before.
  725. if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
  726. // FIXME: We shouldn't use / 8 here.
  727. int64_t Offset =
  728. (int64_t)(LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl) -
  729. OffsetInLayoutClass) / 8;
  730. // Add the vbase offset offset.
  731. assert(!VBaseOffsetOffsets.count(BaseDecl) &&
  732. "vbase offset offset already exists!");
  733. int64_t VBaseOffsetOffset = getCurrentOffsetOffset();
  734. VBaseOffsetOffsets.insert(std::make_pair(BaseDecl, VBaseOffsetOffset));
  735. Components.push_back(VTableComponent::MakeVBaseOffset(Offset));
  736. }
  737. // Check the base class looking for more vbase offsets.
  738. AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
  739. }
  740. }
  741. /// VTableBuilder - Class for building vtable layout information.
  742. class VTableBuilder {
  743. public:
  744. /// PrimaryBasesSetVectorTy - A set vector of direct and indirect
  745. /// primary bases.
  746. typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
  747. PrimaryBasesSetVectorTy;
  748. typedef llvm::DenseMap<const CXXRecordDecl *, int64_t>
  749. VBaseOffsetOffsetsMapTy;
  750. typedef llvm::DenseMap<BaseSubobject, uint64_t>
  751. AddressPointsMapTy;
  752. private:
  753. /// VTables - Global vtable information.
  754. CodeGenVTables &VTables;
  755. /// MostDerivedClass - The most derived class for which we're building this
  756. /// vtable.
  757. const CXXRecordDecl *MostDerivedClass;
  758. /// MostDerivedClassOffset - If we're building a construction vtable, this
  759. /// holds the offset from the layout class to the most derived class.
  760. const uint64_t MostDerivedClassOffset;
  761. /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual
  762. /// base. (This only makes sense when building a construction vtable).
  763. bool MostDerivedClassIsVirtual;
  764. /// LayoutClass - The class we're using for layout information. Will be
  765. /// different than the most derived class if we're building a construction
  766. /// vtable.
  767. const CXXRecordDecl *LayoutClass;
  768. /// Context - The ASTContext which we will use for layout information.
  769. ASTContext &Context;
  770. /// FinalOverriders - The final overriders of the most derived class.
  771. const FinalOverriders Overriders;
  772. /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
  773. /// bases in this vtable.
  774. llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
  775. /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
  776. /// the most derived class.
  777. VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
  778. /// Components - The components of the vtable being built.
  779. llvm::SmallVector<VTableComponent, 64> Components;
  780. /// AddressPoints - Address points for the vtable being built.
  781. AddressPointsMapTy AddressPoints;
  782. /// MethodInfo - Contains information about a method in a vtable.
  783. /// (Used for computing 'this' pointer adjustment thunks.
  784. struct MethodInfo {
  785. /// BaseOffset - The base offset of this method.
  786. const uint64_t BaseOffset;
  787. /// BaseOffsetInLayoutClass - The base offset in the layout class of this
  788. /// method.
  789. const uint64_t BaseOffsetInLayoutClass;
  790. /// VTableIndex - The index in the vtable that this method has.
  791. /// (For destructors, this is the index of the complete destructor).
  792. const uint64_t VTableIndex;
  793. MethodInfo(uint64_t BaseOffset, uint64_t BaseOffsetInLayoutClass,
  794. uint64_t VTableIndex)
  795. : BaseOffset(BaseOffset),
  796. BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
  797. VTableIndex(VTableIndex) { }
  798. MethodInfo() : BaseOffset(0), BaseOffsetInLayoutClass(0), VTableIndex(0) { }
  799. };
  800. typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
  801. /// MethodInfoMap - The information for all methods in the vtable we're
  802. /// currently building.
  803. MethodInfoMapTy MethodInfoMap;
  804. typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
  805. /// VTableThunks - The thunks by vtable index in the vtable currently being
  806. /// built.
  807. VTableThunksMapTy VTableThunks;
  808. typedef llvm::SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
  809. typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
  810. /// Thunks - A map that contains all the thunks needed for all methods in the
  811. /// most derived class for which the vtable is currently being built.
  812. ThunksMapTy Thunks;
  813. /// AddThunk - Add a thunk for the given method.
  814. void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
  815. /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
  816. /// part of the vtable we're currently building.
  817. void ComputeThisAdjustments();
  818. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  819. /// PrimaryVirtualBases - All known virtual bases who are a primary base of
  820. /// some other base.
  821. VisitedVirtualBasesSetTy PrimaryVirtualBases;
  822. /// ComputeReturnAdjustment - Compute the return adjustment given a return
  823. /// adjustment base offset.
  824. ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
  825. /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
  826. /// the 'this' pointer from the base subobject to the derived subobject.
  827. BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
  828. BaseSubobject Derived) const;
  829. /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
  830. /// given virtual member function, its offset in the layout class and its
  831. /// final overrider.
  832. ThisAdjustment
  833. ComputeThisAdjustment(const CXXMethodDecl *MD,
  834. uint64_t BaseOffsetInLayoutClass,
  835. FinalOverriders::OverriderInfo Overrider);
  836. /// AddMethod - Add a single virtual member function to the vtable
  837. /// components vector.
  838. void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
  839. /// IsOverriderUsed - Returns whether the overrider will ever be used in this
  840. /// part of the vtable.
  841. ///
  842. /// Itanium C++ ABI 2.5.2:
  843. ///
  844. /// struct A { virtual void f(); };
  845. /// struct B : virtual public A { int i; };
  846. /// struct C : virtual public A { int j; };
  847. /// struct D : public B, public C {};
  848. ///
  849. /// When B and C are declared, A is a primary base in each case, so although
  850. /// vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
  851. /// adjustment is required and no thunk is generated. However, inside D
  852. /// objects, A is no longer a primary base of C, so if we allowed calls to
  853. /// C::f() to use the copy of A's vtable in the C subobject, we would need
  854. /// to adjust this from C* to B::A*, which would require a third-party
  855. /// thunk. Since we require that a call to C::f() first convert to A*,
  856. /// C-in-D's copy of A's vtable is never referenced, so this is not
  857. /// necessary.
  858. bool IsOverriderUsed(const CXXMethodDecl *Overrider,
  859. uint64_t BaseOffsetInLayoutClass,
  860. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  861. uint64_t FirstBaseOffsetInLayoutClass) const;
  862. /// AddMethods - Add the methods of this base subobject and all its
  863. /// primary bases to the vtable components vector.
  864. void AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass,
  865. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  866. uint64_t FirstBaseOffsetInLayoutClass,
  867. PrimaryBasesSetVectorTy &PrimaryBases);
  868. // LayoutVTable - Layout the vtable for the given base class, including its
  869. // secondary vtables and any vtables for virtual bases.
  870. void LayoutVTable();
  871. /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
  872. /// given base subobject, as well as all its secondary vtables.
  873. ///
  874. /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
  875. /// or a direct or indirect base of a virtual base.
  876. ///
  877. /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
  878. /// in the layout class.
  879. void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
  880. bool BaseIsMorallyVirtual,
  881. bool BaseIsVirtualInLayoutClass,
  882. uint64_t OffsetInLayoutClass);
  883. /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
  884. /// subobject.
  885. ///
  886. /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
  887. /// or a direct or indirect base of a virtual base.
  888. void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
  889. uint64_t OffsetInLayoutClass);
  890. /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
  891. /// class hierarchy.
  892. void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
  893. uint64_t OffsetInLayoutClass,
  894. VisitedVirtualBasesSetTy &VBases);
  895. /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
  896. /// given base (excluding any primary bases).
  897. void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
  898. VisitedVirtualBasesSetTy &VBases);
  899. /// isBuildingConstructionVTable - Return whether this vtable builder is
  900. /// building a construction vtable.
  901. bool isBuildingConstructorVTable() const {
  902. return MostDerivedClass != LayoutClass;
  903. }
  904. public:
  905. VTableBuilder(CodeGenVTables &VTables, const CXXRecordDecl *MostDerivedClass,
  906. uint64_t MostDerivedClassOffset, bool MostDerivedClassIsVirtual,
  907. const CXXRecordDecl *LayoutClass)
  908. : VTables(VTables), MostDerivedClass(MostDerivedClass),
  909. MostDerivedClassOffset(MostDerivedClassOffset),
  910. MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
  911. LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
  912. Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
  913. LayoutVTable();
  914. }
  915. ThunksMapTy::const_iterator thunks_begin() const {
  916. return Thunks.begin();
  917. }
  918. ThunksMapTy::const_iterator thunks_end() const {
  919. return Thunks.end();
  920. }
  921. const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
  922. return VBaseOffsetOffsets;
  923. }
  924. /// getNumVTableComponents - Return the number of components in the vtable
  925. /// currently built.
  926. uint64_t getNumVTableComponents() const {
  927. return Components.size();
  928. }
  929. const uint64_t *vtable_components_data_begin() const {
  930. return reinterpret_cast<const uint64_t *>(Components.begin());
  931. }
  932. const uint64_t *vtable_components_data_end() const {
  933. return reinterpret_cast<const uint64_t *>(Components.end());
  934. }
  935. AddressPointsMapTy::const_iterator address_points_begin() const {
  936. return AddressPoints.begin();
  937. }
  938. AddressPointsMapTy::const_iterator address_points_end() const {
  939. return AddressPoints.end();
  940. }
  941. VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
  942. return VTableThunks.begin();
  943. }
  944. VTableThunksMapTy::const_iterator vtable_thunks_end() const {
  945. return VTableThunks.end();
  946. }
  947. /// dumpLayout - Dump the vtable layout.
  948. void dumpLayout(llvm::raw_ostream&);
  949. };
  950. void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
  951. assert(!isBuildingConstructorVTable() &&
  952. "Can't add thunks for construction vtable");
  953. llvm::SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
  954. // Check if we have this thunk already.
  955. if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) !=
  956. ThunksVector.end())
  957. return;
  958. ThunksVector.push_back(Thunk);
  959. }
  960. typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
  961. /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
  962. /// the overridden methods that the function decl overrides.
  963. static void
  964. ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
  965. OverriddenMethodsSetTy& OverriddenMethods) {
  966. assert(MD->isVirtual() && "Method is not virtual!");
  967. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  968. E = MD->end_overridden_methods(); I != E; ++I) {
  969. const CXXMethodDecl *OverriddenMD = *I;
  970. OverriddenMethods.insert(OverriddenMD);
  971. ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
  972. }
  973. }
  974. void VTableBuilder::ComputeThisAdjustments() {
  975. // Now go through the method info map and see if any of the methods need
  976. // 'this' pointer adjustments.
  977. for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
  978. E = MethodInfoMap.end(); I != E; ++I) {
  979. const CXXMethodDecl *MD = I->first;
  980. const MethodInfo &MethodInfo = I->second;
  981. // Ignore adjustments for unused function pointers.
  982. uint64_t VTableIndex = MethodInfo.VTableIndex;
  983. if (Components[VTableIndex].getKind() ==
  984. VTableComponent::CK_UnusedFunctionPointer)
  985. continue;
  986. // Get the final overrider for this method.
  987. FinalOverriders::OverriderInfo Overrider =
  988. Overriders.getOverrider(MD, MethodInfo.BaseOffset);
  989. // Check if we need an adjustment at all.
  990. if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
  991. // When a return thunk is needed by a derived class that overrides a
  992. // virtual base, gcc uses a virtual 'this' adjustment as well.
  993. // While the thunk itself might be needed by vtables in subclasses or
  994. // in construction vtables, there doesn't seem to be a reason for using
  995. // the thunk in this vtable. Still, we do so to match gcc.
  996. if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
  997. continue;
  998. }
  999. ThisAdjustment ThisAdjustment =
  1000. ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
  1001. if (ThisAdjustment.isEmpty())
  1002. continue;
  1003. // Add it.
  1004. VTableThunks[VTableIndex].This = ThisAdjustment;
  1005. if (isa<CXXDestructorDecl>(MD)) {
  1006. // Add an adjustment for the deleting destructor as well.
  1007. VTableThunks[VTableIndex + 1].This = ThisAdjustment;
  1008. }
  1009. }
  1010. /// Clear the method info map.
  1011. MethodInfoMap.clear();
  1012. if (isBuildingConstructorVTable()) {
  1013. // We don't need to store thunk information for construction vtables.
  1014. return;
  1015. }
  1016. for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
  1017. E = VTableThunks.end(); I != E; ++I) {
  1018. const VTableComponent &Component = Components[I->first];
  1019. const ThunkInfo &Thunk = I->second;
  1020. const CXXMethodDecl *MD;
  1021. switch (Component.getKind()) {
  1022. default:
  1023. llvm_unreachable("Unexpected vtable component kind!");
  1024. case VTableComponent::CK_FunctionPointer:
  1025. MD = Component.getFunctionDecl();
  1026. break;
  1027. case VTableComponent::CK_CompleteDtorPointer:
  1028. MD = Component.getDestructorDecl();
  1029. break;
  1030. case VTableComponent::CK_DeletingDtorPointer:
  1031. // We've already added the thunk when we saw the complete dtor pointer.
  1032. continue;
  1033. }
  1034. if (MD->getParent() == MostDerivedClass)
  1035. AddThunk(MD, Thunk);
  1036. }
  1037. }
  1038. ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
  1039. ReturnAdjustment Adjustment;
  1040. if (!Offset.isEmpty()) {
  1041. if (Offset.VirtualBase) {
  1042. // Get the virtual base offset offset.
  1043. if (Offset.DerivedClass == MostDerivedClass) {
  1044. // We can get the offset offset directly from our map.
  1045. Adjustment.VBaseOffsetOffset =
  1046. VBaseOffsetOffsets.lookup(Offset.VirtualBase);
  1047. } else {
  1048. Adjustment.VBaseOffsetOffset =
  1049. VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
  1050. Offset.VirtualBase);
  1051. }
  1052. }
  1053. Adjustment.NonVirtual = Offset.NonVirtualOffset;
  1054. }
  1055. return Adjustment;
  1056. }
  1057. BaseOffset
  1058. VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
  1059. BaseSubobject Derived) const {
  1060. const CXXRecordDecl *BaseRD = Base.getBase();
  1061. const CXXRecordDecl *DerivedRD = Derived.getBase();
  1062. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  1063. /*RecordPaths=*/true, /*DetectVirtual=*/true);
  1064. if (!const_cast<CXXRecordDecl *>(DerivedRD)->
  1065. isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
  1066. assert(false && "Class must be derived from the passed in base class!");
  1067. return BaseOffset();
  1068. }
  1069. // We have to go through all the paths, and see which one leads us to the
  1070. // right base subobject.
  1071. for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
  1072. I != E; ++I) {
  1073. BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
  1074. // FIXME: Should not use * 8 here.
  1075. uint64_t OffsetToBaseSubobject = Offset.NonVirtualOffset * 8;
  1076. if (Offset.VirtualBase) {
  1077. // If we have a virtual base class, the non-virtual offset is relative
  1078. // to the virtual base class offset.
  1079. const ASTRecordLayout &LayoutClassLayout =
  1080. Context.getASTRecordLayout(LayoutClass);
  1081. /// Get the virtual base offset, relative to the most derived class
  1082. /// layout.
  1083. OffsetToBaseSubobject +=
  1084. LayoutClassLayout.getVBaseClassOffsetInBits(Offset.VirtualBase);
  1085. } else {
  1086. // Otherwise, the non-virtual offset is relative to the derived class
  1087. // offset.
  1088. OffsetToBaseSubobject += Derived.getBaseOffset();
  1089. }
  1090. // Check if this path gives us the right base subobject.
  1091. if (OffsetToBaseSubobject == Base.getBaseOffset()) {
  1092. // Since we're going from the base class _to_ the derived class, we'll
  1093. // invert the non-virtual offset here.
  1094. Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
  1095. return Offset;
  1096. }
  1097. }
  1098. return BaseOffset();
  1099. }
  1100. ThisAdjustment
  1101. VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD,
  1102. uint64_t BaseOffsetInLayoutClass,
  1103. FinalOverriders::OverriderInfo Overrider) {
  1104. // Ignore adjustments for pure virtual member functions.
  1105. if (Overrider.Method->isPure())
  1106. return ThisAdjustment();
  1107. BaseSubobject OverriddenBaseSubobject(MD->getParent(),
  1108. BaseOffsetInLayoutClass);
  1109. BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
  1110. Overrider.Offset);
  1111. // Compute the adjustment offset.
  1112. BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
  1113. OverriderBaseSubobject);
  1114. if (Offset.isEmpty())
  1115. return ThisAdjustment();
  1116. ThisAdjustment Adjustment;
  1117. if (Offset.VirtualBase) {
  1118. // Get the vcall offset map for this virtual base.
  1119. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
  1120. if (VCallOffsets.empty()) {
  1121. // We don't have vcall offsets for this virtual base, go ahead and
  1122. // build them.
  1123. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
  1124. /*FinalOverriders=*/0,
  1125. BaseSubobject(Offset.VirtualBase, 0),
  1126. /*BaseIsVirtual=*/true,
  1127. /*OffsetInLayoutClass=*/0);
  1128. VCallOffsets = Builder.getVCallOffsets();
  1129. }
  1130. Adjustment.VCallOffsetOffset = VCallOffsets.getVCallOffsetOffset(MD);
  1131. }
  1132. // Set the non-virtual part of the adjustment.
  1133. Adjustment.NonVirtual = Offset.NonVirtualOffset;
  1134. return Adjustment;
  1135. }
  1136. void
  1137. VTableBuilder::AddMethod(const CXXMethodDecl *MD,
  1138. ReturnAdjustment ReturnAdjustment) {
  1139. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1140. assert(ReturnAdjustment.isEmpty() &&
  1141. "Destructor can't have return adjustment!");
  1142. // Add both the complete destructor and the deleting destructor.
  1143. Components.push_back(VTableComponent::MakeCompleteDtor(DD));
  1144. Components.push_back(VTableComponent::MakeDeletingDtor(DD));
  1145. } else {
  1146. // Add the return adjustment if necessary.
  1147. if (!ReturnAdjustment.isEmpty())
  1148. VTableThunks[Components.size()].Return = ReturnAdjustment;
  1149. // Add the function.
  1150. Components.push_back(VTableComponent::MakeFunction(MD));
  1151. }
  1152. }
  1153. /// OverridesIndirectMethodInBase - Return whether the given member function
  1154. /// overrides any methods in the set of given bases.
  1155. /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
  1156. /// For example, if we have:
  1157. ///
  1158. /// struct A { virtual void f(); }
  1159. /// struct B : A { virtual void f(); }
  1160. /// struct C : B { virtual void f(); }
  1161. ///
  1162. /// OverridesIndirectMethodInBase will return true if given C::f as the method
  1163. /// and { A } as the set of bases.
  1164. static bool
  1165. OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
  1166. VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
  1167. if (Bases.count(MD->getParent()))
  1168. return true;
  1169. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  1170. E = MD->end_overridden_methods(); I != E; ++I) {
  1171. const CXXMethodDecl *OverriddenMD = *I;
  1172. // Check "indirect overriders".
  1173. if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
  1174. return true;
  1175. }
  1176. return false;
  1177. }
  1178. bool
  1179. VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
  1180. uint64_t BaseOffsetInLayoutClass,
  1181. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  1182. uint64_t FirstBaseOffsetInLayoutClass) const {
  1183. // If the base and the first base in the primary base chain have the same
  1184. // offsets, then this overrider will be used.
  1185. if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
  1186. return true;
  1187. // We know now that Base (or a direct or indirect base of it) is a primary
  1188. // base in part of the class hierarchy, but not a primary base in the most
  1189. // derived class.
  1190. // If the overrider is the first base in the primary base chain, we know
  1191. // that the overrider will be used.
  1192. if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
  1193. return true;
  1194. VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
  1195. const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
  1196. PrimaryBases.insert(RD);
  1197. // Now traverse the base chain, starting with the first base, until we find
  1198. // the base that is no longer a primary base.
  1199. while (true) {
  1200. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1201. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1202. if (!PrimaryBase)
  1203. break;
  1204. if (Layout.getPrimaryBaseWasVirtual()) {
  1205. assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
  1206. "Primary base should always be at offset 0!");
  1207. const ASTRecordLayout &LayoutClassLayout =
  1208. Context.getASTRecordLayout(LayoutClass);
  1209. // Now check if this is the primary base that is not a primary base in the
  1210. // most derived class.
  1211. if (LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase) !=
  1212. FirstBaseOffsetInLayoutClass) {
  1213. // We found it, stop walking the chain.
  1214. break;
  1215. }
  1216. } else {
  1217. assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
  1218. "Primary base should always be at offset 0!");
  1219. }
  1220. if (!PrimaryBases.insert(PrimaryBase))
  1221. assert(false && "Found a duplicate primary base!");
  1222. RD = PrimaryBase;
  1223. }
  1224. // If the final overrider is an override of one of the primary bases,
  1225. // then we know that it will be used.
  1226. return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
  1227. }
  1228. /// FindNearestOverriddenMethod - Given a method, returns the overridden method
  1229. /// from the nearest base. Returns null if no method was found.
  1230. static const CXXMethodDecl *
  1231. FindNearestOverriddenMethod(const CXXMethodDecl *MD,
  1232. VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
  1233. OverriddenMethodsSetTy OverriddenMethods;
  1234. ComputeAllOverriddenMethods(MD, OverriddenMethods);
  1235. for (int I = Bases.size(), E = 0; I != E; --I) {
  1236. const CXXRecordDecl *PrimaryBase = Bases[I - 1];
  1237. // Now check the overriden methods.
  1238. for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
  1239. E = OverriddenMethods.end(); I != E; ++I) {
  1240. const CXXMethodDecl *OverriddenMD = *I;
  1241. // We found our overridden method.
  1242. if (OverriddenMD->getParent() == PrimaryBase)
  1243. return OverriddenMD;
  1244. }
  1245. }
  1246. return 0;
  1247. }
  1248. void
  1249. VTableBuilder::AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass,
  1250. const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
  1251. uint64_t FirstBaseOffsetInLayoutClass,
  1252. PrimaryBasesSetVectorTy &PrimaryBases) {
  1253. const CXXRecordDecl *RD = Base.getBase();
  1254. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1255. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  1256. uint64_t PrimaryBaseOffset;
  1257. uint64_t PrimaryBaseOffsetInLayoutClass;
  1258. if (Layout.getPrimaryBaseWasVirtual()) {
  1259. assert(Layout.getVBaseClassOffsetInBits(PrimaryBase) == 0 &&
  1260. "Primary vbase should have a zero offset!");
  1261. const ASTRecordLayout &MostDerivedClassLayout =
  1262. Context.getASTRecordLayout(MostDerivedClass);
  1263. PrimaryBaseOffset =
  1264. MostDerivedClassLayout.getVBaseClassOffsetInBits(PrimaryBase);
  1265. const ASTRecordLayout &LayoutClassLayout =
  1266. Context.getASTRecordLayout(LayoutClass);
  1267. PrimaryBaseOffsetInLayoutClass =
  1268. LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase);
  1269. } else {
  1270. assert(Layout.getBaseClassOffsetInBits(PrimaryBase) == 0 &&
  1271. "Primary base should have a zero offset!");
  1272. PrimaryBaseOffset = Base.getBaseOffset();
  1273. PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
  1274. }
  1275. AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
  1276. PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
  1277. FirstBaseOffsetInLayoutClass, PrimaryBases);
  1278. if (!PrimaryBases.insert(PrimaryBase))
  1279. assert(false && "Found a duplicate primary base!");
  1280. }
  1281. // Now go through all virtual member functions and add them.
  1282. for (CXXRecordDecl::method_iterator I = RD->method_begin(),
  1283. E = RD->method_end(); I != E; ++I) {
  1284. const CXXMethodDecl *MD = *I;
  1285. if (!MD->isVirtual())
  1286. continue;
  1287. // Get the final overrider.
  1288. FinalOverriders::OverriderInfo Overrider =
  1289. Overriders.getOverrider(MD, Base.getBaseOffset());
  1290. // Check if this virtual member function overrides a method in a primary
  1291. // base. If this is the case, and the return type doesn't require adjustment
  1292. // then we can just use the member function from the primary base.
  1293. if (const CXXMethodDecl *OverriddenMD =
  1294. FindNearestOverriddenMethod(MD, PrimaryBases)) {
  1295. if (ComputeReturnAdjustmentBaseOffset(Context, MD,
  1296. OverriddenMD).isEmpty()) {
  1297. // Replace the method info of the overridden method with our own
  1298. // method.
  1299. assert(MethodInfoMap.count(OverriddenMD) &&
  1300. "Did not find the overridden method!");
  1301. MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
  1302. MethodInfo MethodInfo(Base.getBaseOffset(),
  1303. BaseOffsetInLayoutClass,
  1304. OverriddenMethodInfo.VTableIndex);
  1305. assert(!MethodInfoMap.count(MD) &&
  1306. "Should not have method info for this method yet!");
  1307. MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
  1308. MethodInfoMap.erase(OverriddenMD);
  1309. // If the overridden method exists in a virtual base class or a direct
  1310. // or indirect base class of a virtual base class, we need to emit a
  1311. // thunk if we ever have a class hierarchy where the base class is not
  1312. // a primary base in the complete object.
  1313. if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
  1314. // Compute the this adjustment.
  1315. ThisAdjustment ThisAdjustment =
  1316. ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
  1317. Overrider);
  1318. if (ThisAdjustment.VCallOffsetOffset &&
  1319. Overrider.Method->getParent() == MostDerivedClass) {
  1320. // This is a virtual thunk for the most derived class, add it.
  1321. AddThunk(Overrider.Method,
  1322. ThunkInfo(ThisAdjustment, ReturnAdjustment()));
  1323. }
  1324. }
  1325. continue;
  1326. }
  1327. }
  1328. // Insert the method info for this method.
  1329. MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
  1330. Components.size());
  1331. assert(!MethodInfoMap.count(MD) &&
  1332. "Should not have method info for this method yet!");
  1333. MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
  1334. // Check if this overrider is going to be used.
  1335. const CXXMethodDecl *OverriderMD = Overrider.Method;
  1336. if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
  1337. FirstBaseInPrimaryBaseChain,
  1338. FirstBaseOffsetInLayoutClass)) {
  1339. Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
  1340. continue;
  1341. }
  1342. // Check if this overrider needs a return adjustment.
  1343. // We don't want to do this for pure virtual member functions.
  1344. BaseOffset ReturnAdjustmentOffset;
  1345. if (!OverriderMD->isPure()) {
  1346. ReturnAdjustmentOffset =
  1347. ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
  1348. }
  1349. ReturnAdjustment ReturnAdjustment =
  1350. ComputeReturnAdjustment(ReturnAdjustmentOffset);
  1351. AddMethod(Overrider.Method, ReturnAdjustment);
  1352. }
  1353. }
  1354. void VTableBuilder::LayoutVTable() {
  1355. LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass, 0),
  1356. /*BaseIsMorallyVirtual=*/false,
  1357. MostDerivedClassIsVirtual,
  1358. MostDerivedClassOffset);
  1359. VisitedVirtualBasesSetTy VBases;
  1360. // Determine the primary virtual bases.
  1361. DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
  1362. VBases);
  1363. VBases.clear();
  1364. LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
  1365. }
  1366. void
  1367. VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
  1368. bool BaseIsMorallyVirtual,
  1369. bool BaseIsVirtualInLayoutClass,
  1370. uint64_t OffsetInLayoutClass) {
  1371. assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
  1372. // Add vcall and vbase offsets for this vtable.
  1373. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
  1374. Base, BaseIsVirtualInLayoutClass,
  1375. OffsetInLayoutClass);
  1376. Components.append(Builder.components_begin(), Builder.components_end());
  1377. // Check if we need to add these vcall offsets.
  1378. if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
  1379. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
  1380. if (VCallOffsets.empty())
  1381. VCallOffsets = Builder.getVCallOffsets();
  1382. }
  1383. // If we're laying out the most derived class we want to keep track of the
  1384. // virtual base class offset offsets.
  1385. if (Base.getBase() == MostDerivedClass)
  1386. VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
  1387. // Add the offset to top.
  1388. // FIXME: We should not use / 8 here.
  1389. int64_t OffsetToTop = -(int64_t)(OffsetInLayoutClass -
  1390. MostDerivedClassOffset) / 8;
  1391. Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
  1392. // Next, add the RTTI.
  1393. Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
  1394. uint64_t AddressPoint = Components.size();
  1395. // Now go through all virtual member functions and add them.
  1396. PrimaryBasesSetVectorTy PrimaryBases;
  1397. AddMethods(Base, OffsetInLayoutClass, Base.getBase(), OffsetInLayoutClass,
  1398. PrimaryBases);
  1399. // Compute 'this' pointer adjustments.
  1400. ComputeThisAdjustments();
  1401. // Add all address points.
  1402. const CXXRecordDecl *RD = Base.getBase();
  1403. while (true) {
  1404. AddressPoints.insert(std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
  1405. AddressPoint));
  1406. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1407. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1408. if (!PrimaryBase)
  1409. break;
  1410. if (Layout.getPrimaryBaseWasVirtual()) {
  1411. // Check if this virtual primary base is a primary base in the layout
  1412. // class. If it's not, we don't want to add it.
  1413. const ASTRecordLayout &LayoutClassLayout =
  1414. Context.getASTRecordLayout(LayoutClass);
  1415. if (LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase) !=
  1416. OffsetInLayoutClass) {
  1417. // We don't want to add this class (or any of its primary bases).
  1418. break;
  1419. }
  1420. }
  1421. RD = PrimaryBase;
  1422. }
  1423. // Layout secondary vtables.
  1424. LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
  1425. }
  1426. void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
  1427. bool BaseIsMorallyVirtual,
  1428. uint64_t OffsetInLayoutClass) {
  1429. // Itanium C++ ABI 2.5.2:
  1430. // Following the primary virtual table of a derived class are secondary
  1431. // virtual tables for each of its proper base classes, except any primary
  1432. // base(s) with which it shares its primary virtual table.
  1433. const CXXRecordDecl *RD = Base.getBase();
  1434. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1435. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1436. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1437. E = RD->bases_end(); I != E; ++I) {
  1438. // Ignore virtual bases, we'll emit them later.
  1439. if (I->isVirtual())
  1440. continue;
  1441. const CXXRecordDecl *BaseDecl =
  1442. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1443. // Ignore bases that don't have a vtable.
  1444. if (!BaseDecl->isDynamicClass())
  1445. continue;
  1446. if (isBuildingConstructorVTable()) {
  1447. // Itanium C++ ABI 2.6.4:
  1448. // Some of the base class subobjects may not need construction virtual
  1449. // tables, which will therefore not be present in the construction
  1450. // virtual table group, even though the subobject virtual tables are
  1451. // present in the main virtual table group for the complete object.
  1452. if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
  1453. continue;
  1454. }
  1455. // Get the base offset of this base.
  1456. uint64_t RelativeBaseOffset = Layout.getBaseClassOffsetInBits(BaseDecl);
  1457. uint64_t BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
  1458. uint64_t BaseOffsetInLayoutClass = OffsetInLayoutClass + RelativeBaseOffset;
  1459. // Don't emit a secondary vtable for a primary base. We might however want
  1460. // to emit secondary vtables for other bases of this base.
  1461. if (BaseDecl == PrimaryBase) {
  1462. LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
  1463. BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
  1464. continue;
  1465. }
  1466. // Layout the primary vtable (and any secondary vtables) for this base.
  1467. LayoutPrimaryAndSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
  1468. BaseIsMorallyVirtual,
  1469. /*BaseIsVirtualInLayoutClass=*/false,
  1470. BaseOffsetInLayoutClass);
  1471. }
  1472. }
  1473. void
  1474. VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
  1475. uint64_t OffsetInLayoutClass,
  1476. VisitedVirtualBasesSetTy &VBases) {
  1477. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1478. // Check if this base has a primary base.
  1479. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  1480. // Check if it's virtual.
  1481. if (Layout.getPrimaryBaseWasVirtual()) {
  1482. bool IsPrimaryVirtualBase = true;
  1483. if (isBuildingConstructorVTable()) {
  1484. // Check if the base is actually a primary base in the class we use for
  1485. // layout.
  1486. const ASTRecordLayout &LayoutClassLayout =
  1487. Context.getASTRecordLayout(LayoutClass);
  1488. uint64_t PrimaryBaseOffsetInLayoutClass =
  1489. LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase);
  1490. // We know that the base is not a primary base in the layout class if
  1491. // the base offsets are different.
  1492. if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
  1493. IsPrimaryVirtualBase = false;
  1494. }
  1495. if (IsPrimaryVirtualBase)
  1496. PrimaryVirtualBases.insert(PrimaryBase);
  1497. }
  1498. }
  1499. // Traverse bases, looking for more primary virtual bases.
  1500. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1501. E = RD->bases_end(); I != E; ++I) {
  1502. const CXXRecordDecl *BaseDecl =
  1503. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1504. uint64_t BaseOffsetInLayoutClass;
  1505. if (I->isVirtual()) {
  1506. if (!VBases.insert(BaseDecl))
  1507. continue;
  1508. const ASTRecordLayout &LayoutClassLayout =
  1509. Context.getASTRecordLayout(LayoutClass);
  1510. BaseOffsetInLayoutClass =
  1511. LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl);
  1512. } else {
  1513. BaseOffsetInLayoutClass =
  1514. OffsetInLayoutClass + Layout.getBaseClassOffsetInBits(BaseDecl);
  1515. }
  1516. DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
  1517. }
  1518. }
  1519. void
  1520. VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
  1521. VisitedVirtualBasesSetTy &VBases) {
  1522. // Itanium C++ ABI 2.5.2:
  1523. // Then come the virtual base virtual tables, also in inheritance graph
  1524. // order, and again excluding primary bases (which share virtual tables with
  1525. // the classes for which they are primary).
  1526. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1527. E = RD->bases_end(); I != E; ++I) {
  1528. const CXXRecordDecl *BaseDecl =
  1529. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1530. // Check if this base needs a vtable. (If it's virtual, not a primary base
  1531. // of some other class, and we haven't visited it before).
  1532. if (I->isVirtual() && BaseDecl->isDynamicClass() &&
  1533. !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
  1534. const ASTRecordLayout &MostDerivedClassLayout =
  1535. Context.getASTRecordLayout(MostDerivedClass);
  1536. uint64_t BaseOffset =
  1537. MostDerivedClassLayout.getVBaseClassOffsetInBits(BaseDecl);
  1538. const ASTRecordLayout &LayoutClassLayout =
  1539. Context.getASTRecordLayout(LayoutClass);
  1540. uint64_t BaseOffsetInLayoutClass =
  1541. LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl);
  1542. LayoutPrimaryAndSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
  1543. /*BaseIsMorallyVirtual=*/true,
  1544. /*BaseIsVirtualInLayoutClass=*/true,
  1545. BaseOffsetInLayoutClass);
  1546. }
  1547. // We only need to check the base for virtual base vtables if it actually
  1548. // has virtual bases.
  1549. if (BaseDecl->getNumVBases())
  1550. LayoutVTablesForVirtualBases(BaseDecl, VBases);
  1551. }
  1552. }
  1553. /// dumpLayout - Dump the vtable layout.
  1554. void VTableBuilder::dumpLayout(llvm::raw_ostream& Out) {
  1555. if (isBuildingConstructorVTable()) {
  1556. Out << "Construction vtable for ('";
  1557. Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
  1558. // FIXME: Don't use / 8 .
  1559. Out << MostDerivedClassOffset / 8 << ") in '";
  1560. Out << LayoutClass->getQualifiedNameAsString();
  1561. } else {
  1562. Out << "Vtable for '";
  1563. Out << MostDerivedClass->getQualifiedNameAsString();
  1564. }
  1565. Out << "' (" << Components.size() << " entries).\n";
  1566. // Iterate through the address points and insert them into a new map where
  1567. // they are keyed by the index and not the base object.
  1568. // Since an address point can be shared by multiple subobjects, we use an
  1569. // STL multimap.
  1570. std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
  1571. for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
  1572. E = AddressPoints.end(); I != E; ++I) {
  1573. const BaseSubobject& Base = I->first;
  1574. uint64_t Index = I->second;
  1575. AddressPointsByIndex.insert(std::make_pair(Index, Base));
  1576. }
  1577. for (unsigned I = 0, E = Components.size(); I != E; ++I) {
  1578. uint64_t Index = I;
  1579. Out << llvm::format("%4d | ", I);
  1580. const VTableComponent &Component = Components[I];
  1581. // Dump the component.
  1582. switch (Component.getKind()) {
  1583. case VTableComponent::CK_VCallOffset:
  1584. Out << "vcall_offset (" << Component.getVCallOffset() << ")";
  1585. break;
  1586. case VTableComponent::CK_VBaseOffset:
  1587. Out << "vbase_offset (" << Component.getVBaseOffset() << ")";
  1588. break;
  1589. case VTableComponent::CK_OffsetToTop:
  1590. Out << "offset_to_top (" << Component.getOffsetToTop() << ")";
  1591. break;
  1592. case VTableComponent::CK_RTTI:
  1593. Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
  1594. break;
  1595. case VTableComponent::CK_FunctionPointer: {
  1596. const CXXMethodDecl *MD = Component.getFunctionDecl();
  1597. std::string Str =
  1598. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1599. MD);
  1600. Out << Str;
  1601. if (MD->isPure())
  1602. Out << " [pure]";
  1603. ThunkInfo Thunk = VTableThunks.lookup(I);
  1604. if (!Thunk.isEmpty()) {
  1605. // If this function pointer has a return adjustment, dump it.
  1606. if (!Thunk.Return.isEmpty()) {
  1607. Out << "\n [return adjustment: ";
  1608. Out << Thunk.Return.NonVirtual << " non-virtual";
  1609. if (Thunk.Return.VBaseOffsetOffset) {
  1610. Out << ", " << Thunk.Return.VBaseOffsetOffset;
  1611. Out << " vbase offset offset";
  1612. }
  1613. Out << ']';
  1614. }
  1615. // If this function pointer has a 'this' pointer adjustment, dump it.
  1616. if (!Thunk.This.isEmpty()) {
  1617. Out << "\n [this adjustment: ";
  1618. Out << Thunk.This.NonVirtual << " non-virtual";
  1619. if (Thunk.This.VCallOffsetOffset) {
  1620. Out << ", " << Thunk.This.VCallOffsetOffset;
  1621. Out << " vcall offset offset";
  1622. }
  1623. Out << ']';
  1624. }
  1625. }
  1626. break;
  1627. }
  1628. case VTableComponent::CK_CompleteDtorPointer:
  1629. case VTableComponent::CK_DeletingDtorPointer: {
  1630. bool IsComplete =
  1631. Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
  1632. const CXXDestructorDecl *DD = Component.getDestructorDecl();
  1633. Out << DD->getQualifiedNameAsString();
  1634. if (IsComplete)
  1635. Out << "() [complete]";
  1636. else
  1637. Out << "() [deleting]";
  1638. if (DD->isPure())
  1639. Out << " [pure]";
  1640. ThunkInfo Thunk = VTableThunks.lookup(I);
  1641. if (!Thunk.isEmpty()) {
  1642. // If this destructor has a 'this' pointer adjustment, dump it.
  1643. if (!Thunk.This.isEmpty()) {
  1644. Out << "\n [this adjustment: ";
  1645. Out << Thunk.This.NonVirtual << " non-virtual";
  1646. if (Thunk.This.VCallOffsetOffset) {
  1647. Out << ", " << Thunk.This.VCallOffsetOffset;
  1648. Out << " vcall offset offset";
  1649. }
  1650. Out << ']';
  1651. }
  1652. }
  1653. break;
  1654. }
  1655. case VTableComponent::CK_UnusedFunctionPointer: {
  1656. const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
  1657. std::string Str =
  1658. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1659. MD);
  1660. Out << "[unused] " << Str;
  1661. if (MD->isPure())
  1662. Out << " [pure]";
  1663. }
  1664. }
  1665. Out << '\n';
  1666. // Dump the next address point.
  1667. uint64_t NextIndex = Index + 1;
  1668. if (AddressPointsByIndex.count(NextIndex)) {
  1669. if (AddressPointsByIndex.count(NextIndex) == 1) {
  1670. const BaseSubobject &Base =
  1671. AddressPointsByIndex.find(NextIndex)->second;
  1672. // FIXME: Instead of dividing by 8, we should be using CharUnits.
  1673. Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
  1674. Out << ", " << Base.getBaseOffset() / 8 << ") vtable address --\n";
  1675. } else {
  1676. uint64_t BaseOffset =
  1677. AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
  1678. // We store the class names in a set to get a stable order.
  1679. std::set<std::string> ClassNames;
  1680. for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
  1681. AddressPointsByIndex.lower_bound(NextIndex), E =
  1682. AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
  1683. assert(I->second.getBaseOffset() == BaseOffset &&
  1684. "Invalid base offset!");
  1685. const CXXRecordDecl *RD = I->second.getBase();
  1686. ClassNames.insert(RD->getQualifiedNameAsString());
  1687. }
  1688. for (std::set<std::string>::const_iterator I = ClassNames.begin(),
  1689. E = ClassNames.end(); I != E; ++I) {
  1690. // FIXME: Instead of dividing by 8, we should be using CharUnits.
  1691. Out << " -- (" << *I;
  1692. Out << ", " << BaseOffset / 8 << ") vtable address --\n";
  1693. }
  1694. }
  1695. }
  1696. }
  1697. Out << '\n';
  1698. if (isBuildingConstructorVTable())
  1699. return;
  1700. if (MostDerivedClass->getNumVBases()) {
  1701. // We store the virtual base class names and their offsets in a map to get
  1702. // a stable order.
  1703. std::map<std::string, int64_t> ClassNamesAndOffsets;
  1704. for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
  1705. E = VBaseOffsetOffsets.end(); I != E; ++I) {
  1706. std::string ClassName = I->first->getQualifiedNameAsString();
  1707. int64_t OffsetOffset = I->second;
  1708. ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
  1709. }
  1710. Out << "Virtual base offset offsets for '";
  1711. Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
  1712. Out << ClassNamesAndOffsets.size();
  1713. Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
  1714. for (std::map<std::string, int64_t>::const_iterator I =
  1715. ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
  1716. I != E; ++I)
  1717. Out << " " << I->first << " | " << I->second << '\n';
  1718. Out << "\n";
  1719. }
  1720. if (!Thunks.empty()) {
  1721. // We store the method names in a map to get a stable order.
  1722. std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
  1723. for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
  1724. I != E; ++I) {
  1725. const CXXMethodDecl *MD = I->first;
  1726. std::string MethodName =
  1727. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1728. MD);
  1729. MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
  1730. }
  1731. for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
  1732. MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
  1733. I != E; ++I) {
  1734. const std::string &MethodName = I->first;
  1735. const CXXMethodDecl *MD = I->second;
  1736. ThunkInfoVectorTy ThunksVector = Thunks[MD];
  1737. std::sort(ThunksVector.begin(), ThunksVector.end());
  1738. Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
  1739. Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
  1740. for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
  1741. const ThunkInfo &Thunk = ThunksVector[I];
  1742. Out << llvm::format("%4d | ", I);
  1743. // If this function pointer has a return pointer adjustment, dump it.
  1744. if (!Thunk.Return.isEmpty()) {
  1745. Out << "return adjustment: " << Thunk.This.NonVirtual;
  1746. Out << " non-virtual";
  1747. if (Thunk.Return.VBaseOffsetOffset) {
  1748. Out << ", " << Thunk.Return.VBaseOffsetOffset;
  1749. Out << " vbase offset offset";
  1750. }
  1751. if (!Thunk.This.isEmpty())
  1752. Out << "\n ";
  1753. }
  1754. // If this function pointer has a 'this' pointer adjustment, dump it.
  1755. if (!Thunk.This.isEmpty()) {
  1756. Out << "this adjustment: ";
  1757. Out << Thunk.This.NonVirtual << " non-virtual";
  1758. if (Thunk.This.VCallOffsetOffset) {
  1759. Out << ", " << Thunk.This.VCallOffsetOffset;
  1760. Out << " vcall offset offset";
  1761. }
  1762. }
  1763. Out << '\n';
  1764. }
  1765. Out << '\n';
  1766. }
  1767. }
  1768. }
  1769. }
  1770. void CodeGenVTables::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
  1771. // Itanium C++ ABI 2.5.2:
  1772. // The order of the virtual function pointers in a virtual table is the
  1773. // order of declaration of the corresponding member functions in the class.
  1774. //
  1775. // There is an entry for any virtual function declared in a class,
  1776. // whether it is a new function or overrides a base class function,
  1777. // unless it overrides a function from the primary base, and conversion
  1778. // between their return types does not require an adjustment.
  1779. int64_t CurrentIndex = 0;
  1780. const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
  1781. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1782. if (PrimaryBase) {
  1783. assert(PrimaryBase->isDefinition() &&
  1784. "Should have the definition decl of the primary base!");
  1785. // Since the record decl shares its vtable pointer with the primary base
  1786. // we need to start counting at the end of the primary base's vtable.
  1787. CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
  1788. }
  1789. // Collect all the primary bases, so we can check whether methods override
  1790. // a method from the base.
  1791. VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
  1792. for (ASTRecordLayout::primary_base_info_iterator
  1793. I = Layout.primary_base_begin(), E = Layout.primary_base_end();
  1794. I != E; ++I)
  1795. PrimaryBases.insert((*I).getBase());
  1796. const CXXDestructorDecl *ImplicitVirtualDtor = 0;
  1797. for (CXXRecordDecl::method_iterator i = RD->method_begin(),
  1798. e = RD->method_end(); i != e; ++i) {
  1799. const CXXMethodDecl *MD = *i;
  1800. // We only want virtual methods.
  1801. if (!MD->isVirtual())
  1802. continue;
  1803. // Check if this method overrides a method in the primary base.
  1804. if (const CXXMethodDecl *OverriddenMD =
  1805. FindNearestOverriddenMethod(MD, PrimaryBases)) {
  1806. // Check if converting from the return type of the method to the
  1807. // return type of the overridden method requires conversion.
  1808. if (ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD,
  1809. OverriddenMD).isEmpty()) {
  1810. // This index is shared between the index in the vtable of the primary
  1811. // base class.
  1812. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1813. const CXXDestructorDecl *OverriddenDD =
  1814. cast<CXXDestructorDecl>(OverriddenMD);
  1815. // Add both the complete and deleting entries.
  1816. MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
  1817. getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
  1818. MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
  1819. getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
  1820. } else {
  1821. MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
  1822. }
  1823. // We don't need to add an entry for this method.
  1824. continue;
  1825. }
  1826. }
  1827. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1828. if (MD->isImplicit()) {
  1829. assert(!ImplicitVirtualDtor &&
  1830. "Did already see an implicit virtual dtor!");
  1831. ImplicitVirtualDtor = DD;
  1832. continue;
  1833. }
  1834. // Add the complete dtor.
  1835. MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
  1836. // Add the deleting dtor.
  1837. MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
  1838. } else {
  1839. // Add the entry.
  1840. MethodVTableIndices[MD] = CurrentIndex++;
  1841. }
  1842. }
  1843. if (ImplicitVirtualDtor) {
  1844. // Itanium C++ ABI 2.5.2:
  1845. // If a class has an implicitly-defined virtual destructor,
  1846. // its entries come after the declared virtual function pointers.
  1847. // Add the complete dtor.
  1848. MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
  1849. CurrentIndex++;
  1850. // Add the deleting dtor.
  1851. MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
  1852. CurrentIndex++;
  1853. }
  1854. NumVirtualFunctionPointers[RD] = CurrentIndex;
  1855. }
  1856. bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) {
  1857. assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
  1858. TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
  1859. if (TSK == TSK_ExplicitInstantiationDeclaration)
  1860. return false;
  1861. const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
  1862. if (!KeyFunction)
  1863. return true;
  1864. // Itanium C++ ABI, 5.2.6 Instantiated Templates:
  1865. // An instantiation of a class template requires:
  1866. // - In the object where instantiated, the virtual table...
  1867. if (TSK == TSK_ImplicitInstantiation ||
  1868. TSK == TSK_ExplicitInstantiationDefinition)
  1869. return true;
  1870. return KeyFunction->hasBody();
  1871. }
  1872. uint64_t CodeGenVTables::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
  1873. llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
  1874. NumVirtualFunctionPointers.find(RD);
  1875. if (I != NumVirtualFunctionPointers.end())
  1876. return I->second;
  1877. ComputeMethodVTableIndices(RD);
  1878. I = NumVirtualFunctionPointers.find(RD);
  1879. assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
  1880. return I->second;
  1881. }
  1882. uint64_t CodeGenVTables::getMethodVTableIndex(GlobalDecl GD) {
  1883. MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
  1884. if (I != MethodVTableIndices.end())
  1885. return I->second;
  1886. const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  1887. ComputeMethodVTableIndices(RD);
  1888. I = MethodVTableIndices.find(GD);
  1889. assert(I != MethodVTableIndices.end() && "Did not find index!");
  1890. return I->second;
  1891. }
  1892. int64_t CodeGenVTables::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
  1893. const CXXRecordDecl *VBase) {
  1894. ClassPairTy ClassPair(RD, VBase);
  1895. VirtualBaseClassOffsetOffsetsMapTy::iterator I =
  1896. VirtualBaseClassOffsetOffsets.find(ClassPair);
  1897. if (I != VirtualBaseClassOffsetOffsets.end())
  1898. return I->second;
  1899. VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
  1900. BaseSubobject(RD, 0),
  1901. /*BaseIsVirtual=*/false,
  1902. /*OffsetInLayoutClass=*/0);
  1903. for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
  1904. Builder.getVBaseOffsetOffsets().begin(),
  1905. E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
  1906. // Insert all types.
  1907. ClassPairTy ClassPair(RD, I->first);
  1908. VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
  1909. }
  1910. I = VirtualBaseClassOffsetOffsets.find(ClassPair);
  1911. assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
  1912. return I->second;
  1913. }
  1914. uint64_t
  1915. CodeGenVTables::getAddressPoint(BaseSubobject Base, const CXXRecordDecl *RD) {
  1916. assert(AddressPoints.count(std::make_pair(RD, Base)) &&
  1917. "Did not find address point!");
  1918. uint64_t AddressPoint = AddressPoints.lookup(std::make_pair(RD, Base));
  1919. assert(AddressPoint && "Address point must not be zero!");
  1920. return AddressPoint;
  1921. }
  1922. llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
  1923. const ThunkInfo &Thunk) {
  1924. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1925. // Compute the mangled name.
  1926. llvm::SmallString<256> Name;
  1927. if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
  1928. getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
  1929. Thunk.This, Name);
  1930. else
  1931. getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Name);
  1932. const llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
  1933. return GetOrCreateLLVMFunction(Name, Ty, GD);
  1934. }
  1935. static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
  1936. llvm::Value *Ptr,
  1937. int64_t NonVirtualAdjustment,
  1938. int64_t VirtualAdjustment) {
  1939. if (!NonVirtualAdjustment && !VirtualAdjustment)
  1940. return Ptr;
  1941. const llvm::Type *Int8PtrTy =
  1942. llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
  1943. llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
  1944. if (NonVirtualAdjustment) {
  1945. // Do the non-virtual adjustment.
  1946. V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
  1947. }
  1948. if (VirtualAdjustment) {
  1949. const llvm::Type *PtrDiffTy =
  1950. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  1951. // Do the virtual adjustment.
  1952. llvm::Value *VTablePtrPtr =
  1953. CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
  1954. llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
  1955. llvm::Value *OffsetPtr =
  1956. CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
  1957. OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
  1958. // Load the adjustment offset from the vtable.
  1959. llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
  1960. // Adjust our pointer.
  1961. V = CGF.Builder.CreateInBoundsGEP(V, Offset);
  1962. }
  1963. // Cast back to the original type.
  1964. return CGF.Builder.CreateBitCast(V, Ptr->getType());
  1965. }
  1966. static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
  1967. const ThunkInfo &Thunk, llvm::Function *Fn) {
  1968. CGM.setGlobalVisibility(Fn, MD, /*ForDef*/ true);
  1969. if (!CGM.getCodeGenOpts().HiddenWeakVTables)
  1970. return;
  1971. // If the thunk has weak/linkonce linkage, but the function must be
  1972. // emitted in every translation unit that references it, then we can
  1973. // emit its thunks with hidden visibility, since its thunks must be
  1974. // emitted when the function is.
  1975. // This follows CodeGenModule::setTypeVisibility; see the comments
  1976. // there for explanation.
  1977. if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
  1978. Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
  1979. Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  1980. return;
  1981. if (MD->hasAttr<VisibilityAttr>())
  1982. return;
  1983. switch (MD->getTemplateSpecializationKind()) {
  1984. case TSK_ExplicitInstantiationDefinition:
  1985. case TSK_ExplicitInstantiationDeclaration:
  1986. return;
  1987. case TSK_Undeclared:
  1988. break;
  1989. case TSK_ExplicitSpecialization:
  1990. case TSK_ImplicitInstantiation:
  1991. if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables)
  1992. return;
  1993. break;
  1994. }
  1995. // If there's an explicit definition, and that definition is
  1996. // out-of-line, then we can't assume that all users will have a
  1997. // definition to emit.
  1998. const FunctionDecl *Def = 0;
  1999. if (MD->hasBody(Def) && Def->isOutOfLine())
  2000. return;
  2001. Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
  2002. }
  2003. void CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
  2004. const ThunkInfo &Thunk) {
  2005. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  2006. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  2007. QualType ResultType = FPT->getResultType();
  2008. QualType ThisType = MD->getThisType(getContext());
  2009. FunctionArgList FunctionArgs;
  2010. // FIXME: It would be nice if more of this code could be shared with
  2011. // CodeGenFunction::GenerateCode.
  2012. // Create the implicit 'this' parameter declaration.
  2013. CurGD = GD;
  2014. CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
  2015. // Add the rest of the parameters.
  2016. for (FunctionDecl::param_const_iterator I = MD->param_begin(),
  2017. E = MD->param_end(); I != E; ++I) {
  2018. ParmVarDecl *Param = *I;
  2019. FunctionArgs.push_back(std::make_pair(Param, Param->getType()));
  2020. }
  2021. StartFunction(GlobalDecl(), ResultType, Fn, FunctionArgs, SourceLocation());
  2022. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  2023. // Adjust the 'this' pointer if necessary.
  2024. llvm::Value *AdjustedThisPtr =
  2025. PerformTypeAdjustment(*this, LoadCXXThis(),
  2026. Thunk.This.NonVirtual,
  2027. Thunk.This.VCallOffsetOffset);
  2028. CallArgList CallArgs;
  2029. // Add our adjusted 'this' pointer.
  2030. CallArgs.push_back(std::make_pair(RValue::get(AdjustedThisPtr), ThisType));
  2031. // Add the rest of the parameters.
  2032. for (FunctionDecl::param_const_iterator I = MD->param_begin(),
  2033. E = MD->param_end(); I != E; ++I) {
  2034. ParmVarDecl *Param = *I;
  2035. QualType ArgType = Param->getType();
  2036. RValue Arg = EmitDelegateCallArg(Param);
  2037. CallArgs.push_back(std::make_pair(Arg, ArgType));
  2038. }
  2039. // Get our callee.
  2040. const llvm::Type *Ty =
  2041. CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(GD),
  2042. FPT->isVariadic());
  2043. llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
  2044. const CGFunctionInfo &FnInfo =
  2045. CGM.getTypes().getFunctionInfo(ResultType, CallArgs,
  2046. FPT->getExtInfo());
  2047. // Determine whether we have a return value slot to use.
  2048. ReturnValueSlot Slot;
  2049. if (!ResultType->isVoidType() &&
  2050. FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  2051. hasAggregateLLVMType(CurFnInfo->getReturnType()))
  2052. Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
  2053. // Now emit our call.
  2054. RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
  2055. if (!Thunk.Return.isEmpty()) {
  2056. // Emit the return adjustment.
  2057. bool NullCheckValue = !ResultType->isReferenceType();
  2058. llvm::BasicBlock *AdjustNull = 0;
  2059. llvm::BasicBlock *AdjustNotNull = 0;
  2060. llvm::BasicBlock *AdjustEnd = 0;
  2061. llvm::Value *ReturnValue = RV.getScalarVal();
  2062. if (NullCheckValue) {
  2063. AdjustNull = createBasicBlock("adjust.null");
  2064. AdjustNotNull = createBasicBlock("adjust.notnull");
  2065. AdjustEnd = createBasicBlock("adjust.end");
  2066. llvm::Value *IsNull = Builder.CreateIsNull(ReturnValue);
  2067. Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
  2068. EmitBlock(AdjustNotNull);
  2069. }
  2070. ReturnValue = PerformTypeAdjustment(*this, ReturnValue,
  2071. Thunk.Return.NonVirtual,
  2072. Thunk.Return.VBaseOffsetOffset);
  2073. if (NullCheckValue) {
  2074. Builder.CreateBr(AdjustEnd);
  2075. EmitBlock(AdjustNull);
  2076. Builder.CreateBr(AdjustEnd);
  2077. EmitBlock(AdjustEnd);
  2078. llvm::PHINode *PHI = Builder.CreatePHI(ReturnValue->getType());
  2079. PHI->reserveOperandSpace(2);
  2080. PHI->addIncoming(ReturnValue, AdjustNotNull);
  2081. PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
  2082. AdjustNull);
  2083. ReturnValue = PHI;
  2084. }
  2085. RV = RValue::get(ReturnValue);
  2086. }
  2087. if (!ResultType->isVoidType() && Slot.isNull())
  2088. CGM.getCXXABI().EmitReturnFromThunk(CGF, RV, ResultType);
  2089. FinishFunction();
  2090. // Set the right linkage.
  2091. CGM.setFunctionLinkage(MD, Fn);
  2092. // Set the right visibility.
  2093. setThunkVisibility(CGM, MD, Thunk, Fn);
  2094. }
  2095. void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk)
  2096. {
  2097. llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
  2098. // Strip off a bitcast if we got one back.
  2099. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  2100. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  2101. Entry = CE->getOperand(0);
  2102. }
  2103. // There's already a declaration with the same name, check if it has the same
  2104. // type or if we need to replace it.
  2105. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
  2106. CGM.getTypes().GetFunctionTypeForVTable(GD)) {
  2107. llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
  2108. // If the types mismatch then we have to rewrite the definition.
  2109. assert(OldThunkFn->isDeclaration() &&
  2110. "Shouldn't replace non-declaration");
  2111. // Remove the name from the old thunk function and get a new thunk.
  2112. OldThunkFn->setName(llvm::StringRef());
  2113. Entry = CGM.GetAddrOfThunk(GD, Thunk);
  2114. // If needed, replace the old thunk with a bitcast.
  2115. if (!OldThunkFn->use_empty()) {
  2116. llvm::Constant *NewPtrForOldDecl =
  2117. llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
  2118. OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
  2119. }
  2120. // Remove the old thunk.
  2121. OldThunkFn->eraseFromParent();
  2122. }
  2123. // Actually generate the thunk body.
  2124. llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
  2125. CodeGenFunction(CGM).GenerateThunk(ThunkFn, GD, Thunk);
  2126. }
  2127. void CodeGenVTables::EmitThunks(GlobalDecl GD)
  2128. {
  2129. const CXXMethodDecl *MD =
  2130. cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
  2131. // We don't need to generate thunks for the base destructor.
  2132. if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
  2133. return;
  2134. const CXXRecordDecl *RD = MD->getParent();
  2135. // Compute VTable related info for this class.
  2136. ComputeVTableRelatedInformation(RD, false);
  2137. ThunksMapTy::const_iterator I = Thunks.find(MD);
  2138. if (I == Thunks.end()) {
  2139. // We did not find a thunk for this method.
  2140. return;
  2141. }
  2142. const ThunkInfoVectorTy &ThunkInfoVector = I->second;
  2143. for (unsigned I = 0, E = ThunkInfoVector.size(); I != E; ++I)
  2144. EmitThunk(GD, ThunkInfoVector[I]);
  2145. }
  2146. void CodeGenVTables::ComputeVTableRelatedInformation(const CXXRecordDecl *RD,
  2147. bool RequireVTable) {
  2148. VTableLayoutData &Entry = VTableLayoutMap[RD];
  2149. // We may need to generate a definition for this vtable.
  2150. if (RequireVTable && !Entry.getInt()) {
  2151. if (ShouldEmitVTableInThisTU(RD))
  2152. CGM.DeferredVTables.push_back(RD);
  2153. Entry.setInt(true);
  2154. }
  2155. // Check if we've computed this information before.
  2156. if (Entry.getPointer())
  2157. return;
  2158. VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
  2159. // Add the VTable layout.
  2160. uint64_t NumVTableComponents = Builder.getNumVTableComponents();
  2161. uint64_t *LayoutData = new uint64_t[NumVTableComponents + 1];
  2162. Entry.setPointer(LayoutData);
  2163. // Store the number of components.
  2164. LayoutData[0] = NumVTableComponents;
  2165. // Store the components.
  2166. std::copy(Builder.vtable_components_data_begin(),
  2167. Builder.vtable_components_data_end(),
  2168. &LayoutData[1]);
  2169. // Add the known thunks.
  2170. Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
  2171. // Add the thunks needed in this vtable.
  2172. assert(!VTableThunksMap.count(RD) &&
  2173. "Thunks already exists for this vtable!");
  2174. VTableThunksTy &VTableThunks = VTableThunksMap[RD];
  2175. VTableThunks.append(Builder.vtable_thunks_begin(),
  2176. Builder.vtable_thunks_end());
  2177. // Sort them.
  2178. std::sort(VTableThunks.begin(), VTableThunks.end());
  2179. // Add the address points.
  2180. for (VTableBuilder::AddressPointsMapTy::const_iterator I =
  2181. Builder.address_points_begin(), E = Builder.address_points_end();
  2182. I != E; ++I) {
  2183. uint64_t &AddressPoint = AddressPoints[std::make_pair(RD, I->first)];
  2184. // Check if we already have the address points for this base.
  2185. assert(!AddressPoint && "Address point already exists for this base!");
  2186. AddressPoint = I->second;
  2187. }
  2188. // If we don't have the vbase information for this class, insert it.
  2189. // getVirtualBaseOffsetOffset will compute it separately without computing
  2190. // the rest of the vtable related information.
  2191. if (!RD->getNumVBases())
  2192. return;
  2193. const RecordType *VBaseRT =
  2194. RD->vbases_begin()->getType()->getAs<RecordType>();
  2195. const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
  2196. if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
  2197. return;
  2198. for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
  2199. Builder.getVBaseOffsetOffsets().begin(),
  2200. E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
  2201. // Insert all types.
  2202. ClassPairTy ClassPair(RD, I->first);
  2203. VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
  2204. }
  2205. }
  2206. llvm::Constant *
  2207. CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
  2208. const uint64_t *Components,
  2209. unsigned NumComponents,
  2210. const VTableThunksTy &VTableThunks) {
  2211. llvm::SmallVector<llvm::Constant *, 64> Inits;
  2212. const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
  2213. const llvm::Type *PtrDiffTy =
  2214. CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
  2215. QualType ClassType = CGM.getContext().getTagDeclType(RD);
  2216. llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
  2217. unsigned NextVTableThunkIndex = 0;
  2218. llvm::Constant* PureVirtualFn = 0;
  2219. for (unsigned I = 0; I != NumComponents; ++I) {
  2220. VTableComponent Component =
  2221. VTableComponent::getFromOpaqueInteger(Components[I]);
  2222. llvm::Constant *Init = 0;
  2223. switch (Component.getKind()) {
  2224. case VTableComponent::CK_VCallOffset:
  2225. Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVCallOffset());
  2226. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  2227. break;
  2228. case VTableComponent::CK_VBaseOffset:
  2229. Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVBaseOffset());
  2230. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  2231. break;
  2232. case VTableComponent::CK_OffsetToTop:
  2233. Init = llvm::ConstantInt::get(PtrDiffTy, Component.getOffsetToTop());
  2234. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  2235. break;
  2236. case VTableComponent::CK_RTTI:
  2237. Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
  2238. break;
  2239. case VTableComponent::CK_FunctionPointer:
  2240. case VTableComponent::CK_CompleteDtorPointer:
  2241. case VTableComponent::CK_DeletingDtorPointer: {
  2242. GlobalDecl GD;
  2243. // Get the right global decl.
  2244. switch (Component.getKind()) {
  2245. default:
  2246. llvm_unreachable("Unexpected vtable component kind");
  2247. case VTableComponent::CK_FunctionPointer:
  2248. GD = Component.getFunctionDecl();
  2249. break;
  2250. case VTableComponent::CK_CompleteDtorPointer:
  2251. GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
  2252. break;
  2253. case VTableComponent::CK_DeletingDtorPointer:
  2254. GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
  2255. break;
  2256. }
  2257. if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
  2258. // We have a pure virtual member function.
  2259. if (!PureVirtualFn) {
  2260. const llvm::FunctionType *Ty =
  2261. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
  2262. /*isVarArg=*/false);
  2263. PureVirtualFn =
  2264. CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
  2265. PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
  2266. Int8PtrTy);
  2267. }
  2268. Init = PureVirtualFn;
  2269. } else {
  2270. // Check if we should use a thunk.
  2271. if (NextVTableThunkIndex < VTableThunks.size() &&
  2272. VTableThunks[NextVTableThunkIndex].first == I) {
  2273. const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
  2274. Init = CGM.GetAddrOfThunk(GD, Thunk);
  2275. NextVTableThunkIndex++;
  2276. } else {
  2277. const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
  2278. Init = CGM.GetAddrOfFunction(GD, Ty);
  2279. }
  2280. Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
  2281. }
  2282. break;
  2283. }
  2284. case VTableComponent::CK_UnusedFunctionPointer:
  2285. Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
  2286. break;
  2287. };
  2288. Inits.push_back(Init);
  2289. }
  2290. llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
  2291. return llvm::ConstantArray::get(ArrayType, Inits.data(), Inits.size());
  2292. }
  2293. /// GetGlobalVariable - Will return a global variable of the given type.
  2294. /// If a variable with a different type already exists then a new variable
  2295. /// with the right type will be created.
  2296. /// FIXME: We should move this to CodeGenModule and rename it to something
  2297. /// better and then use it in CGVTT and CGRTTI.
  2298. static llvm::GlobalVariable *
  2299. GetGlobalVariable(llvm::Module &Module, llvm::StringRef Name,
  2300. const llvm::Type *Ty,
  2301. llvm::GlobalValue::LinkageTypes Linkage) {
  2302. llvm::GlobalVariable *GV = Module.getNamedGlobal(Name);
  2303. llvm::GlobalVariable *OldGV = 0;
  2304. if (GV) {
  2305. // Check if the variable has the right type.
  2306. if (GV->getType()->getElementType() == Ty)
  2307. return GV;
  2308. assert(GV->isDeclaration() && "Declaration has wrong type!");
  2309. OldGV = GV;
  2310. }
  2311. // Create a new variable.
  2312. GV = new llvm::GlobalVariable(Module, Ty, /*isConstant=*/true,
  2313. Linkage, 0, Name);
  2314. if (OldGV) {
  2315. // Replace occurrences of the old variable if needed.
  2316. GV->takeName(OldGV);
  2317. if (!OldGV->use_empty()) {
  2318. llvm::Constant *NewPtrForOldDecl =
  2319. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  2320. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  2321. }
  2322. OldGV->eraseFromParent();
  2323. }
  2324. return GV;
  2325. }
  2326. llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
  2327. llvm::SmallString<256> OutName;
  2328. CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, OutName);
  2329. llvm::StringRef Name = OutName.str();
  2330. ComputeVTableRelatedInformation(RD, true);
  2331. const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
  2332. llvm::ArrayType *ArrayType =
  2333. llvm::ArrayType::get(Int8PtrTy, getNumVTableComponents(RD));
  2334. return GetGlobalVariable(CGM.getModule(), Name, ArrayType,
  2335. llvm::GlobalValue::ExternalLinkage);
  2336. }
  2337. void
  2338. CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
  2339. llvm::GlobalVariable::LinkageTypes Linkage,
  2340. const CXXRecordDecl *RD) {
  2341. // Dump the vtable layout if necessary.
  2342. if (CGM.getLangOptions().DumpVTableLayouts) {
  2343. VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
  2344. Builder.dumpLayout(llvm::errs());
  2345. }
  2346. assert(VTableThunksMap.count(RD) &&
  2347. "No thunk status for this record decl!");
  2348. const VTableThunksTy& Thunks = VTableThunksMap[RD];
  2349. // Create and set the initializer.
  2350. llvm::Constant *Init =
  2351. CreateVTableInitializer(RD, getVTableComponentsData(RD),
  2352. getNumVTableComponents(RD), Thunks);
  2353. VTable->setInitializer(Init);
  2354. // Set the correct linkage.
  2355. VTable->setLinkage(Linkage);
  2356. // Set the right visibility.
  2357. CGM.setTypeVisibility(VTable, RD, /*ForRTTI*/ false, /*ForDef*/ true);
  2358. }
  2359. llvm::GlobalVariable *
  2360. CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
  2361. const BaseSubobject &Base,
  2362. bool BaseIsVirtual,
  2363. VTableAddressPointsMapTy& AddressPoints) {
  2364. VTableBuilder Builder(*this, Base.getBase(), Base.getBaseOffset(),
  2365. /*MostDerivedClassIsVirtual=*/BaseIsVirtual, RD);
  2366. // Dump the vtable layout if necessary.
  2367. if (CGM.getLangOptions().DumpVTableLayouts)
  2368. Builder.dumpLayout(llvm::errs());
  2369. // Add the address points.
  2370. AddressPoints.insert(Builder.address_points_begin(),
  2371. Builder.address_points_end());
  2372. // Get the mangled construction vtable name.
  2373. llvm::SmallString<256> OutName;
  2374. CGM.getCXXABI().getMangleContext().
  2375. mangleCXXCtorVTable(RD, Base.getBaseOffset() / 8, Base.getBase(), OutName);
  2376. llvm::StringRef Name = OutName.str();
  2377. const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
  2378. llvm::ArrayType *ArrayType =
  2379. llvm::ArrayType::get(Int8PtrTy, Builder.getNumVTableComponents());
  2380. // Create the variable that will hold the construction vtable.
  2381. llvm::GlobalVariable *VTable =
  2382. GetGlobalVariable(CGM.getModule(), Name, ArrayType,
  2383. llvm::GlobalValue::InternalLinkage);
  2384. // Add the thunks.
  2385. VTableThunksTy VTableThunks;
  2386. VTableThunks.append(Builder.vtable_thunks_begin(),
  2387. Builder.vtable_thunks_end());
  2388. // Sort them.
  2389. std::sort(VTableThunks.begin(), VTableThunks.end());
  2390. // Create and set the initializer.
  2391. llvm::Constant *Init =
  2392. CreateVTableInitializer(Base.getBase(),
  2393. Builder.vtable_components_data_begin(),
  2394. Builder.getNumVTableComponents(), VTableThunks);
  2395. VTable->setInitializer(Init);
  2396. return VTable;
  2397. }
  2398. void
  2399. CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
  2400. const CXXRecordDecl *RD) {
  2401. llvm::GlobalVariable *&VTable = VTables[RD];
  2402. if (VTable) {
  2403. assert(VTable->getInitializer() && "VTable doesn't have a definition!");
  2404. return;
  2405. }
  2406. VTable = GetAddrOfVTable(RD);
  2407. EmitVTableDefinition(VTable, Linkage, RD);
  2408. GenerateVTT(Linkage, /*GenerateDefinition=*/true, RD);
  2409. // If this is the magic class __cxxabiv1::__fundamental_type_info,
  2410. // we will emit the typeinfo for the fundamental types. This is the
  2411. // same behaviour as GCC.
  2412. const DeclContext *DC = RD->getDeclContext();
  2413. if (RD->getIdentifier() &&
  2414. RD->getIdentifier()->isStr("__fundamental_type_info") &&
  2415. isa<NamespaceDecl>(DC) &&
  2416. cast<NamespaceDecl>(DC)->getIdentifier() &&
  2417. cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
  2418. DC->getParent()->isTranslationUnit())
  2419. CGM.EmitFundamentalRTTIDescriptors();
  2420. }