CGObjCGNU.cpp 168 KB

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