MicrosoftCXXABI.cpp 181 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474
  1. //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This provides C++ code generation targeting the Microsoft Visual C++ ABI.
  10. // The class in this file generates structures that follow the Microsoft
  11. // Visual C++ ABI, which is actually not very well documented at all outside
  12. // of Microsoft.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "CGCXXABI.h"
  16. #include "CGCleanup.h"
  17. #include "CGVTables.h"
  18. #include "CodeGenModule.h"
  19. #include "CodeGenTypes.h"
  20. #include "TargetInfo.h"
  21. #include "clang/AST/Attr.h"
  22. #include "clang/AST/CXXInheritance.h"
  23. #include "clang/AST/Decl.h"
  24. #include "clang/AST/DeclCXX.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/AST/VTableBuilder.h"
  27. #include "clang/CodeGen/ConstantInitBuilder.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/ADT/StringSet.h"
  30. #include "llvm/IR/Intrinsics.h"
  31. using namespace clang;
  32. using namespace CodeGen;
  33. namespace {
  34. /// Holds all the vbtable globals for a given class.
  35. struct VBTableGlobals {
  36. const VPtrInfoVector *VBTables;
  37. SmallVector<llvm::GlobalVariable *, 2> Globals;
  38. };
  39. class MicrosoftCXXABI : public CGCXXABI {
  40. public:
  41. MicrosoftCXXABI(CodeGenModule &CGM)
  42. : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
  43. ClassHierarchyDescriptorType(nullptr),
  44. CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
  45. ThrowInfoType(nullptr) {}
  46. bool HasThisReturn(GlobalDecl GD) const override;
  47. bool hasMostDerivedReturn(GlobalDecl GD) const override;
  48. bool classifyReturnType(CGFunctionInfo &FI) const override;
  49. RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
  50. bool isSRetParameterAfterThis() const override { return true; }
  51. bool isThisCompleteObject(GlobalDecl GD) const override {
  52. // The Microsoft ABI doesn't use separate complete-object vs.
  53. // base-object variants of constructors, but it does of destructors.
  54. if (isa<CXXDestructorDecl>(GD.getDecl())) {
  55. switch (GD.getDtorType()) {
  56. case Dtor_Complete:
  57. case Dtor_Deleting:
  58. return true;
  59. case Dtor_Base:
  60. return false;
  61. case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
  62. }
  63. llvm_unreachable("bad dtor kind");
  64. }
  65. // No other kinds.
  66. return false;
  67. }
  68. size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
  69. FunctionArgList &Args) const override {
  70. assert(Args.size() >= 2 &&
  71. "expected the arglist to have at least two args!");
  72. // The 'most_derived' parameter goes second if the ctor is variadic and
  73. // has v-bases.
  74. if (CD->getParent()->getNumVBases() > 0 &&
  75. CD->getType()->castAs<FunctionProtoType>()->isVariadic())
  76. return 2;
  77. return 1;
  78. }
  79. std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
  80. std::vector<CharUnits> VBPtrOffsets;
  81. const ASTContext &Context = getContext();
  82. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  83. const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
  84. for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
  85. const ASTRecordLayout &SubobjectLayout =
  86. Context.getASTRecordLayout(VBT->IntroducingObject);
  87. CharUnits Offs = VBT->NonVirtualOffset;
  88. Offs += SubobjectLayout.getVBPtrOffset();
  89. if (VBT->getVBaseWithVPtr())
  90. Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
  91. VBPtrOffsets.push_back(Offs);
  92. }
  93. llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
  94. return VBPtrOffsets;
  95. }
  96. StringRef GetPureVirtualCallName() override { return "_purecall"; }
  97. StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
  98. void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
  99. Address Ptr, QualType ElementType,
  100. const CXXDestructorDecl *Dtor) override;
  101. void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
  102. void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
  103. void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
  104. llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
  105. const VPtrInfo &Info);
  106. llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
  107. CatchTypeInfo
  108. getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
  109. /// MSVC needs an extra flag to indicate a catchall.
  110. CatchTypeInfo getCatchAllTypeInfo() override {
  111. // For -EHa catch(...) must handle HW exception
  112. // Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions
  113. if (getContext().getLangOpts().EHAsynch)
  114. return CatchTypeInfo{nullptr, 0};
  115. else
  116. return CatchTypeInfo{nullptr, 0x40};
  117. }
  118. bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
  119. void EmitBadTypeidCall(CodeGenFunction &CGF) override;
  120. llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
  121. Address ThisPtr,
  122. llvm::Type *StdTypeInfoPtrTy) override;
  123. bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
  124. QualType SrcRecordTy) override;
  125. llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
  126. QualType SrcRecordTy, QualType DestTy,
  127. QualType DestRecordTy,
  128. llvm::BasicBlock *CastEnd) override;
  129. llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
  130. QualType SrcRecordTy,
  131. QualType DestTy) override;
  132. bool EmitBadCastCall(CodeGenFunction &CGF) override;
  133. bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
  134. return false;
  135. }
  136. llvm::Value *
  137. GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
  138. const CXXRecordDecl *ClassDecl,
  139. const CXXRecordDecl *BaseClassDecl) override;
  140. llvm::BasicBlock *
  141. EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
  142. const CXXRecordDecl *RD) override;
  143. llvm::BasicBlock *
  144. EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
  145. void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
  146. const CXXRecordDecl *RD) override;
  147. void EmitCXXConstructors(const CXXConstructorDecl *D) override;
  148. // Background on MSVC destructors
  149. // ==============================
  150. //
  151. // Both Itanium and MSVC ABIs have destructor variants. The variant names
  152. // roughly correspond in the following way:
  153. // Itanium Microsoft
  154. // Base -> no name, just ~Class
  155. // Complete -> vbase destructor
  156. // Deleting -> scalar deleting destructor
  157. // vector deleting destructor
  158. //
  159. // The base and complete destructors are the same as in Itanium, although the
  160. // complete destructor does not accept a VTT parameter when there are virtual
  161. // bases. A separate mechanism involving vtordisps is used to ensure that
  162. // virtual methods of destroyed subobjects are not called.
  163. //
  164. // The deleting destructors accept an i32 bitfield as a second parameter. Bit
  165. // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
  166. // pointer points to an array. The scalar deleting destructor assumes that
  167. // bit 2 is zero, and therefore does not contain a loop.
  168. //
  169. // For virtual destructors, only one entry is reserved in the vftable, and it
  170. // always points to the vector deleting destructor. The vector deleting
  171. // destructor is the most general, so it can be used to destroy objects in
  172. // place, delete single heap objects, or delete arrays.
  173. //
  174. // A TU defining a non-inline destructor is only guaranteed to emit a base
  175. // destructor, and all of the other variants are emitted on an as-needed basis
  176. // in COMDATs. Because a non-base destructor can be emitted in a TU that
  177. // lacks a definition for the destructor, non-base destructors must always
  178. // delegate to or alias the base destructor.
  179. AddedStructorArgCounts
  180. buildStructorSignature(GlobalDecl GD,
  181. SmallVectorImpl<CanQualType> &ArgTys) override;
  182. /// Non-base dtors should be emitted as delegating thunks in this ABI.
  183. bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
  184. CXXDtorType DT) const override {
  185. return DT != Dtor_Base;
  186. }
  187. void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
  188. const CXXDestructorDecl *Dtor,
  189. CXXDtorType DT) const override;
  190. llvm::GlobalValue::LinkageTypes
  191. getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
  192. CXXDtorType DT) const override;
  193. void EmitCXXDestructors(const CXXDestructorDecl *D) override;
  194. const CXXRecordDecl *
  195. getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
  196. if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
  197. MethodVFTableLocation ML =
  198. CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
  199. // The vbases might be ordered differently in the final overrider object
  200. // and the complete object, so the "this" argument may sometimes point to
  201. // memory that has no particular type (e.g. past the complete object).
  202. // In this case, we just use a generic pointer type.
  203. // FIXME: might want to have a more precise type in the non-virtual
  204. // multiple inheritance case.
  205. if (ML.VBase || !ML.VFPtrOffset.isZero())
  206. return nullptr;
  207. }
  208. return MD->getParent();
  209. }
  210. Address
  211. adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
  212. Address This,
  213. bool VirtualCall) override;
  214. void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
  215. FunctionArgList &Params) override;
  216. void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
  217. AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
  218. const CXXConstructorDecl *D,
  219. CXXCtorType Type,
  220. bool ForVirtualBase,
  221. bool Delegating) override;
  222. llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
  223. const CXXDestructorDecl *DD,
  224. CXXDtorType Type,
  225. bool ForVirtualBase,
  226. bool Delegating) override;
  227. void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
  228. CXXDtorType Type, bool ForVirtualBase,
  229. bool Delegating, Address This,
  230. QualType ThisTy) override;
  231. void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
  232. llvm::GlobalVariable *VTable);
  233. void emitVTableDefinitions(CodeGenVTables &CGVT,
  234. const CXXRecordDecl *RD) override;
  235. bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
  236. CodeGenFunction::VPtr Vptr) override;
  237. /// Don't initialize vptrs if dynamic class
  238. /// is marked with with the 'novtable' attribute.
  239. bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
  240. return !VTableClass->hasAttr<MSNoVTableAttr>();
  241. }
  242. llvm::Constant *
  243. getVTableAddressPoint(BaseSubobject Base,
  244. const CXXRecordDecl *VTableClass) override;
  245. llvm::Value *getVTableAddressPointInStructor(
  246. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
  247. BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
  248. llvm::Constant *
  249. getVTableAddressPointForConstExpr(BaseSubobject Base,
  250. const CXXRecordDecl *VTableClass) override;
  251. llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
  252. CharUnits VPtrOffset) override;
  253. CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
  254. Address This, llvm::Type *Ty,
  255. SourceLocation Loc) override;
  256. llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
  257. const CXXDestructorDecl *Dtor,
  258. CXXDtorType DtorType, Address This,
  259. DeleteOrMemberCallExpr E) override;
  260. void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
  261. CallArgList &CallArgs) override {
  262. assert(GD.getDtorType() == Dtor_Deleting &&
  263. "Only deleting destructor thunks are available in this ABI");
  264. CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
  265. getContext().IntTy);
  266. }
  267. void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
  268. llvm::GlobalVariable *
  269. getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
  270. llvm::GlobalVariable::LinkageTypes Linkage);
  271. llvm::GlobalVariable *
  272. getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
  273. const CXXRecordDecl *DstRD) {
  274. SmallString<256> OutName;
  275. llvm::raw_svector_ostream Out(OutName);
  276. getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
  277. StringRef MangledName = OutName.str();
  278. if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
  279. return VDispMap;
  280. MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
  281. unsigned NumEntries = 1 + SrcRD->getNumVBases();
  282. SmallVector<llvm::Constant *, 4> Map(NumEntries,
  283. llvm::UndefValue::get(CGM.IntTy));
  284. Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
  285. bool AnyDifferent = false;
  286. for (const auto &I : SrcRD->vbases()) {
  287. const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
  288. if (!DstRD->isVirtuallyDerivedFrom(VBase))
  289. continue;
  290. unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
  291. unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
  292. Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
  293. AnyDifferent |= SrcVBIndex != DstVBIndex;
  294. }
  295. // This map would be useless, don't use it.
  296. if (!AnyDifferent)
  297. return nullptr;
  298. llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
  299. llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
  300. llvm::GlobalValue::LinkageTypes Linkage =
  301. SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
  302. ? llvm::GlobalValue::LinkOnceODRLinkage
  303. : llvm::GlobalValue::InternalLinkage;
  304. auto *VDispMap = new llvm::GlobalVariable(
  305. CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
  306. /*Initializer=*/Init, MangledName);
  307. return VDispMap;
  308. }
  309. void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
  310. llvm::GlobalVariable *GV) const;
  311. void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
  312. GlobalDecl GD, bool ReturnAdjustment) override {
  313. GVALinkage Linkage =
  314. getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
  315. if (Linkage == GVA_Internal)
  316. Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
  317. else if (ReturnAdjustment)
  318. Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
  319. else
  320. Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
  321. }
  322. bool exportThunk() override { return false; }
  323. llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
  324. const ThisAdjustment &TA) override;
  325. llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
  326. const ReturnAdjustment &RA) override;
  327. void EmitThreadLocalInitFuncs(
  328. CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
  329. ArrayRef<llvm::Function *> CXXThreadLocalInits,
  330. ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
  331. bool usesThreadWrapperFunction(const VarDecl *VD) const override {
  332. return getContext().getLangOpts().isCompatibleWithMSVC(
  333. LangOptions::MSVC2019_5) &&
  334. (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));
  335. }
  336. LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
  337. QualType LValType) override;
  338. void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
  339. llvm::GlobalVariable *DeclPtr,
  340. bool PerformInit) override;
  341. void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
  342. llvm::FunctionCallee Dtor,
  343. llvm::Constant *Addr) override;
  344. // ==== Notes on array cookies =========
  345. //
  346. // MSVC seems to only use cookies when the class has a destructor; a
  347. // two-argument usual array deallocation function isn't sufficient.
  348. //
  349. // For example, this code prints "100" and "1":
  350. // struct A {
  351. // char x;
  352. // void *operator new[](size_t sz) {
  353. // printf("%u\n", sz);
  354. // return malloc(sz);
  355. // }
  356. // void operator delete[](void *p, size_t sz) {
  357. // printf("%u\n", sz);
  358. // free(p);
  359. // }
  360. // };
  361. // int main() {
  362. // A *p = new A[100];
  363. // delete[] p;
  364. // }
  365. // Whereas it prints "104" and "104" if you give A a destructor.
  366. bool requiresArrayCookie(const CXXDeleteExpr *expr,
  367. QualType elementType) override;
  368. bool requiresArrayCookie(const CXXNewExpr *expr) override;
  369. CharUnits getArrayCookieSizeImpl(QualType type) override;
  370. Address InitializeArrayCookie(CodeGenFunction &CGF,
  371. Address NewPtr,
  372. llvm::Value *NumElements,
  373. const CXXNewExpr *expr,
  374. QualType ElementType) override;
  375. llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
  376. Address allocPtr,
  377. CharUnits cookieSize) override;
  378. friend struct MSRTTIBuilder;
  379. bool isImageRelative() const {
  380. return CGM.getTarget().getPointerWidth(/*AddrSpace=*/0) == 64;
  381. }
  382. // 5 routines for constructing the llvm types for MS RTTI structs.
  383. llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
  384. llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
  385. TDTypeName += llvm::utostr(TypeInfoString.size());
  386. llvm::StructType *&TypeDescriptorType =
  387. TypeDescriptorTypeMap[TypeInfoString.size()];
  388. if (TypeDescriptorType)
  389. return TypeDescriptorType;
  390. llvm::Type *FieldTypes[] = {
  391. CGM.Int8PtrPtrTy,
  392. CGM.Int8PtrTy,
  393. llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
  394. TypeDescriptorType =
  395. llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
  396. return TypeDescriptorType;
  397. }
  398. llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
  399. if (!isImageRelative())
  400. return PtrType;
  401. return CGM.IntTy;
  402. }
  403. llvm::StructType *getBaseClassDescriptorType() {
  404. if (BaseClassDescriptorType)
  405. return BaseClassDescriptorType;
  406. llvm::Type *FieldTypes[] = {
  407. getImageRelativeType(CGM.Int8PtrTy),
  408. CGM.IntTy,
  409. CGM.IntTy,
  410. CGM.IntTy,
  411. CGM.IntTy,
  412. CGM.IntTy,
  413. getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
  414. };
  415. BaseClassDescriptorType = llvm::StructType::create(
  416. CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
  417. return BaseClassDescriptorType;
  418. }
  419. llvm::StructType *getClassHierarchyDescriptorType() {
  420. if (ClassHierarchyDescriptorType)
  421. return ClassHierarchyDescriptorType;
  422. // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
  423. ClassHierarchyDescriptorType = llvm::StructType::create(
  424. CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
  425. llvm::Type *FieldTypes[] = {
  426. CGM.IntTy,
  427. CGM.IntTy,
  428. CGM.IntTy,
  429. getImageRelativeType(
  430. getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
  431. };
  432. ClassHierarchyDescriptorType->setBody(FieldTypes);
  433. return ClassHierarchyDescriptorType;
  434. }
  435. llvm::StructType *getCompleteObjectLocatorType() {
  436. if (CompleteObjectLocatorType)
  437. return CompleteObjectLocatorType;
  438. CompleteObjectLocatorType = llvm::StructType::create(
  439. CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
  440. llvm::Type *FieldTypes[] = {
  441. CGM.IntTy,
  442. CGM.IntTy,
  443. CGM.IntTy,
  444. getImageRelativeType(CGM.Int8PtrTy),
  445. getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
  446. getImageRelativeType(CompleteObjectLocatorType),
  447. };
  448. llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
  449. if (!isImageRelative())
  450. FieldTypesRef = FieldTypesRef.drop_back();
  451. CompleteObjectLocatorType->setBody(FieldTypesRef);
  452. return CompleteObjectLocatorType;
  453. }
  454. llvm::GlobalVariable *getImageBase() {
  455. StringRef Name = "__ImageBase";
  456. if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
  457. return GV;
  458. auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
  459. /*isConstant=*/true,
  460. llvm::GlobalValue::ExternalLinkage,
  461. /*Initializer=*/nullptr, Name);
  462. CGM.setDSOLocal(GV);
  463. return GV;
  464. }
  465. llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
  466. if (!isImageRelative())
  467. return PtrVal;
  468. if (PtrVal->isNullValue())
  469. return llvm::Constant::getNullValue(CGM.IntTy);
  470. llvm::Constant *ImageBaseAsInt =
  471. llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
  472. llvm::Constant *PtrValAsInt =
  473. llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
  474. llvm::Constant *Diff =
  475. llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
  476. /*HasNUW=*/true, /*HasNSW=*/true);
  477. return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
  478. }
  479. private:
  480. MicrosoftMangleContext &getMangleContext() {
  481. return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
  482. }
  483. llvm::Constant *getZeroInt() {
  484. return llvm::ConstantInt::get(CGM.IntTy, 0);
  485. }
  486. llvm::Constant *getAllOnesInt() {
  487. return llvm::Constant::getAllOnesValue(CGM.IntTy);
  488. }
  489. CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
  490. void
  491. GetNullMemberPointerFields(const MemberPointerType *MPT,
  492. llvm::SmallVectorImpl<llvm::Constant *> &fields);
  493. /// Shared code for virtual base adjustment. Returns the offset from
  494. /// the vbptr to the virtual base. Optionally returns the address of the
  495. /// vbptr itself.
  496. llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
  497. Address Base,
  498. llvm::Value *VBPtrOffset,
  499. llvm::Value *VBTableOffset,
  500. llvm::Value **VBPtr = nullptr);
  501. llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
  502. Address Base,
  503. int32_t VBPtrOffset,
  504. int32_t VBTableOffset,
  505. llvm::Value **VBPtr = nullptr) {
  506. assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
  507. llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
  508. *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
  509. return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
  510. }
  511. std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
  512. performBaseAdjustment(CodeGenFunction &CGF, Address Value,
  513. QualType SrcRecordTy);
  514. /// Performs a full virtual base adjustment. Used to dereference
  515. /// pointers to members of virtual bases.
  516. llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
  517. const CXXRecordDecl *RD, Address Base,
  518. llvm::Value *VirtualBaseAdjustmentOffset,
  519. llvm::Value *VBPtrOffset /* optional */);
  520. /// Emits a full member pointer with the fields common to data and
  521. /// function member pointers.
  522. llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
  523. bool IsMemberFunction,
  524. const CXXRecordDecl *RD,
  525. CharUnits NonVirtualBaseAdjustment,
  526. unsigned VBTableIndex);
  527. bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
  528. llvm::Constant *MP);
  529. /// - Initialize all vbptrs of 'this' with RD as the complete type.
  530. void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
  531. /// Caching wrapper around VBTableBuilder::enumerateVBTables().
  532. const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
  533. /// Generate a thunk for calling a virtual member function MD.
  534. llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
  535. const MethodVFTableLocation &ML);
  536. llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
  537. CharUnits offset);
  538. public:
  539. llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
  540. bool isZeroInitializable(const MemberPointerType *MPT) override;
  541. bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
  542. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  543. return RD->hasAttr<MSInheritanceAttr>();
  544. }
  545. llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
  546. llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
  547. CharUnits offset) override;
  548. llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
  549. llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
  550. llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
  551. llvm::Value *L,
  552. llvm::Value *R,
  553. const MemberPointerType *MPT,
  554. bool Inequality) override;
  555. llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  556. llvm::Value *MemPtr,
  557. const MemberPointerType *MPT) override;
  558. llvm::Value *
  559. EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
  560. Address Base, llvm::Value *MemPtr,
  561. const MemberPointerType *MPT) override;
  562. llvm::Value *EmitNonNullMemberPointerConversion(
  563. const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
  564. CastKind CK, CastExpr::path_const_iterator PathBegin,
  565. CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
  566. CGBuilderTy &Builder);
  567. llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
  568. const CastExpr *E,
  569. llvm::Value *Src) override;
  570. llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
  571. llvm::Constant *Src) override;
  572. llvm::Constant *EmitMemberPointerConversion(
  573. const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
  574. CastKind CK, CastExpr::path_const_iterator PathBegin,
  575. CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
  576. CGCallee
  577. EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
  578. Address This, llvm::Value *&ThisPtrForCall,
  579. llvm::Value *MemPtr,
  580. const MemberPointerType *MPT) override;
  581. void emitCXXStructor(GlobalDecl GD) override;
  582. llvm::StructType *getCatchableTypeType() {
  583. if (CatchableTypeType)
  584. return CatchableTypeType;
  585. llvm::Type *FieldTypes[] = {
  586. CGM.IntTy, // Flags
  587. getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
  588. CGM.IntTy, // NonVirtualAdjustment
  589. CGM.IntTy, // OffsetToVBPtr
  590. CGM.IntTy, // VBTableIndex
  591. CGM.IntTy, // Size
  592. getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
  593. };
  594. CatchableTypeType = llvm::StructType::create(
  595. CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
  596. return CatchableTypeType;
  597. }
  598. llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
  599. llvm::StructType *&CatchableTypeArrayType =
  600. CatchableTypeArrayTypeMap[NumEntries];
  601. if (CatchableTypeArrayType)
  602. return CatchableTypeArrayType;
  603. llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
  604. CTATypeName += llvm::utostr(NumEntries);
  605. llvm::Type *CTType =
  606. getImageRelativeType(getCatchableTypeType()->getPointerTo());
  607. llvm::Type *FieldTypes[] = {
  608. CGM.IntTy, // NumEntries
  609. llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
  610. };
  611. CatchableTypeArrayType =
  612. llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
  613. return CatchableTypeArrayType;
  614. }
  615. llvm::StructType *getThrowInfoType() {
  616. if (ThrowInfoType)
  617. return ThrowInfoType;
  618. llvm::Type *FieldTypes[] = {
  619. CGM.IntTy, // Flags
  620. getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
  621. getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
  622. getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
  623. };
  624. ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
  625. "eh.ThrowInfo");
  626. return ThrowInfoType;
  627. }
  628. llvm::FunctionCallee getThrowFn() {
  629. // _CxxThrowException is passed an exception object and a ThrowInfo object
  630. // which describes the exception.
  631. llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
  632. llvm::FunctionType *FTy =
  633. llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
  634. llvm::FunctionCallee Throw =
  635. CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
  636. // _CxxThrowException is stdcall on 32-bit x86 platforms.
  637. if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
  638. if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
  639. Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
  640. }
  641. return Throw;
  642. }
  643. llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
  644. CXXCtorType CT);
  645. llvm::Constant *getCatchableType(QualType T,
  646. uint32_t NVOffset = 0,
  647. int32_t VBPtrOffset = -1,
  648. uint32_t VBIndex = 0);
  649. llvm::GlobalVariable *getCatchableTypeArray(QualType T);
  650. llvm::GlobalVariable *getThrowInfo(QualType T) override;
  651. std::pair<llvm::Value *, const CXXRecordDecl *>
  652. LoadVTablePtr(CodeGenFunction &CGF, Address This,
  653. const CXXRecordDecl *RD) override;
  654. virtual bool
  655. isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
  656. private:
  657. typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
  658. typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
  659. typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
  660. /// All the vftables that have been referenced.
  661. VFTablesMapTy VFTablesMap;
  662. VTablesMapTy VTablesMap;
  663. /// This set holds the record decls we've deferred vtable emission for.
  664. llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
  665. /// All the vbtables which have been referenced.
  666. llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
  667. /// Info on the global variable used to guard initialization of static locals.
  668. /// The BitIndex field is only used for externally invisible declarations.
  669. struct GuardInfo {
  670. GuardInfo() : Guard(nullptr), BitIndex(0) {}
  671. llvm::GlobalVariable *Guard;
  672. unsigned BitIndex;
  673. };
  674. /// Map from DeclContext to the current guard variable. We assume that the
  675. /// AST is visited in source code order.
  676. llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
  677. llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
  678. llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
  679. llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
  680. llvm::StructType *BaseClassDescriptorType;
  681. llvm::StructType *ClassHierarchyDescriptorType;
  682. llvm::StructType *CompleteObjectLocatorType;
  683. llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
  684. llvm::StructType *CatchableTypeType;
  685. llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
  686. llvm::StructType *ThrowInfoType;
  687. };
  688. }
  689. CGCXXABI::RecordArgABI
  690. MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
  691. // Use the default C calling convention rules for things that can be passed in
  692. // registers, i.e. non-trivially copyable records or records marked with
  693. // [[trivial_abi]].
  694. if (RD->canPassInRegisters())
  695. return RAA_Default;
  696. switch (CGM.getTarget().getTriple().getArch()) {
  697. default:
  698. // FIXME: Implement for other architectures.
  699. return RAA_Indirect;
  700. case llvm::Triple::thumb:
  701. // Pass things indirectly for now because it is simple.
  702. // FIXME: This is incompatible with MSVC for arguments with a dtor and no
  703. // copy ctor.
  704. return RAA_Indirect;
  705. case llvm::Triple::x86: {
  706. // If the argument has *required* alignment greater than four bytes, pass
  707. // it indirectly. Prior to MSVC version 19.14, passing overaligned
  708. // arguments was not supported and resulted in a compiler error. In 19.14
  709. // and later versions, such arguments are now passed indirectly.
  710. TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
  711. if (Info.isAlignRequired() && Info.Align > 4)
  712. return RAA_Indirect;
  713. // If C++ prohibits us from making a copy, construct the arguments directly
  714. // into argument memory.
  715. return RAA_DirectInMemory;
  716. }
  717. case llvm::Triple::x86_64:
  718. case llvm::Triple::aarch64:
  719. return RAA_Indirect;
  720. }
  721. llvm_unreachable("invalid enum");
  722. }
  723. void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
  724. const CXXDeleteExpr *DE,
  725. Address Ptr,
  726. QualType ElementType,
  727. const CXXDestructorDecl *Dtor) {
  728. // FIXME: Provide a source location here even though there's no
  729. // CXXMemberCallExpr for dtor call.
  730. bool UseGlobalDelete = DE->isGlobalDelete();
  731. CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
  732. llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
  733. if (UseGlobalDelete)
  734. CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
  735. }
  736. void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
  737. llvm::Value *Args[] = {
  738. llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
  739. llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
  740. llvm::FunctionCallee Fn = getThrowFn();
  741. if (isNoReturn)
  742. CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
  743. else
  744. CGF.EmitRuntimeCallOrInvoke(Fn, Args);
  745. }
  746. void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
  747. const CXXCatchStmt *S) {
  748. // In the MS ABI, the runtime handles the copy, and the catch handler is
  749. // responsible for destruction.
  750. VarDecl *CatchParam = S->getExceptionDecl();
  751. llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
  752. llvm::CatchPadInst *CPI =
  753. cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
  754. CGF.CurrentFuncletPad = CPI;
  755. // If this is a catch-all or the catch parameter is unnamed, we don't need to
  756. // emit an alloca to the object.
  757. if (!CatchParam || !CatchParam->getDeclName()) {
  758. CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
  759. return;
  760. }
  761. CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
  762. CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
  763. CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
  764. CGF.EmitAutoVarCleanups(var);
  765. }
  766. /// We need to perform a generic polymorphic operation (like a typeid
  767. /// or a cast), which requires an object with a vfptr. Adjust the
  768. /// address to point to an object with a vfptr.
  769. std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
  770. MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
  771. QualType SrcRecordTy) {
  772. Value = CGF.Builder.CreateElementBitCast(Value, CGF.Int8Ty);
  773. const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
  774. const ASTContext &Context = getContext();
  775. // If the class itself has a vfptr, great. This check implicitly
  776. // covers non-virtual base subobjects: a class with its own virtual
  777. // functions would be a candidate to be a primary base.
  778. if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
  779. return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
  780. SrcDecl);
  781. // Okay, one of the vbases must have a vfptr, or else this isn't
  782. // actually a polymorphic class.
  783. const CXXRecordDecl *PolymorphicBase = nullptr;
  784. for (auto &Base : SrcDecl->vbases()) {
  785. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  786. if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
  787. PolymorphicBase = BaseDecl;
  788. break;
  789. }
  790. }
  791. assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
  792. llvm::Value *Offset =
  793. GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
  794. llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
  795. Value.getElementType(), Value.getPointer(), Offset);
  796. CharUnits VBaseAlign =
  797. CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
  798. return std::make_tuple(Address(Ptr, VBaseAlign), Offset, PolymorphicBase);
  799. }
  800. bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
  801. QualType SrcRecordTy) {
  802. const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
  803. return IsDeref &&
  804. !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
  805. }
  806. static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
  807. llvm::Value *Argument) {
  808. llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
  809. llvm::FunctionType *FTy =
  810. llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
  811. llvm::Value *Args[] = {Argument};
  812. llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
  813. return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
  814. }
  815. void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
  816. llvm::CallBase *Call =
  817. emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
  818. Call->setDoesNotReturn();
  819. CGF.Builder.CreateUnreachable();
  820. }
  821. llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
  822. QualType SrcRecordTy,
  823. Address ThisPtr,
  824. llvm::Type *StdTypeInfoPtrTy) {
  825. std::tie(ThisPtr, std::ignore, std::ignore) =
  826. performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
  827. llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer());
  828. return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
  829. }
  830. bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
  831. QualType SrcRecordTy) {
  832. const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
  833. return SrcIsPtr &&
  834. !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
  835. }
  836. llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
  837. CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
  838. QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
  839. llvm::Type *DestLTy = CGF.ConvertType(DestTy);
  840. llvm::Value *SrcRTTI =
  841. CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
  842. llvm::Value *DestRTTI =
  843. CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
  844. llvm::Value *Offset;
  845. std::tie(This, Offset, std::ignore) =
  846. performBaseAdjustment(CGF, This, SrcRecordTy);
  847. llvm::Value *ThisPtr = This.getPointer();
  848. Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
  849. // PVOID __RTDynamicCast(
  850. // PVOID inptr,
  851. // LONG VfDelta,
  852. // PVOID SrcType,
  853. // PVOID TargetType,
  854. // BOOL isReference)
  855. llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
  856. CGF.Int8PtrTy, CGF.Int32Ty};
  857. llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
  858. llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
  859. "__RTDynamicCast");
  860. llvm::Value *Args[] = {
  861. ThisPtr, Offset, SrcRTTI, DestRTTI,
  862. llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
  863. ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args);
  864. return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
  865. }
  866. llvm::Value *
  867. MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
  868. QualType SrcRecordTy,
  869. QualType DestTy) {
  870. std::tie(Value, std::ignore, std::ignore) =
  871. performBaseAdjustment(CGF, Value, SrcRecordTy);
  872. // PVOID __RTCastToVoid(
  873. // PVOID inptr)
  874. llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
  875. llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
  876. llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
  877. "__RTCastToVoid");
  878. llvm::Value *Args[] = {Value.getPointer()};
  879. return CGF.EmitRuntimeCall(Function, Args);
  880. }
  881. bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
  882. return false;
  883. }
  884. llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
  885. CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
  886. const CXXRecordDecl *BaseClassDecl) {
  887. const ASTContext &Context = getContext();
  888. int64_t VBPtrChars =
  889. Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
  890. llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
  891. CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
  892. CharUnits VBTableChars =
  893. IntSize *
  894. CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
  895. llvm::Value *VBTableOffset =
  896. llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
  897. llvm::Value *VBPtrToNewBase =
  898. GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
  899. VBPtrToNewBase =
  900. CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
  901. return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
  902. }
  903. bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
  904. return isa<CXXConstructorDecl>(GD.getDecl());
  905. }
  906. static bool isDeletingDtor(GlobalDecl GD) {
  907. return isa<CXXDestructorDecl>(GD.getDecl()) &&
  908. GD.getDtorType() == Dtor_Deleting;
  909. }
  910. bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
  911. return isDeletingDtor(GD);
  912. }
  913. static bool isTrivialForAArch64MSVC(const CXXRecordDecl *RD) {
  914. // For AArch64, we use the C++14 definition of an aggregate, so we also
  915. // check for:
  916. // No private or protected non static data members.
  917. // No base classes
  918. // No virtual functions
  919. // Additionally, we need to ensure that there is a trivial copy assignment
  920. // operator, a trivial destructor and no user-provided constructors.
  921. if (RD->hasProtectedFields() || RD->hasPrivateFields())
  922. return false;
  923. if (RD->getNumBases() > 0)
  924. return false;
  925. if (RD->isPolymorphic())
  926. return false;
  927. if (RD->hasNonTrivialCopyAssignment())
  928. return false;
  929. for (const CXXConstructorDecl *Ctor : RD->ctors())
  930. if (Ctor->isUserProvided())
  931. return false;
  932. if (RD->hasNonTrivialDestructor())
  933. return false;
  934. return true;
  935. }
  936. bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
  937. const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
  938. if (!RD)
  939. return false;
  940. // Normally, the C++ concept of "is trivially copyable" is used to determine
  941. // if a struct can be returned directly. However, as MSVC and the language
  942. // have evolved, the definition of "trivially copyable" has changed, while the
  943. // ABI must remain stable. AArch64 uses the C++14 concept of an "aggregate",
  944. // while other ISAs use the older concept of "plain old data".
  945. bool isTrivialForABI = RD->isPOD();
  946. bool isAArch64 = CGM.getTarget().getTriple().isAArch64();
  947. if (isAArch64)
  948. isTrivialForABI = RD->canPassInRegisters() && isTrivialForAArch64MSVC(RD);
  949. // MSVC always returns structs indirectly from C++ instance methods.
  950. bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
  951. if (isIndirectReturn) {
  952. CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
  953. FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
  954. // MSVC always passes `this` before the `sret` parameter.
  955. FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
  956. // On AArch64, use the `inreg` attribute if the object is considered to not
  957. // be trivially copyable, or if this is an instance method struct return.
  958. FI.getReturnInfo().setInReg(isAArch64);
  959. return true;
  960. }
  961. // Otherwise, use the C ABI rules.
  962. return false;
  963. }
  964. llvm::BasicBlock *
  965. MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
  966. const CXXRecordDecl *RD) {
  967. llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
  968. assert(IsMostDerivedClass &&
  969. "ctor for a class with virtual bases must have an implicit parameter");
  970. llvm::Value *IsCompleteObject =
  971. CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
  972. llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
  973. llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
  974. CGF.Builder.CreateCondBr(IsCompleteObject,
  975. CallVbaseCtorsBB, SkipVbaseCtorsBB);
  976. CGF.EmitBlock(CallVbaseCtorsBB);
  977. // Fill in the vbtable pointers here.
  978. EmitVBPtrStores(CGF, RD);
  979. // CGF will put the base ctor calls in this basic block for us later.
  980. return SkipVbaseCtorsBB;
  981. }
  982. llvm::BasicBlock *
  983. MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
  984. llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
  985. assert(IsMostDerivedClass &&
  986. "ctor for a class with virtual bases must have an implicit parameter");
  987. llvm::Value *IsCompleteObject =
  988. CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
  989. llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
  990. llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
  991. CGF.Builder.CreateCondBr(IsCompleteObject,
  992. CallVbaseDtorsBB, SkipVbaseDtorsBB);
  993. CGF.EmitBlock(CallVbaseDtorsBB);
  994. // CGF will put the base dtor calls in this basic block for us later.
  995. return SkipVbaseDtorsBB;
  996. }
  997. void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
  998. CodeGenFunction &CGF, const CXXRecordDecl *RD) {
  999. // In most cases, an override for a vbase virtual method can adjust
  1000. // the "this" parameter by applying a constant offset.
  1001. // However, this is not enough while a constructor or a destructor of some
  1002. // class X is being executed if all the following conditions are met:
  1003. // - X has virtual bases, (1)
  1004. // - X overrides a virtual method M of a vbase Y, (2)
  1005. // - X itself is a vbase of the most derived class.
  1006. //
  1007. // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
  1008. // which holds the extra amount of "this" adjustment we must do when we use
  1009. // the X vftables (i.e. during X ctor or dtor).
  1010. // Outside the ctors and dtors, the values of vtorDisps are zero.
  1011. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1012. typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
  1013. const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
  1014. CGBuilderTy &Builder = CGF.Builder;
  1015. unsigned AS = getThisAddress(CGF).getAddressSpace();
  1016. llvm::Value *Int8This = nullptr; // Initialize lazily.
  1017. for (const CXXBaseSpecifier &S : RD->vbases()) {
  1018. const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
  1019. auto I = VBaseMap.find(VBase);
  1020. assert(I != VBaseMap.end());
  1021. if (!I->second.hasVtorDisp())
  1022. continue;
  1023. llvm::Value *VBaseOffset =
  1024. GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
  1025. uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
  1026. // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
  1027. llvm::Value *VtorDispValue = Builder.CreateSub(
  1028. VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
  1029. "vtordisp.value");
  1030. VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
  1031. if (!Int8This)
  1032. Int8This = Builder.CreateBitCast(getThisValue(CGF),
  1033. CGF.Int8Ty->getPointerTo(AS));
  1034. llvm::Value *VtorDispPtr =
  1035. Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
  1036. // vtorDisp is always the 32-bits before the vbase in the class layout.
  1037. VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);
  1038. VtorDispPtr = Builder.CreateBitCast(
  1039. VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
  1040. Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
  1041. CharUnits::fromQuantity(4));
  1042. }
  1043. }
  1044. static bool hasDefaultCXXMethodCC(ASTContext &Context,
  1045. const CXXMethodDecl *MD) {
  1046. CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
  1047. /*IsVariadic=*/false, /*IsCXXMethod=*/true);
  1048. CallingConv ActualCallingConv =
  1049. MD->getType()->castAs<FunctionProtoType>()->getCallConv();
  1050. return ExpectedCallingConv == ActualCallingConv;
  1051. }
  1052. void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
  1053. // There's only one constructor type in this ABI.
  1054. CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
  1055. // Exported default constructors either have a simple call-site where they use
  1056. // the typical calling convention and have a single 'this' pointer for an
  1057. // argument -or- they get a wrapper function which appropriately thunks to the
  1058. // real default constructor. This thunk is the default constructor closure.
  1059. if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
  1060. D->isDefined()) {
  1061. if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
  1062. llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
  1063. Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
  1064. CGM.setGVProperties(Fn, D);
  1065. }
  1066. }
  1067. }
  1068. void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
  1069. const CXXRecordDecl *RD) {
  1070. Address This = getThisAddress(CGF);
  1071. This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
  1072. const ASTContext &Context = getContext();
  1073. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  1074. const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
  1075. for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
  1076. const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
  1077. llvm::GlobalVariable *GV = VBGlobals.Globals[I];
  1078. const ASTRecordLayout &SubobjectLayout =
  1079. Context.getASTRecordLayout(VBT->IntroducingObject);
  1080. CharUnits Offs = VBT->NonVirtualOffset;
  1081. Offs += SubobjectLayout.getVBPtrOffset();
  1082. if (VBT->getVBaseWithVPtr())
  1083. Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
  1084. Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
  1085. llvm::Value *GVPtr =
  1086. CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
  1087. VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
  1088. "vbptr." + VBT->ObjectWithVPtr->getName());
  1089. CGF.Builder.CreateStore(GVPtr, VBPtr);
  1090. }
  1091. }
  1092. CGCXXABI::AddedStructorArgCounts
  1093. MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
  1094. SmallVectorImpl<CanQualType> &ArgTys) {
  1095. AddedStructorArgCounts Added;
  1096. // TODO: 'for base' flag
  1097. if (isa<CXXDestructorDecl>(GD.getDecl()) &&
  1098. GD.getDtorType() == Dtor_Deleting) {
  1099. // The scalar deleting destructor takes an implicit int parameter.
  1100. ArgTys.push_back(getContext().IntTy);
  1101. ++Added.Suffix;
  1102. }
  1103. auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
  1104. if (!CD)
  1105. return Added;
  1106. // All parameters are already in place except is_most_derived, which goes
  1107. // after 'this' if it's variadic and last if it's not.
  1108. const CXXRecordDecl *Class = CD->getParent();
  1109. const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
  1110. if (Class->getNumVBases()) {
  1111. if (FPT->isVariadic()) {
  1112. ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
  1113. ++Added.Prefix;
  1114. } else {
  1115. ArgTys.push_back(getContext().IntTy);
  1116. ++Added.Suffix;
  1117. }
  1118. }
  1119. return Added;
  1120. }
  1121. void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
  1122. const CXXDestructorDecl *Dtor,
  1123. CXXDtorType DT) const {
  1124. // Deleting destructor variants are never imported or exported. Give them the
  1125. // default storage class.
  1126. if (DT == Dtor_Deleting) {
  1127. GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1128. } else {
  1129. const NamedDecl *ND = Dtor;
  1130. CGM.setDLLImportDLLExport(GV, ND);
  1131. }
  1132. }
  1133. llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
  1134. GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
  1135. // Internal things are always internal, regardless of attributes. After this,
  1136. // we know the thunk is externally visible.
  1137. if (Linkage == GVA_Internal)
  1138. return llvm::GlobalValue::InternalLinkage;
  1139. switch (DT) {
  1140. case Dtor_Base:
  1141. // The base destructor most closely tracks the user-declared constructor, so
  1142. // we delegate back to the normal declarator case.
  1143. return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
  1144. /*IsConstantVariable=*/false);
  1145. case Dtor_Complete:
  1146. // The complete destructor is like an inline function, but it may be
  1147. // imported and therefore must be exported as well. This requires changing
  1148. // the linkage if a DLL attribute is present.
  1149. if (Dtor->hasAttr<DLLExportAttr>())
  1150. return llvm::GlobalValue::WeakODRLinkage;
  1151. if (Dtor->hasAttr<DLLImportAttr>())
  1152. return llvm::GlobalValue::AvailableExternallyLinkage;
  1153. return llvm::GlobalValue::LinkOnceODRLinkage;
  1154. case Dtor_Deleting:
  1155. // Deleting destructors are like inline functions. They have vague linkage
  1156. // and are emitted everywhere they are used. They are internal if the class
  1157. // is internal.
  1158. return llvm::GlobalValue::LinkOnceODRLinkage;
  1159. case Dtor_Comdat:
  1160. llvm_unreachable("MS C++ ABI does not support comdat dtors");
  1161. }
  1162. llvm_unreachable("invalid dtor type");
  1163. }
  1164. void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
  1165. // The TU defining a dtor is only guaranteed to emit a base destructor. All
  1166. // other destructor variants are delegating thunks.
  1167. CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
  1168. // If the class is dllexported, emit the complete (vbase) destructor wherever
  1169. // the base dtor is emitted.
  1170. // FIXME: To match MSVC, this should only be done when the class is exported
  1171. // with -fdllexport-inlines enabled.
  1172. if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
  1173. CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
  1174. }
  1175. CharUnits
  1176. MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
  1177. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1178. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1179. // Complete destructors take a pointer to the complete object as a
  1180. // parameter, thus don't need this adjustment.
  1181. if (GD.getDtorType() == Dtor_Complete)
  1182. return CharUnits();
  1183. // There's no Dtor_Base in vftable but it shares the this adjustment with
  1184. // the deleting one, so look it up instead.
  1185. GD = GlobalDecl(DD, Dtor_Deleting);
  1186. }
  1187. MethodVFTableLocation ML =
  1188. CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
  1189. CharUnits Adjustment = ML.VFPtrOffset;
  1190. // Normal virtual instance methods need to adjust from the vfptr that first
  1191. // defined the virtual method to the virtual base subobject, but destructors
  1192. // do not. The vector deleting destructor thunk applies this adjustment for
  1193. // us if necessary.
  1194. if (isa<CXXDestructorDecl>(MD))
  1195. Adjustment = CharUnits::Zero();
  1196. if (ML.VBase) {
  1197. const ASTRecordLayout &DerivedLayout =
  1198. getContext().getASTRecordLayout(MD->getParent());
  1199. Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
  1200. }
  1201. return Adjustment;
  1202. }
  1203. Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
  1204. CodeGenFunction &CGF, GlobalDecl GD, Address This,
  1205. bool VirtualCall) {
  1206. if (!VirtualCall) {
  1207. // If the call of a virtual function is not virtual, we just have to
  1208. // compensate for the adjustment the virtual function does in its prologue.
  1209. CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
  1210. if (Adjustment.isZero())
  1211. return This;
  1212. This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
  1213. assert(Adjustment.isPositive());
  1214. return CGF.Builder.CreateConstByteGEP(This, Adjustment);
  1215. }
  1216. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1217. GlobalDecl LookupGD = GD;
  1218. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1219. // Complete dtors take a pointer to the complete object,
  1220. // thus don't need adjustment.
  1221. if (GD.getDtorType() == Dtor_Complete)
  1222. return This;
  1223. // There's only Dtor_Deleting in vftable but it shares the this adjustment
  1224. // with the base one, so look up the deleting one instead.
  1225. LookupGD = GlobalDecl(DD, Dtor_Deleting);
  1226. }
  1227. MethodVFTableLocation ML =
  1228. CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
  1229. CharUnits StaticOffset = ML.VFPtrOffset;
  1230. // Base destructors expect 'this' to point to the beginning of the base
  1231. // subobject, not the first vfptr that happens to contain the virtual dtor.
  1232. // However, we still need to apply the virtual base adjustment.
  1233. if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
  1234. StaticOffset = CharUnits::Zero();
  1235. Address Result = This;
  1236. if (ML.VBase) {
  1237. Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
  1238. const CXXRecordDecl *Derived = MD->getParent();
  1239. const CXXRecordDecl *VBase = ML.VBase;
  1240. llvm::Value *VBaseOffset =
  1241. GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
  1242. llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
  1243. Result.getElementType(), Result.getPointer(), VBaseOffset);
  1244. CharUnits VBaseAlign =
  1245. CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
  1246. Result = Address(VBasePtr, VBaseAlign);
  1247. }
  1248. if (!StaticOffset.isZero()) {
  1249. assert(StaticOffset.isPositive());
  1250. Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
  1251. if (ML.VBase) {
  1252. // Non-virtual adjustment might result in a pointer outside the allocated
  1253. // object, e.g. if the final overrider class is laid out after the virtual
  1254. // base that declares a method in the most derived class.
  1255. // FIXME: Update the code that emits this adjustment in thunks prologues.
  1256. Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
  1257. } else {
  1258. Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
  1259. }
  1260. }
  1261. return Result;
  1262. }
  1263. void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
  1264. QualType &ResTy,
  1265. FunctionArgList &Params) {
  1266. ASTContext &Context = getContext();
  1267. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
  1268. assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
  1269. if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
  1270. auto *IsMostDerived = ImplicitParamDecl::Create(
  1271. Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
  1272. &Context.Idents.get("is_most_derived"), Context.IntTy,
  1273. ImplicitParamDecl::Other);
  1274. // The 'most_derived' parameter goes second if the ctor is variadic and last
  1275. // if it's not. Dtors can't be variadic.
  1276. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  1277. if (FPT->isVariadic())
  1278. Params.insert(Params.begin() + 1, IsMostDerived);
  1279. else
  1280. Params.push_back(IsMostDerived);
  1281. getStructorImplicitParamDecl(CGF) = IsMostDerived;
  1282. } else if (isDeletingDtor(CGF.CurGD)) {
  1283. auto *ShouldDelete = ImplicitParamDecl::Create(
  1284. Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
  1285. &Context.Idents.get("should_call_delete"), Context.IntTy,
  1286. ImplicitParamDecl::Other);
  1287. Params.push_back(ShouldDelete);
  1288. getStructorImplicitParamDecl(CGF) = ShouldDelete;
  1289. }
  1290. }
  1291. void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
  1292. // Naked functions have no prolog.
  1293. if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
  1294. return;
  1295. // Overridden virtual methods of non-primary bases need to adjust the incoming
  1296. // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
  1297. // sizeof(void*) to adjust from B* to C*:
  1298. // struct A { virtual void a(); };
  1299. // struct B { virtual void b(); };
  1300. // struct C : A, B { virtual void b(); };
  1301. //
  1302. // Leave the value stored in the 'this' alloca unadjusted, so that the
  1303. // debugger sees the unadjusted value. Microsoft debuggers require this, and
  1304. // will apply the ThisAdjustment in the method type information.
  1305. // FIXME: Do something better for DWARF debuggers, which won't expect this,
  1306. // without making our codegen depend on debug info settings.
  1307. llvm::Value *This = loadIncomingCXXThis(CGF);
  1308. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
  1309. if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
  1310. CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
  1311. if (!Adjustment.isZero()) {
  1312. unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
  1313. llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
  1314. *thisTy = This->getType();
  1315. This = CGF.Builder.CreateBitCast(This, charPtrTy);
  1316. assert(Adjustment.isPositive());
  1317. This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
  1318. -Adjustment.getQuantity());
  1319. This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
  1320. }
  1321. }
  1322. setCXXABIThisValue(CGF, This);
  1323. // If this is a function that the ABI specifies returns 'this', initialize
  1324. // the return slot to 'this' at the start of the function.
  1325. //
  1326. // Unlike the setting of return types, this is done within the ABI
  1327. // implementation instead of by clients of CGCXXABI because:
  1328. // 1) getThisValue is currently protected
  1329. // 2) in theory, an ABI could implement 'this' returns some other way;
  1330. // HasThisReturn only specifies a contract, not the implementation
  1331. if (HasThisReturn(CGF.CurGD))
  1332. CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
  1333. else if (hasMostDerivedReturn(CGF.CurGD))
  1334. CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
  1335. CGF.ReturnValue);
  1336. if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
  1337. assert(getStructorImplicitParamDecl(CGF) &&
  1338. "no implicit parameter for a constructor with virtual bases?");
  1339. getStructorImplicitParamValue(CGF)
  1340. = CGF.Builder.CreateLoad(
  1341. CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
  1342. "is_most_derived");
  1343. }
  1344. if (isDeletingDtor(CGF.CurGD)) {
  1345. assert(getStructorImplicitParamDecl(CGF) &&
  1346. "no implicit parameter for a deleting destructor?");
  1347. getStructorImplicitParamValue(CGF)
  1348. = CGF.Builder.CreateLoad(
  1349. CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
  1350. "should_call_delete");
  1351. }
  1352. }
  1353. CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
  1354. CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
  1355. bool ForVirtualBase, bool Delegating) {
  1356. assert(Type == Ctor_Complete || Type == Ctor_Base);
  1357. // Check if we need a 'most_derived' parameter.
  1358. if (!D->getParent()->getNumVBases())
  1359. return AddedStructorArgs{};
  1360. // Add the 'most_derived' argument second if we are variadic or last if not.
  1361. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1362. llvm::Value *MostDerivedArg;
  1363. if (Delegating) {
  1364. MostDerivedArg = getStructorImplicitParamValue(CGF);
  1365. } else {
  1366. MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
  1367. }
  1368. if (FPT->isVariadic()) {
  1369. return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
  1370. }
  1371. return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
  1372. }
  1373. llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
  1374. CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
  1375. bool ForVirtualBase, bool Delegating) {
  1376. return nullptr;
  1377. }
  1378. void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
  1379. const CXXDestructorDecl *DD,
  1380. CXXDtorType Type, bool ForVirtualBase,
  1381. bool Delegating, Address This,
  1382. QualType ThisTy) {
  1383. // Use the base destructor variant in place of the complete destructor variant
  1384. // if the class has no virtual bases. This effectively implements some of the
  1385. // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
  1386. if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
  1387. Type = Dtor_Base;
  1388. GlobalDecl GD(DD, Type);
  1389. CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
  1390. if (DD->isVirtual()) {
  1391. assert(Type != CXXDtorType::Dtor_Deleting &&
  1392. "The deleting destructor should only be called via a virtual call");
  1393. This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
  1394. This, false);
  1395. }
  1396. llvm::BasicBlock *BaseDtorEndBB = nullptr;
  1397. if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
  1398. BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
  1399. }
  1400. llvm::Value *Implicit =
  1401. getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
  1402. Delegating); // = nullptr
  1403. CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
  1404. /*ImplicitParam=*/Implicit,
  1405. /*ImplicitParamTy=*/QualType(), nullptr);
  1406. if (BaseDtorEndBB) {
  1407. // Complete object handler should continue to be the remaining
  1408. CGF.Builder.CreateBr(BaseDtorEndBB);
  1409. CGF.EmitBlock(BaseDtorEndBB);
  1410. }
  1411. }
  1412. void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
  1413. const CXXRecordDecl *RD,
  1414. llvm::GlobalVariable *VTable) {
  1415. if (!CGM.getCodeGenOpts().LTOUnit)
  1416. return;
  1417. // TODO: Should VirtualFunctionElimination also be supported here?
  1418. // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
  1419. if (CGM.getCodeGenOpts().WholeProgramVTables) {
  1420. llvm::DenseSet<const CXXRecordDecl *> Visited;
  1421. llvm::GlobalObject::VCallVisibility TypeVis =
  1422. CGM.GetVCallVisibilityLevel(RD, Visited);
  1423. if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
  1424. VTable->setVCallVisibilityMetadata(TypeVis);
  1425. }
  1426. // The location of the first virtual function pointer in the virtual table,
  1427. // aka the "address point" on Itanium. This is at offset 0 if RTTI is
  1428. // disabled, or sizeof(void*) if RTTI is enabled.
  1429. CharUnits AddressPoint =
  1430. getContext().getLangOpts().RTTIData
  1431. ? getContext().toCharUnitsFromBits(
  1432. getContext().getTargetInfo().getPointerWidth(0))
  1433. : CharUnits::Zero();
  1434. if (Info.PathToIntroducingObject.empty()) {
  1435. CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
  1436. return;
  1437. }
  1438. // Add a bitset entry for the least derived base belonging to this vftable.
  1439. CGM.AddVTableTypeMetadata(VTable, AddressPoint,
  1440. Info.PathToIntroducingObject.back());
  1441. // Add a bitset entry for each derived class that is laid out at the same
  1442. // offset as the least derived base.
  1443. for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
  1444. const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
  1445. const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
  1446. const ASTRecordLayout &Layout =
  1447. getContext().getASTRecordLayout(DerivedRD);
  1448. CharUnits Offset;
  1449. auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
  1450. if (VBI == Layout.getVBaseOffsetsMap().end())
  1451. Offset = Layout.getBaseClassOffset(BaseRD);
  1452. else
  1453. Offset = VBI->second.VBaseOffset;
  1454. if (!Offset.isZero())
  1455. return;
  1456. CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
  1457. }
  1458. // Finally do the same for the most derived class.
  1459. if (Info.FullOffsetInMDC.isZero())
  1460. CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
  1461. }
  1462. void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
  1463. const CXXRecordDecl *RD) {
  1464. MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
  1465. const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
  1466. for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
  1467. llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
  1468. if (VTable->hasInitializer())
  1469. continue;
  1470. const VTableLayout &VTLayout =
  1471. VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
  1472. llvm::Constant *RTTI = nullptr;
  1473. if (any_of(VTLayout.vtable_components(),
  1474. [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
  1475. RTTI = getMSCompleteObjectLocator(RD, *Info);
  1476. ConstantInitBuilder builder(CGM);
  1477. auto components = builder.beginStruct();
  1478. CGVT.createVTableInitializer(components, VTLayout, RTTI,
  1479. VTable->hasLocalLinkage());
  1480. components.finishAndSetAsInitializer(VTable);
  1481. emitVTableTypeMetadata(*Info, RD, VTable);
  1482. }
  1483. }
  1484. bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
  1485. CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
  1486. return Vptr.NearestVBase != nullptr;
  1487. }
  1488. llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
  1489. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
  1490. const CXXRecordDecl *NearestVBase) {
  1491. llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
  1492. if (!VTableAddressPoint) {
  1493. assert(Base.getBase()->getNumVBases() &&
  1494. !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
  1495. }
  1496. return VTableAddressPoint;
  1497. }
  1498. static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
  1499. const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
  1500. SmallString<256> &Name) {
  1501. llvm::raw_svector_ostream Out(Name);
  1502. MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
  1503. }
  1504. llvm::Constant *
  1505. MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
  1506. const CXXRecordDecl *VTableClass) {
  1507. (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
  1508. VFTableIdTy ID(VTableClass, Base.getBaseOffset());
  1509. return VFTablesMap[ID];
  1510. }
  1511. llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
  1512. BaseSubobject Base, const CXXRecordDecl *VTableClass) {
  1513. llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
  1514. assert(VFTable && "Couldn't find a vftable for the given base?");
  1515. return VFTable;
  1516. }
  1517. llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
  1518. CharUnits VPtrOffset) {
  1519. // getAddrOfVTable may return 0 if asked to get an address of a vtable which
  1520. // shouldn't be used in the given record type. We want to cache this result in
  1521. // VFTablesMap, thus a simple zero check is not sufficient.
  1522. VFTableIdTy ID(RD, VPtrOffset);
  1523. VTablesMapTy::iterator I;
  1524. bool Inserted;
  1525. std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
  1526. if (!Inserted)
  1527. return I->second;
  1528. llvm::GlobalVariable *&VTable = I->second;
  1529. MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
  1530. const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
  1531. if (DeferredVFTables.insert(RD).second) {
  1532. // We haven't processed this record type before.
  1533. // Queue up this vtable for possible deferred emission.
  1534. CGM.addDeferredVTable(RD);
  1535. #ifndef NDEBUG
  1536. // Create all the vftables at once in order to make sure each vftable has
  1537. // a unique mangled name.
  1538. llvm::StringSet<> ObservedMangledNames;
  1539. for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
  1540. SmallString<256> Name;
  1541. mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
  1542. if (!ObservedMangledNames.insert(Name.str()).second)
  1543. llvm_unreachable("Already saw this mangling before?");
  1544. }
  1545. #endif
  1546. }
  1547. const std::unique_ptr<VPtrInfo> *VFPtrI =
  1548. llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {
  1549. return VPI->FullOffsetInMDC == VPtrOffset;
  1550. });
  1551. if (VFPtrI == VFPtrs.end()) {
  1552. VFTablesMap[ID] = nullptr;
  1553. return nullptr;
  1554. }
  1555. const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
  1556. SmallString<256> VFTableName;
  1557. mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
  1558. // Classes marked __declspec(dllimport) need vftables generated on the
  1559. // import-side in order to support features like constexpr. No other
  1560. // translation unit relies on the emission of the local vftable, translation
  1561. // units are expected to generate them as needed.
  1562. //
  1563. // Because of this unique behavior, we maintain this logic here instead of
  1564. // getVTableLinkage.
  1565. llvm::GlobalValue::LinkageTypes VFTableLinkage =
  1566. RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
  1567. : CGM.getVTableLinkage(RD);
  1568. bool VFTableComesFromAnotherTU =
  1569. llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
  1570. llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
  1571. bool VTableAliasIsRequred =
  1572. !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
  1573. if (llvm::GlobalValue *VFTable =
  1574. CGM.getModule().getNamedGlobal(VFTableName)) {
  1575. VFTablesMap[ID] = VFTable;
  1576. VTable = VTableAliasIsRequred
  1577. ? cast<llvm::GlobalVariable>(
  1578. cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())
  1579. : cast<llvm::GlobalVariable>(VFTable);
  1580. return VTable;
  1581. }
  1582. const VTableLayout &VTLayout =
  1583. VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
  1584. llvm::GlobalValue::LinkageTypes VTableLinkage =
  1585. VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
  1586. StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
  1587. llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
  1588. // Create a backing variable for the contents of VTable. The VTable may
  1589. // or may not include space for a pointer to RTTI data.
  1590. llvm::GlobalValue *VFTable;
  1591. VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
  1592. /*isConstant=*/true, VTableLinkage,
  1593. /*Initializer=*/nullptr, VTableName);
  1594. VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1595. llvm::Comdat *C = nullptr;
  1596. if (!VFTableComesFromAnotherTU &&
  1597. (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
  1598. (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
  1599. VTableAliasIsRequred)))
  1600. C = CGM.getModule().getOrInsertComdat(VFTableName.str());
  1601. // Only insert a pointer into the VFTable for RTTI data if we are not
  1602. // importing it. We never reference the RTTI data directly so there is no
  1603. // need to make room for it.
  1604. if (VTableAliasIsRequred) {
  1605. llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
  1606. llvm::ConstantInt::get(CGM.Int32Ty, 0),
  1607. llvm::ConstantInt::get(CGM.Int32Ty, 1)};
  1608. // Create a GEP which points just after the first entry in the VFTable,
  1609. // this should be the location of the first virtual method.
  1610. llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
  1611. VTable->getValueType(), VTable, GEPIndices);
  1612. if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
  1613. VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
  1614. if (C)
  1615. C->setSelectionKind(llvm::Comdat::Largest);
  1616. }
  1617. VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
  1618. /*AddressSpace=*/0, VFTableLinkage,
  1619. VFTableName.str(), VTableGEP,
  1620. &CGM.getModule());
  1621. VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1622. } else {
  1623. // We don't need a GlobalAlias to be a symbol for the VTable if we won't
  1624. // be referencing any RTTI data.
  1625. // The GlobalVariable will end up being an appropriate definition of the
  1626. // VFTable.
  1627. VFTable = VTable;
  1628. }
  1629. if (C)
  1630. VTable->setComdat(C);
  1631. if (RD->hasAttr<DLLExportAttr>())
  1632. VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  1633. VFTablesMap[ID] = VFTable;
  1634. return VTable;
  1635. }
  1636. CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
  1637. GlobalDecl GD,
  1638. Address This,
  1639. llvm::Type *Ty,
  1640. SourceLocation Loc) {
  1641. CGBuilderTy &Builder = CGF.Builder;
  1642. Ty = Ty->getPointerTo();
  1643. Address VPtr =
  1644. adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
  1645. auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
  1646. llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty->getPointerTo(),
  1647. MethodDecl->getParent());
  1648. MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
  1649. MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
  1650. // Compute the identity of the most derived class whose virtual table is
  1651. // located at the MethodVFTableLocation ML.
  1652. auto getObjectWithVPtr = [&] {
  1653. return llvm::find_if(VFTContext.getVFPtrOffsets(
  1654. ML.VBase ? ML.VBase : MethodDecl->getParent()),
  1655. [&](const std::unique_ptr<VPtrInfo> &Info) {
  1656. return Info->FullOffsetInMDC == ML.VFPtrOffset;
  1657. })
  1658. ->get()
  1659. ->ObjectWithVPtr;
  1660. };
  1661. llvm::Value *VFunc;
  1662. if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
  1663. VFunc = CGF.EmitVTableTypeCheckedLoad(
  1664. getObjectWithVPtr(), VTable,
  1665. ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
  1666. } else {
  1667. if (CGM.getCodeGenOpts().PrepareForLTO)
  1668. CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
  1669. llvm::Value *VFuncPtr =
  1670. Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");
  1671. VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());
  1672. }
  1673. CGCallee Callee(GD, VFunc);
  1674. return Callee;
  1675. }
  1676. llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
  1677. CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
  1678. Address This, DeleteOrMemberCallExpr E) {
  1679. auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
  1680. auto *D = E.dyn_cast<const CXXDeleteExpr *>();
  1681. assert((CE != nullptr) ^ (D != nullptr));
  1682. assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
  1683. assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
  1684. // We have only one destructor in the vftable but can get both behaviors
  1685. // by passing an implicit int parameter.
  1686. GlobalDecl GD(Dtor, Dtor_Deleting);
  1687. const CGFunctionInfo *FInfo =
  1688. &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
  1689. llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
  1690. CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
  1691. ASTContext &Context = getContext();
  1692. llvm::Value *ImplicitParam = llvm::ConstantInt::get(
  1693. llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
  1694. DtorType == Dtor_Deleting);
  1695. QualType ThisTy;
  1696. if (CE) {
  1697. ThisTy = CE->getObjectType();
  1698. } else {
  1699. ThisTy = D->getDestroyedType();
  1700. }
  1701. This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
  1702. RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
  1703. ImplicitParam, Context.IntTy, CE);
  1704. return RV.getScalarVal();
  1705. }
  1706. const VBTableGlobals &
  1707. MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
  1708. // At this layer, we can key the cache off of a single class, which is much
  1709. // easier than caching each vbtable individually.
  1710. llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
  1711. bool Added;
  1712. std::tie(Entry, Added) =
  1713. VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
  1714. VBTableGlobals &VBGlobals = Entry->second;
  1715. if (!Added)
  1716. return VBGlobals;
  1717. MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
  1718. VBGlobals.VBTables = &Context.enumerateVBTables(RD);
  1719. // Cache the globals for all vbtables so we don't have to recompute the
  1720. // mangled names.
  1721. llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
  1722. for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
  1723. E = VBGlobals.VBTables->end();
  1724. I != E; ++I) {
  1725. VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
  1726. }
  1727. return VBGlobals;
  1728. }
  1729. llvm::Function *
  1730. MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
  1731. const MethodVFTableLocation &ML) {
  1732. assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
  1733. "can't form pointers to ctors or virtual dtors");
  1734. // Calculate the mangled name.
  1735. SmallString<256> ThunkName;
  1736. llvm::raw_svector_ostream Out(ThunkName);
  1737. getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
  1738. // If the thunk has been generated previously, just return it.
  1739. if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
  1740. return cast<llvm::Function>(GV);
  1741. // Create the llvm::Function.
  1742. const CGFunctionInfo &FnInfo =
  1743. CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
  1744. llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
  1745. llvm::Function *ThunkFn =
  1746. llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
  1747. ThunkName.str(), &CGM.getModule());
  1748. assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
  1749. ThunkFn->setLinkage(MD->isExternallyVisible()
  1750. ? llvm::GlobalValue::LinkOnceODRLinkage
  1751. : llvm::GlobalValue::InternalLinkage);
  1752. if (MD->isExternallyVisible())
  1753. ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
  1754. CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
  1755. CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
  1756. // Add the "thunk" attribute so that LLVM knows that the return type is
  1757. // meaningless. These thunks can be used to call functions with differing
  1758. // return types, and the caller is required to cast the prototype
  1759. // appropriately to extract the correct value.
  1760. ThunkFn->addFnAttr("thunk");
  1761. // These thunks can be compared, so they are not unnamed.
  1762. ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
  1763. // Start codegen.
  1764. CodeGenFunction CGF(CGM);
  1765. CGF.CurGD = GlobalDecl(MD);
  1766. CGF.CurFuncIsThunk = true;
  1767. // Build FunctionArgs, but only include the implicit 'this' parameter
  1768. // declaration.
  1769. FunctionArgList FunctionArgs;
  1770. buildThisParam(CGF, FunctionArgs);
  1771. // Start defining the function.
  1772. CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
  1773. FunctionArgs, MD->getLocation(), SourceLocation());
  1774. setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
  1775. // Load the vfptr and then callee from the vftable. The callee should have
  1776. // adjusted 'this' so that the vfptr is at offset zero.
  1777. llvm::Type *ThunkPtrTy = ThunkTy->getPointerTo();
  1778. llvm::Value *VTable = CGF.GetVTablePtr(
  1779. getThisAddress(CGF), ThunkPtrTy->getPointerTo(), MD->getParent());
  1780. llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
  1781. ThunkPtrTy, VTable, ML.Index, "vfn");
  1782. llvm::Value *Callee =
  1783. CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());
  1784. CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
  1785. return ThunkFn;
  1786. }
  1787. void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
  1788. const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
  1789. for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
  1790. const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
  1791. llvm::GlobalVariable *GV = VBGlobals.Globals[I];
  1792. if (GV->isDeclaration())
  1793. emitVBTableDefinition(*VBT, RD, GV);
  1794. }
  1795. }
  1796. llvm::GlobalVariable *
  1797. MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
  1798. llvm::GlobalVariable::LinkageTypes Linkage) {
  1799. SmallString<256> OutName;
  1800. llvm::raw_svector_ostream Out(OutName);
  1801. getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
  1802. StringRef Name = OutName.str();
  1803. llvm::ArrayType *VBTableType =
  1804. llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
  1805. assert(!CGM.getModule().getNamedGlobal(Name) &&
  1806. "vbtable with this name already exists: mangling bug?");
  1807. CharUnits Alignment =
  1808. CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
  1809. llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
  1810. Name, VBTableType, Linkage, Alignment.getQuantity());
  1811. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1812. if (RD->hasAttr<DLLImportAttr>())
  1813. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  1814. else if (RD->hasAttr<DLLExportAttr>())
  1815. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  1816. if (!GV->hasExternalLinkage())
  1817. emitVBTableDefinition(VBT, RD, GV);
  1818. return GV;
  1819. }
  1820. void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
  1821. const CXXRecordDecl *RD,
  1822. llvm::GlobalVariable *GV) const {
  1823. const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
  1824. assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
  1825. "should only emit vbtables for classes with vbtables");
  1826. const ASTRecordLayout &BaseLayout =
  1827. getContext().getASTRecordLayout(VBT.IntroducingObject);
  1828. const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
  1829. SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
  1830. nullptr);
  1831. // The offset from ObjectWithVPtr's vbptr to itself always leads.
  1832. CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
  1833. Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
  1834. MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
  1835. for (const auto &I : ObjectWithVPtr->vbases()) {
  1836. const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
  1837. CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
  1838. assert(!Offset.isNegative());
  1839. // Make it relative to the subobject vbptr.
  1840. CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
  1841. if (VBT.getVBaseWithVPtr())
  1842. CompleteVBPtrOffset +=
  1843. DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
  1844. Offset -= CompleteVBPtrOffset;
  1845. unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
  1846. assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
  1847. Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
  1848. }
  1849. assert(Offsets.size() ==
  1850. cast<llvm::ArrayType>(GV->getValueType())->getNumElements());
  1851. llvm::ArrayType *VBTableType =
  1852. llvm::ArrayType::get(CGM.IntTy, Offsets.size());
  1853. llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
  1854. GV->setInitializer(Init);
  1855. if (RD->hasAttr<DLLImportAttr>())
  1856. GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
  1857. }
  1858. llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
  1859. Address This,
  1860. const ThisAdjustment &TA) {
  1861. if (TA.isEmpty())
  1862. return This.getPointer();
  1863. This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
  1864. llvm::Value *V;
  1865. if (TA.Virtual.isEmpty()) {
  1866. V = This.getPointer();
  1867. } else {
  1868. assert(TA.Virtual.Microsoft.VtordispOffset < 0);
  1869. // Adjust the this argument based on the vtordisp value.
  1870. Address VtorDispPtr =
  1871. CGF.Builder.CreateConstInBoundsByteGEP(This,
  1872. CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
  1873. VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
  1874. llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
  1875. V = CGF.Builder.CreateGEP(This.getElementType(), This.getPointer(),
  1876. CGF.Builder.CreateNeg(VtorDisp));
  1877. // Unfortunately, having applied the vtordisp means that we no
  1878. // longer really have a known alignment for the vbptr step.
  1879. // We'll assume the vbptr is pointer-aligned.
  1880. if (TA.Virtual.Microsoft.VBPtrOffset) {
  1881. // If the final overrider is defined in a virtual base other than the one
  1882. // that holds the vfptr, we have to use a vtordispex thunk which looks up
  1883. // the vbtable of the derived class.
  1884. assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
  1885. assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
  1886. llvm::Value *VBPtr;
  1887. llvm::Value *VBaseOffset =
  1888. GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()),
  1889. -TA.Virtual.Microsoft.VBPtrOffset,
  1890. TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
  1891. V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
  1892. }
  1893. }
  1894. if (TA.NonVirtual) {
  1895. // Non-virtual adjustment might result in a pointer outside the allocated
  1896. // object, e.g. if the final overrider class is laid out after the virtual
  1897. // base that declares a method in the most derived class.
  1898. V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);
  1899. }
  1900. // Don't need to bitcast back, the call CodeGen will handle this.
  1901. return V;
  1902. }
  1903. llvm::Value *
  1904. MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
  1905. const ReturnAdjustment &RA) {
  1906. if (RA.isEmpty())
  1907. return Ret.getPointer();
  1908. auto OrigTy = Ret.getType();
  1909. Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
  1910. llvm::Value *V = Ret.getPointer();
  1911. if (RA.Virtual.Microsoft.VBIndex) {
  1912. assert(RA.Virtual.Microsoft.VBIndex > 0);
  1913. int32_t IntSize = CGF.getIntSize().getQuantity();
  1914. llvm::Value *VBPtr;
  1915. llvm::Value *VBaseOffset =
  1916. GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
  1917. IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
  1918. V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
  1919. }
  1920. if (RA.NonVirtual)
  1921. V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
  1922. // Cast back to the original type.
  1923. return CGF.Builder.CreateBitCast(V, OrigTy);
  1924. }
  1925. bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
  1926. QualType elementType) {
  1927. // Microsoft seems to completely ignore the possibility of a
  1928. // two-argument usual deallocation function.
  1929. return elementType.isDestructedType();
  1930. }
  1931. bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
  1932. // Microsoft seems to completely ignore the possibility of a
  1933. // two-argument usual deallocation function.
  1934. return expr->getAllocatedType().isDestructedType();
  1935. }
  1936. CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
  1937. // The array cookie is always a size_t; we then pad that out to the
  1938. // alignment of the element type.
  1939. ASTContext &Ctx = getContext();
  1940. return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
  1941. Ctx.getTypeAlignInChars(type));
  1942. }
  1943. llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
  1944. Address allocPtr,
  1945. CharUnits cookieSize) {
  1946. Address numElementsPtr =
  1947. CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
  1948. return CGF.Builder.CreateLoad(numElementsPtr);
  1949. }
  1950. Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
  1951. Address newPtr,
  1952. llvm::Value *numElements,
  1953. const CXXNewExpr *expr,
  1954. QualType elementType) {
  1955. assert(requiresArrayCookie(expr));
  1956. // The size of the cookie.
  1957. CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
  1958. // Compute an offset to the cookie.
  1959. Address cookiePtr = newPtr;
  1960. // Write the number of elements into the appropriate slot.
  1961. Address numElementsPtr
  1962. = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
  1963. CGF.Builder.CreateStore(numElements, numElementsPtr);
  1964. // Finally, compute a pointer to the actual data buffer by skipping
  1965. // over the cookie completely.
  1966. return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
  1967. }
  1968. static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
  1969. llvm::FunctionCallee Dtor,
  1970. llvm::Constant *Addr) {
  1971. // Create a function which calls the destructor.
  1972. llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
  1973. // extern "C" int __tlregdtor(void (*f)(void));
  1974. llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
  1975. CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
  1976. llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
  1977. TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
  1978. if (llvm::Function *TLRegDtorFn =
  1979. dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
  1980. TLRegDtorFn->setDoesNotThrow();
  1981. CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
  1982. }
  1983. void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
  1984. llvm::FunctionCallee Dtor,
  1985. llvm::Constant *Addr) {
  1986. if (D.isNoDestroy(CGM.getContext()))
  1987. return;
  1988. if (D.getTLSKind())
  1989. return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
  1990. // The default behavior is to use atexit.
  1991. CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
  1992. }
  1993. void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
  1994. CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
  1995. ArrayRef<llvm::Function *> CXXThreadLocalInits,
  1996. ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
  1997. if (CXXThreadLocalInits.empty())
  1998. return;
  1999. CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
  2000. llvm::Triple::x86
  2001. ? "/include:___dyn_tls_init@12"
  2002. : "/include:__dyn_tls_init");
  2003. // This will create a GV in the .CRT$XDU section. It will point to our
  2004. // initialization function. The CRT will call all of these function
  2005. // pointers at start-up time and, eventually, at thread-creation time.
  2006. auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
  2007. llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
  2008. CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
  2009. llvm::GlobalVariable::InternalLinkage, InitFunc,
  2010. Twine(InitFunc->getName(), "$initializer$"));
  2011. InitFuncPtr->setSection(".CRT$XDU");
  2012. // This variable has discardable linkage, we have to add it to @llvm.used to
  2013. // ensure it won't get discarded.
  2014. CGM.addUsedGlobal(InitFuncPtr);
  2015. return InitFuncPtr;
  2016. };
  2017. std::vector<llvm::Function *> NonComdatInits;
  2018. for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
  2019. llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
  2020. CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
  2021. llvm::Function *F = CXXThreadLocalInits[I];
  2022. // If the GV is already in a comdat group, then we have to join it.
  2023. if (llvm::Comdat *C = GV->getComdat())
  2024. AddToXDU(F)->setComdat(C);
  2025. else
  2026. NonComdatInits.push_back(F);
  2027. }
  2028. if (!NonComdatInits.empty()) {
  2029. llvm::FunctionType *FTy =
  2030. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  2031. llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
  2032. FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
  2033. SourceLocation(), /*TLS=*/true);
  2034. CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
  2035. AddToXDU(InitFunc);
  2036. }
  2037. }
  2038. static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
  2039. // __tls_guard comes from the MSVC runtime and reflects
  2040. // whether TLS has been initialized for a particular thread.
  2041. // It is set from within __dyn_tls_init by the runtime.
  2042. // Every library and executable has its own variable.
  2043. llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());
  2044. llvm::Constant *TlsGuardConstant =
  2045. CGM.CreateRuntimeVariable(VTy, "__tls_guard");
  2046. llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);
  2047. TlsGuard->setThreadLocal(true);
  2048. return TlsGuard;
  2049. }
  2050. static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {
  2051. // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers
  2052. // dynamic TLS initialization by calling __dyn_tls_init internally.
  2053. llvm::FunctionType *FTy =
  2054. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},
  2055. /*isVarArg=*/false);
  2056. return CGM.CreateRuntimeFunction(
  2057. FTy, "__dyn_tls_on_demand_init",
  2058. llvm::AttributeList::get(CGM.getLLVMContext(),
  2059. llvm::AttributeList::FunctionIndex,
  2060. llvm::Attribute::NoUnwind),
  2061. /*Local=*/true);
  2062. }
  2063. static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,
  2064. llvm::BasicBlock *DynInitBB,
  2065. llvm::BasicBlock *ContinueBB) {
  2066. llvm::LoadInst *TlsGuardValue =
  2067. CGF.Builder.CreateLoad(Address(TlsGuard, CharUnits::One()));
  2068. llvm::Value *CmpResult =
  2069. CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));
  2070. CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);
  2071. }
  2072. static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF,
  2073. llvm::GlobalValue *TlsGuard,
  2074. llvm::BasicBlock *ContinueBB) {
  2075. llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);
  2076. llvm::Function *InitializerFunction =
  2077. cast<llvm::Function>(Initializer.getCallee());
  2078. llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);
  2079. CallVal->setCallingConv(InitializerFunction->getCallingConv());
  2080. CGF.Builder.CreateBr(ContinueBB);
  2081. }
  2082. static void emitDynamicTlsInitialization(CodeGenFunction &CGF) {
  2083. llvm::BasicBlock *DynInitBB =
  2084. CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);
  2085. llvm::BasicBlock *ContinueBB =
  2086. CGF.createBasicBlock("dyntls.continue", CGF.CurFn);
  2087. llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);
  2088. emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);
  2089. CGF.Builder.SetInsertPoint(DynInitBB);
  2090. emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);
  2091. CGF.Builder.SetInsertPoint(ContinueBB);
  2092. }
  2093. LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
  2094. const VarDecl *VD,
  2095. QualType LValType) {
  2096. // Dynamic TLS initialization works by checking the state of a
  2097. // guard variable (__tls_guard) to see whether TLS initialization
  2098. // for a thread has happend yet.
  2099. // If not, the initialization is triggered on-demand
  2100. // by calling __dyn_tls_on_demand_init.
  2101. emitDynamicTlsInitialization(CGF);
  2102. // Emit the variable just like any regular global variable.
  2103. llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
  2104. llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
  2105. unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
  2106. V = CGF.Builder.CreateBitCast(V, RealVarTy->getPointerTo(AS));
  2107. CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
  2108. Address Addr(V, Alignment);
  2109. LValue LV = VD->getType()->isReferenceType()
  2110. ? CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
  2111. AlignmentSource::Decl)
  2112. : CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);
  2113. return LV;
  2114. }
  2115. static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
  2116. StringRef VarName("_Init_thread_epoch");
  2117. CharUnits Align = CGM.getIntAlign();
  2118. if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
  2119. return ConstantAddress(GV, GV->getValueType(), Align);
  2120. auto *GV = new llvm::GlobalVariable(
  2121. CGM.getModule(), CGM.IntTy,
  2122. /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
  2123. /*Initializer=*/nullptr, VarName,
  2124. /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
  2125. GV->setAlignment(Align.getAsAlign());
  2126. return ConstantAddress(GV, GV->getValueType(), Align);
  2127. }
  2128. static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
  2129. llvm::FunctionType *FTy =
  2130. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
  2131. CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
  2132. return CGM.CreateRuntimeFunction(
  2133. FTy, "_Init_thread_header",
  2134. llvm::AttributeList::get(CGM.getLLVMContext(),
  2135. llvm::AttributeList::FunctionIndex,
  2136. llvm::Attribute::NoUnwind),
  2137. /*Local=*/true);
  2138. }
  2139. static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
  2140. llvm::FunctionType *FTy =
  2141. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
  2142. CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
  2143. return CGM.CreateRuntimeFunction(
  2144. FTy, "_Init_thread_footer",
  2145. llvm::AttributeList::get(CGM.getLLVMContext(),
  2146. llvm::AttributeList::FunctionIndex,
  2147. llvm::Attribute::NoUnwind),
  2148. /*Local=*/true);
  2149. }
  2150. static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
  2151. llvm::FunctionType *FTy =
  2152. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
  2153. CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
  2154. return CGM.CreateRuntimeFunction(
  2155. FTy, "_Init_thread_abort",
  2156. llvm::AttributeList::get(CGM.getLLVMContext(),
  2157. llvm::AttributeList::FunctionIndex,
  2158. llvm::Attribute::NoUnwind),
  2159. /*Local=*/true);
  2160. }
  2161. namespace {
  2162. struct ResetGuardBit final : EHScopeStack::Cleanup {
  2163. Address Guard;
  2164. unsigned GuardNum;
  2165. ResetGuardBit(Address Guard, unsigned GuardNum)
  2166. : Guard(Guard), GuardNum(GuardNum) {}
  2167. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2168. // Reset the bit in the mask so that the static variable may be
  2169. // reinitialized.
  2170. CGBuilderTy &Builder = CGF.Builder;
  2171. llvm::LoadInst *LI = Builder.CreateLoad(Guard);
  2172. llvm::ConstantInt *Mask =
  2173. llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
  2174. Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
  2175. }
  2176. };
  2177. struct CallInitThreadAbort final : EHScopeStack::Cleanup {
  2178. llvm::Value *Guard;
  2179. CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
  2180. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2181. // Calling _Init_thread_abort will reset the guard's state.
  2182. CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
  2183. }
  2184. };
  2185. }
  2186. void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
  2187. llvm::GlobalVariable *GV,
  2188. bool PerformInit) {
  2189. // MSVC only uses guards for static locals.
  2190. if (!D.isStaticLocal()) {
  2191. assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
  2192. // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
  2193. llvm::Function *F = CGF.CurFn;
  2194. F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
  2195. F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
  2196. CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
  2197. return;
  2198. }
  2199. bool ThreadlocalStatic = D.getTLSKind();
  2200. bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
  2201. // Thread-safe static variables which aren't thread-specific have a
  2202. // per-variable guard.
  2203. bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
  2204. CGBuilderTy &Builder = CGF.Builder;
  2205. llvm::IntegerType *GuardTy = CGF.Int32Ty;
  2206. llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
  2207. CharUnits GuardAlign = CharUnits::fromQuantity(4);
  2208. // Get the guard variable for this function if we have one already.
  2209. GuardInfo *GI = nullptr;
  2210. if (ThreadlocalStatic)
  2211. GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
  2212. else if (!ThreadsafeStatic)
  2213. GI = &GuardVariableMap[D.getDeclContext()];
  2214. llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
  2215. unsigned GuardNum;
  2216. if (D.isExternallyVisible()) {
  2217. // Externally visible variables have to be numbered in Sema to properly
  2218. // handle unreachable VarDecls.
  2219. GuardNum = getContext().getStaticLocalNumber(&D);
  2220. assert(GuardNum > 0);
  2221. GuardNum--;
  2222. } else if (HasPerVariableGuard) {
  2223. GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
  2224. } else {
  2225. // Non-externally visible variables are numbered here in CodeGen.
  2226. GuardNum = GI->BitIndex++;
  2227. }
  2228. if (!HasPerVariableGuard && GuardNum >= 32) {
  2229. if (D.isExternallyVisible())
  2230. ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
  2231. GuardNum %= 32;
  2232. GuardVar = nullptr;
  2233. }
  2234. if (!GuardVar) {
  2235. // Mangle the name for the guard.
  2236. SmallString<256> GuardName;
  2237. {
  2238. llvm::raw_svector_ostream Out(GuardName);
  2239. if (HasPerVariableGuard)
  2240. getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
  2241. Out);
  2242. else
  2243. getMangleContext().mangleStaticGuardVariable(&D, Out);
  2244. }
  2245. // Create the guard variable with a zero-initializer. Just absorb linkage,
  2246. // visibility and dll storage class from the guarded variable.
  2247. GuardVar =
  2248. new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
  2249. GV->getLinkage(), Zero, GuardName.str());
  2250. GuardVar->setVisibility(GV->getVisibility());
  2251. GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
  2252. GuardVar->setAlignment(GuardAlign.getAsAlign());
  2253. if (GuardVar->isWeakForLinker())
  2254. GuardVar->setComdat(
  2255. CGM.getModule().getOrInsertComdat(GuardVar->getName()));
  2256. if (D.getTLSKind())
  2257. CGM.setTLSMode(GuardVar, D);
  2258. if (GI && !HasPerVariableGuard)
  2259. GI->Guard = GuardVar;
  2260. }
  2261. ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);
  2262. assert(GuardVar->getLinkage() == GV->getLinkage() &&
  2263. "static local from the same function had different linkage");
  2264. if (!HasPerVariableGuard) {
  2265. // Pseudo code for the test:
  2266. // if (!(GuardVar & MyGuardBit)) {
  2267. // GuardVar |= MyGuardBit;
  2268. // ... initialize the object ...;
  2269. // }
  2270. // Test our bit from the guard variable.
  2271. llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
  2272. llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
  2273. llvm::Value *NeedsInit =
  2274. Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
  2275. llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
  2276. llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
  2277. CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
  2278. CodeGenFunction::GuardKind::VariableGuard, &D);
  2279. // Set our bit in the guard variable and emit the initializer and add a global
  2280. // destructor if appropriate.
  2281. CGF.EmitBlock(InitBlock);
  2282. Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
  2283. CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
  2284. CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
  2285. CGF.PopCleanupBlock();
  2286. Builder.CreateBr(EndBlock);
  2287. // Continue.
  2288. CGF.EmitBlock(EndBlock);
  2289. } else {
  2290. // Pseudo code for the test:
  2291. // if (TSS > _Init_thread_epoch) {
  2292. // _Init_thread_header(&TSS);
  2293. // if (TSS == -1) {
  2294. // ... initialize the object ...;
  2295. // _Init_thread_footer(&TSS);
  2296. // }
  2297. // }
  2298. //
  2299. // The algorithm is almost identical to what can be found in the appendix
  2300. // found in N2325.
  2301. // This BasicBLock determines whether or not we have any work to do.
  2302. llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
  2303. FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
  2304. llvm::LoadInst *InitThreadEpoch =
  2305. Builder.CreateLoad(getInitThreadEpochPtr(CGM));
  2306. llvm::Value *IsUninitialized =
  2307. Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
  2308. llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
  2309. llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
  2310. CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
  2311. CodeGenFunction::GuardKind::VariableGuard, &D);
  2312. // This BasicBlock attempts to determine whether or not this thread is
  2313. // responsible for doing the initialization.
  2314. CGF.EmitBlock(AttemptInitBlock);
  2315. CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
  2316. GuardAddr.getPointer());
  2317. llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
  2318. SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
  2319. llvm::Value *ShouldDoInit =
  2320. Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
  2321. llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
  2322. Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
  2323. // Ok, we ended up getting selected as the initializing thread.
  2324. CGF.EmitBlock(InitBlock);
  2325. CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
  2326. CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
  2327. CGF.PopCleanupBlock();
  2328. CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
  2329. GuardAddr.getPointer());
  2330. Builder.CreateBr(EndBlock);
  2331. CGF.EmitBlock(EndBlock);
  2332. }
  2333. }
  2334. bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
  2335. // Null-ness for function memptrs only depends on the first field, which is
  2336. // the function pointer. The rest don't matter, so we can zero initialize.
  2337. if (MPT->isMemberFunctionPointer())
  2338. return true;
  2339. // The virtual base adjustment field is always -1 for null, so if we have one
  2340. // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
  2341. // valid field offset.
  2342. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  2343. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2344. return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
  2345. RD->nullFieldOffsetIsZero());
  2346. }
  2347. llvm::Type *
  2348. MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
  2349. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  2350. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2351. llvm::SmallVector<llvm::Type *, 4> fields;
  2352. if (MPT->isMemberFunctionPointer())
  2353. fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
  2354. else
  2355. fields.push_back(CGM.IntTy); // FieldOffset
  2356. if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
  2357. Inheritance))
  2358. fields.push_back(CGM.IntTy);
  2359. if (inheritanceModelHasVBPtrOffsetField(Inheritance))
  2360. fields.push_back(CGM.IntTy);
  2361. if (inheritanceModelHasVBTableOffsetField(Inheritance))
  2362. fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
  2363. if (fields.size() == 1)
  2364. return fields[0];
  2365. return llvm::StructType::get(CGM.getLLVMContext(), fields);
  2366. }
  2367. void MicrosoftCXXABI::
  2368. GetNullMemberPointerFields(const MemberPointerType *MPT,
  2369. llvm::SmallVectorImpl<llvm::Constant *> &fields) {
  2370. assert(fields.empty());
  2371. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  2372. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2373. if (MPT->isMemberFunctionPointer()) {
  2374. // FunctionPointerOrVirtualThunk
  2375. fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
  2376. } else {
  2377. if (RD->nullFieldOffsetIsZero())
  2378. fields.push_back(getZeroInt()); // FieldOffset
  2379. else
  2380. fields.push_back(getAllOnesInt()); // FieldOffset
  2381. }
  2382. if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
  2383. Inheritance))
  2384. fields.push_back(getZeroInt());
  2385. if (inheritanceModelHasVBPtrOffsetField(Inheritance))
  2386. fields.push_back(getZeroInt());
  2387. if (inheritanceModelHasVBTableOffsetField(Inheritance))
  2388. fields.push_back(getAllOnesInt());
  2389. }
  2390. llvm::Constant *
  2391. MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
  2392. llvm::SmallVector<llvm::Constant *, 4> fields;
  2393. GetNullMemberPointerFields(MPT, fields);
  2394. if (fields.size() == 1)
  2395. return fields[0];
  2396. llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
  2397. assert(Res->getType() == ConvertMemberPointerType(MPT));
  2398. return Res;
  2399. }
  2400. llvm::Constant *
  2401. MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
  2402. bool IsMemberFunction,
  2403. const CXXRecordDecl *RD,
  2404. CharUnits NonVirtualBaseAdjustment,
  2405. unsigned VBTableIndex) {
  2406. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2407. // Single inheritance class member pointer are represented as scalars instead
  2408. // of aggregates.
  2409. if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
  2410. return FirstField;
  2411. llvm::SmallVector<llvm::Constant *, 4> fields;
  2412. fields.push_back(FirstField);
  2413. if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
  2414. fields.push_back(llvm::ConstantInt::get(
  2415. CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
  2416. if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
  2417. CharUnits Offs = CharUnits::Zero();
  2418. if (VBTableIndex)
  2419. Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
  2420. fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
  2421. }
  2422. // The rest of the fields are adjusted by conversions to a more derived class.
  2423. if (inheritanceModelHasVBTableOffsetField(Inheritance))
  2424. fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
  2425. return llvm::ConstantStruct::getAnon(fields);
  2426. }
  2427. llvm::Constant *
  2428. MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
  2429. CharUnits offset) {
  2430. return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
  2431. }
  2432. llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
  2433. CharUnits offset) {
  2434. if (RD->getMSInheritanceModel() ==
  2435. MSInheritanceModel::Virtual)
  2436. offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
  2437. llvm::Constant *FirstField =
  2438. llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
  2439. return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
  2440. CharUnits::Zero(), /*VBTableIndex=*/0);
  2441. }
  2442. llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
  2443. QualType MPType) {
  2444. const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
  2445. const ValueDecl *MPD = MP.getMemberPointerDecl();
  2446. if (!MPD)
  2447. return EmitNullMemberPointer(DstTy);
  2448. ASTContext &Ctx = getContext();
  2449. ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
  2450. llvm::Constant *C;
  2451. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
  2452. C = EmitMemberFunctionPointer(MD);
  2453. } else {
  2454. // For a pointer to data member, start off with the offset of the field in
  2455. // the class in which it was declared, and convert from there if necessary.
  2456. // For indirect field decls, get the outermost anonymous field and use the
  2457. // parent class.
  2458. CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
  2459. const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
  2460. if (!FD)
  2461. FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
  2462. const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
  2463. RD = RD->getMostRecentNonInjectedDecl();
  2464. C = EmitMemberDataPointer(RD, FieldOffset);
  2465. }
  2466. if (!MemberPointerPath.empty()) {
  2467. const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
  2468. const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
  2469. const MemberPointerType *SrcTy =
  2470. Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
  2471. ->castAs<MemberPointerType>();
  2472. bool DerivedMember = MP.isMemberPointerToDerivedMember();
  2473. SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
  2474. const CXXRecordDecl *PrevRD = SrcRD;
  2475. for (const CXXRecordDecl *PathElem : MemberPointerPath) {
  2476. const CXXRecordDecl *Base = nullptr;
  2477. const CXXRecordDecl *Derived = nullptr;
  2478. if (DerivedMember) {
  2479. Base = PathElem;
  2480. Derived = PrevRD;
  2481. } else {
  2482. Base = PrevRD;
  2483. Derived = PathElem;
  2484. }
  2485. for (const CXXBaseSpecifier &BS : Derived->bases())
  2486. if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
  2487. Base->getCanonicalDecl())
  2488. DerivedToBasePath.push_back(&BS);
  2489. PrevRD = PathElem;
  2490. }
  2491. assert(DerivedToBasePath.size() == MemberPointerPath.size());
  2492. CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
  2493. : CK_BaseToDerivedMemberPointer;
  2494. C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
  2495. DerivedToBasePath.end(), C);
  2496. }
  2497. return C;
  2498. }
  2499. llvm::Constant *
  2500. MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
  2501. assert(MD->isInstance() && "Member function must not be static!");
  2502. CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
  2503. const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
  2504. CodeGenTypes &Types = CGM.getTypes();
  2505. unsigned VBTableIndex = 0;
  2506. llvm::Constant *FirstField;
  2507. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  2508. if (!MD->isVirtual()) {
  2509. llvm::Type *Ty;
  2510. // Check whether the function has a computable LLVM signature.
  2511. if (Types.isFuncTypeConvertible(FPT)) {
  2512. // The function has a computable LLVM signature; use the correct type.
  2513. Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
  2514. } else {
  2515. // Use an arbitrary non-function type to tell GetAddrOfFunction that the
  2516. // function type is incomplete.
  2517. Ty = CGM.PtrDiffTy;
  2518. }
  2519. FirstField = CGM.GetAddrOfFunction(MD, Ty);
  2520. } else {
  2521. auto &VTableContext = CGM.getMicrosoftVTableContext();
  2522. MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
  2523. FirstField = EmitVirtualMemPtrThunk(MD, ML);
  2524. // Include the vfptr adjustment if the method is in a non-primary vftable.
  2525. NonVirtualBaseAdjustment += ML.VFPtrOffset;
  2526. if (ML.VBase)
  2527. VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
  2528. }
  2529. if (VBTableIndex == 0 &&
  2530. RD->getMSInheritanceModel() ==
  2531. MSInheritanceModel::Virtual)
  2532. NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
  2533. // The rest of the fields are common with data member pointers.
  2534. FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
  2535. return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
  2536. NonVirtualBaseAdjustment, VBTableIndex);
  2537. }
  2538. /// Member pointers are the same if they're either bitwise identical *or* both
  2539. /// null. Null-ness for function members is determined by the first field,
  2540. /// while for data member pointers we must compare all fields.
  2541. llvm::Value *
  2542. MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
  2543. llvm::Value *L,
  2544. llvm::Value *R,
  2545. const MemberPointerType *MPT,
  2546. bool Inequality) {
  2547. CGBuilderTy &Builder = CGF.Builder;
  2548. // Handle != comparisons by switching the sense of all boolean operations.
  2549. llvm::ICmpInst::Predicate Eq;
  2550. llvm::Instruction::BinaryOps And, Or;
  2551. if (Inequality) {
  2552. Eq = llvm::ICmpInst::ICMP_NE;
  2553. And = llvm::Instruction::Or;
  2554. Or = llvm::Instruction::And;
  2555. } else {
  2556. Eq = llvm::ICmpInst::ICMP_EQ;
  2557. And = llvm::Instruction::And;
  2558. Or = llvm::Instruction::Or;
  2559. }
  2560. // If this is a single field member pointer (single inheritance), this is a
  2561. // single icmp.
  2562. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  2563. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2564. if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),
  2565. Inheritance))
  2566. return Builder.CreateICmp(Eq, L, R);
  2567. // Compare the first field.
  2568. llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
  2569. llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
  2570. llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
  2571. // Compare everything other than the first field.
  2572. llvm::Value *Res = nullptr;
  2573. llvm::StructType *LType = cast<llvm::StructType>(L->getType());
  2574. for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
  2575. llvm::Value *LF = Builder.CreateExtractValue(L, I);
  2576. llvm::Value *RF = Builder.CreateExtractValue(R, I);
  2577. llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
  2578. if (Res)
  2579. Res = Builder.CreateBinOp(And, Res, Cmp);
  2580. else
  2581. Res = Cmp;
  2582. }
  2583. // Check if the first field is 0 if this is a function pointer.
  2584. if (MPT->isMemberFunctionPointer()) {
  2585. // (l1 == r1 && ...) || l0 == 0
  2586. llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
  2587. llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
  2588. Res = Builder.CreateBinOp(Or, Res, IsZero);
  2589. }
  2590. // Combine the comparison of the first field, which must always be true for
  2591. // this comparison to succeeed.
  2592. return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
  2593. }
  2594. llvm::Value *
  2595. MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  2596. llvm::Value *MemPtr,
  2597. const MemberPointerType *MPT) {
  2598. CGBuilderTy &Builder = CGF.Builder;
  2599. llvm::SmallVector<llvm::Constant *, 4> fields;
  2600. // We only need one field for member functions.
  2601. if (MPT->isMemberFunctionPointer())
  2602. fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
  2603. else
  2604. GetNullMemberPointerFields(MPT, fields);
  2605. assert(!fields.empty());
  2606. llvm::Value *FirstField = MemPtr;
  2607. if (MemPtr->getType()->isStructTy())
  2608. FirstField = Builder.CreateExtractValue(MemPtr, 0);
  2609. llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
  2610. // For function member pointers, we only need to test the function pointer
  2611. // field. The other fields if any can be garbage.
  2612. if (MPT->isMemberFunctionPointer())
  2613. return Res;
  2614. // Otherwise, emit a series of compares and combine the results.
  2615. for (int I = 1, E = fields.size(); I < E; ++I) {
  2616. llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
  2617. llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
  2618. Res = Builder.CreateOr(Res, Next, "memptr.tobool");
  2619. }
  2620. return Res;
  2621. }
  2622. bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
  2623. llvm::Constant *Val) {
  2624. // Function pointers are null if the pointer in the first field is null.
  2625. if (MPT->isMemberFunctionPointer()) {
  2626. llvm::Constant *FirstField = Val->getType()->isStructTy() ?
  2627. Val->getAggregateElement(0U) : Val;
  2628. return FirstField->isNullValue();
  2629. }
  2630. // If it's not a function pointer and it's zero initializable, we can easily
  2631. // check zero.
  2632. if (isZeroInitializable(MPT) && Val->isNullValue())
  2633. return true;
  2634. // Otherwise, break down all the fields for comparison. Hopefully these
  2635. // little Constants are reused, while a big null struct might not be.
  2636. llvm::SmallVector<llvm::Constant *, 4> Fields;
  2637. GetNullMemberPointerFields(MPT, Fields);
  2638. if (Fields.size() == 1) {
  2639. assert(Val->getType()->isIntegerTy());
  2640. return Val == Fields[0];
  2641. }
  2642. unsigned I, E;
  2643. for (I = 0, E = Fields.size(); I != E; ++I) {
  2644. if (Val->getAggregateElement(I) != Fields[I])
  2645. break;
  2646. }
  2647. return I == E;
  2648. }
  2649. llvm::Value *
  2650. MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
  2651. Address This,
  2652. llvm::Value *VBPtrOffset,
  2653. llvm::Value *VBTableOffset,
  2654. llvm::Value **VBPtrOut) {
  2655. CGBuilderTy &Builder = CGF.Builder;
  2656. // Load the vbtable pointer from the vbptr in the instance.
  2657. This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
  2658. llvm::Value *VBPtr = Builder.CreateInBoundsGEP(
  2659. This.getElementType(), This.getPointer(), VBPtrOffset, "vbptr");
  2660. if (VBPtrOut) *VBPtrOut = VBPtr;
  2661. VBPtr = Builder.CreateBitCast(VBPtr,
  2662. CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
  2663. CharUnits VBPtrAlign;
  2664. if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
  2665. VBPtrAlign = This.getAlignment().alignmentAtOffset(
  2666. CharUnits::fromQuantity(CI->getSExtValue()));
  2667. } else {
  2668. VBPtrAlign = CGF.getPointerAlign();
  2669. }
  2670. llvm::Value *VBTable = Builder.CreateAlignedLoad(
  2671. CGM.Int32Ty->getPointerTo(0), VBPtr, VBPtrAlign, "vbtable");
  2672. // Translate from byte offset to table index. It improves analyzability.
  2673. llvm::Value *VBTableIndex = Builder.CreateAShr(
  2674. VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
  2675. "vbtindex", /*isExact=*/true);
  2676. // Load an i32 offset from the vb-table.
  2677. llvm::Value *VBaseOffs =
  2678. Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);
  2679. VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
  2680. return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,
  2681. CharUnits::fromQuantity(4), "vbase_offs");
  2682. }
  2683. // Returns an adjusted base cast to i8*, since we do more address arithmetic on
  2684. // it.
  2685. llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
  2686. CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
  2687. Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
  2688. CGBuilderTy &Builder = CGF.Builder;
  2689. Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
  2690. llvm::BasicBlock *OriginalBB = nullptr;
  2691. llvm::BasicBlock *SkipAdjustBB = nullptr;
  2692. llvm::BasicBlock *VBaseAdjustBB = nullptr;
  2693. // In the unspecified inheritance model, there might not be a vbtable at all,
  2694. // in which case we need to skip the virtual base lookup. If there is a
  2695. // vbtable, the first entry is a no-op entry that gives back the original
  2696. // base, so look for a virtual base adjustment offset of zero.
  2697. if (VBPtrOffset) {
  2698. OriginalBB = Builder.GetInsertBlock();
  2699. VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
  2700. SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
  2701. llvm::Value *IsVirtual =
  2702. Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
  2703. "memptr.is_vbase");
  2704. Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
  2705. CGF.EmitBlock(VBaseAdjustBB);
  2706. }
  2707. // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
  2708. // know the vbptr offset.
  2709. if (!VBPtrOffset) {
  2710. CharUnits offs = CharUnits::Zero();
  2711. if (!RD->hasDefinition()) {
  2712. DiagnosticsEngine &Diags = CGF.CGM.getDiags();
  2713. unsigned DiagID = Diags.getCustomDiagID(
  2714. DiagnosticsEngine::Error,
  2715. "member pointer representation requires a "
  2716. "complete class type for %0 to perform this expression");
  2717. Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
  2718. } else if (RD->getNumVBases())
  2719. offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
  2720. VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
  2721. }
  2722. llvm::Value *VBPtr = nullptr;
  2723. llvm::Value *VBaseOffs =
  2724. GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
  2725. llvm::Value *AdjustedBase =
  2726. Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);
  2727. // Merge control flow with the case where we didn't have to adjust.
  2728. if (VBaseAdjustBB) {
  2729. Builder.CreateBr(SkipAdjustBB);
  2730. CGF.EmitBlock(SkipAdjustBB);
  2731. llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
  2732. Phi->addIncoming(Base.getPointer(), OriginalBB);
  2733. Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
  2734. return Phi;
  2735. }
  2736. return AdjustedBase;
  2737. }
  2738. llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
  2739. CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
  2740. const MemberPointerType *MPT) {
  2741. assert(MPT->isMemberDataPointer());
  2742. unsigned AS = Base.getAddressSpace();
  2743. llvm::Type *PType =
  2744. CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
  2745. CGBuilderTy &Builder = CGF.Builder;
  2746. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  2747. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  2748. // Extract the fields we need, regardless of model. We'll apply them if we
  2749. // have them.
  2750. llvm::Value *FieldOffset = MemPtr;
  2751. llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
  2752. llvm::Value *VBPtrOffset = nullptr;
  2753. if (MemPtr->getType()->isStructTy()) {
  2754. // We need to extract values.
  2755. unsigned I = 0;
  2756. FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
  2757. if (inheritanceModelHasVBPtrOffsetField(Inheritance))
  2758. VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
  2759. if (inheritanceModelHasVBTableOffsetField(Inheritance))
  2760. VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
  2761. }
  2762. llvm::Value *Addr;
  2763. if (VirtualBaseAdjustmentOffset) {
  2764. Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
  2765. VBPtrOffset);
  2766. } else {
  2767. Addr = Base.getPointer();
  2768. }
  2769. // Cast to char*.
  2770. Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
  2771. // Apply the offset, which we assume is non-null.
  2772. Addr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Addr, FieldOffset,
  2773. "memptr.offset");
  2774. // Cast the address to the appropriate pointer type, adopting the address
  2775. // space of the base pointer.
  2776. return Builder.CreateBitCast(Addr, PType);
  2777. }
  2778. llvm::Value *
  2779. MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
  2780. const CastExpr *E,
  2781. llvm::Value *Src) {
  2782. assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
  2783. E->getCastKind() == CK_BaseToDerivedMemberPointer ||
  2784. E->getCastKind() == CK_ReinterpretMemberPointer);
  2785. // Use constant emission if we can.
  2786. if (isa<llvm::Constant>(Src))
  2787. return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
  2788. // We may be adding or dropping fields from the member pointer, so we need
  2789. // both types and the inheritance models of both records.
  2790. const MemberPointerType *SrcTy =
  2791. E->getSubExpr()->getType()->castAs<MemberPointerType>();
  2792. const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
  2793. bool IsFunc = SrcTy->isMemberFunctionPointer();
  2794. // If the classes use the same null representation, reinterpret_cast is a nop.
  2795. bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
  2796. if (IsReinterpret && IsFunc)
  2797. return Src;
  2798. CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
  2799. CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
  2800. if (IsReinterpret &&
  2801. SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
  2802. return Src;
  2803. CGBuilderTy &Builder = CGF.Builder;
  2804. // Branch past the conversion if Src is null.
  2805. llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
  2806. llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
  2807. // C++ 5.2.10p9: The null member pointer value is converted to the null member
  2808. // pointer value of the destination type.
  2809. if (IsReinterpret) {
  2810. // For reinterpret casts, sema ensures that src and dst are both functions
  2811. // or data and have the same size, which means the LLVM types should match.
  2812. assert(Src->getType() == DstNull->getType());
  2813. return Builder.CreateSelect(IsNotNull, Src, DstNull);
  2814. }
  2815. llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
  2816. llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
  2817. llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
  2818. Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
  2819. CGF.EmitBlock(ConvertBB);
  2820. llvm::Value *Dst = EmitNonNullMemberPointerConversion(
  2821. SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
  2822. Builder);
  2823. Builder.CreateBr(ContinueBB);
  2824. // In the continuation, choose between DstNull and Dst.
  2825. CGF.EmitBlock(ContinueBB);
  2826. llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
  2827. Phi->addIncoming(DstNull, OriginalBB);
  2828. Phi->addIncoming(Dst, ConvertBB);
  2829. return Phi;
  2830. }
  2831. llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
  2832. const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
  2833. CastExpr::path_const_iterator PathBegin,
  2834. CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
  2835. CGBuilderTy &Builder) {
  2836. const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
  2837. const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
  2838. MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
  2839. MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
  2840. bool IsFunc = SrcTy->isMemberFunctionPointer();
  2841. bool IsConstant = isa<llvm::Constant>(Src);
  2842. // Decompose src.
  2843. llvm::Value *FirstField = Src;
  2844. llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
  2845. llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
  2846. llvm::Value *VBPtrOffset = getZeroInt();
  2847. if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
  2848. // We need to extract values.
  2849. unsigned I = 0;
  2850. FirstField = Builder.CreateExtractValue(Src, I++);
  2851. if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
  2852. NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
  2853. if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
  2854. VBPtrOffset = Builder.CreateExtractValue(Src, I++);
  2855. if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
  2856. VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
  2857. }
  2858. bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
  2859. const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
  2860. const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
  2861. // For data pointers, we adjust the field offset directly. For functions, we
  2862. // have a separate field.
  2863. llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
  2864. // The virtual inheritance model has a quirk: the virtual base table is always
  2865. // referenced when dereferencing a member pointer even if the member pointer
  2866. // is non-virtual. This is accounted for by adjusting the non-virtual offset
  2867. // to point backwards to the top of the MDC from the first VBase. Undo this
  2868. // adjustment to normalize the member pointer.
  2869. llvm::Value *SrcVBIndexEqZero =
  2870. Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
  2871. if (SrcInheritance == MSInheritanceModel::Virtual) {
  2872. if (int64_t SrcOffsetToFirstVBase =
  2873. getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
  2874. llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
  2875. SrcVBIndexEqZero,
  2876. llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
  2877. getZeroInt());
  2878. NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
  2879. }
  2880. }
  2881. // A non-zero vbindex implies that we are dealing with a source member in a
  2882. // floating virtual base in addition to some non-virtual offset. If the
  2883. // vbindex is zero, we are dealing with a source that exists in a non-virtual,
  2884. // fixed, base. The difference between these two cases is that the vbindex +
  2885. // nvoffset *always* point to the member regardless of what context they are
  2886. // evaluated in so long as the vbindex is adjusted. A member inside a fixed
  2887. // base requires explicit nv adjustment.
  2888. llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
  2889. CGM.IntTy,
  2890. CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
  2891. .getQuantity());
  2892. llvm::Value *NVDisp;
  2893. if (IsDerivedToBase)
  2894. NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
  2895. else
  2896. NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
  2897. NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
  2898. // Update the vbindex to an appropriate value in the destination because
  2899. // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
  2900. llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
  2901. if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
  2902. inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
  2903. if (llvm::GlobalVariable *VDispMap =
  2904. getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
  2905. llvm::Value *VBIndex = Builder.CreateExactUDiv(
  2906. VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
  2907. if (IsConstant) {
  2908. llvm::Constant *Mapping = VDispMap->getInitializer();
  2909. VirtualBaseAdjustmentOffset =
  2910. Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
  2911. } else {
  2912. llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
  2913. VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(
  2914. CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),
  2915. VDispMap, Idxs),
  2916. CharUnits::fromQuantity(4));
  2917. }
  2918. DstVBIndexEqZero =
  2919. Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
  2920. }
  2921. }
  2922. // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
  2923. // it to the offset of the vbptr.
  2924. if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
  2925. llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
  2926. CGM.IntTy,
  2927. getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
  2928. VBPtrOffset =
  2929. Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
  2930. }
  2931. // Likewise, apply a similar adjustment so that dereferencing the member
  2932. // pointer correctly accounts for the distance between the start of the first
  2933. // virtual base and the top of the MDC.
  2934. if (DstInheritance == MSInheritanceModel::Virtual) {
  2935. if (int64_t DstOffsetToFirstVBase =
  2936. getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
  2937. llvm::Value *DoDstAdjustment = Builder.CreateSelect(
  2938. DstVBIndexEqZero,
  2939. llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
  2940. getZeroInt());
  2941. NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
  2942. }
  2943. }
  2944. // Recompose dst from the null struct and the adjusted fields from src.
  2945. llvm::Value *Dst;
  2946. if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
  2947. Dst = FirstField;
  2948. } else {
  2949. Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
  2950. unsigned Idx = 0;
  2951. Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
  2952. if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
  2953. Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
  2954. if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
  2955. Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
  2956. if (inheritanceModelHasVBTableOffsetField(DstInheritance))
  2957. Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
  2958. }
  2959. return Dst;
  2960. }
  2961. llvm::Constant *
  2962. MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
  2963. llvm::Constant *Src) {
  2964. const MemberPointerType *SrcTy =
  2965. E->getSubExpr()->getType()->castAs<MemberPointerType>();
  2966. const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
  2967. CastKind CK = E->getCastKind();
  2968. return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
  2969. E->path_end(), Src);
  2970. }
  2971. llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
  2972. const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
  2973. CastExpr::path_const_iterator PathBegin,
  2974. CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
  2975. assert(CK == CK_DerivedToBaseMemberPointer ||
  2976. CK == CK_BaseToDerivedMemberPointer ||
  2977. CK == CK_ReinterpretMemberPointer);
  2978. // If src is null, emit a new null for dst. We can't return src because dst
  2979. // might have a new representation.
  2980. if (MemberPointerConstantIsNull(SrcTy, Src))
  2981. return EmitNullMemberPointer(DstTy);
  2982. // We don't need to do anything for reinterpret_casts of non-null member
  2983. // pointers. We should only get here when the two type representations have
  2984. // the same size.
  2985. if (CK == CK_ReinterpretMemberPointer)
  2986. return Src;
  2987. CGBuilderTy Builder(CGM, CGM.getLLVMContext());
  2988. auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
  2989. SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
  2990. return Dst;
  2991. }
  2992. CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
  2993. CodeGenFunction &CGF, const Expr *E, Address This,
  2994. llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
  2995. const MemberPointerType *MPT) {
  2996. assert(MPT->isMemberFunctionPointer());
  2997. const FunctionProtoType *FPT =
  2998. MPT->getPointeeType()->castAs<FunctionProtoType>();
  2999. const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
  3000. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
  3001. CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
  3002. CGBuilderTy &Builder = CGF.Builder;
  3003. MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
  3004. // Extract the fields we need, regardless of model. We'll apply them if we
  3005. // have them.
  3006. llvm::Value *FunctionPointer = MemPtr;
  3007. llvm::Value *NonVirtualBaseAdjustment = nullptr;
  3008. llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
  3009. llvm::Value *VBPtrOffset = nullptr;
  3010. if (MemPtr->getType()->isStructTy()) {
  3011. // We need to extract values.
  3012. unsigned I = 0;
  3013. FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
  3014. if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
  3015. NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
  3016. if (inheritanceModelHasVBPtrOffsetField(Inheritance))
  3017. VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
  3018. if (inheritanceModelHasVBTableOffsetField(Inheritance))
  3019. VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
  3020. }
  3021. if (VirtualBaseAdjustmentOffset) {
  3022. ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
  3023. VirtualBaseAdjustmentOffset, VBPtrOffset);
  3024. } else {
  3025. ThisPtrForCall = This.getPointer();
  3026. }
  3027. if (NonVirtualBaseAdjustment) {
  3028. // Apply the adjustment and cast back to the original struct type.
  3029. llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
  3030. Ptr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Ptr, NonVirtualBaseAdjustment);
  3031. ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
  3032. "this.adjusted");
  3033. }
  3034. FunctionPointer =
  3035. Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
  3036. CGCallee Callee(FPT, FunctionPointer);
  3037. return Callee;
  3038. }
  3039. CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
  3040. return new MicrosoftCXXABI(CGM);
  3041. }
  3042. // MS RTTI Overview:
  3043. // The run time type information emitted by cl.exe contains 5 distinct types of
  3044. // structures. Many of them reference each other.
  3045. //
  3046. // TypeInfo: Static classes that are returned by typeid.
  3047. //
  3048. // CompleteObjectLocator: Referenced by vftables. They contain information
  3049. // required for dynamic casting, including OffsetFromTop. They also contain
  3050. // a reference to the TypeInfo for the type and a reference to the
  3051. // CompleteHierarchyDescriptor for the type.
  3052. //
  3053. // ClassHierarchyDescriptor: Contains information about a class hierarchy.
  3054. // Used during dynamic_cast to walk a class hierarchy. References a base
  3055. // class array and the size of said array.
  3056. //
  3057. // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
  3058. // somewhat of a misnomer because the most derived class is also in the list
  3059. // as well as multiple copies of virtual bases (if they occur multiple times
  3060. // in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for
  3061. // every path in the hierarchy, in pre-order depth first order. Note, we do
  3062. // not declare a specific llvm type for BaseClassArray, it's merely an array
  3063. // of BaseClassDescriptor pointers.
  3064. //
  3065. // BaseClassDescriptor: Contains information about a class in a class hierarchy.
  3066. // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
  3067. // BaseClassArray is. It contains information about a class within a
  3068. // hierarchy such as: is this base is ambiguous and what is its offset in the
  3069. // vbtable. The names of the BaseClassDescriptors have all of their fields
  3070. // mangled into them so they can be aggressively deduplicated by the linker.
  3071. static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
  3072. StringRef MangledName("??_7type_info@@6B@");
  3073. if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
  3074. return VTable;
  3075. return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
  3076. /*isConstant=*/true,
  3077. llvm::GlobalVariable::ExternalLinkage,
  3078. /*Initializer=*/nullptr, MangledName);
  3079. }
  3080. namespace {
  3081. /// A Helper struct that stores information about a class in a class
  3082. /// hierarchy. The information stored in these structs struct is used during
  3083. /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
  3084. // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
  3085. // implicit depth first pre-order tree connectivity. getFirstChild and
  3086. // getNextSibling allow us to walk the tree efficiently.
  3087. struct MSRTTIClass {
  3088. enum {
  3089. IsPrivateOnPath = 1 | 8,
  3090. IsAmbiguous = 2,
  3091. IsPrivate = 4,
  3092. IsVirtual = 16,
  3093. HasHierarchyDescriptor = 64
  3094. };
  3095. MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
  3096. uint32_t initialize(const MSRTTIClass *Parent,
  3097. const CXXBaseSpecifier *Specifier);
  3098. MSRTTIClass *getFirstChild() { return this + 1; }
  3099. static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
  3100. return Child + 1 + Child->NumBases;
  3101. }
  3102. const CXXRecordDecl *RD, *VirtualRoot;
  3103. uint32_t Flags, NumBases, OffsetInVBase;
  3104. };
  3105. /// Recursively initialize the base class array.
  3106. uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
  3107. const CXXBaseSpecifier *Specifier) {
  3108. Flags = HasHierarchyDescriptor;
  3109. if (!Parent) {
  3110. VirtualRoot = nullptr;
  3111. OffsetInVBase = 0;
  3112. } else {
  3113. if (Specifier->getAccessSpecifier() != AS_public)
  3114. Flags |= IsPrivate | IsPrivateOnPath;
  3115. if (Specifier->isVirtual()) {
  3116. Flags |= IsVirtual;
  3117. VirtualRoot = RD;
  3118. OffsetInVBase = 0;
  3119. } else {
  3120. if (Parent->Flags & IsPrivateOnPath)
  3121. Flags |= IsPrivateOnPath;
  3122. VirtualRoot = Parent->VirtualRoot;
  3123. OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
  3124. .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
  3125. }
  3126. }
  3127. NumBases = 0;
  3128. MSRTTIClass *Child = getFirstChild();
  3129. for (const CXXBaseSpecifier &Base : RD->bases()) {
  3130. NumBases += Child->initialize(this, &Base) + 1;
  3131. Child = getNextChild(Child);
  3132. }
  3133. return NumBases;
  3134. }
  3135. static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
  3136. switch (Ty->getLinkage()) {
  3137. case NoLinkage:
  3138. case InternalLinkage:
  3139. case UniqueExternalLinkage:
  3140. return llvm::GlobalValue::InternalLinkage;
  3141. case VisibleNoLinkage:
  3142. case ModuleInternalLinkage:
  3143. case ModuleLinkage:
  3144. case ExternalLinkage:
  3145. return llvm::GlobalValue::LinkOnceODRLinkage;
  3146. }
  3147. llvm_unreachable("Invalid linkage!");
  3148. }
  3149. /// An ephemeral helper class for building MS RTTI types. It caches some
  3150. /// calls to the module and information about the most derived class in a
  3151. /// hierarchy.
  3152. struct MSRTTIBuilder {
  3153. enum {
  3154. HasBranchingHierarchy = 1,
  3155. HasVirtualBranchingHierarchy = 2,
  3156. HasAmbiguousBases = 4
  3157. };
  3158. MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
  3159. : CGM(ABI.CGM), Context(CGM.getContext()),
  3160. VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
  3161. Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
  3162. ABI(ABI) {}
  3163. llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
  3164. llvm::GlobalVariable *
  3165. getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
  3166. llvm::GlobalVariable *getClassHierarchyDescriptor();
  3167. llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
  3168. CodeGenModule &CGM;
  3169. ASTContext &Context;
  3170. llvm::LLVMContext &VMContext;
  3171. llvm::Module &Module;
  3172. const CXXRecordDecl *RD;
  3173. llvm::GlobalVariable::LinkageTypes Linkage;
  3174. MicrosoftCXXABI &ABI;
  3175. };
  3176. } // namespace
  3177. /// Recursively serializes a class hierarchy in pre-order depth first
  3178. /// order.
  3179. static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
  3180. const CXXRecordDecl *RD) {
  3181. Classes.push_back(MSRTTIClass(RD));
  3182. for (const CXXBaseSpecifier &Base : RD->bases())
  3183. serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
  3184. }
  3185. /// Find ambiguity among base classes.
  3186. static void
  3187. detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
  3188. llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
  3189. llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
  3190. llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
  3191. for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
  3192. if ((Class->Flags & MSRTTIClass::IsVirtual) &&
  3193. !VirtualBases.insert(Class->RD).second) {
  3194. Class = MSRTTIClass::getNextChild(Class);
  3195. continue;
  3196. }
  3197. if (!UniqueBases.insert(Class->RD).second)
  3198. AmbiguousBases.insert(Class->RD);
  3199. Class++;
  3200. }
  3201. if (AmbiguousBases.empty())
  3202. return;
  3203. for (MSRTTIClass &Class : Classes)
  3204. if (AmbiguousBases.count(Class.RD))
  3205. Class.Flags |= MSRTTIClass::IsAmbiguous;
  3206. }
  3207. llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
  3208. SmallString<256> MangledName;
  3209. {
  3210. llvm::raw_svector_ostream Out(MangledName);
  3211. ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
  3212. }
  3213. // Check to see if we've already declared this ClassHierarchyDescriptor.
  3214. if (auto CHD = Module.getNamedGlobal(MangledName))
  3215. return CHD;
  3216. // Serialize the class hierarchy and initialize the CHD Fields.
  3217. SmallVector<MSRTTIClass, 8> Classes;
  3218. serializeClassHierarchy(Classes, RD);
  3219. Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
  3220. detectAmbiguousBases(Classes);
  3221. int Flags = 0;
  3222. for (auto Class : Classes) {
  3223. if (Class.RD->getNumBases() > 1)
  3224. Flags |= HasBranchingHierarchy;
  3225. // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
  3226. // believe the field isn't actually used.
  3227. if (Class.Flags & MSRTTIClass::IsAmbiguous)
  3228. Flags |= HasAmbiguousBases;
  3229. }
  3230. if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
  3231. Flags |= HasVirtualBranchingHierarchy;
  3232. // These gep indices are used to get the address of the first element of the
  3233. // base class array.
  3234. llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
  3235. llvm::ConstantInt::get(CGM.IntTy, 0)};
  3236. // Forward-declare the class hierarchy descriptor
  3237. auto Type = ABI.getClassHierarchyDescriptorType();
  3238. auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
  3239. /*Initializer=*/nullptr,
  3240. MangledName);
  3241. if (CHD->isWeakForLinker())
  3242. CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
  3243. auto *Bases = getBaseClassArray(Classes);
  3244. // Initialize the base class ClassHierarchyDescriptor.
  3245. llvm::Constant *Fields[] = {
  3246. llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
  3247. llvm::ConstantInt::get(CGM.IntTy, Flags),
  3248. llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
  3249. ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
  3250. Bases->getValueType(), Bases,
  3251. llvm::ArrayRef<llvm::Value *>(GEPIndices))),
  3252. };
  3253. CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
  3254. return CHD;
  3255. }
  3256. llvm::GlobalVariable *
  3257. MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
  3258. SmallString<256> MangledName;
  3259. {
  3260. llvm::raw_svector_ostream Out(MangledName);
  3261. ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
  3262. }
  3263. // Forward-declare the base class array.
  3264. // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
  3265. // mode) bytes of padding. We provide a pointer sized amount of padding by
  3266. // adding +1 to Classes.size(). The sections have pointer alignment and are
  3267. // marked pick-any so it shouldn't matter.
  3268. llvm::Type *PtrType = ABI.getImageRelativeType(
  3269. ABI.getBaseClassDescriptorType()->getPointerTo());
  3270. auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
  3271. auto *BCA =
  3272. new llvm::GlobalVariable(Module, ArrType,
  3273. /*isConstant=*/true, Linkage,
  3274. /*Initializer=*/nullptr, MangledName);
  3275. if (BCA->isWeakForLinker())
  3276. BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
  3277. // Initialize the BaseClassArray.
  3278. SmallVector<llvm::Constant *, 8> BaseClassArrayData;
  3279. for (MSRTTIClass &Class : Classes)
  3280. BaseClassArrayData.push_back(
  3281. ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
  3282. BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
  3283. BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
  3284. return BCA;
  3285. }
  3286. llvm::GlobalVariable *
  3287. MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
  3288. // Compute the fields for the BaseClassDescriptor. They are computed up front
  3289. // because they are mangled into the name of the object.
  3290. uint32_t OffsetInVBTable = 0;
  3291. int32_t VBPtrOffset = -1;
  3292. if (Class.VirtualRoot) {
  3293. auto &VTableContext = CGM.getMicrosoftVTableContext();
  3294. OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
  3295. VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
  3296. }
  3297. SmallString<256> MangledName;
  3298. {
  3299. llvm::raw_svector_ostream Out(MangledName);
  3300. ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
  3301. Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
  3302. Class.Flags, Out);
  3303. }
  3304. // Check to see if we've already declared this object.
  3305. if (auto BCD = Module.getNamedGlobal(MangledName))
  3306. return BCD;
  3307. // Forward-declare the base class descriptor.
  3308. auto Type = ABI.getBaseClassDescriptorType();
  3309. auto BCD =
  3310. new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
  3311. /*Initializer=*/nullptr, MangledName);
  3312. if (BCD->isWeakForLinker())
  3313. BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
  3314. // Initialize the BaseClassDescriptor.
  3315. llvm::Constant *Fields[] = {
  3316. ABI.getImageRelativeConstant(
  3317. ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
  3318. llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
  3319. llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
  3320. llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
  3321. llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
  3322. llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
  3323. ABI.getImageRelativeConstant(
  3324. MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
  3325. };
  3326. BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
  3327. return BCD;
  3328. }
  3329. llvm::GlobalVariable *
  3330. MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
  3331. SmallString<256> MangledName;
  3332. {
  3333. llvm::raw_svector_ostream Out(MangledName);
  3334. ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
  3335. }
  3336. // Check to see if we've already computed this complete object locator.
  3337. if (auto COL = Module.getNamedGlobal(MangledName))
  3338. return COL;
  3339. // Compute the fields of the complete object locator.
  3340. int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
  3341. int VFPtrOffset = 0;
  3342. // The offset includes the vtordisp if one exists.
  3343. if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
  3344. if (Context.getASTRecordLayout(RD)
  3345. .getVBaseOffsetsMap()
  3346. .find(VBase)
  3347. ->second.hasVtorDisp())
  3348. VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
  3349. // Forward-declare the complete object locator.
  3350. llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
  3351. auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
  3352. /*Initializer=*/nullptr, MangledName);
  3353. // Initialize the CompleteObjectLocator.
  3354. llvm::Constant *Fields[] = {
  3355. llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
  3356. llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
  3357. llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
  3358. ABI.getImageRelativeConstant(
  3359. CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
  3360. ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
  3361. ABI.getImageRelativeConstant(COL),
  3362. };
  3363. llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
  3364. if (!ABI.isImageRelative())
  3365. FieldsRef = FieldsRef.drop_back();
  3366. COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
  3367. if (COL->isWeakForLinker())
  3368. COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
  3369. return COL;
  3370. }
  3371. static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
  3372. bool &IsConst, bool &IsVolatile,
  3373. bool &IsUnaligned) {
  3374. T = Context.getExceptionObjectType(T);
  3375. // C++14 [except.handle]p3:
  3376. // A handler is a match for an exception object of type E if [...]
  3377. // - the handler is of type cv T or const T& where T is a pointer type and
  3378. // E is a pointer type that can be converted to T by [...]
  3379. // - a qualification conversion
  3380. IsConst = false;
  3381. IsVolatile = false;
  3382. IsUnaligned = false;
  3383. QualType PointeeType = T->getPointeeType();
  3384. if (!PointeeType.isNull()) {
  3385. IsConst = PointeeType.isConstQualified();
  3386. IsVolatile = PointeeType.isVolatileQualified();
  3387. IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
  3388. }
  3389. // Member pointer types like "const int A::*" are represented by having RTTI
  3390. // for "int A::*" and separately storing the const qualifier.
  3391. if (const auto *MPTy = T->getAs<MemberPointerType>())
  3392. T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
  3393. MPTy->getClass());
  3394. // Pointer types like "const int * const *" are represented by having RTTI
  3395. // for "const int **" and separately storing the const qualifier.
  3396. if (T->isPointerType())
  3397. T = Context.getPointerType(PointeeType.getUnqualifiedType());
  3398. return T;
  3399. }
  3400. CatchTypeInfo
  3401. MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
  3402. QualType CatchHandlerType) {
  3403. // TypeDescriptors for exceptions never have qualified pointer types,
  3404. // qualifiers are stored separately in order to support qualification
  3405. // conversions.
  3406. bool IsConst, IsVolatile, IsUnaligned;
  3407. Type =
  3408. decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
  3409. bool IsReference = CatchHandlerType->isReferenceType();
  3410. uint32_t Flags = 0;
  3411. if (IsConst)
  3412. Flags |= 1;
  3413. if (IsVolatile)
  3414. Flags |= 2;
  3415. if (IsUnaligned)
  3416. Flags |= 4;
  3417. if (IsReference)
  3418. Flags |= 8;
  3419. return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
  3420. Flags};
  3421. }
  3422. /// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
  3423. /// llvm::GlobalVariable * because different type descriptors have different
  3424. /// types, and need to be abstracted. They are abstracting by casting the
  3425. /// address to an Int8PtrTy.
  3426. llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
  3427. SmallString<256> MangledName;
  3428. {
  3429. llvm::raw_svector_ostream Out(MangledName);
  3430. getMangleContext().mangleCXXRTTI(Type, Out);
  3431. }
  3432. // Check to see if we've already declared this TypeDescriptor.
  3433. if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
  3434. return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
  3435. // Note for the future: If we would ever like to do deferred emission of
  3436. // RTTI, check if emitting vtables opportunistically need any adjustment.
  3437. // Compute the fields for the TypeDescriptor.
  3438. SmallString<256> TypeInfoString;
  3439. {
  3440. llvm::raw_svector_ostream Out(TypeInfoString);
  3441. getMangleContext().mangleCXXRTTIName(Type, Out);
  3442. }
  3443. // Declare and initialize the TypeDescriptor.
  3444. llvm::Constant *Fields[] = {
  3445. getTypeInfoVTable(CGM), // VFPtr
  3446. llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
  3447. llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
  3448. llvm::StructType *TypeDescriptorType =
  3449. getTypeDescriptorType(TypeInfoString);
  3450. auto *Var = new llvm::GlobalVariable(
  3451. CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
  3452. getLinkageForRTTI(Type),
  3453. llvm::ConstantStruct::get(TypeDescriptorType, Fields),
  3454. MangledName);
  3455. if (Var->isWeakForLinker())
  3456. Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
  3457. return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
  3458. }
  3459. /// Gets or a creates a Microsoft CompleteObjectLocator.
  3460. llvm::GlobalVariable *
  3461. MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
  3462. const VPtrInfo &Info) {
  3463. return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
  3464. }
  3465. void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
  3466. if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
  3467. // There are no constructor variants, always emit the complete destructor.
  3468. llvm::Function *Fn =
  3469. CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
  3470. CGM.maybeSetTrivialComdat(*ctor, *Fn);
  3471. return;
  3472. }
  3473. auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
  3474. // Emit the base destructor if the base and complete (vbase) destructors are
  3475. // equivalent. This effectively implements -mconstructor-aliases as part of
  3476. // the ABI.
  3477. if (GD.getDtorType() == Dtor_Complete &&
  3478. dtor->getParent()->getNumVBases() == 0)
  3479. GD = GD.getWithDtorType(Dtor_Base);
  3480. // The base destructor is equivalent to the base destructor of its
  3481. // base class if there is exactly one non-virtual base class with a
  3482. // non-trivial destructor, there are no fields with a non-trivial
  3483. // destructor, and the body of the destructor is trivial.
  3484. if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
  3485. return;
  3486. llvm::Function *Fn = CGM.codegenCXXStructor(GD);
  3487. if (Fn->isWeakForLinker())
  3488. Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
  3489. }
  3490. llvm::Function *
  3491. MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
  3492. CXXCtorType CT) {
  3493. assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
  3494. // Calculate the mangled name.
  3495. SmallString<256> ThunkName;
  3496. llvm::raw_svector_ostream Out(ThunkName);
  3497. getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
  3498. // If the thunk has been generated previously, just return it.
  3499. if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
  3500. return cast<llvm::Function>(GV);
  3501. // Create the llvm::Function.
  3502. const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
  3503. llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
  3504. const CXXRecordDecl *RD = CD->getParent();
  3505. QualType RecordTy = getContext().getRecordType(RD);
  3506. llvm::Function *ThunkFn = llvm::Function::Create(
  3507. ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
  3508. ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
  3509. FnInfo.getEffectiveCallingConvention()));
  3510. if (ThunkFn->isWeakForLinker())
  3511. ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
  3512. bool IsCopy = CT == Ctor_CopyingClosure;
  3513. // Start codegen.
  3514. CodeGenFunction CGF(CGM);
  3515. CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
  3516. // Build FunctionArgs.
  3517. FunctionArgList FunctionArgs;
  3518. // A constructor always starts with a 'this' pointer as its first argument.
  3519. buildThisParam(CGF, FunctionArgs);
  3520. // Following the 'this' pointer is a reference to the source object that we
  3521. // are copying from.
  3522. ImplicitParamDecl SrcParam(
  3523. getContext(), /*DC=*/nullptr, SourceLocation(),
  3524. &getContext().Idents.get("src"),
  3525. getContext().getLValueReferenceType(RecordTy,
  3526. /*SpelledAsLValue=*/true),
  3527. ImplicitParamDecl::Other);
  3528. if (IsCopy)
  3529. FunctionArgs.push_back(&SrcParam);
  3530. // Constructors for classes which utilize virtual bases have an additional
  3531. // parameter which indicates whether or not it is being delegated to by a more
  3532. // derived constructor.
  3533. ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
  3534. SourceLocation(),
  3535. &getContext().Idents.get("is_most_derived"),
  3536. getContext().IntTy, ImplicitParamDecl::Other);
  3537. // Only add the parameter to the list if the class has virtual bases.
  3538. if (RD->getNumVBases() > 0)
  3539. FunctionArgs.push_back(&IsMostDerived);
  3540. // Start defining the function.
  3541. auto NL = ApplyDebugLocation::CreateEmpty(CGF);
  3542. CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
  3543. FunctionArgs, CD->getLocation(), SourceLocation());
  3544. // Create a scope with an artificial location for the body of this function.
  3545. auto AL = ApplyDebugLocation::CreateArtificial(CGF);
  3546. setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
  3547. llvm::Value *This = getThisValue(CGF);
  3548. llvm::Value *SrcVal =
  3549. IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
  3550. : nullptr;
  3551. CallArgList Args;
  3552. // Push the this ptr.
  3553. Args.add(RValue::get(This), CD->getThisType());
  3554. // Push the src ptr.
  3555. if (SrcVal)
  3556. Args.add(RValue::get(SrcVal), SrcParam.getType());
  3557. // Add the rest of the default arguments.
  3558. SmallVector<const Stmt *, 4> ArgVec;
  3559. ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
  3560. for (const ParmVarDecl *PD : params) {
  3561. assert(PD->hasDefaultArg() && "ctor closure lacks default args");
  3562. ArgVec.push_back(PD->getDefaultArg());
  3563. }
  3564. CodeGenFunction::RunCleanupsScope Cleanups(CGF);
  3565. const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
  3566. CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
  3567. // Insert any ABI-specific implicit constructor arguments.
  3568. AddedStructorArgCounts ExtraArgs =
  3569. addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
  3570. /*ForVirtualBase=*/false,
  3571. /*Delegating=*/false, Args);
  3572. // Call the destructor with our arguments.
  3573. llvm::Constant *CalleePtr =
  3574. CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
  3575. CGCallee Callee =
  3576. CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
  3577. const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
  3578. Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
  3579. CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
  3580. Cleanups.ForceCleanup();
  3581. // Emit the ret instruction, remove any temporary instructions created for the
  3582. // aid of CodeGen.
  3583. CGF.FinishFunction(SourceLocation());
  3584. return ThunkFn;
  3585. }
  3586. llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
  3587. uint32_t NVOffset,
  3588. int32_t VBPtrOffset,
  3589. uint32_t VBIndex) {
  3590. assert(!T->isReferenceType());
  3591. CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  3592. const CXXConstructorDecl *CD =
  3593. RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
  3594. CXXCtorType CT = Ctor_Complete;
  3595. if (CD)
  3596. if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
  3597. CT = Ctor_CopyingClosure;
  3598. uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
  3599. SmallString<256> MangledName;
  3600. {
  3601. llvm::raw_svector_ostream Out(MangledName);
  3602. getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
  3603. VBPtrOffset, VBIndex, Out);
  3604. }
  3605. if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
  3606. return getImageRelativeConstant(GV);
  3607. // The TypeDescriptor is used by the runtime to determine if a catch handler
  3608. // is appropriate for the exception object.
  3609. llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
  3610. // The runtime is responsible for calling the copy constructor if the
  3611. // exception is caught by value.
  3612. llvm::Constant *CopyCtor;
  3613. if (CD) {
  3614. if (CT == Ctor_CopyingClosure)
  3615. CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
  3616. else
  3617. CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
  3618. CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
  3619. } else {
  3620. CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
  3621. }
  3622. CopyCtor = getImageRelativeConstant(CopyCtor);
  3623. bool IsScalar = !RD;
  3624. bool HasVirtualBases = false;
  3625. bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
  3626. QualType PointeeType = T;
  3627. if (T->isPointerType())
  3628. PointeeType = T->getPointeeType();
  3629. if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
  3630. HasVirtualBases = RD->getNumVBases() > 0;
  3631. if (IdentifierInfo *II = RD->getIdentifier())
  3632. IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
  3633. }
  3634. // Encode the relevant CatchableType properties into the Flags bitfield.
  3635. // FIXME: Figure out how bits 2 or 8 can get set.
  3636. uint32_t Flags = 0;
  3637. if (IsScalar)
  3638. Flags |= 1;
  3639. if (HasVirtualBases)
  3640. Flags |= 4;
  3641. if (IsStdBadAlloc)
  3642. Flags |= 16;
  3643. llvm::Constant *Fields[] = {
  3644. llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
  3645. TD, // TypeDescriptor
  3646. llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
  3647. llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
  3648. llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
  3649. llvm::ConstantInt::get(CGM.IntTy, Size), // Size
  3650. CopyCtor // CopyCtor
  3651. };
  3652. llvm::StructType *CTType = getCatchableTypeType();
  3653. auto *GV = new llvm::GlobalVariable(
  3654. CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
  3655. llvm::ConstantStruct::get(CTType, Fields), MangledName);
  3656. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3657. GV->setSection(".xdata");
  3658. if (GV->isWeakForLinker())
  3659. GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
  3660. return getImageRelativeConstant(GV);
  3661. }
  3662. llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
  3663. assert(!T->isReferenceType());
  3664. // See if we've already generated a CatchableTypeArray for this type before.
  3665. llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
  3666. if (CTA)
  3667. return CTA;
  3668. // Ensure that we don't have duplicate entries in our CatchableTypeArray by
  3669. // using a SmallSetVector. Duplicates may arise due to virtual bases
  3670. // occurring more than once in the hierarchy.
  3671. llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
  3672. // C++14 [except.handle]p3:
  3673. // A handler is a match for an exception object of type E if [...]
  3674. // - the handler is of type cv T or cv T& and T is an unambiguous public
  3675. // base class of E, or
  3676. // - the handler is of type cv T or const T& where T is a pointer type and
  3677. // E is a pointer type that can be converted to T by [...]
  3678. // - a standard pointer conversion (4.10) not involving conversions to
  3679. // pointers to private or protected or ambiguous classes
  3680. const CXXRecordDecl *MostDerivedClass = nullptr;
  3681. bool IsPointer = T->isPointerType();
  3682. if (IsPointer)
  3683. MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
  3684. else
  3685. MostDerivedClass = T->getAsCXXRecordDecl();
  3686. // Collect all the unambiguous public bases of the MostDerivedClass.
  3687. if (MostDerivedClass) {
  3688. const ASTContext &Context = getContext();
  3689. const ASTRecordLayout &MostDerivedLayout =
  3690. Context.getASTRecordLayout(MostDerivedClass);
  3691. MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
  3692. SmallVector<MSRTTIClass, 8> Classes;
  3693. serializeClassHierarchy(Classes, MostDerivedClass);
  3694. Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
  3695. detectAmbiguousBases(Classes);
  3696. for (const MSRTTIClass &Class : Classes) {
  3697. // Skip any ambiguous or private bases.
  3698. if (Class.Flags &
  3699. (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
  3700. continue;
  3701. // Write down how to convert from a derived pointer to a base pointer.
  3702. uint32_t OffsetInVBTable = 0;
  3703. int32_t VBPtrOffset = -1;
  3704. if (Class.VirtualRoot) {
  3705. OffsetInVBTable =
  3706. VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
  3707. VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
  3708. }
  3709. // Turn our record back into a pointer if the exception object is a
  3710. // pointer.
  3711. QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
  3712. if (IsPointer)
  3713. RTTITy = Context.getPointerType(RTTITy);
  3714. CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
  3715. VBPtrOffset, OffsetInVBTable));
  3716. }
  3717. }
  3718. // C++14 [except.handle]p3:
  3719. // A handler is a match for an exception object of type E if
  3720. // - The handler is of type cv T or cv T& and E and T are the same type
  3721. // (ignoring the top-level cv-qualifiers)
  3722. CatchableTypes.insert(getCatchableType(T));
  3723. // C++14 [except.handle]p3:
  3724. // A handler is a match for an exception object of type E if
  3725. // - the handler is of type cv T or const T& where T is a pointer type and
  3726. // E is a pointer type that can be converted to T by [...]
  3727. // - a standard pointer conversion (4.10) not involving conversions to
  3728. // pointers to private or protected or ambiguous classes
  3729. //
  3730. // C++14 [conv.ptr]p2:
  3731. // A prvalue of type "pointer to cv T," where T is an object type, can be
  3732. // converted to a prvalue of type "pointer to cv void".
  3733. if (IsPointer && T->getPointeeType()->isObjectType())
  3734. CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
  3735. // C++14 [except.handle]p3:
  3736. // A handler is a match for an exception object of type E if [...]
  3737. // - the handler is of type cv T or const T& where T is a pointer or
  3738. // pointer to member type and E is std::nullptr_t.
  3739. //
  3740. // We cannot possibly list all possible pointer types here, making this
  3741. // implementation incompatible with the standard. However, MSVC includes an
  3742. // entry for pointer-to-void in this case. Let's do the same.
  3743. if (T->isNullPtrType())
  3744. CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
  3745. uint32_t NumEntries = CatchableTypes.size();
  3746. llvm::Type *CTType =
  3747. getImageRelativeType(getCatchableTypeType()->getPointerTo());
  3748. llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
  3749. llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
  3750. llvm::Constant *Fields[] = {
  3751. llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
  3752. llvm::ConstantArray::get(
  3753. AT, llvm::makeArrayRef(CatchableTypes.begin(),
  3754. CatchableTypes.end())) // CatchableTypes
  3755. };
  3756. SmallString<256> MangledName;
  3757. {
  3758. llvm::raw_svector_ostream Out(MangledName);
  3759. getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
  3760. }
  3761. CTA = new llvm::GlobalVariable(
  3762. CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
  3763. llvm::ConstantStruct::get(CTAType, Fields), MangledName);
  3764. CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3765. CTA->setSection(".xdata");
  3766. if (CTA->isWeakForLinker())
  3767. CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
  3768. return CTA;
  3769. }
  3770. llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
  3771. bool IsConst, IsVolatile, IsUnaligned;
  3772. T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
  3773. // The CatchableTypeArray enumerates the various (CV-unqualified) types that
  3774. // the exception object may be caught as.
  3775. llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
  3776. // The first field in a CatchableTypeArray is the number of CatchableTypes.
  3777. // This is used as a component of the mangled name which means that we need to
  3778. // know what it is in order to see if we have previously generated the
  3779. // ThrowInfo.
  3780. uint32_t NumEntries =
  3781. cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
  3782. ->getLimitedValue();
  3783. SmallString<256> MangledName;
  3784. {
  3785. llvm::raw_svector_ostream Out(MangledName);
  3786. getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
  3787. NumEntries, Out);
  3788. }
  3789. // Reuse a previously generated ThrowInfo if we have generated an appropriate
  3790. // one before.
  3791. if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
  3792. return GV;
  3793. // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
  3794. // be at least as CV qualified. Encode this requirement into the Flags
  3795. // bitfield.
  3796. uint32_t Flags = 0;
  3797. if (IsConst)
  3798. Flags |= 1;
  3799. if (IsVolatile)
  3800. Flags |= 2;
  3801. if (IsUnaligned)
  3802. Flags |= 4;
  3803. // The cleanup-function (a destructor) must be called when the exception
  3804. // object's lifetime ends.
  3805. llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
  3806. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  3807. if (CXXDestructorDecl *DtorD = RD->getDestructor())
  3808. if (!DtorD->isTrivial())
  3809. CleanupFn = llvm::ConstantExpr::getBitCast(
  3810. CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)),
  3811. CGM.Int8PtrTy);
  3812. // This is unused as far as we can tell, initialize it to null.
  3813. llvm::Constant *ForwardCompat =
  3814. getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
  3815. llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
  3816. llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
  3817. llvm::StructType *TIType = getThrowInfoType();
  3818. llvm::Constant *Fields[] = {
  3819. llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
  3820. getImageRelativeConstant(CleanupFn), // CleanupFn
  3821. ForwardCompat, // ForwardCompat
  3822. PointerToCatchableTypes // CatchableTypeArray
  3823. };
  3824. auto *GV = new llvm::GlobalVariable(
  3825. CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
  3826. llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
  3827. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3828. GV->setSection(".xdata");
  3829. if (GV->isWeakForLinker())
  3830. GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
  3831. return GV;
  3832. }
  3833. void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
  3834. const Expr *SubExpr = E->getSubExpr();
  3835. assert(SubExpr && "SubExpr cannot be null");
  3836. QualType ThrowType = SubExpr->getType();
  3837. // The exception object lives on the stack and it's address is passed to the
  3838. // runtime function.
  3839. Address AI = CGF.CreateMemTemp(ThrowType);
  3840. CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
  3841. /*IsInit=*/true);
  3842. // The so-called ThrowInfo is used to describe how the exception object may be
  3843. // caught.
  3844. llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
  3845. // Call into the runtime to throw the exception.
  3846. llvm::Value *Args[] = {
  3847. CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
  3848. TI
  3849. };
  3850. CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
  3851. }
  3852. std::pair<llvm::Value *, const CXXRecordDecl *>
  3853. MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
  3854. const CXXRecordDecl *RD) {
  3855. std::tie(This, std::ignore, RD) =
  3856. performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
  3857. return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
  3858. }
  3859. bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
  3860. const CXXRecordDecl *CXXRD) const {
  3861. // MSVC Windows on Arm64 considers a type not HFA if it is not an
  3862. // aggregate according to the C++14 spec. This is not consistent with the
  3863. // AAPCS64, but is defacto spec on that platform.
  3864. return !CGM.getTarget().getTriple().isAArch64() ||
  3865. isTrivialForAArch64MSVC(CXXRD);
  3866. }