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