ItaniumCXXABI.cpp 162 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239
  1. //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This provides C++ code generation targeting the Itanium C++ ABI. The class
  11. // in this file generates structures that follow the Itanium C++ ABI, which is
  12. // documented at:
  13. // http://www.codesourcery.com/public/cxx-abi/abi.html
  14. // http://www.codesourcery.com/public/cxx-abi/abi-eh.html
  15. //
  16. // It also supports the closely-related ARM ABI, documented at:
  17. // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #include "CGCXXABI.h"
  21. #include "CGCleanup.h"
  22. #include "CGRecordLayout.h"
  23. #include "CGVTables.h"
  24. #include "CodeGenFunction.h"
  25. #include "CodeGenModule.h"
  26. #include "TargetInfo.h"
  27. #include "clang/CodeGen/ConstantInitBuilder.h"
  28. #include "clang/AST/Mangle.h"
  29. #include "clang/AST/Type.h"
  30. #include "clang/AST/StmtCXX.h"
  31. #include "llvm/IR/CallSite.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/GlobalValue.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/Value.h"
  37. #include "llvm/Support/ScopedPrinter.h"
  38. using namespace clang;
  39. using namespace CodeGen;
  40. namespace {
  41. class ItaniumCXXABI : public CodeGen::CGCXXABI {
  42. /// VTables - All the vtables which have been defined.
  43. llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
  44. protected:
  45. bool UseARMMethodPtrABI;
  46. bool UseARMGuardVarABI;
  47. bool Use32BitVTableOffsetABI;
  48. ItaniumMangleContext &getMangleContext() {
  49. return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
  50. }
  51. public:
  52. ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
  53. bool UseARMMethodPtrABI = false,
  54. bool UseARMGuardVarABI = false) :
  55. CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
  56. UseARMGuardVarABI(UseARMGuardVarABI),
  57. Use32BitVTableOffsetABI(false) { }
  58. bool classifyReturnType(CGFunctionInfo &FI) const override;
  59. bool passClassIndirect(const CXXRecordDecl *RD) const {
  60. return !canCopyArgument(RD);
  61. }
  62. RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
  63. // If C++ prohibits us from making a copy, pass by address.
  64. if (passClassIndirect(RD))
  65. return RAA_Indirect;
  66. return RAA_Default;
  67. }
  68. bool isThisCompleteObject(GlobalDecl GD) const override {
  69. // The Itanium ABI has separate complete-object vs. base-object
  70. // variants of both constructors and destructors.
  71. if (isa<CXXDestructorDecl>(GD.getDecl())) {
  72. switch (GD.getDtorType()) {
  73. case Dtor_Complete:
  74. case Dtor_Deleting:
  75. return true;
  76. case Dtor_Base:
  77. return false;
  78. case Dtor_Comdat:
  79. llvm_unreachable("emitting dtor comdat as function?");
  80. }
  81. llvm_unreachable("bad dtor kind");
  82. }
  83. if (isa<CXXConstructorDecl>(GD.getDecl())) {
  84. switch (GD.getCtorType()) {
  85. case Ctor_Complete:
  86. return true;
  87. case Ctor_Base:
  88. return false;
  89. case Ctor_CopyingClosure:
  90. case Ctor_DefaultClosure:
  91. llvm_unreachable("closure ctors in Itanium ABI?");
  92. case Ctor_Comdat:
  93. llvm_unreachable("emitting ctor comdat as function?");
  94. }
  95. llvm_unreachable("bad dtor kind");
  96. }
  97. // No other kinds.
  98. return false;
  99. }
  100. bool isZeroInitializable(const MemberPointerType *MPT) override;
  101. llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
  102. CGCallee
  103. EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
  104. const Expr *E,
  105. Address This,
  106. llvm::Value *&ThisPtrForCall,
  107. llvm::Value *MemFnPtr,
  108. const MemberPointerType *MPT) override;
  109. llvm::Value *
  110. EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
  111. Address Base,
  112. llvm::Value *MemPtr,
  113. const MemberPointerType *MPT) override;
  114. llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
  115. const CastExpr *E,
  116. llvm::Value *Src) override;
  117. llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
  118. llvm::Constant *Src) override;
  119. llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
  120. llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
  121. llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
  122. CharUnits offset) override;
  123. llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
  124. llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
  125. CharUnits ThisAdjustment);
  126. llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
  127. llvm::Value *L, llvm::Value *R,
  128. const MemberPointerType *MPT,
  129. bool Inequality) override;
  130. llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  131. llvm::Value *Addr,
  132. const MemberPointerType *MPT) override;
  133. void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
  134. Address Ptr, QualType ElementType,
  135. const CXXDestructorDecl *Dtor) override;
  136. /// Itanium says that an _Unwind_Exception has to be "double-word"
  137. /// aligned (and thus the end of it is also so-aligned), meaning 16
  138. /// bytes. Of course, that was written for the actual Itanium,
  139. /// which is a 64-bit platform. Classically, the ABI doesn't really
  140. /// specify the alignment on other platforms, but in practice
  141. /// libUnwind declares the struct with __attribute__((aligned)), so
  142. /// we assume that alignment here. (It's generally 16 bytes, but
  143. /// some targets overwrite it.)
  144. CharUnits getAlignmentOfExnObject() {
  145. auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned();
  146. return CGM.getContext().toCharUnitsFromBits(align);
  147. }
  148. void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
  149. void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
  150. void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
  151. llvm::CallInst *
  152. emitTerminateForUnexpectedException(CodeGenFunction &CGF,
  153. llvm::Value *Exn) override;
  154. void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD);
  155. llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
  156. CatchTypeInfo
  157. getAddrOfCXXCatchHandlerType(QualType Ty,
  158. QualType CatchHandlerType) override {
  159. return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
  160. }
  161. bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
  162. void EmitBadTypeidCall(CodeGenFunction &CGF) override;
  163. llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
  164. Address ThisPtr,
  165. llvm::Type *StdTypeInfoPtrTy) override;
  166. bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
  167. QualType SrcRecordTy) override;
  168. llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
  169. QualType SrcRecordTy, QualType DestTy,
  170. QualType DestRecordTy,
  171. llvm::BasicBlock *CastEnd) override;
  172. llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
  173. QualType SrcRecordTy,
  174. QualType DestTy) override;
  175. bool EmitBadCastCall(CodeGenFunction &CGF) override;
  176. llvm::Value *
  177. GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
  178. const CXXRecordDecl *ClassDecl,
  179. const CXXRecordDecl *BaseClassDecl) override;
  180. void EmitCXXConstructors(const CXXConstructorDecl *D) override;
  181. AddedStructorArgs
  182. buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
  183. SmallVectorImpl<CanQualType> &ArgTys) override;
  184. bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
  185. CXXDtorType DT) const override {
  186. // Itanium does not emit any destructor variant as an inline thunk.
  187. // Delegating may occur as an optimization, but all variants are either
  188. // emitted with external linkage or as linkonce if they are inline and used.
  189. return false;
  190. }
  191. void EmitCXXDestructors(const CXXDestructorDecl *D) override;
  192. void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
  193. FunctionArgList &Params) override;
  194. void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
  195. AddedStructorArgs
  196. addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
  197. CXXCtorType Type, bool ForVirtualBase,
  198. bool Delegating, CallArgList &Args) override;
  199. void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
  200. CXXDtorType Type, bool ForVirtualBase,
  201. bool Delegating, Address This) override;
  202. void emitVTableDefinitions(CodeGenVTables &CGVT,
  203. const CXXRecordDecl *RD) override;
  204. bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
  205. CodeGenFunction::VPtr Vptr) override;
  206. bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
  207. return true;
  208. }
  209. llvm::Constant *
  210. getVTableAddressPoint(BaseSubobject Base,
  211. const CXXRecordDecl *VTableClass) override;
  212. llvm::Value *getVTableAddressPointInStructor(
  213. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
  214. BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
  215. llvm::Value *getVTableAddressPointInStructorWithVTT(
  216. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
  217. BaseSubobject Base, const CXXRecordDecl *NearestVBase);
  218. llvm::Constant *
  219. getVTableAddressPointForConstExpr(BaseSubobject Base,
  220. const CXXRecordDecl *VTableClass) override;
  221. llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
  222. CharUnits VPtrOffset) override;
  223. CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
  224. Address This, llvm::Type *Ty,
  225. SourceLocation Loc) override;
  226. llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
  227. const CXXDestructorDecl *Dtor,
  228. CXXDtorType DtorType,
  229. Address This,
  230. const CXXMemberCallExpr *CE) override;
  231. void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
  232. bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
  233. void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
  234. bool ReturnAdjustment) override {
  235. // Allow inlining of thunks by emitting them with available_externally
  236. // linkage together with vtables when needed.
  237. if (ForVTable && !Thunk->hasLocalLinkage())
  238. Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  239. CGM.setGVProperties(Thunk, GD);
  240. }
  241. bool exportThunk() override { return true; }
  242. llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
  243. const ThisAdjustment &TA) override;
  244. llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
  245. const ReturnAdjustment &RA) override;
  246. size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
  247. FunctionArgList &Args) const override {
  248. assert(!Args.empty() && "expected the arglist to not be empty!");
  249. return Args.size() - 1;
  250. }
  251. StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
  252. StringRef GetDeletedVirtualCallName() override
  253. { return "__cxa_deleted_virtual"; }
  254. CharUnits getArrayCookieSizeImpl(QualType elementType) override;
  255. Address InitializeArrayCookie(CodeGenFunction &CGF,
  256. Address NewPtr,
  257. llvm::Value *NumElements,
  258. const CXXNewExpr *expr,
  259. QualType ElementType) override;
  260. llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
  261. Address allocPtr,
  262. CharUnits cookieSize) override;
  263. void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
  264. llvm::GlobalVariable *DeclPtr,
  265. bool PerformInit) override;
  266. void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
  267. llvm::Constant *dtor, llvm::Constant *addr) override;
  268. llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
  269. llvm::Value *Val);
  270. void EmitThreadLocalInitFuncs(
  271. CodeGenModule &CGM,
  272. ArrayRef<const VarDecl *> CXXThreadLocals,
  273. ArrayRef<llvm::Function *> CXXThreadLocalInits,
  274. ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
  275. bool usesThreadWrapperFunction() const override { return true; }
  276. LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
  277. QualType LValType) override;
  278. bool NeedsVTTParameter(GlobalDecl GD) override;
  279. /**************************** RTTI Uniqueness ******************************/
  280. protected:
  281. /// Returns true if the ABI requires RTTI type_info objects to be unique
  282. /// across a program.
  283. virtual bool shouldRTTIBeUnique() const { return true; }
  284. public:
  285. /// What sort of unique-RTTI behavior should we use?
  286. enum RTTIUniquenessKind {
  287. /// We are guaranteeing, or need to guarantee, that the RTTI string
  288. /// is unique.
  289. RUK_Unique,
  290. /// We are not guaranteeing uniqueness for the RTTI string, so we
  291. /// can demote to hidden visibility but must use string comparisons.
  292. RUK_NonUniqueHidden,
  293. /// We are not guaranteeing uniqueness for the RTTI string, so we
  294. /// have to use string comparisons, but we also have to emit it with
  295. /// non-hidden visibility.
  296. RUK_NonUniqueVisible
  297. };
  298. /// Return the required visibility status for the given type and linkage in
  299. /// the current ABI.
  300. RTTIUniquenessKind
  301. classifyRTTIUniqueness(QualType CanTy,
  302. llvm::GlobalValue::LinkageTypes Linkage) const;
  303. friend class ItaniumRTTIBuilder;
  304. void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
  305. std::pair<llvm::Value *, const CXXRecordDecl *>
  306. LoadVTablePtr(CodeGenFunction &CGF, Address This,
  307. const CXXRecordDecl *RD) override;
  308. private:
  309. bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
  310. const auto &VtableLayout =
  311. CGM.getItaniumVTableContext().getVTableLayout(RD);
  312. for (const auto &VtableComponent : VtableLayout.vtable_components()) {
  313. // Skip empty slot.
  314. if (!VtableComponent.isUsedFunctionPointerKind())
  315. continue;
  316. const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
  317. if (!Method->getCanonicalDecl()->isInlined())
  318. continue;
  319. StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
  320. auto *Entry = CGM.GetGlobalValue(Name);
  321. // This checks if virtual inline function has already been emitted.
  322. // Note that it is possible that this inline function would be emitted
  323. // after trying to emit vtable speculatively. Because of this we do
  324. // an extra pass after emitting all deferred vtables to find and emit
  325. // these vtables opportunistically.
  326. if (!Entry || Entry->isDeclaration())
  327. return true;
  328. }
  329. return false;
  330. }
  331. bool isVTableHidden(const CXXRecordDecl *RD) const {
  332. const auto &VtableLayout =
  333. CGM.getItaniumVTableContext().getVTableLayout(RD);
  334. for (const auto &VtableComponent : VtableLayout.vtable_components()) {
  335. if (VtableComponent.isRTTIKind()) {
  336. const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
  337. if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
  338. return true;
  339. } else if (VtableComponent.isUsedFunctionPointerKind()) {
  340. const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
  341. if (Method->getVisibility() == Visibility::HiddenVisibility &&
  342. !Method->isDefined())
  343. return true;
  344. }
  345. }
  346. return false;
  347. }
  348. };
  349. class ARMCXXABI : public ItaniumCXXABI {
  350. public:
  351. ARMCXXABI(CodeGen::CodeGenModule &CGM) :
  352. ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
  353. /* UseARMGuardVarABI = */ true) {}
  354. bool HasThisReturn(GlobalDecl GD) const override {
  355. return (isa<CXXConstructorDecl>(GD.getDecl()) || (
  356. isa<CXXDestructorDecl>(GD.getDecl()) &&
  357. GD.getDtorType() != Dtor_Deleting));
  358. }
  359. void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
  360. QualType ResTy) override;
  361. CharUnits getArrayCookieSizeImpl(QualType elementType) override;
  362. Address InitializeArrayCookie(CodeGenFunction &CGF,
  363. Address NewPtr,
  364. llvm::Value *NumElements,
  365. const CXXNewExpr *expr,
  366. QualType ElementType) override;
  367. llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
  368. CharUnits cookieSize) override;
  369. };
  370. class iOS64CXXABI : public ARMCXXABI {
  371. public:
  372. iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
  373. Use32BitVTableOffsetABI = true;
  374. }
  375. // ARM64 libraries are prepared for non-unique RTTI.
  376. bool shouldRTTIBeUnique() const override { return false; }
  377. };
  378. class WebAssemblyCXXABI final : public ItaniumCXXABI {
  379. public:
  380. explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
  381. : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
  382. /*UseARMGuardVarABI=*/true) {}
  383. void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
  384. private:
  385. bool HasThisReturn(GlobalDecl GD) const override {
  386. return isa<CXXConstructorDecl>(GD.getDecl()) ||
  387. (isa<CXXDestructorDecl>(GD.getDecl()) &&
  388. GD.getDtorType() != Dtor_Deleting);
  389. }
  390. bool canCallMismatchedFunctionType() const override { return false; }
  391. };
  392. }
  393. CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
  394. switch (CGM.getTarget().getCXXABI().getKind()) {
  395. // For IR-generation purposes, there's no significant difference
  396. // between the ARM and iOS ABIs.
  397. case TargetCXXABI::GenericARM:
  398. case TargetCXXABI::iOS:
  399. case TargetCXXABI::WatchOS:
  400. return new ARMCXXABI(CGM);
  401. case TargetCXXABI::iOS64:
  402. return new iOS64CXXABI(CGM);
  403. // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
  404. // include the other 32-bit ARM oddities: constructor/destructor return values
  405. // and array cookies.
  406. case TargetCXXABI::GenericAArch64:
  407. return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
  408. /* UseARMGuardVarABI = */ true);
  409. case TargetCXXABI::GenericMIPS:
  410. return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
  411. case TargetCXXABI::WebAssembly:
  412. return new WebAssemblyCXXABI(CGM);
  413. case TargetCXXABI::GenericItanium:
  414. if (CGM.getContext().getTargetInfo().getTriple().getArch()
  415. == llvm::Triple::le32) {
  416. // For PNaCl, use ARM-style method pointers so that PNaCl code
  417. // does not assume anything about the alignment of function
  418. // pointers.
  419. return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
  420. /* UseARMGuardVarABI = */ false);
  421. }
  422. return new ItaniumCXXABI(CGM);
  423. case TargetCXXABI::Microsoft:
  424. llvm_unreachable("Microsoft ABI is not Itanium-based");
  425. }
  426. llvm_unreachable("bad ABI kind");
  427. }
  428. llvm::Type *
  429. ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
  430. if (MPT->isMemberDataPointer())
  431. return CGM.PtrDiffTy;
  432. return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
  433. }
  434. /// In the Itanium and ARM ABIs, method pointers have the form:
  435. /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
  436. ///
  437. /// In the Itanium ABI:
  438. /// - method pointers are virtual if (memptr.ptr & 1) is nonzero
  439. /// - the this-adjustment is (memptr.adj)
  440. /// - the virtual offset is (memptr.ptr - 1)
  441. ///
  442. /// In the ARM ABI:
  443. /// - method pointers are virtual if (memptr.adj & 1) is nonzero
  444. /// - the this-adjustment is (memptr.adj >> 1)
  445. /// - the virtual offset is (memptr.ptr)
  446. /// ARM uses 'adj' for the virtual flag because Thumb functions
  447. /// may be only single-byte aligned.
  448. ///
  449. /// If the member is virtual, the adjusted 'this' pointer points
  450. /// to a vtable pointer from which the virtual offset is applied.
  451. ///
  452. /// If the member is non-virtual, memptr.ptr is the address of
  453. /// the function to call.
  454. CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
  455. CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
  456. llvm::Value *&ThisPtrForCall,
  457. llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
  458. CGBuilderTy &Builder = CGF.Builder;
  459. const FunctionProtoType *FPT =
  460. MPT->getPointeeType()->getAs<FunctionProtoType>();
  461. const CXXRecordDecl *RD =
  462. cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
  463. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
  464. CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
  465. llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
  466. llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
  467. llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
  468. llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
  469. // Extract memptr.adj, which is in the second field.
  470. llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
  471. // Compute the true adjustment.
  472. llvm::Value *Adj = RawAdj;
  473. if (UseARMMethodPtrABI)
  474. Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
  475. // Apply the adjustment and cast back to the original struct type
  476. // for consistency.
  477. llvm::Value *This = ThisAddr.getPointer();
  478. llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
  479. Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
  480. This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
  481. ThisPtrForCall = This;
  482. // Load the function pointer.
  483. llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
  484. // If the LSB in the function pointer is 1, the function pointer points to
  485. // a virtual function.
  486. llvm::Value *IsVirtual;
  487. if (UseARMMethodPtrABI)
  488. IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
  489. else
  490. IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
  491. IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
  492. Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
  493. // In the virtual path, the adjustment left 'This' pointing to the
  494. // vtable of the correct base subobject. The "function pointer" is an
  495. // offset within the vtable (+1 for the virtual flag on non-ARM).
  496. CGF.EmitBlock(FnVirtual);
  497. // Cast the adjusted this to a pointer to vtable pointer and load.
  498. llvm::Type *VTableTy = Builder.getInt8PtrTy();
  499. CharUnits VTablePtrAlign =
  500. CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
  501. CGF.getPointerAlign());
  502. llvm::Value *VTable =
  503. CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
  504. // Apply the offset.
  505. // On ARM64, to reserve extra space in virtual member function pointers,
  506. // we only pay attention to the low 32 bits of the offset.
  507. llvm::Value *VTableOffset = FnAsInt;
  508. if (!UseARMMethodPtrABI)
  509. VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
  510. if (Use32BitVTableOffsetABI) {
  511. VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
  512. VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
  513. }
  514. // Compute the address of the virtual function pointer.
  515. llvm::Value *VFPAddr = Builder.CreateGEP(VTable, VTableOffset);
  516. // Check the address of the function pointer if CFI on member function
  517. // pointers is enabled.
  518. llvm::Constant *CheckSourceLocation;
  519. llvm::Constant *CheckTypeDesc;
  520. bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) &&
  521. CGM.HasHiddenLTOVisibility(RD);
  522. if (ShouldEmitCFICheck) {
  523. CodeGenFunction::SanitizerScope SanScope(&CGF);
  524. CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc());
  525. CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0));
  526. llvm::Constant *StaticData[] = {
  527. llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall),
  528. CheckSourceLocation,
  529. CheckTypeDesc,
  530. };
  531. llvm::Metadata *MD =
  532. CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0));
  533. llvm::Value *TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
  534. llvm::Value *TypeTest = Builder.CreateCall(
  535. CGM.getIntrinsic(llvm::Intrinsic::type_test), {VFPAddr, TypeId});
  536. if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) {
  537. CGF.EmitTrapCheck(TypeTest);
  538. } else {
  539. llvm::Value *AllVtables = llvm::MetadataAsValue::get(
  540. CGM.getLLVMContext(),
  541. llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
  542. llvm::Value *ValidVtable = Builder.CreateCall(
  543. CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
  544. CGF.EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIMFCall),
  545. SanitizerHandler::CFICheckFail, StaticData,
  546. {VTable, ValidVtable});
  547. }
  548. FnVirtual = Builder.GetInsertBlock();
  549. }
  550. // Load the virtual function to call.
  551. VFPAddr = Builder.CreateBitCast(VFPAddr, FTy->getPointerTo()->getPointerTo());
  552. llvm::Value *VirtualFn = Builder.CreateAlignedLoad(
  553. VFPAddr, CGF.getPointerAlign(), "memptr.virtualfn");
  554. CGF.EmitBranch(FnEnd);
  555. // In the non-virtual path, the function pointer is actually a
  556. // function pointer.
  557. CGF.EmitBlock(FnNonVirtual);
  558. llvm::Value *NonVirtualFn =
  559. Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
  560. // Check the function pointer if CFI on member function pointers is enabled.
  561. if (ShouldEmitCFICheck) {
  562. CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
  563. if (RD->hasDefinition()) {
  564. CodeGenFunction::SanitizerScope SanScope(&CGF);
  565. llvm::Constant *StaticData[] = {
  566. llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall),
  567. CheckSourceLocation,
  568. CheckTypeDesc,
  569. };
  570. llvm::Value *Bit = Builder.getFalse();
  571. llvm::Value *CastedNonVirtualFn =
  572. Builder.CreateBitCast(NonVirtualFn, CGF.Int8PtrTy);
  573. for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) {
  574. llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
  575. getContext().getMemberPointerType(
  576. MPT->getPointeeType(),
  577. getContext().getRecordType(Base).getTypePtr()));
  578. llvm::Value *TypeId =
  579. llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
  580. llvm::Value *TypeTest =
  581. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
  582. {CastedNonVirtualFn, TypeId});
  583. Bit = Builder.CreateOr(Bit, TypeTest);
  584. }
  585. CGF.EmitCheck(std::make_pair(Bit, SanitizerKind::CFIMFCall),
  586. SanitizerHandler::CFICheckFail, StaticData,
  587. {CastedNonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)});
  588. FnNonVirtual = Builder.GetInsertBlock();
  589. }
  590. }
  591. // We're done.
  592. CGF.EmitBlock(FnEnd);
  593. llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
  594. CalleePtr->addIncoming(VirtualFn, FnVirtual);
  595. CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
  596. CGCallee Callee(FPT, CalleePtr);
  597. return Callee;
  598. }
  599. /// Compute an l-value by applying the given pointer-to-member to a
  600. /// base object.
  601. llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
  602. CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
  603. const MemberPointerType *MPT) {
  604. assert(MemPtr->getType() == CGM.PtrDiffTy);
  605. CGBuilderTy &Builder = CGF.Builder;
  606. // Cast to char*.
  607. Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
  608. // Apply the offset, which we assume is non-null.
  609. llvm::Value *Addr =
  610. Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
  611. // Cast the address to the appropriate pointer type, adopting the
  612. // address space of the base pointer.
  613. llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
  614. ->getPointerTo(Base.getAddressSpace());
  615. return Builder.CreateBitCast(Addr, PType);
  616. }
  617. /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
  618. /// conversion.
  619. ///
  620. /// Bitcast conversions are always a no-op under Itanium.
  621. ///
  622. /// Obligatory offset/adjustment diagram:
  623. /// <-- offset --> <-- adjustment -->
  624. /// |--------------------------|----------------------|--------------------|
  625. /// ^Derived address point ^Base address point ^Member address point
  626. ///
  627. /// So when converting a base member pointer to a derived member pointer,
  628. /// we add the offset to the adjustment because the address point has
  629. /// decreased; and conversely, when converting a derived MP to a base MP
  630. /// we subtract the offset from the adjustment because the address point
  631. /// has increased.
  632. ///
  633. /// The standard forbids (at compile time) conversion to and from
  634. /// virtual bases, which is why we don't have to consider them here.
  635. ///
  636. /// The standard forbids (at run time) casting a derived MP to a base
  637. /// MP when the derived MP does not point to a member of the base.
  638. /// This is why -1 is a reasonable choice for null data member
  639. /// pointers.
  640. llvm::Value *
  641. ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
  642. const CastExpr *E,
  643. llvm::Value *src) {
  644. assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
  645. E->getCastKind() == CK_BaseToDerivedMemberPointer ||
  646. E->getCastKind() == CK_ReinterpretMemberPointer);
  647. // Under Itanium, reinterprets don't require any additional processing.
  648. if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
  649. // Use constant emission if we can.
  650. if (isa<llvm::Constant>(src))
  651. return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
  652. llvm::Constant *adj = getMemberPointerAdjustment(E);
  653. if (!adj) return src;
  654. CGBuilderTy &Builder = CGF.Builder;
  655. bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
  656. const MemberPointerType *destTy =
  657. E->getType()->castAs<MemberPointerType>();
  658. // For member data pointers, this is just a matter of adding the
  659. // offset if the source is non-null.
  660. if (destTy->isMemberDataPointer()) {
  661. llvm::Value *dst;
  662. if (isDerivedToBase)
  663. dst = Builder.CreateNSWSub(src, adj, "adj");
  664. else
  665. dst = Builder.CreateNSWAdd(src, adj, "adj");
  666. // Null check.
  667. llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
  668. llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
  669. return Builder.CreateSelect(isNull, src, dst);
  670. }
  671. // The this-adjustment is left-shifted by 1 on ARM.
  672. if (UseARMMethodPtrABI) {
  673. uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
  674. offset <<= 1;
  675. adj = llvm::ConstantInt::get(adj->getType(), offset);
  676. }
  677. llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
  678. llvm::Value *dstAdj;
  679. if (isDerivedToBase)
  680. dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
  681. else
  682. dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
  683. return Builder.CreateInsertValue(src, dstAdj, 1);
  684. }
  685. llvm::Constant *
  686. ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
  687. llvm::Constant *src) {
  688. assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
  689. E->getCastKind() == CK_BaseToDerivedMemberPointer ||
  690. E->getCastKind() == CK_ReinterpretMemberPointer);
  691. // Under Itanium, reinterprets don't require any additional processing.
  692. if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
  693. // If the adjustment is trivial, we don't need to do anything.
  694. llvm::Constant *adj = getMemberPointerAdjustment(E);
  695. if (!adj) return src;
  696. bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
  697. const MemberPointerType *destTy =
  698. E->getType()->castAs<MemberPointerType>();
  699. // For member data pointers, this is just a matter of adding the
  700. // offset if the source is non-null.
  701. if (destTy->isMemberDataPointer()) {
  702. // null maps to null.
  703. if (src->isAllOnesValue()) return src;
  704. if (isDerivedToBase)
  705. return llvm::ConstantExpr::getNSWSub(src, adj);
  706. else
  707. return llvm::ConstantExpr::getNSWAdd(src, adj);
  708. }
  709. // The this-adjustment is left-shifted by 1 on ARM.
  710. if (UseARMMethodPtrABI) {
  711. uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
  712. offset <<= 1;
  713. adj = llvm::ConstantInt::get(adj->getType(), offset);
  714. }
  715. llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
  716. llvm::Constant *dstAdj;
  717. if (isDerivedToBase)
  718. dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
  719. else
  720. dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
  721. return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
  722. }
  723. llvm::Constant *
  724. ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
  725. // Itanium C++ ABI 2.3:
  726. // A NULL pointer is represented as -1.
  727. if (MPT->isMemberDataPointer())
  728. return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
  729. llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
  730. llvm::Constant *Values[2] = { Zero, Zero };
  731. return llvm::ConstantStruct::getAnon(Values);
  732. }
  733. llvm::Constant *
  734. ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
  735. CharUnits offset) {
  736. // Itanium C++ ABI 2.3:
  737. // A pointer to data member is an offset from the base address of
  738. // the class object containing it, represented as a ptrdiff_t
  739. return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
  740. }
  741. llvm::Constant *
  742. ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
  743. return BuildMemberPointer(MD, CharUnits::Zero());
  744. }
  745. llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
  746. CharUnits ThisAdjustment) {
  747. assert(MD->isInstance() && "Member function must not be static!");
  748. CodeGenTypes &Types = CGM.getTypes();
  749. // Get the function pointer (or index if this is a virtual function).
  750. llvm::Constant *MemPtr[2];
  751. if (MD->isVirtual()) {
  752. uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
  753. const ASTContext &Context = getContext();
  754. CharUnits PointerWidth =
  755. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  756. uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
  757. if (UseARMMethodPtrABI) {
  758. // ARM C++ ABI 3.2.1:
  759. // This ABI specifies that adj contains twice the this
  760. // adjustment, plus 1 if the member function is virtual. The
  761. // least significant bit of adj then makes exactly the same
  762. // discrimination as the least significant bit of ptr does for
  763. // Itanium.
  764. MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
  765. MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
  766. 2 * ThisAdjustment.getQuantity() + 1);
  767. } else {
  768. // Itanium C++ ABI 2.3:
  769. // For a virtual function, [the pointer field] is 1 plus the
  770. // virtual table offset (in bytes) of the function,
  771. // represented as a ptrdiff_t.
  772. MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
  773. MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
  774. ThisAdjustment.getQuantity());
  775. }
  776. } else {
  777. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  778. llvm::Type *Ty;
  779. // Check whether the function has a computable LLVM signature.
  780. if (Types.isFuncTypeConvertible(FPT)) {
  781. // The function has a computable LLVM signature; use the correct type.
  782. Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
  783. } else {
  784. // Use an arbitrary non-function type to tell GetAddrOfFunction that the
  785. // function type is incomplete.
  786. Ty = CGM.PtrDiffTy;
  787. }
  788. llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
  789. MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
  790. MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
  791. (UseARMMethodPtrABI ? 2 : 1) *
  792. ThisAdjustment.getQuantity());
  793. }
  794. return llvm::ConstantStruct::getAnon(MemPtr);
  795. }
  796. llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
  797. QualType MPType) {
  798. const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
  799. const ValueDecl *MPD = MP.getMemberPointerDecl();
  800. if (!MPD)
  801. return EmitNullMemberPointer(MPT);
  802. CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
  803. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
  804. return BuildMemberPointer(MD, ThisAdjustment);
  805. CharUnits FieldOffset =
  806. getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
  807. return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
  808. }
  809. /// The comparison algorithm is pretty easy: the member pointers are
  810. /// the same if they're either bitwise identical *or* both null.
  811. ///
  812. /// ARM is different here only because null-ness is more complicated.
  813. llvm::Value *
  814. ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
  815. llvm::Value *L,
  816. llvm::Value *R,
  817. const MemberPointerType *MPT,
  818. bool Inequality) {
  819. CGBuilderTy &Builder = CGF.Builder;
  820. llvm::ICmpInst::Predicate Eq;
  821. llvm::Instruction::BinaryOps And, Or;
  822. if (Inequality) {
  823. Eq = llvm::ICmpInst::ICMP_NE;
  824. And = llvm::Instruction::Or;
  825. Or = llvm::Instruction::And;
  826. } else {
  827. Eq = llvm::ICmpInst::ICMP_EQ;
  828. And = llvm::Instruction::And;
  829. Or = llvm::Instruction::Or;
  830. }
  831. // Member data pointers are easy because there's a unique null
  832. // value, so it just comes down to bitwise equality.
  833. if (MPT->isMemberDataPointer())
  834. return Builder.CreateICmp(Eq, L, R);
  835. // For member function pointers, the tautologies are more complex.
  836. // The Itanium tautology is:
  837. // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
  838. // The ARM tautology is:
  839. // (L == R) <==> (L.ptr == R.ptr &&
  840. // (L.adj == R.adj ||
  841. // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
  842. // The inequality tautologies have exactly the same structure, except
  843. // applying De Morgan's laws.
  844. llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
  845. llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
  846. // This condition tests whether L.ptr == R.ptr. This must always be
  847. // true for equality to hold.
  848. llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
  849. // This condition, together with the assumption that L.ptr == R.ptr,
  850. // tests whether the pointers are both null. ARM imposes an extra
  851. // condition.
  852. llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
  853. llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
  854. // This condition tests whether L.adj == R.adj. If this isn't
  855. // true, the pointers are unequal unless they're both null.
  856. llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
  857. llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
  858. llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
  859. // Null member function pointers on ARM clear the low bit of Adj,
  860. // so the zero condition has to check that neither low bit is set.
  861. if (UseARMMethodPtrABI) {
  862. llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
  863. // Compute (l.adj | r.adj) & 1 and test it against zero.
  864. llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
  865. llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
  866. llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
  867. "cmp.or.adj");
  868. EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
  869. }
  870. // Tie together all our conditions.
  871. llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
  872. Result = Builder.CreateBinOp(And, PtrEq, Result,
  873. Inequality ? "memptr.ne" : "memptr.eq");
  874. return Result;
  875. }
  876. llvm::Value *
  877. ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  878. llvm::Value *MemPtr,
  879. const MemberPointerType *MPT) {
  880. CGBuilderTy &Builder = CGF.Builder;
  881. /// For member data pointers, this is just a check against -1.
  882. if (MPT->isMemberDataPointer()) {
  883. assert(MemPtr->getType() == CGM.PtrDiffTy);
  884. llvm::Value *NegativeOne =
  885. llvm::Constant::getAllOnesValue(MemPtr->getType());
  886. return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
  887. }
  888. // In Itanium, a member function pointer is not null if 'ptr' is not null.
  889. llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
  890. llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
  891. llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
  892. // On ARM, a member function pointer is also non-null if the low bit of 'adj'
  893. // (the virtual bit) is set.
  894. if (UseARMMethodPtrABI) {
  895. llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
  896. llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
  897. llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
  898. llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
  899. "memptr.isvirtual");
  900. Result = Builder.CreateOr(Result, IsVirtual);
  901. }
  902. return Result;
  903. }
  904. bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
  905. const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
  906. if (!RD)
  907. return false;
  908. // If C++ prohibits us from making a copy, return by address.
  909. if (passClassIndirect(RD)) {
  910. auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
  911. FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
  912. return true;
  913. }
  914. return false;
  915. }
  916. /// The Itanium ABI requires non-zero initialization only for data
  917. /// member pointers, for which '0' is a valid offset.
  918. bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
  919. return MPT->isMemberFunctionPointer();
  920. }
  921. /// The Itanium ABI always places an offset to the complete object
  922. /// at entry -2 in the vtable.
  923. void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
  924. const CXXDeleteExpr *DE,
  925. Address Ptr,
  926. QualType ElementType,
  927. const CXXDestructorDecl *Dtor) {
  928. bool UseGlobalDelete = DE->isGlobalDelete();
  929. if (UseGlobalDelete) {
  930. // Derive the complete-object pointer, which is what we need
  931. // to pass to the deallocation function.
  932. // Grab the vtable pointer as an intptr_t*.
  933. auto *ClassDecl =
  934. cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
  935. llvm::Value *VTable =
  936. CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
  937. // Track back to entry -2 and pull out the offset there.
  938. llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
  939. VTable, -2, "complete-offset.ptr");
  940. llvm::Value *Offset =
  941. CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
  942. // Apply the offset.
  943. llvm::Value *CompletePtr =
  944. CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
  945. CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
  946. // If we're supposed to call the global delete, make sure we do so
  947. // even if the destructor throws.
  948. CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
  949. ElementType);
  950. }
  951. // FIXME: Provide a source location here even though there's no
  952. // CXXMemberCallExpr for dtor call.
  953. CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
  954. EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
  955. if (UseGlobalDelete)
  956. CGF.PopCleanupBlock();
  957. }
  958. void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
  959. // void __cxa_rethrow();
  960. llvm::FunctionType *FTy =
  961. llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
  962. llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
  963. if (isNoReturn)
  964. CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
  965. else
  966. CGF.EmitRuntimeCallOrInvoke(Fn);
  967. }
  968. static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
  969. // void *__cxa_allocate_exception(size_t thrown_size);
  970. llvm::FunctionType *FTy =
  971. llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
  972. return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
  973. }
  974. static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
  975. // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
  976. // void (*dest) (void *));
  977. llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
  978. llvm::FunctionType *FTy =
  979. llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
  980. return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
  981. }
  982. void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
  983. QualType ThrowType = E->getSubExpr()->getType();
  984. // Now allocate the exception object.
  985. llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
  986. uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
  987. llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
  988. llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
  989. AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
  990. CharUnits ExnAlign = getAlignmentOfExnObject();
  991. CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
  992. // Now throw the exception.
  993. llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
  994. /*ForEH=*/true);
  995. // The address of the destructor. If the exception type has a
  996. // trivial destructor (or isn't a record), we just pass null.
  997. llvm::Constant *Dtor = nullptr;
  998. if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
  999. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
  1000. if (!Record->hasTrivialDestructor()) {
  1001. CXXDestructorDecl *DtorD = Record->getDestructor();
  1002. Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
  1003. Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
  1004. }
  1005. }
  1006. if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
  1007. llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
  1008. CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
  1009. }
  1010. static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
  1011. // void *__dynamic_cast(const void *sub,
  1012. // const abi::__class_type_info *src,
  1013. // const abi::__class_type_info *dst,
  1014. // std::ptrdiff_t src2dst_offset);
  1015. llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
  1016. llvm::Type *PtrDiffTy =
  1017. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  1018. llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
  1019. llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
  1020. // Mark the function as nounwind readonly.
  1021. llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
  1022. llvm::Attribute::ReadOnly };
  1023. llvm::AttributeList Attrs = llvm::AttributeList::get(
  1024. CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
  1025. return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
  1026. }
  1027. static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
  1028. // void __cxa_bad_cast();
  1029. llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
  1030. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
  1031. }
  1032. /// Compute the src2dst_offset hint as described in the
  1033. /// Itanium C++ ABI [2.9.7]
  1034. static CharUnits computeOffsetHint(ASTContext &Context,
  1035. const CXXRecordDecl *Src,
  1036. const CXXRecordDecl *Dst) {
  1037. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1038. /*DetectVirtual=*/false);
  1039. // If Dst is not derived from Src we can skip the whole computation below and
  1040. // return that Src is not a public base of Dst. Record all inheritance paths.
  1041. if (!Dst->isDerivedFrom(Src, Paths))
  1042. return CharUnits::fromQuantity(-2ULL);
  1043. unsigned NumPublicPaths = 0;
  1044. CharUnits Offset;
  1045. // Now walk all possible inheritance paths.
  1046. for (const CXXBasePath &Path : Paths) {
  1047. if (Path.Access != AS_public) // Ignore non-public inheritance.
  1048. continue;
  1049. ++NumPublicPaths;
  1050. for (const CXXBasePathElement &PathElement : Path) {
  1051. // If the path contains a virtual base class we can't give any hint.
  1052. // -1: no hint.
  1053. if (PathElement.Base->isVirtual())
  1054. return CharUnits::fromQuantity(-1ULL);
  1055. if (NumPublicPaths > 1) // Won't use offsets, skip computation.
  1056. continue;
  1057. // Accumulate the base class offsets.
  1058. const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
  1059. Offset += L.getBaseClassOffset(
  1060. PathElement.Base->getType()->getAsCXXRecordDecl());
  1061. }
  1062. }
  1063. // -2: Src is not a public base of Dst.
  1064. if (NumPublicPaths == 0)
  1065. return CharUnits::fromQuantity(-2ULL);
  1066. // -3: Src is a multiple public base type but never a virtual base type.
  1067. if (NumPublicPaths > 1)
  1068. return CharUnits::fromQuantity(-3ULL);
  1069. // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
  1070. // Return the offset of Src from the origin of Dst.
  1071. return Offset;
  1072. }
  1073. static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
  1074. // void __cxa_bad_typeid();
  1075. llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
  1076. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
  1077. }
  1078. bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
  1079. QualType SrcRecordTy) {
  1080. return IsDeref;
  1081. }
  1082. void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
  1083. llvm::Value *Fn = getBadTypeidFn(CGF);
  1084. CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
  1085. CGF.Builder.CreateUnreachable();
  1086. }
  1087. llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
  1088. QualType SrcRecordTy,
  1089. Address ThisPtr,
  1090. llvm::Type *StdTypeInfoPtrTy) {
  1091. auto *ClassDecl =
  1092. cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
  1093. llvm::Value *Value =
  1094. CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
  1095. // Load the type info.
  1096. Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
  1097. return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
  1098. }
  1099. bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
  1100. QualType SrcRecordTy) {
  1101. return SrcIsPtr;
  1102. }
  1103. llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
  1104. CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
  1105. QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
  1106. llvm::Type *PtrDiffLTy =
  1107. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  1108. llvm::Type *DestLTy = CGF.ConvertType(DestTy);
  1109. llvm::Value *SrcRTTI =
  1110. CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
  1111. llvm::Value *DestRTTI =
  1112. CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
  1113. // Compute the offset hint.
  1114. const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
  1115. const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
  1116. llvm::Value *OffsetHint = llvm::ConstantInt::get(
  1117. PtrDiffLTy,
  1118. computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
  1119. // Emit the call to __dynamic_cast.
  1120. llvm::Value *Value = ThisAddr.getPointer();
  1121. Value = CGF.EmitCastToVoidPtr(Value);
  1122. llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
  1123. Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
  1124. Value = CGF.Builder.CreateBitCast(Value, DestLTy);
  1125. /// C++ [expr.dynamic.cast]p9:
  1126. /// A failed cast to reference type throws std::bad_cast
  1127. if (DestTy->isReferenceType()) {
  1128. llvm::BasicBlock *BadCastBlock =
  1129. CGF.createBasicBlock("dynamic_cast.bad_cast");
  1130. llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
  1131. CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
  1132. CGF.EmitBlock(BadCastBlock);
  1133. EmitBadCastCall(CGF);
  1134. }
  1135. return Value;
  1136. }
  1137. llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
  1138. Address ThisAddr,
  1139. QualType SrcRecordTy,
  1140. QualType DestTy) {
  1141. llvm::Type *PtrDiffLTy =
  1142. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  1143. llvm::Type *DestLTy = CGF.ConvertType(DestTy);
  1144. auto *ClassDecl =
  1145. cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
  1146. // Get the vtable pointer.
  1147. llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
  1148. ClassDecl);
  1149. // Get the offset-to-top from the vtable.
  1150. llvm::Value *OffsetToTop =
  1151. CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
  1152. OffsetToTop =
  1153. CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
  1154. "offset.to.top");
  1155. // Finally, add the offset to the pointer.
  1156. llvm::Value *Value = ThisAddr.getPointer();
  1157. Value = CGF.EmitCastToVoidPtr(Value);
  1158. Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
  1159. return CGF.Builder.CreateBitCast(Value, DestLTy);
  1160. }
  1161. bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
  1162. llvm::Value *Fn = getBadCastFn(CGF);
  1163. CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
  1164. CGF.Builder.CreateUnreachable();
  1165. return true;
  1166. }
  1167. llvm::Value *
  1168. ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
  1169. Address This,
  1170. const CXXRecordDecl *ClassDecl,
  1171. const CXXRecordDecl *BaseClassDecl) {
  1172. llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
  1173. CharUnits VBaseOffsetOffset =
  1174. CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
  1175. BaseClassDecl);
  1176. llvm::Value *VBaseOffsetPtr =
  1177. CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
  1178. "vbase.offset.ptr");
  1179. VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
  1180. CGM.PtrDiffTy->getPointerTo());
  1181. llvm::Value *VBaseOffset =
  1182. CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
  1183. "vbase.offset");
  1184. return VBaseOffset;
  1185. }
  1186. void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
  1187. // Just make sure we're in sync with TargetCXXABI.
  1188. assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
  1189. // The constructor used for constructing this as a base class;
  1190. // ignores virtual bases.
  1191. CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
  1192. // The constructor used for constructing this as a complete class;
  1193. // constructs the virtual bases, then calls the base constructor.
  1194. if (!D->getParent()->isAbstract()) {
  1195. // We don't need to emit the complete ctor if the class is abstract.
  1196. CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
  1197. }
  1198. }
  1199. CGCXXABI::AddedStructorArgs
  1200. ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
  1201. SmallVectorImpl<CanQualType> &ArgTys) {
  1202. ASTContext &Context = getContext();
  1203. // All parameters are already in place except VTT, which goes after 'this'.
  1204. // These are Clang types, so we don't need to worry about sret yet.
  1205. // Check if we need to add a VTT parameter (which has type void **).
  1206. if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
  1207. ArgTys.insert(ArgTys.begin() + 1,
  1208. Context.getPointerType(Context.VoidPtrTy));
  1209. return AddedStructorArgs::prefix(1);
  1210. }
  1211. return AddedStructorArgs{};
  1212. }
  1213. void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
  1214. // The destructor used for destructing this as a base class; ignores
  1215. // virtual bases.
  1216. CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
  1217. // The destructor used for destructing this as a most-derived class;
  1218. // call the base destructor and then destructs any virtual bases.
  1219. CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
  1220. // The destructor in a virtual table is always a 'deleting'
  1221. // destructor, which calls the complete destructor and then uses the
  1222. // appropriate operator delete.
  1223. if (D->isVirtual())
  1224. CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
  1225. }
  1226. void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
  1227. QualType &ResTy,
  1228. FunctionArgList &Params) {
  1229. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
  1230. assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
  1231. // Check if we need a VTT parameter as well.
  1232. if (NeedsVTTParameter(CGF.CurGD)) {
  1233. ASTContext &Context = getContext();
  1234. // FIXME: avoid the fake decl
  1235. QualType T = Context.getPointerType(Context.VoidPtrTy);
  1236. auto *VTTDecl = ImplicitParamDecl::Create(
  1237. Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
  1238. T, ImplicitParamDecl::CXXVTT);
  1239. Params.insert(Params.begin() + 1, VTTDecl);
  1240. getStructorImplicitParamDecl(CGF) = VTTDecl;
  1241. }
  1242. }
  1243. void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
  1244. // Naked functions have no prolog.
  1245. if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
  1246. return;
  1247. /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
  1248. /// adjustments are required, because they are all handled by thunks.
  1249. setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
  1250. /// Initialize the 'vtt' slot if needed.
  1251. if (getStructorImplicitParamDecl(CGF)) {
  1252. getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
  1253. CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
  1254. }
  1255. /// If this is a function that the ABI specifies returns 'this', initialize
  1256. /// the return slot to 'this' at the start of the function.
  1257. ///
  1258. /// Unlike the setting of return types, this is done within the ABI
  1259. /// implementation instead of by clients of CGCXXABI because:
  1260. /// 1) getThisValue is currently protected
  1261. /// 2) in theory, an ABI could implement 'this' returns some other way;
  1262. /// HasThisReturn only specifies a contract, not the implementation
  1263. if (HasThisReturn(CGF.CurGD))
  1264. CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
  1265. }
  1266. CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
  1267. CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
  1268. bool ForVirtualBase, bool Delegating, CallArgList &Args) {
  1269. if (!NeedsVTTParameter(GlobalDecl(D, Type)))
  1270. return AddedStructorArgs{};
  1271. // Insert the implicit 'vtt' argument as the second argument.
  1272. llvm::Value *VTT =
  1273. CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
  1274. QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
  1275. Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
  1276. return AddedStructorArgs::prefix(1); // Added one arg.
  1277. }
  1278. void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
  1279. const CXXDestructorDecl *DD,
  1280. CXXDtorType Type, bool ForVirtualBase,
  1281. bool Delegating, Address This) {
  1282. GlobalDecl GD(DD, Type);
  1283. llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
  1284. QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
  1285. CGCallee Callee;
  1286. if (getContext().getLangOpts().AppleKext &&
  1287. Type != Dtor_Base && DD->isVirtual())
  1288. Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
  1289. else
  1290. Callee =
  1291. CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
  1292. DD);
  1293. CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
  1294. This.getPointer(), VTT, VTTTy,
  1295. nullptr, nullptr);
  1296. }
  1297. void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
  1298. const CXXRecordDecl *RD) {
  1299. llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
  1300. if (VTable->hasInitializer())
  1301. return;
  1302. ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
  1303. const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
  1304. llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
  1305. llvm::Constant *RTTI =
  1306. CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
  1307. // Create and set the initializer.
  1308. ConstantInitBuilder Builder(CGM);
  1309. auto Components = Builder.beginStruct();
  1310. CGVT.createVTableInitializer(Components, VTLayout, RTTI);
  1311. Components.finishAndSetAsInitializer(VTable);
  1312. // Set the correct linkage.
  1313. VTable->setLinkage(Linkage);
  1314. if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
  1315. VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
  1316. // Set the right visibility.
  1317. CGM.setGVProperties(VTable, RD);
  1318. // If this is the magic class __cxxabiv1::__fundamental_type_info,
  1319. // we will emit the typeinfo for the fundamental types. This is the
  1320. // same behaviour as GCC.
  1321. const DeclContext *DC = RD->getDeclContext();
  1322. if (RD->getIdentifier() &&
  1323. RD->getIdentifier()->isStr("__fundamental_type_info") &&
  1324. isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
  1325. cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
  1326. DC->getParent()->isTranslationUnit())
  1327. EmitFundamentalRTTIDescriptors(RD);
  1328. if (!VTable->isDeclarationForLinker())
  1329. CGM.EmitVTableTypeMetadata(VTable, VTLayout);
  1330. }
  1331. bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
  1332. CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
  1333. if (Vptr.NearestVBase == nullptr)
  1334. return false;
  1335. return NeedsVTTParameter(CGF.CurGD);
  1336. }
  1337. llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
  1338. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
  1339. const CXXRecordDecl *NearestVBase) {
  1340. if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
  1341. NeedsVTTParameter(CGF.CurGD)) {
  1342. return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
  1343. NearestVBase);
  1344. }
  1345. return getVTableAddressPoint(Base, VTableClass);
  1346. }
  1347. llvm::Constant *
  1348. ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
  1349. const CXXRecordDecl *VTableClass) {
  1350. llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
  1351. // Find the appropriate vtable within the vtable group, and the address point
  1352. // within that vtable.
  1353. VTableLayout::AddressPointLocation AddressPoint =
  1354. CGM.getItaniumVTableContext()
  1355. .getVTableLayout(VTableClass)
  1356. .getAddressPoint(Base);
  1357. llvm::Value *Indices[] = {
  1358. llvm::ConstantInt::get(CGM.Int32Ty, 0),
  1359. llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
  1360. llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
  1361. };
  1362. return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
  1363. Indices, /*InBounds=*/true,
  1364. /*InRangeIndex=*/1);
  1365. }
  1366. llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
  1367. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
  1368. const CXXRecordDecl *NearestVBase) {
  1369. assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
  1370. NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
  1371. // Get the secondary vpointer index.
  1372. uint64_t VirtualPointerIndex =
  1373. CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
  1374. /// Load the VTT.
  1375. llvm::Value *VTT = CGF.LoadCXXVTT();
  1376. if (VirtualPointerIndex)
  1377. VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
  1378. // And load the address point from the VTT.
  1379. return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
  1380. }
  1381. llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
  1382. BaseSubobject Base, const CXXRecordDecl *VTableClass) {
  1383. return getVTableAddressPoint(Base, VTableClass);
  1384. }
  1385. llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
  1386. CharUnits VPtrOffset) {
  1387. assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
  1388. llvm::GlobalVariable *&VTable = VTables[RD];
  1389. if (VTable)
  1390. return VTable;
  1391. // Queue up this vtable for possible deferred emission.
  1392. CGM.addDeferredVTable(RD);
  1393. SmallString<256> Name;
  1394. llvm::raw_svector_ostream Out(Name);
  1395. getMangleContext().mangleCXXVTable(RD, Out);
  1396. const VTableLayout &VTLayout =
  1397. CGM.getItaniumVTableContext().getVTableLayout(RD);
  1398. llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
  1399. // Use pointer alignment for the vtable. Otherwise we would align them based
  1400. // on the size of the initializer which doesn't make sense as only single
  1401. // values are read.
  1402. unsigned PAlign = CGM.getTarget().getPointerAlign(0);
  1403. VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
  1404. Name, VTableType, llvm::GlobalValue::ExternalLinkage,
  1405. getContext().toCharUnitsFromBits(PAlign).getQuantity());
  1406. VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1407. CGM.setGVProperties(VTable, RD);
  1408. return VTable;
  1409. }
  1410. CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
  1411. GlobalDecl GD,
  1412. Address This,
  1413. llvm::Type *Ty,
  1414. SourceLocation Loc) {
  1415. Ty = Ty->getPointerTo()->getPointerTo();
  1416. auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
  1417. llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
  1418. uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
  1419. llvm::Value *VFunc;
  1420. if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
  1421. VFunc = CGF.EmitVTableTypeCheckedLoad(
  1422. MethodDecl->getParent(), VTable,
  1423. VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
  1424. } else {
  1425. CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
  1426. llvm::Value *VFuncPtr =
  1427. CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
  1428. auto *VFuncLoad =
  1429. CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
  1430. // Add !invariant.load md to virtual function load to indicate that
  1431. // function didn't change inside vtable.
  1432. // It's safe to add it without -fstrict-vtable-pointers, but it would not
  1433. // help in devirtualization because it will only matter if we will have 2
  1434. // the same virtual function loads from the same vtable load, which won't
  1435. // happen without enabled devirtualization with -fstrict-vtable-pointers.
  1436. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1437. CGM.getCodeGenOpts().StrictVTablePointers)
  1438. VFuncLoad->setMetadata(
  1439. llvm::LLVMContext::MD_invariant_load,
  1440. llvm::MDNode::get(CGM.getLLVMContext(),
  1441. llvm::ArrayRef<llvm::Metadata *>()));
  1442. VFunc = VFuncLoad;
  1443. }
  1444. CGCallee Callee(MethodDecl->getCanonicalDecl(), VFunc);
  1445. return Callee;
  1446. }
  1447. llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
  1448. CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
  1449. Address This, const CXXMemberCallExpr *CE) {
  1450. assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
  1451. assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
  1452. const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
  1453. Dtor, getFromDtorType(DtorType));
  1454. llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
  1455. CGCallee Callee =
  1456. CGCallee::forVirtual(CE, GlobalDecl(Dtor, DtorType), This, Ty);
  1457. CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
  1458. This.getPointer(), /*ImplicitParam=*/nullptr,
  1459. QualType(), CE, nullptr);
  1460. return nullptr;
  1461. }
  1462. void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
  1463. CodeGenVTables &VTables = CGM.getVTables();
  1464. llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
  1465. VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
  1466. }
  1467. bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
  1468. // We don't emit available_externally vtables if we are in -fapple-kext mode
  1469. // because kext mode does not permit devirtualization.
  1470. if (CGM.getLangOpts().AppleKext)
  1471. return false;
  1472. // If the vtable is hidden then it is not safe to emit an available_externally
  1473. // copy of vtable.
  1474. if (isVTableHidden(RD))
  1475. return false;
  1476. if (CGM.getCodeGenOpts().ForceEmitVTables)
  1477. return true;
  1478. // If we don't have any not emitted inline virtual function then we are safe
  1479. // to emit an available_externally copy of vtable.
  1480. // FIXME we can still emit a copy of the vtable if we
  1481. // can emit definition of the inline functions.
  1482. return !hasAnyUnusedVirtualInlineFunction(RD);
  1483. }
  1484. static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
  1485. Address InitialPtr,
  1486. int64_t NonVirtualAdjustment,
  1487. int64_t VirtualAdjustment,
  1488. bool IsReturnAdjustment) {
  1489. if (!NonVirtualAdjustment && !VirtualAdjustment)
  1490. return InitialPtr.getPointer();
  1491. Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
  1492. // In a base-to-derived cast, the non-virtual adjustment is applied first.
  1493. if (NonVirtualAdjustment && !IsReturnAdjustment) {
  1494. V = CGF.Builder.CreateConstInBoundsByteGEP(V,
  1495. CharUnits::fromQuantity(NonVirtualAdjustment));
  1496. }
  1497. // Perform the virtual adjustment if we have one.
  1498. llvm::Value *ResultPtr;
  1499. if (VirtualAdjustment) {
  1500. llvm::Type *PtrDiffTy =
  1501. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  1502. Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
  1503. llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
  1504. llvm::Value *OffsetPtr =
  1505. CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
  1506. OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
  1507. // Load the adjustment offset from the vtable.
  1508. llvm::Value *Offset =
  1509. CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
  1510. // Adjust our pointer.
  1511. ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
  1512. } else {
  1513. ResultPtr = V.getPointer();
  1514. }
  1515. // In a derived-to-base conversion, the non-virtual adjustment is
  1516. // applied second.
  1517. if (NonVirtualAdjustment && IsReturnAdjustment) {
  1518. ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
  1519. NonVirtualAdjustment);
  1520. }
  1521. // Cast back to the original type.
  1522. return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
  1523. }
  1524. llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
  1525. Address This,
  1526. const ThisAdjustment &TA) {
  1527. return performTypeAdjustment(CGF, This, TA.NonVirtual,
  1528. TA.Virtual.Itanium.VCallOffsetOffset,
  1529. /*IsReturnAdjustment=*/false);
  1530. }
  1531. llvm::Value *
  1532. ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
  1533. const ReturnAdjustment &RA) {
  1534. return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
  1535. RA.Virtual.Itanium.VBaseOffsetOffset,
  1536. /*IsReturnAdjustment=*/true);
  1537. }
  1538. void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
  1539. RValue RV, QualType ResultType) {
  1540. if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
  1541. return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
  1542. // Destructor thunks in the ARM ABI have indeterminate results.
  1543. llvm::Type *T = CGF.ReturnValue.getElementType();
  1544. RValue Undef = RValue::get(llvm::UndefValue::get(T));
  1545. return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
  1546. }
  1547. /************************** Array allocation cookies **************************/
  1548. CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
  1549. // The array cookie is a size_t; pad that up to the element alignment.
  1550. // The cookie is actually right-justified in that space.
  1551. return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
  1552. CGM.getContext().getTypeAlignInChars(elementType));
  1553. }
  1554. Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
  1555. Address NewPtr,
  1556. llvm::Value *NumElements,
  1557. const CXXNewExpr *expr,
  1558. QualType ElementType) {
  1559. assert(requiresArrayCookie(expr));
  1560. unsigned AS = NewPtr.getAddressSpace();
  1561. ASTContext &Ctx = getContext();
  1562. CharUnits SizeSize = CGF.getSizeSize();
  1563. // The size of the cookie.
  1564. CharUnits CookieSize =
  1565. std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
  1566. assert(CookieSize == getArrayCookieSizeImpl(ElementType));
  1567. // Compute an offset to the cookie.
  1568. Address CookiePtr = NewPtr;
  1569. CharUnits CookieOffset = CookieSize - SizeSize;
  1570. if (!CookieOffset.isZero())
  1571. CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
  1572. // Write the number of elements into the appropriate slot.
  1573. Address NumElementsPtr =
  1574. CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
  1575. llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
  1576. // Handle the array cookie specially in ASan.
  1577. if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
  1578. (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
  1579. CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
  1580. // The store to the CookiePtr does not need to be instrumented.
  1581. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
  1582. llvm::FunctionType *FTy =
  1583. llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
  1584. llvm::Constant *F =
  1585. CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
  1586. CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
  1587. }
  1588. // Finally, compute a pointer to the actual data buffer by skipping
  1589. // over the cookie completely.
  1590. return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
  1591. }
  1592. llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
  1593. Address allocPtr,
  1594. CharUnits cookieSize) {
  1595. // The element size is right-justified in the cookie.
  1596. Address numElementsPtr = allocPtr;
  1597. CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
  1598. if (!numElementsOffset.isZero())
  1599. numElementsPtr =
  1600. CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
  1601. unsigned AS = allocPtr.getAddressSpace();
  1602. numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
  1603. if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
  1604. return CGF.Builder.CreateLoad(numElementsPtr);
  1605. // In asan mode emit a function call instead of a regular load and let the
  1606. // run-time deal with it: if the shadow is properly poisoned return the
  1607. // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
  1608. // We can't simply ignore this load using nosanitize metadata because
  1609. // the metadata may be lost.
  1610. llvm::FunctionType *FTy =
  1611. llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
  1612. llvm::Constant *F =
  1613. CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
  1614. return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
  1615. }
  1616. CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
  1617. // ARM says that the cookie is always:
  1618. // struct array_cookie {
  1619. // std::size_t element_size; // element_size != 0
  1620. // std::size_t element_count;
  1621. // };
  1622. // But the base ABI doesn't give anything an alignment greater than
  1623. // 8, so we can dismiss this as typical ABI-author blindness to
  1624. // actual language complexity and round up to the element alignment.
  1625. return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
  1626. CGM.getContext().getTypeAlignInChars(elementType));
  1627. }
  1628. Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
  1629. Address newPtr,
  1630. llvm::Value *numElements,
  1631. const CXXNewExpr *expr,
  1632. QualType elementType) {
  1633. assert(requiresArrayCookie(expr));
  1634. // The cookie is always at the start of the buffer.
  1635. Address cookie = newPtr;
  1636. // The first element is the element size.
  1637. cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
  1638. llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
  1639. getContext().getTypeSizeInChars(elementType).getQuantity());
  1640. CGF.Builder.CreateStore(elementSize, cookie);
  1641. // The second element is the element count.
  1642. cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
  1643. CGF.Builder.CreateStore(numElements, cookie);
  1644. // Finally, compute a pointer to the actual data buffer by skipping
  1645. // over the cookie completely.
  1646. CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
  1647. return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
  1648. }
  1649. llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
  1650. Address allocPtr,
  1651. CharUnits cookieSize) {
  1652. // The number of elements is at offset sizeof(size_t) relative to
  1653. // the allocated pointer.
  1654. Address numElementsPtr
  1655. = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
  1656. numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
  1657. return CGF.Builder.CreateLoad(numElementsPtr);
  1658. }
  1659. /*********************** Static local initialization **************************/
  1660. static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
  1661. llvm::PointerType *GuardPtrTy) {
  1662. // int __cxa_guard_acquire(__guard *guard_object);
  1663. llvm::FunctionType *FTy =
  1664. llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
  1665. GuardPtrTy, /*isVarArg=*/false);
  1666. return CGM.CreateRuntimeFunction(
  1667. FTy, "__cxa_guard_acquire",
  1668. llvm::AttributeList::get(CGM.getLLVMContext(),
  1669. llvm::AttributeList::FunctionIndex,
  1670. llvm::Attribute::NoUnwind));
  1671. }
  1672. static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
  1673. llvm::PointerType *GuardPtrTy) {
  1674. // void __cxa_guard_release(__guard *guard_object);
  1675. llvm::FunctionType *FTy =
  1676. llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
  1677. return CGM.CreateRuntimeFunction(
  1678. FTy, "__cxa_guard_release",
  1679. llvm::AttributeList::get(CGM.getLLVMContext(),
  1680. llvm::AttributeList::FunctionIndex,
  1681. llvm::Attribute::NoUnwind));
  1682. }
  1683. static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
  1684. llvm::PointerType *GuardPtrTy) {
  1685. // void __cxa_guard_abort(__guard *guard_object);
  1686. llvm::FunctionType *FTy =
  1687. llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
  1688. return CGM.CreateRuntimeFunction(
  1689. FTy, "__cxa_guard_abort",
  1690. llvm::AttributeList::get(CGM.getLLVMContext(),
  1691. llvm::AttributeList::FunctionIndex,
  1692. llvm::Attribute::NoUnwind));
  1693. }
  1694. namespace {
  1695. struct CallGuardAbort final : EHScopeStack::Cleanup {
  1696. llvm::GlobalVariable *Guard;
  1697. CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
  1698. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1699. CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
  1700. Guard);
  1701. }
  1702. };
  1703. }
  1704. /// The ARM code here follows the Itanium code closely enough that we
  1705. /// just special-case it at particular places.
  1706. void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
  1707. const VarDecl &D,
  1708. llvm::GlobalVariable *var,
  1709. bool shouldPerformInit) {
  1710. CGBuilderTy &Builder = CGF.Builder;
  1711. // Inline variables that weren't instantiated from variable templates have
  1712. // partially-ordered initialization within their translation unit.
  1713. bool NonTemplateInline =
  1714. D.isInline() &&
  1715. !isTemplateInstantiation(D.getTemplateSpecializationKind());
  1716. // We only need to use thread-safe statics for local non-TLS variables and
  1717. // inline variables; other global initialization is always single-threaded
  1718. // or (through lazy dynamic loading in multiple threads) unsequenced.
  1719. bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
  1720. (D.isLocalVarDecl() || NonTemplateInline) &&
  1721. !D.getTLSKind();
  1722. // If we have a global variable with internal linkage and thread-safe statics
  1723. // are disabled, we can just let the guard variable be of type i8.
  1724. bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
  1725. llvm::IntegerType *guardTy;
  1726. CharUnits guardAlignment;
  1727. if (useInt8GuardVariable) {
  1728. guardTy = CGF.Int8Ty;
  1729. guardAlignment = CharUnits::One();
  1730. } else {
  1731. // Guard variables are 64 bits in the generic ABI and size width on ARM
  1732. // (i.e. 32-bit on AArch32, 64-bit on AArch64).
  1733. if (UseARMGuardVarABI) {
  1734. guardTy = CGF.SizeTy;
  1735. guardAlignment = CGF.getSizeAlign();
  1736. } else {
  1737. guardTy = CGF.Int64Ty;
  1738. guardAlignment = CharUnits::fromQuantity(
  1739. CGM.getDataLayout().getABITypeAlignment(guardTy));
  1740. }
  1741. }
  1742. llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
  1743. // Create the guard variable if we don't already have it (as we
  1744. // might if we're double-emitting this function body).
  1745. llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
  1746. if (!guard) {
  1747. // Mangle the name for the guard.
  1748. SmallString<256> guardName;
  1749. {
  1750. llvm::raw_svector_ostream out(guardName);
  1751. getMangleContext().mangleStaticGuardVariable(&D, out);
  1752. }
  1753. // Create the guard variable with a zero-initializer.
  1754. // Just absorb linkage and visibility from the guarded variable.
  1755. guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
  1756. false, var->getLinkage(),
  1757. llvm::ConstantInt::get(guardTy, 0),
  1758. guardName.str());
  1759. guard->setDSOLocal(var->isDSOLocal());
  1760. guard->setVisibility(var->getVisibility());
  1761. // If the variable is thread-local, so is its guard variable.
  1762. guard->setThreadLocalMode(var->getThreadLocalMode());
  1763. guard->setAlignment(guardAlignment.getQuantity());
  1764. // The ABI says: "It is suggested that it be emitted in the same COMDAT
  1765. // group as the associated data object." In practice, this doesn't work for
  1766. // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
  1767. llvm::Comdat *C = var->getComdat();
  1768. if (!D.isLocalVarDecl() && C &&
  1769. (CGM.getTarget().getTriple().isOSBinFormatELF() ||
  1770. CGM.getTarget().getTriple().isOSBinFormatWasm())) {
  1771. guard->setComdat(C);
  1772. // An inline variable's guard function is run from the per-TU
  1773. // initialization function, not via a dedicated global ctor function, so
  1774. // we can't put it in a comdat.
  1775. if (!NonTemplateInline)
  1776. CGF.CurFn->setComdat(C);
  1777. } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
  1778. guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
  1779. }
  1780. CGM.setStaticLocalDeclGuardAddress(&D, guard);
  1781. }
  1782. Address guardAddr = Address(guard, guardAlignment);
  1783. // Test whether the variable has completed initialization.
  1784. //
  1785. // Itanium C++ ABI 3.3.2:
  1786. // The following is pseudo-code showing how these functions can be used:
  1787. // if (obj_guard.first_byte == 0) {
  1788. // if ( __cxa_guard_acquire (&obj_guard) ) {
  1789. // try {
  1790. // ... initialize the object ...;
  1791. // } catch (...) {
  1792. // __cxa_guard_abort (&obj_guard);
  1793. // throw;
  1794. // }
  1795. // ... queue object destructor with __cxa_atexit() ...;
  1796. // __cxa_guard_release (&obj_guard);
  1797. // }
  1798. // }
  1799. // Load the first byte of the guard variable.
  1800. llvm::LoadInst *LI =
  1801. Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
  1802. // Itanium ABI:
  1803. // An implementation supporting thread-safety on multiprocessor
  1804. // systems must also guarantee that references to the initialized
  1805. // object do not occur before the load of the initialization flag.
  1806. //
  1807. // In LLVM, we do this by marking the load Acquire.
  1808. if (threadsafe)
  1809. LI->setAtomic(llvm::AtomicOrdering::Acquire);
  1810. // For ARM, we should only check the first bit, rather than the entire byte:
  1811. //
  1812. // ARM C++ ABI 3.2.3.1:
  1813. // To support the potential use of initialization guard variables
  1814. // as semaphores that are the target of ARM SWP and LDREX/STREX
  1815. // synchronizing instructions we define a static initialization
  1816. // guard variable to be a 4-byte aligned, 4-byte word with the
  1817. // following inline access protocol.
  1818. // #define INITIALIZED 1
  1819. // if ((obj_guard & INITIALIZED) != INITIALIZED) {
  1820. // if (__cxa_guard_acquire(&obj_guard))
  1821. // ...
  1822. // }
  1823. //
  1824. // and similarly for ARM64:
  1825. //
  1826. // ARM64 C++ ABI 3.2.2:
  1827. // This ABI instead only specifies the value bit 0 of the static guard
  1828. // variable; all other bits are platform defined. Bit 0 shall be 0 when the
  1829. // variable is not initialized and 1 when it is.
  1830. llvm::Value *V =
  1831. (UseARMGuardVarABI && !useInt8GuardVariable)
  1832. ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
  1833. : LI;
  1834. llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
  1835. llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
  1836. llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
  1837. // Check if the first byte of the guard variable is zero.
  1838. CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
  1839. CodeGenFunction::GuardKind::VariableGuard, &D);
  1840. CGF.EmitBlock(InitCheckBlock);
  1841. // Variables used when coping with thread-safe statics and exceptions.
  1842. if (threadsafe) {
  1843. // Call __cxa_guard_acquire.
  1844. llvm::Value *V
  1845. = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
  1846. llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
  1847. Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
  1848. InitBlock, EndBlock);
  1849. // Call __cxa_guard_abort along the exceptional edge.
  1850. CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
  1851. CGF.EmitBlock(InitBlock);
  1852. }
  1853. // Emit the initializer and add a global destructor if appropriate.
  1854. CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
  1855. if (threadsafe) {
  1856. // Pop the guard-abort cleanup if we pushed one.
  1857. CGF.PopCleanupBlock();
  1858. // Call __cxa_guard_release. This cannot throw.
  1859. CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
  1860. guardAddr.getPointer());
  1861. } else {
  1862. Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
  1863. }
  1864. CGF.EmitBlock(EndBlock);
  1865. }
  1866. /// Register a global destructor using __cxa_atexit.
  1867. static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
  1868. llvm::Constant *dtor,
  1869. llvm::Constant *addr,
  1870. bool TLS) {
  1871. const char *Name = "__cxa_atexit";
  1872. if (TLS) {
  1873. const llvm::Triple &T = CGF.getTarget().getTriple();
  1874. Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
  1875. }
  1876. // We're assuming that the destructor function is something we can
  1877. // reasonably call with the default CC. Go ahead and cast it to the
  1878. // right prototype.
  1879. llvm::Type *dtorTy =
  1880. llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
  1881. // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
  1882. llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
  1883. llvm::FunctionType *atexitTy =
  1884. llvm::FunctionType::get(CGF.IntTy, paramTys, false);
  1885. // Fetch the actual function.
  1886. llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
  1887. if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
  1888. fn->setDoesNotThrow();
  1889. // Create a variable that binds the atexit to this shared object.
  1890. llvm::Constant *handle =
  1891. CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
  1892. auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
  1893. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1894. if (!addr)
  1895. // addr is null when we are trying to register a dtor annotated with
  1896. // __attribute__((destructor)) in a constructor function. Using null here is
  1897. // okay because this argument is just passed back to the destructor
  1898. // function.
  1899. addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
  1900. llvm::Value *args[] = {
  1901. llvm::ConstantExpr::getBitCast(dtor, dtorTy),
  1902. llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
  1903. handle
  1904. };
  1905. CGF.EmitNounwindRuntimeCall(atexit, args);
  1906. }
  1907. void CodeGenModule::registerGlobalDtorsWithAtExit() {
  1908. for (const auto I : DtorsUsingAtExit) {
  1909. int Priority = I.first;
  1910. const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
  1911. // Create a function that registers destructors that have the same priority.
  1912. //
  1913. // Since constructor functions are run in non-descending order of their
  1914. // priorities, destructors are registered in non-descending order of their
  1915. // priorities, and since destructor functions are run in the reverse order
  1916. // of their registration, destructor functions are run in non-ascending
  1917. // order of their priorities.
  1918. CodeGenFunction CGF(*this);
  1919. std::string GlobalInitFnName =
  1920. std::string("__GLOBAL_init_") + llvm::to_string(Priority);
  1921. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  1922. llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
  1923. FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
  1924. SourceLocation());
  1925. ASTContext &Ctx = getContext();
  1926. FunctionDecl *FD = FunctionDecl::Create(
  1927. Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
  1928. &Ctx.Idents.get(GlobalInitFnName), Ctx.VoidTy, nullptr, SC_Static,
  1929. false, false);
  1930. CGF.StartFunction(GlobalDecl(FD), getContext().VoidTy, GlobalInitFn,
  1931. getTypes().arrangeNullaryFunction(), FunctionArgList(),
  1932. SourceLocation(), SourceLocation());
  1933. for (auto *Dtor : Dtors) {
  1934. // Register the destructor function calling __cxa_atexit if it is
  1935. // available. Otherwise fall back on calling atexit.
  1936. if (getCodeGenOpts().CXAAtExit)
  1937. emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
  1938. else
  1939. CGF.registerGlobalDtorWithAtExit(Dtor);
  1940. }
  1941. CGF.FinishFunction();
  1942. AddGlobalCtor(GlobalInitFn, Priority, nullptr);
  1943. }
  1944. }
  1945. /// Register a global destructor as best as we know how.
  1946. void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
  1947. const VarDecl &D,
  1948. llvm::Constant *dtor,
  1949. llvm::Constant *addr) {
  1950. if (D.isNoDestroy(CGM.getContext()))
  1951. return;
  1952. // Use __cxa_atexit if available.
  1953. if (CGM.getCodeGenOpts().CXAAtExit)
  1954. return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
  1955. if (D.getTLSKind())
  1956. CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
  1957. // In Apple kexts, we want to add a global destructor entry.
  1958. // FIXME: shouldn't this be guarded by some variable?
  1959. if (CGM.getLangOpts().AppleKext) {
  1960. // Generate a global destructor entry.
  1961. return CGM.AddCXXDtorEntry(dtor, addr);
  1962. }
  1963. CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
  1964. }
  1965. static bool isThreadWrapperReplaceable(const VarDecl *VD,
  1966. CodeGen::CodeGenModule &CGM) {
  1967. assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
  1968. // Darwin prefers to have references to thread local variables to go through
  1969. // the thread wrapper instead of directly referencing the backing variable.
  1970. return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
  1971. CGM.getTarget().getTriple().isOSDarwin();
  1972. }
  1973. /// Get the appropriate linkage for the wrapper function. This is essentially
  1974. /// the weak form of the variable's linkage; every translation unit which needs
  1975. /// the wrapper emits a copy, and we want the linker to merge them.
  1976. static llvm::GlobalValue::LinkageTypes
  1977. getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
  1978. llvm::GlobalValue::LinkageTypes VarLinkage =
  1979. CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
  1980. // For internal linkage variables, we don't need an external or weak wrapper.
  1981. if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
  1982. return VarLinkage;
  1983. // If the thread wrapper is replaceable, give it appropriate linkage.
  1984. if (isThreadWrapperReplaceable(VD, CGM))
  1985. if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
  1986. !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
  1987. return VarLinkage;
  1988. return llvm::GlobalValue::WeakODRLinkage;
  1989. }
  1990. llvm::Function *
  1991. ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
  1992. llvm::Value *Val) {
  1993. // Mangle the name for the thread_local wrapper function.
  1994. SmallString<256> WrapperName;
  1995. {
  1996. llvm::raw_svector_ostream Out(WrapperName);
  1997. getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
  1998. }
  1999. // FIXME: If VD is a definition, we should regenerate the function attributes
  2000. // before returning.
  2001. if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
  2002. return cast<llvm::Function>(V);
  2003. QualType RetQT = VD->getType();
  2004. if (RetQT->isReferenceType())
  2005. RetQT = RetQT.getNonReferenceType();
  2006. const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
  2007. getContext().getPointerType(RetQT), FunctionArgList());
  2008. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
  2009. llvm::Function *Wrapper =
  2010. llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
  2011. WrapperName.str(), &CGM.getModule());
  2012. CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
  2013. if (VD->hasDefinition())
  2014. CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
  2015. // Always resolve references to the wrapper at link time.
  2016. if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
  2017. !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
  2018. !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
  2019. Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
  2020. if (isThreadWrapperReplaceable(VD, CGM)) {
  2021. Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
  2022. Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
  2023. }
  2024. return Wrapper;
  2025. }
  2026. void ItaniumCXXABI::EmitThreadLocalInitFuncs(
  2027. CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
  2028. ArrayRef<llvm::Function *> CXXThreadLocalInits,
  2029. ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
  2030. llvm::Function *InitFunc = nullptr;
  2031. // Separate initializers into those with ordered (or partially-ordered)
  2032. // initialization and those with unordered initialization.
  2033. llvm::SmallVector<llvm::Function *, 8> OrderedInits;
  2034. llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
  2035. for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
  2036. if (isTemplateInstantiation(
  2037. CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
  2038. UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
  2039. CXXThreadLocalInits[I];
  2040. else
  2041. OrderedInits.push_back(CXXThreadLocalInits[I]);
  2042. }
  2043. if (!OrderedInits.empty()) {
  2044. // Generate a guarded initialization function.
  2045. llvm::FunctionType *FTy =
  2046. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  2047. const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
  2048. InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
  2049. SourceLocation(),
  2050. /*TLS=*/true);
  2051. llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
  2052. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
  2053. llvm::GlobalVariable::InternalLinkage,
  2054. llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
  2055. Guard->setThreadLocal(true);
  2056. CharUnits GuardAlign = CharUnits::One();
  2057. Guard->setAlignment(GuardAlign.getQuantity());
  2058. CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
  2059. InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign));
  2060. // On Darwin platforms, use CXX_FAST_TLS calling convention.
  2061. if (CGM.getTarget().getTriple().isOSDarwin()) {
  2062. InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
  2063. InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
  2064. }
  2065. }
  2066. // Emit thread wrappers.
  2067. for (const VarDecl *VD : CXXThreadLocals) {
  2068. llvm::GlobalVariable *Var =
  2069. cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
  2070. llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
  2071. // Some targets require that all access to thread local variables go through
  2072. // the thread wrapper. This means that we cannot attempt to create a thread
  2073. // wrapper or a thread helper.
  2074. if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
  2075. Wrapper->setLinkage(llvm::Function::ExternalLinkage);
  2076. continue;
  2077. }
  2078. // Mangle the name for the thread_local initialization function.
  2079. SmallString<256> InitFnName;
  2080. {
  2081. llvm::raw_svector_ostream Out(InitFnName);
  2082. getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
  2083. }
  2084. // If we have a definition for the variable, emit the initialization
  2085. // function as an alias to the global Init function (if any). Otherwise,
  2086. // produce a declaration of the initialization function.
  2087. llvm::GlobalValue *Init = nullptr;
  2088. bool InitIsInitFunc = false;
  2089. if (VD->hasDefinition()) {
  2090. InitIsInitFunc = true;
  2091. llvm::Function *InitFuncToUse = InitFunc;
  2092. if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
  2093. InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
  2094. if (InitFuncToUse)
  2095. Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
  2096. InitFuncToUse);
  2097. } else {
  2098. // Emit a weak global function referring to the initialization function.
  2099. // This function will not exist if the TU defining the thread_local
  2100. // variable in question does not need any dynamic initialization for
  2101. // its thread_local variables.
  2102. llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
  2103. Init = llvm::Function::Create(FnTy,
  2104. llvm::GlobalVariable::ExternalWeakLinkage,
  2105. InitFnName.str(), &CGM.getModule());
  2106. const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
  2107. CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
  2108. }
  2109. if (Init) {
  2110. Init->setVisibility(Var->getVisibility());
  2111. Init->setDSOLocal(Var->isDSOLocal());
  2112. }
  2113. llvm::LLVMContext &Context = CGM.getModule().getContext();
  2114. llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
  2115. CGBuilderTy Builder(CGM, Entry);
  2116. if (InitIsInitFunc) {
  2117. if (Init) {
  2118. llvm::CallInst *CallVal = Builder.CreateCall(Init);
  2119. if (isThreadWrapperReplaceable(VD, CGM)) {
  2120. CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
  2121. llvm::Function *Fn =
  2122. cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
  2123. Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
  2124. }
  2125. }
  2126. } else {
  2127. // Don't know whether we have an init function. Call it if it exists.
  2128. llvm::Value *Have = Builder.CreateIsNotNull(Init);
  2129. llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
  2130. llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
  2131. Builder.CreateCondBr(Have, InitBB, ExitBB);
  2132. Builder.SetInsertPoint(InitBB);
  2133. Builder.CreateCall(Init);
  2134. Builder.CreateBr(ExitBB);
  2135. Builder.SetInsertPoint(ExitBB);
  2136. }
  2137. // For a reference, the result of the wrapper function is a pointer to
  2138. // the referenced object.
  2139. llvm::Value *Val = Var;
  2140. if (VD->getType()->isReferenceType()) {
  2141. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  2142. Val = Builder.CreateAlignedLoad(Val, Align);
  2143. }
  2144. if (Val->getType() != Wrapper->getReturnType())
  2145. Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
  2146. Val, Wrapper->getReturnType(), "");
  2147. Builder.CreateRet(Val);
  2148. }
  2149. }
  2150. LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
  2151. const VarDecl *VD,
  2152. QualType LValType) {
  2153. llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
  2154. llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
  2155. llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
  2156. CallVal->setCallingConv(Wrapper->getCallingConv());
  2157. LValue LV;
  2158. if (VD->getType()->isReferenceType())
  2159. LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
  2160. else
  2161. LV = CGF.MakeAddrLValue(CallVal, LValType,
  2162. CGF.getContext().getDeclAlign(VD));
  2163. // FIXME: need setObjCGCLValueClass?
  2164. return LV;
  2165. }
  2166. /// Return whether the given global decl needs a VTT parameter, which it does
  2167. /// if it's a base constructor or destructor with virtual bases.
  2168. bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
  2169. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  2170. // We don't have any virtual bases, just return early.
  2171. if (!MD->getParent()->getNumVBases())
  2172. return false;
  2173. // Check if we have a base constructor.
  2174. if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
  2175. return true;
  2176. // Check if we have a base destructor.
  2177. if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
  2178. return true;
  2179. return false;
  2180. }
  2181. namespace {
  2182. class ItaniumRTTIBuilder {
  2183. CodeGenModule &CGM; // Per-module state.
  2184. llvm::LLVMContext &VMContext;
  2185. const ItaniumCXXABI &CXXABI; // Per-module state.
  2186. /// Fields - The fields of the RTTI descriptor currently being built.
  2187. SmallVector<llvm::Constant *, 16> Fields;
  2188. /// GetAddrOfTypeName - Returns the mangled type name of the given type.
  2189. llvm::GlobalVariable *
  2190. GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
  2191. /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
  2192. /// descriptor of the given type.
  2193. llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
  2194. /// BuildVTablePointer - Build the vtable pointer for the given type.
  2195. void BuildVTablePointer(const Type *Ty);
  2196. /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
  2197. /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
  2198. void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
  2199. /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
  2200. /// classes with bases that do not satisfy the abi::__si_class_type_info
  2201. /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
  2202. void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
  2203. /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
  2204. /// for pointer types.
  2205. void BuildPointerTypeInfo(QualType PointeeTy);
  2206. /// BuildObjCObjectTypeInfo - Build the appropriate kind of
  2207. /// type_info for an object type.
  2208. void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
  2209. /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
  2210. /// struct, used for member pointer types.
  2211. void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
  2212. public:
  2213. ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
  2214. : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
  2215. // Pointer type info flags.
  2216. enum {
  2217. /// PTI_Const - Type has const qualifier.
  2218. PTI_Const = 0x1,
  2219. /// PTI_Volatile - Type has volatile qualifier.
  2220. PTI_Volatile = 0x2,
  2221. /// PTI_Restrict - Type has restrict qualifier.
  2222. PTI_Restrict = 0x4,
  2223. /// PTI_Incomplete - Type is incomplete.
  2224. PTI_Incomplete = 0x8,
  2225. /// PTI_ContainingClassIncomplete - Containing class is incomplete.
  2226. /// (in pointer to member).
  2227. PTI_ContainingClassIncomplete = 0x10,
  2228. /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
  2229. //PTI_TransactionSafe = 0x20,
  2230. /// PTI_Noexcept - Pointee is noexcept function (C++1z).
  2231. PTI_Noexcept = 0x40,
  2232. };
  2233. // VMI type info flags.
  2234. enum {
  2235. /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
  2236. VMI_NonDiamondRepeat = 0x1,
  2237. /// VMI_DiamondShaped - Class is diamond shaped.
  2238. VMI_DiamondShaped = 0x2
  2239. };
  2240. // Base class type info flags.
  2241. enum {
  2242. /// BCTI_Virtual - Base class is virtual.
  2243. BCTI_Virtual = 0x1,
  2244. /// BCTI_Public - Base class is public.
  2245. BCTI_Public = 0x2
  2246. };
  2247. /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
  2248. /// link to an existing RTTI descriptor if one already exists.
  2249. llvm::Constant *BuildTypeInfo(QualType Ty);
  2250. /// BuildTypeInfo - Build the RTTI type info struct for the given type.
  2251. llvm::Constant *BuildTypeInfo(
  2252. QualType Ty,
  2253. llvm::GlobalVariable::LinkageTypes Linkage,
  2254. llvm::GlobalValue::VisibilityTypes Visibility,
  2255. llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
  2256. };
  2257. }
  2258. llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
  2259. QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
  2260. SmallString<256> Name;
  2261. llvm::raw_svector_ostream Out(Name);
  2262. CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
  2263. // We know that the mangled name of the type starts at index 4 of the
  2264. // mangled name of the typename, so we can just index into it in order to
  2265. // get the mangled name of the type.
  2266. llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
  2267. Name.substr(4));
  2268. auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
  2269. llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
  2270. Name, Init->getType(), Linkage, Align.getQuantity());
  2271. GV->setInitializer(Init);
  2272. return GV;
  2273. }
  2274. llvm::Constant *
  2275. ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
  2276. // Mangle the RTTI name.
  2277. SmallString<256> Name;
  2278. llvm::raw_svector_ostream Out(Name);
  2279. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
  2280. // Look for an existing global.
  2281. llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
  2282. if (!GV) {
  2283. // Create a new global variable.
  2284. // Note for the future: If we would ever like to do deferred emission of
  2285. // RTTI, check if emitting vtables opportunistically need any adjustment.
  2286. GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
  2287. /*Constant=*/true,
  2288. llvm::GlobalValue::ExternalLinkage, nullptr,
  2289. Name);
  2290. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  2291. CGM.setGVProperties(GV, RD);
  2292. }
  2293. return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
  2294. }
  2295. /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
  2296. /// info for that type is defined in the standard library.
  2297. static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
  2298. // Itanium C++ ABI 2.9.2:
  2299. // Basic type information (e.g. for "int", "bool", etc.) will be kept in
  2300. // the run-time support library. Specifically, the run-time support
  2301. // library should contain type_info objects for the types X, X* and
  2302. // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
  2303. // unsigned char, signed char, short, unsigned short, int, unsigned int,
  2304. // long, unsigned long, long long, unsigned long long, float, double,
  2305. // long double, char16_t, char32_t, and the IEEE 754r decimal and
  2306. // half-precision floating point types.
  2307. //
  2308. // GCC also emits RTTI for __int128.
  2309. // FIXME: We do not emit RTTI information for decimal types here.
  2310. // Types added here must also be added to EmitFundamentalRTTIDescriptors.
  2311. switch (Ty->getKind()) {
  2312. case BuiltinType::Void:
  2313. case BuiltinType::NullPtr:
  2314. case BuiltinType::Bool:
  2315. case BuiltinType::WChar_S:
  2316. case BuiltinType::WChar_U:
  2317. case BuiltinType::Char_U:
  2318. case BuiltinType::Char_S:
  2319. case BuiltinType::UChar:
  2320. case BuiltinType::SChar:
  2321. case BuiltinType::Short:
  2322. case BuiltinType::UShort:
  2323. case BuiltinType::Int:
  2324. case BuiltinType::UInt:
  2325. case BuiltinType::Long:
  2326. case BuiltinType::ULong:
  2327. case BuiltinType::LongLong:
  2328. case BuiltinType::ULongLong:
  2329. case BuiltinType::Half:
  2330. case BuiltinType::Float:
  2331. case BuiltinType::Double:
  2332. case BuiltinType::LongDouble:
  2333. case BuiltinType::Float16:
  2334. case BuiltinType::Float128:
  2335. case BuiltinType::Char8:
  2336. case BuiltinType::Char16:
  2337. case BuiltinType::Char32:
  2338. case BuiltinType::Int128:
  2339. case BuiltinType::UInt128:
  2340. return true;
  2341. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  2342. case BuiltinType::Id:
  2343. #include "clang/Basic/OpenCLImageTypes.def"
  2344. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  2345. case BuiltinType::Id:
  2346. #include "clang/Basic/OpenCLExtensionTypes.def"
  2347. case BuiltinType::OCLSampler:
  2348. case BuiltinType::OCLEvent:
  2349. case BuiltinType::OCLClkEvent:
  2350. case BuiltinType::OCLQueue:
  2351. case BuiltinType::OCLReserveID:
  2352. case BuiltinType::ShortAccum:
  2353. case BuiltinType::Accum:
  2354. case BuiltinType::LongAccum:
  2355. case BuiltinType::UShortAccum:
  2356. case BuiltinType::UAccum:
  2357. case BuiltinType::ULongAccum:
  2358. case BuiltinType::ShortFract:
  2359. case BuiltinType::Fract:
  2360. case BuiltinType::LongFract:
  2361. case BuiltinType::UShortFract:
  2362. case BuiltinType::UFract:
  2363. case BuiltinType::ULongFract:
  2364. case BuiltinType::SatShortAccum:
  2365. case BuiltinType::SatAccum:
  2366. case BuiltinType::SatLongAccum:
  2367. case BuiltinType::SatUShortAccum:
  2368. case BuiltinType::SatUAccum:
  2369. case BuiltinType::SatULongAccum:
  2370. case BuiltinType::SatShortFract:
  2371. case BuiltinType::SatFract:
  2372. case BuiltinType::SatLongFract:
  2373. case BuiltinType::SatUShortFract:
  2374. case BuiltinType::SatUFract:
  2375. case BuiltinType::SatULongFract:
  2376. return false;
  2377. case BuiltinType::Dependent:
  2378. #define BUILTIN_TYPE(Id, SingletonId)
  2379. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  2380. case BuiltinType::Id:
  2381. #include "clang/AST/BuiltinTypes.def"
  2382. llvm_unreachable("asking for RRTI for a placeholder type!");
  2383. case BuiltinType::ObjCId:
  2384. case BuiltinType::ObjCClass:
  2385. case BuiltinType::ObjCSel:
  2386. llvm_unreachable("FIXME: Objective-C types are unsupported!");
  2387. }
  2388. llvm_unreachable("Invalid BuiltinType Kind!");
  2389. }
  2390. static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
  2391. QualType PointeeTy = PointerTy->getPointeeType();
  2392. const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
  2393. if (!BuiltinTy)
  2394. return false;
  2395. // Check the qualifiers.
  2396. Qualifiers Quals = PointeeTy.getQualifiers();
  2397. Quals.removeConst();
  2398. if (!Quals.empty())
  2399. return false;
  2400. return TypeInfoIsInStandardLibrary(BuiltinTy);
  2401. }
  2402. /// IsStandardLibraryRTTIDescriptor - Returns whether the type
  2403. /// information for the given type exists in the standard library.
  2404. static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
  2405. // Type info for builtin types is defined in the standard library.
  2406. if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
  2407. return TypeInfoIsInStandardLibrary(BuiltinTy);
  2408. // Type info for some pointer types to builtin types is defined in the
  2409. // standard library.
  2410. if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
  2411. return TypeInfoIsInStandardLibrary(PointerTy);
  2412. return false;
  2413. }
  2414. /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
  2415. /// the given type exists somewhere else, and that we should not emit the type
  2416. /// information in this translation unit. Assumes that it is not a
  2417. /// standard-library type.
  2418. static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
  2419. QualType Ty) {
  2420. ASTContext &Context = CGM.getContext();
  2421. // If RTTI is disabled, assume it might be disabled in the
  2422. // translation unit that defines any potential key function, too.
  2423. if (!Context.getLangOpts().RTTI) return false;
  2424. if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
  2425. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  2426. if (!RD->hasDefinition())
  2427. return false;
  2428. if (!RD->isDynamicClass())
  2429. return false;
  2430. // FIXME: this may need to be reconsidered if the key function
  2431. // changes.
  2432. // N.B. We must always emit the RTTI data ourselves if there exists a key
  2433. // function.
  2434. bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
  2435. // Don't import the RTTI but emit it locally.
  2436. if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
  2437. return false;
  2438. if (CGM.getVTables().isVTableExternal(RD))
  2439. return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
  2440. ? false
  2441. : true;
  2442. if (IsDLLImport)
  2443. return true;
  2444. }
  2445. return false;
  2446. }
  2447. /// IsIncompleteClassType - Returns whether the given record type is incomplete.
  2448. static bool IsIncompleteClassType(const RecordType *RecordTy) {
  2449. return !RecordTy->getDecl()->isCompleteDefinition();
  2450. }
  2451. /// ContainsIncompleteClassType - Returns whether the given type contains an
  2452. /// incomplete class type. This is true if
  2453. ///
  2454. /// * The given type is an incomplete class type.
  2455. /// * The given type is a pointer type whose pointee type contains an
  2456. /// incomplete class type.
  2457. /// * The given type is a member pointer type whose class is an incomplete
  2458. /// class type.
  2459. /// * The given type is a member pointer type whoise pointee type contains an
  2460. /// incomplete class type.
  2461. /// is an indirect or direct pointer to an incomplete class type.
  2462. static bool ContainsIncompleteClassType(QualType Ty) {
  2463. if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
  2464. if (IsIncompleteClassType(RecordTy))
  2465. return true;
  2466. }
  2467. if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
  2468. return ContainsIncompleteClassType(PointerTy->getPointeeType());
  2469. if (const MemberPointerType *MemberPointerTy =
  2470. dyn_cast<MemberPointerType>(Ty)) {
  2471. // Check if the class type is incomplete.
  2472. const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
  2473. if (IsIncompleteClassType(ClassType))
  2474. return true;
  2475. return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
  2476. }
  2477. return false;
  2478. }
  2479. // CanUseSingleInheritance - Return whether the given record decl has a "single,
  2480. // public, non-virtual base at offset zero (i.e. the derived class is dynamic
  2481. // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
  2482. static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
  2483. // Check the number of bases.
  2484. if (RD->getNumBases() != 1)
  2485. return false;
  2486. // Get the base.
  2487. CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
  2488. // Check that the base is not virtual.
  2489. if (Base->isVirtual())
  2490. return false;
  2491. // Check that the base is public.
  2492. if (Base->getAccessSpecifier() != AS_public)
  2493. return false;
  2494. // Check that the class is dynamic iff the base is.
  2495. const CXXRecordDecl *BaseDecl =
  2496. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  2497. if (!BaseDecl->isEmpty() &&
  2498. BaseDecl->isDynamicClass() != RD->isDynamicClass())
  2499. return false;
  2500. return true;
  2501. }
  2502. void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
  2503. // abi::__class_type_info.
  2504. static const char * const ClassTypeInfo =
  2505. "_ZTVN10__cxxabiv117__class_type_infoE";
  2506. // abi::__si_class_type_info.
  2507. static const char * const SIClassTypeInfo =
  2508. "_ZTVN10__cxxabiv120__si_class_type_infoE";
  2509. // abi::__vmi_class_type_info.
  2510. static const char * const VMIClassTypeInfo =
  2511. "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
  2512. const char *VTableName = nullptr;
  2513. switch (Ty->getTypeClass()) {
  2514. #define TYPE(Class, Base)
  2515. #define ABSTRACT_TYPE(Class, Base)
  2516. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  2517. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  2518. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  2519. #include "clang/AST/TypeNodes.def"
  2520. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  2521. case Type::LValueReference:
  2522. case Type::RValueReference:
  2523. llvm_unreachable("References shouldn't get here");
  2524. case Type::Auto:
  2525. case Type::DeducedTemplateSpecialization:
  2526. llvm_unreachable("Undeduced type shouldn't get here");
  2527. case Type::Pipe:
  2528. llvm_unreachable("Pipe types shouldn't get here");
  2529. case Type::Builtin:
  2530. // GCC treats vector and complex types as fundamental types.
  2531. case Type::Vector:
  2532. case Type::ExtVector:
  2533. case Type::Complex:
  2534. case Type::Atomic:
  2535. // FIXME: GCC treats block pointers as fundamental types?!
  2536. case Type::BlockPointer:
  2537. // abi::__fundamental_type_info.
  2538. VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
  2539. break;
  2540. case Type::ConstantArray:
  2541. case Type::IncompleteArray:
  2542. case Type::VariableArray:
  2543. // abi::__array_type_info.
  2544. VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
  2545. break;
  2546. case Type::FunctionNoProto:
  2547. case Type::FunctionProto:
  2548. // abi::__function_type_info.
  2549. VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
  2550. break;
  2551. case Type::Enum:
  2552. // abi::__enum_type_info.
  2553. VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
  2554. break;
  2555. case Type::Record: {
  2556. const CXXRecordDecl *RD =
  2557. cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
  2558. if (!RD->hasDefinition() || !RD->getNumBases()) {
  2559. VTableName = ClassTypeInfo;
  2560. } else if (CanUseSingleInheritance(RD)) {
  2561. VTableName = SIClassTypeInfo;
  2562. } else {
  2563. VTableName = VMIClassTypeInfo;
  2564. }
  2565. break;
  2566. }
  2567. case Type::ObjCObject:
  2568. // Ignore protocol qualifiers.
  2569. Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
  2570. // Handle id and Class.
  2571. if (isa<BuiltinType>(Ty)) {
  2572. VTableName = ClassTypeInfo;
  2573. break;
  2574. }
  2575. assert(isa<ObjCInterfaceType>(Ty));
  2576. LLVM_FALLTHROUGH;
  2577. case Type::ObjCInterface:
  2578. if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
  2579. VTableName = SIClassTypeInfo;
  2580. } else {
  2581. VTableName = ClassTypeInfo;
  2582. }
  2583. break;
  2584. case Type::ObjCObjectPointer:
  2585. case Type::Pointer:
  2586. // abi::__pointer_type_info.
  2587. VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
  2588. break;
  2589. case Type::MemberPointer:
  2590. // abi::__pointer_to_member_type_info.
  2591. VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
  2592. break;
  2593. }
  2594. llvm::Constant *VTable =
  2595. CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
  2596. CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
  2597. llvm::Type *PtrDiffTy =
  2598. CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
  2599. // The vtable address point is 2.
  2600. llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
  2601. VTable =
  2602. llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
  2603. VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
  2604. Fields.push_back(VTable);
  2605. }
  2606. /// Return the linkage that the type info and type info name constants
  2607. /// should have for the given type.
  2608. static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
  2609. QualType Ty) {
  2610. // Itanium C++ ABI 2.9.5p7:
  2611. // In addition, it and all of the intermediate abi::__pointer_type_info
  2612. // structs in the chain down to the abi::__class_type_info for the
  2613. // incomplete class type must be prevented from resolving to the
  2614. // corresponding type_info structs for the complete class type, possibly
  2615. // by making them local static objects. Finally, a dummy class RTTI is
  2616. // generated for the incomplete type that will not resolve to the final
  2617. // complete class RTTI (because the latter need not exist), possibly by
  2618. // making it a local static object.
  2619. if (ContainsIncompleteClassType(Ty))
  2620. return llvm::GlobalValue::InternalLinkage;
  2621. switch (Ty->getLinkage()) {
  2622. case NoLinkage:
  2623. case InternalLinkage:
  2624. case UniqueExternalLinkage:
  2625. return llvm::GlobalValue::InternalLinkage;
  2626. case VisibleNoLinkage:
  2627. case ModuleInternalLinkage:
  2628. case ModuleLinkage:
  2629. case ExternalLinkage:
  2630. // RTTI is not enabled, which means that this type info struct is going
  2631. // to be used for exception handling. Give it linkonce_odr linkage.
  2632. if (!CGM.getLangOpts().RTTI)
  2633. return llvm::GlobalValue::LinkOnceODRLinkage;
  2634. if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
  2635. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2636. if (RD->hasAttr<WeakAttr>())
  2637. return llvm::GlobalValue::WeakODRLinkage;
  2638. if (CGM.getTriple().isWindowsItaniumEnvironment())
  2639. if (RD->hasAttr<DLLImportAttr>() &&
  2640. ShouldUseExternalRTTIDescriptor(CGM, Ty))
  2641. return llvm::GlobalValue::ExternalLinkage;
  2642. // MinGW always uses LinkOnceODRLinkage for type info.
  2643. if (RD->isDynamicClass() &&
  2644. !CGM.getContext()
  2645. .getTargetInfo()
  2646. .getTriple()
  2647. .isWindowsGNUEnvironment())
  2648. return CGM.getVTableLinkage(RD);
  2649. }
  2650. return llvm::GlobalValue::LinkOnceODRLinkage;
  2651. }
  2652. llvm_unreachable("Invalid linkage!");
  2653. }
  2654. llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
  2655. // We want to operate on the canonical type.
  2656. Ty = Ty.getCanonicalType();
  2657. // Check if we've already emitted an RTTI descriptor for this type.
  2658. SmallString<256> Name;
  2659. llvm::raw_svector_ostream Out(Name);
  2660. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
  2661. llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
  2662. if (OldGV && !OldGV->isDeclaration()) {
  2663. assert(!OldGV->hasAvailableExternallyLinkage() &&
  2664. "available_externally typeinfos not yet implemented");
  2665. return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
  2666. }
  2667. // Check if there is already an external RTTI descriptor for this type.
  2668. if (IsStandardLibraryRTTIDescriptor(Ty) ||
  2669. ShouldUseExternalRTTIDescriptor(CGM, Ty))
  2670. return GetAddrOfExternalRTTIDescriptor(Ty);
  2671. // Emit the standard library with external linkage.
  2672. llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
  2673. // Give the type_info object and name the formal visibility of the
  2674. // type itself.
  2675. llvm::GlobalValue::VisibilityTypes llvmVisibility;
  2676. if (llvm::GlobalValue::isLocalLinkage(Linkage))
  2677. // If the linkage is local, only default visibility makes sense.
  2678. llvmVisibility = llvm::GlobalValue::DefaultVisibility;
  2679. else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
  2680. ItaniumCXXABI::RUK_NonUniqueHidden)
  2681. llvmVisibility = llvm::GlobalValue::HiddenVisibility;
  2682. else
  2683. llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
  2684. llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
  2685. llvm::GlobalValue::DefaultStorageClass;
  2686. if (CGM.getTriple().isWindowsItaniumEnvironment()) {
  2687. auto RD = Ty->getAsCXXRecordDecl();
  2688. if (RD && RD->hasAttr<DLLExportAttr>())
  2689. DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
  2690. }
  2691. return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
  2692. }
  2693. llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
  2694. QualType Ty,
  2695. llvm::GlobalVariable::LinkageTypes Linkage,
  2696. llvm::GlobalValue::VisibilityTypes Visibility,
  2697. llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
  2698. // Add the vtable pointer.
  2699. BuildVTablePointer(cast<Type>(Ty));
  2700. // And the name.
  2701. llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
  2702. llvm::Constant *TypeNameField;
  2703. // If we're supposed to demote the visibility, be sure to set a flag
  2704. // to use a string comparison for type_info comparisons.
  2705. ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
  2706. CXXABI.classifyRTTIUniqueness(Ty, Linkage);
  2707. if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
  2708. // The flag is the sign bit, which on ARM64 is defined to be clear
  2709. // for global pointers. This is very ARM64-specific.
  2710. TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
  2711. llvm::Constant *flag =
  2712. llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
  2713. TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
  2714. TypeNameField =
  2715. llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
  2716. } else {
  2717. TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
  2718. }
  2719. Fields.push_back(TypeNameField);
  2720. switch (Ty->getTypeClass()) {
  2721. #define TYPE(Class, Base)
  2722. #define ABSTRACT_TYPE(Class, Base)
  2723. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  2724. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  2725. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  2726. #include "clang/AST/TypeNodes.def"
  2727. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  2728. // GCC treats vector types as fundamental types.
  2729. case Type::Builtin:
  2730. case Type::Vector:
  2731. case Type::ExtVector:
  2732. case Type::Complex:
  2733. case Type::BlockPointer:
  2734. // Itanium C++ ABI 2.9.5p4:
  2735. // abi::__fundamental_type_info adds no data members to std::type_info.
  2736. break;
  2737. case Type::LValueReference:
  2738. case Type::RValueReference:
  2739. llvm_unreachable("References shouldn't get here");
  2740. case Type::Auto:
  2741. case Type::DeducedTemplateSpecialization:
  2742. llvm_unreachable("Undeduced type shouldn't get here");
  2743. case Type::Pipe:
  2744. llvm_unreachable("Pipe type shouldn't get here");
  2745. case Type::ConstantArray:
  2746. case Type::IncompleteArray:
  2747. case Type::VariableArray:
  2748. // Itanium C++ ABI 2.9.5p5:
  2749. // abi::__array_type_info adds no data members to std::type_info.
  2750. break;
  2751. case Type::FunctionNoProto:
  2752. case Type::FunctionProto:
  2753. // Itanium C++ ABI 2.9.5p5:
  2754. // abi::__function_type_info adds no data members to std::type_info.
  2755. break;
  2756. case Type::Enum:
  2757. // Itanium C++ ABI 2.9.5p5:
  2758. // abi::__enum_type_info adds no data members to std::type_info.
  2759. break;
  2760. case Type::Record: {
  2761. const CXXRecordDecl *RD =
  2762. cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
  2763. if (!RD->hasDefinition() || !RD->getNumBases()) {
  2764. // We don't need to emit any fields.
  2765. break;
  2766. }
  2767. if (CanUseSingleInheritance(RD))
  2768. BuildSIClassTypeInfo(RD);
  2769. else
  2770. BuildVMIClassTypeInfo(RD);
  2771. break;
  2772. }
  2773. case Type::ObjCObject:
  2774. case Type::ObjCInterface:
  2775. BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
  2776. break;
  2777. case Type::ObjCObjectPointer:
  2778. BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
  2779. break;
  2780. case Type::Pointer:
  2781. BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
  2782. break;
  2783. case Type::MemberPointer:
  2784. BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
  2785. break;
  2786. case Type::Atomic:
  2787. // No fields, at least for the moment.
  2788. break;
  2789. }
  2790. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
  2791. SmallString<256> Name;
  2792. llvm::raw_svector_ostream Out(Name);
  2793. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
  2794. llvm::Module &M = CGM.getModule();
  2795. llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
  2796. llvm::GlobalVariable *GV =
  2797. new llvm::GlobalVariable(M, Init->getType(),
  2798. /*Constant=*/true, Linkage, Init, Name);
  2799. // If there's already an old global variable, replace it with the new one.
  2800. if (OldGV) {
  2801. GV->takeName(OldGV);
  2802. llvm::Constant *NewPtr =
  2803. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  2804. OldGV->replaceAllUsesWith(NewPtr);
  2805. OldGV->eraseFromParent();
  2806. }
  2807. if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
  2808. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  2809. CharUnits Align =
  2810. CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0));
  2811. GV->setAlignment(Align.getQuantity());
  2812. // The Itanium ABI specifies that type_info objects must be globally
  2813. // unique, with one exception: if the type is an incomplete class
  2814. // type or a (possibly indirect) pointer to one. That exception
  2815. // affects the general case of comparing type_info objects produced
  2816. // by the typeid operator, which is why the comparison operators on
  2817. // std::type_info generally use the type_info name pointers instead
  2818. // of the object addresses. However, the language's built-in uses
  2819. // of RTTI generally require class types to be complete, even when
  2820. // manipulating pointers to those class types. This allows the
  2821. // implementation of dynamic_cast to rely on address equality tests,
  2822. // which is much faster.
  2823. // All of this is to say that it's important that both the type_info
  2824. // object and the type_info name be uniqued when weakly emitted.
  2825. TypeName->setVisibility(Visibility);
  2826. CGM.setDSOLocal(TypeName);
  2827. GV->setVisibility(Visibility);
  2828. CGM.setDSOLocal(GV);
  2829. TypeName->setDLLStorageClass(DLLStorageClass);
  2830. GV->setDLLStorageClass(DLLStorageClass);
  2831. return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
  2832. }
  2833. /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
  2834. /// for the given Objective-C object type.
  2835. void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
  2836. // Drop qualifiers.
  2837. const Type *T = OT->getBaseType().getTypePtr();
  2838. assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
  2839. // The builtin types are abi::__class_type_infos and don't require
  2840. // extra fields.
  2841. if (isa<BuiltinType>(T)) return;
  2842. ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
  2843. ObjCInterfaceDecl *Super = Class->getSuperClass();
  2844. // Root classes are also __class_type_info.
  2845. if (!Super) return;
  2846. QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
  2847. // Everything else is single inheritance.
  2848. llvm::Constant *BaseTypeInfo =
  2849. ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
  2850. Fields.push_back(BaseTypeInfo);
  2851. }
  2852. /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
  2853. /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
  2854. void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
  2855. // Itanium C++ ABI 2.9.5p6b:
  2856. // It adds to abi::__class_type_info a single member pointing to the
  2857. // type_info structure for the base type,
  2858. llvm::Constant *BaseTypeInfo =
  2859. ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
  2860. Fields.push_back(BaseTypeInfo);
  2861. }
  2862. namespace {
  2863. /// SeenBases - Contains virtual and non-virtual bases seen when traversing
  2864. /// a class hierarchy.
  2865. struct SeenBases {
  2866. llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
  2867. llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
  2868. };
  2869. }
  2870. /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
  2871. /// abi::__vmi_class_type_info.
  2872. ///
  2873. static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
  2874. SeenBases &Bases) {
  2875. unsigned Flags = 0;
  2876. const CXXRecordDecl *BaseDecl =
  2877. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  2878. if (Base->isVirtual()) {
  2879. // Mark the virtual base as seen.
  2880. if (!Bases.VirtualBases.insert(BaseDecl).second) {
  2881. // If this virtual base has been seen before, then the class is diamond
  2882. // shaped.
  2883. Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
  2884. } else {
  2885. if (Bases.NonVirtualBases.count(BaseDecl))
  2886. Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
  2887. }
  2888. } else {
  2889. // Mark the non-virtual base as seen.
  2890. if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
  2891. // If this non-virtual base has been seen before, then the class has non-
  2892. // diamond shaped repeated inheritance.
  2893. Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
  2894. } else {
  2895. if (Bases.VirtualBases.count(BaseDecl))
  2896. Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
  2897. }
  2898. }
  2899. // Walk all bases.
  2900. for (const auto &I : BaseDecl->bases())
  2901. Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
  2902. return Flags;
  2903. }
  2904. static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
  2905. unsigned Flags = 0;
  2906. SeenBases Bases;
  2907. // Walk all bases.
  2908. for (const auto &I : RD->bases())
  2909. Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
  2910. return Flags;
  2911. }
  2912. /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
  2913. /// classes with bases that do not satisfy the abi::__si_class_type_info
  2914. /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
  2915. void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
  2916. llvm::Type *UnsignedIntLTy =
  2917. CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
  2918. // Itanium C++ ABI 2.9.5p6c:
  2919. // __flags is a word with flags describing details about the class
  2920. // structure, which may be referenced by using the __flags_masks
  2921. // enumeration. These flags refer to both direct and indirect bases.
  2922. unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
  2923. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
  2924. // Itanium C++ ABI 2.9.5p6c:
  2925. // __base_count is a word with the number of direct proper base class
  2926. // descriptions that follow.
  2927. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
  2928. if (!RD->getNumBases())
  2929. return;
  2930. // Now add the base class descriptions.
  2931. // Itanium C++ ABI 2.9.5p6c:
  2932. // __base_info[] is an array of base class descriptions -- one for every
  2933. // direct proper base. Each description is of the type:
  2934. //
  2935. // struct abi::__base_class_type_info {
  2936. // public:
  2937. // const __class_type_info *__base_type;
  2938. // long __offset_flags;
  2939. //
  2940. // enum __offset_flags_masks {
  2941. // __virtual_mask = 0x1,
  2942. // __public_mask = 0x2,
  2943. // __offset_shift = 8
  2944. // };
  2945. // };
  2946. // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
  2947. // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
  2948. // LLP64 platforms.
  2949. // FIXME: Consider updating libc++abi to match, and extend this logic to all
  2950. // LLP64 platforms.
  2951. QualType OffsetFlagsTy = CGM.getContext().LongTy;
  2952. const TargetInfo &TI = CGM.getContext().getTargetInfo();
  2953. if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
  2954. OffsetFlagsTy = CGM.getContext().LongLongTy;
  2955. llvm::Type *OffsetFlagsLTy =
  2956. CGM.getTypes().ConvertType(OffsetFlagsTy);
  2957. for (const auto &Base : RD->bases()) {
  2958. // The __base_type member points to the RTTI for the base type.
  2959. Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
  2960. const CXXRecordDecl *BaseDecl =
  2961. cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  2962. int64_t OffsetFlags = 0;
  2963. // All but the lower 8 bits of __offset_flags are a signed offset.
  2964. // For a non-virtual base, this is the offset in the object of the base
  2965. // subobject. For a virtual base, this is the offset in the virtual table of
  2966. // the virtual base offset for the virtual base referenced (negative).
  2967. CharUnits Offset;
  2968. if (Base.isVirtual())
  2969. Offset =
  2970. CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
  2971. else {
  2972. const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
  2973. Offset = Layout.getBaseClassOffset(BaseDecl);
  2974. };
  2975. OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
  2976. // The low-order byte of __offset_flags contains flags, as given by the
  2977. // masks from the enumeration __offset_flags_masks.
  2978. if (Base.isVirtual())
  2979. OffsetFlags |= BCTI_Virtual;
  2980. if (Base.getAccessSpecifier() == AS_public)
  2981. OffsetFlags |= BCTI_Public;
  2982. Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
  2983. }
  2984. }
  2985. /// Compute the flags for a __pbase_type_info, and remove the corresponding
  2986. /// pieces from \p Type.
  2987. static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
  2988. unsigned Flags = 0;
  2989. if (Type.isConstQualified())
  2990. Flags |= ItaniumRTTIBuilder::PTI_Const;
  2991. if (Type.isVolatileQualified())
  2992. Flags |= ItaniumRTTIBuilder::PTI_Volatile;
  2993. if (Type.isRestrictQualified())
  2994. Flags |= ItaniumRTTIBuilder::PTI_Restrict;
  2995. Type = Type.getUnqualifiedType();
  2996. // Itanium C++ ABI 2.9.5p7:
  2997. // When the abi::__pbase_type_info is for a direct or indirect pointer to an
  2998. // incomplete class type, the incomplete target type flag is set.
  2999. if (ContainsIncompleteClassType(Type))
  3000. Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
  3001. if (auto *Proto = Type->getAs<FunctionProtoType>()) {
  3002. if (Proto->isNothrow()) {
  3003. Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
  3004. Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
  3005. }
  3006. }
  3007. return Flags;
  3008. }
  3009. /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
  3010. /// used for pointer types.
  3011. void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
  3012. // Itanium C++ ABI 2.9.5p7:
  3013. // __flags is a flag word describing the cv-qualification and other
  3014. // attributes of the type pointed to
  3015. unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
  3016. llvm::Type *UnsignedIntLTy =
  3017. CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
  3018. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
  3019. // Itanium C++ ABI 2.9.5p7:
  3020. // __pointee is a pointer to the std::type_info derivation for the
  3021. // unqualified type being pointed to.
  3022. llvm::Constant *PointeeTypeInfo =
  3023. ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
  3024. Fields.push_back(PointeeTypeInfo);
  3025. }
  3026. /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
  3027. /// struct, used for member pointer types.
  3028. void
  3029. ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
  3030. QualType PointeeTy = Ty->getPointeeType();
  3031. // Itanium C++ ABI 2.9.5p7:
  3032. // __flags is a flag word describing the cv-qualification and other
  3033. // attributes of the type pointed to.
  3034. unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
  3035. const RecordType *ClassType = cast<RecordType>(Ty->getClass());
  3036. if (IsIncompleteClassType(ClassType))
  3037. Flags |= PTI_ContainingClassIncomplete;
  3038. llvm::Type *UnsignedIntLTy =
  3039. CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
  3040. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
  3041. // Itanium C++ ABI 2.9.5p7:
  3042. // __pointee is a pointer to the std::type_info derivation for the
  3043. // unqualified type being pointed to.
  3044. llvm::Constant *PointeeTypeInfo =
  3045. ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
  3046. Fields.push_back(PointeeTypeInfo);
  3047. // Itanium C++ ABI 2.9.5p9:
  3048. // __context is a pointer to an abi::__class_type_info corresponding to the
  3049. // class type containing the member pointed to
  3050. // (e.g., the "A" in "int A::*").
  3051. Fields.push_back(
  3052. ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
  3053. }
  3054. llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
  3055. return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
  3056. }
  3057. void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
  3058. // Types added here must also be added to TypeInfoIsInStandardLibrary.
  3059. QualType FundamentalTypes[] = {
  3060. getContext().VoidTy, getContext().NullPtrTy,
  3061. getContext().BoolTy, getContext().WCharTy,
  3062. getContext().CharTy, getContext().UnsignedCharTy,
  3063. getContext().SignedCharTy, getContext().ShortTy,
  3064. getContext().UnsignedShortTy, getContext().IntTy,
  3065. getContext().UnsignedIntTy, getContext().LongTy,
  3066. getContext().UnsignedLongTy, getContext().LongLongTy,
  3067. getContext().UnsignedLongLongTy, getContext().Int128Ty,
  3068. getContext().UnsignedInt128Ty, getContext().HalfTy,
  3069. getContext().FloatTy, getContext().DoubleTy,
  3070. getContext().LongDoubleTy, getContext().Float128Ty,
  3071. getContext().Char8Ty, getContext().Char16Ty,
  3072. getContext().Char32Ty
  3073. };
  3074. llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
  3075. RD->hasAttr<DLLExportAttr>()
  3076. ? llvm::GlobalValue::DLLExportStorageClass
  3077. : llvm::GlobalValue::DefaultStorageClass;
  3078. llvm::GlobalValue::VisibilityTypes Visibility =
  3079. CodeGenModule::GetLLVMVisibility(RD->getVisibility());
  3080. for (const QualType &FundamentalType : FundamentalTypes) {
  3081. QualType PointerType = getContext().getPointerType(FundamentalType);
  3082. QualType PointerTypeConst = getContext().getPointerType(
  3083. FundamentalType.withConst());
  3084. for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
  3085. ItaniumRTTIBuilder(*this).BuildTypeInfo(
  3086. Type, llvm::GlobalValue::ExternalLinkage,
  3087. Visibility, DLLStorageClass);
  3088. }
  3089. }
  3090. /// What sort of uniqueness rules should we use for the RTTI for the
  3091. /// given type?
  3092. ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
  3093. QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
  3094. if (shouldRTTIBeUnique())
  3095. return RUK_Unique;
  3096. // It's only necessary for linkonce_odr or weak_odr linkage.
  3097. if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
  3098. Linkage != llvm::GlobalValue::WeakODRLinkage)
  3099. return RUK_Unique;
  3100. // It's only necessary with default visibility.
  3101. if (CanTy->getVisibility() != DefaultVisibility)
  3102. return RUK_Unique;
  3103. // If we're not required to publish this symbol, hide it.
  3104. if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
  3105. return RUK_NonUniqueHidden;
  3106. // If we're required to publish this symbol, as we might be under an
  3107. // explicit instantiation, leave it with default visibility but
  3108. // enable string-comparisons.
  3109. assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
  3110. return RUK_NonUniqueVisible;
  3111. }
  3112. // Find out how to codegen the complete destructor and constructor
  3113. namespace {
  3114. enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
  3115. }
  3116. static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
  3117. const CXXMethodDecl *MD) {
  3118. if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
  3119. return StructorCodegen::Emit;
  3120. // The complete and base structors are not equivalent if there are any virtual
  3121. // bases, so emit separate functions.
  3122. if (MD->getParent()->getNumVBases())
  3123. return StructorCodegen::Emit;
  3124. GlobalDecl AliasDecl;
  3125. if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  3126. AliasDecl = GlobalDecl(DD, Dtor_Complete);
  3127. } else {
  3128. const auto *CD = cast<CXXConstructorDecl>(MD);
  3129. AliasDecl = GlobalDecl(CD, Ctor_Complete);
  3130. }
  3131. llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
  3132. if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
  3133. return StructorCodegen::RAUW;
  3134. // FIXME: Should we allow available_externally aliases?
  3135. if (!llvm::GlobalAlias::isValidLinkage(Linkage))
  3136. return StructorCodegen::RAUW;
  3137. if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
  3138. // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
  3139. if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
  3140. CGM.getTarget().getTriple().isOSBinFormatWasm())
  3141. return StructorCodegen::COMDAT;
  3142. return StructorCodegen::Emit;
  3143. }
  3144. return StructorCodegen::Alias;
  3145. }
  3146. static void emitConstructorDestructorAlias(CodeGenModule &CGM,
  3147. GlobalDecl AliasDecl,
  3148. GlobalDecl TargetDecl) {
  3149. llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
  3150. StringRef MangledName = CGM.getMangledName(AliasDecl);
  3151. llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
  3152. if (Entry && !Entry->isDeclaration())
  3153. return;
  3154. auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
  3155. // Create the alias with no name.
  3156. auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
  3157. // Constructors and destructors are always unnamed_addr.
  3158. Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3159. // Switch any previous uses to the alias.
  3160. if (Entry) {
  3161. assert(Entry->getType() == Aliasee->getType() &&
  3162. "declaration exists with different type");
  3163. Alias->takeName(Entry);
  3164. Entry->replaceAllUsesWith(Alias);
  3165. Entry->eraseFromParent();
  3166. } else {
  3167. Alias->setName(MangledName);
  3168. }
  3169. // Finally, set up the alias with its proper name and attributes.
  3170. CGM.SetCommonAttributes(AliasDecl, Alias);
  3171. }
  3172. void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
  3173. StructorType Type) {
  3174. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  3175. const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
  3176. StructorCodegen CGType = getCodegenToUse(CGM, MD);
  3177. if (Type == StructorType::Complete) {
  3178. GlobalDecl CompleteDecl;
  3179. GlobalDecl BaseDecl;
  3180. if (CD) {
  3181. CompleteDecl = GlobalDecl(CD, Ctor_Complete);
  3182. BaseDecl = GlobalDecl(CD, Ctor_Base);
  3183. } else {
  3184. CompleteDecl = GlobalDecl(DD, Dtor_Complete);
  3185. BaseDecl = GlobalDecl(DD, Dtor_Base);
  3186. }
  3187. if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
  3188. emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
  3189. return;
  3190. }
  3191. if (CGType == StructorCodegen::RAUW) {
  3192. StringRef MangledName = CGM.getMangledName(CompleteDecl);
  3193. auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
  3194. CGM.addReplacement(MangledName, Aliasee);
  3195. return;
  3196. }
  3197. }
  3198. // The base destructor is equivalent to the base destructor of its
  3199. // base class if there is exactly one non-virtual base class with a
  3200. // non-trivial destructor, there are no fields with a non-trivial
  3201. // destructor, and the body of the destructor is trivial.
  3202. if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
  3203. !CGM.TryEmitBaseDestructorAsAlias(DD))
  3204. return;
  3205. // FIXME: The deleting destructor is equivalent to the selected operator
  3206. // delete if:
  3207. // * either the delete is a destroying operator delete or the destructor
  3208. // would be trivial if it weren't virtual,
  3209. // * the conversion from the 'this' parameter to the first parameter of the
  3210. // destructor is equivalent to a bitcast,
  3211. // * the destructor does not have an implicit "this" return, and
  3212. // * the operator delete has the same calling convention and IR function type
  3213. // as the destructor.
  3214. // In such cases we should try to emit the deleting dtor as an alias to the
  3215. // selected 'operator delete'.
  3216. llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
  3217. if (CGType == StructorCodegen::COMDAT) {
  3218. SmallString<256> Buffer;
  3219. llvm::raw_svector_ostream Out(Buffer);
  3220. if (DD)
  3221. getMangleContext().mangleCXXDtorComdat(DD, Out);
  3222. else
  3223. getMangleContext().mangleCXXCtorComdat(CD, Out);
  3224. llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
  3225. Fn->setComdat(C);
  3226. } else {
  3227. CGM.maybeSetTrivialComdat(*MD, *Fn);
  3228. }
  3229. }
  3230. static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
  3231. // void *__cxa_begin_catch(void*);
  3232. llvm::FunctionType *FTy = llvm::FunctionType::get(
  3233. CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
  3234. return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
  3235. }
  3236. static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
  3237. // void __cxa_end_catch();
  3238. llvm::FunctionType *FTy =
  3239. llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
  3240. return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
  3241. }
  3242. static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
  3243. // void *__cxa_get_exception_ptr(void*);
  3244. llvm::FunctionType *FTy = llvm::FunctionType::get(
  3245. CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
  3246. return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
  3247. }
  3248. namespace {
  3249. /// A cleanup to call __cxa_end_catch. In many cases, the caught
  3250. /// exception type lets us state definitively that the thrown exception
  3251. /// type does not have a destructor. In particular:
  3252. /// - Catch-alls tell us nothing, so we have to conservatively
  3253. /// assume that the thrown exception might have a destructor.
  3254. /// - Catches by reference behave according to their base types.
  3255. /// - Catches of non-record types will only trigger for exceptions
  3256. /// of non-record types, which never have destructors.
  3257. /// - Catches of record types can trigger for arbitrary subclasses
  3258. /// of the caught type, so we have to assume the actual thrown
  3259. /// exception type might have a throwing destructor, even if the
  3260. /// caught type's destructor is trivial or nothrow.
  3261. struct CallEndCatch final : EHScopeStack::Cleanup {
  3262. CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
  3263. bool MightThrow;
  3264. void Emit(CodeGenFunction &CGF, Flags flags) override {
  3265. if (!MightThrow) {
  3266. CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
  3267. return;
  3268. }
  3269. CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
  3270. }
  3271. };
  3272. }
  3273. /// Emits a call to __cxa_begin_catch and enters a cleanup to call
  3274. /// __cxa_end_catch.
  3275. ///
  3276. /// \param EndMightThrow - true if __cxa_end_catch might throw
  3277. static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
  3278. llvm::Value *Exn,
  3279. bool EndMightThrow) {
  3280. llvm::CallInst *call =
  3281. CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
  3282. CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
  3283. return call;
  3284. }
  3285. /// A "special initializer" callback for initializing a catch
  3286. /// parameter during catch initialization.
  3287. static void InitCatchParam(CodeGenFunction &CGF,
  3288. const VarDecl &CatchParam,
  3289. Address ParamAddr,
  3290. SourceLocation Loc) {
  3291. // Load the exception from where the landing pad saved it.
  3292. llvm::Value *Exn = CGF.getExceptionFromSlot();
  3293. CanQualType CatchType =
  3294. CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
  3295. llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
  3296. // If we're catching by reference, we can just cast the object
  3297. // pointer to the appropriate pointer.
  3298. if (isa<ReferenceType>(CatchType)) {
  3299. QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
  3300. bool EndCatchMightThrow = CaughtType->isRecordType();
  3301. // __cxa_begin_catch returns the adjusted object pointer.
  3302. llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
  3303. // We have no way to tell the personality function that we're
  3304. // catching by reference, so if we're catching a pointer,
  3305. // __cxa_begin_catch will actually return that pointer by value.
  3306. if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
  3307. QualType PointeeType = PT->getPointeeType();
  3308. // When catching by reference, generally we should just ignore
  3309. // this by-value pointer and use the exception object instead.
  3310. if (!PointeeType->isRecordType()) {
  3311. // Exn points to the struct _Unwind_Exception header, which
  3312. // we have to skip past in order to reach the exception data.
  3313. unsigned HeaderSize =
  3314. CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
  3315. AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
  3316. // However, if we're catching a pointer-to-record type that won't
  3317. // work, because the personality function might have adjusted
  3318. // the pointer. There's actually no way for us to fully satisfy
  3319. // the language/ABI contract here: we can't use Exn because it
  3320. // might have the wrong adjustment, but we can't use the by-value
  3321. // pointer because it's off by a level of abstraction.
  3322. //
  3323. // The current solution is to dump the adjusted pointer into an
  3324. // alloca, which breaks language semantics (because changing the
  3325. // pointer doesn't change the exception) but at least works.
  3326. // The better solution would be to filter out non-exact matches
  3327. // and rethrow them, but this is tricky because the rethrow
  3328. // really needs to be catchable by other sites at this landing
  3329. // pad. The best solution is to fix the personality function.
  3330. } else {
  3331. // Pull the pointer for the reference type off.
  3332. llvm::Type *PtrTy =
  3333. cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
  3334. // Create the temporary and write the adjusted pointer into it.
  3335. Address ExnPtrTmp =
  3336. CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
  3337. llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
  3338. CGF.Builder.CreateStore(Casted, ExnPtrTmp);
  3339. // Bind the reference to the temporary.
  3340. AdjustedExn = ExnPtrTmp.getPointer();
  3341. }
  3342. }
  3343. llvm::Value *ExnCast =
  3344. CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
  3345. CGF.Builder.CreateStore(ExnCast, ParamAddr);
  3346. return;
  3347. }
  3348. // Scalars and complexes.
  3349. TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
  3350. if (TEK != TEK_Aggregate) {
  3351. llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
  3352. // If the catch type is a pointer type, __cxa_begin_catch returns
  3353. // the pointer by value.
  3354. if (CatchType->hasPointerRepresentation()) {
  3355. llvm::Value *CastExn =
  3356. CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
  3357. switch (CatchType.getQualifiers().getObjCLifetime()) {
  3358. case Qualifiers::OCL_Strong:
  3359. CastExn = CGF.EmitARCRetainNonBlock(CastExn);
  3360. LLVM_FALLTHROUGH;
  3361. case Qualifiers::OCL_None:
  3362. case Qualifiers::OCL_ExplicitNone:
  3363. case Qualifiers::OCL_Autoreleasing:
  3364. CGF.Builder.CreateStore(CastExn, ParamAddr);
  3365. return;
  3366. case Qualifiers::OCL_Weak:
  3367. CGF.EmitARCInitWeak(ParamAddr, CastExn);
  3368. return;
  3369. }
  3370. llvm_unreachable("bad ownership qualifier!");
  3371. }
  3372. // Otherwise, it returns a pointer into the exception object.
  3373. llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
  3374. llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
  3375. LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
  3376. LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
  3377. switch (TEK) {
  3378. case TEK_Complex:
  3379. CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
  3380. /*init*/ true);
  3381. return;
  3382. case TEK_Scalar: {
  3383. llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
  3384. CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
  3385. return;
  3386. }
  3387. case TEK_Aggregate:
  3388. llvm_unreachable("evaluation kind filtered out!");
  3389. }
  3390. llvm_unreachable("bad evaluation kind");
  3391. }
  3392. assert(isa<RecordType>(CatchType) && "unexpected catch type!");
  3393. auto catchRD = CatchType->getAsCXXRecordDecl();
  3394. CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
  3395. llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
  3396. // Check for a copy expression. If we don't have a copy expression,
  3397. // that means a trivial copy is okay.
  3398. const Expr *copyExpr = CatchParam.getInit();
  3399. if (!copyExpr) {
  3400. llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
  3401. Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
  3402. caughtExnAlignment);
  3403. LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
  3404. LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
  3405. CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
  3406. return;
  3407. }
  3408. // We have to call __cxa_get_exception_ptr to get the adjusted
  3409. // pointer before copying.
  3410. llvm::CallInst *rawAdjustedExn =
  3411. CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
  3412. // Cast that to the appropriate type.
  3413. Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
  3414. caughtExnAlignment);
  3415. // The copy expression is defined in terms of an OpaqueValueExpr.
  3416. // Find it and map it to the adjusted expression.
  3417. CodeGenFunction::OpaqueValueMapping
  3418. opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
  3419. CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
  3420. // Call the copy ctor in a terminate scope.
  3421. CGF.EHStack.pushTerminate();
  3422. // Perform the copy construction.
  3423. CGF.EmitAggExpr(copyExpr,
  3424. AggValueSlot::forAddr(ParamAddr, Qualifiers(),
  3425. AggValueSlot::IsNotDestructed,
  3426. AggValueSlot::DoesNotNeedGCBarriers,
  3427. AggValueSlot::IsNotAliased,
  3428. AggValueSlot::DoesNotOverlap));
  3429. // Leave the terminate scope.
  3430. CGF.EHStack.popTerminate();
  3431. // Undo the opaque value mapping.
  3432. opaque.pop();
  3433. // Finally we can call __cxa_begin_catch.
  3434. CallBeginCatch(CGF, Exn, true);
  3435. }
  3436. /// Begins a catch statement by initializing the catch variable and
  3437. /// calling __cxa_begin_catch.
  3438. void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
  3439. const CXXCatchStmt *S) {
  3440. // We have to be very careful with the ordering of cleanups here:
  3441. // C++ [except.throw]p4:
  3442. // The destruction [of the exception temporary] occurs
  3443. // immediately after the destruction of the object declared in
  3444. // the exception-declaration in the handler.
  3445. //
  3446. // So the precise ordering is:
  3447. // 1. Construct catch variable.
  3448. // 2. __cxa_begin_catch
  3449. // 3. Enter __cxa_end_catch cleanup
  3450. // 4. Enter dtor cleanup
  3451. //
  3452. // We do this by using a slightly abnormal initialization process.
  3453. // Delegation sequence:
  3454. // - ExitCXXTryStmt opens a RunCleanupsScope
  3455. // - EmitAutoVarAlloca creates the variable and debug info
  3456. // - InitCatchParam initializes the variable from the exception
  3457. // - CallBeginCatch calls __cxa_begin_catch
  3458. // - CallBeginCatch enters the __cxa_end_catch cleanup
  3459. // - EmitAutoVarCleanups enters the variable destructor cleanup
  3460. // - EmitCXXTryStmt emits the code for the catch body
  3461. // - EmitCXXTryStmt close the RunCleanupsScope
  3462. VarDecl *CatchParam = S->getExceptionDecl();
  3463. if (!CatchParam) {
  3464. llvm::Value *Exn = CGF.getExceptionFromSlot();
  3465. CallBeginCatch(CGF, Exn, true);
  3466. return;
  3467. }
  3468. // Emit the local.
  3469. CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
  3470. InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getBeginLoc());
  3471. CGF.EmitAutoVarCleanups(var);
  3472. }
  3473. /// Get or define the following function:
  3474. /// void @__clang_call_terminate(i8* %exn) nounwind noreturn
  3475. /// This code is used only in C++.
  3476. static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
  3477. llvm::FunctionType *fnTy =
  3478. llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
  3479. llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
  3480. fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
  3481. llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
  3482. if (fn && fn->empty()) {
  3483. fn->setDoesNotThrow();
  3484. fn->setDoesNotReturn();
  3485. // What we really want is to massively penalize inlining without
  3486. // forbidding it completely. The difference between that and
  3487. // 'noinline' is negligible.
  3488. fn->addFnAttr(llvm::Attribute::NoInline);
  3489. // Allow this function to be shared across translation units, but
  3490. // we don't want it to turn into an exported symbol.
  3491. fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
  3492. fn->setVisibility(llvm::Function::HiddenVisibility);
  3493. if (CGM.supportsCOMDAT())
  3494. fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
  3495. // Set up the function.
  3496. llvm::BasicBlock *entry =
  3497. llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
  3498. CGBuilderTy builder(CGM, entry);
  3499. // Pull the exception pointer out of the parameter list.
  3500. llvm::Value *exn = &*fn->arg_begin();
  3501. // Call __cxa_begin_catch(exn).
  3502. llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
  3503. catchCall->setDoesNotThrow();
  3504. catchCall->setCallingConv(CGM.getRuntimeCC());
  3505. // Call std::terminate().
  3506. llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
  3507. termCall->setDoesNotThrow();
  3508. termCall->setDoesNotReturn();
  3509. termCall->setCallingConv(CGM.getRuntimeCC());
  3510. // std::terminate cannot return.
  3511. builder.CreateUnreachable();
  3512. }
  3513. return fnRef;
  3514. }
  3515. llvm::CallInst *
  3516. ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
  3517. llvm::Value *Exn) {
  3518. // In C++, we want to call __cxa_begin_catch() before terminating.
  3519. if (Exn) {
  3520. assert(CGF.CGM.getLangOpts().CPlusPlus);
  3521. return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
  3522. }
  3523. return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
  3524. }
  3525. std::pair<llvm::Value *, const CXXRecordDecl *>
  3526. ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
  3527. const CXXRecordDecl *RD) {
  3528. return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
  3529. }
  3530. void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
  3531. const CXXCatchStmt *C) {
  3532. if (CGF.getTarget().hasFeature("exception-handling"))
  3533. CGF.EHStack.pushCleanup<CatchRetScope>(
  3534. NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
  3535. ItaniumCXXABI::emitBeginCatch(CGF, C);
  3536. }