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