CGObjCGNU.cpp 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666
  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(ArrayRef<llvm::Constant *> IvarNames,
  324. ArrayRef<llvm::Constant *> IvarTypes,
  325. ArrayRef<llvm::Constant *> IvarOffsets);
  326. /// Generates a method list structure. This is a structure containing a size
  327. /// and an array of structures containing method metadata.
  328. ///
  329. /// This structure is used by both classes and categories, and contains a next
  330. /// pointer allowing them to be chained together in a linked list.
  331. llvm::Constant *GenerateMethodList(const StringRef &ClassName,
  332. const StringRef &CategoryName,
  333. ArrayRef<Selector> MethodSels,
  334. ArrayRef<llvm::Constant *> MethodTypes,
  335. bool isClassMethodList);
  336. /// Emits an empty protocol. This is used for @protocol() where no protocol
  337. /// is found. The runtime will (hopefully) fix up the pointer to refer to the
  338. /// real protocol.
  339. llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
  340. /// Generates a list of property metadata structures. This follows the same
  341. /// pattern as method and instance variable metadata lists.
  342. llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
  343. SmallVectorImpl<Selector> &InstanceMethodSels,
  344. SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
  345. /// Generates a list of referenced protocols. Classes, categories, and
  346. /// protocols all use this structure.
  347. llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
  348. /// To ensure that all protocols are seen by the runtime, we add a category on
  349. /// a class defined in the runtime, declaring no methods, but adopting the
  350. /// protocols. This is a horribly ugly hack, but it allows us to collect all
  351. /// of the protocols without changing the ABI.
  352. void GenerateProtocolHolderCategory(void);
  353. /// Generates a class structure.
  354. llvm::Constant *GenerateClassStructure(
  355. llvm::Constant *MetaClass,
  356. llvm::Constant *SuperClass,
  357. unsigned info,
  358. const char *Name,
  359. llvm::Constant *Version,
  360. llvm::Constant *InstanceSize,
  361. llvm::Constant *IVars,
  362. llvm::Constant *Methods,
  363. llvm::Constant *Protocols,
  364. llvm::Constant *IvarOffsets,
  365. llvm::Constant *Properties,
  366. llvm::Constant *StrongIvarBitmap,
  367. llvm::Constant *WeakIvarBitmap,
  368. bool isMeta=false);
  369. /// Generates a method list. This is used by protocols to define the required
  370. /// and optional methods.
  371. llvm::Constant *GenerateProtocolMethodList(
  372. ArrayRef<llvm::Constant *> MethodNames,
  373. ArrayRef<llvm::Constant *> MethodTypes);
  374. /// Returns a selector with the specified type encoding. An empty string is
  375. /// used to return an untyped selector (with the types field set to NULL).
  376. llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
  377. const std::string &TypeEncoding, bool lval);
  378. /// Returns the variable used to store the offset of an instance variable.
  379. llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
  380. const ObjCIvarDecl *Ivar);
  381. /// Emits a reference to a class. This allows the linker to object if there
  382. /// is no class of the matching name.
  383. void EmitClassRef(const std::string &className);
  384. /// Emits a pointer to the named class
  385. llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
  386. bool isWeak);
  387. protected:
  388. /// Looks up the method for sending a message to the specified object. This
  389. /// mechanism differs between the GCC and GNU runtimes, so this method must be
  390. /// overridden in subclasses.
  391. virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
  392. llvm::Value *&Receiver,
  393. llvm::Value *cmd,
  394. llvm::MDNode *node) = 0;
  395. /// Looks up the method for sending a message to a superclass. This
  396. /// mechanism differs between the GCC and GNU runtimes, so this method must
  397. /// be overridden in subclasses.
  398. virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
  399. llvm::Value *ObjCSuper,
  400. llvm::Value *cmd) = 0;
  401. /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
  402. /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
  403. /// bits set to their values, LSB first, while larger ones are stored in a
  404. /// structure of this / form:
  405. ///
  406. /// struct { int32_t length; int32_t values[length]; };
  407. ///
  408. /// The values in the array are stored in host-endian format, with the least
  409. /// significant bit being assumed to come first in the bitfield. Therefore,
  410. /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
  411. /// while a bitfield / with the 63rd bit set will be 1<<64.
  412. llvm::Constant *MakeBitField(ArrayRef<bool> bits);
  413. public:
  414. CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
  415. unsigned protocolClassVersion);
  416. virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
  417. virtual RValue
  418. GenerateMessageSend(CodeGenFunction &CGF,
  419. ReturnValueSlot Return,
  420. QualType ResultType,
  421. Selector Sel,
  422. llvm::Value *Receiver,
  423. const CallArgList &CallArgs,
  424. const ObjCInterfaceDecl *Class,
  425. const ObjCMethodDecl *Method);
  426. virtual RValue
  427. GenerateMessageSendSuper(CodeGenFunction &CGF,
  428. ReturnValueSlot Return,
  429. QualType ResultType,
  430. Selector Sel,
  431. const ObjCInterfaceDecl *Class,
  432. bool isCategoryImpl,
  433. llvm::Value *Receiver,
  434. bool IsClassMessage,
  435. const CallArgList &CallArgs,
  436. const ObjCMethodDecl *Method);
  437. virtual llvm::Value *GetClass(CGBuilderTy &Builder,
  438. const ObjCInterfaceDecl *OID);
  439. virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
  440. bool lval = false);
  441. virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
  442. *Method);
  443. virtual llvm::Constant *GetEHType(QualType T);
  444. virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
  445. const ObjCContainerDecl *CD);
  446. virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
  447. virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
  448. virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD);
  449. virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
  450. const ObjCProtocolDecl *PD);
  451. virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
  452. virtual llvm::Function *ModuleInitFunction();
  453. virtual llvm::Constant *GetPropertyGetFunction();
  454. virtual llvm::Constant *GetPropertySetFunction();
  455. virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
  456. bool copy);
  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.getLangOpts().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.getLangOpts();
  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.getLangOpts().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.getLangOpts().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.getLangOpts().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.getLangOpts().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.getLangOpts().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::
  1148. GenerateMethodList(const StringRef &ClassName,
  1149. const StringRef &CategoryName,
  1150. ArrayRef<Selector> MethodSels,
  1151. ArrayRef<llvm::Constant *> MethodTypes,
  1152. bool isClassMethodList) {
  1153. if (MethodSels.empty())
  1154. return NULLPtr;
  1155. // Get the method structure type.
  1156. llvm::StructType *ObjCMethodTy = llvm::StructType::get(
  1157. PtrToInt8Ty, // Really a selector, but the runtime creates it us.
  1158. PtrToInt8Ty, // Method types
  1159. IMPTy, //Method pointer
  1160. NULL);
  1161. std::vector<llvm::Constant*> Methods;
  1162. std::vector<llvm::Constant*> Elements;
  1163. for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
  1164. Elements.clear();
  1165. llvm::Constant *Method =
  1166. TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
  1167. MethodSels[i],
  1168. isClassMethodList));
  1169. assert(Method && "Can't generate metadata for method that doesn't exist");
  1170. llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
  1171. Elements.push_back(C);
  1172. Elements.push_back(MethodTypes[i]);
  1173. Method = llvm::ConstantExpr::getBitCast(Method,
  1174. IMPTy);
  1175. Elements.push_back(Method);
  1176. Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
  1177. }
  1178. // Array of method structures
  1179. llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
  1180. Methods.size());
  1181. llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
  1182. Methods);
  1183. // Structure containing list pointer, array and array count
  1184. llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
  1185. llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
  1186. ObjCMethodListTy->setBody(
  1187. NextPtrTy,
  1188. IntTy,
  1189. ObjCMethodArrayTy,
  1190. NULL);
  1191. Methods.clear();
  1192. Methods.push_back(llvm::ConstantPointerNull::get(
  1193. llvm::PointerType::getUnqual(ObjCMethodListTy)));
  1194. Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
  1195. Methods.push_back(MethodArray);
  1196. // Create an instance of the structure
  1197. return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
  1198. }
  1199. /// Generates an IvarList. Used in construction of a objc_class.
  1200. llvm::Constant *CGObjCGNU::
  1201. GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
  1202. ArrayRef<llvm::Constant *> IvarTypes,
  1203. ArrayRef<llvm::Constant *> IvarOffsets) {
  1204. if (IvarNames.size() == 0)
  1205. return NULLPtr;
  1206. // Get the method structure type.
  1207. llvm::StructType *ObjCIvarTy = llvm::StructType::get(
  1208. PtrToInt8Ty,
  1209. PtrToInt8Ty,
  1210. IntTy,
  1211. NULL);
  1212. std::vector<llvm::Constant*> Ivars;
  1213. std::vector<llvm::Constant*> Elements;
  1214. for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
  1215. Elements.clear();
  1216. Elements.push_back(IvarNames[i]);
  1217. Elements.push_back(IvarTypes[i]);
  1218. Elements.push_back(IvarOffsets[i]);
  1219. Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
  1220. }
  1221. // Array of method structures
  1222. llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
  1223. IvarNames.size());
  1224. Elements.clear();
  1225. Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
  1226. Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
  1227. // Structure containing array and array count
  1228. llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
  1229. ObjCIvarArrayTy,
  1230. NULL);
  1231. // Create an instance of the structure
  1232. return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
  1233. }
  1234. /// Generate a class structure
  1235. llvm::Constant *CGObjCGNU::GenerateClassStructure(
  1236. llvm::Constant *MetaClass,
  1237. llvm::Constant *SuperClass,
  1238. unsigned info,
  1239. const char *Name,
  1240. llvm::Constant *Version,
  1241. llvm::Constant *InstanceSize,
  1242. llvm::Constant *IVars,
  1243. llvm::Constant *Methods,
  1244. llvm::Constant *Protocols,
  1245. llvm::Constant *IvarOffsets,
  1246. llvm::Constant *Properties,
  1247. llvm::Constant *StrongIvarBitmap,
  1248. llvm::Constant *WeakIvarBitmap,
  1249. bool isMeta) {
  1250. // Set up the class structure
  1251. // Note: Several of these are char*s when they should be ids. This is
  1252. // because the runtime performs this translation on load.
  1253. //
  1254. // Fields marked New ABI are part of the GNUstep runtime. We emit them
  1255. // anyway; the classes will still work with the GNU runtime, they will just
  1256. // be ignored.
  1257. llvm::StructType *ClassTy = llvm::StructType::get(
  1258. PtrToInt8Ty, // isa
  1259. PtrToInt8Ty, // super_class
  1260. PtrToInt8Ty, // name
  1261. LongTy, // version
  1262. LongTy, // info
  1263. LongTy, // instance_size
  1264. IVars->getType(), // ivars
  1265. Methods->getType(), // methods
  1266. // These are all filled in by the runtime, so we pretend
  1267. PtrTy, // dtable
  1268. PtrTy, // subclass_list
  1269. PtrTy, // sibling_class
  1270. PtrTy, // protocols
  1271. PtrTy, // gc_object_type
  1272. // New ABI:
  1273. LongTy, // abi_version
  1274. IvarOffsets->getType(), // ivar_offsets
  1275. Properties->getType(), // properties
  1276. IntPtrTy, // strong_pointers
  1277. IntPtrTy, // weak_pointers
  1278. NULL);
  1279. llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
  1280. // Fill in the structure
  1281. std::vector<llvm::Constant*> Elements;
  1282. Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
  1283. Elements.push_back(SuperClass);
  1284. Elements.push_back(MakeConstantString(Name, ".class_name"));
  1285. Elements.push_back(Zero);
  1286. Elements.push_back(llvm::ConstantInt::get(LongTy, info));
  1287. if (isMeta) {
  1288. llvm::TargetData td(&TheModule);
  1289. Elements.push_back(
  1290. llvm::ConstantInt::get(LongTy,
  1291. td.getTypeSizeInBits(ClassTy) /
  1292. CGM.getContext().getCharWidth()));
  1293. } else
  1294. Elements.push_back(InstanceSize);
  1295. Elements.push_back(IVars);
  1296. Elements.push_back(Methods);
  1297. Elements.push_back(NULLPtr);
  1298. Elements.push_back(NULLPtr);
  1299. Elements.push_back(NULLPtr);
  1300. Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
  1301. Elements.push_back(NULLPtr);
  1302. Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
  1303. Elements.push_back(IvarOffsets);
  1304. Elements.push_back(Properties);
  1305. Elements.push_back(StrongIvarBitmap);
  1306. Elements.push_back(WeakIvarBitmap);
  1307. // Create an instance of the structure
  1308. // This is now an externally visible symbol, so that we can speed up class
  1309. // messages in the next ABI. We may already have some weak references to
  1310. // this, so check and fix them properly.
  1311. std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
  1312. std::string(Name));
  1313. llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
  1314. llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
  1315. llvm::GlobalValue::ExternalLinkage);
  1316. if (ClassRef) {
  1317. ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
  1318. ClassRef->getType()));
  1319. ClassRef->removeFromParent();
  1320. Class->setName(ClassSym);
  1321. }
  1322. return Class;
  1323. }
  1324. llvm::Constant *CGObjCGNU::
  1325. GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
  1326. ArrayRef<llvm::Constant *> MethodTypes) {
  1327. // Get the method structure type.
  1328. llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
  1329. PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
  1330. PtrToInt8Ty,
  1331. NULL);
  1332. std::vector<llvm::Constant*> Methods;
  1333. std::vector<llvm::Constant*> Elements;
  1334. for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
  1335. Elements.clear();
  1336. Elements.push_back(MethodNames[i]);
  1337. Elements.push_back(MethodTypes[i]);
  1338. Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
  1339. }
  1340. llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
  1341. MethodNames.size());
  1342. llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
  1343. Methods);
  1344. llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
  1345. IntTy, ObjCMethodArrayTy, NULL);
  1346. Methods.clear();
  1347. Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
  1348. Methods.push_back(Array);
  1349. return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
  1350. }
  1351. // Create the protocol list structure used in classes, categories and so on
  1352. llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<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(ArrayRef<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().getLangOpts().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().getLangOpts().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.getLangOpts().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.getLangOpts().getGC()) {
  2131. case LangOptions::GCOnly:
  2132. Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
  2133. break;
  2134. case LangOptions::NonGC:
  2135. if (CGM.getLangOpts().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::GetOptimizedPropertySetFunction(bool atomic,
  2226. bool copy) {
  2227. return 0;
  2228. }
  2229. llvm::Constant *CGObjCGNU::GetGetStructFunction() {
  2230. return GetStructPropertyFn;
  2231. }
  2232. llvm::Constant *CGObjCGNU::GetSetStructFunction() {
  2233. return SetStructPropertyFn;
  2234. }
  2235. llvm::Constant *CGObjCGNU::GetCppAtomicObjectFunction() {
  2236. return 0;
  2237. }
  2238. llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
  2239. return EnumerationMutationFn;
  2240. }
  2241. void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
  2242. const ObjCAtSynchronizedStmt &S) {
  2243. EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
  2244. }
  2245. void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
  2246. const ObjCAtTryStmt &S) {
  2247. // Unlike the Apple non-fragile runtimes, which also uses
  2248. // unwind-based zero cost exceptions, the GNU Objective C runtime's
  2249. // EH support isn't a veneer over C++ EH. Instead, exception
  2250. // objects are created by __objc_exception_throw and destroyed by
  2251. // the personality function; this avoids the need for bracketing
  2252. // catch handlers with calls to __blah_begin_catch/__blah_end_catch
  2253. // (or even _Unwind_DeleteException), but probably doesn't
  2254. // interoperate very well with foreign exceptions.
  2255. //
  2256. // In Objective-C++ mode, we actually emit something equivalent to the C++
  2257. // exception handler.
  2258. EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
  2259. return ;
  2260. }
  2261. void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
  2262. const ObjCAtThrowStmt &S) {
  2263. llvm::Value *ExceptionAsObject;
  2264. if (const Expr *ThrowExpr = S.getThrowExpr()) {
  2265. llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
  2266. ExceptionAsObject = Exception;
  2267. } else {
  2268. assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
  2269. "Unexpected rethrow outside @catch block.");
  2270. ExceptionAsObject = CGF.ObjCEHValueStack.back();
  2271. }
  2272. ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
  2273. // Note: This may have to be an invoke, if we want to support constructs like:
  2274. // @try {
  2275. // @throw(obj);
  2276. // }
  2277. // @catch(id) ...
  2278. //
  2279. // This is effectively turning @throw into an incredibly-expensive goto, but
  2280. // it may happen as a result of inlining followed by missed optimizations, or
  2281. // as a result of stupidity.
  2282. llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
  2283. if (!UnwindBB) {
  2284. CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
  2285. CGF.Builder.CreateUnreachable();
  2286. } else {
  2287. CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB,
  2288. ExceptionAsObject);
  2289. }
  2290. // Clear the insertion point to indicate we are in unreachable code.
  2291. CGF.Builder.ClearInsertionPoint();
  2292. }
  2293. llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
  2294. llvm::Value *AddrWeakObj) {
  2295. CGBuilderTy B = CGF.Builder;
  2296. AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
  2297. return B.CreateCall(WeakReadFn, AddrWeakObj);
  2298. }
  2299. void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
  2300. llvm::Value *src, llvm::Value *dst) {
  2301. CGBuilderTy B = CGF.Builder;
  2302. src = EnforceType(B, src, IdTy);
  2303. dst = EnforceType(B, dst, PtrToIdTy);
  2304. B.CreateCall2(WeakAssignFn, src, dst);
  2305. }
  2306. void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
  2307. llvm::Value *src, llvm::Value *dst,
  2308. bool threadlocal) {
  2309. CGBuilderTy B = CGF.Builder;
  2310. src = EnforceType(B, src, IdTy);
  2311. dst = EnforceType(B, dst, PtrToIdTy);
  2312. if (!threadlocal)
  2313. B.CreateCall2(GlobalAssignFn, src, dst);
  2314. else
  2315. // FIXME. Add threadloca assign API
  2316. llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
  2317. }
  2318. void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
  2319. llvm::Value *src, llvm::Value *dst,
  2320. llvm::Value *ivarOffset) {
  2321. CGBuilderTy B = CGF.Builder;
  2322. src = EnforceType(B, src, IdTy);
  2323. dst = EnforceType(B, dst, IdTy);
  2324. B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
  2325. }
  2326. void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
  2327. llvm::Value *src, llvm::Value *dst) {
  2328. CGBuilderTy B = CGF.Builder;
  2329. src = EnforceType(B, src, IdTy);
  2330. dst = EnforceType(B, dst, PtrToIdTy);
  2331. B.CreateCall2(StrongCastAssignFn, src, dst);
  2332. }
  2333. void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
  2334. llvm::Value *DestPtr,
  2335. llvm::Value *SrcPtr,
  2336. llvm::Value *Size) {
  2337. CGBuilderTy B = CGF.Builder;
  2338. DestPtr = EnforceType(B, DestPtr, PtrTy);
  2339. SrcPtr = EnforceType(B, SrcPtr, PtrTy);
  2340. B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
  2341. }
  2342. llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
  2343. const ObjCInterfaceDecl *ID,
  2344. const ObjCIvarDecl *Ivar) {
  2345. const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
  2346. + '.' + Ivar->getNameAsString();
  2347. // Emit the variable and initialize it with what we think the correct value
  2348. // is. This allows code compiled with non-fragile ivars to work correctly
  2349. // when linked against code which isn't (most of the time).
  2350. llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
  2351. if (!IvarOffsetPointer) {
  2352. // This will cause a run-time crash if we accidentally use it. A value of
  2353. // 0 would seem more sensible, but will silently overwrite the isa pointer
  2354. // causing a great deal of confusion.
  2355. uint64_t Offset = -1;
  2356. // We can't call ComputeIvarBaseOffset() here if we have the
  2357. // implementation, because it will create an invalid ASTRecordLayout object
  2358. // that we are then stuck with forever, so we only initialize the ivar
  2359. // offset variable with a guess if we only have the interface. The
  2360. // initializer will be reset later anyway, when we are generating the class
  2361. // description.
  2362. if (!CGM.getContext().getObjCImplementation(
  2363. const_cast<ObjCInterfaceDecl *>(ID)))
  2364. Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
  2365. llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
  2366. /*isSigned*/true);
  2367. // Don't emit the guess in non-PIC code because the linker will not be able
  2368. // to replace it with the real version for a library. In non-PIC code you
  2369. // must compile with the fragile ABI if you want to use ivars from a
  2370. // GCC-compiled class.
  2371. if (CGM.getLangOpts().PICLevel) {
  2372. llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
  2373. Int32Ty, false,
  2374. llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
  2375. IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
  2376. IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
  2377. IvarOffsetGV, Name);
  2378. } else {
  2379. IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
  2380. llvm::Type::getInt32PtrTy(VMContext), false,
  2381. llvm::GlobalValue::ExternalLinkage, 0, Name);
  2382. }
  2383. }
  2384. return IvarOffsetPointer;
  2385. }
  2386. LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
  2387. QualType ObjectTy,
  2388. llvm::Value *BaseValue,
  2389. const ObjCIvarDecl *Ivar,
  2390. unsigned CVRQualifiers) {
  2391. const ObjCInterfaceDecl *ID =
  2392. ObjectTy->getAs<ObjCObjectType>()->getInterface();
  2393. return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
  2394. EmitIvarOffset(CGF, ID, Ivar));
  2395. }
  2396. static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
  2397. const ObjCInterfaceDecl *OID,
  2398. const ObjCIvarDecl *OIVD) {
  2399. for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
  2400. next = next->getNextIvar()) {
  2401. if (OIVD == next)
  2402. return OID;
  2403. }
  2404. // Otherwise check in the super class.
  2405. if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
  2406. return FindIvarInterface(Context, Super, OIVD);
  2407. return 0;
  2408. }
  2409. llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
  2410. const ObjCInterfaceDecl *Interface,
  2411. const ObjCIvarDecl *Ivar) {
  2412. if (CGM.getLangOpts().ObjCNonFragileABI) {
  2413. Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
  2414. if (RuntimeVersion < 10)
  2415. return CGF.Builder.CreateZExtOrBitCast(
  2416. CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
  2417. ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
  2418. PtrDiffTy);
  2419. std::string name = "__objc_ivar_offset_value_" +
  2420. Interface->getNameAsString() +"." + Ivar->getNameAsString();
  2421. llvm::Value *Offset = TheModule.getGlobalVariable(name);
  2422. if (!Offset)
  2423. Offset = new llvm::GlobalVariable(TheModule, IntTy,
  2424. false, llvm::GlobalValue::LinkOnceAnyLinkage,
  2425. llvm::Constant::getNullValue(IntTy), name);
  2426. return CGF.Builder.CreateLoad(Offset);
  2427. }
  2428. uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
  2429. return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
  2430. }
  2431. CGObjCRuntime *
  2432. clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
  2433. if (CGM.getLangOpts().ObjCNonFragileABI)
  2434. return new CGObjCGNUstep(CGM);
  2435. return new CGObjCGCC(CGM);
  2436. }