CGObjCGNU.cpp 172 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224
  1. //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This provides Objective-C code generation targeting the GNU runtime. The
  10. // class in this file generates structures used by the GNU Objective-C runtime
  11. // library. These structures are defined in objc/objc.h and objc/objc-api.h in
  12. // the GNU runtime distribution.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "CGCXXABI.h"
  16. #include "CGCleanup.h"
  17. #include "CGObjCRuntime.h"
  18. #include "CodeGenFunction.h"
  19. #include "CodeGenModule.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/Attr.h"
  22. #include "clang/AST/Decl.h"
  23. #include "clang/AST/DeclObjC.h"
  24. #include "clang/AST/RecordLayout.h"
  25. #include "clang/AST/StmtObjC.h"
  26. #include "clang/Basic/FileManager.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/CodeGen/ConstantInitBuilder.h"
  29. #include "llvm/ADT/SmallVector.h"
  30. #include "llvm/ADT/StringMap.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/Intrinsics.h"
  33. #include "llvm/IR/LLVMContext.h"
  34. #include "llvm/IR/Module.h"
  35. #include "llvm/Support/Compiler.h"
  36. #include "llvm/Support/ConvertUTF.h"
  37. #include <cctype>
  38. using namespace clang;
  39. using namespace CodeGen;
  40. namespace {
  41. /// Class that lazily initialises the runtime function. Avoids inserting the
  42. /// types and the function declaration into a module if they're not used, and
  43. /// avoids constructing the type more than once if it's used more than once.
  44. class LazyRuntimeFunction {
  45. CodeGenModule *CGM;
  46. llvm::FunctionType *FTy;
  47. const char *FunctionName;
  48. llvm::FunctionCallee Function;
  49. public:
  50. /// Constructor leaves this class uninitialized, because it is intended to
  51. /// be used as a field in another class and not all of the types that are
  52. /// used as arguments will necessarily be available at construction time.
  53. LazyRuntimeFunction()
  54. : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
  55. /// Initialises the lazy function with the name, return type, and the types
  56. /// of the arguments.
  57. template <typename... Tys>
  58. void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
  59. Tys *... Types) {
  60. CGM = Mod;
  61. FunctionName = name;
  62. Function = nullptr;
  63. if(sizeof...(Tys)) {
  64. SmallVector<llvm::Type *, 8> ArgTys({Types...});
  65. FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
  66. }
  67. else {
  68. FTy = llvm::FunctionType::get(RetTy, std::nullopt, false);
  69. }
  70. }
  71. llvm::FunctionType *getType() { return FTy; }
  72. /// Overloaded cast operator, allows the class to be implicitly cast to an
  73. /// LLVM constant.
  74. operator llvm::FunctionCallee() {
  75. if (!Function) {
  76. if (!FunctionName)
  77. return nullptr;
  78. Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
  79. }
  80. return Function;
  81. }
  82. };
  83. /// GNU Objective-C runtime code generation. This class implements the parts of
  84. /// Objective-C support that are specific to the GNU family of runtimes (GCC,
  85. /// GNUstep and ObjFW).
  86. class CGObjCGNU : public CGObjCRuntime {
  87. protected:
  88. /// The LLVM module into which output is inserted
  89. llvm::Module &TheModule;
  90. /// strut objc_super. Used for sending messages to super. This structure
  91. /// contains the receiver (object) and the expected class.
  92. llvm::StructType *ObjCSuperTy;
  93. /// struct objc_super*. The type of the argument to the superclass message
  94. /// lookup functions.
  95. llvm::PointerType *PtrToObjCSuperTy;
  96. /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
  97. /// SEL is included in a header somewhere, in which case it will be whatever
  98. /// type is declared in that header, most likely {i8*, i8*}.
  99. llvm::PointerType *SelectorTy;
  100. /// Element type of SelectorTy.
  101. llvm::Type *SelectorElemTy;
  102. /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
  103. /// places where it's used
  104. llvm::IntegerType *Int8Ty;
  105. /// Pointer to i8 - LLVM type of char*, for all of the places where the
  106. /// runtime needs to deal with C strings.
  107. llvm::PointerType *PtrToInt8Ty;
  108. /// struct objc_protocol type
  109. llvm::StructType *ProtocolTy;
  110. /// Protocol * type.
  111. llvm::PointerType *ProtocolPtrTy;
  112. /// Instance Method Pointer type. This is a pointer to a function that takes,
  113. /// at a minimum, an object and a selector, and is the generic type for
  114. /// Objective-C methods. Due to differences between variadic / non-variadic
  115. /// calling conventions, it must always be cast to the correct type before
  116. /// actually being used.
  117. llvm::PointerType *IMPTy;
  118. /// Type of an untyped Objective-C object. Clang treats id as a built-in type
  119. /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
  120. /// but if the runtime header declaring it is included then it may be a
  121. /// pointer to a structure.
  122. llvm::PointerType *IdTy;
  123. /// Element type of IdTy.
  124. llvm::Type *IdElemTy;
  125. /// Pointer to a pointer to an Objective-C object. Used in the new ABI
  126. /// message lookup function and some GC-related functions.
  127. llvm::PointerType *PtrToIdTy;
  128. /// The clang type of id. Used when using the clang CGCall infrastructure to
  129. /// call Objective-C methods.
  130. CanQualType ASTIdTy;
  131. /// LLVM type for C int type.
  132. llvm::IntegerType *IntTy;
  133. /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
  134. /// used in the code to document the difference between i8* meaning a pointer
  135. /// to a C string and i8* meaning a pointer to some opaque type.
  136. llvm::PointerType *PtrTy;
  137. /// LLVM type for C long type. The runtime uses this in a lot of places where
  138. /// it should be using intptr_t, but we can't fix this without breaking
  139. /// compatibility with GCC...
  140. llvm::IntegerType *LongTy;
  141. /// LLVM type for C size_t. Used in various runtime data structures.
  142. llvm::IntegerType *SizeTy;
  143. /// LLVM type for C intptr_t.
  144. llvm::IntegerType *IntPtrTy;
  145. /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
  146. llvm::IntegerType *PtrDiffTy;
  147. /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
  148. /// variables.
  149. llvm::PointerType *PtrToIntTy;
  150. /// LLVM type for Objective-C BOOL type.
  151. llvm::Type *BoolTy;
  152. /// 32-bit integer type, to save us needing to look it up every time it's used.
  153. llvm::IntegerType *Int32Ty;
  154. /// 64-bit integer type, to save us needing to look it up every time it's used.
  155. llvm::IntegerType *Int64Ty;
  156. /// The type of struct objc_property.
  157. llvm::StructType *PropertyMetadataTy;
  158. /// Metadata kind used to tie method lookups to message sends. The GNUstep
  159. /// runtime provides some LLVM passes that can use this to do things like
  160. /// automatic IMP caching and speculative inlining.
  161. unsigned msgSendMDKind;
  162. /// Does the current target use SEH-based exceptions? False implies
  163. /// Itanium-style DWARF unwinding.
  164. bool usesSEHExceptions;
  165. /// Helper to check if we are targeting a specific runtime version or later.
  166. bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
  167. const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
  168. return (R.getKind() == kind) &&
  169. (R.getVersion() >= VersionTuple(major, minor));
  170. }
  171. std::string ManglePublicSymbol(StringRef Name) {
  172. return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
  173. }
  174. std::string SymbolForProtocol(Twine Name) {
  175. return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
  176. }
  177. std::string SymbolForProtocolRef(StringRef Name) {
  178. return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
  179. }
  180. /// Helper function that generates a constant string and returns a pointer to
  181. /// the start of the string. The result of this function can be used anywhere
  182. /// where the C code specifies const char*.
  183. llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
  184. ConstantAddress Array =
  185. CGM.GetAddrOfConstantCString(std::string(Str), Name);
  186. return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
  187. Array.getPointer(), Zeros);
  188. }
  189. /// Emits a linkonce_odr string, whose name is the prefix followed by the
  190. /// string value. This allows the linker to combine the strings between
  191. /// different modules. Used for EH typeinfo names, selector strings, and a
  192. /// few other things.
  193. llvm::Constant *ExportUniqueString(const std::string &Str,
  194. const std::string &prefix,
  195. bool Private=false) {
  196. std::string name = prefix + Str;
  197. auto *ConstStr = TheModule.getGlobalVariable(name);
  198. if (!ConstStr) {
  199. llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
  200. auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
  201. llvm::GlobalValue::LinkOnceODRLinkage, value, name);
  202. GV->setComdat(TheModule.getOrInsertComdat(name));
  203. if (Private)
  204. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  205. ConstStr = GV;
  206. }
  207. return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
  208. ConstStr, Zeros);
  209. }
  210. /// Returns a property name and encoding string.
  211. llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
  212. const Decl *Container) {
  213. assert(!isRuntime(ObjCRuntime::GNUstep, 2));
  214. if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
  215. std::string NameAndAttributes;
  216. std::string TypeStr =
  217. CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
  218. NameAndAttributes += '\0';
  219. NameAndAttributes += TypeStr.length() + 3;
  220. NameAndAttributes += TypeStr;
  221. NameAndAttributes += '\0';
  222. NameAndAttributes += PD->getNameAsString();
  223. return MakeConstantString(NameAndAttributes);
  224. }
  225. return MakeConstantString(PD->getNameAsString());
  226. }
  227. /// Push the property attributes into two structure fields.
  228. void PushPropertyAttributes(ConstantStructBuilder &Fields,
  229. const ObjCPropertyDecl *property, bool isSynthesized=true, bool
  230. isDynamic=true) {
  231. int attrs = property->getPropertyAttributes();
  232. // For read-only properties, clear the copy and retain flags
  233. if (attrs & ObjCPropertyAttribute::kind_readonly) {
  234. attrs &= ~ObjCPropertyAttribute::kind_copy;
  235. attrs &= ~ObjCPropertyAttribute::kind_retain;
  236. attrs &= ~ObjCPropertyAttribute::kind_weak;
  237. attrs &= ~ObjCPropertyAttribute::kind_strong;
  238. }
  239. // The first flags field has the same attribute values as clang uses internally
  240. Fields.addInt(Int8Ty, attrs & 0xff);
  241. attrs >>= 8;
  242. attrs <<= 2;
  243. // For protocol properties, synthesized and dynamic have no meaning, so we
  244. // reuse these flags to indicate that this is a protocol property (both set
  245. // has no meaning, as a property can't be both synthesized and dynamic)
  246. attrs |= isSynthesized ? (1<<0) : 0;
  247. attrs |= isDynamic ? (1<<1) : 0;
  248. // The second field is the next four fields left shifted by two, with the
  249. // low bit set to indicate whether the field is synthesized or dynamic.
  250. Fields.addInt(Int8Ty, attrs & 0xff);
  251. // Two padding fields
  252. Fields.addInt(Int8Ty, 0);
  253. Fields.addInt(Int8Ty, 0);
  254. }
  255. virtual llvm::Constant *GenerateCategoryProtocolList(const
  256. ObjCCategoryDecl *OCD);
  257. virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
  258. int count) {
  259. // int count;
  260. Fields.addInt(IntTy, count);
  261. // int size; (only in GNUstep v2 ABI.
  262. if (isRuntime(ObjCRuntime::GNUstep, 2)) {
  263. llvm::DataLayout td(&TheModule);
  264. Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
  265. CGM.getContext().getCharWidth());
  266. }
  267. // struct objc_property_list *next;
  268. Fields.add(NULLPtr);
  269. // struct objc_property properties[]
  270. return Fields.beginArray(PropertyMetadataTy);
  271. }
  272. virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
  273. const ObjCPropertyDecl *property,
  274. const Decl *OCD,
  275. bool isSynthesized=true, bool
  276. isDynamic=true) {
  277. auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
  278. ASTContext &Context = CGM.getContext();
  279. Fields.add(MakePropertyEncodingString(property, OCD));
  280. PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
  281. auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
  282. if (accessor) {
  283. std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
  284. llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
  285. Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
  286. Fields.add(TypeEncoding);
  287. } else {
  288. Fields.add(NULLPtr);
  289. Fields.add(NULLPtr);
  290. }
  291. };
  292. addPropertyMethod(property->getGetterMethodDecl());
  293. addPropertyMethod(property->getSetterMethodDecl());
  294. Fields.finishAndAddTo(PropertiesArray);
  295. }
  296. /// Ensures that the value has the required type, by inserting a bitcast if
  297. /// required. This function lets us avoid inserting bitcasts that are
  298. /// redundant.
  299. llvm::Value *EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
  300. if (V->getType() == Ty)
  301. return V;
  302. return B.CreateBitCast(V, Ty);
  303. }
  304. // Some zeros used for GEPs in lots of places.
  305. llvm::Constant *Zeros[2];
  306. /// Null pointer value. Mainly used as a terminator in various arrays.
  307. llvm::Constant *NULLPtr;
  308. /// LLVM context.
  309. llvm::LLVMContext &VMContext;
  310. protected:
  311. /// Placeholder for the class. Lots of things refer to the class before we've
  312. /// actually emitted it. We use this alias as a placeholder, and then replace
  313. /// it with a pointer to the class structure before finally emitting the
  314. /// module.
  315. llvm::GlobalAlias *ClassPtrAlias;
  316. /// Placeholder for the metaclass. Lots of things refer to the class before
  317. /// we've / actually emitted it. We use this alias as a placeholder, and then
  318. /// replace / it with a pointer to the metaclass structure before finally
  319. /// emitting the / module.
  320. llvm::GlobalAlias *MetaClassPtrAlias;
  321. /// All of the classes that have been generated for this compilation units.
  322. std::vector<llvm::Constant*> Classes;
  323. /// All of the categories that have been generated for this compilation units.
  324. std::vector<llvm::Constant*> Categories;
  325. /// All of the Objective-C constant strings that have been generated for this
  326. /// compilation units.
  327. std::vector<llvm::Constant*> ConstantStrings;
  328. /// Map from string values to Objective-C constant strings in the output.
  329. /// Used to prevent emitting Objective-C strings more than once. This should
  330. /// not be required at all - CodeGenModule should manage this list.
  331. llvm::StringMap<llvm::Constant*> ObjCStrings;
  332. /// All of the protocols that have been declared.
  333. llvm::StringMap<llvm::Constant*> ExistingProtocols;
  334. /// For each variant of a selector, we store the type encoding and a
  335. /// placeholder value. For an untyped selector, the type will be the empty
  336. /// string. Selector references are all done via the module's selector table,
  337. /// so we create an alias as a placeholder and then replace it with the real
  338. /// value later.
  339. typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
  340. /// Type of the selector map. This is roughly equivalent to the structure
  341. /// used in the GNUstep runtime, which maintains a list of all of the valid
  342. /// types for a selector in a table.
  343. typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
  344. SelectorMap;
  345. /// A map from selectors to selector types. This allows us to emit all
  346. /// selectors of the same name and type together.
  347. SelectorMap SelectorTable;
  348. /// Selectors related to memory management. When compiling in GC mode, we
  349. /// omit these.
  350. Selector RetainSel, ReleaseSel, AutoreleaseSel;
  351. /// Runtime functions used for memory management in GC mode. Note that clang
  352. /// supports code generation for calling these functions, but neither GNU
  353. /// runtime actually supports this API properly yet.
  354. LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
  355. WeakAssignFn, GlobalAssignFn;
  356. typedef std::pair<std::string, std::string> ClassAliasPair;
  357. /// All classes that have aliases set for them.
  358. std::vector<ClassAliasPair> ClassAliases;
  359. protected:
  360. /// Function used for throwing Objective-C exceptions.
  361. LazyRuntimeFunction ExceptionThrowFn;
  362. /// Function used for rethrowing exceptions, used at the end of \@finally or
  363. /// \@synchronize blocks.
  364. LazyRuntimeFunction ExceptionReThrowFn;
  365. /// Function called when entering a catch function. This is required for
  366. /// differentiating Objective-C exceptions and foreign exceptions.
  367. LazyRuntimeFunction EnterCatchFn;
  368. /// Function called when exiting from a catch block. Used to do exception
  369. /// cleanup.
  370. LazyRuntimeFunction ExitCatchFn;
  371. /// Function called when entering an \@synchronize block. Acquires the lock.
  372. LazyRuntimeFunction SyncEnterFn;
  373. /// Function called when exiting an \@synchronize block. Releases the lock.
  374. LazyRuntimeFunction SyncExitFn;
  375. private:
  376. /// Function called if fast enumeration detects that the collection is
  377. /// modified during the update.
  378. LazyRuntimeFunction EnumerationMutationFn;
  379. /// Function for implementing synthesized property getters that return an
  380. /// object.
  381. LazyRuntimeFunction GetPropertyFn;
  382. /// Function for implementing synthesized property setters that return an
  383. /// object.
  384. LazyRuntimeFunction SetPropertyFn;
  385. /// Function used for non-object declared property getters.
  386. LazyRuntimeFunction GetStructPropertyFn;
  387. /// Function used for non-object declared property setters.
  388. LazyRuntimeFunction SetStructPropertyFn;
  389. protected:
  390. /// The version of the runtime that this class targets. Must match the
  391. /// version in the runtime.
  392. int RuntimeVersion;
  393. /// The version of the protocol class. Used to differentiate between ObjC1
  394. /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
  395. /// components and can not contain declared properties. We always emit
  396. /// Objective-C 2 property structures, but we have to pretend that they're
  397. /// Objective-C 1 property structures when targeting the GCC runtime or it
  398. /// will abort.
  399. const int ProtocolVersion;
  400. /// The version of the class ABI. This value is used in the class structure
  401. /// and indicates how various fields should be interpreted.
  402. const int ClassABIVersion;
  403. /// Generates an instance variable list structure. This is a structure
  404. /// containing a size and an array of structures containing instance variable
  405. /// metadata. This is used purely for introspection in the fragile ABI. In
  406. /// the non-fragile ABI, it's used for instance variable fixup.
  407. virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
  408. ArrayRef<llvm::Constant *> IvarTypes,
  409. ArrayRef<llvm::Constant *> IvarOffsets,
  410. ArrayRef<llvm::Constant *> IvarAlign,
  411. ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
  412. /// Generates a method list structure. This is a structure containing a size
  413. /// and an array of structures containing method metadata.
  414. ///
  415. /// This structure is used by both classes and categories, and contains a next
  416. /// pointer allowing them to be chained together in a linked list.
  417. llvm::Constant *GenerateMethodList(StringRef ClassName,
  418. StringRef CategoryName,
  419. ArrayRef<const ObjCMethodDecl*> Methods,
  420. bool isClassMethodList);
  421. /// Emits an empty protocol. This is used for \@protocol() where no protocol
  422. /// is found. The runtime will (hopefully) fix up the pointer to refer to the
  423. /// real protocol.
  424. virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
  425. /// Generates a list of property metadata structures. This follows the same
  426. /// pattern as method and instance variable metadata lists.
  427. llvm::Constant *GeneratePropertyList(const Decl *Container,
  428. const ObjCContainerDecl *OCD,
  429. bool isClassProperty=false,
  430. bool protocolOptionalProperties=false);
  431. /// Generates a list of referenced protocols. Classes, categories, and
  432. /// protocols all use this structure.
  433. llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
  434. /// To ensure that all protocols are seen by the runtime, we add a category on
  435. /// a class defined in the runtime, declaring no methods, but adopting the
  436. /// protocols. This is a horribly ugly hack, but it allows us to collect all
  437. /// of the protocols without changing the ABI.
  438. void GenerateProtocolHolderCategory();
  439. /// Generates a class structure.
  440. llvm::Constant *GenerateClassStructure(
  441. llvm::Constant *MetaClass,
  442. llvm::Constant *SuperClass,
  443. unsigned info,
  444. const char *Name,
  445. llvm::Constant *Version,
  446. llvm::Constant *InstanceSize,
  447. llvm::Constant *IVars,
  448. llvm::Constant *Methods,
  449. llvm::Constant *Protocols,
  450. llvm::Constant *IvarOffsets,
  451. llvm::Constant *Properties,
  452. llvm::Constant *StrongIvarBitmap,
  453. llvm::Constant *WeakIvarBitmap,
  454. bool isMeta=false);
  455. /// Generates a method list. This is used by protocols to define the required
  456. /// and optional methods.
  457. virtual llvm::Constant *GenerateProtocolMethodList(
  458. ArrayRef<const ObjCMethodDecl*> Methods);
  459. /// Emits optional and required method lists.
  460. template<class T>
  461. void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
  462. llvm::Constant *&Optional) {
  463. SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
  464. SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
  465. for (const auto *I : Methods)
  466. if (I->isOptional())
  467. OptionalMethods.push_back(I);
  468. else
  469. RequiredMethods.push_back(I);
  470. Required = GenerateProtocolMethodList(RequiredMethods);
  471. Optional = GenerateProtocolMethodList(OptionalMethods);
  472. }
  473. /// Returns a selector with the specified type encoding. An empty string is
  474. /// used to return an untyped selector (with the types field set to NULL).
  475. virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
  476. const std::string &TypeEncoding);
  477. /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
  478. /// contains the class and ivar names, in the v2 ABI this contains the type
  479. /// encoding as well.
  480. virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
  481. const ObjCIvarDecl *Ivar) {
  482. const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
  483. + '.' + Ivar->getNameAsString();
  484. return Name;
  485. }
  486. /// Returns the variable used to store the offset of an instance variable.
  487. llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
  488. const ObjCIvarDecl *Ivar);
  489. /// Emits a reference to a class. This allows the linker to object if there
  490. /// is no class of the matching name.
  491. void EmitClassRef(const std::string &className);
  492. /// Emits a pointer to the named class
  493. virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
  494. const std::string &Name, bool isWeak);
  495. /// Looks up the method for sending a message to the specified object. This
  496. /// mechanism differs between the GCC and GNU runtimes, so this method must be
  497. /// overridden in subclasses.
  498. virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
  499. llvm::Value *&Receiver,
  500. llvm::Value *cmd,
  501. llvm::MDNode *node,
  502. MessageSendInfo &MSI) = 0;
  503. /// Looks up the method for sending a message to a superclass. This
  504. /// mechanism differs between the GCC and GNU runtimes, so this method must
  505. /// be overridden in subclasses.
  506. virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
  507. Address ObjCSuper,
  508. llvm::Value *cmd,
  509. MessageSendInfo &MSI) = 0;
  510. /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
  511. /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
  512. /// bits set to their values, LSB first, while larger ones are stored in a
  513. /// structure of this / form:
  514. ///
  515. /// struct { int32_t length; int32_t values[length]; };
  516. ///
  517. /// The values in the array are stored in host-endian format, with the least
  518. /// significant bit being assumed to come first in the bitfield. Therefore,
  519. /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
  520. /// while a bitfield / with the 63rd bit set will be 1<<64.
  521. llvm::Constant *MakeBitField(ArrayRef<bool> bits);
  522. public:
  523. CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
  524. unsigned protocolClassVersion, unsigned classABI=1);
  525. ConstantAddress GenerateConstantString(const StringLiteral *) override;
  526. RValue
  527. GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
  528. QualType ResultType, Selector Sel,
  529. llvm::Value *Receiver, const CallArgList &CallArgs,
  530. const ObjCInterfaceDecl *Class,
  531. const ObjCMethodDecl *Method) override;
  532. RValue
  533. GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
  534. QualType ResultType, Selector Sel,
  535. const ObjCInterfaceDecl *Class,
  536. bool isCategoryImpl, llvm::Value *Receiver,
  537. bool IsClassMessage, const CallArgList &CallArgs,
  538. const ObjCMethodDecl *Method) override;
  539. llvm::Value *GetClass(CodeGenFunction &CGF,
  540. const ObjCInterfaceDecl *OID) override;
  541. llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
  542. Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
  543. llvm::Value *GetSelector(CodeGenFunction &CGF,
  544. const ObjCMethodDecl *Method) override;
  545. virtual llvm::Constant *GetConstantSelector(Selector Sel,
  546. const std::string &TypeEncoding) {
  547. llvm_unreachable("Runtime unable to generate constant selector");
  548. }
  549. llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
  550. return GetConstantSelector(M->getSelector(),
  551. CGM.getContext().getObjCEncodingForMethodDecl(M));
  552. }
  553. llvm::Constant *GetEHType(QualType T) override;
  554. llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
  555. const ObjCContainerDecl *CD) override;
  556. void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
  557. const ObjCMethodDecl *OMD,
  558. const ObjCContainerDecl *CD) override;
  559. void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
  560. void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
  561. void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
  562. llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
  563. const ObjCProtocolDecl *PD) override;
  564. void GenerateProtocol(const ObjCProtocolDecl *PD) override;
  565. virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD);
  566. llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override {
  567. return GenerateProtocolRef(PD);
  568. }
  569. llvm::Function *ModuleInitFunction() override;
  570. llvm::FunctionCallee GetPropertyGetFunction() override;
  571. llvm::FunctionCallee GetPropertySetFunction() override;
  572. llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
  573. bool copy) override;
  574. llvm::FunctionCallee GetSetStructFunction() override;
  575. llvm::FunctionCallee GetGetStructFunction() override;
  576. llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
  577. llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
  578. llvm::FunctionCallee EnumerationMutationFunction() override;
  579. void EmitTryStmt(CodeGenFunction &CGF,
  580. const ObjCAtTryStmt &S) override;
  581. void EmitSynchronizedStmt(CodeGenFunction &CGF,
  582. const ObjCAtSynchronizedStmt &S) override;
  583. void EmitThrowStmt(CodeGenFunction &CGF,
  584. const ObjCAtThrowStmt &S,
  585. bool ClearInsertionPoint=true) override;
  586. llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
  587. Address AddrWeakObj) override;
  588. void EmitObjCWeakAssign(CodeGenFunction &CGF,
  589. llvm::Value *src, Address dst) override;
  590. void EmitObjCGlobalAssign(CodeGenFunction &CGF,
  591. llvm::Value *src, Address dest,
  592. bool threadlocal=false) override;
  593. void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
  594. Address dest, llvm::Value *ivarOffset) override;
  595. void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
  596. llvm::Value *src, Address dest) override;
  597. void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
  598. Address SrcPtr,
  599. llvm::Value *Size) override;
  600. LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
  601. llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
  602. unsigned CVRQualifiers) override;
  603. llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
  604. const ObjCInterfaceDecl *Interface,
  605. const ObjCIvarDecl *Ivar) override;
  606. llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
  607. llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
  608. const CGBlockInfo &blockInfo) override {
  609. return NULLPtr;
  610. }
  611. llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
  612. const CGBlockInfo &blockInfo) override {
  613. return NULLPtr;
  614. }
  615. llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
  616. return NULLPtr;
  617. }
  618. };
  619. /// Class representing the legacy GCC Objective-C ABI. This is the default when
  620. /// -fobjc-nonfragile-abi is not specified.
  621. ///
  622. /// The GCC ABI target actually generates code that is approximately compatible
  623. /// with the new GNUstep runtime ABI, but refrains from using any features that
  624. /// would not work with the GCC runtime. For example, clang always generates
  625. /// the extended form of the class structure, and the extra fields are simply
  626. /// ignored by GCC libobjc.
  627. class CGObjCGCC : public CGObjCGNU {
  628. /// The GCC ABI message lookup function. Returns an IMP pointing to the
  629. /// method implementation for this message.
  630. LazyRuntimeFunction MsgLookupFn;
  631. /// The GCC ABI superclass message lookup function. Takes a pointer to a
  632. /// structure describing the receiver and the class, and a selector as
  633. /// arguments. Returns the IMP for the corresponding method.
  634. LazyRuntimeFunction MsgLookupSuperFn;
  635. protected:
  636. llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
  637. llvm::Value *cmd, llvm::MDNode *node,
  638. MessageSendInfo &MSI) override {
  639. CGBuilderTy &Builder = CGF.Builder;
  640. llvm::Value *args[] = {
  641. EnforceType(Builder, Receiver, IdTy),
  642. EnforceType(Builder, cmd, SelectorTy) };
  643. llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
  644. imp->setMetadata(msgSendMDKind, node);
  645. return imp;
  646. }
  647. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  648. llvm::Value *cmd, MessageSendInfo &MSI) override {
  649. CGBuilderTy &Builder = CGF.Builder;
  650. llvm::Value *lookupArgs[] = {
  651. EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd};
  652. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
  653. }
  654. public:
  655. CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
  656. // IMP objc_msg_lookup(id, SEL);
  657. MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
  658. // IMP objc_msg_lookup_super(struct objc_super*, SEL);
  659. MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
  660. PtrToObjCSuperTy, SelectorTy);
  661. }
  662. };
  663. /// Class used when targeting the new GNUstep runtime ABI.
  664. class CGObjCGNUstep : public CGObjCGNU {
  665. /// The slot lookup function. Returns a pointer to a cacheable structure
  666. /// that contains (among other things) the IMP.
  667. LazyRuntimeFunction SlotLookupFn;
  668. /// The GNUstep ABI superclass message lookup function. Takes a pointer to
  669. /// a structure describing the receiver and the class, and a selector as
  670. /// arguments. Returns the slot for the corresponding method. Superclass
  671. /// message lookup rarely changes, so this is a good caching opportunity.
  672. LazyRuntimeFunction SlotLookupSuperFn;
  673. /// Specialised function for setting atomic retain properties
  674. LazyRuntimeFunction SetPropertyAtomic;
  675. /// Specialised function for setting atomic copy properties
  676. LazyRuntimeFunction SetPropertyAtomicCopy;
  677. /// Specialised function for setting nonatomic retain properties
  678. LazyRuntimeFunction SetPropertyNonAtomic;
  679. /// Specialised function for setting nonatomic copy properties
  680. LazyRuntimeFunction SetPropertyNonAtomicCopy;
  681. /// Function to perform atomic copies of C++ objects with nontrivial copy
  682. /// constructors from Objective-C ivars.
  683. LazyRuntimeFunction CxxAtomicObjectGetFn;
  684. /// Function to perform atomic copies of C++ objects with nontrivial copy
  685. /// constructors to Objective-C ivars.
  686. LazyRuntimeFunction CxxAtomicObjectSetFn;
  687. /// Type of a slot structure pointer. This is returned by the various
  688. /// lookup functions.
  689. llvm::Type *SlotTy;
  690. /// Type of a slot structure.
  691. llvm::Type *SlotStructTy;
  692. public:
  693. llvm::Constant *GetEHType(QualType T) override;
  694. protected:
  695. llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
  696. llvm::Value *cmd, llvm::MDNode *node,
  697. MessageSendInfo &MSI) override {
  698. CGBuilderTy &Builder = CGF.Builder;
  699. llvm::FunctionCallee LookupFn = SlotLookupFn;
  700. // Store the receiver on the stack so that we can reload it later
  701. Address ReceiverPtr =
  702. CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
  703. Builder.CreateStore(Receiver, ReceiverPtr);
  704. llvm::Value *self;
  705. if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
  706. self = CGF.LoadObjCSelf();
  707. } else {
  708. self = llvm::ConstantPointerNull::get(IdTy);
  709. }
  710. // The lookup function is guaranteed not to capture the receiver pointer.
  711. if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
  712. LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
  713. llvm::Value *args[] = {
  714. EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
  715. EnforceType(Builder, cmd, SelectorTy),
  716. EnforceType(Builder, self, IdTy) };
  717. llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
  718. slot->setOnlyReadsMemory();
  719. slot->setMetadata(msgSendMDKind, node);
  720. // Load the imp from the slot
  721. llvm::Value *imp = Builder.CreateAlignedLoad(
  722. IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
  723. CGF.getPointerAlign());
  724. // The lookup function may have changed the receiver, so make sure we use
  725. // the new one.
  726. Receiver = Builder.CreateLoad(ReceiverPtr, true);
  727. return imp;
  728. }
  729. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  730. llvm::Value *cmd,
  731. MessageSendInfo &MSI) override {
  732. CGBuilderTy &Builder = CGF.Builder;
  733. llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
  734. llvm::CallInst *slot =
  735. CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
  736. slot->setOnlyReadsMemory();
  737. return Builder.CreateAlignedLoad(
  738. IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
  739. CGF.getPointerAlign());
  740. }
  741. public:
  742. CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
  743. CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
  744. unsigned ClassABI) :
  745. CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
  746. const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
  747. SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
  748. SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
  749. // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
  750. SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
  751. SelectorTy, IdTy);
  752. // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
  753. SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  754. PtrToObjCSuperTy, SelectorTy);
  755. // If we're in ObjC++ mode, then we want to make
  756. if (usesSEHExceptions) {
  757. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  758. // void objc_exception_rethrow(void)
  759. ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
  760. } else if (CGM.getLangOpts().CPlusPlus) {
  761. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  762. // void *__cxa_begin_catch(void *e)
  763. EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
  764. // void __cxa_end_catch(void)
  765. ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
  766. // void _Unwind_Resume_or_Rethrow(void*)
  767. ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
  768. PtrTy);
  769. } else if (R.getVersion() >= VersionTuple(1, 7)) {
  770. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  771. // id objc_begin_catch(void *e)
  772. EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
  773. // void objc_end_catch(void)
  774. ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
  775. // void _Unwind_Resume_or_Rethrow(void*)
  776. ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
  777. }
  778. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  779. SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
  780. SelectorTy, IdTy, PtrDiffTy);
  781. SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
  782. IdTy, SelectorTy, IdTy, PtrDiffTy);
  783. SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
  784. IdTy, SelectorTy, IdTy, PtrDiffTy);
  785. SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
  786. VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
  787. // void objc_setCppObjectAtomic(void *dest, const void *src, void
  788. // *helper);
  789. CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
  790. PtrTy, PtrTy);
  791. // void objc_getCppObjectAtomic(void *dest, const void *src, void
  792. // *helper);
  793. CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
  794. PtrTy, PtrTy);
  795. }
  796. llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
  797. // The optimised functions were added in version 1.7 of the GNUstep
  798. // runtime.
  799. assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
  800. VersionTuple(1, 7));
  801. return CxxAtomicObjectGetFn;
  802. }
  803. llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
  804. // The optimised functions were added in version 1.7 of the GNUstep
  805. // runtime.
  806. assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
  807. VersionTuple(1, 7));
  808. return CxxAtomicObjectSetFn;
  809. }
  810. llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
  811. bool copy) override {
  812. // The optimised property functions omit the GC check, and so are not
  813. // safe to use in GC mode. The standard functions are fast in GC mode,
  814. // so there is less advantage in using them.
  815. assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
  816. // The optimised functions were added in version 1.7 of the GNUstep
  817. // runtime.
  818. assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
  819. VersionTuple(1, 7));
  820. if (atomic) {
  821. if (copy) return SetPropertyAtomicCopy;
  822. return SetPropertyAtomic;
  823. }
  824. return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
  825. }
  826. };
  827. /// GNUstep Objective-C ABI version 2 implementation.
  828. /// This is the ABI that provides a clean break with the legacy GCC ABI and
  829. /// cleans up a number of things that were added to work around 1980s linkers.
  830. class CGObjCGNUstep2 : public CGObjCGNUstep {
  831. enum SectionKind
  832. {
  833. SelectorSection = 0,
  834. ClassSection,
  835. ClassReferenceSection,
  836. CategorySection,
  837. ProtocolSection,
  838. ProtocolReferenceSection,
  839. ClassAliasSection,
  840. ConstantStringSection
  841. };
  842. static const char *const SectionsBaseNames[8];
  843. static const char *const PECOFFSectionsBaseNames[8];
  844. template<SectionKind K>
  845. std::string sectionName() {
  846. if (CGM.getTriple().isOSBinFormatCOFF()) {
  847. std::string name(PECOFFSectionsBaseNames[K]);
  848. name += "$m";
  849. return name;
  850. }
  851. return SectionsBaseNames[K];
  852. }
  853. /// The GCC ABI superclass message lookup function. Takes a pointer to a
  854. /// structure describing the receiver and the class, and a selector as
  855. /// arguments. Returns the IMP for the corresponding method.
  856. LazyRuntimeFunction MsgLookupSuperFn;
  857. /// A flag indicating if we've emitted at least one protocol.
  858. /// If we haven't, then we need to emit an empty protocol, to ensure that the
  859. /// __start__objc_protocols and __stop__objc_protocols sections exist.
  860. bool EmittedProtocol = false;
  861. /// A flag indicating if we've emitted at least one protocol reference.
  862. /// If we haven't, then we need to emit an empty protocol, to ensure that the
  863. /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
  864. /// exist.
  865. bool EmittedProtocolRef = false;
  866. /// A flag indicating if we've emitted at least one class.
  867. /// If we haven't, then we need to emit an empty protocol, to ensure that the
  868. /// __start__objc_classes and __stop__objc_classes sections / exist.
  869. bool EmittedClass = false;
  870. /// Generate the name of a symbol for a reference to a class. Accesses to
  871. /// classes should be indirected via this.
  872. typedef std::pair<std::string, std::pair<llvm::GlobalVariable*, int>>
  873. EarlyInitPair;
  874. std::vector<EarlyInitPair> EarlyInitList;
  875. std::string SymbolForClassRef(StringRef Name, bool isWeak) {
  876. if (isWeak)
  877. return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
  878. else
  879. return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
  880. }
  881. /// Generate the name of a class symbol.
  882. std::string SymbolForClass(StringRef Name) {
  883. return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
  884. }
  885. void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
  886. ArrayRef<llvm::Value*> Args) {
  887. SmallVector<llvm::Type *,8> Types;
  888. for (auto *Arg : Args)
  889. Types.push_back(Arg->getType());
  890. llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
  891. false);
  892. llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
  893. B.CreateCall(Fn, Args);
  894. }
  895. ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
  896. auto Str = SL->getString();
  897. CharUnits Align = CGM.getPointerAlign();
  898. // Look for an existing one
  899. llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
  900. if (old != ObjCStrings.end())
  901. return ConstantAddress(old->getValue(), IdElemTy, Align);
  902. bool isNonASCII = SL->containsNonAscii();
  903. auto LiteralLength = SL->getLength();
  904. if ((CGM.getTarget().getPointerWidth(LangAS::Default) == 64) &&
  905. (LiteralLength < 9) && !isNonASCII) {
  906. // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
  907. // ASCII characters in the high 56 bits, followed by a 4-bit length and a
  908. // 3-bit tag (which is always 4).
  909. uint64_t str = 0;
  910. // Fill in the characters
  911. for (unsigned i=0 ; i<LiteralLength ; i++)
  912. str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
  913. // Fill in the length
  914. str |= LiteralLength << 3;
  915. // Set the tag
  916. str |= 4;
  917. auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
  918. llvm::ConstantInt::get(Int64Ty, str), IdTy);
  919. ObjCStrings[Str] = ObjCStr;
  920. return ConstantAddress(ObjCStr, IdElemTy, Align);
  921. }
  922. StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
  923. if (StringClass.empty()) StringClass = "NSConstantString";
  924. std::string Sym = SymbolForClass(StringClass);
  925. llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
  926. if (!isa) {
  927. isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
  928. llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
  929. if (CGM.getTriple().isOSBinFormatCOFF()) {
  930. cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  931. }
  932. } else if (isa->getType() != PtrToIdTy)
  933. isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
  934. // struct
  935. // {
  936. // Class isa;
  937. // uint32_t flags;
  938. // uint32_t length; // Number of codepoints
  939. // uint32_t size; // Number of bytes
  940. // uint32_t hash;
  941. // const char *data;
  942. // };
  943. ConstantInitBuilder Builder(CGM);
  944. auto Fields = Builder.beginStruct();
  945. if (!CGM.getTriple().isOSBinFormatCOFF()) {
  946. Fields.add(isa);
  947. } else {
  948. Fields.addNullPointer(PtrTy);
  949. }
  950. // For now, all non-ASCII strings are represented as UTF-16. As such, the
  951. // number of bytes is simply double the number of UTF-16 codepoints. In
  952. // ASCII strings, the number of bytes is equal to the number of non-ASCII
  953. // codepoints.
  954. if (isNonASCII) {
  955. unsigned NumU8CodeUnits = Str.size();
  956. // A UTF-16 representation of a unicode string contains at most the same
  957. // number of code units as a UTF-8 representation. Allocate that much
  958. // space, plus one for the final null character.
  959. SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
  960. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
  961. llvm::UTF16 *ToPtr = &ToBuf[0];
  962. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
  963. &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
  964. uint32_t StringLength = ToPtr - &ToBuf[0];
  965. // Add null terminator
  966. *ToPtr = 0;
  967. // Flags: 2 indicates UTF-16 encoding
  968. Fields.addInt(Int32Ty, 2);
  969. // Number of UTF-16 codepoints
  970. Fields.addInt(Int32Ty, StringLength);
  971. // Number of bytes
  972. Fields.addInt(Int32Ty, StringLength * 2);
  973. // Hash. Not currently initialised by the compiler.
  974. Fields.addInt(Int32Ty, 0);
  975. // pointer to the data string.
  976. auto Arr = llvm::ArrayRef(&ToBuf[0], ToPtr + 1);
  977. auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
  978. auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
  979. /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
  980. Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  981. Fields.add(Buffer);
  982. } else {
  983. // Flags: 0 indicates ASCII encoding
  984. Fields.addInt(Int32Ty, 0);
  985. // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
  986. Fields.addInt(Int32Ty, Str.size());
  987. // Number of bytes
  988. Fields.addInt(Int32Ty, Str.size());
  989. // Hash. Not currently initialised by the compiler.
  990. Fields.addInt(Int32Ty, 0);
  991. // Data pointer
  992. Fields.add(MakeConstantString(Str));
  993. }
  994. std::string StringName;
  995. bool isNamed = !isNonASCII;
  996. if (isNamed) {
  997. StringName = ".objc_str_";
  998. for (int i=0,e=Str.size() ; i<e ; ++i) {
  999. unsigned char c = Str[i];
  1000. if (isalnum(c))
  1001. StringName += c;
  1002. else if (c == ' ')
  1003. StringName += '_';
  1004. else {
  1005. isNamed = false;
  1006. break;
  1007. }
  1008. }
  1009. }
  1010. llvm::GlobalVariable *ObjCStrGV =
  1011. Fields.finishAndCreateGlobal(
  1012. isNamed ? StringRef(StringName) : ".objc_string",
  1013. Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
  1014. : llvm::GlobalValue::PrivateLinkage);
  1015. ObjCStrGV->setSection(sectionName<ConstantStringSection>());
  1016. if (isNamed) {
  1017. ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
  1018. ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1019. }
  1020. if (CGM.getTriple().isOSBinFormatCOFF()) {
  1021. std::pair<llvm::GlobalVariable*, int> v{ObjCStrGV, 0};
  1022. EarlyInitList.emplace_back(Sym, v);
  1023. }
  1024. llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
  1025. ObjCStrings[Str] = ObjCStr;
  1026. ConstantStrings.push_back(ObjCStr);
  1027. return ConstantAddress(ObjCStr, IdElemTy, Align);
  1028. }
  1029. void PushProperty(ConstantArrayBuilder &PropertiesArray,
  1030. const ObjCPropertyDecl *property,
  1031. const Decl *OCD,
  1032. bool isSynthesized=true, bool
  1033. isDynamic=true) override {
  1034. // struct objc_property
  1035. // {
  1036. // const char *name;
  1037. // const char *attributes;
  1038. // const char *type;
  1039. // SEL getter;
  1040. // SEL setter;
  1041. // };
  1042. auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
  1043. ASTContext &Context = CGM.getContext();
  1044. Fields.add(MakeConstantString(property->getNameAsString()));
  1045. std::string TypeStr =
  1046. CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
  1047. Fields.add(MakeConstantString(TypeStr));
  1048. std::string typeStr;
  1049. Context.getObjCEncodingForType(property->getType(), typeStr);
  1050. Fields.add(MakeConstantString(typeStr));
  1051. auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
  1052. if (accessor) {
  1053. std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
  1054. Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
  1055. } else {
  1056. Fields.add(NULLPtr);
  1057. }
  1058. };
  1059. addPropertyMethod(property->getGetterMethodDecl());
  1060. addPropertyMethod(property->getSetterMethodDecl());
  1061. Fields.finishAndAddTo(PropertiesArray);
  1062. }
  1063. llvm::Constant *
  1064. GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
  1065. // struct objc_protocol_method_description
  1066. // {
  1067. // SEL selector;
  1068. // const char *types;
  1069. // };
  1070. llvm::StructType *ObjCMethodDescTy =
  1071. llvm::StructType::get(CGM.getLLVMContext(),
  1072. { PtrToInt8Ty, PtrToInt8Ty });
  1073. ASTContext &Context = CGM.getContext();
  1074. ConstantInitBuilder Builder(CGM);
  1075. // struct objc_protocol_method_description_list
  1076. // {
  1077. // int count;
  1078. // int size;
  1079. // struct objc_protocol_method_description methods[];
  1080. // };
  1081. auto MethodList = Builder.beginStruct();
  1082. // int count;
  1083. MethodList.addInt(IntTy, Methods.size());
  1084. // int size; // sizeof(struct objc_method_description)
  1085. llvm::DataLayout td(&TheModule);
  1086. MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
  1087. CGM.getContext().getCharWidth());
  1088. // struct objc_method_description[]
  1089. auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
  1090. for (auto *M : Methods) {
  1091. auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
  1092. Method.add(CGObjCGNU::GetConstantSelector(M));
  1093. Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
  1094. Method.finishAndAddTo(MethodArray);
  1095. }
  1096. MethodArray.finishAndAddTo(MethodList);
  1097. return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
  1098. CGM.getPointerAlign());
  1099. }
  1100. llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
  1101. override {
  1102. const auto &ReferencedProtocols = OCD->getReferencedProtocols();
  1103. auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),
  1104. ReferencedProtocols.end());
  1105. SmallVector<llvm::Constant *, 16> Protocols;
  1106. for (const auto *PI : RuntimeProtocols)
  1107. Protocols.push_back(
  1108. llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
  1109. ProtocolPtrTy));
  1110. return GenerateProtocolList(Protocols);
  1111. }
  1112. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  1113. llvm::Value *cmd, MessageSendInfo &MSI) override {
  1114. // Don't access the slot unless we're trying to cache the result.
  1115. CGBuilderTy &Builder = CGF.Builder;
  1116. llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder,
  1117. ObjCSuper.getPointer(),
  1118. PtrToObjCSuperTy),
  1119. cmd};
  1120. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
  1121. }
  1122. llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
  1123. std::string SymbolName = SymbolForClassRef(Name, isWeak);
  1124. auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
  1125. if (ClassSymbol)
  1126. return ClassSymbol;
  1127. ClassSymbol = new llvm::GlobalVariable(TheModule,
  1128. IdTy, false, llvm::GlobalValue::ExternalLinkage,
  1129. nullptr, SymbolName);
  1130. // If this is a weak symbol, then we are creating a valid definition for
  1131. // the symbol, pointing to a weak definition of the real class pointer. If
  1132. // this is not a weak reference, then we are expecting another compilation
  1133. // unit to provide the real indirection symbol.
  1134. if (isWeak)
  1135. ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
  1136. Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
  1137. nullptr, SymbolForClass(Name)));
  1138. else {
  1139. if (CGM.getTriple().isOSBinFormatCOFF()) {
  1140. IdentifierInfo &II = CGM.getContext().Idents.get(Name);
  1141. TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
  1142. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  1143. const ObjCInterfaceDecl *OID = nullptr;
  1144. for (const auto *Result : DC->lookup(&II))
  1145. if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
  1146. break;
  1147. // The first Interface we find may be a @class,
  1148. // which should only be treated as the source of
  1149. // truth in the absence of a true declaration.
  1150. assert(OID && "Failed to find ObjCInterfaceDecl");
  1151. const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
  1152. if (OIDDef != nullptr)
  1153. OID = OIDDef;
  1154. auto Storage = llvm::GlobalValue::DefaultStorageClass;
  1155. if (OID->hasAttr<DLLImportAttr>())
  1156. Storage = llvm::GlobalValue::DLLImportStorageClass;
  1157. else if (OID->hasAttr<DLLExportAttr>())
  1158. Storage = llvm::GlobalValue::DLLExportStorageClass;
  1159. cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
  1160. }
  1161. }
  1162. assert(ClassSymbol->getName() == SymbolName);
  1163. return ClassSymbol;
  1164. }
  1165. llvm::Value *GetClassNamed(CodeGenFunction &CGF,
  1166. const std::string &Name,
  1167. bool isWeak) override {
  1168. return CGF.Builder.CreateLoad(
  1169. Address(GetClassVar(Name, isWeak), IdTy, CGM.getPointerAlign()));
  1170. }
  1171. int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
  1172. // typedef enum {
  1173. // ownership_invalid = 0,
  1174. // ownership_strong = 1,
  1175. // ownership_weak = 2,
  1176. // ownership_unsafe = 3
  1177. // } ivar_ownership;
  1178. int Flag;
  1179. switch (Ownership) {
  1180. case Qualifiers::OCL_Strong:
  1181. Flag = 1;
  1182. break;
  1183. case Qualifiers::OCL_Weak:
  1184. Flag = 2;
  1185. break;
  1186. case Qualifiers::OCL_ExplicitNone:
  1187. Flag = 3;
  1188. break;
  1189. case Qualifiers::OCL_None:
  1190. case Qualifiers::OCL_Autoreleasing:
  1191. assert(Ownership != Qualifiers::OCL_Autoreleasing);
  1192. Flag = 0;
  1193. }
  1194. return Flag;
  1195. }
  1196. llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
  1197. ArrayRef<llvm::Constant *> IvarTypes,
  1198. ArrayRef<llvm::Constant *> IvarOffsets,
  1199. ArrayRef<llvm::Constant *> IvarAlign,
  1200. ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
  1201. llvm_unreachable("Method should not be called!");
  1202. }
  1203. llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
  1204. std::string Name = SymbolForProtocol(ProtocolName);
  1205. auto *GV = TheModule.getGlobalVariable(Name);
  1206. if (!GV) {
  1207. // Emit a placeholder symbol.
  1208. GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
  1209. llvm::GlobalValue::ExternalLinkage, nullptr, Name);
  1210. GV->setAlignment(CGM.getPointerAlign().getAsAlign());
  1211. }
  1212. return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
  1213. }
  1214. /// Existing protocol references.
  1215. llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
  1216. llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
  1217. const ObjCProtocolDecl *PD) override {
  1218. auto Name = PD->getNameAsString();
  1219. auto *&Ref = ExistingProtocolRefs[Name];
  1220. if (!Ref) {
  1221. auto *&Protocol = ExistingProtocols[Name];
  1222. if (!Protocol)
  1223. Protocol = GenerateProtocolRef(PD);
  1224. std::string RefName = SymbolForProtocolRef(Name);
  1225. assert(!TheModule.getGlobalVariable(RefName));
  1226. // Emit a reference symbol.
  1227. auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
  1228. false, llvm::GlobalValue::LinkOnceODRLinkage,
  1229. llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
  1230. GV->setComdat(TheModule.getOrInsertComdat(RefName));
  1231. GV->setSection(sectionName<ProtocolReferenceSection>());
  1232. GV->setAlignment(CGM.getPointerAlign().getAsAlign());
  1233. Ref = GV;
  1234. }
  1235. EmittedProtocolRef = true;
  1236. return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,
  1237. CGM.getPointerAlign());
  1238. }
  1239. llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
  1240. llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
  1241. Protocols.size());
  1242. llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
  1243. Protocols);
  1244. ConstantInitBuilder builder(CGM);
  1245. auto ProtocolBuilder = builder.beginStruct();
  1246. ProtocolBuilder.addNullPointer(PtrTy);
  1247. ProtocolBuilder.addInt(SizeTy, Protocols.size());
  1248. ProtocolBuilder.add(ProtocolArray);
  1249. return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
  1250. CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
  1251. }
  1252. void GenerateProtocol(const ObjCProtocolDecl *PD) override {
  1253. // Do nothing - we only emit referenced protocols.
  1254. }
  1255. llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {
  1256. std::string ProtocolName = PD->getNameAsString();
  1257. auto *&Protocol = ExistingProtocols[ProtocolName];
  1258. if (Protocol)
  1259. return Protocol;
  1260. EmittedProtocol = true;
  1261. auto SymName = SymbolForProtocol(ProtocolName);
  1262. auto *OldGV = TheModule.getGlobalVariable(SymName);
  1263. // Use the protocol definition, if there is one.
  1264. if (const ObjCProtocolDecl *Def = PD->getDefinition())
  1265. PD = Def;
  1266. else {
  1267. // If there is no definition, then create an external linkage symbol and
  1268. // hope that someone else fills it in for us (and fail to link if they
  1269. // don't).
  1270. assert(!OldGV);
  1271. Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
  1272. /*isConstant*/false,
  1273. llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
  1274. return Protocol;
  1275. }
  1276. SmallVector<llvm::Constant*, 16> Protocols;
  1277. auto RuntimeProtocols =
  1278. GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());
  1279. for (const auto *PI : RuntimeProtocols)
  1280. Protocols.push_back(
  1281. llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
  1282. ProtocolPtrTy));
  1283. llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
  1284. // Collect information about methods
  1285. llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
  1286. llvm::Constant *ClassMethodList, *OptionalClassMethodList;
  1287. EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
  1288. OptionalInstanceMethodList);
  1289. EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
  1290. OptionalClassMethodList);
  1291. // The isa pointer must be set to a magic number so the runtime knows it's
  1292. // the correct layout.
  1293. ConstantInitBuilder builder(CGM);
  1294. auto ProtocolBuilder = builder.beginStruct();
  1295. ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
  1296. llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
  1297. ProtocolBuilder.add(MakeConstantString(ProtocolName));
  1298. ProtocolBuilder.add(ProtocolList);
  1299. ProtocolBuilder.add(InstanceMethodList);
  1300. ProtocolBuilder.add(ClassMethodList);
  1301. ProtocolBuilder.add(OptionalInstanceMethodList);
  1302. ProtocolBuilder.add(OptionalClassMethodList);
  1303. // Required instance properties
  1304. ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
  1305. // Optional instance properties
  1306. ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
  1307. // Required class properties
  1308. ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
  1309. // Optional class properties
  1310. ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
  1311. auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
  1312. CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
  1313. GV->setSection(sectionName<ProtocolSection>());
  1314. GV->setComdat(TheModule.getOrInsertComdat(SymName));
  1315. if (OldGV) {
  1316. OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
  1317. OldGV->getType()));
  1318. OldGV->removeFromParent();
  1319. GV->setName(SymName);
  1320. }
  1321. Protocol = GV;
  1322. return GV;
  1323. }
  1324. llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
  1325. if (Val->getType() == Ty)
  1326. return Val;
  1327. return llvm::ConstantExpr::getBitCast(Val, Ty);
  1328. }
  1329. llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
  1330. const std::string &TypeEncoding) override {
  1331. return GetConstantSelector(Sel, TypeEncoding);
  1332. }
  1333. llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
  1334. if (TypeEncoding.empty())
  1335. return NULLPtr;
  1336. std::string MangledTypes = std::string(TypeEncoding);
  1337. std::replace(MangledTypes.begin(), MangledTypes.end(),
  1338. '@', '\1');
  1339. std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
  1340. auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
  1341. if (!TypesGlobal) {
  1342. llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
  1343. TypeEncoding);
  1344. auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
  1345. true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
  1346. GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
  1347. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1348. TypesGlobal = GV;
  1349. }
  1350. return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
  1351. TypesGlobal, Zeros);
  1352. }
  1353. llvm::Constant *GetConstantSelector(Selector Sel,
  1354. const std::string &TypeEncoding) override {
  1355. // @ is used as a special character in symbol names (used for symbol
  1356. // versioning), so mangle the name to not include it. Replace it with a
  1357. // character that is not a valid type encoding character (and, being
  1358. // non-printable, never will be!)
  1359. std::string MangledTypes = TypeEncoding;
  1360. std::replace(MangledTypes.begin(), MangledTypes.end(),
  1361. '@', '\1');
  1362. auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
  1363. MangledTypes).str();
  1364. if (auto *GV = TheModule.getNamedGlobal(SelVarName))
  1365. return EnforceType(GV, SelectorTy);
  1366. ConstantInitBuilder builder(CGM);
  1367. auto SelBuilder = builder.beginStruct();
  1368. SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
  1369. true));
  1370. SelBuilder.add(GetTypeString(TypeEncoding));
  1371. auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
  1372. CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
  1373. GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
  1374. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1375. GV->setSection(sectionName<SelectorSection>());
  1376. auto *SelVal = EnforceType(GV, SelectorTy);
  1377. return SelVal;
  1378. }
  1379. llvm::StructType *emptyStruct = nullptr;
  1380. /// Return pointers to the start and end of a section. On ELF platforms, we
  1381. /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
  1382. /// to the start and end of section names, as long as those section names are
  1383. /// valid identifiers and the symbols are referenced but not defined. On
  1384. /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
  1385. /// by subsections and place everything that we want to reference in a middle
  1386. /// subsection and then insert zero-sized symbols in subsections a and z.
  1387. std::pair<llvm::Constant*,llvm::Constant*>
  1388. GetSectionBounds(StringRef Section) {
  1389. if (CGM.getTriple().isOSBinFormatCOFF()) {
  1390. if (emptyStruct == nullptr) {
  1391. emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
  1392. emptyStruct->setBody({}, /*isPacked*/true);
  1393. }
  1394. auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
  1395. auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
  1396. auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
  1397. /*isConstant*/false,
  1398. llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
  1399. Section);
  1400. Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1401. Sym->setSection((Section + SecSuffix).str());
  1402. Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
  1403. Section).str()));
  1404. Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
  1405. return Sym;
  1406. };
  1407. return { Sym("__start_", "$a"), Sym("__stop", "$z") };
  1408. }
  1409. auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
  1410. /*isConstant*/false,
  1411. llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
  1412. Section);
  1413. Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1414. auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
  1415. /*isConstant*/false,
  1416. llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
  1417. Section);
  1418. Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1419. return { Start, Stop };
  1420. }
  1421. CatchTypeInfo getCatchAllTypeInfo() override {
  1422. return CGM.getCXXABI().getCatchAllTypeInfo();
  1423. }
  1424. llvm::Function *ModuleInitFunction() override {
  1425. llvm::Function *LoadFunction = llvm::Function::Create(
  1426. llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
  1427. llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
  1428. &TheModule);
  1429. LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1430. LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
  1431. llvm::BasicBlock *EntryBB =
  1432. llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
  1433. CGBuilderTy B(CGM, VMContext);
  1434. B.SetInsertPoint(EntryBB);
  1435. ConstantInitBuilder builder(CGM);
  1436. auto InitStructBuilder = builder.beginStruct();
  1437. InitStructBuilder.addInt(Int64Ty, 0);
  1438. auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
  1439. for (auto *s : sectionVec) {
  1440. auto bounds = GetSectionBounds(s);
  1441. InitStructBuilder.add(bounds.first);
  1442. InitStructBuilder.add(bounds.second);
  1443. }
  1444. auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
  1445. CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
  1446. InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1447. InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
  1448. CallRuntimeFunction(B, "__objc_load", {InitStruct});;
  1449. B.CreateRetVoid();
  1450. // Make sure that the optimisers don't delete this function.
  1451. CGM.addCompilerUsedGlobal(LoadFunction);
  1452. // FIXME: Currently ELF only!
  1453. // We have to do this by hand, rather than with @llvm.ctors, so that the
  1454. // linker can remove the duplicate invocations.
  1455. auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
  1456. /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,
  1457. LoadFunction, ".objc_ctor");
  1458. // Check that this hasn't been renamed. This shouldn't happen, because
  1459. // this function should be called precisely once.
  1460. assert(InitVar->getName() == ".objc_ctor");
  1461. // In Windows, initialisers are sorted by the suffix. XCL is for library
  1462. // initialisers, which run before user initialisers. We are running
  1463. // Objective-C loads at the end of library load. This means +load methods
  1464. // will run before any other static constructors, but that static
  1465. // constructors can see a fully initialised Objective-C state.
  1466. if (CGM.getTriple().isOSBinFormatCOFF())
  1467. InitVar->setSection(".CRT$XCLz");
  1468. else
  1469. {
  1470. if (CGM.getCodeGenOpts().UseInitArray)
  1471. InitVar->setSection(".init_array");
  1472. else
  1473. InitVar->setSection(".ctors");
  1474. }
  1475. InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1476. InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
  1477. CGM.addUsedGlobal(InitVar);
  1478. for (auto *C : Categories) {
  1479. auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
  1480. Cat->setSection(sectionName<CategorySection>());
  1481. CGM.addUsedGlobal(Cat);
  1482. }
  1483. auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
  1484. StringRef Section) {
  1485. auto nullBuilder = builder.beginStruct();
  1486. for (auto *F : Init)
  1487. nullBuilder.add(F);
  1488. auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
  1489. false, llvm::GlobalValue::LinkOnceODRLinkage);
  1490. GV->setSection(Section);
  1491. GV->setComdat(TheModule.getOrInsertComdat(Name));
  1492. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1493. CGM.addUsedGlobal(GV);
  1494. return GV;
  1495. };
  1496. for (auto clsAlias : ClassAliases)
  1497. createNullGlobal(std::string(".objc_class_alias") +
  1498. clsAlias.second, { MakeConstantString(clsAlias.second),
  1499. GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
  1500. // On ELF platforms, add a null value for each special section so that we
  1501. // can always guarantee that the _start and _stop symbols will exist and be
  1502. // meaningful. This is not required on COFF platforms, where our start and
  1503. // stop symbols will create the section.
  1504. if (!CGM.getTriple().isOSBinFormatCOFF()) {
  1505. createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
  1506. sectionName<SelectorSection>());
  1507. if (Categories.empty())
  1508. createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
  1509. NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
  1510. sectionName<CategorySection>());
  1511. if (!EmittedClass) {
  1512. createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
  1513. sectionName<ClassSection>());
  1514. createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
  1515. sectionName<ClassReferenceSection>());
  1516. }
  1517. if (!EmittedProtocol)
  1518. createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
  1519. NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
  1520. NULLPtr}, sectionName<ProtocolSection>());
  1521. if (!EmittedProtocolRef)
  1522. createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
  1523. sectionName<ProtocolReferenceSection>());
  1524. if (ClassAliases.empty())
  1525. createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
  1526. sectionName<ClassAliasSection>());
  1527. if (ConstantStrings.empty()) {
  1528. auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
  1529. createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
  1530. i32Zero, i32Zero, i32Zero, NULLPtr },
  1531. sectionName<ConstantStringSection>());
  1532. }
  1533. }
  1534. ConstantStrings.clear();
  1535. Categories.clear();
  1536. Classes.clear();
  1537. if (EarlyInitList.size() > 0) {
  1538. auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
  1539. {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
  1540. &CGM.getModule());
  1541. llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
  1542. Init));
  1543. for (const auto &lateInit : EarlyInitList) {
  1544. auto *global = TheModule.getGlobalVariable(lateInit.first);
  1545. if (global) {
  1546. llvm::GlobalVariable *GV = lateInit.second.first;
  1547. b.CreateAlignedStore(
  1548. global,
  1549. b.CreateStructGEP(GV->getValueType(), GV, lateInit.second.second),
  1550. CGM.getPointerAlign().getAsAlign());
  1551. }
  1552. }
  1553. b.CreateRetVoid();
  1554. // We can't use the normal LLVM global initialisation array, because we
  1555. // need to specify that this runs early in library initialisation.
  1556. auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  1557. /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
  1558. Init, ".objc_early_init_ptr");
  1559. InitVar->setSection(".CRT$XCLb");
  1560. CGM.addUsedGlobal(InitVar);
  1561. }
  1562. return nullptr;
  1563. }
  1564. /// In the v2 ABI, ivar offset variables use the type encoding in their name
  1565. /// to trigger linker failures if the types don't match.
  1566. std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
  1567. const ObjCIvarDecl *Ivar) override {
  1568. std::string TypeEncoding;
  1569. CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
  1570. // Prevent the @ from being interpreted as a symbol version.
  1571. std::replace(TypeEncoding.begin(), TypeEncoding.end(),
  1572. '@', '\1');
  1573. const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
  1574. + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
  1575. return Name;
  1576. }
  1577. llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
  1578. const ObjCInterfaceDecl *Interface,
  1579. const ObjCIvarDecl *Ivar) override {
  1580. const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
  1581. llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
  1582. if (!IvarOffsetPointer)
  1583. IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
  1584. llvm::GlobalValue::ExternalLinkage, nullptr, Name);
  1585. CharUnits Align = CGM.getIntAlign();
  1586. llvm::Value *Offset =
  1587. CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
  1588. if (Offset->getType() != PtrDiffTy)
  1589. Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
  1590. return Offset;
  1591. }
  1592. void GenerateClass(const ObjCImplementationDecl *OID) override {
  1593. ASTContext &Context = CGM.getContext();
  1594. bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
  1595. // Get the class name
  1596. ObjCInterfaceDecl *classDecl =
  1597. const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
  1598. std::string className = classDecl->getNameAsString();
  1599. auto *classNameConstant = MakeConstantString(className);
  1600. ConstantInitBuilder builder(CGM);
  1601. auto metaclassFields = builder.beginStruct();
  1602. // struct objc_class *isa;
  1603. metaclassFields.addNullPointer(PtrTy);
  1604. // struct objc_class *super_class;
  1605. metaclassFields.addNullPointer(PtrTy);
  1606. // const char *name;
  1607. metaclassFields.add(classNameConstant);
  1608. // long version;
  1609. metaclassFields.addInt(LongTy, 0);
  1610. // unsigned long info;
  1611. // objc_class_flag_meta
  1612. metaclassFields.addInt(LongTy, 1);
  1613. // long instance_size;
  1614. // Setting this to zero is consistent with the older ABI, but it might be
  1615. // more sensible to set this to sizeof(struct objc_class)
  1616. metaclassFields.addInt(LongTy, 0);
  1617. // struct objc_ivar_list *ivars;
  1618. metaclassFields.addNullPointer(PtrTy);
  1619. // struct objc_method_list *methods
  1620. // FIXME: Almost identical code is copied and pasted below for the
  1621. // class, but refactoring it cleanly requires C++14 generic lambdas.
  1622. if (OID->classmeth_begin() == OID->classmeth_end())
  1623. metaclassFields.addNullPointer(PtrTy);
  1624. else {
  1625. SmallVector<ObjCMethodDecl*, 16> ClassMethods;
  1626. ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
  1627. OID->classmeth_end());
  1628. metaclassFields.addBitCast(
  1629. GenerateMethodList(className, "", ClassMethods, true),
  1630. PtrTy);
  1631. }
  1632. // void *dtable;
  1633. metaclassFields.addNullPointer(PtrTy);
  1634. // IMP cxx_construct;
  1635. metaclassFields.addNullPointer(PtrTy);
  1636. // IMP cxx_destruct;
  1637. metaclassFields.addNullPointer(PtrTy);
  1638. // struct objc_class *subclass_list
  1639. metaclassFields.addNullPointer(PtrTy);
  1640. // struct objc_class *sibling_class
  1641. metaclassFields.addNullPointer(PtrTy);
  1642. // struct objc_protocol_list *protocols;
  1643. metaclassFields.addNullPointer(PtrTy);
  1644. // struct reference_list *extra_data;
  1645. metaclassFields.addNullPointer(PtrTy);
  1646. // long abi_version;
  1647. metaclassFields.addInt(LongTy, 0);
  1648. // struct objc_property_list *properties
  1649. metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
  1650. auto *metaclass = metaclassFields.finishAndCreateGlobal(
  1651. ManglePublicSymbol("OBJC_METACLASS_") + className,
  1652. CGM.getPointerAlign());
  1653. auto classFields = builder.beginStruct();
  1654. // struct objc_class *isa;
  1655. classFields.add(metaclass);
  1656. // struct objc_class *super_class;
  1657. // Get the superclass name.
  1658. const ObjCInterfaceDecl * SuperClassDecl =
  1659. OID->getClassInterface()->getSuperClass();
  1660. llvm::Constant *SuperClass = nullptr;
  1661. if (SuperClassDecl) {
  1662. auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
  1663. SuperClass = TheModule.getNamedGlobal(SuperClassName);
  1664. if (!SuperClass)
  1665. {
  1666. SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
  1667. llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
  1668. if (IsCOFF) {
  1669. auto Storage = llvm::GlobalValue::DefaultStorageClass;
  1670. if (SuperClassDecl->hasAttr<DLLImportAttr>())
  1671. Storage = llvm::GlobalValue::DLLImportStorageClass;
  1672. else if (SuperClassDecl->hasAttr<DLLExportAttr>())
  1673. Storage = llvm::GlobalValue::DLLExportStorageClass;
  1674. cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
  1675. }
  1676. }
  1677. if (!IsCOFF)
  1678. classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
  1679. else
  1680. classFields.addNullPointer(PtrTy);
  1681. } else
  1682. classFields.addNullPointer(PtrTy);
  1683. // const char *name;
  1684. classFields.add(classNameConstant);
  1685. // long version;
  1686. classFields.addInt(LongTy, 0);
  1687. // unsigned long info;
  1688. // !objc_class_flag_meta
  1689. classFields.addInt(LongTy, 0);
  1690. // long instance_size;
  1691. int superInstanceSize = !SuperClassDecl ? 0 :
  1692. Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
  1693. // Instance size is negative for classes that have not yet had their ivar
  1694. // layout calculated.
  1695. classFields.addInt(LongTy,
  1696. 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
  1697. superInstanceSize));
  1698. if (classDecl->all_declared_ivar_begin() == nullptr)
  1699. classFields.addNullPointer(PtrTy);
  1700. else {
  1701. int ivar_count = 0;
  1702. for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
  1703. IVD = IVD->getNextIvar()) ivar_count++;
  1704. llvm::DataLayout td(&TheModule);
  1705. // struct objc_ivar_list *ivars;
  1706. ConstantInitBuilder b(CGM);
  1707. auto ivarListBuilder = b.beginStruct();
  1708. // int count;
  1709. ivarListBuilder.addInt(IntTy, ivar_count);
  1710. // size_t size;
  1711. llvm::StructType *ObjCIvarTy = llvm::StructType::get(
  1712. PtrToInt8Ty,
  1713. PtrToInt8Ty,
  1714. PtrToInt8Ty,
  1715. Int32Ty,
  1716. Int32Ty);
  1717. ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
  1718. CGM.getContext().getCharWidth());
  1719. // struct objc_ivar ivars[]
  1720. auto ivarArrayBuilder = ivarListBuilder.beginArray();
  1721. for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
  1722. IVD = IVD->getNextIvar()) {
  1723. auto ivarTy = IVD->getType();
  1724. auto ivarBuilder = ivarArrayBuilder.beginStruct();
  1725. // const char *name;
  1726. ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
  1727. // const char *type;
  1728. std::string TypeStr;
  1729. //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
  1730. Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
  1731. ivarBuilder.add(MakeConstantString(TypeStr));
  1732. // int *offset;
  1733. uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
  1734. uint64_t Offset = BaseOffset - superInstanceSize;
  1735. llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
  1736. std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
  1737. llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
  1738. if (OffsetVar)
  1739. OffsetVar->setInitializer(OffsetValue);
  1740. else
  1741. OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
  1742. false, llvm::GlobalValue::ExternalLinkage,
  1743. OffsetValue, OffsetName);
  1744. auto ivarVisibility =
  1745. (IVD->getAccessControl() == ObjCIvarDecl::Private ||
  1746. IVD->getAccessControl() == ObjCIvarDecl::Package ||
  1747. classDecl->getVisibility() == HiddenVisibility) ?
  1748. llvm::GlobalValue::HiddenVisibility :
  1749. llvm::GlobalValue::DefaultVisibility;
  1750. OffsetVar->setVisibility(ivarVisibility);
  1751. ivarBuilder.add(OffsetVar);
  1752. // Ivar size
  1753. ivarBuilder.addInt(Int32Ty,
  1754. CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
  1755. // Alignment will be stored as a base-2 log of the alignment.
  1756. unsigned align =
  1757. llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
  1758. // Objects that require more than 2^64-byte alignment should be impossible!
  1759. assert(align < 64);
  1760. // uint32_t flags;
  1761. // Bits 0-1 are ownership.
  1762. // Bit 2 indicates an extended type encoding
  1763. // Bits 3-8 contain log2(aligment)
  1764. ivarBuilder.addInt(Int32Ty,
  1765. (align << 3) | (1<<2) |
  1766. FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
  1767. ivarBuilder.finishAndAddTo(ivarArrayBuilder);
  1768. }
  1769. ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
  1770. auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
  1771. CGM.getPointerAlign(), /*constant*/ false,
  1772. llvm::GlobalValue::PrivateLinkage);
  1773. classFields.add(ivarList);
  1774. }
  1775. // struct objc_method_list *methods
  1776. SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
  1777. InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
  1778. OID->instmeth_end());
  1779. for (auto *propImpl : OID->property_impls())
  1780. if (propImpl->getPropertyImplementation() ==
  1781. ObjCPropertyImplDecl::Synthesize) {
  1782. auto addIfExists = [&](const ObjCMethodDecl *OMD) {
  1783. if (OMD && OMD->hasBody())
  1784. InstanceMethods.push_back(OMD);
  1785. };
  1786. addIfExists(propImpl->getGetterMethodDecl());
  1787. addIfExists(propImpl->getSetterMethodDecl());
  1788. }
  1789. if (InstanceMethods.size() == 0)
  1790. classFields.addNullPointer(PtrTy);
  1791. else
  1792. classFields.addBitCast(
  1793. GenerateMethodList(className, "", InstanceMethods, false),
  1794. PtrTy);
  1795. // void *dtable;
  1796. classFields.addNullPointer(PtrTy);
  1797. // IMP cxx_construct;
  1798. classFields.addNullPointer(PtrTy);
  1799. // IMP cxx_destruct;
  1800. classFields.addNullPointer(PtrTy);
  1801. // struct objc_class *subclass_list
  1802. classFields.addNullPointer(PtrTy);
  1803. // struct objc_class *sibling_class
  1804. classFields.addNullPointer(PtrTy);
  1805. // struct objc_protocol_list *protocols;
  1806. auto RuntimeProtocols = GetRuntimeProtocolList(classDecl->protocol_begin(),
  1807. classDecl->protocol_end());
  1808. SmallVector<llvm::Constant *, 16> Protocols;
  1809. for (const auto *I : RuntimeProtocols)
  1810. Protocols.push_back(
  1811. llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
  1812. ProtocolPtrTy));
  1813. if (Protocols.empty())
  1814. classFields.addNullPointer(PtrTy);
  1815. else
  1816. classFields.add(GenerateProtocolList(Protocols));
  1817. // struct reference_list *extra_data;
  1818. classFields.addNullPointer(PtrTy);
  1819. // long abi_version;
  1820. classFields.addInt(LongTy, 0);
  1821. // struct objc_property_list *properties
  1822. classFields.add(GeneratePropertyList(OID, classDecl));
  1823. llvm::GlobalVariable *classStruct =
  1824. classFields.finishAndCreateGlobal(SymbolForClass(className),
  1825. CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
  1826. auto *classRefSymbol = GetClassVar(className);
  1827. classRefSymbol->setSection(sectionName<ClassReferenceSection>());
  1828. classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
  1829. if (IsCOFF) {
  1830. // we can't import a class struct.
  1831. if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
  1832. classStruct->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  1833. cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  1834. }
  1835. if (SuperClass) {
  1836. std::pair<llvm::GlobalVariable*, int> v{classStruct, 1};
  1837. EarlyInitList.emplace_back(std::string(SuperClass->getName()),
  1838. std::move(v));
  1839. }
  1840. }
  1841. // Resolve the class aliases, if they exist.
  1842. // FIXME: Class pointer aliases shouldn't exist!
  1843. if (ClassPtrAlias) {
  1844. ClassPtrAlias->replaceAllUsesWith(
  1845. llvm::ConstantExpr::getBitCast(classStruct, IdTy));
  1846. ClassPtrAlias->eraseFromParent();
  1847. ClassPtrAlias = nullptr;
  1848. }
  1849. if (auto Placeholder =
  1850. TheModule.getNamedGlobal(SymbolForClass(className)))
  1851. if (Placeholder != classStruct) {
  1852. Placeholder->replaceAllUsesWith(
  1853. llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
  1854. Placeholder->eraseFromParent();
  1855. classStruct->setName(SymbolForClass(className));
  1856. }
  1857. if (MetaClassPtrAlias) {
  1858. MetaClassPtrAlias->replaceAllUsesWith(
  1859. llvm::ConstantExpr::getBitCast(metaclass, IdTy));
  1860. MetaClassPtrAlias->eraseFromParent();
  1861. MetaClassPtrAlias = nullptr;
  1862. }
  1863. assert(classStruct->getName() == SymbolForClass(className));
  1864. auto classInitRef = new llvm::GlobalVariable(TheModule,
  1865. classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
  1866. classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
  1867. classInitRef->setSection(sectionName<ClassSection>());
  1868. CGM.addUsedGlobal(classInitRef);
  1869. EmittedClass = true;
  1870. }
  1871. public:
  1872. CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
  1873. MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
  1874. PtrToObjCSuperTy, SelectorTy);
  1875. // struct objc_property
  1876. // {
  1877. // const char *name;
  1878. // const char *attributes;
  1879. // const char *type;
  1880. // SEL getter;
  1881. // SEL setter;
  1882. // }
  1883. PropertyMetadataTy =
  1884. llvm::StructType::get(CGM.getLLVMContext(),
  1885. { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
  1886. }
  1887. };
  1888. const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
  1889. {
  1890. "__objc_selectors",
  1891. "__objc_classes",
  1892. "__objc_class_refs",
  1893. "__objc_cats",
  1894. "__objc_protocols",
  1895. "__objc_protocol_refs",
  1896. "__objc_class_aliases",
  1897. "__objc_constant_string"
  1898. };
  1899. const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
  1900. {
  1901. ".objcrt$SEL",
  1902. ".objcrt$CLS",
  1903. ".objcrt$CLR",
  1904. ".objcrt$CAT",
  1905. ".objcrt$PCL",
  1906. ".objcrt$PCR",
  1907. ".objcrt$CAL",
  1908. ".objcrt$STR"
  1909. };
  1910. /// Support for the ObjFW runtime.
  1911. class CGObjCObjFW: public CGObjCGNU {
  1912. protected:
  1913. /// The GCC ABI message lookup function. Returns an IMP pointing to the
  1914. /// method implementation for this message.
  1915. LazyRuntimeFunction MsgLookupFn;
  1916. /// stret lookup function. While this does not seem to make sense at the
  1917. /// first look, this is required to call the correct forwarding function.
  1918. LazyRuntimeFunction MsgLookupFnSRet;
  1919. /// The GCC ABI superclass message lookup function. Takes a pointer to a
  1920. /// structure describing the receiver and the class, and a selector as
  1921. /// arguments. Returns the IMP for the corresponding method.
  1922. LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
  1923. llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
  1924. llvm::Value *cmd, llvm::MDNode *node,
  1925. MessageSendInfo &MSI) override {
  1926. CGBuilderTy &Builder = CGF.Builder;
  1927. llvm::Value *args[] = {
  1928. EnforceType(Builder, Receiver, IdTy),
  1929. EnforceType(Builder, cmd, SelectorTy) };
  1930. llvm::CallBase *imp;
  1931. if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
  1932. imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
  1933. else
  1934. imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
  1935. imp->setMetadata(msgSendMDKind, node);
  1936. return imp;
  1937. }
  1938. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  1939. llvm::Value *cmd, MessageSendInfo &MSI) override {
  1940. CGBuilderTy &Builder = CGF.Builder;
  1941. llvm::Value *lookupArgs[] = {
  1942. EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
  1943. };
  1944. if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
  1945. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
  1946. else
  1947. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
  1948. }
  1949. llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
  1950. bool isWeak) override {
  1951. if (isWeak)
  1952. return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
  1953. EmitClassRef(Name);
  1954. std::string SymbolName = "_OBJC_CLASS_" + Name;
  1955. llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
  1956. if (!ClassSymbol)
  1957. ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
  1958. llvm::GlobalValue::ExternalLinkage,
  1959. nullptr, SymbolName);
  1960. return ClassSymbol;
  1961. }
  1962. public:
  1963. CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
  1964. // IMP objc_msg_lookup(id, SEL);
  1965. MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
  1966. MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
  1967. SelectorTy);
  1968. // IMP objc_msg_lookup_super(struct objc_super*, SEL);
  1969. MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
  1970. PtrToObjCSuperTy, SelectorTy);
  1971. MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
  1972. PtrToObjCSuperTy, SelectorTy);
  1973. }
  1974. };
  1975. } // end anonymous namespace
  1976. /// Emits a reference to a dummy variable which is emitted with each class.
  1977. /// This ensures that a linker error will be generated when trying to link
  1978. /// together modules where a referenced class is not defined.
  1979. void CGObjCGNU::EmitClassRef(const std::string &className) {
  1980. std::string symbolRef = "__objc_class_ref_" + className;
  1981. // Don't emit two copies of the same symbol
  1982. if (TheModule.getGlobalVariable(symbolRef))
  1983. return;
  1984. std::string symbolName = "__objc_class_name_" + className;
  1985. llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
  1986. if (!ClassSymbol) {
  1987. ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
  1988. llvm::GlobalValue::ExternalLinkage,
  1989. nullptr, symbolName);
  1990. }
  1991. new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
  1992. llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
  1993. }
  1994. CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
  1995. unsigned protocolClassVersion, unsigned classABI)
  1996. : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
  1997. VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
  1998. MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
  1999. ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
  2000. msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
  2001. usesSEHExceptions =
  2002. cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
  2003. CodeGenTypes &Types = CGM.getTypes();
  2004. IntTy = cast<llvm::IntegerType>(
  2005. Types.ConvertType(CGM.getContext().IntTy));
  2006. LongTy = cast<llvm::IntegerType>(
  2007. Types.ConvertType(CGM.getContext().LongTy));
  2008. SizeTy = cast<llvm::IntegerType>(
  2009. Types.ConvertType(CGM.getContext().getSizeType()));
  2010. PtrDiffTy = cast<llvm::IntegerType>(
  2011. Types.ConvertType(CGM.getContext().getPointerDiffType()));
  2012. BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
  2013. Int8Ty = llvm::Type::getInt8Ty(VMContext);
  2014. // C string type. Used in lots of places.
  2015. PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
  2016. ProtocolPtrTy = llvm::PointerType::getUnqual(
  2017. Types.ConvertType(CGM.getContext().getObjCProtoType()));
  2018. Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
  2019. Zeros[1] = Zeros[0];
  2020. NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
  2021. // Get the selector Type.
  2022. QualType selTy = CGM.getContext().getObjCSelType();
  2023. if (QualType() == selTy) {
  2024. SelectorTy = PtrToInt8Ty;
  2025. SelectorElemTy = Int8Ty;
  2026. } else {
  2027. SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
  2028. SelectorElemTy = CGM.getTypes().ConvertTypeForMem(selTy->getPointeeType());
  2029. }
  2030. PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
  2031. PtrTy = PtrToInt8Ty;
  2032. Int32Ty = llvm::Type::getInt32Ty(VMContext);
  2033. Int64Ty = llvm::Type::getInt64Ty(VMContext);
  2034. IntPtrTy =
  2035. CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
  2036. // Object type
  2037. QualType UnqualIdTy = CGM.getContext().getObjCIdType();
  2038. ASTIdTy = CanQualType();
  2039. if (UnqualIdTy != QualType()) {
  2040. ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
  2041. IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
  2042. IdElemTy = CGM.getTypes().ConvertTypeForMem(
  2043. ASTIdTy.getTypePtr()->getPointeeType());
  2044. } else {
  2045. IdTy = PtrToInt8Ty;
  2046. IdElemTy = Int8Ty;
  2047. }
  2048. PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
  2049. ProtocolTy = llvm::StructType::get(IdTy,
  2050. PtrToInt8Ty, // name
  2051. PtrToInt8Ty, // protocols
  2052. PtrToInt8Ty, // instance methods
  2053. PtrToInt8Ty, // class methods
  2054. PtrToInt8Ty, // optional instance methods
  2055. PtrToInt8Ty, // optional class methods
  2056. PtrToInt8Ty, // properties
  2057. PtrToInt8Ty);// optional properties
  2058. // struct objc_property_gsv1
  2059. // {
  2060. // const char *name;
  2061. // char attributes;
  2062. // char attributes2;
  2063. // char unused1;
  2064. // char unused2;
  2065. // const char *getter_name;
  2066. // const char *getter_types;
  2067. // const char *setter_name;
  2068. // const char *setter_types;
  2069. // }
  2070. PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
  2071. PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
  2072. PtrToInt8Ty, PtrToInt8Ty });
  2073. ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
  2074. PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
  2075. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  2076. // void objc_exception_throw(id);
  2077. ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
  2078. ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
  2079. // int objc_sync_enter(id);
  2080. SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
  2081. // int objc_sync_exit(id);
  2082. SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
  2083. // void objc_enumerationMutation (id)
  2084. EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
  2085. // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
  2086. GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
  2087. PtrDiffTy, BoolTy);
  2088. // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
  2089. SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
  2090. PtrDiffTy, IdTy, BoolTy, BoolTy);
  2091. // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
  2092. GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
  2093. PtrDiffTy, BoolTy, BoolTy);
  2094. // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
  2095. SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
  2096. PtrDiffTy, BoolTy, BoolTy);
  2097. // IMP type
  2098. llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
  2099. IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
  2100. true));
  2101. const LangOptions &Opts = CGM.getLangOpts();
  2102. if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
  2103. RuntimeVersion = 10;
  2104. // Don't bother initialising the GC stuff unless we're compiling in GC mode
  2105. if (Opts.getGC() != LangOptions::NonGC) {
  2106. // This is a bit of an hack. We should sort this out by having a proper
  2107. // CGObjCGNUstep subclass for GC, but we may want to really support the old
  2108. // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
  2109. // Get selectors needed in GC mode
  2110. RetainSel = GetNullarySelector("retain", CGM.getContext());
  2111. ReleaseSel = GetNullarySelector("release", CGM.getContext());
  2112. AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
  2113. // Get functions needed in GC mode
  2114. // id objc_assign_ivar(id, id, ptrdiff_t);
  2115. IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
  2116. // id objc_assign_strongCast (id, id*)
  2117. StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
  2118. PtrToIdTy);
  2119. // id objc_assign_global(id, id*);
  2120. GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
  2121. // id objc_assign_weak(id, id*);
  2122. WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
  2123. // id objc_read_weak(id*);
  2124. WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
  2125. // void *objc_memmove_collectable(void*, void *, size_t);
  2126. MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
  2127. SizeTy);
  2128. }
  2129. }
  2130. llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
  2131. const std::string &Name, bool isWeak) {
  2132. llvm::Constant *ClassName = MakeConstantString(Name);
  2133. // With the incompatible ABI, this will need to be replaced with a direct
  2134. // reference to the class symbol. For the compatible nonfragile ABI we are
  2135. // still performing this lookup at run time but emitting the symbol for the
  2136. // class externally so that we can make the switch later.
  2137. //
  2138. // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
  2139. // with memoized versions or with static references if it's safe to do so.
  2140. if (!isWeak)
  2141. EmitClassRef(Name);
  2142. llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
  2143. llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
  2144. return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
  2145. }
  2146. // This has to perform the lookup every time, since posing and related
  2147. // techniques can modify the name -> class mapping.
  2148. llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
  2149. const ObjCInterfaceDecl *OID) {
  2150. auto *Value =
  2151. GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
  2152. if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
  2153. CGM.setGVProperties(ClassSymbol, OID);
  2154. return Value;
  2155. }
  2156. llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
  2157. auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
  2158. if (CGM.getTriple().isOSBinFormatCOFF()) {
  2159. if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
  2160. IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
  2161. TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
  2162. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2163. const VarDecl *VD = nullptr;
  2164. for (const auto *Result : DC->lookup(&II))
  2165. if ((VD = dyn_cast<VarDecl>(Result)))
  2166. break;
  2167. CGM.setGVProperties(ClassSymbol, VD);
  2168. }
  2169. }
  2170. return Value;
  2171. }
  2172. llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
  2173. const std::string &TypeEncoding) {
  2174. SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
  2175. llvm::GlobalAlias *SelValue = nullptr;
  2176. for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
  2177. e = Types.end() ; i!=e ; i++) {
  2178. if (i->first == TypeEncoding) {
  2179. SelValue = i->second;
  2180. break;
  2181. }
  2182. }
  2183. if (!SelValue) {
  2184. SelValue = llvm::GlobalAlias::create(SelectorElemTy, 0,
  2185. llvm::GlobalValue::PrivateLinkage,
  2186. ".objc_selector_" + Sel.getAsString(),
  2187. &TheModule);
  2188. Types.emplace_back(TypeEncoding, SelValue);
  2189. }
  2190. return SelValue;
  2191. }
  2192. Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
  2193. llvm::Value *SelValue = GetSelector(CGF, Sel);
  2194. // Store it to a temporary. Does this satisfy the semantics of
  2195. // GetAddrOfSelector? Hopefully.
  2196. Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
  2197. CGF.getPointerAlign());
  2198. CGF.Builder.CreateStore(SelValue, tmp);
  2199. return tmp;
  2200. }
  2201. llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
  2202. return GetTypedSelector(CGF, Sel, std::string());
  2203. }
  2204. llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
  2205. const ObjCMethodDecl *Method) {
  2206. std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
  2207. return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
  2208. }
  2209. llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
  2210. if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
  2211. // With the old ABI, there was only one kind of catchall, which broke
  2212. // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
  2213. // a pointer indicating object catchalls, and NULL to indicate real
  2214. // catchalls
  2215. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  2216. return MakeConstantString("@id");
  2217. } else {
  2218. return nullptr;
  2219. }
  2220. }
  2221. // All other types should be Objective-C interface pointer types.
  2222. const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
  2223. assert(OPT && "Invalid @catch type.");
  2224. const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
  2225. assert(IDecl && "Invalid @catch type.");
  2226. return MakeConstantString(IDecl->getIdentifier()->getName());
  2227. }
  2228. llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
  2229. if (usesSEHExceptions)
  2230. return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
  2231. if (!CGM.getLangOpts().CPlusPlus)
  2232. return CGObjCGNU::GetEHType(T);
  2233. // For Objective-C++, we want to provide the ability to catch both C++ and
  2234. // Objective-C objects in the same function.
  2235. // There's a particular fixed type info for 'id'.
  2236. if (T->isObjCIdType() ||
  2237. T->isObjCQualifiedIdType()) {
  2238. llvm::Constant *IDEHType =
  2239. CGM.getModule().getGlobalVariable("__objc_id_type_info");
  2240. if (!IDEHType)
  2241. IDEHType =
  2242. new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
  2243. false,
  2244. llvm::GlobalValue::ExternalLinkage,
  2245. nullptr, "__objc_id_type_info");
  2246. return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
  2247. }
  2248. const ObjCObjectPointerType *PT =
  2249. T->getAs<ObjCObjectPointerType>();
  2250. assert(PT && "Invalid @catch type.");
  2251. const ObjCInterfaceType *IT = PT->getInterfaceType();
  2252. assert(IT && "Invalid @catch type.");
  2253. std::string className =
  2254. std::string(IT->getDecl()->getIdentifier()->getName());
  2255. std::string typeinfoName = "__objc_eh_typeinfo_" + className;
  2256. // Return the existing typeinfo if it exists
  2257. llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
  2258. if (typeinfo)
  2259. return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
  2260. // Otherwise create it.
  2261. // vtable for gnustep::libobjc::__objc_class_type_info
  2262. // It's quite ugly hard-coding this. Ideally we'd generate it using the host
  2263. // platform's name mangling.
  2264. const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
  2265. auto *Vtable = TheModule.getGlobalVariable(vtableName);
  2266. if (!Vtable) {
  2267. Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
  2268. llvm::GlobalValue::ExternalLinkage,
  2269. nullptr, vtableName);
  2270. }
  2271. llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
  2272. auto *BVtable = llvm::ConstantExpr::getBitCast(
  2273. llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
  2274. PtrToInt8Ty);
  2275. llvm::Constant *typeName =
  2276. ExportUniqueString(className, "__objc_eh_typename_");
  2277. ConstantInitBuilder builder(CGM);
  2278. auto fields = builder.beginStruct();
  2279. fields.add(BVtable);
  2280. fields.add(typeName);
  2281. llvm::Constant *TI =
  2282. fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
  2283. CGM.getPointerAlign(),
  2284. /*constant*/ false,
  2285. llvm::GlobalValue::LinkOnceODRLinkage);
  2286. return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
  2287. }
  2288. /// Generate an NSConstantString object.
  2289. ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
  2290. std::string Str = SL->getString().str();
  2291. CharUnits Align = CGM.getPointerAlign();
  2292. // Look for an existing one
  2293. llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
  2294. if (old != ObjCStrings.end())
  2295. return ConstantAddress(old->getValue(), Int8Ty, Align);
  2296. StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
  2297. if (StringClass.empty()) StringClass = "NSConstantString";
  2298. std::string Sym = "_OBJC_CLASS_";
  2299. Sym += StringClass;
  2300. llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
  2301. if (!isa)
  2302. isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
  2303. llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
  2304. else if (isa->getType() != PtrToIdTy)
  2305. isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
  2306. ConstantInitBuilder Builder(CGM);
  2307. auto Fields = Builder.beginStruct();
  2308. Fields.add(isa);
  2309. Fields.add(MakeConstantString(Str));
  2310. Fields.addInt(IntTy, Str.size());
  2311. llvm::Constant *ObjCStr =
  2312. Fields.finishAndCreateGlobal(".objc_str", Align);
  2313. ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
  2314. ObjCStrings[Str] = ObjCStr;
  2315. ConstantStrings.push_back(ObjCStr);
  2316. return ConstantAddress(ObjCStr, Int8Ty, Align);
  2317. }
  2318. ///Generates a message send where the super is the receiver. This is a message
  2319. ///send to self with special delivery semantics indicating which class's method
  2320. ///should be called.
  2321. RValue
  2322. CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
  2323. ReturnValueSlot Return,
  2324. QualType ResultType,
  2325. Selector Sel,
  2326. const ObjCInterfaceDecl *Class,
  2327. bool isCategoryImpl,
  2328. llvm::Value *Receiver,
  2329. bool IsClassMessage,
  2330. const CallArgList &CallArgs,
  2331. const ObjCMethodDecl *Method) {
  2332. CGBuilderTy &Builder = CGF.Builder;
  2333. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
  2334. if (Sel == RetainSel || Sel == AutoreleaseSel) {
  2335. return RValue::get(EnforceType(Builder, Receiver,
  2336. CGM.getTypes().ConvertType(ResultType)));
  2337. }
  2338. if (Sel == ReleaseSel) {
  2339. return RValue::get(nullptr);
  2340. }
  2341. }
  2342. llvm::Value *cmd = GetSelector(CGF, Sel);
  2343. CallArgList ActualArgs;
  2344. ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
  2345. ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
  2346. ActualArgs.addFrom(CallArgs);
  2347. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
  2348. llvm::Value *ReceiverClass = nullptr;
  2349. bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
  2350. if (isV2ABI) {
  2351. ReceiverClass = GetClassNamed(CGF,
  2352. Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
  2353. if (IsClassMessage) {
  2354. // Load the isa pointer of the superclass is this is a class method.
  2355. ReceiverClass = Builder.CreateBitCast(ReceiverClass,
  2356. llvm::PointerType::getUnqual(IdTy));
  2357. ReceiverClass =
  2358. Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
  2359. }
  2360. ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
  2361. } else {
  2362. if (isCategoryImpl) {
  2363. llvm::FunctionCallee classLookupFunction = nullptr;
  2364. if (IsClassMessage) {
  2365. classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
  2366. IdTy, PtrTy, true), "objc_get_meta_class");
  2367. } else {
  2368. classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
  2369. IdTy, PtrTy, true), "objc_get_class");
  2370. }
  2371. ReceiverClass = Builder.CreateCall(classLookupFunction,
  2372. MakeConstantString(Class->getNameAsString()));
  2373. } else {
  2374. // Set up global aliases for the metaclass or class pointer if they do not
  2375. // already exist. These will are forward-references which will be set to
  2376. // pointers to the class and metaclass structure created for the runtime
  2377. // load function. To send a message to super, we look up the value of the
  2378. // super_class pointer from either the class or metaclass structure.
  2379. if (IsClassMessage) {
  2380. if (!MetaClassPtrAlias) {
  2381. MetaClassPtrAlias = llvm::GlobalAlias::create(
  2382. IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
  2383. ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
  2384. }
  2385. ReceiverClass = MetaClassPtrAlias;
  2386. } else {
  2387. if (!ClassPtrAlias) {
  2388. ClassPtrAlias = llvm::GlobalAlias::create(
  2389. IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
  2390. ".objc_class_ref" + Class->getNameAsString(), &TheModule);
  2391. }
  2392. ReceiverClass = ClassPtrAlias;
  2393. }
  2394. }
  2395. // Cast the pointer to a simplified version of the class structure
  2396. llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
  2397. ReceiverClass = Builder.CreateBitCast(ReceiverClass,
  2398. llvm::PointerType::getUnqual(CastTy));
  2399. // Get the superclass pointer
  2400. ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
  2401. // Load the superclass pointer
  2402. ReceiverClass =
  2403. Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
  2404. }
  2405. // Construct the structure used to look up the IMP
  2406. llvm::StructType *ObjCSuperTy =
  2407. llvm::StructType::get(Receiver->getType(), IdTy);
  2408. Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
  2409. CGF.getPointerAlign());
  2410. Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
  2411. Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
  2412. // Get the IMP
  2413. llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
  2414. imp = EnforceType(Builder, imp, MSI.MessengerType);
  2415. llvm::Metadata *impMD[] = {
  2416. llvm::MDString::get(VMContext, Sel.getAsString()),
  2417. llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
  2418. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  2419. llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
  2420. llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
  2421. CGCallee callee(CGCalleeInfo(), imp);
  2422. llvm::CallBase *call;
  2423. RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
  2424. call->setMetadata(msgSendMDKind, node);
  2425. return msgRet;
  2426. }
  2427. /// Generate code for a message send expression.
  2428. RValue
  2429. CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
  2430. ReturnValueSlot Return,
  2431. QualType ResultType,
  2432. Selector Sel,
  2433. llvm::Value *Receiver,
  2434. const CallArgList &CallArgs,
  2435. const ObjCInterfaceDecl *Class,
  2436. const ObjCMethodDecl *Method) {
  2437. CGBuilderTy &Builder = CGF.Builder;
  2438. // Strip out message sends to retain / release in GC mode
  2439. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
  2440. if (Sel == RetainSel || Sel == AutoreleaseSel) {
  2441. return RValue::get(EnforceType(Builder, Receiver,
  2442. CGM.getTypes().ConvertType(ResultType)));
  2443. }
  2444. if (Sel == ReleaseSel) {
  2445. return RValue::get(nullptr);
  2446. }
  2447. }
  2448. IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
  2449. llvm::Value *cmd;
  2450. if (Method)
  2451. cmd = GetSelector(CGF, Method);
  2452. else
  2453. cmd = GetSelector(CGF, Sel);
  2454. cmd = EnforceType(Builder, cmd, SelectorTy);
  2455. Receiver = EnforceType(Builder, Receiver, IdTy);
  2456. llvm::Metadata *impMD[] = {
  2457. llvm::MDString::get(VMContext, Sel.getAsString()),
  2458. llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
  2459. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  2460. llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
  2461. llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
  2462. CallArgList ActualArgs;
  2463. ActualArgs.add(RValue::get(Receiver), ASTIdTy);
  2464. ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
  2465. ActualArgs.addFrom(CallArgs);
  2466. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
  2467. // Message sends are expected to return a zero value when the
  2468. // receiver is nil. At one point, this was only guaranteed for
  2469. // simple integer and pointer types, but expectations have grown
  2470. // over time.
  2471. //
  2472. // Given a nil receiver, the GNU runtime's message lookup will
  2473. // return a stub function that simply sets various return-value
  2474. // registers to zero and then returns. That's good enough for us
  2475. // if and only if (1) the calling conventions of that stub are
  2476. // compatible with the signature we're using and (2) the registers
  2477. // it sets are sufficient to produce a zero value of the return type.
  2478. // Rather than doing a whole target-specific analysis, we assume it
  2479. // only works for void, integer, and pointer types, and in all
  2480. // other cases we do an explicit nil check is emitted code. In
  2481. // addition to ensuring we produe a zero value for other types, this
  2482. // sidesteps the few outright CC incompatibilities we know about that
  2483. // could otherwise lead to crashes, like when a method is expected to
  2484. // return on the x87 floating point stack or adjust the stack pointer
  2485. // because of an indirect return.
  2486. bool hasParamDestroyedInCallee = false;
  2487. bool requiresExplicitZeroResult = false;
  2488. bool requiresNilReceiverCheck = [&] {
  2489. // We never need a check if we statically know the receiver isn't nil.
  2490. if (!canMessageReceiverBeNull(CGF, Method, /*IsSuper*/ false,
  2491. Class, Receiver))
  2492. return false;
  2493. // If there's a consumed argument, we need a nil check.
  2494. if (Method && Method->hasParamDestroyedInCallee()) {
  2495. hasParamDestroyedInCallee = true;
  2496. }
  2497. // If the return value isn't flagged as unused, and the result
  2498. // type isn't in our narrow set where we assume compatibility,
  2499. // we need a nil check to ensure a nil value.
  2500. if (!Return.isUnused()) {
  2501. if (ResultType->isVoidType()) {
  2502. // void results are definitely okay.
  2503. } else if (ResultType->hasPointerRepresentation() &&
  2504. CGM.getTypes().isZeroInitializable(ResultType)) {
  2505. // Pointer types should be fine as long as they have
  2506. // bitwise-zero null pointers. But do we need to worry
  2507. // about unusual address spaces?
  2508. } else if (ResultType->isIntegralOrEnumerationType()) {
  2509. // Bitwise zero should always be zero for integral types.
  2510. // FIXME: we probably need a size limit here, but we've
  2511. // never imposed one before
  2512. } else {
  2513. // Otherwise, use an explicit check just to be sure.
  2514. requiresExplicitZeroResult = true;
  2515. }
  2516. }
  2517. return hasParamDestroyedInCallee || requiresExplicitZeroResult;
  2518. }();
  2519. // We will need to explicitly zero-initialize an aggregate result slot
  2520. // if we generally require explicit zeroing and we have an aggregate
  2521. // result.
  2522. bool requiresExplicitAggZeroing =
  2523. requiresExplicitZeroResult && CGF.hasAggregateEvaluationKind(ResultType);
  2524. // The block we're going to end up in after any message send or nil path.
  2525. llvm::BasicBlock *continueBB = nullptr;
  2526. // The block that eventually branched to continueBB along the nil path.
  2527. llvm::BasicBlock *nilPathBB = nullptr;
  2528. // The block to do explicit work in along the nil path, if necessary.
  2529. llvm::BasicBlock *nilCleanupBB = nullptr;
  2530. // Emit the nil-receiver check.
  2531. if (requiresNilReceiverCheck) {
  2532. llvm::BasicBlock *messageBB = CGF.createBasicBlock("msgSend");
  2533. continueBB = CGF.createBasicBlock("continue");
  2534. // If we need to zero-initialize an aggregate result or destroy
  2535. // consumed arguments, we'll need a separate cleanup block.
  2536. // Otherwise we can just branch directly to the continuation block.
  2537. if (requiresExplicitAggZeroing || hasParamDestroyedInCallee) {
  2538. nilCleanupBB = CGF.createBasicBlock("nilReceiverCleanup");
  2539. } else {
  2540. nilPathBB = Builder.GetInsertBlock();
  2541. }
  2542. llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
  2543. llvm::Constant::getNullValue(Receiver->getType()));
  2544. Builder.CreateCondBr(isNil, nilCleanupBB ? nilCleanupBB : continueBB,
  2545. messageBB);
  2546. CGF.EmitBlock(messageBB);
  2547. }
  2548. // Get the IMP to call
  2549. llvm::Value *imp;
  2550. // If we have non-legacy dispatch specified, we try using the objc_msgSend()
  2551. // functions. These are not supported on all platforms (or all runtimes on a
  2552. // given platform), so we
  2553. switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
  2554. case CodeGenOptions::Legacy:
  2555. imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
  2556. break;
  2557. case CodeGenOptions::Mixed:
  2558. case CodeGenOptions::NonLegacy:
  2559. if (CGM.ReturnTypeUsesFPRet(ResultType)) {
  2560. imp =
  2561. CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  2562. "objc_msgSend_fpret")
  2563. .getCallee();
  2564. } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
  2565. // The actual types here don't matter - we're going to bitcast the
  2566. // function anyway
  2567. imp =
  2568. CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  2569. "objc_msgSend_stret")
  2570. .getCallee();
  2571. } else {
  2572. imp = CGM.CreateRuntimeFunction(
  2573. llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
  2574. .getCallee();
  2575. }
  2576. }
  2577. // Reset the receiver in case the lookup modified it
  2578. ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
  2579. imp = EnforceType(Builder, imp, MSI.MessengerType);
  2580. llvm::CallBase *call;
  2581. CGCallee callee(CGCalleeInfo(), imp);
  2582. RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
  2583. call->setMetadata(msgSendMDKind, node);
  2584. if (requiresNilReceiverCheck) {
  2585. llvm::BasicBlock *nonNilPathBB = CGF.Builder.GetInsertBlock();
  2586. CGF.Builder.CreateBr(continueBB);
  2587. // Emit the nil path if we decided it was necessary above.
  2588. if (nilCleanupBB) {
  2589. CGF.EmitBlock(nilCleanupBB);
  2590. if (hasParamDestroyedInCallee) {
  2591. destroyCalleeDestroyedArguments(CGF, Method, CallArgs);
  2592. }
  2593. if (requiresExplicitAggZeroing) {
  2594. assert(msgRet.isAggregate());
  2595. Address addr = msgRet.getAggregateAddress();
  2596. CGF.EmitNullInitialization(addr, ResultType);
  2597. }
  2598. nilPathBB = CGF.Builder.GetInsertBlock();
  2599. CGF.Builder.CreateBr(continueBB);
  2600. }
  2601. // Enter the continuation block and emit a phi if required.
  2602. CGF.EmitBlock(continueBB);
  2603. if (msgRet.isScalar()) {
  2604. // If the return type is void, do nothing
  2605. if (llvm::Value *v = msgRet.getScalarVal()) {
  2606. llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
  2607. phi->addIncoming(v, nonNilPathBB);
  2608. phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB);
  2609. msgRet = RValue::get(phi);
  2610. }
  2611. } else if (msgRet.isAggregate()) {
  2612. // Aggregate zeroing is handled in nilCleanupBB when it's required.
  2613. } else /* isComplex() */ {
  2614. std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
  2615. llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
  2616. phi->addIncoming(v.first, nonNilPathBB);
  2617. phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
  2618. nilPathBB);
  2619. llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
  2620. phi2->addIncoming(v.second, nonNilPathBB);
  2621. phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
  2622. nilPathBB);
  2623. msgRet = RValue::getComplex(phi, phi2);
  2624. }
  2625. }
  2626. return msgRet;
  2627. }
  2628. /// Generates a MethodList. Used in construction of a objc_class and
  2629. /// objc_category structures.
  2630. llvm::Constant *CGObjCGNU::
  2631. GenerateMethodList(StringRef ClassName,
  2632. StringRef CategoryName,
  2633. ArrayRef<const ObjCMethodDecl*> Methods,
  2634. bool isClassMethodList) {
  2635. if (Methods.empty())
  2636. return NULLPtr;
  2637. ConstantInitBuilder Builder(CGM);
  2638. auto MethodList = Builder.beginStruct();
  2639. MethodList.addNullPointer(CGM.Int8PtrTy);
  2640. MethodList.addInt(Int32Ty, Methods.size());
  2641. // Get the method structure type.
  2642. llvm::StructType *ObjCMethodTy =
  2643. llvm::StructType::get(CGM.getLLVMContext(), {
  2644. PtrToInt8Ty, // Really a selector, but the runtime creates it us.
  2645. PtrToInt8Ty, // Method types
  2646. IMPTy // Method pointer
  2647. });
  2648. bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
  2649. if (isV2ABI) {
  2650. // size_t size;
  2651. llvm::DataLayout td(&TheModule);
  2652. MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
  2653. CGM.getContext().getCharWidth());
  2654. ObjCMethodTy =
  2655. llvm::StructType::get(CGM.getLLVMContext(), {
  2656. IMPTy, // Method pointer
  2657. PtrToInt8Ty, // Selector
  2658. PtrToInt8Ty // Extended type encoding
  2659. });
  2660. } else {
  2661. ObjCMethodTy =
  2662. llvm::StructType::get(CGM.getLLVMContext(), {
  2663. PtrToInt8Ty, // Really a selector, but the runtime creates it us.
  2664. PtrToInt8Ty, // Method types
  2665. IMPTy // Method pointer
  2666. });
  2667. }
  2668. auto MethodArray = MethodList.beginArray();
  2669. ASTContext &Context = CGM.getContext();
  2670. for (const auto *OMD : Methods) {
  2671. llvm::Constant *FnPtr =
  2672. TheModule.getFunction(getSymbolNameForMethod(OMD));
  2673. assert(FnPtr && "Can't generate metadata for method that doesn't exist");
  2674. auto Method = MethodArray.beginStruct(ObjCMethodTy);
  2675. if (isV2ABI) {
  2676. Method.addBitCast(FnPtr, IMPTy);
  2677. Method.add(GetConstantSelector(OMD->getSelector(),
  2678. Context.getObjCEncodingForMethodDecl(OMD)));
  2679. Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
  2680. } else {
  2681. Method.add(MakeConstantString(OMD->getSelector().getAsString()));
  2682. Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
  2683. Method.addBitCast(FnPtr, IMPTy);
  2684. }
  2685. Method.finishAndAddTo(MethodArray);
  2686. }
  2687. MethodArray.finishAndAddTo(MethodList);
  2688. // Create an instance of the structure
  2689. return MethodList.finishAndCreateGlobal(".objc_method_list",
  2690. CGM.getPointerAlign());
  2691. }
  2692. /// Generates an IvarList. Used in construction of a objc_class.
  2693. llvm::Constant *CGObjCGNU::
  2694. GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
  2695. ArrayRef<llvm::Constant *> IvarTypes,
  2696. ArrayRef<llvm::Constant *> IvarOffsets,
  2697. ArrayRef<llvm::Constant *> IvarAlign,
  2698. ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
  2699. if (IvarNames.empty())
  2700. return NULLPtr;
  2701. ConstantInitBuilder Builder(CGM);
  2702. // Structure containing array count followed by array.
  2703. auto IvarList = Builder.beginStruct();
  2704. IvarList.addInt(IntTy, (int)IvarNames.size());
  2705. // Get the ivar structure type.
  2706. llvm::StructType *ObjCIvarTy =
  2707. llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
  2708. // Array of ivar structures.
  2709. auto Ivars = IvarList.beginArray(ObjCIvarTy);
  2710. for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
  2711. auto Ivar = Ivars.beginStruct(ObjCIvarTy);
  2712. Ivar.add(IvarNames[i]);
  2713. Ivar.add(IvarTypes[i]);
  2714. Ivar.add(IvarOffsets[i]);
  2715. Ivar.finishAndAddTo(Ivars);
  2716. }
  2717. Ivars.finishAndAddTo(IvarList);
  2718. // Create an instance of the structure
  2719. return IvarList.finishAndCreateGlobal(".objc_ivar_list",
  2720. CGM.getPointerAlign());
  2721. }
  2722. /// Generate a class structure
  2723. llvm::Constant *CGObjCGNU::GenerateClassStructure(
  2724. llvm::Constant *MetaClass,
  2725. llvm::Constant *SuperClass,
  2726. unsigned info,
  2727. const char *Name,
  2728. llvm::Constant *Version,
  2729. llvm::Constant *InstanceSize,
  2730. llvm::Constant *IVars,
  2731. llvm::Constant *Methods,
  2732. llvm::Constant *Protocols,
  2733. llvm::Constant *IvarOffsets,
  2734. llvm::Constant *Properties,
  2735. llvm::Constant *StrongIvarBitmap,
  2736. llvm::Constant *WeakIvarBitmap,
  2737. bool isMeta) {
  2738. // Set up the class structure
  2739. // Note: Several of these are char*s when they should be ids. This is
  2740. // because the runtime performs this translation on load.
  2741. //
  2742. // Fields marked New ABI are part of the GNUstep runtime. We emit them
  2743. // anyway; the classes will still work with the GNU runtime, they will just
  2744. // be ignored.
  2745. llvm::StructType *ClassTy = llvm::StructType::get(
  2746. PtrToInt8Ty, // isa
  2747. PtrToInt8Ty, // super_class
  2748. PtrToInt8Ty, // name
  2749. LongTy, // version
  2750. LongTy, // info
  2751. LongTy, // instance_size
  2752. IVars->getType(), // ivars
  2753. Methods->getType(), // methods
  2754. // These are all filled in by the runtime, so we pretend
  2755. PtrTy, // dtable
  2756. PtrTy, // subclass_list
  2757. PtrTy, // sibling_class
  2758. PtrTy, // protocols
  2759. PtrTy, // gc_object_type
  2760. // New ABI:
  2761. LongTy, // abi_version
  2762. IvarOffsets->getType(), // ivar_offsets
  2763. Properties->getType(), // properties
  2764. IntPtrTy, // strong_pointers
  2765. IntPtrTy // weak_pointers
  2766. );
  2767. ConstantInitBuilder Builder(CGM);
  2768. auto Elements = Builder.beginStruct(ClassTy);
  2769. // Fill in the structure
  2770. // isa
  2771. Elements.addBitCast(MetaClass, PtrToInt8Ty);
  2772. // super_class
  2773. Elements.add(SuperClass);
  2774. // name
  2775. Elements.add(MakeConstantString(Name, ".class_name"));
  2776. // version
  2777. Elements.addInt(LongTy, 0);
  2778. // info
  2779. Elements.addInt(LongTy, info);
  2780. // instance_size
  2781. if (isMeta) {
  2782. llvm::DataLayout td(&TheModule);
  2783. Elements.addInt(LongTy,
  2784. td.getTypeSizeInBits(ClassTy) /
  2785. CGM.getContext().getCharWidth());
  2786. } else
  2787. Elements.add(InstanceSize);
  2788. // ivars
  2789. Elements.add(IVars);
  2790. // methods
  2791. Elements.add(Methods);
  2792. // These are all filled in by the runtime, so we pretend
  2793. // dtable
  2794. Elements.add(NULLPtr);
  2795. // subclass_list
  2796. Elements.add(NULLPtr);
  2797. // sibling_class
  2798. Elements.add(NULLPtr);
  2799. // protocols
  2800. Elements.addBitCast(Protocols, PtrTy);
  2801. // gc_object_type
  2802. Elements.add(NULLPtr);
  2803. // abi_version
  2804. Elements.addInt(LongTy, ClassABIVersion);
  2805. // ivar_offsets
  2806. Elements.add(IvarOffsets);
  2807. // properties
  2808. Elements.add(Properties);
  2809. // strong_pointers
  2810. Elements.add(StrongIvarBitmap);
  2811. // weak_pointers
  2812. Elements.add(WeakIvarBitmap);
  2813. // Create an instance of the structure
  2814. // This is now an externally visible symbol, so that we can speed up class
  2815. // messages in the next ABI. We may already have some weak references to
  2816. // this, so check and fix them properly.
  2817. std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
  2818. std::string(Name));
  2819. llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
  2820. llvm::Constant *Class =
  2821. Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
  2822. llvm::GlobalValue::ExternalLinkage);
  2823. if (ClassRef) {
  2824. ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
  2825. ClassRef->getType()));
  2826. ClassRef->removeFromParent();
  2827. Class->setName(ClassSym);
  2828. }
  2829. return Class;
  2830. }
  2831. llvm::Constant *CGObjCGNU::
  2832. GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
  2833. // Get the method structure type.
  2834. llvm::StructType *ObjCMethodDescTy =
  2835. llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
  2836. ASTContext &Context = CGM.getContext();
  2837. ConstantInitBuilder Builder(CGM);
  2838. auto MethodList = Builder.beginStruct();
  2839. MethodList.addInt(IntTy, Methods.size());
  2840. auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
  2841. for (auto *M : Methods) {
  2842. auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
  2843. Method.add(MakeConstantString(M->getSelector().getAsString()));
  2844. Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
  2845. Method.finishAndAddTo(MethodArray);
  2846. }
  2847. MethodArray.finishAndAddTo(MethodList);
  2848. return MethodList.finishAndCreateGlobal(".objc_method_list",
  2849. CGM.getPointerAlign());
  2850. }
  2851. // Create the protocol list structure used in classes, categories and so on
  2852. llvm::Constant *
  2853. CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
  2854. ConstantInitBuilder Builder(CGM);
  2855. auto ProtocolList = Builder.beginStruct();
  2856. ProtocolList.add(NULLPtr);
  2857. ProtocolList.addInt(LongTy, Protocols.size());
  2858. auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
  2859. for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
  2860. iter != endIter ; iter++) {
  2861. llvm::Constant *protocol = nullptr;
  2862. llvm::StringMap<llvm::Constant*>::iterator value =
  2863. ExistingProtocols.find(*iter);
  2864. if (value == ExistingProtocols.end()) {
  2865. protocol = GenerateEmptyProtocol(*iter);
  2866. } else {
  2867. protocol = value->getValue();
  2868. }
  2869. Elements.addBitCast(protocol, PtrToInt8Ty);
  2870. }
  2871. Elements.finishAndAddTo(ProtocolList);
  2872. return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
  2873. CGM.getPointerAlign());
  2874. }
  2875. llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
  2876. const ObjCProtocolDecl *PD) {
  2877. auto protocol = GenerateProtocolRef(PD);
  2878. llvm::Type *T =
  2879. CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
  2880. return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
  2881. }
  2882. llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
  2883. llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
  2884. if (!protocol)
  2885. GenerateProtocol(PD);
  2886. assert(protocol && "Unknown protocol");
  2887. return protocol;
  2888. }
  2889. llvm::Constant *
  2890. CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
  2891. llvm::Constant *ProtocolList = GenerateProtocolList({});
  2892. llvm::Constant *MethodList = GenerateProtocolMethodList({});
  2893. MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
  2894. // Protocols are objects containing lists of the methods implemented and
  2895. // protocols adopted.
  2896. ConstantInitBuilder Builder(CGM);
  2897. auto Elements = Builder.beginStruct();
  2898. // The isa pointer must be set to a magic number so the runtime knows it's
  2899. // the correct layout.
  2900. Elements.add(llvm::ConstantExpr::getIntToPtr(
  2901. llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
  2902. Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
  2903. Elements.add(ProtocolList); /* .protocol_list */
  2904. Elements.add(MethodList); /* .instance_methods */
  2905. Elements.add(MethodList); /* .class_methods */
  2906. Elements.add(MethodList); /* .optional_instance_methods */
  2907. Elements.add(MethodList); /* .optional_class_methods */
  2908. Elements.add(NULLPtr); /* .properties */
  2909. Elements.add(NULLPtr); /* .optional_properties */
  2910. return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
  2911. CGM.getPointerAlign());
  2912. }
  2913. void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
  2914. if (PD->isNonRuntimeProtocol())
  2915. return;
  2916. std::string ProtocolName = PD->getNameAsString();
  2917. // Use the protocol definition, if there is one.
  2918. if (const ObjCProtocolDecl *Def = PD->getDefinition())
  2919. PD = Def;
  2920. SmallVector<std::string, 16> Protocols;
  2921. for (const auto *PI : PD->protocols())
  2922. Protocols.push_back(PI->getNameAsString());
  2923. SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
  2924. SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
  2925. for (const auto *I : PD->instance_methods())
  2926. if (I->isOptional())
  2927. OptionalInstanceMethods.push_back(I);
  2928. else
  2929. InstanceMethods.push_back(I);
  2930. // Collect information about class methods:
  2931. SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
  2932. SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
  2933. for (const auto *I : PD->class_methods())
  2934. if (I->isOptional())
  2935. OptionalClassMethods.push_back(I);
  2936. else
  2937. ClassMethods.push_back(I);
  2938. llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
  2939. llvm::Constant *InstanceMethodList =
  2940. GenerateProtocolMethodList(InstanceMethods);
  2941. llvm::Constant *ClassMethodList =
  2942. GenerateProtocolMethodList(ClassMethods);
  2943. llvm::Constant *OptionalInstanceMethodList =
  2944. GenerateProtocolMethodList(OptionalInstanceMethods);
  2945. llvm::Constant *OptionalClassMethodList =
  2946. GenerateProtocolMethodList(OptionalClassMethods);
  2947. // Property metadata: name, attributes, isSynthesized, setter name, setter
  2948. // types, getter name, getter types.
  2949. // The isSynthesized value is always set to 0 in a protocol. It exists to
  2950. // simplify the runtime library by allowing it to use the same data
  2951. // structures for protocol metadata everywhere.
  2952. llvm::Constant *PropertyList =
  2953. GeneratePropertyList(nullptr, PD, false, false);
  2954. llvm::Constant *OptionalPropertyList =
  2955. GeneratePropertyList(nullptr, PD, false, true);
  2956. // Protocols are objects containing lists of the methods implemented and
  2957. // protocols adopted.
  2958. // The isa pointer must be set to a magic number so the runtime knows it's
  2959. // the correct layout.
  2960. ConstantInitBuilder Builder(CGM);
  2961. auto Elements = Builder.beginStruct();
  2962. Elements.add(
  2963. llvm::ConstantExpr::getIntToPtr(
  2964. llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
  2965. Elements.add(MakeConstantString(ProtocolName));
  2966. Elements.add(ProtocolList);
  2967. Elements.add(InstanceMethodList);
  2968. Elements.add(ClassMethodList);
  2969. Elements.add(OptionalInstanceMethodList);
  2970. Elements.add(OptionalClassMethodList);
  2971. Elements.add(PropertyList);
  2972. Elements.add(OptionalPropertyList);
  2973. ExistingProtocols[ProtocolName] =
  2974. llvm::ConstantExpr::getBitCast(
  2975. Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
  2976. IdTy);
  2977. }
  2978. void CGObjCGNU::GenerateProtocolHolderCategory() {
  2979. // Collect information about instance methods
  2980. ConstantInitBuilder Builder(CGM);
  2981. auto Elements = Builder.beginStruct();
  2982. const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
  2983. const std::string CategoryName = "AnotherHack";
  2984. Elements.add(MakeConstantString(CategoryName));
  2985. Elements.add(MakeConstantString(ClassName));
  2986. // Instance method list
  2987. Elements.addBitCast(GenerateMethodList(
  2988. ClassName, CategoryName, {}, false), PtrTy);
  2989. // Class method list
  2990. Elements.addBitCast(GenerateMethodList(
  2991. ClassName, CategoryName, {}, true), PtrTy);
  2992. // Protocol list
  2993. ConstantInitBuilder ProtocolListBuilder(CGM);
  2994. auto ProtocolList = ProtocolListBuilder.beginStruct();
  2995. ProtocolList.add(NULLPtr);
  2996. ProtocolList.addInt(LongTy, ExistingProtocols.size());
  2997. auto ProtocolElements = ProtocolList.beginArray(PtrTy);
  2998. for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
  2999. iter != endIter ; iter++) {
  3000. ProtocolElements.addBitCast(iter->getValue(), PtrTy);
  3001. }
  3002. ProtocolElements.finishAndAddTo(ProtocolList);
  3003. Elements.addBitCast(
  3004. ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
  3005. CGM.getPointerAlign()),
  3006. PtrTy);
  3007. Categories.push_back(llvm::ConstantExpr::getBitCast(
  3008. Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
  3009. PtrTy));
  3010. }
  3011. /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
  3012. /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
  3013. /// bits set to their values, LSB first, while larger ones are stored in a
  3014. /// structure of this / form:
  3015. ///
  3016. /// struct { int32_t length; int32_t values[length]; };
  3017. ///
  3018. /// The values in the array are stored in host-endian format, with the least
  3019. /// significant bit being assumed to come first in the bitfield. Therefore, a
  3020. /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
  3021. /// bitfield / with the 63rd bit set will be 1<<64.
  3022. llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
  3023. int bitCount = bits.size();
  3024. int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
  3025. if (bitCount < ptrBits) {
  3026. uint64_t val = 1;
  3027. for (int i=0 ; i<bitCount ; ++i) {
  3028. if (bits[i]) val |= 1ULL<<(i+1);
  3029. }
  3030. return llvm::ConstantInt::get(IntPtrTy, val);
  3031. }
  3032. SmallVector<llvm::Constant *, 8> values;
  3033. int v=0;
  3034. while (v < bitCount) {
  3035. int32_t word = 0;
  3036. for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
  3037. if (bits[v]) word |= 1<<i;
  3038. v++;
  3039. }
  3040. values.push_back(llvm::ConstantInt::get(Int32Ty, word));
  3041. }
  3042. ConstantInitBuilder builder(CGM);
  3043. auto fields = builder.beginStruct();
  3044. fields.addInt(Int32Ty, values.size());
  3045. auto array = fields.beginArray();
  3046. for (auto *v : values) array.add(v);
  3047. array.finishAndAddTo(fields);
  3048. llvm::Constant *GS =
  3049. fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
  3050. llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
  3051. return ptr;
  3052. }
  3053. llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
  3054. ObjCCategoryDecl *OCD) {
  3055. const auto &RefPro = OCD->getReferencedProtocols();
  3056. const auto RuntimeProtos =
  3057. GetRuntimeProtocolList(RefPro.begin(), RefPro.end());
  3058. SmallVector<std::string, 16> Protocols;
  3059. for (const auto *PD : RuntimeProtos)
  3060. Protocols.push_back(PD->getNameAsString());
  3061. return GenerateProtocolList(Protocols);
  3062. }
  3063. void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
  3064. const ObjCInterfaceDecl *Class = OCD->getClassInterface();
  3065. std::string ClassName = Class->getNameAsString();
  3066. std::string CategoryName = OCD->getNameAsString();
  3067. // Collect the names of referenced protocols
  3068. const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
  3069. ConstantInitBuilder Builder(CGM);
  3070. auto Elements = Builder.beginStruct();
  3071. Elements.add(MakeConstantString(CategoryName));
  3072. Elements.add(MakeConstantString(ClassName));
  3073. // Instance method list
  3074. SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
  3075. InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
  3076. OCD->instmeth_end());
  3077. Elements.addBitCast(
  3078. GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
  3079. PtrTy);
  3080. // Class method list
  3081. SmallVector<ObjCMethodDecl*, 16> ClassMethods;
  3082. ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
  3083. OCD->classmeth_end());
  3084. Elements.addBitCast(
  3085. GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
  3086. PtrTy);
  3087. // Protocol list
  3088. Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
  3089. if (isRuntime(ObjCRuntime::GNUstep, 2)) {
  3090. const ObjCCategoryDecl *Category =
  3091. Class->FindCategoryDeclaration(OCD->getIdentifier());
  3092. if (Category) {
  3093. // Instance properties
  3094. Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
  3095. // Class properties
  3096. Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
  3097. } else {
  3098. Elements.addNullPointer(PtrTy);
  3099. Elements.addNullPointer(PtrTy);
  3100. }
  3101. }
  3102. Categories.push_back(llvm::ConstantExpr::getBitCast(
  3103. Elements.finishAndCreateGlobal(
  3104. std::string(".objc_category_")+ClassName+CategoryName,
  3105. CGM.getPointerAlign()),
  3106. PtrTy));
  3107. }
  3108. llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
  3109. const ObjCContainerDecl *OCD,
  3110. bool isClassProperty,
  3111. bool protocolOptionalProperties) {
  3112. SmallVector<const ObjCPropertyDecl *, 16> Properties;
  3113. llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
  3114. bool isProtocol = isa<ObjCProtocolDecl>(OCD);
  3115. ASTContext &Context = CGM.getContext();
  3116. std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
  3117. = [&](const ObjCProtocolDecl *Proto) {
  3118. for (const auto *P : Proto->protocols())
  3119. collectProtocolProperties(P);
  3120. for (const auto *PD : Proto->properties()) {
  3121. if (isClassProperty != PD->isClassProperty())
  3122. continue;
  3123. // Skip any properties that are declared in protocols that this class
  3124. // conforms to but are not actually implemented by this class.
  3125. if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
  3126. continue;
  3127. if (!PropertySet.insert(PD->getIdentifier()).second)
  3128. continue;
  3129. Properties.push_back(PD);
  3130. }
  3131. };
  3132. if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
  3133. for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
  3134. for (auto *PD : ClassExt->properties()) {
  3135. if (isClassProperty != PD->isClassProperty())
  3136. continue;
  3137. PropertySet.insert(PD->getIdentifier());
  3138. Properties.push_back(PD);
  3139. }
  3140. for (const auto *PD : OCD->properties()) {
  3141. if (isClassProperty != PD->isClassProperty())
  3142. continue;
  3143. // If we're generating a list for a protocol, skip optional / required ones
  3144. // when generating the other list.
  3145. if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
  3146. continue;
  3147. // Don't emit duplicate metadata for properties that were already in a
  3148. // class extension.
  3149. if (!PropertySet.insert(PD->getIdentifier()).second)
  3150. continue;
  3151. Properties.push_back(PD);
  3152. }
  3153. if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
  3154. for (const auto *P : OID->all_referenced_protocols())
  3155. collectProtocolProperties(P);
  3156. else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
  3157. for (const auto *P : CD->protocols())
  3158. collectProtocolProperties(P);
  3159. auto numProperties = Properties.size();
  3160. if (numProperties == 0)
  3161. return NULLPtr;
  3162. ConstantInitBuilder builder(CGM);
  3163. auto propertyList = builder.beginStruct();
  3164. auto properties = PushPropertyListHeader(propertyList, numProperties);
  3165. // Add all of the property methods need adding to the method list and to the
  3166. // property metadata list.
  3167. for (auto *property : Properties) {
  3168. bool isSynthesized = false;
  3169. bool isDynamic = false;
  3170. if (!isProtocol) {
  3171. auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
  3172. if (propertyImpl) {
  3173. isSynthesized = (propertyImpl->getPropertyImplementation() ==
  3174. ObjCPropertyImplDecl::Synthesize);
  3175. isDynamic = (propertyImpl->getPropertyImplementation() ==
  3176. ObjCPropertyImplDecl::Dynamic);
  3177. }
  3178. }
  3179. PushProperty(properties, property, Container, isSynthesized, isDynamic);
  3180. }
  3181. properties.finishAndAddTo(propertyList);
  3182. return propertyList.finishAndCreateGlobal(".objc_property_list",
  3183. CGM.getPointerAlign());
  3184. }
  3185. void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
  3186. // Get the class declaration for which the alias is specified.
  3187. ObjCInterfaceDecl *ClassDecl =
  3188. const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
  3189. ClassAliases.emplace_back(ClassDecl->getNameAsString(),
  3190. OAD->getNameAsString());
  3191. }
  3192. void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
  3193. ASTContext &Context = CGM.getContext();
  3194. // Get the superclass name.
  3195. const ObjCInterfaceDecl * SuperClassDecl =
  3196. OID->getClassInterface()->getSuperClass();
  3197. std::string SuperClassName;
  3198. if (SuperClassDecl) {
  3199. SuperClassName = SuperClassDecl->getNameAsString();
  3200. EmitClassRef(SuperClassName);
  3201. }
  3202. // Get the class name
  3203. ObjCInterfaceDecl *ClassDecl =
  3204. const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
  3205. std::string ClassName = ClassDecl->getNameAsString();
  3206. // Emit the symbol that is used to generate linker errors if this class is
  3207. // referenced in other modules but not declared.
  3208. std::string classSymbolName = "__objc_class_name_" + ClassName;
  3209. if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
  3210. symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
  3211. } else {
  3212. new llvm::GlobalVariable(TheModule, LongTy, false,
  3213. llvm::GlobalValue::ExternalLinkage,
  3214. llvm::ConstantInt::get(LongTy, 0),
  3215. classSymbolName);
  3216. }
  3217. // Get the size of instances.
  3218. int instanceSize =
  3219. Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
  3220. // Collect information about instance variables.
  3221. SmallVector<llvm::Constant*, 16> IvarNames;
  3222. SmallVector<llvm::Constant*, 16> IvarTypes;
  3223. SmallVector<llvm::Constant*, 16> IvarOffsets;
  3224. SmallVector<llvm::Constant*, 16> IvarAligns;
  3225. SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
  3226. ConstantInitBuilder IvarOffsetBuilder(CGM);
  3227. auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
  3228. SmallVector<bool, 16> WeakIvars;
  3229. SmallVector<bool, 16> StrongIvars;
  3230. int superInstanceSize = !SuperClassDecl ? 0 :
  3231. Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
  3232. // For non-fragile ivars, set the instance size to 0 - {the size of just this
  3233. // class}. The runtime will then set this to the correct value on load.
  3234. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  3235. instanceSize = 0 - (instanceSize - superInstanceSize);
  3236. }
  3237. for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
  3238. IVD = IVD->getNextIvar()) {
  3239. // Store the name
  3240. IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
  3241. // Get the type encoding for this ivar
  3242. std::string TypeStr;
  3243. Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
  3244. IvarTypes.push_back(MakeConstantString(TypeStr));
  3245. IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
  3246. Context.getTypeSize(IVD->getType())));
  3247. // Get the offset
  3248. uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
  3249. uint64_t Offset = BaseOffset;
  3250. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  3251. Offset = BaseOffset - superInstanceSize;
  3252. }
  3253. llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
  3254. // Create the direct offset value
  3255. std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
  3256. IVD->getNameAsString();
  3257. llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
  3258. if (OffsetVar) {
  3259. OffsetVar->setInitializer(OffsetValue);
  3260. // If this is the real definition, change its linkage type so that
  3261. // different modules will use this one, rather than their private
  3262. // copy.
  3263. OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3264. } else
  3265. OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
  3266. false, llvm::GlobalValue::ExternalLinkage,
  3267. OffsetValue, OffsetName);
  3268. IvarOffsets.push_back(OffsetValue);
  3269. IvarOffsetValues.add(OffsetVar);
  3270. Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
  3271. IvarOwnership.push_back(lt);
  3272. switch (lt) {
  3273. case Qualifiers::OCL_Strong:
  3274. StrongIvars.push_back(true);
  3275. WeakIvars.push_back(false);
  3276. break;
  3277. case Qualifiers::OCL_Weak:
  3278. StrongIvars.push_back(false);
  3279. WeakIvars.push_back(true);
  3280. break;
  3281. default:
  3282. StrongIvars.push_back(false);
  3283. WeakIvars.push_back(false);
  3284. }
  3285. }
  3286. llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
  3287. llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
  3288. llvm::GlobalVariable *IvarOffsetArray =
  3289. IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
  3290. CGM.getPointerAlign());
  3291. // Collect information about instance methods
  3292. SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
  3293. InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
  3294. OID->instmeth_end());
  3295. SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
  3296. ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
  3297. OID->classmeth_end());
  3298. llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
  3299. // Collect the names of referenced protocols
  3300. auto RefProtocols = ClassDecl->protocols();
  3301. auto RuntimeProtocols =
  3302. GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());
  3303. SmallVector<std::string, 16> Protocols;
  3304. for (const auto *I : RuntimeProtocols)
  3305. Protocols.push_back(I->getNameAsString());
  3306. // Get the superclass pointer.
  3307. llvm::Constant *SuperClass;
  3308. if (!SuperClassName.empty()) {
  3309. SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
  3310. } else {
  3311. SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
  3312. }
  3313. // Empty vector used to construct empty method lists
  3314. SmallVector<llvm::Constant*, 1> empty;
  3315. // Generate the method and instance variable lists
  3316. llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
  3317. InstanceMethods, false);
  3318. llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
  3319. ClassMethods, true);
  3320. llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
  3321. IvarOffsets, IvarAligns, IvarOwnership);
  3322. // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
  3323. // we emit a symbol containing the offset for each ivar in the class. This
  3324. // allows code compiled for the non-Fragile ABI to inherit from code compiled
  3325. // for the legacy ABI, without causing problems. The converse is also
  3326. // possible, but causes all ivar accesses to be fragile.
  3327. // Offset pointer for getting at the correct field in the ivar list when
  3328. // setting up the alias. These are: The base address for the global, the
  3329. // ivar array (second field), the ivar in this list (set for each ivar), and
  3330. // the offset (third field in ivar structure)
  3331. llvm::Type *IndexTy = Int32Ty;
  3332. llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
  3333. llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
  3334. llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
  3335. unsigned ivarIndex = 0;
  3336. for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
  3337. IVD = IVD->getNextIvar()) {
  3338. const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
  3339. offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
  3340. // Get the correct ivar field
  3341. llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
  3342. cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
  3343. offsetPointerIndexes);
  3344. // Get the existing variable, if one exists.
  3345. llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
  3346. if (offset) {
  3347. offset->setInitializer(offsetValue);
  3348. // If this is the real definition, change its linkage type so that
  3349. // different modules will use this one, rather than their private
  3350. // copy.
  3351. offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3352. } else
  3353. // Add a new alias if there isn't one already.
  3354. new llvm::GlobalVariable(TheModule, offsetValue->getType(),
  3355. false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
  3356. ++ivarIndex;
  3357. }
  3358. llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
  3359. //Generate metaclass for class methods
  3360. llvm::Constant *MetaClassStruct = GenerateClassStructure(
  3361. NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
  3362. NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
  3363. GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
  3364. CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
  3365. OID->getClassInterface());
  3366. // Generate the class structure
  3367. llvm::Constant *ClassStruct = GenerateClassStructure(
  3368. MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
  3369. llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
  3370. GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
  3371. StrongIvarBitmap, WeakIvarBitmap);
  3372. CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
  3373. OID->getClassInterface());
  3374. // Resolve the class aliases, if they exist.
  3375. if (ClassPtrAlias) {
  3376. ClassPtrAlias->replaceAllUsesWith(
  3377. llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
  3378. ClassPtrAlias->eraseFromParent();
  3379. ClassPtrAlias = nullptr;
  3380. }
  3381. if (MetaClassPtrAlias) {
  3382. MetaClassPtrAlias->replaceAllUsesWith(
  3383. llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
  3384. MetaClassPtrAlias->eraseFromParent();
  3385. MetaClassPtrAlias = nullptr;
  3386. }
  3387. // Add class structure to list to be added to the symtab later
  3388. ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
  3389. Classes.push_back(ClassStruct);
  3390. }
  3391. llvm::Function *CGObjCGNU::ModuleInitFunction() {
  3392. // Only emit an ObjC load function if no Objective-C stuff has been called
  3393. if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
  3394. ExistingProtocols.empty() && SelectorTable.empty())
  3395. return nullptr;
  3396. // Add all referenced protocols to a category.
  3397. GenerateProtocolHolderCategory();
  3398. llvm::StructType *selStructTy = dyn_cast<llvm::StructType>(SelectorElemTy);
  3399. llvm::Type *selStructPtrTy = SelectorTy;
  3400. if (!selStructTy) {
  3401. selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
  3402. { PtrToInt8Ty, PtrToInt8Ty });
  3403. selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
  3404. }
  3405. // Generate statics list:
  3406. llvm::Constant *statics = NULLPtr;
  3407. if (!ConstantStrings.empty()) {
  3408. llvm::GlobalVariable *fileStatics = [&] {
  3409. ConstantInitBuilder builder(CGM);
  3410. auto staticsStruct = builder.beginStruct();
  3411. StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
  3412. if (stringClass.empty()) stringClass = "NXConstantString";
  3413. staticsStruct.add(MakeConstantString(stringClass,
  3414. ".objc_static_class_name"));
  3415. auto array = staticsStruct.beginArray();
  3416. array.addAll(ConstantStrings);
  3417. array.add(NULLPtr);
  3418. array.finishAndAddTo(staticsStruct);
  3419. return staticsStruct.finishAndCreateGlobal(".objc_statics",
  3420. CGM.getPointerAlign());
  3421. }();
  3422. ConstantInitBuilder builder(CGM);
  3423. auto allStaticsArray = builder.beginArray(fileStatics->getType());
  3424. allStaticsArray.add(fileStatics);
  3425. allStaticsArray.addNullPointer(fileStatics->getType());
  3426. statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
  3427. CGM.getPointerAlign());
  3428. statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
  3429. }
  3430. // Array of classes, categories, and constant objects.
  3431. SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
  3432. unsigned selectorCount;
  3433. // Pointer to an array of selectors used in this module.
  3434. llvm::GlobalVariable *selectorList = [&] {
  3435. ConstantInitBuilder builder(CGM);
  3436. auto selectors = builder.beginArray(selStructTy);
  3437. auto &table = SelectorTable; // MSVC workaround
  3438. std::vector<Selector> allSelectors;
  3439. for (auto &entry : table)
  3440. allSelectors.push_back(entry.first);
  3441. llvm::sort(allSelectors);
  3442. for (auto &untypedSel : allSelectors) {
  3443. std::string selNameStr = untypedSel.getAsString();
  3444. llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
  3445. for (TypedSelector &sel : table[untypedSel]) {
  3446. llvm::Constant *selectorTypeEncoding = NULLPtr;
  3447. if (!sel.first.empty())
  3448. selectorTypeEncoding =
  3449. MakeConstantString(sel.first, ".objc_sel_types");
  3450. auto selStruct = selectors.beginStruct(selStructTy);
  3451. selStruct.add(selName);
  3452. selStruct.add(selectorTypeEncoding);
  3453. selStruct.finishAndAddTo(selectors);
  3454. // Store the selector alias for later replacement
  3455. selectorAliases.push_back(sel.second);
  3456. }
  3457. }
  3458. // Remember the number of entries in the selector table.
  3459. selectorCount = selectors.size();
  3460. // NULL-terminate the selector list. This should not actually be required,
  3461. // because the selector list has a length field. Unfortunately, the GCC
  3462. // runtime decides to ignore the length field and expects a NULL terminator,
  3463. // and GCC cooperates with this by always setting the length to 0.
  3464. auto selStruct = selectors.beginStruct(selStructTy);
  3465. selStruct.add(NULLPtr);
  3466. selStruct.add(NULLPtr);
  3467. selStruct.finishAndAddTo(selectors);
  3468. return selectors.finishAndCreateGlobal(".objc_selector_list",
  3469. CGM.getPointerAlign());
  3470. }();
  3471. // Now that all of the static selectors exist, create pointers to them.
  3472. for (unsigned i = 0; i < selectorCount; ++i) {
  3473. llvm::Constant *idxs[] = {
  3474. Zeros[0],
  3475. llvm::ConstantInt::get(Int32Ty, i)
  3476. };
  3477. // FIXME: We're generating redundant loads and stores here!
  3478. llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
  3479. selectorList->getValueType(), selectorList, idxs);
  3480. // If selectors are defined as an opaque type, cast the pointer to this
  3481. // type.
  3482. selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
  3483. selectorAliases[i]->replaceAllUsesWith(selPtr);
  3484. selectorAliases[i]->eraseFromParent();
  3485. }
  3486. llvm::GlobalVariable *symtab = [&] {
  3487. ConstantInitBuilder builder(CGM);
  3488. auto symtab = builder.beginStruct();
  3489. // Number of static selectors
  3490. symtab.addInt(LongTy, selectorCount);
  3491. symtab.addBitCast(selectorList, selStructPtrTy);
  3492. // Number of classes defined.
  3493. symtab.addInt(CGM.Int16Ty, Classes.size());
  3494. // Number of categories defined
  3495. symtab.addInt(CGM.Int16Ty, Categories.size());
  3496. // Create an array of classes, then categories, then static object instances
  3497. auto classList = symtab.beginArray(PtrToInt8Ty);
  3498. classList.addAll(Classes);
  3499. classList.addAll(Categories);
  3500. // NULL-terminated list of static object instances (mainly constant strings)
  3501. classList.add(statics);
  3502. classList.add(NULLPtr);
  3503. classList.finishAndAddTo(symtab);
  3504. // Construct the symbol table.
  3505. return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
  3506. }();
  3507. // The symbol table is contained in a module which has some version-checking
  3508. // constants
  3509. llvm::Constant *module = [&] {
  3510. llvm::Type *moduleEltTys[] = {
  3511. LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
  3512. };
  3513. llvm::StructType *moduleTy = llvm::StructType::get(
  3514. CGM.getLLVMContext(),
  3515. ArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
  3516. ConstantInitBuilder builder(CGM);
  3517. auto module = builder.beginStruct(moduleTy);
  3518. // Runtime version, used for ABI compatibility checking.
  3519. module.addInt(LongTy, RuntimeVersion);
  3520. // sizeof(ModuleTy)
  3521. module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
  3522. // The path to the source file where this module was declared
  3523. SourceManager &SM = CGM.getContext().getSourceManager();
  3524. OptionalFileEntryRef mainFile = SM.getFileEntryRefForID(SM.getMainFileID());
  3525. std::string path =
  3526. (mainFile->getDir().getName() + "/" + mainFile->getName()).str();
  3527. module.add(MakeConstantString(path, ".objc_source_file_name"));
  3528. module.add(symtab);
  3529. if (RuntimeVersion >= 10) {
  3530. switch (CGM.getLangOpts().getGC()) {
  3531. case LangOptions::GCOnly:
  3532. module.addInt(IntTy, 2);
  3533. break;
  3534. case LangOptions::NonGC:
  3535. if (CGM.getLangOpts().ObjCAutoRefCount)
  3536. module.addInt(IntTy, 1);
  3537. else
  3538. module.addInt(IntTy, 0);
  3539. break;
  3540. case LangOptions::HybridGC:
  3541. module.addInt(IntTy, 1);
  3542. break;
  3543. }
  3544. }
  3545. return module.finishAndCreateGlobal("", CGM.getPointerAlign());
  3546. }();
  3547. // Create the load function calling the runtime entry point with the module
  3548. // structure
  3549. llvm::Function * LoadFunction = llvm::Function::Create(
  3550. llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
  3551. llvm::GlobalValue::InternalLinkage, ".objc_load_function",
  3552. &TheModule);
  3553. llvm::BasicBlock *EntryBB =
  3554. llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
  3555. CGBuilderTy Builder(CGM, VMContext);
  3556. Builder.SetInsertPoint(EntryBB);
  3557. llvm::FunctionType *FT =
  3558. llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
  3559. llvm::FunctionCallee Register =
  3560. CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
  3561. Builder.CreateCall(Register, module);
  3562. if (!ClassAliases.empty()) {
  3563. llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
  3564. llvm::FunctionType *RegisterAliasTy =
  3565. llvm::FunctionType::get(Builder.getVoidTy(),
  3566. ArgTypes, false);
  3567. llvm::Function *RegisterAlias = llvm::Function::Create(
  3568. RegisterAliasTy,
  3569. llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
  3570. &TheModule);
  3571. llvm::BasicBlock *AliasBB =
  3572. llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
  3573. llvm::BasicBlock *NoAliasBB =
  3574. llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
  3575. // Branch based on whether the runtime provided class_registerAlias_np()
  3576. llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
  3577. llvm::Constant::getNullValue(RegisterAlias->getType()));
  3578. Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
  3579. // The true branch (has alias registration function):
  3580. Builder.SetInsertPoint(AliasBB);
  3581. // Emit alias registration calls:
  3582. for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
  3583. iter != ClassAliases.end(); ++iter) {
  3584. llvm::Constant *TheClass =
  3585. TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
  3586. if (TheClass) {
  3587. TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
  3588. Builder.CreateCall(RegisterAlias,
  3589. {TheClass, MakeConstantString(iter->second)});
  3590. }
  3591. }
  3592. // Jump to end:
  3593. Builder.CreateBr(NoAliasBB);
  3594. // Missing alias registration function, just return from the function:
  3595. Builder.SetInsertPoint(NoAliasBB);
  3596. }
  3597. Builder.CreateRetVoid();
  3598. return LoadFunction;
  3599. }
  3600. llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
  3601. const ObjCContainerDecl *CD) {
  3602. CodeGenTypes &Types = CGM.getTypes();
  3603. llvm::FunctionType *MethodTy =
  3604. Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
  3605. std::string FunctionName = getSymbolNameForMethod(OMD);
  3606. llvm::Function *Method
  3607. = llvm::Function::Create(MethodTy,
  3608. llvm::GlobalValue::InternalLinkage,
  3609. FunctionName,
  3610. &TheModule);
  3611. return Method;
  3612. }
  3613. void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
  3614. llvm::Function *Fn,
  3615. const ObjCMethodDecl *OMD,
  3616. const ObjCContainerDecl *CD) {
  3617. // GNU runtime doesn't support direct calls at this time
  3618. }
  3619. llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
  3620. return GetPropertyFn;
  3621. }
  3622. llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
  3623. return SetPropertyFn;
  3624. }
  3625. llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
  3626. bool copy) {
  3627. return nullptr;
  3628. }
  3629. llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
  3630. return GetStructPropertyFn;
  3631. }
  3632. llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
  3633. return SetStructPropertyFn;
  3634. }
  3635. llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
  3636. return nullptr;
  3637. }
  3638. llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
  3639. return nullptr;
  3640. }
  3641. llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
  3642. return EnumerationMutationFn;
  3643. }
  3644. void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
  3645. const ObjCAtSynchronizedStmt &S) {
  3646. EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
  3647. }
  3648. void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
  3649. const ObjCAtTryStmt &S) {
  3650. // Unlike the Apple non-fragile runtimes, which also uses
  3651. // unwind-based zero cost exceptions, the GNU Objective C runtime's
  3652. // EH support isn't a veneer over C++ EH. Instead, exception
  3653. // objects are created by objc_exception_throw and destroyed by
  3654. // the personality function; this avoids the need for bracketing
  3655. // catch handlers with calls to __blah_begin_catch/__blah_end_catch
  3656. // (or even _Unwind_DeleteException), but probably doesn't
  3657. // interoperate very well with foreign exceptions.
  3658. //
  3659. // In Objective-C++ mode, we actually emit something equivalent to the C++
  3660. // exception handler.
  3661. EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
  3662. }
  3663. void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
  3664. const ObjCAtThrowStmt &S,
  3665. bool ClearInsertionPoint) {
  3666. llvm::Value *ExceptionAsObject;
  3667. bool isRethrow = false;
  3668. if (const Expr *ThrowExpr = S.getThrowExpr()) {
  3669. llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
  3670. ExceptionAsObject = Exception;
  3671. } else {
  3672. assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
  3673. "Unexpected rethrow outside @catch block.");
  3674. ExceptionAsObject = CGF.ObjCEHValueStack.back();
  3675. isRethrow = true;
  3676. }
  3677. if (isRethrow && usesSEHExceptions) {
  3678. // For SEH, ExceptionAsObject may be undef, because the catch handler is
  3679. // not passed it for catchalls and so it is not visible to the catch
  3680. // funclet. The real thrown object will still be live on the stack at this
  3681. // point and will be rethrown. If we are explicitly rethrowing the object
  3682. // that was passed into the `@catch` block, then this code path is not
  3683. // reached and we will instead call `objc_exception_throw` with an explicit
  3684. // argument.
  3685. llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
  3686. Throw->setDoesNotReturn();
  3687. }
  3688. else {
  3689. ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
  3690. llvm::CallBase *Throw =
  3691. CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
  3692. Throw->setDoesNotReturn();
  3693. }
  3694. CGF.Builder.CreateUnreachable();
  3695. if (ClearInsertionPoint)
  3696. CGF.Builder.ClearInsertionPoint();
  3697. }
  3698. llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
  3699. Address AddrWeakObj) {
  3700. CGBuilderTy &B = CGF.Builder;
  3701. return B.CreateCall(WeakReadFn,
  3702. EnforceType(B, AddrWeakObj.getPointer(), PtrToIdTy));
  3703. }
  3704. void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
  3705. llvm::Value *src, Address dst) {
  3706. CGBuilderTy &B = CGF.Builder;
  3707. src = EnforceType(B, src, IdTy);
  3708. llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
  3709. B.CreateCall(WeakAssignFn, {src, dstVal});
  3710. }
  3711. void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
  3712. llvm::Value *src, Address dst,
  3713. bool threadlocal) {
  3714. CGBuilderTy &B = CGF.Builder;
  3715. src = EnforceType(B, src, IdTy);
  3716. llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
  3717. // FIXME. Add threadloca assign API
  3718. assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
  3719. B.CreateCall(GlobalAssignFn, {src, dstVal});
  3720. }
  3721. void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
  3722. llvm::Value *src, Address dst,
  3723. llvm::Value *ivarOffset) {
  3724. CGBuilderTy &B = CGF.Builder;
  3725. src = EnforceType(B, src, IdTy);
  3726. llvm::Value *dstVal = EnforceType(B, dst.getPointer(), IdTy);
  3727. B.CreateCall(IvarAssignFn, {src, dstVal, ivarOffset});
  3728. }
  3729. void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
  3730. llvm::Value *src, Address dst) {
  3731. CGBuilderTy &B = CGF.Builder;
  3732. src = EnforceType(B, src, IdTy);
  3733. llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
  3734. B.CreateCall(StrongCastAssignFn, {src, dstVal});
  3735. }
  3736. void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
  3737. Address DestPtr,
  3738. Address SrcPtr,
  3739. llvm::Value *Size) {
  3740. CGBuilderTy &B = CGF.Builder;
  3741. llvm::Value *DestPtrVal = EnforceType(B, DestPtr.getPointer(), PtrTy);
  3742. llvm::Value *SrcPtrVal = EnforceType(B, SrcPtr.getPointer(), PtrTy);
  3743. B.CreateCall(MemMoveFn, {DestPtrVal, SrcPtrVal, Size});
  3744. }
  3745. llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
  3746. const ObjCInterfaceDecl *ID,
  3747. const ObjCIvarDecl *Ivar) {
  3748. const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
  3749. // Emit the variable and initialize it with what we think the correct value
  3750. // is. This allows code compiled with non-fragile ivars to work correctly
  3751. // when linked against code which isn't (most of the time).
  3752. llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
  3753. if (!IvarOffsetPointer)
  3754. IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
  3755. llvm::Type::getInt32PtrTy(VMContext), false,
  3756. llvm::GlobalValue::ExternalLinkage, nullptr, Name);
  3757. return IvarOffsetPointer;
  3758. }
  3759. LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
  3760. QualType ObjectTy,
  3761. llvm::Value *BaseValue,
  3762. const ObjCIvarDecl *Ivar,
  3763. unsigned CVRQualifiers) {
  3764. const ObjCInterfaceDecl *ID =
  3765. ObjectTy->castAs<ObjCObjectType>()->getInterface();
  3766. return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
  3767. EmitIvarOffset(CGF, ID, Ivar));
  3768. }
  3769. static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
  3770. const ObjCInterfaceDecl *OID,
  3771. const ObjCIvarDecl *OIVD) {
  3772. for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
  3773. next = next->getNextIvar()) {
  3774. if (OIVD == next)
  3775. return OID;
  3776. }
  3777. // Otherwise check in the super class.
  3778. if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
  3779. return FindIvarInterface(Context, Super, OIVD);
  3780. return nullptr;
  3781. }
  3782. llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
  3783. const ObjCInterfaceDecl *Interface,
  3784. const ObjCIvarDecl *Ivar) {
  3785. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  3786. Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
  3787. // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
  3788. // and ExternalLinkage, so create a reference to the ivar global and rely on
  3789. // the definition being created as part of GenerateClass.
  3790. if (RuntimeVersion < 10 ||
  3791. CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
  3792. return CGF.Builder.CreateZExtOrBitCast(
  3793. CGF.Builder.CreateAlignedLoad(
  3794. Int32Ty, CGF.Builder.CreateAlignedLoad(
  3795. llvm::Type::getInt32PtrTy(VMContext),
  3796. ObjCIvarOffsetVariable(Interface, Ivar),
  3797. CGF.getPointerAlign(), "ivar"),
  3798. CharUnits::fromQuantity(4)),
  3799. PtrDiffTy);
  3800. std::string name = "__objc_ivar_offset_value_" +
  3801. Interface->getNameAsString() +"." + Ivar->getNameAsString();
  3802. CharUnits Align = CGM.getIntAlign();
  3803. llvm::Value *Offset = TheModule.getGlobalVariable(name);
  3804. if (!Offset) {
  3805. auto GV = new llvm::GlobalVariable(TheModule, IntTy,
  3806. false, llvm::GlobalValue::LinkOnceAnyLinkage,
  3807. llvm::Constant::getNullValue(IntTy), name);
  3808. GV->setAlignment(Align.getAsAlign());
  3809. Offset = GV;
  3810. }
  3811. Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);
  3812. if (Offset->getType() != PtrDiffTy)
  3813. Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
  3814. return Offset;
  3815. }
  3816. uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
  3817. return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
  3818. }
  3819. CGObjCRuntime *
  3820. clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
  3821. auto Runtime = CGM.getLangOpts().ObjCRuntime;
  3822. switch (Runtime.getKind()) {
  3823. case ObjCRuntime::GNUstep:
  3824. if (Runtime.getVersion() >= VersionTuple(2, 0))
  3825. return new CGObjCGNUstep2(CGM);
  3826. return new CGObjCGNUstep(CGM);
  3827. case ObjCRuntime::GCC:
  3828. return new CGObjCGCC(CGM);
  3829. case ObjCRuntime::ObjFW:
  3830. return new CGObjCObjFW(CGM);
  3831. case ObjCRuntime::FragileMacOSX:
  3832. case ObjCRuntime::MacOSX:
  3833. case ObjCRuntime::iOS:
  3834. case ObjCRuntime::WatchOS:
  3835. llvm_unreachable("these runtimes are not GNU runtimes");
  3836. }
  3837. llvm_unreachable("bad runtime");
  3838. }