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