CGObjCGNU.cpp 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661
  1. //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This provides Objective-C code generation targeting the GNU runtime. The
  11. // class in this file generates structures used by the GNU Objective-C runtime
  12. // library. These structures are defined in objc/objc.h and objc/objc-api.h in
  13. // the GNU runtime distribution.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "CGObjCRuntime.h"
  17. #include "CodeGenModule.h"
  18. #include "CodeGenFunction.h"
  19. #include "CGCleanup.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/Decl.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/RecordLayout.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/Basic/SourceManager.h"
  26. #include "clang/Basic/FileManager.h"
  27. #include "llvm/Intrinsics.h"
  28. #include "llvm/Module.h"
  29. #include "llvm/LLVMContext.h"
  30. #include "llvm/ADT/SmallVector.h"
  31. #include "llvm/ADT/StringMap.h"
  32. #include "llvm/Support/CallSite.h"
  33. #include "llvm/Support/Compiler.h"
  34. #include "llvm/Target/TargetData.h"
  35. #include <cstdarg>
  36. using namespace clang;
  37. using namespace CodeGen;
  38. namespace {
  39. /// Class that lazily initialises the runtime function. Avoids inserting the
  40. /// types and the function declaration into a module if they're not used, and
  41. /// avoids constructing the type more than once if it's used more than once.
  42. class LazyRuntimeFunction {
  43. CodeGenModule *CGM;
  44. std::vector<llvm::Type*> ArgTys;
  45. const char *FunctionName;
  46. llvm::Constant *Function;
  47. public:
  48. /// Constructor leaves this class uninitialized, because it is intended to
  49. /// be used as a field in another class and not all of the types that are
  50. /// used as arguments will necessarily be available at construction time.
  51. LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
  52. /// Initialises the lazy function with the name, return type, and the types
  53. /// of the arguments.
  54. END_WITH_NULL
  55. void init(CodeGenModule *Mod, const char *name,
  56. llvm::Type *RetTy, ...) {
  57. CGM =Mod;
  58. FunctionName = name;
  59. Function = 0;
  60. ArgTys.clear();
  61. va_list Args;
  62. va_start(Args, RetTy);
  63. while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
  64. ArgTys.push_back(ArgTy);
  65. va_end(Args);
  66. // Push the return type on at the end so we can pop it off easily
  67. ArgTys.push_back(RetTy);
  68. }
  69. /// Overloaded cast operator, allows the class to be implicitly cast to an
  70. /// LLVM constant.
  71. operator llvm::Constant*() {
  72. if (!Function) {
  73. if (0 == FunctionName) return 0;
  74. // We put the return type on the end of the vector, so pop it back off
  75. llvm::Type *RetTy = ArgTys.back();
  76. ArgTys.pop_back();
  77. llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
  78. Function =
  79. cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
  80. // We won't need to use the types again, so we may as well clean up the
  81. // vector now
  82. ArgTys.resize(0);
  83. }
  84. return Function;
  85. }
  86. operator llvm::Function*() {
  87. return cast<llvm::Function>((llvm::Constant*)*this);
  88. }
  89. };
  90. /// GNU Objective-C runtime code generation. This class implements the parts of
  91. /// Objective-C support that are specific to the GNU family of runtimes (GCC and
  92. /// GNUstep).
  93. class CGObjCGNU : public CGObjCRuntime {
  94. protected:
  95. /// The LLVM module into which output is inserted
  96. llvm::Module &TheModule;
  97. /// strut objc_super. Used for sending messages to super. This structure
  98. /// contains the receiver (object) and the expected class.
  99. llvm::StructType *ObjCSuperTy;
  100. /// struct objc_super*. The type of the argument to the superclass message
  101. /// lookup functions.
  102. llvm::PointerType *PtrToObjCSuperTy;
  103. /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
  104. /// SEL is included in a header somewhere, in which case it will be whatever
  105. /// type is declared in that header, most likely {i8*, i8*}.
  106. llvm::PointerType *SelectorTy;
  107. /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
  108. /// places where it's used
  109. llvm::IntegerType *Int8Ty;
  110. /// Pointer to i8 - LLVM type of char*, for all of the places where the
  111. /// runtime needs to deal with C strings.
  112. llvm::PointerType *PtrToInt8Ty;
  113. /// Instance Method Pointer type. This is a pointer to a function that takes,
  114. /// at a minimum, an object and a selector, and is the generic type for
  115. /// Objective-C methods. Due to differences between variadic / non-variadic
  116. /// calling conventions, it must always be cast to the correct type before
  117. /// actually being used.
  118. llvm::PointerType *IMPTy;
  119. /// Type of an untyped Objective-C object. Clang treats id as a built-in type
  120. /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
  121. /// but if the runtime header declaring it is included then it may be a
  122. /// pointer to a structure.
  123. llvm::PointerType *IdTy;
  124. /// Pointer to a pointer to an Objective-C object. Used in the new ABI
  125. /// message lookup function and some GC-related functions.
  126. llvm::PointerType *PtrToIdTy;
  127. /// The clang type of id. Used when using the clang CGCall infrastructure to
  128. /// call Objective-C methods.
  129. CanQualType ASTIdTy;
  130. /// LLVM type for C int type.
  131. llvm::IntegerType *IntTy;
  132. /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
  133. /// used in the code to document the difference between i8* meaning a pointer
  134. /// to a C string and i8* meaning a pointer to some opaque type.
  135. llvm::PointerType *PtrTy;
  136. /// LLVM type for C long type. The runtime uses this in a lot of places where
  137. /// it should be using intptr_t, but we can't fix this without breaking
  138. /// compatibility with GCC...
  139. llvm::IntegerType *LongTy;
  140. /// LLVM type for C size_t. Used in various runtime data structures.
  141. llvm::IntegerType *SizeTy;
  142. /// LLVM type for C intptr_t.
  143. llvm::IntegerType *IntPtrTy;
  144. /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
  145. llvm::IntegerType *PtrDiffTy;
  146. /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
  147. /// variables.
  148. llvm::PointerType *PtrToIntTy;
  149. /// LLVM type for Objective-C BOOL type.
  150. llvm::Type *BoolTy;
  151. /// 32-bit integer type, to save us needing to look it up every time it's used.
  152. llvm::IntegerType *Int32Ty;
  153. /// 64-bit integer type, to save us needing to look it up every time it's used.
  154. llvm::IntegerType *Int64Ty;
  155. /// Metadata kind used to tie method lookups to message sends. The GNUstep
  156. /// runtime provides some LLVM passes that can use this to do things like
  157. /// automatic IMP caching and speculative inlining.
  158. unsigned msgSendMDKind;
  159. /// Helper function that generates a constant string and returns a pointer to
  160. /// the start of the string. The result of this function can be used anywhere
  161. /// where the C code specifies const char*.
  162. llvm::Constant *MakeConstantString(const std::string &Str,
  163. const std::string &Name="") {
  164. llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
  165. return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
  166. }
  167. /// Emits a linkonce_odr string, whose name is the prefix followed by the
  168. /// string value. This allows the linker to combine the strings between
  169. /// different modules. Used for EH typeinfo names, selector strings, and a
  170. /// few other things.
  171. llvm::Constant *ExportUniqueString(const std::string &Str,
  172. const std::string prefix) {
  173. std::string name = prefix + Str;
  174. llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
  175. if (!ConstStr) {
  176. llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
  177. ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
  178. llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
  179. }
  180. return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
  181. }
  182. /// Generates a global structure, initialized by the elements in the vector.
  183. /// The element types must match the types of the structure elements in the
  184. /// first argument.
  185. llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
  186. llvm::ArrayRef<llvm::Constant*> V,
  187. StringRef Name="",
  188. llvm::GlobalValue::LinkageTypes linkage
  189. =llvm::GlobalValue::InternalLinkage) {
  190. llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
  191. return new llvm::GlobalVariable(TheModule, Ty, false,
  192. linkage, C, Name);
  193. }
  194. /// Generates a global array. The vector must contain the same number of
  195. /// elements that the array type declares, of the type specified as the array
  196. /// element type.
  197. llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
  198. llvm::ArrayRef<llvm::Constant*> V,
  199. StringRef Name="",
  200. llvm::GlobalValue::LinkageTypes linkage
  201. =llvm::GlobalValue::InternalLinkage) {
  202. llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
  203. return new llvm::GlobalVariable(TheModule, Ty, false,
  204. linkage, C, Name);
  205. }
  206. /// Generates a global array, inferring the array type from the specified
  207. /// element type and the size of the initialiser.
  208. llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
  209. llvm::ArrayRef<llvm::Constant*> V,
  210. StringRef Name="",
  211. llvm::GlobalValue::LinkageTypes linkage
  212. =llvm::GlobalValue::InternalLinkage) {
  213. llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
  214. return MakeGlobal(ArrayTy, V, Name, linkage);
  215. }
  216. /// Ensures that the value has the required type, by inserting a bitcast if
  217. /// required. This function lets us avoid inserting bitcasts that are
  218. /// redundant.
  219. llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
  220. if (V->getType() == Ty) return V;
  221. return B.CreateBitCast(V, Ty);
  222. }
  223. // Some zeros used for GEPs in lots of places.
  224. llvm::Constant *Zeros[2];
  225. /// Null pointer value. Mainly used as a terminator in various arrays.
  226. llvm::Constant *NULLPtr;
  227. /// LLVM context.
  228. llvm::LLVMContext &VMContext;
  229. private:
  230. /// Placeholder for the class. Lots of things refer to the class before we've
  231. /// actually emitted it. We use this alias as a placeholder, and then replace
  232. /// it with a pointer to the class structure before finally emitting the
  233. /// module.
  234. llvm::GlobalAlias *ClassPtrAlias;
  235. /// Placeholder for the metaclass. Lots of things refer to the class before
  236. /// we've / actually emitted it. We use this alias as a placeholder, and then
  237. /// replace / it with a pointer to the metaclass structure before finally
  238. /// emitting the / module.
  239. llvm::GlobalAlias *MetaClassPtrAlias;
  240. /// All of the classes that have been generated for this compilation units.
  241. std::vector<llvm::Constant*> Classes;
  242. /// All of the categories that have been generated for this compilation units.
  243. std::vector<llvm::Constant*> Categories;
  244. /// All of the Objective-C constant strings that have been generated for this
  245. /// compilation units.
  246. std::vector<llvm::Constant*> ConstantStrings;
  247. /// Map from string values to Objective-C constant strings in the output.
  248. /// Used to prevent emitting Objective-C strings more than once. This should
  249. /// not be required at all - CodeGenModule should manage this list.
  250. llvm::StringMap<llvm::Constant*> ObjCStrings;
  251. /// All of the protocols that have been declared.
  252. llvm::StringMap<llvm::Constant*> ExistingProtocols;
  253. /// For each variant of a selector, we store the type encoding and a
  254. /// placeholder value. For an untyped selector, the type will be the empty
  255. /// string. Selector references are all done via the module's selector table,
  256. /// so we create an alias as a placeholder and then replace it with the real
  257. /// value later.
  258. typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
  259. /// Type of the selector map. This is roughly equivalent to the structure
  260. /// used in the GNUstep runtime, which maintains a list of all of the valid
  261. /// types for a selector in a table.
  262. typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
  263. SelectorMap;
  264. /// A map from selectors to selector types. This allows us to emit all
  265. /// selectors of the same name and type together.
  266. SelectorMap SelectorTable;
  267. /// Selectors related to memory management. When compiling in GC mode, we
  268. /// omit these.
  269. Selector RetainSel, ReleaseSel, AutoreleaseSel;
  270. /// Runtime functions used for memory management in GC mode. Note that clang
  271. /// supports code generation for calling these functions, but neither GNU
  272. /// runtime actually supports this API properly yet.
  273. LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
  274. WeakAssignFn, GlobalAssignFn;
  275. typedef std::pair<std::string, std::string> ClassAliasPair;
  276. /// All classes that have aliases set for them.
  277. std::vector<ClassAliasPair> ClassAliases;
  278. protected:
  279. /// Function used for throwing Objective-C exceptions.
  280. LazyRuntimeFunction ExceptionThrowFn;
  281. /// Function used for rethrowing exceptions, used at the end of @finally or
  282. /// @synchronize blocks.
  283. LazyRuntimeFunction ExceptionReThrowFn;
  284. /// Function called when entering a catch function. This is required for
  285. /// differentiating Objective-C exceptions and foreign exceptions.
  286. LazyRuntimeFunction EnterCatchFn;
  287. /// Function called when exiting from a catch block. Used to do exception
  288. /// cleanup.
  289. LazyRuntimeFunction ExitCatchFn;
  290. /// Function called when entering an @synchronize block. Acquires the lock.
  291. LazyRuntimeFunction SyncEnterFn;
  292. /// Function called when exiting an @synchronize block. Releases the lock.
  293. LazyRuntimeFunction SyncExitFn;
  294. private:
  295. /// Function called if fast enumeration detects that the collection is
  296. /// modified during the update.
  297. LazyRuntimeFunction EnumerationMutationFn;
  298. /// Function for implementing synthesized property getters that return an
  299. /// object.
  300. LazyRuntimeFunction GetPropertyFn;
  301. /// Function for implementing synthesized property setters that return an
  302. /// object.
  303. LazyRuntimeFunction SetPropertyFn;
  304. /// Function used for non-object declared property getters.
  305. LazyRuntimeFunction GetStructPropertyFn;
  306. /// Function used for non-object declared property setters.
  307. LazyRuntimeFunction SetStructPropertyFn;
  308. /// The version of the runtime that this class targets. Must match the
  309. /// version in the runtime.
  310. int RuntimeVersion;
  311. /// The version of the protocol class. Used to differentiate between ObjC1
  312. /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
  313. /// components and can not contain declared properties. We always emit
  314. /// Objective-C 2 property structures, but we have to pretend that they're
  315. /// Objective-C 1 property structures when targeting the GCC runtime or it
  316. /// will abort.
  317. const int ProtocolVersion;
  318. private:
  319. /// Generates an instance variable list structure. This is a structure
  320. /// containing a size and an array of structures containing instance variable
  321. /// metadata. This is used purely for introspection in the fragile ABI. In
  322. /// the non-fragile ABI, it's used for instance variable fixup.
  323. llvm::Constant *GenerateIvarList(
  324. const SmallVectorImpl<llvm::Constant *> &IvarNames,
  325. const SmallVectorImpl<llvm::Constant *> &IvarTypes,
  326. const SmallVectorImpl<llvm::Constant *> &IvarOffsets);
  327. /// Generates a method list structure. This is a structure containing a size
  328. /// and an array of structures containing method metadata.
  329. ///
  330. /// This structure is used by both classes and categories, and contains a next
  331. /// pointer allowing them to be chained together in a linked list.
  332. llvm::Constant *GenerateMethodList(const StringRef &ClassName,
  333. const StringRef &CategoryName,
  334. const SmallVectorImpl<Selector> &MethodSels,
  335. const SmallVectorImpl<llvm::Constant *> &MethodTypes,
  336. bool isClassMethodList);
  337. /// Emits an empty protocol. This is used for @protocol() where no protocol
  338. /// is found. The runtime will (hopefully) fix up the pointer to refer to the
  339. /// real protocol.
  340. llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
  341. /// Generates a list of property metadata structures. This follows the same
  342. /// pattern as method and instance variable metadata lists.
  343. llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
  344. SmallVectorImpl<Selector> &InstanceMethodSels,
  345. SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
  346. /// Generates a list of referenced protocols. Classes, categories, and
  347. /// protocols all use this structure.
  348. llvm::Constant *GenerateProtocolList(
  349. const SmallVectorImpl<std::string> &Protocols);
  350. /// To ensure that all protocols are seen by the runtime, we add a category on
  351. /// a class defined in the runtime, declaring no methods, but adopting the
  352. /// protocols. This is a horribly ugly hack, but it allows us to collect all
  353. /// of the protocols without changing the ABI.
  354. void GenerateProtocolHolderCategory(void);
  355. /// Generates a class structure.
  356. llvm::Constant *GenerateClassStructure(
  357. llvm::Constant *MetaClass,
  358. llvm::Constant *SuperClass,
  359. unsigned info,
  360. const char *Name,
  361. llvm::Constant *Version,
  362. llvm::Constant *InstanceSize,
  363. llvm::Constant *IVars,
  364. llvm::Constant *Methods,
  365. llvm::Constant *Protocols,
  366. llvm::Constant *IvarOffsets,
  367. llvm::Constant *Properties,
  368. llvm::Constant *StrongIvarBitmap,
  369. llvm::Constant *WeakIvarBitmap,
  370. bool isMeta=false);
  371. /// Generates a method list. This is used by protocols to define the required
  372. /// and optional methods.
  373. llvm::Constant *GenerateProtocolMethodList(
  374. const SmallVectorImpl<llvm::Constant *> &MethodNames,
  375. const SmallVectorImpl<llvm::Constant *> &MethodTypes);
  376. /// Returns a selector with the specified type encoding. An empty string is
  377. /// used to return an untyped selector (with the types field set to NULL).
  378. llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
  379. const std::string &TypeEncoding, bool lval);
  380. /// Returns the variable used to store the offset of an instance variable.
  381. llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
  382. const ObjCIvarDecl *Ivar);
  383. /// Emits a reference to a class. This allows the linker to object if there
  384. /// is no class of the matching name.
  385. void EmitClassRef(const std::string &className);
  386. /// Emits a pointer to the named class
  387. llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
  388. bool isWeak);
  389. protected:
  390. /// Looks up the method for sending a message to the specified object. This
  391. /// mechanism differs between the GCC and GNU runtimes, so this method must be
  392. /// overridden in subclasses.
  393. virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
  394. llvm::Value *&Receiver,
  395. llvm::Value *cmd,
  396. llvm::MDNode *node) = 0;
  397. /// Looks up the method for sending a message to a superclass. This
  398. /// mechanism differs between the GCC and GNU runtimes, so this method must
  399. /// be overridden in subclasses.
  400. virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
  401. llvm::Value *ObjCSuper,
  402. llvm::Value *cmd) = 0;
  403. /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
  404. /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
  405. /// bits set to their values, LSB first, while larger ones are stored in a
  406. /// structure of this / form:
  407. ///
  408. /// struct { int32_t length; int32_t values[length]; };
  409. ///
  410. /// The values in the array are stored in host-endian format, with the least
  411. /// significant bit being assumed to come first in the bitfield. Therefore,
  412. /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
  413. /// while a bitfield / with the 63rd bit set will be 1<<64.
  414. llvm::Constant *MakeBitField(llvm::SmallVectorImpl<bool> &bits);
  415. public:
  416. CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
  417. unsigned protocolClassVersion);
  418. virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
  419. virtual RValue
  420. GenerateMessageSend(CodeGenFunction &CGF,
  421. ReturnValueSlot Return,
  422. QualType ResultType,
  423. Selector Sel,
  424. llvm::Value *Receiver,
  425. const CallArgList &CallArgs,
  426. const ObjCInterfaceDecl *Class,
  427. const ObjCMethodDecl *Method);
  428. virtual RValue
  429. GenerateMessageSendSuper(CodeGenFunction &CGF,
  430. ReturnValueSlot Return,
  431. QualType ResultType,
  432. Selector Sel,
  433. const ObjCInterfaceDecl *Class,
  434. bool isCategoryImpl,
  435. llvm::Value *Receiver,
  436. bool IsClassMessage,
  437. const CallArgList &CallArgs,
  438. const ObjCMethodDecl *Method);
  439. virtual llvm::Value *GetClass(CGBuilderTy &Builder,
  440. const ObjCInterfaceDecl *OID);
  441. virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
  442. bool lval = false);
  443. virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
  444. *Method);
  445. virtual llvm::Constant *GetEHType(QualType T);
  446. virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
  447. const ObjCContainerDecl *CD);
  448. virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
  449. virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
  450. virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD);
  451. virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
  452. const ObjCProtocolDecl *PD);
  453. virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
  454. virtual llvm::Function *ModuleInitFunction();
  455. virtual llvm::Constant *GetPropertyGetFunction();
  456. virtual llvm::Constant *GetPropertySetFunction();
  457. virtual llvm::Constant *GetSetStructFunction();
  458. virtual llvm::Constant *GetCppAtomicObjectFunction();
  459. virtual llvm::Constant *GetGetStructFunction();
  460. virtual llvm::Constant *EnumerationMutationFunction();
  461. virtual void EmitTryStmt(CodeGenFunction &CGF,
  462. const ObjCAtTryStmt &S);
  463. virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
  464. const ObjCAtSynchronizedStmt &S);
  465. virtual void EmitThrowStmt(CodeGenFunction &CGF,
  466. const ObjCAtThrowStmt &S);
  467. virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
  468. llvm::Value *AddrWeakObj);
  469. virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
  470. llvm::Value *src, llvm::Value *dst);
  471. virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
  472. llvm::Value *src, llvm::Value *dest,
  473. bool threadlocal=false);
  474. virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
  475. llvm::Value *src, llvm::Value *dest,
  476. llvm::Value *ivarOffset);
  477. virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
  478. llvm::Value *src, llvm::Value *dest);
  479. virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
  480. llvm::Value *DestPtr,
  481. llvm::Value *SrcPtr,
  482. llvm::Value *Size);
  483. virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
  484. QualType ObjectTy,
  485. llvm::Value *BaseValue,
  486. const ObjCIvarDecl *Ivar,
  487. unsigned CVRQualifiers);
  488. virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
  489. const ObjCInterfaceDecl *Interface,
  490. const ObjCIvarDecl *Ivar);
  491. virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
  492. virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
  493. const CGBlockInfo &blockInfo) {
  494. return NULLPtr;
  495. }
  496. virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
  497. return 0;
  498. }
  499. };
  500. /// Class representing the legacy GCC Objective-C ABI. This is the default when
  501. /// -fobjc-nonfragile-abi is not specified.
  502. ///
  503. /// The GCC ABI target actually generates code that is approximately compatible
  504. /// with the new GNUstep runtime ABI, but refrains from using any features that
  505. /// would not work with the GCC runtime. For example, clang always generates
  506. /// the extended form of the class structure, and the extra fields are simply
  507. /// ignored by GCC libobjc.
  508. class CGObjCGCC : public CGObjCGNU {
  509. /// The GCC ABI message lookup function. Returns an IMP pointing to the
  510. /// method implementation for this message.
  511. LazyRuntimeFunction MsgLookupFn;
  512. /// The GCC ABI superclass message lookup function. Takes a pointer to a
  513. /// structure describing the receiver and the class, and a selector as
  514. /// arguments. Returns the IMP for the corresponding method.
  515. LazyRuntimeFunction MsgLookupSuperFn;
  516. protected:
  517. virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
  518. llvm::Value *&Receiver,
  519. llvm::Value *cmd,
  520. llvm::MDNode *node) {
  521. CGBuilderTy &Builder = CGF.Builder;
  522. llvm::Value *args[] = {
  523. EnforceType(Builder, Receiver, IdTy),
  524. EnforceType(Builder, cmd, SelectorTy) };
  525. llvm::CallSite imp = CGF.EmitCallOrInvoke(MsgLookupFn, args);
  526. imp->setMetadata(msgSendMDKind, node);
  527. return imp.getInstruction();
  528. }
  529. virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
  530. llvm::Value *ObjCSuper,
  531. llvm::Value *cmd) {
  532. CGBuilderTy &Builder = CGF.Builder;
  533. llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
  534. PtrToObjCSuperTy), cmd};
  535. return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
  536. }
  537. public:
  538. CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
  539. // IMP objc_msg_lookup(id, SEL);
  540. MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
  541. // IMP objc_msg_lookup_super(struct objc_super*, SEL);
  542. MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
  543. PtrToObjCSuperTy, SelectorTy, NULL);
  544. }
  545. };
  546. /// Class used when targeting the new GNUstep runtime ABI.
  547. class CGObjCGNUstep : public CGObjCGNU {
  548. /// The slot lookup function. Returns a pointer to a cacheable structure
  549. /// that contains (among other things) the IMP.
  550. LazyRuntimeFunction SlotLookupFn;
  551. /// The GNUstep ABI superclass message lookup function. Takes a pointer to
  552. /// a structure describing the receiver and the class, and a selector as
  553. /// arguments. Returns the slot for the corresponding method. Superclass
  554. /// message lookup rarely changes, so this is a good caching opportunity.
  555. LazyRuntimeFunction SlotLookupSuperFn;
  556. /// Type of an slot structure pointer. This is returned by the various
  557. /// lookup functions.
  558. llvm::Type *SlotTy;
  559. protected:
  560. virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
  561. llvm::Value *&Receiver,
  562. llvm::Value *cmd,
  563. llvm::MDNode *node) {
  564. CGBuilderTy &Builder = CGF.Builder;
  565. llvm::Function *LookupFn = SlotLookupFn;
  566. // Store the receiver on the stack so that we can reload it later
  567. llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
  568. Builder.CreateStore(Receiver, ReceiverPtr);
  569. llvm::Value *self;
  570. if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
  571. self = CGF.LoadObjCSelf();
  572. } else {
  573. self = llvm::ConstantPointerNull::get(IdTy);
  574. }
  575. // The lookup function is guaranteed not to capture the receiver pointer.
  576. LookupFn->setDoesNotCapture(1);
  577. llvm::Value *args[] = {
  578. EnforceType(Builder, ReceiverPtr, PtrToIdTy),
  579. EnforceType(Builder, cmd, SelectorTy),
  580. EnforceType(Builder, self, IdTy) };
  581. llvm::CallSite slot = CGF.EmitCallOrInvoke(LookupFn, args);
  582. slot.setOnlyReadsMemory();
  583. slot->setMetadata(msgSendMDKind, node);
  584. // Load the imp from the slot
  585. llvm::Value *imp =
  586. Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
  587. // The lookup function may have changed the receiver, so make sure we use
  588. // the new one.
  589. Receiver = Builder.CreateLoad(ReceiverPtr, true);
  590. return imp;
  591. }
  592. virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
  593. llvm::Value *ObjCSuper,
  594. llvm::Value *cmd) {
  595. CGBuilderTy &Builder = CGF.Builder;
  596. llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
  597. llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
  598. slot->setOnlyReadsMemory();
  599. return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
  600. }
  601. public:
  602. CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
  603. llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
  604. PtrTy, PtrTy, IntTy, IMPTy, NULL);
  605. SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
  606. // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
  607. SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
  608. SelectorTy, IdTy, NULL);
  609. // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
  610. SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  611. PtrToObjCSuperTy, SelectorTy, NULL);
  612. // If we're in ObjC++ mode, then we want to make
  613. if (CGM.getLangOptions().CPlusPlus) {
  614. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  615. // void *__cxa_begin_catch(void *e)
  616. EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
  617. // void __cxa_end_catch(void)
  618. ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
  619. // void _Unwind_Resume_or_Rethrow(void*)
  620. ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
  621. }
  622. }
  623. };
  624. } // end anonymous namespace
  625. /// Emits a reference to a dummy variable which is emitted with each class.
  626. /// This ensures that a linker error will be generated when trying to link
  627. /// together modules where a referenced class is not defined.
  628. void CGObjCGNU::EmitClassRef(const std::string &className) {
  629. std::string symbolRef = "__objc_class_ref_" + className;
  630. // Don't emit two copies of the same symbol
  631. if (TheModule.getGlobalVariable(symbolRef))
  632. return;
  633. std::string symbolName = "__objc_class_name_" + className;
  634. llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
  635. if (!ClassSymbol) {
  636. ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
  637. llvm::GlobalValue::ExternalLinkage, 0, symbolName);
  638. }
  639. new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
  640. llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
  641. }
  642. static std::string SymbolNameForMethod(const StringRef &ClassName,
  643. const StringRef &CategoryName, const Selector MethodName,
  644. bool isClassMethod) {
  645. std::string MethodNameColonStripped = MethodName.getAsString();
  646. std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
  647. ':', '_');
  648. return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
  649. CategoryName + "_" + MethodNameColonStripped).str();
  650. }
  651. CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
  652. unsigned protocolClassVersion)
  653. : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
  654. VMContext(cgm.getLLVMContext()), ClassPtrAlias(0), MetaClassPtrAlias(0),
  655. RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersion) {
  656. msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
  657. CodeGenTypes &Types = CGM.getTypes();
  658. IntTy = cast<llvm::IntegerType>(
  659. Types.ConvertType(CGM.getContext().IntTy));
  660. LongTy = cast<llvm::IntegerType>(
  661. Types.ConvertType(CGM.getContext().LongTy));
  662. SizeTy = cast<llvm::IntegerType>(
  663. Types.ConvertType(CGM.getContext().getSizeType()));
  664. PtrDiffTy = cast<llvm::IntegerType>(
  665. Types.ConvertType(CGM.getContext().getPointerDiffType()));
  666. BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
  667. Int8Ty = llvm::Type::getInt8Ty(VMContext);
  668. // C string type. Used in lots of places.
  669. PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
  670. Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
  671. Zeros[1] = Zeros[0];
  672. NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
  673. // Get the selector Type.
  674. QualType selTy = CGM.getContext().getObjCSelType();
  675. if (QualType() == selTy) {
  676. SelectorTy = PtrToInt8Ty;
  677. } else {
  678. SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
  679. }
  680. PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
  681. PtrTy = PtrToInt8Ty;
  682. Int32Ty = llvm::Type::getInt32Ty(VMContext);
  683. Int64Ty = llvm::Type::getInt64Ty(VMContext);
  684. IntPtrTy =
  685. TheModule.getPointerSize() == llvm::Module::Pointer32 ? Int32Ty : Int64Ty;
  686. // Object type
  687. QualType UnqualIdTy = CGM.getContext().getObjCIdType();
  688. ASTIdTy = CanQualType();
  689. if (UnqualIdTy != QualType()) {
  690. ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
  691. IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
  692. } else {
  693. IdTy = PtrToInt8Ty;
  694. }
  695. PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
  696. ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
  697. PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
  698. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  699. // void objc_exception_throw(id);
  700. ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
  701. ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
  702. // int objc_sync_enter(id);
  703. SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
  704. // int objc_sync_exit(id);
  705. SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
  706. // void objc_enumerationMutation (id)
  707. EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
  708. IdTy, NULL);
  709. // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
  710. GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
  711. PtrDiffTy, BoolTy, NULL);
  712. // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
  713. SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
  714. PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
  715. // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
  716. GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
  717. PtrDiffTy, BoolTy, BoolTy, NULL);
  718. // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
  719. SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
  720. PtrDiffTy, BoolTy, BoolTy, NULL);
  721. // IMP type
  722. llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
  723. IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
  724. true));
  725. const LangOptions &Opts = CGM.getLangOptions();
  726. if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
  727. RuntimeVersion = 10;
  728. // Don't bother initialising the GC stuff unless we're compiling in GC mode
  729. if (Opts.getGC() != LangOptions::NonGC) {
  730. // This is a bit of an hack. We should sort this out by having a proper
  731. // CGObjCGNUstep subclass for GC, but we may want to really support the old
  732. // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
  733. // Get selectors needed in GC mode
  734. RetainSel = GetNullarySelector("retain", CGM.getContext());
  735. ReleaseSel = GetNullarySelector("release", CGM.getContext());
  736. AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
  737. // Get functions needed in GC mode
  738. // id objc_assign_ivar(id, id, ptrdiff_t);
  739. IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
  740. NULL);
  741. // id objc_assign_strongCast (id, id*)
  742. StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
  743. PtrToIdTy, NULL);
  744. // id objc_assign_global(id, id*);
  745. GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
  746. NULL);
  747. // id objc_assign_weak(id, id*);
  748. WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
  749. // id objc_read_weak(id*);
  750. WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
  751. // void *objc_memmove_collectable(void*, void *, size_t);
  752. MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
  753. SizeTy, NULL);
  754. }
  755. }
  756. llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
  757. const std::string &Name,
  758. bool isWeak) {
  759. llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
  760. // With the incompatible ABI, this will need to be replaced with a direct
  761. // reference to the class symbol. For the compatible nonfragile ABI we are
  762. // still performing this lookup at run time but emitting the symbol for the
  763. // class externally so that we can make the switch later.
  764. //
  765. // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
  766. // with memoized versions or with static references if it's safe to do so.
  767. if (!isWeak)
  768. EmitClassRef(Name);
  769. ClassName = Builder.CreateStructGEP(ClassName, 0);
  770. llvm::Constant *ClassLookupFn =
  771. CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
  772. "objc_lookup_class");
  773. return Builder.CreateCall(ClassLookupFn, ClassName);
  774. }
  775. // This has to perform the lookup every time, since posing and related
  776. // techniques can modify the name -> class mapping.
  777. llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
  778. const ObjCInterfaceDecl *OID) {
  779. return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
  780. }
  781. llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
  782. return GetClassNamed(Builder, "NSAutoreleasePool", false);
  783. }
  784. llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
  785. const std::string &TypeEncoding, bool lval) {
  786. SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
  787. llvm::GlobalAlias *SelValue = 0;
  788. for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
  789. e = Types.end() ; i!=e ; i++) {
  790. if (i->first == TypeEncoding) {
  791. SelValue = i->second;
  792. break;
  793. }
  794. }
  795. if (0 == SelValue) {
  796. SelValue = new llvm::GlobalAlias(SelectorTy,
  797. llvm::GlobalValue::PrivateLinkage,
  798. ".objc_selector_"+Sel.getAsString(), NULL,
  799. &TheModule);
  800. Types.push_back(TypedSelector(TypeEncoding, SelValue));
  801. }
  802. if (lval) {
  803. llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
  804. Builder.CreateStore(SelValue, tmp);
  805. return tmp;
  806. }
  807. return SelValue;
  808. }
  809. llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
  810. bool lval) {
  811. return GetSelector(Builder, Sel, std::string(), lval);
  812. }
  813. llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
  814. *Method) {
  815. std::string SelTypes;
  816. CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
  817. return GetSelector(Builder, Method->getSelector(), SelTypes, false);
  818. }
  819. llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
  820. if (!CGM.getLangOptions().CPlusPlus) {
  821. if (T->isObjCIdType()
  822. || T->isObjCQualifiedIdType()) {
  823. // With the old ABI, there was only one kind of catchall, which broke
  824. // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
  825. // a pointer indicating object catchalls, and NULL to indicate real
  826. // catchalls
  827. if (CGM.getLangOptions().ObjCNonFragileABI) {
  828. return MakeConstantString("@id");
  829. } else {
  830. return 0;
  831. }
  832. }
  833. // All other types should be Objective-C interface pointer types.
  834. const ObjCObjectPointerType *OPT =
  835. T->getAs<ObjCObjectPointerType>();
  836. assert(OPT && "Invalid @catch type.");
  837. const ObjCInterfaceDecl *IDecl =
  838. OPT->getObjectType()->getInterface();
  839. assert(IDecl && "Invalid @catch type.");
  840. return MakeConstantString(IDecl->getIdentifier()->getName());
  841. }
  842. // For Objective-C++, we want to provide the ability to catch both C++ and
  843. // Objective-C objects in the same function.
  844. // There's a particular fixed type info for 'id'.
  845. if (T->isObjCIdType() ||
  846. T->isObjCQualifiedIdType()) {
  847. llvm::Constant *IDEHType =
  848. CGM.getModule().getGlobalVariable("__objc_id_type_info");
  849. if (!IDEHType)
  850. IDEHType =
  851. new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
  852. false,
  853. llvm::GlobalValue::ExternalLinkage,
  854. 0, "__objc_id_type_info");
  855. return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
  856. }
  857. const ObjCObjectPointerType *PT =
  858. T->getAs<ObjCObjectPointerType>();
  859. assert(PT && "Invalid @catch type.");
  860. const ObjCInterfaceType *IT = PT->getInterfaceType();
  861. assert(IT && "Invalid @catch type.");
  862. std::string className = IT->getDecl()->getIdentifier()->getName();
  863. std::string typeinfoName = "__objc_eh_typeinfo_" + className;
  864. // Return the existing typeinfo if it exists
  865. llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
  866. if (typeinfo) return typeinfo;
  867. // Otherwise create it.
  868. // vtable for gnustep::libobjc::__objc_class_type_info
  869. // It's quite ugly hard-coding this. Ideally we'd generate it using the host
  870. // platform's name mangling.
  871. const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
  872. llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
  873. if (!Vtable) {
  874. Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
  875. llvm::GlobalValue::ExternalLinkage, 0, vtableName);
  876. }
  877. llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
  878. Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
  879. Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
  880. llvm::Constant *typeName =
  881. ExportUniqueString(className, "__objc_eh_typename_");
  882. std::vector<llvm::Constant*> fields;
  883. fields.push_back(Vtable);
  884. fields.push_back(typeName);
  885. llvm::Constant *TI =
  886. MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
  887. NULL), fields, "__objc_eh_typeinfo_" + className,
  888. llvm::GlobalValue::LinkOnceODRLinkage);
  889. return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
  890. }
  891. /// Generate an NSConstantString object.
  892. llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
  893. std::string Str = SL->getString().str();
  894. // Look for an existing one
  895. llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
  896. if (old != ObjCStrings.end())
  897. return old->getValue();
  898. StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
  899. if (StringClass.empty()) StringClass = "NXConstantString";
  900. std::string Sym = "_OBJC_CLASS_";
  901. Sym += StringClass;
  902. llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
  903. if (!isa)
  904. isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
  905. llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
  906. else if (isa->getType() != PtrToIdTy)
  907. isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
  908. std::vector<llvm::Constant*> Ivars;
  909. Ivars.push_back(isa);
  910. Ivars.push_back(MakeConstantString(Str));
  911. Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
  912. llvm::Constant *ObjCStr = MakeGlobal(
  913. llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
  914. Ivars, ".objc_str");
  915. ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
  916. ObjCStrings[Str] = ObjCStr;
  917. ConstantStrings.push_back(ObjCStr);
  918. return ObjCStr;
  919. }
  920. ///Generates a message send where the super is the receiver. This is a message
  921. ///send to self with special delivery semantics indicating which class's method
  922. ///should be called.
  923. RValue
  924. CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
  925. ReturnValueSlot Return,
  926. QualType ResultType,
  927. Selector Sel,
  928. const ObjCInterfaceDecl *Class,
  929. bool isCategoryImpl,
  930. llvm::Value *Receiver,
  931. bool IsClassMessage,
  932. const CallArgList &CallArgs,
  933. const ObjCMethodDecl *Method) {
  934. CGBuilderTy &Builder = CGF.Builder;
  935. if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
  936. if (Sel == RetainSel || Sel == AutoreleaseSel) {
  937. return RValue::get(EnforceType(Builder, Receiver,
  938. CGM.getTypes().ConvertType(ResultType)));
  939. }
  940. if (Sel == ReleaseSel) {
  941. return RValue::get(0);
  942. }
  943. }
  944. llvm::Value *cmd = GetSelector(Builder, Sel);
  945. CallArgList ActualArgs;
  946. ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
  947. ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
  948. ActualArgs.addFrom(CallArgs);
  949. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
  950. llvm::Value *ReceiverClass = 0;
  951. if (isCategoryImpl) {
  952. llvm::Constant *classLookupFunction = 0;
  953. if (IsClassMessage) {
  954. classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
  955. IdTy, PtrTy, true), "objc_get_meta_class");
  956. } else {
  957. classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
  958. IdTy, PtrTy, true), "objc_get_class");
  959. }
  960. ReceiverClass = Builder.CreateCall(classLookupFunction,
  961. MakeConstantString(Class->getNameAsString()));
  962. } else {
  963. // Set up global aliases for the metaclass or class pointer if they do not
  964. // already exist. These will are forward-references which will be set to
  965. // pointers to the class and metaclass structure created for the runtime
  966. // load function. To send a message to super, we look up the value of the
  967. // super_class pointer from either the class or metaclass structure.
  968. if (IsClassMessage) {
  969. if (!MetaClassPtrAlias) {
  970. MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
  971. llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
  972. Class->getNameAsString(), NULL, &TheModule);
  973. }
  974. ReceiverClass = MetaClassPtrAlias;
  975. } else {
  976. if (!ClassPtrAlias) {
  977. ClassPtrAlias = new llvm::GlobalAlias(IdTy,
  978. llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
  979. Class->getNameAsString(), NULL, &TheModule);
  980. }
  981. ReceiverClass = ClassPtrAlias;
  982. }
  983. }
  984. // Cast the pointer to a simplified version of the class structure
  985. ReceiverClass = Builder.CreateBitCast(ReceiverClass,
  986. llvm::PointerType::getUnqual(
  987. llvm::StructType::get(IdTy, IdTy, NULL)));
  988. // Get the superclass pointer
  989. ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
  990. // Load the superclass pointer
  991. ReceiverClass = Builder.CreateLoad(ReceiverClass);
  992. // Construct the structure used to look up the IMP
  993. llvm::StructType *ObjCSuperTy = llvm::StructType::get(
  994. Receiver->getType(), IdTy, NULL);
  995. llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
  996. Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
  997. Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
  998. ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
  999. // Get the IMP
  1000. llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
  1001. imp = EnforceType(Builder, imp, MSI.MessengerType);
  1002. llvm::Value *impMD[] = {
  1003. llvm::MDString::get(VMContext, Sel.getAsString()),
  1004. llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
  1005. llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
  1006. };
  1007. llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
  1008. llvm::Instruction *call;
  1009. RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
  1010. call->setMetadata(msgSendMDKind, node);
  1011. return msgRet;
  1012. }
  1013. /// Generate code for a message send expression.
  1014. RValue
  1015. CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
  1016. ReturnValueSlot Return,
  1017. QualType ResultType,
  1018. Selector Sel,
  1019. llvm::Value *Receiver,
  1020. const CallArgList &CallArgs,
  1021. const ObjCInterfaceDecl *Class,
  1022. const ObjCMethodDecl *Method) {
  1023. CGBuilderTy &Builder = CGF.Builder;
  1024. // Strip out message sends to retain / release in GC mode
  1025. if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
  1026. if (Sel == RetainSel || Sel == AutoreleaseSel) {
  1027. return RValue::get(EnforceType(Builder, Receiver,
  1028. CGM.getTypes().ConvertType(ResultType)));
  1029. }
  1030. if (Sel == ReleaseSel) {
  1031. return RValue::get(0);
  1032. }
  1033. }
  1034. // If the return type is something that goes in an integer register, the
  1035. // runtime will handle 0 returns. For other cases, we fill in the 0 value
  1036. // ourselves.
  1037. //
  1038. // The language spec says the result of this kind of message send is
  1039. // undefined, but lots of people seem to have forgotten to read that
  1040. // paragraph and insist on sending messages to nil that have structure
  1041. // returns. With GCC, this generates a random return value (whatever happens
  1042. // to be on the stack / in those registers at the time) on most platforms,
  1043. // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
  1044. // the stack.
  1045. bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
  1046. ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
  1047. llvm::BasicBlock *startBB = 0;
  1048. llvm::BasicBlock *messageBB = 0;
  1049. llvm::BasicBlock *continueBB = 0;
  1050. if (!isPointerSizedReturn) {
  1051. startBB = Builder.GetInsertBlock();
  1052. messageBB = CGF.createBasicBlock("msgSend");
  1053. continueBB = CGF.createBasicBlock("continue");
  1054. llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
  1055. llvm::Constant::getNullValue(Receiver->getType()));
  1056. Builder.CreateCondBr(isNil, continueBB, messageBB);
  1057. CGF.EmitBlock(messageBB);
  1058. }
  1059. IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
  1060. llvm::Value *cmd;
  1061. if (Method)
  1062. cmd = GetSelector(Builder, Method);
  1063. else
  1064. cmd = GetSelector(Builder, Sel);
  1065. cmd = EnforceType(Builder, cmd, SelectorTy);
  1066. Receiver = EnforceType(Builder, Receiver, IdTy);
  1067. llvm::Value *impMD[] = {
  1068. llvm::MDString::get(VMContext, Sel.getAsString()),
  1069. llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
  1070. llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
  1071. };
  1072. llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
  1073. CallArgList ActualArgs;
  1074. ActualArgs.add(RValue::get(Receiver), ASTIdTy);
  1075. ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
  1076. ActualArgs.addFrom(CallArgs);
  1077. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
  1078. // Get the IMP to call
  1079. llvm::Value *imp;
  1080. // If we have non-legacy dispatch specified, we try using the objc_msgSend()
  1081. // functions. These are not supported on all platforms (or all runtimes on a
  1082. // given platform), so we
  1083. switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
  1084. case CodeGenOptions::Legacy:
  1085. imp = LookupIMP(CGF, Receiver, cmd, node);
  1086. break;
  1087. case CodeGenOptions::Mixed:
  1088. case CodeGenOptions::NonLegacy:
  1089. if (CGM.ReturnTypeUsesFPRet(ResultType)) {
  1090. imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  1091. "objc_msgSend_fpret");
  1092. } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
  1093. // The actual types here don't matter - we're going to bitcast the
  1094. // function anyway
  1095. imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  1096. "objc_msgSend_stret");
  1097. } else {
  1098. imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  1099. "objc_msgSend");
  1100. }
  1101. }
  1102. // Reset the receiver in case the lookup modified it
  1103. ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
  1104. imp = EnforceType(Builder, imp, MSI.MessengerType);
  1105. llvm::Instruction *call;
  1106. RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
  1107. 0, &call);
  1108. call->setMetadata(msgSendMDKind, node);
  1109. if (!isPointerSizedReturn) {
  1110. messageBB = CGF.Builder.GetInsertBlock();
  1111. CGF.Builder.CreateBr(continueBB);
  1112. CGF.EmitBlock(continueBB);
  1113. if (msgRet.isScalar()) {
  1114. llvm::Value *v = msgRet.getScalarVal();
  1115. llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
  1116. phi->addIncoming(v, messageBB);
  1117. phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
  1118. msgRet = RValue::get(phi);
  1119. } else if (msgRet.isAggregate()) {
  1120. llvm::Value *v = msgRet.getAggregateAddr();
  1121. llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
  1122. llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
  1123. llvm::AllocaInst *NullVal =
  1124. CGF.CreateTempAlloca(RetTy->getElementType(), "null");
  1125. CGF.InitTempAlloca(NullVal,
  1126. llvm::Constant::getNullValue(RetTy->getElementType()));
  1127. phi->addIncoming(v, messageBB);
  1128. phi->addIncoming(NullVal, startBB);
  1129. msgRet = RValue::getAggregate(phi);
  1130. } else /* isComplex() */ {
  1131. std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
  1132. llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
  1133. phi->addIncoming(v.first, messageBB);
  1134. phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
  1135. startBB);
  1136. llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
  1137. phi2->addIncoming(v.second, messageBB);
  1138. phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
  1139. startBB);
  1140. msgRet = RValue::getComplex(phi, phi2);
  1141. }
  1142. }
  1143. return msgRet;
  1144. }
  1145. /// Generates a MethodList. Used in construction of a objc_class and
  1146. /// objc_category structures.
  1147. llvm::Constant *CGObjCGNU::GenerateMethodList(const StringRef &ClassName,
  1148. const StringRef &CategoryName,
  1149. const SmallVectorImpl<Selector> &MethodSels,
  1150. const SmallVectorImpl<llvm::Constant *> &MethodTypes,
  1151. bool isClassMethodList) {
  1152. if (MethodSels.empty())
  1153. return NULLPtr;
  1154. // Get the method structure type.
  1155. llvm::StructType *ObjCMethodTy = llvm::StructType::get(
  1156. PtrToInt8Ty, // Really a selector, but the runtime creates it us.
  1157. PtrToInt8Ty, // Method types
  1158. IMPTy, //Method pointer
  1159. NULL);
  1160. std::vector<llvm::Constant*> Methods;
  1161. std::vector<llvm::Constant*> Elements;
  1162. for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
  1163. Elements.clear();
  1164. llvm::Constant *Method =
  1165. TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
  1166. MethodSels[i],
  1167. isClassMethodList));
  1168. assert(Method && "Can't generate metadata for method that doesn't exist");
  1169. llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
  1170. Elements.push_back(C);
  1171. Elements.push_back(MethodTypes[i]);
  1172. Method = llvm::ConstantExpr::getBitCast(Method,
  1173. IMPTy);
  1174. Elements.push_back(Method);
  1175. Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
  1176. }
  1177. // Array of method structures
  1178. llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
  1179. Methods.size());
  1180. llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
  1181. Methods);
  1182. // Structure containing list pointer, array and array count
  1183. llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
  1184. llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
  1185. ObjCMethodListTy->setBody(
  1186. NextPtrTy,
  1187. IntTy,
  1188. ObjCMethodArrayTy,
  1189. NULL);
  1190. Methods.clear();
  1191. Methods.push_back(llvm::ConstantPointerNull::get(
  1192. llvm::PointerType::getUnqual(ObjCMethodListTy)));
  1193. Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
  1194. Methods.push_back(MethodArray);
  1195. // Create an instance of the structure
  1196. return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
  1197. }
  1198. /// Generates an IvarList. Used in construction of a objc_class.
  1199. llvm::Constant *CGObjCGNU::GenerateIvarList(
  1200. const SmallVectorImpl<llvm::Constant *> &IvarNames,
  1201. const SmallVectorImpl<llvm::Constant *> &IvarTypes,
  1202. const SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
  1203. if (IvarNames.size() == 0)
  1204. return NULLPtr;
  1205. // Get the method structure type.
  1206. llvm::StructType *ObjCIvarTy = llvm::StructType::get(
  1207. PtrToInt8Ty,
  1208. PtrToInt8Ty,
  1209. IntTy,
  1210. NULL);
  1211. std::vector<llvm::Constant*> Ivars;
  1212. std::vector<llvm::Constant*> Elements;
  1213. for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
  1214. Elements.clear();
  1215. Elements.push_back(IvarNames[i]);
  1216. Elements.push_back(IvarTypes[i]);
  1217. Elements.push_back(IvarOffsets[i]);
  1218. Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
  1219. }
  1220. // Array of method structures
  1221. llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
  1222. IvarNames.size());
  1223. Elements.clear();
  1224. Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
  1225. Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
  1226. // Structure containing array and array count
  1227. llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
  1228. ObjCIvarArrayTy,
  1229. NULL);
  1230. // Create an instance of the structure
  1231. return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
  1232. }
  1233. /// Generate a class structure
  1234. llvm::Constant *CGObjCGNU::GenerateClassStructure(
  1235. llvm::Constant *MetaClass,
  1236. llvm::Constant *SuperClass,
  1237. unsigned info,
  1238. const char *Name,
  1239. llvm::Constant *Version,
  1240. llvm::Constant *InstanceSize,
  1241. llvm::Constant *IVars,
  1242. llvm::Constant *Methods,
  1243. llvm::Constant *Protocols,
  1244. llvm::Constant *IvarOffsets,
  1245. llvm::Constant *Properties,
  1246. llvm::Constant *StrongIvarBitmap,
  1247. llvm::Constant *WeakIvarBitmap,
  1248. bool isMeta) {
  1249. // Set up the class structure
  1250. // Note: Several of these are char*s when they should be ids. This is
  1251. // because the runtime performs this translation on load.
  1252. //
  1253. // Fields marked New ABI are part of the GNUstep runtime. We emit them
  1254. // anyway; the classes will still work with the GNU runtime, they will just
  1255. // be ignored.
  1256. llvm::StructType *ClassTy = llvm::StructType::get(
  1257. PtrToInt8Ty, // isa
  1258. PtrToInt8Ty, // super_class
  1259. PtrToInt8Ty, // name
  1260. LongTy, // version
  1261. LongTy, // info
  1262. LongTy, // instance_size
  1263. IVars->getType(), // ivars
  1264. Methods->getType(), // methods
  1265. // These are all filled in by the runtime, so we pretend
  1266. PtrTy, // dtable
  1267. PtrTy, // subclass_list
  1268. PtrTy, // sibling_class
  1269. PtrTy, // protocols
  1270. PtrTy, // gc_object_type
  1271. // New ABI:
  1272. LongTy, // abi_version
  1273. IvarOffsets->getType(), // ivar_offsets
  1274. Properties->getType(), // properties
  1275. IntPtrTy, // strong_pointers
  1276. IntPtrTy, // weak_pointers
  1277. NULL);
  1278. llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
  1279. // Fill in the structure
  1280. std::vector<llvm::Constant*> Elements;
  1281. Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
  1282. Elements.push_back(SuperClass);
  1283. Elements.push_back(MakeConstantString(Name, ".class_name"));
  1284. Elements.push_back(Zero);
  1285. Elements.push_back(llvm::ConstantInt::get(LongTy, info));
  1286. if (isMeta) {
  1287. llvm::TargetData td(&TheModule);
  1288. Elements.push_back(
  1289. llvm::ConstantInt::get(LongTy,
  1290. td.getTypeSizeInBits(ClassTy) /
  1291. CGM.getContext().getCharWidth()));
  1292. } else
  1293. Elements.push_back(InstanceSize);
  1294. Elements.push_back(IVars);
  1295. Elements.push_back(Methods);
  1296. Elements.push_back(NULLPtr);
  1297. Elements.push_back(NULLPtr);
  1298. Elements.push_back(NULLPtr);
  1299. Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
  1300. Elements.push_back(NULLPtr);
  1301. Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
  1302. Elements.push_back(IvarOffsets);
  1303. Elements.push_back(Properties);
  1304. Elements.push_back(StrongIvarBitmap);
  1305. Elements.push_back(WeakIvarBitmap);
  1306. // Create an instance of the structure
  1307. // This is now an externally visible symbol, so that we can speed up class
  1308. // messages in the next ABI. We may already have some weak references to
  1309. // this, so check and fix them properly.
  1310. std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
  1311. std::string(Name));
  1312. llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
  1313. llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
  1314. llvm::GlobalValue::ExternalLinkage);
  1315. if (ClassRef) {
  1316. ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
  1317. ClassRef->getType()));
  1318. ClassRef->removeFromParent();
  1319. Class->setName(ClassSym);
  1320. }
  1321. return Class;
  1322. }
  1323. llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
  1324. const SmallVectorImpl<llvm::Constant *> &MethodNames,
  1325. const SmallVectorImpl<llvm::Constant *> &MethodTypes) {
  1326. // Get the method structure type.
  1327. llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
  1328. PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
  1329. PtrToInt8Ty,
  1330. NULL);
  1331. std::vector<llvm::Constant*> Methods;
  1332. std::vector<llvm::Constant*> Elements;
  1333. for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
  1334. Elements.clear();
  1335. Elements.push_back(MethodNames[i]);
  1336. Elements.push_back(MethodTypes[i]);
  1337. Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
  1338. }
  1339. llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
  1340. MethodNames.size());
  1341. llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
  1342. Methods);
  1343. llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
  1344. IntTy, ObjCMethodArrayTy, NULL);
  1345. Methods.clear();
  1346. Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
  1347. Methods.push_back(Array);
  1348. return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
  1349. }
  1350. // Create the protocol list structure used in classes, categories and so on
  1351. llvm::Constant *CGObjCGNU::GenerateProtocolList(
  1352. const SmallVectorImpl<std::string> &Protocols) {
  1353. llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
  1354. Protocols.size());
  1355. llvm::StructType *ProtocolListTy = llvm::StructType::get(
  1356. PtrTy, //Should be a recurisve pointer, but it's always NULL here.
  1357. SizeTy,
  1358. ProtocolArrayTy,
  1359. NULL);
  1360. std::vector<llvm::Constant*> Elements;
  1361. for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
  1362. iter != endIter ; iter++) {
  1363. llvm::Constant *protocol = 0;
  1364. llvm::StringMap<llvm::Constant*>::iterator value =
  1365. ExistingProtocols.find(*iter);
  1366. if (value == ExistingProtocols.end()) {
  1367. protocol = GenerateEmptyProtocol(*iter);
  1368. } else {
  1369. protocol = value->getValue();
  1370. }
  1371. llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
  1372. PtrToInt8Ty);
  1373. Elements.push_back(Ptr);
  1374. }
  1375. llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
  1376. Elements);
  1377. Elements.clear();
  1378. Elements.push_back(NULLPtr);
  1379. Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
  1380. Elements.push_back(ProtocolArray);
  1381. return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
  1382. }
  1383. llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
  1384. const ObjCProtocolDecl *PD) {
  1385. llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
  1386. llvm::Type *T =
  1387. CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
  1388. return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
  1389. }
  1390. llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
  1391. const std::string &ProtocolName) {
  1392. SmallVector<std::string, 0> EmptyStringVector;
  1393. SmallVector<llvm::Constant*, 0> EmptyConstantVector;
  1394. llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
  1395. llvm::Constant *MethodList =
  1396. GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
  1397. // Protocols are objects containing lists of the methods implemented and
  1398. // protocols adopted.
  1399. llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
  1400. PtrToInt8Ty,
  1401. ProtocolList->getType(),
  1402. MethodList->getType(),
  1403. MethodList->getType(),
  1404. MethodList->getType(),
  1405. MethodList->getType(),
  1406. NULL);
  1407. std::vector<llvm::Constant*> Elements;
  1408. // The isa pointer must be set to a magic number so the runtime knows it's
  1409. // the correct layout.
  1410. Elements.push_back(llvm::ConstantExpr::getIntToPtr(
  1411. llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
  1412. Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
  1413. Elements.push_back(ProtocolList);
  1414. Elements.push_back(MethodList);
  1415. Elements.push_back(MethodList);
  1416. Elements.push_back(MethodList);
  1417. Elements.push_back(MethodList);
  1418. return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
  1419. }
  1420. void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
  1421. ASTContext &Context = CGM.getContext();
  1422. std::string ProtocolName = PD->getNameAsString();
  1423. // Use the protocol definition, if there is one.
  1424. if (const ObjCProtocolDecl *Def = PD->getDefinition())
  1425. PD = Def;
  1426. SmallVector<std::string, 16> Protocols;
  1427. for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
  1428. E = PD->protocol_end(); PI != E; ++PI)
  1429. Protocols.push_back((*PI)->getNameAsString());
  1430. SmallVector<llvm::Constant*, 16> InstanceMethodNames;
  1431. SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
  1432. SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
  1433. SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
  1434. for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
  1435. E = PD->instmeth_end(); iter != E; iter++) {
  1436. std::string TypeStr;
  1437. Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
  1438. if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
  1439. InstanceMethodNames.push_back(
  1440. MakeConstantString((*iter)->getSelector().getAsString()));
  1441. InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
  1442. } else {
  1443. OptionalInstanceMethodNames.push_back(
  1444. MakeConstantString((*iter)->getSelector().getAsString()));
  1445. OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
  1446. }
  1447. }
  1448. // Collect information about class methods:
  1449. SmallVector<llvm::Constant*, 16> ClassMethodNames;
  1450. SmallVector<llvm::Constant*, 16> ClassMethodTypes;
  1451. SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
  1452. SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
  1453. for (ObjCProtocolDecl::classmeth_iterator
  1454. iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
  1455. iter != endIter ; iter++) {
  1456. std::string TypeStr;
  1457. Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
  1458. if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
  1459. ClassMethodNames.push_back(
  1460. MakeConstantString((*iter)->getSelector().getAsString()));
  1461. ClassMethodTypes.push_back(MakeConstantString(TypeStr));
  1462. } else {
  1463. OptionalClassMethodNames.push_back(
  1464. MakeConstantString((*iter)->getSelector().getAsString()));
  1465. OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
  1466. }
  1467. }
  1468. llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
  1469. llvm::Constant *InstanceMethodList =
  1470. GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
  1471. llvm::Constant *ClassMethodList =
  1472. GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
  1473. llvm::Constant *OptionalInstanceMethodList =
  1474. GenerateProtocolMethodList(OptionalInstanceMethodNames,
  1475. OptionalInstanceMethodTypes);
  1476. llvm::Constant *OptionalClassMethodList =
  1477. GenerateProtocolMethodList(OptionalClassMethodNames,
  1478. OptionalClassMethodTypes);
  1479. // Property metadata: name, attributes, isSynthesized, setter name, setter
  1480. // types, getter name, getter types.
  1481. // The isSynthesized value is always set to 0 in a protocol. It exists to
  1482. // simplify the runtime library by allowing it to use the same data
  1483. // structures for protocol metadata everywhere.
  1484. llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
  1485. PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
  1486. PtrToInt8Ty, NULL);
  1487. std::vector<llvm::Constant*> Properties;
  1488. std::vector<llvm::Constant*> OptionalProperties;
  1489. // Add all of the property methods need adding to the method list and to the
  1490. // property metadata list.
  1491. for (ObjCContainerDecl::prop_iterator
  1492. iter = PD->prop_begin(), endIter = PD->prop_end();
  1493. iter != endIter ; iter++) {
  1494. std::vector<llvm::Constant*> Fields;
  1495. ObjCPropertyDecl *property = (*iter);
  1496. Fields.push_back(MakeConstantString(property->getNameAsString()));
  1497. Fields.push_back(llvm::ConstantInt::get(Int8Ty,
  1498. property->getPropertyAttributes()));
  1499. Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
  1500. if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
  1501. std::string TypeStr;
  1502. Context.getObjCEncodingForMethodDecl(getter,TypeStr);
  1503. llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
  1504. InstanceMethodTypes.push_back(TypeEncoding);
  1505. Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
  1506. Fields.push_back(TypeEncoding);
  1507. } else {
  1508. Fields.push_back(NULLPtr);
  1509. Fields.push_back(NULLPtr);
  1510. }
  1511. if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
  1512. std::string TypeStr;
  1513. Context.getObjCEncodingForMethodDecl(setter,TypeStr);
  1514. llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
  1515. InstanceMethodTypes.push_back(TypeEncoding);
  1516. Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
  1517. Fields.push_back(TypeEncoding);
  1518. } else {
  1519. Fields.push_back(NULLPtr);
  1520. Fields.push_back(NULLPtr);
  1521. }
  1522. if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
  1523. OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
  1524. } else {
  1525. Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
  1526. }
  1527. }
  1528. llvm::Constant *PropertyArray = llvm::ConstantArray::get(
  1529. llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
  1530. llvm::Constant* PropertyListInitFields[] =
  1531. {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
  1532. llvm::Constant *PropertyListInit =
  1533. llvm::ConstantStruct::getAnon(PropertyListInitFields);
  1534. llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
  1535. PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
  1536. PropertyListInit, ".objc_property_list");
  1537. llvm::Constant *OptionalPropertyArray =
  1538. llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
  1539. OptionalProperties.size()) , OptionalProperties);
  1540. llvm::Constant* OptionalPropertyListInitFields[] = {
  1541. llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
  1542. OptionalPropertyArray };
  1543. llvm::Constant *OptionalPropertyListInit =
  1544. llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
  1545. llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
  1546. OptionalPropertyListInit->getType(), false,
  1547. llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
  1548. ".objc_property_list");
  1549. // Protocols are objects containing lists of the methods implemented and
  1550. // protocols adopted.
  1551. llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
  1552. PtrToInt8Ty,
  1553. ProtocolList->getType(),
  1554. InstanceMethodList->getType(),
  1555. ClassMethodList->getType(),
  1556. OptionalInstanceMethodList->getType(),
  1557. OptionalClassMethodList->getType(),
  1558. PropertyList->getType(),
  1559. OptionalPropertyList->getType(),
  1560. NULL);
  1561. std::vector<llvm::Constant*> Elements;
  1562. // The isa pointer must be set to a magic number so the runtime knows it's
  1563. // the correct layout.
  1564. Elements.push_back(llvm::ConstantExpr::getIntToPtr(
  1565. llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
  1566. Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
  1567. Elements.push_back(ProtocolList);
  1568. Elements.push_back(InstanceMethodList);
  1569. Elements.push_back(ClassMethodList);
  1570. Elements.push_back(OptionalInstanceMethodList);
  1571. Elements.push_back(OptionalClassMethodList);
  1572. Elements.push_back(PropertyList);
  1573. Elements.push_back(OptionalPropertyList);
  1574. ExistingProtocols[ProtocolName] =
  1575. llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
  1576. ".objc_protocol"), IdTy);
  1577. }
  1578. void CGObjCGNU::GenerateProtocolHolderCategory(void) {
  1579. // Collect information about instance methods
  1580. SmallVector<Selector, 1> MethodSels;
  1581. SmallVector<llvm::Constant*, 1> MethodTypes;
  1582. std::vector<llvm::Constant*> Elements;
  1583. const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
  1584. const std::string CategoryName = "AnotherHack";
  1585. Elements.push_back(MakeConstantString(CategoryName));
  1586. Elements.push_back(MakeConstantString(ClassName));
  1587. // Instance method list
  1588. Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
  1589. ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
  1590. // Class method list
  1591. Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
  1592. ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
  1593. // Protocol list
  1594. llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
  1595. ExistingProtocols.size());
  1596. llvm::StructType *ProtocolListTy = llvm::StructType::get(
  1597. PtrTy, //Should be a recurisve pointer, but it's always NULL here.
  1598. SizeTy,
  1599. ProtocolArrayTy,
  1600. NULL);
  1601. std::vector<llvm::Constant*> ProtocolElements;
  1602. for (llvm::StringMapIterator<llvm::Constant*> iter =
  1603. ExistingProtocols.begin(), endIter = ExistingProtocols.end();
  1604. iter != endIter ; iter++) {
  1605. llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
  1606. PtrTy);
  1607. ProtocolElements.push_back(Ptr);
  1608. }
  1609. llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
  1610. ProtocolElements);
  1611. ProtocolElements.clear();
  1612. ProtocolElements.push_back(NULLPtr);
  1613. ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
  1614. ExistingProtocols.size()));
  1615. ProtocolElements.push_back(ProtocolArray);
  1616. Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
  1617. ProtocolElements, ".objc_protocol_list"), PtrTy));
  1618. Categories.push_back(llvm::ConstantExpr::getBitCast(
  1619. MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
  1620. PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
  1621. }
  1622. /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
  1623. /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
  1624. /// bits set to their values, LSB first, while larger ones are stored in a
  1625. /// structure of this / form:
  1626. ///
  1627. /// struct { int32_t length; int32_t values[length]; };
  1628. ///
  1629. /// The values in the array are stored in host-endian format, with the least
  1630. /// significant bit being assumed to come first in the bitfield. Therefore, a
  1631. /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
  1632. /// bitfield / with the 63rd bit set will be 1<<64.
  1633. llvm::Constant *CGObjCGNU::MakeBitField(llvm::SmallVectorImpl<bool> &bits) {
  1634. int bitCount = bits.size();
  1635. int ptrBits =
  1636. (TheModule.getPointerSize() == llvm::Module::Pointer32) ? 32 : 64;
  1637. if (bitCount < ptrBits) {
  1638. uint64_t val = 1;
  1639. for (int i=0 ; i<bitCount ; ++i) {
  1640. if (bits[i]) val |= 1ULL<<(i+1);
  1641. }
  1642. return llvm::ConstantInt::get(IntPtrTy, val);
  1643. }
  1644. llvm::SmallVector<llvm::Constant*, 8> values;
  1645. int v=0;
  1646. while (v < bitCount) {
  1647. int32_t word = 0;
  1648. for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
  1649. if (bits[v]) word |= 1<<i;
  1650. v++;
  1651. }
  1652. values.push_back(llvm::ConstantInt::get(Int32Ty, word));
  1653. }
  1654. llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
  1655. llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
  1656. llvm::Constant *fields[2] = {
  1657. llvm::ConstantInt::get(Int32Ty, values.size()),
  1658. array };
  1659. llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
  1660. NULL), fields);
  1661. llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
  1662. return ptr;
  1663. }
  1664. void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
  1665. std::string ClassName = OCD->getClassInterface()->getNameAsString();
  1666. std::string CategoryName = OCD->getNameAsString();
  1667. // Collect information about instance methods
  1668. SmallVector<Selector, 16> InstanceMethodSels;
  1669. SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
  1670. for (ObjCCategoryImplDecl::instmeth_iterator
  1671. iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
  1672. iter != endIter ; iter++) {
  1673. InstanceMethodSels.push_back((*iter)->getSelector());
  1674. std::string TypeStr;
  1675. CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
  1676. InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
  1677. }
  1678. // Collect information about class methods
  1679. SmallVector<Selector, 16> ClassMethodSels;
  1680. SmallVector<llvm::Constant*, 16> ClassMethodTypes;
  1681. for (ObjCCategoryImplDecl::classmeth_iterator
  1682. iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
  1683. iter != endIter ; iter++) {
  1684. ClassMethodSels.push_back((*iter)->getSelector());
  1685. std::string TypeStr;
  1686. CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
  1687. ClassMethodTypes.push_back(MakeConstantString(TypeStr));
  1688. }
  1689. // Collect the names of referenced protocols
  1690. SmallVector<std::string, 16> Protocols;
  1691. const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
  1692. const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
  1693. for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
  1694. E = Protos.end(); I != E; ++I)
  1695. Protocols.push_back((*I)->getNameAsString());
  1696. std::vector<llvm::Constant*> Elements;
  1697. Elements.push_back(MakeConstantString(CategoryName));
  1698. Elements.push_back(MakeConstantString(ClassName));
  1699. // Instance method list
  1700. Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
  1701. ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
  1702. false), PtrTy));
  1703. // Class method list
  1704. Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
  1705. ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
  1706. PtrTy));
  1707. // Protocol list
  1708. Elements.push_back(llvm::ConstantExpr::getBitCast(
  1709. GenerateProtocolList(Protocols), PtrTy));
  1710. Categories.push_back(llvm::ConstantExpr::getBitCast(
  1711. MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
  1712. PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
  1713. }
  1714. llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
  1715. SmallVectorImpl<Selector> &InstanceMethodSels,
  1716. SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
  1717. ASTContext &Context = CGM.getContext();
  1718. //
  1719. // Property metadata: name, attributes, isSynthesized, setter name, setter
  1720. // types, getter name, getter types.
  1721. llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
  1722. PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
  1723. PtrToInt8Ty, NULL);
  1724. std::vector<llvm::Constant*> Properties;
  1725. // Add all of the property methods need adding to the method list and to the
  1726. // property metadata list.
  1727. for (ObjCImplDecl::propimpl_iterator
  1728. iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
  1729. iter != endIter ; iter++) {
  1730. std::vector<llvm::Constant*> Fields;
  1731. ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
  1732. ObjCPropertyImplDecl *propertyImpl = *iter;
  1733. bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
  1734. ObjCPropertyImplDecl::Synthesize);
  1735. Fields.push_back(MakeConstantString(property->getNameAsString()));
  1736. Fields.push_back(llvm::ConstantInt::get(Int8Ty,
  1737. property->getPropertyAttributes()));
  1738. Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
  1739. if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
  1740. std::string TypeStr;
  1741. Context.getObjCEncodingForMethodDecl(getter,TypeStr);
  1742. llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
  1743. if (isSynthesized) {
  1744. InstanceMethodTypes.push_back(TypeEncoding);
  1745. InstanceMethodSels.push_back(getter->getSelector());
  1746. }
  1747. Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
  1748. Fields.push_back(TypeEncoding);
  1749. } else {
  1750. Fields.push_back(NULLPtr);
  1751. Fields.push_back(NULLPtr);
  1752. }
  1753. if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
  1754. std::string TypeStr;
  1755. Context.getObjCEncodingForMethodDecl(setter,TypeStr);
  1756. llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
  1757. if (isSynthesized) {
  1758. InstanceMethodTypes.push_back(TypeEncoding);
  1759. InstanceMethodSels.push_back(setter->getSelector());
  1760. }
  1761. Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
  1762. Fields.push_back(TypeEncoding);
  1763. } else {
  1764. Fields.push_back(NULLPtr);
  1765. Fields.push_back(NULLPtr);
  1766. }
  1767. Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
  1768. }
  1769. llvm::ArrayType *PropertyArrayTy =
  1770. llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
  1771. llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
  1772. Properties);
  1773. llvm::Constant* PropertyListInitFields[] =
  1774. {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
  1775. llvm::Constant *PropertyListInit =
  1776. llvm::ConstantStruct::getAnon(PropertyListInitFields);
  1777. return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
  1778. llvm::GlobalValue::InternalLinkage, PropertyListInit,
  1779. ".objc_property_list");
  1780. }
  1781. void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
  1782. // Get the class declaration for which the alias is specified.
  1783. ObjCInterfaceDecl *ClassDecl =
  1784. const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
  1785. std::string ClassName = ClassDecl->getNameAsString();
  1786. std::string AliasName = OAD->getNameAsString();
  1787. ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
  1788. }
  1789. void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
  1790. ASTContext &Context = CGM.getContext();
  1791. // Get the superclass name.
  1792. const ObjCInterfaceDecl * SuperClassDecl =
  1793. OID->getClassInterface()->getSuperClass();
  1794. std::string SuperClassName;
  1795. if (SuperClassDecl) {
  1796. SuperClassName = SuperClassDecl->getNameAsString();
  1797. EmitClassRef(SuperClassName);
  1798. }
  1799. // Get the class name
  1800. ObjCInterfaceDecl *ClassDecl =
  1801. const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
  1802. std::string ClassName = ClassDecl->getNameAsString();
  1803. // Emit the symbol that is used to generate linker errors if this class is
  1804. // referenced in other modules but not declared.
  1805. std::string classSymbolName = "__objc_class_name_" + ClassName;
  1806. if (llvm::GlobalVariable *symbol =
  1807. TheModule.getGlobalVariable(classSymbolName)) {
  1808. symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
  1809. } else {
  1810. new llvm::GlobalVariable(TheModule, LongTy, false,
  1811. llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
  1812. classSymbolName);
  1813. }
  1814. // Get the size of instances.
  1815. int instanceSize =
  1816. Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
  1817. // Collect information about instance variables.
  1818. SmallVector<llvm::Constant*, 16> IvarNames;
  1819. SmallVector<llvm::Constant*, 16> IvarTypes;
  1820. SmallVector<llvm::Constant*, 16> IvarOffsets;
  1821. std::vector<llvm::Constant*> IvarOffsetValues;
  1822. SmallVector<bool, 16> WeakIvars;
  1823. SmallVector<bool, 16> StrongIvars;
  1824. int superInstanceSize = !SuperClassDecl ? 0 :
  1825. Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
  1826. // For non-fragile ivars, set the instance size to 0 - {the size of just this
  1827. // class}. The runtime will then set this to the correct value on load.
  1828. if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
  1829. instanceSize = 0 - (instanceSize - superInstanceSize);
  1830. }
  1831. for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
  1832. IVD = IVD->getNextIvar()) {
  1833. // Store the name
  1834. IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
  1835. // Get the type encoding for this ivar
  1836. std::string TypeStr;
  1837. Context.getObjCEncodingForType(IVD->getType(), TypeStr);
  1838. IvarTypes.push_back(MakeConstantString(TypeStr));
  1839. // Get the offset
  1840. uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
  1841. uint64_t Offset = BaseOffset;
  1842. if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
  1843. Offset = BaseOffset - superInstanceSize;
  1844. }
  1845. llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
  1846. // Create the direct offset value
  1847. std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
  1848. IVD->getNameAsString();
  1849. llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
  1850. if (OffsetVar) {
  1851. OffsetVar->setInitializer(OffsetValue);
  1852. // If this is the real definition, change its linkage type so that
  1853. // different modules will use this one, rather than their private
  1854. // copy.
  1855. OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
  1856. } else
  1857. OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
  1858. false, llvm::GlobalValue::ExternalLinkage,
  1859. OffsetValue,
  1860. "__objc_ivar_offset_value_" + ClassName +"." +
  1861. IVD->getNameAsString());
  1862. IvarOffsets.push_back(OffsetValue);
  1863. IvarOffsetValues.push_back(OffsetVar);
  1864. Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
  1865. switch (lt) {
  1866. case Qualifiers::OCL_Strong:
  1867. StrongIvars.push_back(true);
  1868. WeakIvars.push_back(false);
  1869. break;
  1870. case Qualifiers::OCL_Weak:
  1871. StrongIvars.push_back(false);
  1872. WeakIvars.push_back(true);
  1873. break;
  1874. default:
  1875. StrongIvars.push_back(false);
  1876. WeakIvars.push_back(false);
  1877. }
  1878. }
  1879. llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
  1880. llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
  1881. llvm::GlobalVariable *IvarOffsetArray =
  1882. MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
  1883. // Collect information about instance methods
  1884. SmallVector<Selector, 16> InstanceMethodSels;
  1885. SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
  1886. for (ObjCImplementationDecl::instmeth_iterator
  1887. iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
  1888. iter != endIter ; iter++) {
  1889. InstanceMethodSels.push_back((*iter)->getSelector());
  1890. std::string TypeStr;
  1891. Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
  1892. InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
  1893. }
  1894. llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
  1895. InstanceMethodTypes);
  1896. // Collect information about class methods
  1897. SmallVector<Selector, 16> ClassMethodSels;
  1898. SmallVector<llvm::Constant*, 16> ClassMethodTypes;
  1899. for (ObjCImplementationDecl::classmeth_iterator
  1900. iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
  1901. iter != endIter ; iter++) {
  1902. ClassMethodSels.push_back((*iter)->getSelector());
  1903. std::string TypeStr;
  1904. Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
  1905. ClassMethodTypes.push_back(MakeConstantString(TypeStr));
  1906. }
  1907. // Collect the names of referenced protocols
  1908. SmallVector<std::string, 16> Protocols;
  1909. const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
  1910. for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
  1911. E = Protos.end(); I != E; ++I)
  1912. Protocols.push_back((*I)->getNameAsString());
  1913. // Get the superclass pointer.
  1914. llvm::Constant *SuperClass;
  1915. if (!SuperClassName.empty()) {
  1916. SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
  1917. } else {
  1918. SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
  1919. }
  1920. // Empty vector used to construct empty method lists
  1921. SmallVector<llvm::Constant*, 1> empty;
  1922. // Generate the method and instance variable lists
  1923. llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
  1924. InstanceMethodSels, InstanceMethodTypes, false);
  1925. llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
  1926. ClassMethodSels, ClassMethodTypes, true);
  1927. llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
  1928. IvarOffsets);
  1929. // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
  1930. // we emit a symbol containing the offset for each ivar in the class. This
  1931. // allows code compiled for the non-Fragile ABI to inherit from code compiled
  1932. // for the legacy ABI, without causing problems. The converse is also
  1933. // possible, but causes all ivar accesses to be fragile.
  1934. // Offset pointer for getting at the correct field in the ivar list when
  1935. // setting up the alias. These are: The base address for the global, the
  1936. // ivar array (second field), the ivar in this list (set for each ivar), and
  1937. // the offset (third field in ivar structure)
  1938. llvm::Type *IndexTy = Int32Ty;
  1939. llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
  1940. llvm::ConstantInt::get(IndexTy, 1), 0,
  1941. llvm::ConstantInt::get(IndexTy, 2) };
  1942. unsigned ivarIndex = 0;
  1943. for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
  1944. IVD = IVD->getNextIvar()) {
  1945. const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
  1946. + IVD->getNameAsString();
  1947. offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
  1948. // Get the correct ivar field
  1949. llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
  1950. IvarList, offsetPointerIndexes);
  1951. // Get the existing variable, if one exists.
  1952. llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
  1953. if (offset) {
  1954. offset->setInitializer(offsetValue);
  1955. // If this is the real definition, change its linkage type so that
  1956. // different modules will use this one, rather than their private
  1957. // copy.
  1958. offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
  1959. } else {
  1960. // Add a new alias if there isn't one already.
  1961. offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
  1962. false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
  1963. }
  1964. ++ivarIndex;
  1965. }
  1966. llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
  1967. //Generate metaclass for class methods
  1968. llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
  1969. NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
  1970. empty, empty, empty), ClassMethodList, NULLPtr,
  1971. NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
  1972. // Generate the class structure
  1973. llvm::Constant *ClassStruct =
  1974. GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
  1975. ClassName.c_str(), 0,
  1976. llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
  1977. MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
  1978. Properties, StrongIvarBitmap, WeakIvarBitmap);
  1979. // Resolve the class aliases, if they exist.
  1980. if (ClassPtrAlias) {
  1981. ClassPtrAlias->replaceAllUsesWith(
  1982. llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
  1983. ClassPtrAlias->eraseFromParent();
  1984. ClassPtrAlias = 0;
  1985. }
  1986. if (MetaClassPtrAlias) {
  1987. MetaClassPtrAlias->replaceAllUsesWith(
  1988. llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
  1989. MetaClassPtrAlias->eraseFromParent();
  1990. MetaClassPtrAlias = 0;
  1991. }
  1992. // Add class structure to list to be added to the symtab later
  1993. ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
  1994. Classes.push_back(ClassStruct);
  1995. }
  1996. llvm::Function *CGObjCGNU::ModuleInitFunction() {
  1997. // Only emit an ObjC load function if no Objective-C stuff has been called
  1998. if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
  1999. ExistingProtocols.empty() && SelectorTable.empty())
  2000. return NULL;
  2001. // Add all referenced protocols to a category.
  2002. GenerateProtocolHolderCategory();
  2003. llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
  2004. SelectorTy->getElementType());
  2005. llvm::Type *SelStructPtrTy = SelectorTy;
  2006. if (SelStructTy == 0) {
  2007. SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
  2008. SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
  2009. }
  2010. std::vector<llvm::Constant*> Elements;
  2011. llvm::Constant *Statics = NULLPtr;
  2012. // Generate statics list:
  2013. if (ConstantStrings.size()) {
  2014. llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
  2015. ConstantStrings.size() + 1);
  2016. ConstantStrings.push_back(NULLPtr);
  2017. StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
  2018. if (StringClass.empty()) StringClass = "NXConstantString";
  2019. Elements.push_back(MakeConstantString(StringClass,
  2020. ".objc_static_class_name"));
  2021. Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
  2022. ConstantStrings));
  2023. llvm::StructType *StaticsListTy =
  2024. llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
  2025. llvm::Type *StaticsListPtrTy =
  2026. llvm::PointerType::getUnqual(StaticsListTy);
  2027. Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
  2028. llvm::ArrayType *StaticsListArrayTy =
  2029. llvm::ArrayType::get(StaticsListPtrTy, 2);
  2030. Elements.clear();
  2031. Elements.push_back(Statics);
  2032. Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
  2033. Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
  2034. Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
  2035. }
  2036. // Array of classes, categories, and constant objects
  2037. llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
  2038. Classes.size() + Categories.size() + 2);
  2039. llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
  2040. llvm::Type::getInt16Ty(VMContext),
  2041. llvm::Type::getInt16Ty(VMContext),
  2042. ClassListTy, NULL);
  2043. Elements.clear();
  2044. // Pointer to an array of selectors used in this module.
  2045. std::vector<llvm::Constant*> Selectors;
  2046. std::vector<llvm::GlobalAlias*> SelectorAliases;
  2047. for (SelectorMap::iterator iter = SelectorTable.begin(),
  2048. iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
  2049. std::string SelNameStr = iter->first.getAsString();
  2050. llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
  2051. SmallVectorImpl<TypedSelector> &Types = iter->second;
  2052. for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
  2053. e = Types.end() ; i!=e ; i++) {
  2054. llvm::Constant *SelectorTypeEncoding = NULLPtr;
  2055. if (!i->first.empty())
  2056. SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
  2057. Elements.push_back(SelName);
  2058. Elements.push_back(SelectorTypeEncoding);
  2059. Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
  2060. Elements.clear();
  2061. // Store the selector alias for later replacement
  2062. SelectorAliases.push_back(i->second);
  2063. }
  2064. }
  2065. unsigned SelectorCount = Selectors.size();
  2066. // NULL-terminate the selector list. This should not actually be required,
  2067. // because the selector list has a length field. Unfortunately, the GCC
  2068. // runtime decides to ignore the length field and expects a NULL terminator,
  2069. // and GCC cooperates with this by always setting the length to 0.
  2070. Elements.push_back(NULLPtr);
  2071. Elements.push_back(NULLPtr);
  2072. Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
  2073. Elements.clear();
  2074. // Number of static selectors
  2075. Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
  2076. llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
  2077. ".objc_selector_list");
  2078. Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
  2079. SelStructPtrTy));
  2080. // Now that all of the static selectors exist, create pointers to them.
  2081. for (unsigned int i=0 ; i<SelectorCount ; i++) {
  2082. llvm::Constant *Idxs[] = {Zeros[0],
  2083. llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
  2084. // FIXME: We're generating redundant loads and stores here!
  2085. llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
  2086. makeArrayRef(Idxs, 2));
  2087. // If selectors are defined as an opaque type, cast the pointer to this
  2088. // type.
  2089. SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
  2090. SelectorAliases[i]->replaceAllUsesWith(SelPtr);
  2091. SelectorAliases[i]->eraseFromParent();
  2092. }
  2093. // Number of classes defined.
  2094. Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
  2095. Classes.size()));
  2096. // Number of categories defined
  2097. Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
  2098. Categories.size()));
  2099. // Create an array of classes, then categories, then static object instances
  2100. Classes.insert(Classes.end(), Categories.begin(), Categories.end());
  2101. // NULL-terminated list of static object instances (mainly constant strings)
  2102. Classes.push_back(Statics);
  2103. Classes.push_back(NULLPtr);
  2104. llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
  2105. Elements.push_back(ClassList);
  2106. // Construct the symbol table
  2107. llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
  2108. // The symbol table is contained in a module which has some version-checking
  2109. // constants
  2110. llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
  2111. PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
  2112. (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
  2113. Elements.clear();
  2114. // Runtime version, used for ABI compatibility checking.
  2115. Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
  2116. // sizeof(ModuleTy)
  2117. llvm::TargetData td(&TheModule);
  2118. Elements.push_back(
  2119. llvm::ConstantInt::get(LongTy,
  2120. td.getTypeSizeInBits(ModuleTy) /
  2121. CGM.getContext().getCharWidth()));
  2122. // The path to the source file where this module was declared
  2123. SourceManager &SM = CGM.getContext().getSourceManager();
  2124. const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
  2125. std::string path =
  2126. std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
  2127. Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
  2128. Elements.push_back(SymTab);
  2129. if (RuntimeVersion >= 10)
  2130. switch (CGM.getLangOptions().getGC()) {
  2131. case LangOptions::GCOnly:
  2132. Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
  2133. break;
  2134. case LangOptions::NonGC:
  2135. if (CGM.getLangOptions().ObjCAutoRefCount)
  2136. Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
  2137. else
  2138. Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
  2139. break;
  2140. case LangOptions::HybridGC:
  2141. Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
  2142. break;
  2143. }
  2144. llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
  2145. // Create the load function calling the runtime entry point with the module
  2146. // structure
  2147. llvm::Function * LoadFunction = llvm::Function::Create(
  2148. llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
  2149. llvm::GlobalValue::InternalLinkage, ".objc_load_function",
  2150. &TheModule);
  2151. llvm::BasicBlock *EntryBB =
  2152. llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
  2153. CGBuilderTy Builder(VMContext);
  2154. Builder.SetInsertPoint(EntryBB);
  2155. llvm::FunctionType *FT =
  2156. llvm::FunctionType::get(Builder.getVoidTy(),
  2157. llvm::PointerType::getUnqual(ModuleTy), true);
  2158. llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
  2159. Builder.CreateCall(Register, Module);
  2160. if (!ClassAliases.empty()) {
  2161. llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
  2162. llvm::FunctionType *RegisterAliasTy =
  2163. llvm::FunctionType::get(Builder.getVoidTy(),
  2164. ArgTypes, false);
  2165. llvm::Function *RegisterAlias = llvm::Function::Create(
  2166. RegisterAliasTy,
  2167. llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
  2168. &TheModule);
  2169. llvm::BasicBlock *AliasBB =
  2170. llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
  2171. llvm::BasicBlock *NoAliasBB =
  2172. llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
  2173. // Branch based on whether the runtime provided class_registerAlias_np()
  2174. llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
  2175. llvm::Constant::getNullValue(RegisterAlias->getType()));
  2176. Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
  2177. // The true branch (has alias registration fucntion):
  2178. Builder.SetInsertPoint(AliasBB);
  2179. // Emit alias registration calls:
  2180. for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
  2181. iter != ClassAliases.end(); ++iter) {
  2182. llvm::Constant *TheClass =
  2183. TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
  2184. true);
  2185. if (0 != TheClass) {
  2186. TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
  2187. Builder.CreateCall2(RegisterAlias, TheClass,
  2188. MakeConstantString(iter->second));
  2189. }
  2190. }
  2191. // Jump to end:
  2192. Builder.CreateBr(NoAliasBB);
  2193. // Missing alias registration function, just return from the function:
  2194. Builder.SetInsertPoint(NoAliasBB);
  2195. }
  2196. Builder.CreateRetVoid();
  2197. return LoadFunction;
  2198. }
  2199. llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
  2200. const ObjCContainerDecl *CD) {
  2201. const ObjCCategoryImplDecl *OCD =
  2202. dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
  2203. StringRef CategoryName = OCD ? OCD->getName() : "";
  2204. StringRef ClassName = CD->getName();
  2205. Selector MethodName = OMD->getSelector();
  2206. bool isClassMethod = !OMD->isInstanceMethod();
  2207. CodeGenTypes &Types = CGM.getTypes();
  2208. llvm::FunctionType *MethodTy =
  2209. Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
  2210. std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
  2211. MethodName, isClassMethod);
  2212. llvm::Function *Method
  2213. = llvm::Function::Create(MethodTy,
  2214. llvm::GlobalValue::InternalLinkage,
  2215. FunctionName,
  2216. &TheModule);
  2217. return Method;
  2218. }
  2219. llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
  2220. return GetPropertyFn;
  2221. }
  2222. llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
  2223. return SetPropertyFn;
  2224. }
  2225. llvm::Constant *CGObjCGNU::GetGetStructFunction() {
  2226. return GetStructPropertyFn;
  2227. }
  2228. llvm::Constant *CGObjCGNU::GetSetStructFunction() {
  2229. return SetStructPropertyFn;
  2230. }
  2231. llvm::Constant *CGObjCGNU::GetCppAtomicObjectFunction() {
  2232. return 0;
  2233. }
  2234. llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
  2235. return EnumerationMutationFn;
  2236. }
  2237. void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
  2238. const ObjCAtSynchronizedStmt &S) {
  2239. EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
  2240. }
  2241. void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
  2242. const ObjCAtTryStmt &S) {
  2243. // Unlike the Apple non-fragile runtimes, which also uses
  2244. // unwind-based zero cost exceptions, the GNU Objective C runtime's
  2245. // EH support isn't a veneer over C++ EH. Instead, exception
  2246. // objects are created by __objc_exception_throw and destroyed by
  2247. // the personality function; this avoids the need for bracketing
  2248. // catch handlers with calls to __blah_begin_catch/__blah_end_catch
  2249. // (or even _Unwind_DeleteException), but probably doesn't
  2250. // interoperate very well with foreign exceptions.
  2251. //
  2252. // In Objective-C++ mode, we actually emit something equivalent to the C++
  2253. // exception handler.
  2254. EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
  2255. return ;
  2256. }
  2257. void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
  2258. const ObjCAtThrowStmt &S) {
  2259. llvm::Value *ExceptionAsObject;
  2260. if (const Expr *ThrowExpr = S.getThrowExpr()) {
  2261. llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
  2262. ExceptionAsObject = Exception;
  2263. } else {
  2264. assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
  2265. "Unexpected rethrow outside @catch block.");
  2266. ExceptionAsObject = CGF.ObjCEHValueStack.back();
  2267. }
  2268. ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
  2269. // Note: This may have to be an invoke, if we want to support constructs like:
  2270. // @try {
  2271. // @throw(obj);
  2272. // }
  2273. // @catch(id) ...
  2274. //
  2275. // This is effectively turning @throw into an incredibly-expensive goto, but
  2276. // it may happen as a result of inlining followed by missed optimizations, or
  2277. // as a result of stupidity.
  2278. llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
  2279. if (!UnwindBB) {
  2280. CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
  2281. CGF.Builder.CreateUnreachable();
  2282. } else {
  2283. CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB,
  2284. ExceptionAsObject);
  2285. }
  2286. // Clear the insertion point to indicate we are in unreachable code.
  2287. CGF.Builder.ClearInsertionPoint();
  2288. }
  2289. llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
  2290. llvm::Value *AddrWeakObj) {
  2291. CGBuilderTy B = CGF.Builder;
  2292. AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
  2293. return B.CreateCall(WeakReadFn, AddrWeakObj);
  2294. }
  2295. void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
  2296. llvm::Value *src, llvm::Value *dst) {
  2297. CGBuilderTy B = CGF.Builder;
  2298. src = EnforceType(B, src, IdTy);
  2299. dst = EnforceType(B, dst, PtrToIdTy);
  2300. B.CreateCall2(WeakAssignFn, src, dst);
  2301. }
  2302. void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
  2303. llvm::Value *src, llvm::Value *dst,
  2304. bool threadlocal) {
  2305. CGBuilderTy B = CGF.Builder;
  2306. src = EnforceType(B, src, IdTy);
  2307. dst = EnforceType(B, dst, PtrToIdTy);
  2308. if (!threadlocal)
  2309. B.CreateCall2(GlobalAssignFn, src, dst);
  2310. else
  2311. // FIXME. Add threadloca assign API
  2312. llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
  2313. }
  2314. void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
  2315. llvm::Value *src, llvm::Value *dst,
  2316. llvm::Value *ivarOffset) {
  2317. CGBuilderTy B = CGF.Builder;
  2318. src = EnforceType(B, src, IdTy);
  2319. dst = EnforceType(B, dst, IdTy);
  2320. B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
  2321. }
  2322. void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
  2323. llvm::Value *src, llvm::Value *dst) {
  2324. CGBuilderTy B = CGF.Builder;
  2325. src = EnforceType(B, src, IdTy);
  2326. dst = EnforceType(B, dst, PtrToIdTy);
  2327. B.CreateCall2(StrongCastAssignFn, src, dst);
  2328. }
  2329. void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
  2330. llvm::Value *DestPtr,
  2331. llvm::Value *SrcPtr,
  2332. llvm::Value *Size) {
  2333. CGBuilderTy B = CGF.Builder;
  2334. DestPtr = EnforceType(B, DestPtr, PtrTy);
  2335. SrcPtr = EnforceType(B, SrcPtr, PtrTy);
  2336. B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
  2337. }
  2338. llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
  2339. const ObjCInterfaceDecl *ID,
  2340. const ObjCIvarDecl *Ivar) {
  2341. const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
  2342. + '.' + Ivar->getNameAsString();
  2343. // Emit the variable and initialize it with what we think the correct value
  2344. // is. This allows code compiled with non-fragile ivars to work correctly
  2345. // when linked against code which isn't (most of the time).
  2346. llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
  2347. if (!IvarOffsetPointer) {
  2348. // This will cause a run-time crash if we accidentally use it. A value of
  2349. // 0 would seem more sensible, but will silently overwrite the isa pointer
  2350. // causing a great deal of confusion.
  2351. uint64_t Offset = -1;
  2352. // We can't call ComputeIvarBaseOffset() here if we have the
  2353. // implementation, because it will create an invalid ASTRecordLayout object
  2354. // that we are then stuck with forever, so we only initialize the ivar
  2355. // offset variable with a guess if we only have the interface. The
  2356. // initializer will be reset later anyway, when we are generating the class
  2357. // description.
  2358. if (!CGM.getContext().getObjCImplementation(
  2359. const_cast<ObjCInterfaceDecl *>(ID)))
  2360. Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
  2361. llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
  2362. /*isSigned*/true);
  2363. // Don't emit the guess in non-PIC code because the linker will not be able
  2364. // to replace it with the real version for a library. In non-PIC code you
  2365. // must compile with the fragile ABI if you want to use ivars from a
  2366. // GCC-compiled class.
  2367. if (CGM.getLangOptions().PICLevel) {
  2368. llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
  2369. Int32Ty, false,
  2370. llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
  2371. IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
  2372. IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
  2373. IvarOffsetGV, Name);
  2374. } else {
  2375. IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
  2376. llvm::Type::getInt32PtrTy(VMContext), false,
  2377. llvm::GlobalValue::ExternalLinkage, 0, Name);
  2378. }
  2379. }
  2380. return IvarOffsetPointer;
  2381. }
  2382. LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
  2383. QualType ObjectTy,
  2384. llvm::Value *BaseValue,
  2385. const ObjCIvarDecl *Ivar,
  2386. unsigned CVRQualifiers) {
  2387. const ObjCInterfaceDecl *ID =
  2388. ObjectTy->getAs<ObjCObjectType>()->getInterface();
  2389. return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
  2390. EmitIvarOffset(CGF, ID, Ivar));
  2391. }
  2392. static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
  2393. const ObjCInterfaceDecl *OID,
  2394. const ObjCIvarDecl *OIVD) {
  2395. for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
  2396. next = next->getNextIvar()) {
  2397. if (OIVD == next)
  2398. return OID;
  2399. }
  2400. // Otherwise check in the super class.
  2401. if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
  2402. return FindIvarInterface(Context, Super, OIVD);
  2403. return 0;
  2404. }
  2405. llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
  2406. const ObjCInterfaceDecl *Interface,
  2407. const ObjCIvarDecl *Ivar) {
  2408. if (CGM.getLangOptions().ObjCNonFragileABI) {
  2409. Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
  2410. if (RuntimeVersion < 10)
  2411. return CGF.Builder.CreateZExtOrBitCast(
  2412. CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
  2413. ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
  2414. PtrDiffTy);
  2415. std::string name = "__objc_ivar_offset_value_" +
  2416. Interface->getNameAsString() +"." + Ivar->getNameAsString();
  2417. llvm::Value *Offset = TheModule.getGlobalVariable(name);
  2418. if (!Offset)
  2419. Offset = new llvm::GlobalVariable(TheModule, IntTy,
  2420. false, llvm::GlobalValue::LinkOnceAnyLinkage,
  2421. llvm::Constant::getNullValue(IntTy), name);
  2422. return CGF.Builder.CreateLoad(Offset);
  2423. }
  2424. uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
  2425. return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
  2426. }
  2427. CGObjCRuntime *
  2428. clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
  2429. if (CGM.getLangOptions().ObjCNonFragileABI)
  2430. return new CGObjCGNUstep(CGM);
  2431. return new CGObjCGCC(CGM);
  2432. }