ItaniumCXXABI.cpp 140 KB

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