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