CGObjCGNU.cpp 172 KB

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