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