CGVTables.cpp 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065
  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.isPrimaryBaseVirtual();
  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.isPrimaryBaseVirtual()) {
  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.isPrimaryBaseVirtual()) {
  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.isPrimaryBaseVirtual()) {
  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. // There's no return adjustment from OverriddenMD and MD,
  1321. // but that doesn't mean there isn't one between MD and
  1322. // the final overrider.
  1323. BaseOffset ReturnAdjustmentOffset =
  1324. ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
  1325. ReturnAdjustment ReturnAdjustment =
  1326. ComputeReturnAdjustment(ReturnAdjustmentOffset);
  1327. // This is a virtual thunk for the most derived class, add it.
  1328. AddThunk(Overrider.Method,
  1329. ThunkInfo(ThisAdjustment, ReturnAdjustment));
  1330. }
  1331. }
  1332. continue;
  1333. }
  1334. }
  1335. // Insert the method info for this method.
  1336. MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
  1337. Components.size());
  1338. assert(!MethodInfoMap.count(MD) &&
  1339. "Should not have method info for this method yet!");
  1340. MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
  1341. // Check if this overrider is going to be used.
  1342. const CXXMethodDecl *OverriderMD = Overrider.Method;
  1343. if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
  1344. FirstBaseInPrimaryBaseChain,
  1345. FirstBaseOffsetInLayoutClass)) {
  1346. Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
  1347. continue;
  1348. }
  1349. // Check if this overrider needs a return adjustment.
  1350. // We don't want to do this for pure virtual member functions.
  1351. BaseOffset ReturnAdjustmentOffset;
  1352. if (!OverriderMD->isPure()) {
  1353. ReturnAdjustmentOffset =
  1354. ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
  1355. }
  1356. ReturnAdjustment ReturnAdjustment =
  1357. ComputeReturnAdjustment(ReturnAdjustmentOffset);
  1358. AddMethod(Overrider.Method, ReturnAdjustment);
  1359. }
  1360. }
  1361. void VTableBuilder::LayoutVTable() {
  1362. LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass, 0),
  1363. /*BaseIsMorallyVirtual=*/false,
  1364. MostDerivedClassIsVirtual,
  1365. MostDerivedClassOffset);
  1366. VisitedVirtualBasesSetTy VBases;
  1367. // Determine the primary virtual bases.
  1368. DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
  1369. VBases);
  1370. VBases.clear();
  1371. LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
  1372. }
  1373. void
  1374. VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
  1375. bool BaseIsMorallyVirtual,
  1376. bool BaseIsVirtualInLayoutClass,
  1377. uint64_t OffsetInLayoutClass) {
  1378. assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
  1379. // Add vcall and vbase offsets for this vtable.
  1380. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
  1381. Base, BaseIsVirtualInLayoutClass,
  1382. OffsetInLayoutClass);
  1383. Components.append(Builder.components_begin(), Builder.components_end());
  1384. // Check if we need to add these vcall offsets.
  1385. if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
  1386. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
  1387. if (VCallOffsets.empty())
  1388. VCallOffsets = Builder.getVCallOffsets();
  1389. }
  1390. // If we're laying out the most derived class we want to keep track of the
  1391. // virtual base class offset offsets.
  1392. if (Base.getBase() == MostDerivedClass)
  1393. VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
  1394. // Add the offset to top.
  1395. // FIXME: We should not use / 8 here.
  1396. int64_t OffsetToTop = -(int64_t)(OffsetInLayoutClass -
  1397. MostDerivedClassOffset) / 8;
  1398. Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
  1399. // Next, add the RTTI.
  1400. Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
  1401. uint64_t AddressPoint = Components.size();
  1402. // Now go through all virtual member functions and add them.
  1403. PrimaryBasesSetVectorTy PrimaryBases;
  1404. AddMethods(Base, OffsetInLayoutClass, Base.getBase(), OffsetInLayoutClass,
  1405. PrimaryBases);
  1406. // Compute 'this' pointer adjustments.
  1407. ComputeThisAdjustments();
  1408. // Add all address points.
  1409. const CXXRecordDecl *RD = Base.getBase();
  1410. while (true) {
  1411. AddressPoints.insert(std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
  1412. AddressPoint));
  1413. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1414. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1415. if (!PrimaryBase)
  1416. break;
  1417. if (Layout.isPrimaryBaseVirtual()) {
  1418. // Check if this virtual primary base is a primary base in the layout
  1419. // class. If it's not, we don't want to add it.
  1420. const ASTRecordLayout &LayoutClassLayout =
  1421. Context.getASTRecordLayout(LayoutClass);
  1422. if (LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase) !=
  1423. OffsetInLayoutClass) {
  1424. // We don't want to add this class (or any of its primary bases).
  1425. break;
  1426. }
  1427. }
  1428. RD = PrimaryBase;
  1429. }
  1430. // Layout secondary vtables.
  1431. LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
  1432. }
  1433. void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
  1434. bool BaseIsMorallyVirtual,
  1435. uint64_t OffsetInLayoutClass) {
  1436. // Itanium C++ ABI 2.5.2:
  1437. // Following the primary virtual table of a derived class are secondary
  1438. // virtual tables for each of its proper base classes, except any primary
  1439. // base(s) with which it shares its primary virtual table.
  1440. const CXXRecordDecl *RD = Base.getBase();
  1441. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1442. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1443. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1444. E = RD->bases_end(); I != E; ++I) {
  1445. // Ignore virtual bases, we'll emit them later.
  1446. if (I->isVirtual())
  1447. continue;
  1448. const CXXRecordDecl *BaseDecl =
  1449. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1450. // Ignore bases that don't have a vtable.
  1451. if (!BaseDecl->isDynamicClass())
  1452. continue;
  1453. if (isBuildingConstructorVTable()) {
  1454. // Itanium C++ ABI 2.6.4:
  1455. // Some of the base class subobjects may not need construction virtual
  1456. // tables, which will therefore not be present in the construction
  1457. // virtual table group, even though the subobject virtual tables are
  1458. // present in the main virtual table group for the complete object.
  1459. if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
  1460. continue;
  1461. }
  1462. // Get the base offset of this base.
  1463. uint64_t RelativeBaseOffset = Layout.getBaseClassOffsetInBits(BaseDecl);
  1464. uint64_t BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
  1465. uint64_t BaseOffsetInLayoutClass = OffsetInLayoutClass + RelativeBaseOffset;
  1466. // Don't emit a secondary vtable for a primary base. We might however want
  1467. // to emit secondary vtables for other bases of this base.
  1468. if (BaseDecl == PrimaryBase) {
  1469. LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
  1470. BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
  1471. continue;
  1472. }
  1473. // Layout the primary vtable (and any secondary vtables) for this base.
  1474. LayoutPrimaryAndSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
  1475. BaseIsMorallyVirtual,
  1476. /*BaseIsVirtualInLayoutClass=*/false,
  1477. BaseOffsetInLayoutClass);
  1478. }
  1479. }
  1480. void
  1481. VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
  1482. uint64_t OffsetInLayoutClass,
  1483. VisitedVirtualBasesSetTy &VBases) {
  1484. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1485. // Check if this base has a primary base.
  1486. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
  1487. // Check if it's virtual.
  1488. if (Layout.isPrimaryBaseVirtual()) {
  1489. bool IsPrimaryVirtualBase = true;
  1490. if (isBuildingConstructorVTable()) {
  1491. // Check if the base is actually a primary base in the class we use for
  1492. // layout.
  1493. const ASTRecordLayout &LayoutClassLayout =
  1494. Context.getASTRecordLayout(LayoutClass);
  1495. uint64_t PrimaryBaseOffsetInLayoutClass =
  1496. LayoutClassLayout.getVBaseClassOffsetInBits(PrimaryBase);
  1497. // We know that the base is not a primary base in the layout class if
  1498. // the base offsets are different.
  1499. if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
  1500. IsPrimaryVirtualBase = false;
  1501. }
  1502. if (IsPrimaryVirtualBase)
  1503. PrimaryVirtualBases.insert(PrimaryBase);
  1504. }
  1505. }
  1506. // Traverse bases, looking for more primary virtual bases.
  1507. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1508. E = RD->bases_end(); I != E; ++I) {
  1509. const CXXRecordDecl *BaseDecl =
  1510. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1511. uint64_t BaseOffsetInLayoutClass;
  1512. if (I->isVirtual()) {
  1513. if (!VBases.insert(BaseDecl))
  1514. continue;
  1515. const ASTRecordLayout &LayoutClassLayout =
  1516. Context.getASTRecordLayout(LayoutClass);
  1517. BaseOffsetInLayoutClass =
  1518. LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl);
  1519. } else {
  1520. BaseOffsetInLayoutClass =
  1521. OffsetInLayoutClass + Layout.getBaseClassOffsetInBits(BaseDecl);
  1522. }
  1523. DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
  1524. }
  1525. }
  1526. void
  1527. VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
  1528. VisitedVirtualBasesSetTy &VBases) {
  1529. // Itanium C++ ABI 2.5.2:
  1530. // Then come the virtual base virtual tables, also in inheritance graph
  1531. // order, and again excluding primary bases (which share virtual tables with
  1532. // the classes for which they are primary).
  1533. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1534. E = RD->bases_end(); I != E; ++I) {
  1535. const CXXRecordDecl *BaseDecl =
  1536. cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1537. // Check if this base needs a vtable. (If it's virtual, not a primary base
  1538. // of some other class, and we haven't visited it before).
  1539. if (I->isVirtual() && BaseDecl->isDynamicClass() &&
  1540. !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
  1541. const ASTRecordLayout &MostDerivedClassLayout =
  1542. Context.getASTRecordLayout(MostDerivedClass);
  1543. uint64_t BaseOffset =
  1544. MostDerivedClassLayout.getVBaseClassOffsetInBits(BaseDecl);
  1545. const ASTRecordLayout &LayoutClassLayout =
  1546. Context.getASTRecordLayout(LayoutClass);
  1547. uint64_t BaseOffsetInLayoutClass =
  1548. LayoutClassLayout.getVBaseClassOffsetInBits(BaseDecl);
  1549. LayoutPrimaryAndSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
  1550. /*BaseIsMorallyVirtual=*/true,
  1551. /*BaseIsVirtualInLayoutClass=*/true,
  1552. BaseOffsetInLayoutClass);
  1553. }
  1554. // We only need to check the base for virtual base vtables if it actually
  1555. // has virtual bases.
  1556. if (BaseDecl->getNumVBases())
  1557. LayoutVTablesForVirtualBases(BaseDecl, VBases);
  1558. }
  1559. }
  1560. /// dumpLayout - Dump the vtable layout.
  1561. void VTableBuilder::dumpLayout(llvm::raw_ostream& Out) {
  1562. if (isBuildingConstructorVTable()) {
  1563. Out << "Construction vtable for ('";
  1564. Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
  1565. // FIXME: Don't use / 8 .
  1566. Out << MostDerivedClassOffset / 8 << ") in '";
  1567. Out << LayoutClass->getQualifiedNameAsString();
  1568. } else {
  1569. Out << "Vtable for '";
  1570. Out << MostDerivedClass->getQualifiedNameAsString();
  1571. }
  1572. Out << "' (" << Components.size() << " entries).\n";
  1573. // Iterate through the address points and insert them into a new map where
  1574. // they are keyed by the index and not the base object.
  1575. // Since an address point can be shared by multiple subobjects, we use an
  1576. // STL multimap.
  1577. std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
  1578. for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(),
  1579. E = AddressPoints.end(); I != E; ++I) {
  1580. const BaseSubobject& Base = I->first;
  1581. uint64_t Index = I->second;
  1582. AddressPointsByIndex.insert(std::make_pair(Index, Base));
  1583. }
  1584. for (unsigned I = 0, E = Components.size(); I != E; ++I) {
  1585. uint64_t Index = I;
  1586. Out << llvm::format("%4d | ", I);
  1587. const VTableComponent &Component = Components[I];
  1588. // Dump the component.
  1589. switch (Component.getKind()) {
  1590. case VTableComponent::CK_VCallOffset:
  1591. Out << "vcall_offset (" << Component.getVCallOffset() << ")";
  1592. break;
  1593. case VTableComponent::CK_VBaseOffset:
  1594. Out << "vbase_offset (" << Component.getVBaseOffset() << ")";
  1595. break;
  1596. case VTableComponent::CK_OffsetToTop:
  1597. Out << "offset_to_top (" << Component.getOffsetToTop() << ")";
  1598. break;
  1599. case VTableComponent::CK_RTTI:
  1600. Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
  1601. break;
  1602. case VTableComponent::CK_FunctionPointer: {
  1603. const CXXMethodDecl *MD = Component.getFunctionDecl();
  1604. std::string Str =
  1605. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1606. MD);
  1607. Out << Str;
  1608. if (MD->isPure())
  1609. Out << " [pure]";
  1610. ThunkInfo Thunk = VTableThunks.lookup(I);
  1611. if (!Thunk.isEmpty()) {
  1612. // If this function pointer has a return adjustment, dump it.
  1613. if (!Thunk.Return.isEmpty()) {
  1614. Out << "\n [return adjustment: ";
  1615. Out << Thunk.Return.NonVirtual << " non-virtual";
  1616. if (Thunk.Return.VBaseOffsetOffset) {
  1617. Out << ", " << Thunk.Return.VBaseOffsetOffset;
  1618. Out << " vbase offset offset";
  1619. }
  1620. Out << ']';
  1621. }
  1622. // If this function pointer has a 'this' pointer adjustment, dump it.
  1623. if (!Thunk.This.isEmpty()) {
  1624. Out << "\n [this adjustment: ";
  1625. Out << Thunk.This.NonVirtual << " non-virtual";
  1626. if (Thunk.This.VCallOffsetOffset) {
  1627. Out << ", " << Thunk.This.VCallOffsetOffset;
  1628. Out << " vcall offset offset";
  1629. }
  1630. Out << ']';
  1631. }
  1632. }
  1633. break;
  1634. }
  1635. case VTableComponent::CK_CompleteDtorPointer:
  1636. case VTableComponent::CK_DeletingDtorPointer: {
  1637. bool IsComplete =
  1638. Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
  1639. const CXXDestructorDecl *DD = Component.getDestructorDecl();
  1640. Out << DD->getQualifiedNameAsString();
  1641. if (IsComplete)
  1642. Out << "() [complete]";
  1643. else
  1644. Out << "() [deleting]";
  1645. if (DD->isPure())
  1646. Out << " [pure]";
  1647. ThunkInfo Thunk = VTableThunks.lookup(I);
  1648. if (!Thunk.isEmpty()) {
  1649. // If this destructor has a 'this' pointer adjustment, dump it.
  1650. if (!Thunk.This.isEmpty()) {
  1651. Out << "\n [this adjustment: ";
  1652. Out << Thunk.This.NonVirtual << " non-virtual";
  1653. if (Thunk.This.VCallOffsetOffset) {
  1654. Out << ", " << Thunk.This.VCallOffsetOffset;
  1655. Out << " vcall offset offset";
  1656. }
  1657. Out << ']';
  1658. }
  1659. }
  1660. break;
  1661. }
  1662. case VTableComponent::CK_UnusedFunctionPointer: {
  1663. const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
  1664. std::string Str =
  1665. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1666. MD);
  1667. Out << "[unused] " << Str;
  1668. if (MD->isPure())
  1669. Out << " [pure]";
  1670. }
  1671. }
  1672. Out << '\n';
  1673. // Dump the next address point.
  1674. uint64_t NextIndex = Index + 1;
  1675. if (AddressPointsByIndex.count(NextIndex)) {
  1676. if (AddressPointsByIndex.count(NextIndex) == 1) {
  1677. const BaseSubobject &Base =
  1678. AddressPointsByIndex.find(NextIndex)->second;
  1679. // FIXME: Instead of dividing by 8, we should be using CharUnits.
  1680. Out << " -- (" << Base.getBase()->getQualifiedNameAsString();
  1681. Out << ", " << Base.getBaseOffset() / 8 << ") vtable address --\n";
  1682. } else {
  1683. uint64_t BaseOffset =
  1684. AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
  1685. // We store the class names in a set to get a stable order.
  1686. std::set<std::string> ClassNames;
  1687. for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
  1688. AddressPointsByIndex.lower_bound(NextIndex), E =
  1689. AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
  1690. assert(I->second.getBaseOffset() == BaseOffset &&
  1691. "Invalid base offset!");
  1692. const CXXRecordDecl *RD = I->second.getBase();
  1693. ClassNames.insert(RD->getQualifiedNameAsString());
  1694. }
  1695. for (std::set<std::string>::const_iterator I = ClassNames.begin(),
  1696. E = ClassNames.end(); I != E; ++I) {
  1697. // FIXME: Instead of dividing by 8, we should be using CharUnits.
  1698. Out << " -- (" << *I;
  1699. Out << ", " << BaseOffset / 8 << ") vtable address --\n";
  1700. }
  1701. }
  1702. }
  1703. }
  1704. Out << '\n';
  1705. if (isBuildingConstructorVTable())
  1706. return;
  1707. if (MostDerivedClass->getNumVBases()) {
  1708. // We store the virtual base class names and their offsets in a map to get
  1709. // a stable order.
  1710. std::map<std::string, int64_t> ClassNamesAndOffsets;
  1711. for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
  1712. E = VBaseOffsetOffsets.end(); I != E; ++I) {
  1713. std::string ClassName = I->first->getQualifiedNameAsString();
  1714. int64_t OffsetOffset = I->second;
  1715. ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
  1716. }
  1717. Out << "Virtual base offset offsets for '";
  1718. Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
  1719. Out << ClassNamesAndOffsets.size();
  1720. Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
  1721. for (std::map<std::string, int64_t>::const_iterator I =
  1722. ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end();
  1723. I != E; ++I)
  1724. Out << " " << I->first << " | " << I->second << '\n';
  1725. Out << "\n";
  1726. }
  1727. if (!Thunks.empty()) {
  1728. // We store the method names in a map to get a stable order.
  1729. std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
  1730. for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
  1731. I != E; ++I) {
  1732. const CXXMethodDecl *MD = I->first;
  1733. std::string MethodName =
  1734. PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
  1735. MD);
  1736. MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
  1737. }
  1738. for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
  1739. MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end();
  1740. I != E; ++I) {
  1741. const std::string &MethodName = I->first;
  1742. const CXXMethodDecl *MD = I->second;
  1743. ThunkInfoVectorTy ThunksVector = Thunks[MD];
  1744. std::sort(ThunksVector.begin(), ThunksVector.end());
  1745. Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
  1746. Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
  1747. for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
  1748. const ThunkInfo &Thunk = ThunksVector[I];
  1749. Out << llvm::format("%4d | ", I);
  1750. // If this function pointer has a return pointer adjustment, dump it.
  1751. if (!Thunk.Return.isEmpty()) {
  1752. Out << "return adjustment: " << Thunk.This.NonVirtual;
  1753. Out << " non-virtual";
  1754. if (Thunk.Return.VBaseOffsetOffset) {
  1755. Out << ", " << Thunk.Return.VBaseOffsetOffset;
  1756. Out << " vbase offset offset";
  1757. }
  1758. if (!Thunk.This.isEmpty())
  1759. Out << "\n ";
  1760. }
  1761. // If this function pointer has a 'this' pointer adjustment, dump it.
  1762. if (!Thunk.This.isEmpty()) {
  1763. Out << "this adjustment: ";
  1764. Out << Thunk.This.NonVirtual << " non-virtual";
  1765. if (Thunk.This.VCallOffsetOffset) {
  1766. Out << ", " << Thunk.This.VCallOffsetOffset;
  1767. Out << " vcall offset offset";
  1768. }
  1769. }
  1770. Out << '\n';
  1771. }
  1772. Out << '\n';
  1773. }
  1774. }
  1775. }
  1776. }
  1777. static void
  1778. CollectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
  1779. VTableBuilder::PrimaryBasesSetVectorTy &PrimaryBases) {
  1780. while (RD) {
  1781. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1782. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1783. if (PrimaryBase)
  1784. PrimaryBases.insert(PrimaryBase);
  1785. RD = PrimaryBase;
  1786. }
  1787. }
  1788. void CodeGenVTables::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
  1789. // Itanium C++ ABI 2.5.2:
  1790. // The order of the virtual function pointers in a virtual table is the
  1791. // order of declaration of the corresponding member functions in the class.
  1792. //
  1793. // There is an entry for any virtual function declared in a class,
  1794. // whether it is a new function or overrides a base class function,
  1795. // unless it overrides a function from the primary base, and conversion
  1796. // between their return types does not require an adjustment.
  1797. int64_t CurrentIndex = 0;
  1798. const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
  1799. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  1800. if (PrimaryBase) {
  1801. assert(PrimaryBase->isDefinition() &&
  1802. "Should have the definition decl of the primary base!");
  1803. // Since the record decl shares its vtable pointer with the primary base
  1804. // we need to start counting at the end of the primary base's vtable.
  1805. CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
  1806. }
  1807. // Collect all the primary bases, so we can check whether methods override
  1808. // a method from the base.
  1809. VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
  1810. CollectPrimaryBases(RD, CGM.getContext(), PrimaryBases);
  1811. const CXXDestructorDecl *ImplicitVirtualDtor = 0;
  1812. for (CXXRecordDecl::method_iterator i = RD->method_begin(),
  1813. e = RD->method_end(); i != e; ++i) {
  1814. const CXXMethodDecl *MD = *i;
  1815. // We only want virtual methods.
  1816. if (!MD->isVirtual())
  1817. continue;
  1818. // Check if this method overrides a method in the primary base.
  1819. if (const CXXMethodDecl *OverriddenMD =
  1820. FindNearestOverriddenMethod(MD, PrimaryBases)) {
  1821. // Check if converting from the return type of the method to the
  1822. // return type of the overridden method requires conversion.
  1823. if (ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD,
  1824. OverriddenMD).isEmpty()) {
  1825. // This index is shared between the index in the vtable of the primary
  1826. // base class.
  1827. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1828. const CXXDestructorDecl *OverriddenDD =
  1829. cast<CXXDestructorDecl>(OverriddenMD);
  1830. // Add both the complete and deleting entries.
  1831. MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] =
  1832. getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
  1833. MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] =
  1834. getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
  1835. } else {
  1836. MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
  1837. }
  1838. // We don't need to add an entry for this method.
  1839. continue;
  1840. }
  1841. }
  1842. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1843. if (MD->isImplicit()) {
  1844. assert(!ImplicitVirtualDtor &&
  1845. "Did already see an implicit virtual dtor!");
  1846. ImplicitVirtualDtor = DD;
  1847. continue;
  1848. }
  1849. // Add the complete dtor.
  1850. MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
  1851. // Add the deleting dtor.
  1852. MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
  1853. } else {
  1854. // Add the entry.
  1855. MethodVTableIndices[MD] = CurrentIndex++;
  1856. }
  1857. }
  1858. if (ImplicitVirtualDtor) {
  1859. // Itanium C++ ABI 2.5.2:
  1860. // If a class has an implicitly-defined virtual destructor,
  1861. // its entries come after the declared virtual function pointers.
  1862. // Add the complete dtor.
  1863. MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] =
  1864. CurrentIndex++;
  1865. // Add the deleting dtor.
  1866. MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] =
  1867. CurrentIndex++;
  1868. }
  1869. NumVirtualFunctionPointers[RD] = CurrentIndex;
  1870. }
  1871. bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) {
  1872. assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
  1873. TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
  1874. if (TSK == TSK_ExplicitInstantiationDeclaration)
  1875. return false;
  1876. const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
  1877. if (!KeyFunction)
  1878. return true;
  1879. // Itanium C++ ABI, 5.2.6 Instantiated Templates:
  1880. // An instantiation of a class template requires:
  1881. // - In the object where instantiated, the virtual table...
  1882. if (TSK == TSK_ImplicitInstantiation ||
  1883. TSK == TSK_ExplicitInstantiationDefinition)
  1884. return true;
  1885. // If we're building with optimization, we always emit VTables since that
  1886. // allows for virtual function calls to be devirtualized.
  1887. // (We don't want to do this in -fapple-kext mode however).
  1888. if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOptions().AppleKext)
  1889. return true;
  1890. return KeyFunction->hasBody();
  1891. }
  1892. uint64_t CodeGenVTables::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
  1893. llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I =
  1894. NumVirtualFunctionPointers.find(RD);
  1895. if (I != NumVirtualFunctionPointers.end())
  1896. return I->second;
  1897. ComputeMethodVTableIndices(RD);
  1898. I = NumVirtualFunctionPointers.find(RD);
  1899. assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
  1900. return I->second;
  1901. }
  1902. uint64_t CodeGenVTables::getMethodVTableIndex(GlobalDecl GD) {
  1903. MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
  1904. if (I != MethodVTableIndices.end())
  1905. return I->second;
  1906. const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  1907. ComputeMethodVTableIndices(RD);
  1908. I = MethodVTableIndices.find(GD);
  1909. assert(I != MethodVTableIndices.end() && "Did not find index!");
  1910. return I->second;
  1911. }
  1912. int64_t CodeGenVTables::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
  1913. const CXXRecordDecl *VBase) {
  1914. ClassPairTy ClassPair(RD, VBase);
  1915. VirtualBaseClassOffsetOffsetsMapTy::iterator I =
  1916. VirtualBaseClassOffsetOffsets.find(ClassPair);
  1917. if (I != VirtualBaseClassOffsetOffsets.end())
  1918. return I->second;
  1919. VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
  1920. BaseSubobject(RD, 0),
  1921. /*BaseIsVirtual=*/false,
  1922. /*OffsetInLayoutClass=*/0);
  1923. for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
  1924. Builder.getVBaseOffsetOffsets().begin(),
  1925. E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
  1926. // Insert all types.
  1927. ClassPairTy ClassPair(RD, I->first);
  1928. VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
  1929. }
  1930. I = VirtualBaseClassOffsetOffsets.find(ClassPair);
  1931. assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
  1932. return I->second;
  1933. }
  1934. uint64_t
  1935. CodeGenVTables::getAddressPoint(BaseSubobject Base, const CXXRecordDecl *RD) {
  1936. assert(AddressPoints.count(std::make_pair(RD, Base)) &&
  1937. "Did not find address point!");
  1938. uint64_t AddressPoint = AddressPoints.lookup(std::make_pair(RD, Base));
  1939. assert(AddressPoint && "Address point must not be zero!");
  1940. return AddressPoint;
  1941. }
  1942. llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
  1943. const ThunkInfo &Thunk) {
  1944. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1945. // Compute the mangled name.
  1946. llvm::SmallString<256> Name;
  1947. if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
  1948. getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
  1949. Thunk.This, Name);
  1950. else
  1951. getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Name);
  1952. const llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
  1953. return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/false);
  1954. }
  1955. static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
  1956. llvm::Value *Ptr,
  1957. int64_t NonVirtualAdjustment,
  1958. int64_t VirtualAdjustment) {
  1959. if (!NonVirtualAdjustment && !VirtualAdjustment)
  1960. return Ptr;
  1961. const llvm::Type *Int8PtrTy =
  1962. llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
  1963. llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
  1964. if (NonVirtualAdjustment) {
  1965. // Do the non-virtual adjustment.
  1966. V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
  1967. }
  1968. if (VirtualAdjustment) {
  1969. const llvm::Type *PtrDiffTy =
  1970. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  1971. // Do the virtual adjustment.
  1972. llvm::Value *VTablePtrPtr =
  1973. CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
  1974. llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
  1975. llvm::Value *OffsetPtr =
  1976. CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
  1977. OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
  1978. // Load the adjustment offset from the vtable.
  1979. llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
  1980. // Adjust our pointer.
  1981. V = CGF.Builder.CreateInBoundsGEP(V, Offset);
  1982. }
  1983. // Cast back to the original type.
  1984. return CGF.Builder.CreateBitCast(V, Ptr->getType());
  1985. }
  1986. static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
  1987. const ThunkInfo &Thunk, llvm::Function *Fn) {
  1988. CGM.setGlobalVisibility(Fn, MD);
  1989. if (!CGM.getCodeGenOpts().HiddenWeakVTables)
  1990. return;
  1991. // If the thunk has weak/linkonce linkage, but the function must be
  1992. // emitted in every translation unit that references it, then we can
  1993. // emit its thunks with hidden visibility, since its thunks must be
  1994. // emitted when the function is.
  1995. // This follows CodeGenModule::setTypeVisibility; see the comments
  1996. // there for explanation.
  1997. if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
  1998. Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
  1999. Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  2000. return;
  2001. if (MD->hasAttr<VisibilityAttr>())
  2002. return;
  2003. switch (MD->getTemplateSpecializationKind()) {
  2004. case TSK_ExplicitInstantiationDefinition:
  2005. case TSK_ExplicitInstantiationDeclaration:
  2006. return;
  2007. case TSK_Undeclared:
  2008. break;
  2009. case TSK_ExplicitSpecialization:
  2010. case TSK_ImplicitInstantiation:
  2011. if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables)
  2012. return;
  2013. break;
  2014. }
  2015. // If there's an explicit definition, and that definition is
  2016. // out-of-line, then we can't assume that all users will have a
  2017. // definition to emit.
  2018. const FunctionDecl *Def = 0;
  2019. if (MD->hasBody(Def) && Def->isOutOfLine())
  2020. return;
  2021. Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
  2022. }
  2023. void CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
  2024. const ThunkInfo &Thunk) {
  2025. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  2026. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  2027. QualType ResultType = FPT->getResultType();
  2028. QualType ThisType = MD->getThisType(getContext());
  2029. FunctionArgList FunctionArgs;
  2030. // FIXME: It would be nice if more of this code could be shared with
  2031. // CodeGenFunction::GenerateCode.
  2032. // Create the implicit 'this' parameter declaration.
  2033. CurGD = GD;
  2034. CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
  2035. // Add the rest of the parameters.
  2036. for (FunctionDecl::param_const_iterator I = MD->param_begin(),
  2037. E = MD->param_end(); I != E; ++I) {
  2038. ParmVarDecl *Param = *I;
  2039. FunctionArgs.push_back(std::make_pair(Param, Param->getType()));
  2040. }
  2041. StartFunction(GlobalDecl(), ResultType, Fn, FunctionArgs, SourceLocation());
  2042. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  2043. // Adjust the 'this' pointer if necessary.
  2044. llvm::Value *AdjustedThisPtr =
  2045. PerformTypeAdjustment(*this, LoadCXXThis(),
  2046. Thunk.This.NonVirtual,
  2047. Thunk.This.VCallOffsetOffset);
  2048. CallArgList CallArgs;
  2049. // Add our adjusted 'this' pointer.
  2050. CallArgs.push_back(std::make_pair(RValue::get(AdjustedThisPtr), ThisType));
  2051. // Add the rest of the parameters.
  2052. for (FunctionDecl::param_const_iterator I = MD->param_begin(),
  2053. E = MD->param_end(); I != E; ++I) {
  2054. ParmVarDecl *Param = *I;
  2055. QualType ArgType = Param->getType();
  2056. RValue Arg = EmitDelegateCallArg(Param);
  2057. CallArgs.push_back(std::make_pair(Arg, ArgType));
  2058. }
  2059. // Get our callee.
  2060. const llvm::Type *Ty =
  2061. CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(GD),
  2062. FPT->isVariadic());
  2063. llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
  2064. const CGFunctionInfo &FnInfo =
  2065. CGM.getTypes().getFunctionInfo(ResultType, CallArgs,
  2066. FPT->getExtInfo());
  2067. // Determine whether we have a return value slot to use.
  2068. ReturnValueSlot Slot;
  2069. if (!ResultType->isVoidType() &&
  2070. FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  2071. hasAggregateLLVMType(CurFnInfo->getReturnType()))
  2072. Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
  2073. // Now emit our call.
  2074. RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
  2075. if (!Thunk.Return.isEmpty()) {
  2076. // Emit the return adjustment.
  2077. bool NullCheckValue = !ResultType->isReferenceType();
  2078. llvm::BasicBlock *AdjustNull = 0;
  2079. llvm::BasicBlock *AdjustNotNull = 0;
  2080. llvm::BasicBlock *AdjustEnd = 0;
  2081. llvm::Value *ReturnValue = RV.getScalarVal();
  2082. if (NullCheckValue) {
  2083. AdjustNull = createBasicBlock("adjust.null");
  2084. AdjustNotNull = createBasicBlock("adjust.notnull");
  2085. AdjustEnd = createBasicBlock("adjust.end");
  2086. llvm::Value *IsNull = Builder.CreateIsNull(ReturnValue);
  2087. Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
  2088. EmitBlock(AdjustNotNull);
  2089. }
  2090. ReturnValue = PerformTypeAdjustment(*this, ReturnValue,
  2091. Thunk.Return.NonVirtual,
  2092. Thunk.Return.VBaseOffsetOffset);
  2093. if (NullCheckValue) {
  2094. Builder.CreateBr(AdjustEnd);
  2095. EmitBlock(AdjustNull);
  2096. Builder.CreateBr(AdjustEnd);
  2097. EmitBlock(AdjustEnd);
  2098. llvm::PHINode *PHI = Builder.CreatePHI(ReturnValue->getType());
  2099. PHI->reserveOperandSpace(2);
  2100. PHI->addIncoming(ReturnValue, AdjustNotNull);
  2101. PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
  2102. AdjustNull);
  2103. ReturnValue = PHI;
  2104. }
  2105. RV = RValue::get(ReturnValue);
  2106. }
  2107. if (!ResultType->isVoidType() && Slot.isNull())
  2108. CGM.getCXXABI().EmitReturnFromThunk(CGF, RV, ResultType);
  2109. FinishFunction();
  2110. // Set the right linkage.
  2111. CGM.setFunctionLinkage(MD, Fn);
  2112. // Set the right visibility.
  2113. setThunkVisibility(CGM, MD, Thunk, Fn);
  2114. }
  2115. void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk)
  2116. {
  2117. llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
  2118. // Strip off a bitcast if we got one back.
  2119. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  2120. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  2121. Entry = CE->getOperand(0);
  2122. }
  2123. // There's already a declaration with the same name, check if it has the same
  2124. // type or if we need to replace it.
  2125. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
  2126. CGM.getTypes().GetFunctionTypeForVTable(GD)) {
  2127. llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
  2128. // If the types mismatch then we have to rewrite the definition.
  2129. assert(OldThunkFn->isDeclaration() &&
  2130. "Shouldn't replace non-declaration");
  2131. // Remove the name from the old thunk function and get a new thunk.
  2132. OldThunkFn->setName(llvm::StringRef());
  2133. Entry = CGM.GetAddrOfThunk(GD, Thunk);
  2134. // If needed, replace the old thunk with a bitcast.
  2135. if (!OldThunkFn->use_empty()) {
  2136. llvm::Constant *NewPtrForOldDecl =
  2137. llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
  2138. OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
  2139. }
  2140. // Remove the old thunk.
  2141. OldThunkFn->eraseFromParent();
  2142. }
  2143. // Actually generate the thunk body.
  2144. llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
  2145. CodeGenFunction(CGM).GenerateThunk(ThunkFn, GD, Thunk);
  2146. }
  2147. void CodeGenVTables::EmitThunks(GlobalDecl GD)
  2148. {
  2149. const CXXMethodDecl *MD =
  2150. cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
  2151. // We don't need to generate thunks for the base destructor.
  2152. if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
  2153. return;
  2154. const CXXRecordDecl *RD = MD->getParent();
  2155. // Compute VTable related info for this class.
  2156. ComputeVTableRelatedInformation(RD, false);
  2157. ThunksMapTy::const_iterator I = Thunks.find(MD);
  2158. if (I == Thunks.end()) {
  2159. // We did not find a thunk for this method.
  2160. return;
  2161. }
  2162. const ThunkInfoVectorTy &ThunkInfoVector = I->second;
  2163. for (unsigned I = 0, E = ThunkInfoVector.size(); I != E; ++I)
  2164. EmitThunk(GD, ThunkInfoVector[I]);
  2165. }
  2166. void CodeGenVTables::ComputeVTableRelatedInformation(const CXXRecordDecl *RD,
  2167. bool RequireVTable) {
  2168. VTableLayoutData &Entry = VTableLayoutMap[RD];
  2169. // We may need to generate a definition for this vtable.
  2170. if (RequireVTable && !Entry.getInt()) {
  2171. if (ShouldEmitVTableInThisTU(RD))
  2172. CGM.DeferredVTables.push_back(RD);
  2173. Entry.setInt(true);
  2174. }
  2175. // Check if we've computed this information before.
  2176. if (Entry.getPointer())
  2177. return;
  2178. VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
  2179. // Add the VTable layout.
  2180. uint64_t NumVTableComponents = Builder.getNumVTableComponents();
  2181. // -fapple-kext adds an extra entry at end of vtbl.
  2182. bool IsAppleKext = CGM.getContext().getLangOptions().AppleKext;
  2183. if (IsAppleKext)
  2184. NumVTableComponents += 1;
  2185. uint64_t *LayoutData = new uint64_t[NumVTableComponents + 1];
  2186. if (IsAppleKext)
  2187. LayoutData[NumVTableComponents] = 0;
  2188. Entry.setPointer(LayoutData);
  2189. // Store the number of components.
  2190. LayoutData[0] = NumVTableComponents;
  2191. // Store the components.
  2192. std::copy(Builder.vtable_components_data_begin(),
  2193. Builder.vtable_components_data_end(),
  2194. &LayoutData[1]);
  2195. // Add the known thunks.
  2196. Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
  2197. // Add the thunks needed in this vtable.
  2198. assert(!VTableThunksMap.count(RD) &&
  2199. "Thunks already exists for this vtable!");
  2200. VTableThunksTy &VTableThunks = VTableThunksMap[RD];
  2201. VTableThunks.append(Builder.vtable_thunks_begin(),
  2202. Builder.vtable_thunks_end());
  2203. // Sort them.
  2204. std::sort(VTableThunks.begin(), VTableThunks.end());
  2205. // Add the address points.
  2206. for (VTableBuilder::AddressPointsMapTy::const_iterator I =
  2207. Builder.address_points_begin(), E = Builder.address_points_end();
  2208. I != E; ++I) {
  2209. uint64_t &AddressPoint = AddressPoints[std::make_pair(RD, I->first)];
  2210. // Check if we already have the address points for this base.
  2211. assert(!AddressPoint && "Address point already exists for this base!");
  2212. AddressPoint = I->second;
  2213. }
  2214. // If we don't have the vbase information for this class, insert it.
  2215. // getVirtualBaseOffsetOffset will compute it separately without computing
  2216. // the rest of the vtable related information.
  2217. if (!RD->getNumVBases())
  2218. return;
  2219. const RecordType *VBaseRT =
  2220. RD->vbases_begin()->getType()->getAs<RecordType>();
  2221. const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
  2222. if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
  2223. return;
  2224. for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
  2225. Builder.getVBaseOffsetOffsets().begin(),
  2226. E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
  2227. // Insert all types.
  2228. ClassPairTy ClassPair(RD, I->first);
  2229. VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
  2230. }
  2231. }
  2232. llvm::Constant *
  2233. CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
  2234. const uint64_t *Components,
  2235. unsigned NumComponents,
  2236. const VTableThunksTy &VTableThunks) {
  2237. llvm::SmallVector<llvm::Constant *, 64> Inits;
  2238. const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
  2239. const llvm::Type *PtrDiffTy =
  2240. CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
  2241. QualType ClassType = CGM.getContext().getTagDeclType(RD);
  2242. llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
  2243. unsigned NextVTableThunkIndex = 0;
  2244. llvm::Constant* PureVirtualFn = 0;
  2245. for (unsigned I = 0; I != NumComponents; ++I) {
  2246. VTableComponent Component =
  2247. VTableComponent::getFromOpaqueInteger(Components[I]);
  2248. llvm::Constant *Init = 0;
  2249. switch (Component.getKind()) {
  2250. case VTableComponent::CK_VCallOffset:
  2251. Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVCallOffset());
  2252. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  2253. break;
  2254. case VTableComponent::CK_VBaseOffset:
  2255. Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVBaseOffset());
  2256. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  2257. break;
  2258. case VTableComponent::CK_OffsetToTop:
  2259. Init = llvm::ConstantInt::get(PtrDiffTy, Component.getOffsetToTop());
  2260. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  2261. break;
  2262. case VTableComponent::CK_RTTI:
  2263. Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
  2264. break;
  2265. case VTableComponent::CK_FunctionPointer:
  2266. case VTableComponent::CK_CompleteDtorPointer:
  2267. case VTableComponent::CK_DeletingDtorPointer: {
  2268. GlobalDecl GD;
  2269. // Get the right global decl.
  2270. switch (Component.getKind()) {
  2271. default:
  2272. llvm_unreachable("Unexpected vtable component kind");
  2273. case VTableComponent::CK_FunctionPointer:
  2274. GD = Component.getFunctionDecl();
  2275. break;
  2276. case VTableComponent::CK_CompleteDtorPointer:
  2277. GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
  2278. break;
  2279. case VTableComponent::CK_DeletingDtorPointer:
  2280. GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
  2281. break;
  2282. }
  2283. if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
  2284. // We have a pure virtual member function.
  2285. if (!PureVirtualFn) {
  2286. const llvm::FunctionType *Ty =
  2287. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
  2288. /*isVarArg=*/false);
  2289. PureVirtualFn =
  2290. CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
  2291. PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
  2292. Int8PtrTy);
  2293. }
  2294. Init = PureVirtualFn;
  2295. } else {
  2296. // Check if we should use a thunk.
  2297. if (NextVTableThunkIndex < VTableThunks.size() &&
  2298. VTableThunks[NextVTableThunkIndex].first == I) {
  2299. const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
  2300. Init = CGM.GetAddrOfThunk(GD, Thunk);
  2301. NextVTableThunkIndex++;
  2302. } else {
  2303. const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
  2304. Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
  2305. }
  2306. Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
  2307. }
  2308. break;
  2309. }
  2310. case VTableComponent::CK_UnusedFunctionPointer:
  2311. Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
  2312. break;
  2313. };
  2314. Inits.push_back(Init);
  2315. }
  2316. llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
  2317. return llvm::ConstantArray::get(ArrayType, Inits.data(), Inits.size());
  2318. }
  2319. llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
  2320. llvm::SmallString<256> OutName;
  2321. CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, OutName);
  2322. llvm::StringRef Name = OutName.str();
  2323. ComputeVTableRelatedInformation(RD, true);
  2324. const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
  2325. llvm::ArrayType *ArrayType =
  2326. llvm::ArrayType::get(Int8PtrTy, getNumVTableComponents(RD));
  2327. llvm::GlobalVariable *GV =
  2328. CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
  2329. llvm::GlobalValue::ExternalLinkage);
  2330. GV->setUnnamedAddr(true);
  2331. return GV;
  2332. }
  2333. void
  2334. CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
  2335. llvm::GlobalVariable::LinkageTypes Linkage,
  2336. const CXXRecordDecl *RD) {
  2337. // Dump the vtable layout if necessary.
  2338. if (CGM.getLangOptions().DumpVTableLayouts) {
  2339. VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
  2340. Builder.dumpLayout(llvm::errs());
  2341. }
  2342. assert(VTableThunksMap.count(RD) &&
  2343. "No thunk status for this record decl!");
  2344. const VTableThunksTy& Thunks = VTableThunksMap[RD];
  2345. // Create and set the initializer.
  2346. llvm::Constant *Init =
  2347. CreateVTableInitializer(RD, getVTableComponentsData(RD),
  2348. getNumVTableComponents(RD), Thunks);
  2349. VTable->setInitializer(Init);
  2350. // Set the correct linkage.
  2351. VTable->setLinkage(Linkage);
  2352. // Set the right visibility.
  2353. CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
  2354. }
  2355. llvm::GlobalVariable *
  2356. CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
  2357. const BaseSubobject &Base,
  2358. bool BaseIsVirtual,
  2359. VTableAddressPointsMapTy& AddressPoints) {
  2360. VTableBuilder Builder(*this, Base.getBase(), Base.getBaseOffset(),
  2361. /*MostDerivedClassIsVirtual=*/BaseIsVirtual, RD);
  2362. // Dump the vtable layout if necessary.
  2363. if (CGM.getLangOptions().DumpVTableLayouts)
  2364. Builder.dumpLayout(llvm::errs());
  2365. // Add the address points.
  2366. AddressPoints.insert(Builder.address_points_begin(),
  2367. Builder.address_points_end());
  2368. // Get the mangled construction vtable name.
  2369. llvm::SmallString<256> OutName;
  2370. CGM.getCXXABI().getMangleContext().
  2371. mangleCXXCtorVTable(RD, Base.getBaseOffset() / 8, Base.getBase(), OutName);
  2372. llvm::StringRef Name = OutName.str();
  2373. const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
  2374. llvm::ArrayType *ArrayType =
  2375. llvm::ArrayType::get(Int8PtrTy, Builder.getNumVTableComponents());
  2376. // Create the variable that will hold the construction vtable.
  2377. llvm::GlobalVariable *VTable =
  2378. CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
  2379. llvm::GlobalValue::InternalLinkage);
  2380. // Add the thunks.
  2381. VTableThunksTy VTableThunks;
  2382. VTableThunks.append(Builder.vtable_thunks_begin(),
  2383. Builder.vtable_thunks_end());
  2384. // Sort them.
  2385. std::sort(VTableThunks.begin(), VTableThunks.end());
  2386. // Create and set the initializer.
  2387. llvm::Constant *Init =
  2388. CreateVTableInitializer(Base.getBase(),
  2389. Builder.vtable_components_data_begin(),
  2390. Builder.getNumVTableComponents(), VTableThunks);
  2391. VTable->setInitializer(Init);
  2392. return VTable;
  2393. }
  2394. void
  2395. CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
  2396. const CXXRecordDecl *RD) {
  2397. llvm::GlobalVariable *&VTable = VTables[RD];
  2398. if (VTable) {
  2399. assert(VTable->getInitializer() && "VTable doesn't have a definition!");
  2400. return;
  2401. }
  2402. VTable = GetAddrOfVTable(RD);
  2403. EmitVTableDefinition(VTable, Linkage, RD);
  2404. if (RD->getNumVBases()) {
  2405. llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
  2406. EmitVTTDefinition(VTT, Linkage, RD);
  2407. }
  2408. // If this is the magic class __cxxabiv1::__fundamental_type_info,
  2409. // we will emit the typeinfo for the fundamental types. This is the
  2410. // same behaviour as GCC.
  2411. const DeclContext *DC = RD->getDeclContext();
  2412. if (RD->getIdentifier() &&
  2413. RD->getIdentifier()->isStr("__fundamental_type_info") &&
  2414. isa<NamespaceDecl>(DC) &&
  2415. cast<NamespaceDecl>(DC)->getIdentifier() &&
  2416. cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
  2417. DC->getParent()->isTranslationUnit())
  2418. CGM.EmitFundamentalRTTIDescriptors();
  2419. }