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 "CGCXXABI.h" 22 #include "clang/CodeGen/ConstantInitBuilder.h" 23 #include "clang/AST/ASTContext.h" 24 #include "clang/AST/Decl.h" 25 #include "clang/AST/DeclObjC.h" 26 #include "clang/AST/RecordLayout.h" 27 #include "clang/AST/StmtObjC.h" 28 #include "clang/Basic/FileManager.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "llvm/ADT/SmallVector.h" 31 #include "llvm/ADT/StringMap.h" 32 #include "llvm/IR/CallSite.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/IR/LLVMContext.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/Support/Compiler.h" 38 #include "llvm/Support/ConvertUTF.h" 39 #include <cctype> 40 41 using namespace clang; 42 using namespace CodeGen; 43 44 namespace { 45 46 std::string SymbolNameForMethod( StringRef ClassName, 47 StringRef CategoryName, const Selector MethodName, 48 bool isClassMethod) { 49 std::string MethodNameColonStripped = MethodName.getAsString(); 50 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(), 51 ':', '_'); 52 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" + 53 CategoryName + "_" + MethodNameColonStripped).str(); 54 } 55 56 /// Class that lazily initialises the runtime function. Avoids inserting the 57 /// types and the function declaration into a module if they're not used, and 58 /// avoids constructing the type more than once if it's used more than once. 59 class LazyRuntimeFunction { 60 CodeGenModule *CGM; 61 llvm::FunctionType *FTy; 62 const char *FunctionName; 63 llvm::Constant *Function; 64 65 public: 66 /// Constructor leaves this class uninitialized, because it is intended to 67 /// be used as a field in another class and not all of the types that are 68 /// used as arguments will necessarily be available at construction time. 69 LazyRuntimeFunction() 70 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {} 71 72 /// Initialises the lazy function with the name, return type, and the types 73 /// of the arguments. 74 template <typename... Tys> 75 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, 76 Tys *... Types) { 77 CGM = Mod; 78 FunctionName = name; 79 Function = nullptr; 80 if(sizeof...(Tys)) { 81 SmallVector<llvm::Type *, 8> ArgTys({Types...}); 82 FTy = llvm::FunctionType::get(RetTy, ArgTys, false); 83 } 84 else { 85 FTy = llvm::FunctionType::get(RetTy, None, false); 86 } 87 } 88 89 llvm::FunctionType *getType() { return FTy; } 90 91 /// Overloaded cast operator, allows the class to be implicitly cast to an 92 /// LLVM constant. 93 operator llvm::Constant *() { 94 if (!Function) { 95 if (!FunctionName) 96 return nullptr; 97 Function = CGM->CreateRuntimeFunction(FTy, FunctionName); 98 } 99 return Function; 100 } 101 operator llvm::Function *() { 102 return cast<llvm::Function>((llvm::Constant *)*this); 103 } 104 }; 105 106 107 /// GNU Objective-C runtime code generation. This class implements the parts of 108 /// Objective-C support that are specific to the GNU family of runtimes (GCC, 109 /// GNUstep and ObjFW). 110 class CGObjCGNU : public CGObjCRuntime { 111 protected: 112 /// The LLVM module into which output is inserted 113 llvm::Module &TheModule; 114 /// strut objc_super. Used for sending messages to super. This structure 115 /// contains the receiver (object) and the expected class. 116 llvm::StructType *ObjCSuperTy; 117 /// struct objc_super*. The type of the argument to the superclass message 118 /// lookup functions. 119 llvm::PointerType *PtrToObjCSuperTy; 120 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring 121 /// SEL is included in a header somewhere, in which case it will be whatever 122 /// type is declared in that header, most likely {i8*, i8*}. 123 llvm::PointerType *SelectorTy; 124 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the 125 /// places where it's used 126 llvm::IntegerType *Int8Ty; 127 /// Pointer to i8 - LLVM type of char*, for all of the places where the 128 /// runtime needs to deal with C strings. 129 llvm::PointerType *PtrToInt8Ty; 130 /// struct objc_protocol type 131 llvm::StructType *ProtocolTy; 132 /// Protocol * type. 133 llvm::PointerType *ProtocolPtrTy; 134 /// Instance Method Pointer type. This is a pointer to a function that takes, 135 /// at a minimum, an object and a selector, and is the generic type for 136 /// Objective-C methods. Due to differences between variadic / non-variadic 137 /// calling conventions, it must always be cast to the correct type before 138 /// actually being used. 139 llvm::PointerType *IMPTy; 140 /// Type of an untyped Objective-C object. Clang treats id as a built-in type 141 /// when compiling Objective-C code, so this may be an opaque pointer (i8*), 142 /// but if the runtime header declaring it is included then it may be a 143 /// pointer to a structure. 144 llvm::PointerType *IdTy; 145 /// Pointer to a pointer to an Objective-C object. Used in the new ABI 146 /// message lookup function and some GC-related functions. 147 llvm::PointerType *PtrToIdTy; 148 /// The clang type of id. Used when using the clang CGCall infrastructure to 149 /// call Objective-C methods. 150 CanQualType ASTIdTy; 151 /// LLVM type for C int type. 152 llvm::IntegerType *IntTy; 153 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is 154 /// used in the code to document the difference between i8* meaning a pointer 155 /// to a C string and i8* meaning a pointer to some opaque type. 156 llvm::PointerType *PtrTy; 157 /// LLVM type for C long type. The runtime uses this in a lot of places where 158 /// it should be using intptr_t, but we can't fix this without breaking 159 /// compatibility with GCC... 160 llvm::IntegerType *LongTy; 161 /// LLVM type for C size_t. Used in various runtime data structures. 162 llvm::IntegerType *SizeTy; 163 /// LLVM type for C intptr_t. 164 llvm::IntegerType *IntPtrTy; 165 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions. 166 llvm::IntegerType *PtrDiffTy; 167 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance 168 /// variables. 169 llvm::PointerType *PtrToIntTy; 170 /// LLVM type for Objective-C BOOL type. 171 llvm::Type *BoolTy; 172 /// 32-bit integer type, to save us needing to look it up every time it's used. 173 llvm::IntegerType *Int32Ty; 174 /// 64-bit integer type, to save us needing to look it up every time it's used. 175 llvm::IntegerType *Int64Ty; 176 /// The type of struct objc_property. 177 llvm::StructType *PropertyMetadataTy; 178 /// Metadata kind used to tie method lookups to message sends. The GNUstep 179 /// runtime provides some LLVM passes that can use this to do things like 180 /// automatic IMP caching and speculative inlining. 181 unsigned msgSendMDKind; 182 /// Does the current target use SEH-based exceptions? False implies 183 /// Itanium-style DWARF unwinding. 184 bool usesSEHExceptions; 185 186 /// Helper to check if we are targeting a specific runtime version or later. 187 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) { 188 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime; 189 return (R.getKind() == kind) && 190 (R.getVersion() >= VersionTuple(major, minor)); 191 } 192 193 std::string SymbolForProtocol(StringRef Name) { 194 return (StringRef("._OBJC_PROTOCOL_") + Name).str(); 195 } 196 197 std::string SymbolForProtocolRef(StringRef Name) { 198 return (StringRef("._OBJC_REF_PROTOCOL_") + Name).str(); 199 } 200 201 202 /// Helper function that generates a constant string and returns a pointer to 203 /// the start of the string. The result of this function can be used anywhere 204 /// where the C code specifies const char*. 205 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") { 206 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name); 207 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(), 208 Array.getPointer(), Zeros); 209 } 210 211 /// Emits a linkonce_odr string, whose name is the prefix followed by the 212 /// string value. This allows the linker to combine the strings between 213 /// different modules. Used for EH typeinfo names, selector strings, and a 214 /// few other things. 215 llvm::Constant *ExportUniqueString(const std::string &Str, 216 const std::string &prefix, 217 bool Private=false) { 218 std::string name = prefix + Str; 219 auto *ConstStr = TheModule.getGlobalVariable(name); 220 if (!ConstStr) { 221 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str); 222 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true, 223 llvm::GlobalValue::LinkOnceODRLinkage, value, name); 224 GV->setComdat(TheModule.getOrInsertComdat(name)); 225 if (Private) 226 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 227 ConstStr = GV; 228 } 229 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(), 230 ConstStr, Zeros); 231 } 232 233 /// Returns a property name and encoding string. 234 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD, 235 const Decl *Container) { 236 assert(!isRuntime(ObjCRuntime::GNUstep, 2)); 237 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) { 238 std::string NameAndAttributes; 239 std::string TypeStr = 240 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container); 241 NameAndAttributes += '\0'; 242 NameAndAttributes += TypeStr.length() + 3; 243 NameAndAttributes += TypeStr; 244 NameAndAttributes += '\0'; 245 NameAndAttributes += PD->getNameAsString(); 246 return MakeConstantString(NameAndAttributes); 247 } 248 return MakeConstantString(PD->getNameAsString()); 249 } 250 251 /// Push the property attributes into two structure fields. 252 void PushPropertyAttributes(ConstantStructBuilder &Fields, 253 const ObjCPropertyDecl *property, bool isSynthesized=true, bool 254 isDynamic=true) { 255 int attrs = property->getPropertyAttributes(); 256 // For read-only properties, clear the copy and retain flags 257 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) { 258 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy; 259 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain; 260 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak; 261 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong; 262 } 263 // The first flags field has the same attribute values as clang uses internally 264 Fields.addInt(Int8Ty, attrs & 0xff); 265 attrs >>= 8; 266 attrs <<= 2; 267 // For protocol properties, synthesized and dynamic have no meaning, so we 268 // reuse these flags to indicate that this is a protocol property (both set 269 // has no meaning, as a property can't be both synthesized and dynamic) 270 attrs |= isSynthesized ? (1<<0) : 0; 271 attrs |= isDynamic ? (1<<1) : 0; 272 // The second field is the next four fields left shifted by two, with the 273 // low bit set to indicate whether the field is synthesized or dynamic. 274 Fields.addInt(Int8Ty, attrs & 0xff); 275 // Two padding fields 276 Fields.addInt(Int8Ty, 0); 277 Fields.addInt(Int8Ty, 0); 278 } 279 280 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields, 281 int count) { 282 // int count; 283 Fields.addInt(IntTy, count); 284 // int size; (only in GNUstep v2 ABI. 285 if (isRuntime(ObjCRuntime::GNUstep, 2)) { 286 llvm::DataLayout td(&TheModule); 287 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) / 288 CGM.getContext().getCharWidth()); 289 } 290 // struct objc_property_list *next; 291 Fields.add(NULLPtr); 292 // struct objc_property properties[] 293 return Fields.beginArray(PropertyMetadataTy); 294 } 295 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray, 296 const ObjCPropertyDecl *property, 297 const Decl *OCD, 298 bool isSynthesized=true, bool 299 isDynamic=true) { 300 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy); 301 ASTContext &Context = CGM.getContext(); 302 Fields.add(MakePropertyEncodingString(property, OCD)); 303 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic); 304 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) { 305 if (accessor) { 306 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor); 307 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr); 308 Fields.add(MakeConstantString(accessor->getSelector().getAsString())); 309 Fields.add(TypeEncoding); 310 } else { 311 Fields.add(NULLPtr); 312 Fields.add(NULLPtr); 313 } 314 }; 315 addPropertyMethod(property->getGetterMethodDecl()); 316 addPropertyMethod(property->getSetterMethodDecl()); 317 Fields.finishAndAddTo(PropertiesArray); 318 } 319 320 /// Ensures that the value has the required type, by inserting a bitcast if 321 /// required. This function lets us avoid inserting bitcasts that are 322 /// redundant. 323 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) { 324 if (V->getType() == Ty) return V; 325 return B.CreateBitCast(V, Ty); 326 } 327 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) { 328 if (V.getType() == Ty) return V; 329 return B.CreateBitCast(V, Ty); 330 } 331 332 // Some zeros used for GEPs in lots of places. 333 llvm::Constant *Zeros[2]; 334 /// Null pointer value. Mainly used as a terminator in various arrays. 335 llvm::Constant *NULLPtr; 336 /// LLVM context. 337 llvm::LLVMContext &VMContext; 338 339 protected: 340 341 /// Placeholder for the class. Lots of things refer to the class before we've 342 /// actually emitted it. We use this alias as a placeholder, and then replace 343 /// it with a pointer to the class structure before finally emitting the 344 /// module. 345 llvm::GlobalAlias *ClassPtrAlias; 346 /// Placeholder for the metaclass. Lots of things refer to the class before 347 /// we've / actually emitted it. We use this alias as a placeholder, and then 348 /// replace / it with a pointer to the metaclass structure before finally 349 /// emitting the / module. 350 llvm::GlobalAlias *MetaClassPtrAlias; 351 /// All of the classes that have been generated for this compilation units. 352 std::vector<llvm::Constant*> Classes; 353 /// All of the categories that have been generated for this compilation units. 354 std::vector<llvm::Constant*> Categories; 355 /// All of the Objective-C constant strings that have been generated for this 356 /// compilation units. 357 std::vector<llvm::Constant*> ConstantStrings; 358 /// Map from string values to Objective-C constant strings in the output. 359 /// Used to prevent emitting Objective-C strings more than once. This should 360 /// not be required at all - CodeGenModule should manage this list. 361 llvm::StringMap<llvm::Constant*> ObjCStrings; 362 /// All of the protocols that have been declared. 363 llvm::StringMap<llvm::Constant*> ExistingProtocols; 364 /// For each variant of a selector, we store the type encoding and a 365 /// placeholder value. For an untyped selector, the type will be the empty 366 /// string. Selector references are all done via the module's selector table, 367 /// so we create an alias as a placeholder and then replace it with the real 368 /// value later. 369 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector; 370 /// Type of the selector map. This is roughly equivalent to the structure 371 /// used in the GNUstep runtime, which maintains a list of all of the valid 372 /// types for a selector in a table. 373 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> > 374 SelectorMap; 375 /// A map from selectors to selector types. This allows us to emit all 376 /// selectors of the same name and type together. 377 SelectorMap SelectorTable; 378 379 /// Selectors related to memory management. When compiling in GC mode, we 380 /// omit these. 381 Selector RetainSel, ReleaseSel, AutoreleaseSel; 382 /// Runtime functions used for memory management in GC mode. Note that clang 383 /// supports code generation for calling these functions, but neither GNU 384 /// runtime actually supports this API properly yet. 385 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn, 386 WeakAssignFn, GlobalAssignFn; 387 388 typedef std::pair<std::string, std::string> ClassAliasPair; 389 /// All classes that have aliases set for them. 390 std::vector<ClassAliasPair> ClassAliases; 391 392 protected: 393 /// Function used for throwing Objective-C exceptions. 394 LazyRuntimeFunction ExceptionThrowFn; 395 /// Function used for rethrowing exceptions, used at the end of \@finally or 396 /// \@synchronize blocks. 397 LazyRuntimeFunction ExceptionReThrowFn; 398 /// Function called when entering a catch function. This is required for 399 /// differentiating Objective-C exceptions and foreign exceptions. 400 LazyRuntimeFunction EnterCatchFn; 401 /// Function called when exiting from a catch block. Used to do exception 402 /// cleanup. 403 LazyRuntimeFunction ExitCatchFn; 404 /// Function called when entering an \@synchronize block. Acquires the lock. 405 LazyRuntimeFunction SyncEnterFn; 406 /// Function called when exiting an \@synchronize block. Releases the lock. 407 LazyRuntimeFunction SyncExitFn; 408 409 private: 410 /// Function called if fast enumeration detects that the collection is 411 /// modified during the update. 412 LazyRuntimeFunction EnumerationMutationFn; 413 /// Function for implementing synthesized property getters that return an 414 /// object. 415 LazyRuntimeFunction GetPropertyFn; 416 /// Function for implementing synthesized property setters that return an 417 /// object. 418 LazyRuntimeFunction SetPropertyFn; 419 /// Function used for non-object declared property getters. 420 LazyRuntimeFunction GetStructPropertyFn; 421 /// Function used for non-object declared property setters. 422 LazyRuntimeFunction SetStructPropertyFn; 423 424 protected: 425 /// The version of the runtime that this class targets. Must match the 426 /// version in the runtime. 427 int RuntimeVersion; 428 /// The version of the protocol class. Used to differentiate between ObjC1 429 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional 430 /// components and can not contain declared properties. We always emit 431 /// Objective-C 2 property structures, but we have to pretend that they're 432 /// Objective-C 1 property structures when targeting the GCC runtime or it 433 /// will abort. 434 const int ProtocolVersion; 435 /// The version of the class ABI. This value is used in the class structure 436 /// and indicates how various fields should be interpreted. 437 const int ClassABIVersion; 438 /// Generates an instance variable list structure. This is a structure 439 /// containing a size and an array of structures containing instance variable 440 /// metadata. This is used purely for introspection in the fragile ABI. In 441 /// the non-fragile ABI, it's used for instance variable fixup. 442 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames, 443 ArrayRef<llvm::Constant *> IvarTypes, 444 ArrayRef<llvm::Constant *> IvarOffsets, 445 ArrayRef<llvm::Constant *> IvarAlign, 446 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership); 447 448 /// Generates a method list structure. This is a structure containing a size 449 /// and an array of structures containing method metadata. 450 /// 451 /// This structure is used by both classes and categories, and contains a next 452 /// pointer allowing them to be chained together in a linked list. 453 llvm::Constant *GenerateMethodList(StringRef ClassName, 454 StringRef CategoryName, 455 ArrayRef<const ObjCMethodDecl*> Methods, 456 bool isClassMethodList); 457 458 /// Emits an empty protocol. This is used for \@protocol() where no protocol 459 /// is found. The runtime will (hopefully) fix up the pointer to refer to the 460 /// real protocol. 461 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName); 462 463 /// Generates a list of property metadata structures. This follows the same 464 /// pattern as method and instance variable metadata lists. 465 llvm::Constant *GeneratePropertyList(const Decl *Container, 466 const ObjCContainerDecl *OCD, 467 bool isClassProperty=false, 468 bool protocolOptionalProperties=false); 469 470 /// Generates a list of referenced protocols. Classes, categories, and 471 /// protocols all use this structure. 472 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols); 473 474 /// To ensure that all protocols are seen by the runtime, we add a category on 475 /// a class defined in the runtime, declaring no methods, but adopting the 476 /// protocols. This is a horribly ugly hack, but it allows us to collect all 477 /// of the protocols without changing the ABI. 478 void GenerateProtocolHolderCategory(); 479 480 /// Generates a class structure. 481 llvm::Constant *GenerateClassStructure( 482 llvm::Constant *MetaClass, 483 llvm::Constant *SuperClass, 484 unsigned info, 485 const char *Name, 486 llvm::Constant *Version, 487 llvm::Constant *InstanceSize, 488 llvm::Constant *IVars, 489 llvm::Constant *Methods, 490 llvm::Constant *Protocols, 491 llvm::Constant *IvarOffsets, 492 llvm::Constant *Properties, 493 llvm::Constant *StrongIvarBitmap, 494 llvm::Constant *WeakIvarBitmap, 495 bool isMeta=false); 496 497 /// Generates a method list. This is used by protocols to define the required 498 /// and optional methods. 499 virtual llvm::Constant *GenerateProtocolMethodList( 500 ArrayRef<const ObjCMethodDecl*> Methods); 501 /// Emits optional and required method lists. 502 template<class T> 503 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required, 504 llvm::Constant *&Optional) { 505 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods; 506 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods; 507 for (const auto *I : Methods) 508 if (I->isOptional()) 509 OptionalMethods.push_back(I); 510 else 511 RequiredMethods.push_back(I); 512 Required = GenerateProtocolMethodList(RequiredMethods); 513 Optional = GenerateProtocolMethodList(OptionalMethods); 514 } 515 516 /// Returns a selector with the specified type encoding. An empty string is 517 /// used to return an untyped selector (with the types field set to NULL). 518 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel, 519 const std::string &TypeEncoding); 520 521 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this 522 /// contains the class and ivar names, in the v2 ABI this contains the type 523 /// encoding as well. 524 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID, 525 const ObjCIvarDecl *Ivar) { 526 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString() 527 + '.' + Ivar->getNameAsString(); 528 return Name; 529 } 530 /// Returns the variable used to store the offset of an instance variable. 531 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID, 532 const ObjCIvarDecl *Ivar); 533 /// Emits a reference to a class. This allows the linker to object if there 534 /// is no class of the matching name. 535 void EmitClassRef(const std::string &className); 536 537 /// Emits a pointer to the named class 538 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF, 539 const std::string &Name, bool isWeak); 540 541 /// Looks up the method for sending a message to the specified object. This 542 /// mechanism differs between the GCC and GNU runtimes, so this method must be 543 /// overridden in subclasses. 544 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF, 545 llvm::Value *&Receiver, 546 llvm::Value *cmd, 547 llvm::MDNode *node, 548 MessageSendInfo &MSI) = 0; 549 550 /// Looks up the method for sending a message to a superclass. This 551 /// mechanism differs between the GCC and GNU runtimes, so this method must 552 /// be overridden in subclasses. 553 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, 554 Address ObjCSuper, 555 llvm::Value *cmd, 556 MessageSendInfo &MSI) = 0; 557 558 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are 559 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63 560 /// bits set to their values, LSB first, while larger ones are stored in a 561 /// structure of this / form: 562 /// 563 /// struct { int32_t length; int32_t values[length]; }; 564 /// 565 /// The values in the array are stored in host-endian format, with the least 566 /// significant bit being assumed to come first in the bitfield. Therefore, 567 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, 568 /// while a bitfield / with the 63rd bit set will be 1<<64. 569 llvm::Constant *MakeBitField(ArrayRef<bool> bits); 570 571 public: 572 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion, 573 unsigned protocolClassVersion, unsigned classABI=1); 574 575 ConstantAddress GenerateConstantString(const StringLiteral *) override; 576 577 RValue 578 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return, 579 QualType ResultType, Selector Sel, 580 llvm::Value *Receiver, const CallArgList &CallArgs, 581 const ObjCInterfaceDecl *Class, 582 const ObjCMethodDecl *Method) override; 583 RValue 584 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return, 585 QualType ResultType, Selector Sel, 586 const ObjCInterfaceDecl *Class, 587 bool isCategoryImpl, llvm::Value *Receiver, 588 bool IsClassMessage, const CallArgList &CallArgs, 589 const ObjCMethodDecl *Method) override; 590 llvm::Value *GetClass(CodeGenFunction &CGF, 591 const ObjCInterfaceDecl *OID) override; 592 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override; 593 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override; 594 llvm::Value *GetSelector(CodeGenFunction &CGF, 595 const ObjCMethodDecl *Method) override; 596 virtual llvm::Constant *GetConstantSelector(Selector Sel, 597 const std::string &TypeEncoding) { 598 llvm_unreachable("Runtime unable to generate constant selector"); 599 } 600 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) { 601 return GetConstantSelector(M->getSelector(), 602 CGM.getContext().getObjCEncodingForMethodDecl(M)); 603 } 604 llvm::Constant *GetEHType(QualType T) override; 605 606 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 607 const ObjCContainerDecl *CD) override; 608 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override; 609 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override; 610 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override; 611 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF, 612 const ObjCProtocolDecl *PD) override; 613 void GenerateProtocol(const ObjCProtocolDecl *PD) override; 614 llvm::Function *ModuleInitFunction() override; 615 llvm::Constant *GetPropertyGetFunction() override; 616 llvm::Constant *GetPropertySetFunction() override; 617 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic, 618 bool copy) override; 619 llvm::Constant *GetSetStructFunction() override; 620 llvm::Constant *GetGetStructFunction() override; 621 llvm::Constant *GetCppAtomicObjectGetFunction() override; 622 llvm::Constant *GetCppAtomicObjectSetFunction() override; 623 llvm::Constant *EnumerationMutationFunction() override; 624 625 void EmitTryStmt(CodeGenFunction &CGF, 626 const ObjCAtTryStmt &S) override; 627 void EmitSynchronizedStmt(CodeGenFunction &CGF, 628 const ObjCAtSynchronizedStmt &S) override; 629 void EmitThrowStmt(CodeGenFunction &CGF, 630 const ObjCAtThrowStmt &S, 631 bool ClearInsertionPoint=true) override; 632 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF, 633 Address AddrWeakObj) override; 634 void EmitObjCWeakAssign(CodeGenFunction &CGF, 635 llvm::Value *src, Address dst) override; 636 void EmitObjCGlobalAssign(CodeGenFunction &CGF, 637 llvm::Value *src, Address dest, 638 bool threadlocal=false) override; 639 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src, 640 Address dest, llvm::Value *ivarOffset) override; 641 void EmitObjCStrongCastAssign(CodeGenFunction &CGF, 642 llvm::Value *src, Address dest) override; 643 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr, 644 Address SrcPtr, 645 llvm::Value *Size) override; 646 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy, 647 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, 648 unsigned CVRQualifiers) override; 649 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF, 650 const ObjCInterfaceDecl *Interface, 651 const ObjCIvarDecl *Ivar) override; 652 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override; 653 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM, 654 const CGBlockInfo &blockInfo) override { 655 return NULLPtr; 656 } 657 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM, 658 const CGBlockInfo &blockInfo) override { 659 return NULLPtr; 660 } 661 662 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override { 663 return NULLPtr; 664 } 665 }; 666 667 /// Class representing the legacy GCC Objective-C ABI. This is the default when 668 /// -fobjc-nonfragile-abi is not specified. 669 /// 670 /// The GCC ABI target actually generates code that is approximately compatible 671 /// with the new GNUstep runtime ABI, but refrains from using any features that 672 /// would not work with the GCC runtime. For example, clang always generates 673 /// the extended form of the class structure, and the extra fields are simply 674 /// ignored by GCC libobjc. 675 class CGObjCGCC : public CGObjCGNU { 676 /// The GCC ABI message lookup function. Returns an IMP pointing to the 677 /// method implementation for this message. 678 LazyRuntimeFunction MsgLookupFn; 679 /// The GCC ABI superclass message lookup function. Takes a pointer to a 680 /// structure describing the receiver and the class, and a selector as 681 /// arguments. Returns the IMP for the corresponding method. 682 LazyRuntimeFunction MsgLookupSuperFn; 683 684 protected: 685 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver, 686 llvm::Value *cmd, llvm::MDNode *node, 687 MessageSendInfo &MSI) override { 688 CGBuilderTy &Builder = CGF.Builder; 689 llvm::Value *args[] = { 690 EnforceType(Builder, Receiver, IdTy), 691 EnforceType(Builder, cmd, SelectorTy) }; 692 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args); 693 imp->setMetadata(msgSendMDKind, node); 694 return imp.getInstruction(); 695 } 696 697 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 698 llvm::Value *cmd, MessageSendInfo &MSI) override { 699 CGBuilderTy &Builder = CGF.Builder; 700 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper, 701 PtrToObjCSuperTy).getPointer(), cmd}; 702 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs); 703 } 704 705 public: 706 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) { 707 // IMP objc_msg_lookup(id, SEL); 708 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy); 709 // IMP objc_msg_lookup_super(struct objc_super*, SEL); 710 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy, 711 PtrToObjCSuperTy, SelectorTy); 712 } 713 }; 714 715 /// Class used when targeting the new GNUstep runtime ABI. 716 class CGObjCGNUstep : public CGObjCGNU { 717 /// The slot lookup function. Returns a pointer to a cacheable structure 718 /// that contains (among other things) the IMP. 719 LazyRuntimeFunction SlotLookupFn; 720 /// The GNUstep ABI superclass message lookup function. Takes a pointer to 721 /// a structure describing the receiver and the class, and a selector as 722 /// arguments. Returns the slot for the corresponding method. Superclass 723 /// message lookup rarely changes, so this is a good caching opportunity. 724 LazyRuntimeFunction SlotLookupSuperFn; 725 /// Specialised function for setting atomic retain properties 726 LazyRuntimeFunction SetPropertyAtomic; 727 /// Specialised function for setting atomic copy properties 728 LazyRuntimeFunction SetPropertyAtomicCopy; 729 /// Specialised function for setting nonatomic retain properties 730 LazyRuntimeFunction SetPropertyNonAtomic; 731 /// Specialised function for setting nonatomic copy properties 732 LazyRuntimeFunction SetPropertyNonAtomicCopy; 733 /// Function to perform atomic copies of C++ objects with nontrivial copy 734 /// constructors from Objective-C ivars. 735 LazyRuntimeFunction CxxAtomicObjectGetFn; 736 /// Function to perform atomic copies of C++ objects with nontrivial copy 737 /// constructors to Objective-C ivars. 738 LazyRuntimeFunction CxxAtomicObjectSetFn; 739 /// Type of an slot structure pointer. This is returned by the various 740 /// lookup functions. 741 llvm::Type *SlotTy; 742 743 public: 744 llvm::Constant *GetEHType(QualType T) override; 745 746 protected: 747 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver, 748 llvm::Value *cmd, llvm::MDNode *node, 749 MessageSendInfo &MSI) override { 750 CGBuilderTy &Builder = CGF.Builder; 751 llvm::Function *LookupFn = SlotLookupFn; 752 753 // Store the receiver on the stack so that we can reload it later 754 Address ReceiverPtr = 755 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign()); 756 Builder.CreateStore(Receiver, ReceiverPtr); 757 758 llvm::Value *self; 759 760 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) { 761 self = CGF.LoadObjCSelf(); 762 } else { 763 self = llvm::ConstantPointerNull::get(IdTy); 764 } 765 766 // The lookup function is guaranteed not to capture the receiver pointer. 767 LookupFn->addParamAttr(0, llvm::Attribute::NoCapture); 768 769 llvm::Value *args[] = { 770 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy), 771 EnforceType(Builder, cmd, SelectorTy), 772 EnforceType(Builder, self, IdTy) }; 773 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args); 774 slot.setOnlyReadsMemory(); 775 slot->setMetadata(msgSendMDKind, node); 776 777 // Load the imp from the slot 778 llvm::Value *imp = Builder.CreateAlignedLoad( 779 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4), 780 CGF.getPointerAlign()); 781 782 // The lookup function may have changed the receiver, so make sure we use 783 // the new one. 784 Receiver = Builder.CreateLoad(ReceiverPtr, true); 785 return imp; 786 } 787 788 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 789 llvm::Value *cmd, 790 MessageSendInfo &MSI) override { 791 CGBuilderTy &Builder = CGF.Builder; 792 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd}; 793 794 llvm::CallInst *slot = 795 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs); 796 slot->setOnlyReadsMemory(); 797 798 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4), 799 CGF.getPointerAlign()); 800 } 801 802 public: 803 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {} 804 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI, 805 unsigned ClassABI) : 806 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) { 807 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime; 808 809 llvm::StructType *SlotStructTy = 810 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy); 811 SlotTy = llvm::PointerType::getUnqual(SlotStructTy); 812 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender); 813 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy, 814 SelectorTy, IdTy); 815 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL); 816 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy, 817 PtrToObjCSuperTy, SelectorTy); 818 // If we're in ObjC++ mode, then we want to make 819 if (usesSEHExceptions) { 820 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 821 // void objc_exception_rethrow(void) 822 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy); 823 } else if (CGM.getLangOpts().CPlusPlus) { 824 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 825 // void *__cxa_begin_catch(void *e) 826 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy); 827 // void __cxa_end_catch(void) 828 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy); 829 // void _Unwind_Resume_or_Rethrow(void*) 830 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, 831 PtrTy); 832 } else if (R.getVersion() >= VersionTuple(1, 7)) { 833 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 834 // id objc_begin_catch(void *e) 835 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy); 836 // void objc_end_catch(void) 837 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy); 838 // void _Unwind_Resume_or_Rethrow(void*) 839 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy); 840 } 841 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 842 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy, 843 SelectorTy, IdTy, PtrDiffTy); 844 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy, 845 IdTy, SelectorTy, IdTy, PtrDiffTy); 846 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy, 847 IdTy, SelectorTy, IdTy, PtrDiffTy); 848 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy", 849 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy); 850 // void objc_setCppObjectAtomic(void *dest, const void *src, void 851 // *helper); 852 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy, 853 PtrTy, PtrTy); 854 // void objc_getCppObjectAtomic(void *dest, const void *src, void 855 // *helper); 856 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy, 857 PtrTy, PtrTy); 858 } 859 860 llvm::Constant *GetCppAtomicObjectGetFunction() override { 861 // The optimised functions were added in version 1.7 of the GNUstep 862 // runtime. 863 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >= 864 VersionTuple(1, 7)); 865 return CxxAtomicObjectGetFn; 866 } 867 868 llvm::Constant *GetCppAtomicObjectSetFunction() override { 869 // The optimised functions were added in version 1.7 of the GNUstep 870 // runtime. 871 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >= 872 VersionTuple(1, 7)); 873 return CxxAtomicObjectSetFn; 874 } 875 876 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic, 877 bool copy) override { 878 // The optimised property functions omit the GC check, and so are not 879 // safe to use in GC mode. The standard functions are fast in GC mode, 880 // so there is less advantage in using them. 881 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC)); 882 // The optimised functions were added in version 1.7 of the GNUstep 883 // runtime. 884 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >= 885 VersionTuple(1, 7)); 886 887 if (atomic) { 888 if (copy) return SetPropertyAtomicCopy; 889 return SetPropertyAtomic; 890 } 891 892 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic; 893 } 894 }; 895 896 /// GNUstep Objective-C ABI version 2 implementation. 897 /// This is the ABI that provides a clean break with the legacy GCC ABI and 898 /// cleans up a number of things that were added to work around 1980s linkers. 899 class CGObjCGNUstep2 : public CGObjCGNUstep { 900 enum SectionKind 901 { 902 SelectorSection = 0, 903 ClassSection, 904 ClassReferenceSection, 905 CategorySection, 906 ProtocolSection, 907 ProtocolReferenceSection, 908 ClassAliasSection, 909 ConstantStringSection 910 }; 911 static const char *const SectionsBaseNames[8]; 912 template<SectionKind K> 913 std::string sectionName() { 914 std::string name(SectionsBaseNames[K]); 915 if (CGM.getTriple().isOSBinFormatCOFF()) 916 name += "$m"; 917 return name; 918 } 919 /// The GCC ABI superclass message lookup function. Takes a pointer to a 920 /// structure describing the receiver and the class, and a selector as 921 /// arguments. Returns the IMP for the corresponding method. 922 LazyRuntimeFunction MsgLookupSuperFn; 923 /// A flag indicating if we've emitted at least one protocol. 924 /// If we haven't, then we need to emit an empty protocol, to ensure that the 925 /// __start__objc_protocols and __stop__objc_protocols sections exist. 926 bool EmittedProtocol = false; 927 /// A flag indicating if we've emitted at least one protocol reference. 928 /// If we haven't, then we need to emit an empty protocol, to ensure that the 929 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections 930 /// exist. 931 bool EmittedProtocolRef = false; 932 /// A flag indicating if we've emitted at least one class. 933 /// If we haven't, then we need to emit an empty protocol, to ensure that the 934 /// __start__objc_classes and __stop__objc_classes sections / exist. 935 bool EmittedClass = false; 936 /// Generate the name of a symbol for a reference to a class. Accesses to 937 /// classes should be indirected via this. 938 std::string SymbolForClassRef(StringRef Name, bool isWeak) { 939 if (isWeak) 940 return (StringRef("._OBJC_WEAK_REF_CLASS_") + Name).str(); 941 else 942 return (StringRef("._OBJC_REF_CLASS_") + Name).str(); 943 } 944 /// Generate the name of a class symbol. 945 std::string SymbolForClass(StringRef Name) { 946 return (StringRef("._OBJC_CLASS_") + Name).str(); 947 } 948 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName, 949 ArrayRef<llvm::Value*> Args) { 950 SmallVector<llvm::Type *,8> Types; 951 for (auto *Arg : Args) 952 Types.push_back(Arg->getType()); 953 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types, 954 false); 955 llvm::Value *Fn = CGM.CreateRuntimeFunction(FT, FunctionName); 956 B.CreateCall(Fn, Args); 957 } 958 959 ConstantAddress GenerateConstantString(const StringLiteral *SL) override { 960 961 auto Str = SL->getString(); 962 CharUnits Align = CGM.getPointerAlign(); 963 964 // Look for an existing one 965 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str); 966 if (old != ObjCStrings.end()) 967 return ConstantAddress(old->getValue(), Align); 968 969 bool isNonASCII = SL->containsNonAscii(); 970 971 auto LiteralLength = SL->getLength(); 972 973 if ((CGM.getTarget().getPointerWidth(0) == 64) && 974 (LiteralLength < 9) && !isNonASCII) { 975 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit 976 // ASCII characters in the high 56 bits, followed by a 4-bit length and a 977 // 3-bit tag (which is always 4). 978 uint64_t str = 0; 979 // Fill in the characters 980 for (unsigned i=0 ; i<LiteralLength ; i++) 981 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7)); 982 // Fill in the length 983 str |= LiteralLength << 3; 984 // Set the tag 985 str |= 4; 986 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr( 987 llvm::ConstantInt::get(Int64Ty, str), IdTy); 988 ObjCStrings[Str] = ObjCStr; 989 return ConstantAddress(ObjCStr, Align); 990 } 991 992 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass; 993 994 if (StringClass.empty()) StringClass = "NSConstantString"; 995 996 std::string Sym = SymbolForClass(StringClass); 997 998 llvm::Constant *isa = TheModule.getNamedGlobal(Sym); 999 1000 if (!isa) 1001 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false, 1002 llvm::GlobalValue::ExternalLinkage, nullptr, Sym); 1003 else if (isa->getType() != PtrToIdTy) 1004 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy); 1005 1006 // struct 1007 // { 1008 // Class isa; 1009 // uint32_t flags; 1010 // uint32_t length; // Number of codepoints 1011 // uint32_t size; // Number of bytes 1012 // uint32_t hash; 1013 // const char *data; 1014 // }; 1015 1016 ConstantInitBuilder Builder(CGM); 1017 auto Fields = Builder.beginStruct(); 1018 Fields.add(isa); 1019 // For now, all non-ASCII strings are represented as UTF-16. As such, the 1020 // number of bytes is simply double the number of UTF-16 codepoints. In 1021 // ASCII strings, the number of bytes is equal to the number of non-ASCII 1022 // codepoints. 1023 if (isNonASCII) { 1024 unsigned NumU8CodeUnits = Str.size(); 1025 // A UTF-16 representation of a unicode string contains at most the same 1026 // number of code units as a UTF-8 representation. Allocate that much 1027 // space, plus one for the final null character. 1028 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1); 1029 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data(); 1030 llvm::UTF16 *ToPtr = &ToBuf[0]; 1031 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits, 1032 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion); 1033 uint32_t StringLength = ToPtr - &ToBuf[0]; 1034 // Add null terminator 1035 *ToPtr = 0; 1036 // Flags: 2 indicates UTF-16 encoding 1037 Fields.addInt(Int32Ty, 2); 1038 // Number of UTF-16 codepoints 1039 Fields.addInt(Int32Ty, StringLength); 1040 // Number of bytes 1041 Fields.addInt(Int32Ty, StringLength * 2); 1042 // Hash. Not currently initialised by the compiler. 1043 Fields.addInt(Int32Ty, 0); 1044 // pointer to the data string. 1045 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1); 1046 auto *C = llvm::ConstantDataArray::get(VMContext, Arr); 1047 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(), 1048 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str"); 1049 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1050 Fields.add(Buffer); 1051 } else { 1052 // Flags: 0 indicates ASCII encoding 1053 Fields.addInt(Int32Ty, 0); 1054 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint 1055 Fields.addInt(Int32Ty, Str.size()); 1056 // Number of bytes 1057 Fields.addInt(Int32Ty, Str.size()); 1058 // Hash. Not currently initialised by the compiler. 1059 Fields.addInt(Int32Ty, 0); 1060 // Data pointer 1061 Fields.add(MakeConstantString(Str)); 1062 } 1063 std::string StringName; 1064 bool isNamed = !isNonASCII; 1065 if (isNamed) { 1066 StringName = ".objc_str_"; 1067 for (int i=0,e=Str.size() ; i<e ; ++i) { 1068 unsigned char c = Str[i]; 1069 if (isalnum(c)) 1070 StringName += c; 1071 else if (c == ' ') 1072 StringName += '_'; 1073 else { 1074 isNamed = false; 1075 break; 1076 } 1077 } 1078 } 1079 auto *ObjCStrGV = 1080 Fields.finishAndCreateGlobal( 1081 isNamed ? StringRef(StringName) : ".objc_string", 1082 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage 1083 : llvm::GlobalValue::PrivateLinkage); 1084 ObjCStrGV->setSection(sectionName<ConstantStringSection>()); 1085 if (isNamed) { 1086 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName)); 1087 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 1088 } 1089 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy); 1090 ObjCStrings[Str] = ObjCStr; 1091 ConstantStrings.push_back(ObjCStr); 1092 return ConstantAddress(ObjCStr, Align); 1093 } 1094 1095 void PushProperty(ConstantArrayBuilder &PropertiesArray, 1096 const ObjCPropertyDecl *property, 1097 const Decl *OCD, 1098 bool isSynthesized=true, bool 1099 isDynamic=true) override { 1100 // struct objc_property 1101 // { 1102 // const char *name; 1103 // const char *attributes; 1104 // const char *type; 1105 // SEL getter; 1106 // SEL setter; 1107 // }; 1108 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy); 1109 ASTContext &Context = CGM.getContext(); 1110 Fields.add(MakeConstantString(property->getNameAsString())); 1111 std::string TypeStr = 1112 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD); 1113 Fields.add(MakeConstantString(TypeStr)); 1114 std::string typeStr; 1115 Context.getObjCEncodingForType(property->getType(), typeStr); 1116 Fields.add(MakeConstantString(typeStr)); 1117 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) { 1118 if (accessor) { 1119 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor); 1120 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr)); 1121 } else { 1122 Fields.add(NULLPtr); 1123 } 1124 }; 1125 addPropertyMethod(property->getGetterMethodDecl()); 1126 addPropertyMethod(property->getSetterMethodDecl()); 1127 Fields.finishAndAddTo(PropertiesArray); 1128 } 1129 1130 llvm::Constant * 1131 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override { 1132 // struct objc_protocol_method_description 1133 // { 1134 // SEL selector; 1135 // const char *types; 1136 // }; 1137 llvm::StructType *ObjCMethodDescTy = 1138 llvm::StructType::get(CGM.getLLVMContext(), 1139 { PtrToInt8Ty, PtrToInt8Ty }); 1140 ASTContext &Context = CGM.getContext(); 1141 ConstantInitBuilder Builder(CGM); 1142 // struct objc_protocol_method_description_list 1143 // { 1144 // int count; 1145 // int size; 1146 // struct objc_protocol_method_description methods[]; 1147 // }; 1148 auto MethodList = Builder.beginStruct(); 1149 // int count; 1150 MethodList.addInt(IntTy, Methods.size()); 1151 // int size; // sizeof(struct objc_method_description) 1152 llvm::DataLayout td(&TheModule); 1153 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) / 1154 CGM.getContext().getCharWidth()); 1155 // struct objc_method_description[] 1156 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy); 1157 for (auto *M : Methods) { 1158 auto Method = MethodArray.beginStruct(ObjCMethodDescTy); 1159 Method.add(CGObjCGNU::GetConstantSelector(M)); 1160 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true))); 1161 Method.finishAndAddTo(MethodArray); 1162 } 1163 MethodArray.finishAndAddTo(MethodList); 1164 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list", 1165 CGM.getPointerAlign()); 1166 } 1167 1168 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 1169 llvm::Value *cmd, MessageSendInfo &MSI) override { 1170 // Don't access the slot unless we're trying to cache the result. 1171 CGBuilderTy &Builder = CGF.Builder; 1172 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper, 1173 PtrToObjCSuperTy).getPointer(), cmd}; 1174 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs); 1175 } 1176 1177 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) { 1178 std::string SymbolName = SymbolForClassRef(Name, isWeak); 1179 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName); 1180 if (ClassSymbol) 1181 return ClassSymbol; 1182 ClassSymbol = new llvm::GlobalVariable(TheModule, 1183 IdTy, false, llvm::GlobalValue::ExternalLinkage, 1184 nullptr, SymbolName); 1185 // If this is a weak symbol, then we are creating a valid definition for 1186 // the symbol, pointing to a weak definition of the real class pointer. If 1187 // this is not a weak reference, then we are expecting another compilation 1188 // unit to provide the real indirection symbol. 1189 if (isWeak) 1190 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule, 1191 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage, 1192 nullptr, SymbolForClass(Name))); 1193 assert(ClassSymbol->getName() == SymbolName); 1194 return ClassSymbol; 1195 } 1196 llvm::Value *GetClassNamed(CodeGenFunction &CGF, 1197 const std::string &Name, 1198 bool isWeak) override { 1199 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak), 1200 CGM.getPointerAlign())); 1201 } 1202 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) { 1203 // typedef enum { 1204 // ownership_invalid = 0, 1205 // ownership_strong = 1, 1206 // ownership_weak = 2, 1207 // ownership_unsafe = 3 1208 // } ivar_ownership; 1209 int Flag; 1210 switch (Ownership) { 1211 case Qualifiers::OCL_Strong: 1212 Flag = 1; 1213 break; 1214 case Qualifiers::OCL_Weak: 1215 Flag = 2; 1216 break; 1217 case Qualifiers::OCL_ExplicitNone: 1218 Flag = 3; 1219 break; 1220 case Qualifiers::OCL_None: 1221 case Qualifiers::OCL_Autoreleasing: 1222 assert(Ownership != Qualifiers::OCL_Autoreleasing); 1223 Flag = 0; 1224 } 1225 return Flag; 1226 } 1227 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames, 1228 ArrayRef<llvm::Constant *> IvarTypes, 1229 ArrayRef<llvm::Constant *> IvarOffsets, 1230 ArrayRef<llvm::Constant *> IvarAlign, 1231 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override { 1232 llvm_unreachable("Method should not be called!"); 1233 } 1234 1235 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override { 1236 std::string Name = SymbolForProtocol(ProtocolName); 1237 auto *GV = TheModule.getGlobalVariable(Name); 1238 if (!GV) { 1239 // Emit a placeholder symbol. 1240 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false, 1241 llvm::GlobalValue::ExternalLinkage, nullptr, Name); 1242 GV->setAlignment(CGM.getPointerAlign().getQuantity()); 1243 } 1244 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy); 1245 } 1246 1247 /// Existing protocol references. 1248 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs; 1249 1250 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF, 1251 const ObjCProtocolDecl *PD) override { 1252 auto Name = PD->getNameAsString(); 1253 auto *&Ref = ExistingProtocolRefs[Name]; 1254 if (!Ref) { 1255 auto *&Protocol = ExistingProtocols[Name]; 1256 if (!Protocol) 1257 Protocol = GenerateProtocolRef(PD); 1258 std::string RefName = SymbolForProtocolRef(Name); 1259 assert(!TheModule.getGlobalVariable(RefName)); 1260 // Emit a reference symbol. 1261 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy, 1262 false, llvm::GlobalValue::LinkOnceODRLinkage, 1263 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName); 1264 GV->setComdat(TheModule.getOrInsertComdat(RefName)); 1265 GV->setSection(sectionName<ProtocolReferenceSection>()); 1266 GV->setAlignment(CGM.getPointerAlign().getQuantity()); 1267 Ref = GV; 1268 } 1269 EmittedProtocolRef = true; 1270 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign()); 1271 } 1272 1273 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) { 1274 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy, 1275 Protocols.size()); 1276 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy, 1277 Protocols); 1278 ConstantInitBuilder builder(CGM); 1279 auto ProtocolBuilder = builder.beginStruct(); 1280 ProtocolBuilder.addNullPointer(PtrTy); 1281 ProtocolBuilder.addInt(SizeTy, Protocols.size()); 1282 ProtocolBuilder.add(ProtocolArray); 1283 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list", 1284 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage); 1285 } 1286 1287 void GenerateProtocol(const ObjCProtocolDecl *PD) override { 1288 // Do nothing - we only emit referenced protocols. 1289 } 1290 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) { 1291 std::string ProtocolName = PD->getNameAsString(); 1292 auto *&Protocol = ExistingProtocols[ProtocolName]; 1293 if (Protocol) 1294 return Protocol; 1295 1296 EmittedProtocol = true; 1297 1298 auto SymName = SymbolForProtocol(ProtocolName); 1299 auto *OldGV = TheModule.getGlobalVariable(SymName); 1300 1301 // Use the protocol definition, if there is one. 1302 if (const ObjCProtocolDecl *Def = PD->getDefinition()) 1303 PD = Def; 1304 else { 1305 // If there is no definition, then create an external linkage symbol and 1306 // hope that someone else fills it in for us (and fail to link if they 1307 // don't). 1308 assert(!OldGV); 1309 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy, 1310 /*isConstant*/false, 1311 llvm::GlobalValue::ExternalLinkage, nullptr, SymName); 1312 return Protocol; 1313 } 1314 1315 SmallVector<llvm::Constant*, 16> Protocols; 1316 for (const auto *PI : PD->protocols()) 1317 Protocols.push_back( 1318 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI), 1319 ProtocolPtrTy)); 1320 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols); 1321 1322 // Collect information about methods 1323 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList; 1324 llvm::Constant *ClassMethodList, *OptionalClassMethodList; 1325 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList, 1326 OptionalInstanceMethodList); 1327 EmitProtocolMethodList(PD->class_methods(), ClassMethodList, 1328 OptionalClassMethodList); 1329 1330 // The isa pointer must be set to a magic number so the runtime knows it's 1331 // the correct layout. 1332 ConstantInitBuilder builder(CGM); 1333 auto ProtocolBuilder = builder.beginStruct(); 1334 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr( 1335 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy)); 1336 ProtocolBuilder.add(MakeConstantString(ProtocolName)); 1337 ProtocolBuilder.add(ProtocolList); 1338 ProtocolBuilder.add(InstanceMethodList); 1339 ProtocolBuilder.add(ClassMethodList); 1340 ProtocolBuilder.add(OptionalInstanceMethodList); 1341 ProtocolBuilder.add(OptionalClassMethodList); 1342 // Required instance properties 1343 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false)); 1344 // Optional instance properties 1345 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true)); 1346 // Required class properties 1347 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false)); 1348 // Optional class properties 1349 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true)); 1350 1351 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName, 1352 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage); 1353 GV->setSection(sectionName<ProtocolSection>()); 1354 GV->setComdat(TheModule.getOrInsertComdat(SymName)); 1355 if (OldGV) { 1356 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV, 1357 OldGV->getType())); 1358 OldGV->removeFromParent(); 1359 GV->setName(SymName); 1360 } 1361 Protocol = GV; 1362 return GV; 1363 } 1364 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) { 1365 if (Val->getType() == Ty) 1366 return Val; 1367 return llvm::ConstantExpr::getBitCast(Val, Ty); 1368 } 1369 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel, 1370 const std::string &TypeEncoding) override { 1371 return GetConstantSelector(Sel, TypeEncoding); 1372 } 1373 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) { 1374 if (TypeEncoding.empty()) 1375 return NULLPtr; 1376 std::string MangledTypes = TypeEncoding; 1377 std::replace(MangledTypes.begin(), MangledTypes.end(), 1378 '@', '\1'); 1379 std::string TypesVarName = ".objc_sel_types_" + MangledTypes; 1380 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName); 1381 if (!TypesGlobal) { 1382 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext, 1383 TypeEncoding); 1384 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(), 1385 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName); 1386 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName)); 1387 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 1388 TypesGlobal = GV; 1389 } 1390 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(), 1391 TypesGlobal, Zeros); 1392 } 1393 llvm::Constant *GetConstantSelector(Selector Sel, 1394 const std::string &TypeEncoding) override { 1395 // @ is used as a special character in symbol names (used for symbol 1396 // versioning), so mangle the name to not include it. Replace it with a 1397 // character that is not a valid type encoding character (and, being 1398 // non-printable, never will be!) 1399 std::string MangledTypes = TypeEncoding; 1400 std::replace(MangledTypes.begin(), MangledTypes.end(), 1401 '@', '\1'); 1402 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" + 1403 MangledTypes).str(); 1404 if (auto *GV = TheModule.getNamedGlobal(SelVarName)) 1405 return EnforceType(GV, SelectorTy); 1406 ConstantInitBuilder builder(CGM); 1407 auto SelBuilder = builder.beginStruct(); 1408 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_", 1409 true)); 1410 SelBuilder.add(GetTypeString(TypeEncoding)); 1411 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName, 1412 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage); 1413 GV->setComdat(TheModule.getOrInsertComdat(SelVarName)); 1414 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 1415 GV->setSection(sectionName<SelectorSection>()); 1416 auto *SelVal = EnforceType(GV, SelectorTy); 1417 return SelVal; 1418 } 1419 llvm::StructType *emptyStruct = nullptr; 1420 1421 /// Return pointers to the start and end of a section. On ELF platforms, we 1422 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set 1423 /// to the start and end of section names, as long as those section names are 1424 /// valid identifiers and the symbols are referenced but not defined. On 1425 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort 1426 /// by subsections and place everything that we want to reference in a middle 1427 /// subsection and then insert zero-sized symbols in subsections a and z. 1428 std::pair<llvm::Constant*,llvm::Constant*> 1429 GetSectionBounds(StringRef Section) { 1430 if (CGM.getTriple().isOSBinFormatCOFF()) { 1431 if (emptyStruct == nullptr) { 1432 emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel"); 1433 emptyStruct->setBody({}, /*isPacked*/true); 1434 } 1435 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct); 1436 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) { 1437 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct, 1438 /*isConstant*/false, 1439 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix + 1440 Section); 1441 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility); 1442 Sym->setSection((Section + SecSuffix).str()); 1443 Sym->setComdat(TheModule.getOrInsertComdat((Prefix + 1444 Section).str())); 1445 Sym->setAlignment(1); 1446 return Sym; 1447 }; 1448 return { Sym("__start_", "$a"), Sym("__stop", "$z") }; 1449 } 1450 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy, 1451 /*isConstant*/false, 1452 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") + 1453 Section); 1454 Start->setVisibility(llvm::GlobalValue::HiddenVisibility); 1455 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy, 1456 /*isConstant*/false, 1457 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") + 1458 Section); 1459 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility); 1460 return { Start, Stop }; 1461 } 1462 CatchTypeInfo getCatchAllTypeInfo() override { 1463 return CGM.getCXXABI().getCatchAllTypeInfo(); 1464 } 1465 llvm::Function *ModuleInitFunction() override { 1466 llvm::Function *LoadFunction = llvm::Function::Create( 1467 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false), 1468 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function", 1469 &TheModule); 1470 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility); 1471 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function")); 1472 1473 llvm::BasicBlock *EntryBB = 1474 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction); 1475 CGBuilderTy B(CGM, VMContext); 1476 B.SetInsertPoint(EntryBB); 1477 ConstantInitBuilder builder(CGM); 1478 auto InitStructBuilder = builder.beginStruct(); 1479 InitStructBuilder.addInt(Int64Ty, 0); 1480 for (auto *s : SectionsBaseNames) { 1481 auto bounds = GetSectionBounds(s); 1482 InitStructBuilder.add(bounds.first); 1483 InitStructBuilder.add(bounds.second); 1484 }; 1485 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init", 1486 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage); 1487 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility); 1488 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init")); 1489 1490 CallRuntimeFunction(B, "__objc_load", {InitStruct});; 1491 B.CreateRetVoid(); 1492 // Make sure that the optimisers don't delete this function. 1493 CGM.addCompilerUsedGlobal(LoadFunction); 1494 // FIXME: Currently ELF only! 1495 // We have to do this by hand, rather than with @llvm.ctors, so that the 1496 // linker can remove the duplicate invocations. 1497 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(), 1498 /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage, 1499 LoadFunction, ".objc_ctor"); 1500 // Check that this hasn't been renamed. This shouldn't happen, because 1501 // this function should be called precisely once. 1502 assert(InitVar->getName() == ".objc_ctor"); 1503 // In Windows, initialisers are sorted by the suffix. XCL is for library 1504 // initialisers, which run before user initialisers. We are running 1505 // Objective-C loads at the end of library load. This means +load methods 1506 // will run before any other static constructors, but that static 1507 // constructors can see a fully initialised Objective-C state. 1508 if (CGM.getTriple().isOSBinFormatCOFF()) 1509 InitVar->setSection(".CRT$XCLz"); 1510 else 1511 InitVar->setSection(".ctors"); 1512 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility); 1513 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor")); 1514 CGM.addUsedGlobal(InitVar); 1515 for (auto *C : Categories) { 1516 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts()); 1517 Cat->setSection(sectionName<CategorySection>()); 1518 CGM.addUsedGlobal(Cat); 1519 } 1520 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init, 1521 StringRef Section) { 1522 auto nullBuilder = builder.beginStruct(); 1523 for (auto *F : Init) 1524 nullBuilder.add(F); 1525 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(), 1526 false, llvm::GlobalValue::LinkOnceODRLinkage); 1527 GV->setSection(Section); 1528 GV->setComdat(TheModule.getOrInsertComdat(Name)); 1529 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 1530 CGM.addUsedGlobal(GV); 1531 return GV; 1532 }; 1533 for (auto clsAlias : ClassAliases) 1534 createNullGlobal(std::string(".objc_class_alias") + 1535 clsAlias.second, { MakeConstantString(clsAlias.second), 1536 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>()); 1537 // On ELF platforms, add a null value for each special section so that we 1538 // can always guarantee that the _start and _stop symbols will exist and be 1539 // meaningful. This is not required on COFF platforms, where our start and 1540 // stop symbols will create the section. 1541 if (!CGM.getTriple().isOSBinFormatCOFF()) { 1542 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr}, 1543 sectionName<SelectorSection>()); 1544 if (Categories.empty()) 1545 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr, 1546 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr}, 1547 sectionName<CategorySection>()); 1548 if (!EmittedClass) { 1549 createNullGlobal(".objc_null_cls_init_ref", NULLPtr, 1550 sectionName<ClassReferenceSection>()); 1551 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr }, 1552 sectionName<ClassReferenceSection>()); 1553 } 1554 if (!EmittedProtocol) 1555 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr, 1556 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, 1557 NULLPtr}, sectionName<ProtocolSection>()); 1558 if (!EmittedProtocolRef) 1559 createNullGlobal(".objc_null_protocol_ref", {NULLPtr}, 1560 sectionName<ProtocolReferenceSection>()); 1561 if (ClassAliases.empty()) 1562 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr }, 1563 sectionName<ClassAliasSection>()); 1564 if (ConstantStrings.empty()) { 1565 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0); 1566 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero, 1567 i32Zero, i32Zero, i32Zero, NULLPtr }, 1568 sectionName<ConstantStringSection>()); 1569 } 1570 } 1571 ConstantStrings.clear(); 1572 Categories.clear(); 1573 Classes.clear(); 1574 return nullptr; 1575 } 1576 /// In the v2 ABI, ivar offset variables use the type encoding in their name 1577 /// to trigger linker failures if the types don't match. 1578 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID, 1579 const ObjCIvarDecl *Ivar) override { 1580 std::string TypeEncoding; 1581 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding); 1582 // Prevent the @ from being interpreted as a symbol version. 1583 std::replace(TypeEncoding.begin(), TypeEncoding.end(), 1584 '@', '\1'); 1585 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString() 1586 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding; 1587 return Name; 1588 } 1589 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF, 1590 const ObjCInterfaceDecl *Interface, 1591 const ObjCIvarDecl *Ivar) override { 1592 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar); 1593 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name); 1594 if (!IvarOffsetPointer) 1595 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false, 1596 llvm::GlobalValue::ExternalLinkage, nullptr, Name); 1597 CharUnits Align = CGM.getIntAlign(); 1598 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align); 1599 if (Offset->getType() != PtrDiffTy) 1600 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy); 1601 return Offset; 1602 } 1603 void GenerateClass(const ObjCImplementationDecl *OID) override { 1604 ASTContext &Context = CGM.getContext(); 1605 1606 // Get the class name 1607 ObjCInterfaceDecl *classDecl = 1608 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface()); 1609 std::string className = classDecl->getNameAsString(); 1610 auto *classNameConstant = MakeConstantString(className); 1611 1612 ConstantInitBuilder builder(CGM); 1613 auto metaclassFields = builder.beginStruct(); 1614 // struct objc_class *isa; 1615 metaclassFields.addNullPointer(PtrTy); 1616 // struct objc_class *super_class; 1617 metaclassFields.addNullPointer(PtrTy); 1618 // const char *name; 1619 metaclassFields.add(classNameConstant); 1620 // long version; 1621 metaclassFields.addInt(LongTy, 0); 1622 // unsigned long info; 1623 // objc_class_flag_meta 1624 metaclassFields.addInt(LongTy, 1); 1625 // long instance_size; 1626 // Setting this to zero is consistent with the older ABI, but it might be 1627 // more sensible to set this to sizeof(struct objc_class) 1628 metaclassFields.addInt(LongTy, 0); 1629 // struct objc_ivar_list *ivars; 1630 metaclassFields.addNullPointer(PtrTy); 1631 // struct objc_method_list *methods 1632 // FIXME: Almost identical code is copied and pasted below for the 1633 // class, but refactoring it cleanly requires C++14 generic lambdas. 1634 if (OID->classmeth_begin() == OID->classmeth_end()) 1635 metaclassFields.addNullPointer(PtrTy); 1636 else { 1637 SmallVector<ObjCMethodDecl*, 16> ClassMethods; 1638 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(), 1639 OID->classmeth_end()); 1640 metaclassFields.addBitCast( 1641 GenerateMethodList(className, "", ClassMethods, true), 1642 PtrTy); 1643 } 1644 // void *dtable; 1645 metaclassFields.addNullPointer(PtrTy); 1646 // IMP cxx_construct; 1647 metaclassFields.addNullPointer(PtrTy); 1648 // IMP cxx_destruct; 1649 metaclassFields.addNullPointer(PtrTy); 1650 // struct objc_class *subclass_list 1651 metaclassFields.addNullPointer(PtrTy); 1652 // struct objc_class *sibling_class 1653 metaclassFields.addNullPointer(PtrTy); 1654 // struct objc_protocol_list *protocols; 1655 metaclassFields.addNullPointer(PtrTy); 1656 // struct reference_list *extra_data; 1657 metaclassFields.addNullPointer(PtrTy); 1658 // long abi_version; 1659 metaclassFields.addInt(LongTy, 0); 1660 // struct objc_property_list *properties 1661 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true)); 1662 1663 auto *metaclass = metaclassFields.finishAndCreateGlobal("._OBJC_METACLASS_" 1664 + className, CGM.getPointerAlign()); 1665 1666 auto classFields = builder.beginStruct(); 1667 // struct objc_class *isa; 1668 classFields.add(metaclass); 1669 // struct objc_class *super_class; 1670 // Get the superclass name. 1671 const ObjCInterfaceDecl * SuperClassDecl = 1672 OID->getClassInterface()->getSuperClass(); 1673 if (SuperClassDecl) { 1674 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString()); 1675 llvm::Constant *SuperClass = TheModule.getNamedGlobal(SuperClassName); 1676 if (!SuperClass) 1677 { 1678 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false, 1679 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName); 1680 } 1681 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy)); 1682 } else 1683 classFields.addNullPointer(PtrTy); 1684 // const char *name; 1685 classFields.add(classNameConstant); 1686 // long version; 1687 classFields.addInt(LongTy, 0); 1688 // unsigned long info; 1689 // !objc_class_flag_meta 1690 classFields.addInt(LongTy, 0); 1691 // long instance_size; 1692 int superInstanceSize = !SuperClassDecl ? 0 : 1693 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity(); 1694 // Instance size is negative for classes that have not yet had their ivar 1695 // layout calculated. 1696 classFields.addInt(LongTy, 1697 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() - 1698 superInstanceSize)); 1699 1700 if (classDecl->all_declared_ivar_begin() == nullptr) 1701 classFields.addNullPointer(PtrTy); 1702 else { 1703 int ivar_count = 0; 1704 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD; 1705 IVD = IVD->getNextIvar()) ivar_count++; 1706 llvm::DataLayout td(&TheModule); 1707 // struct objc_ivar_list *ivars; 1708 ConstantInitBuilder b(CGM); 1709 auto ivarListBuilder = b.beginStruct(); 1710 // int count; 1711 ivarListBuilder.addInt(IntTy, ivar_count); 1712 // size_t size; 1713 llvm::StructType *ObjCIvarTy = llvm::StructType::get( 1714 PtrToInt8Ty, 1715 PtrToInt8Ty, 1716 PtrToInt8Ty, 1717 Int32Ty, 1718 Int32Ty); 1719 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) / 1720 CGM.getContext().getCharWidth()); 1721 // struct objc_ivar ivars[] 1722 auto ivarArrayBuilder = ivarListBuilder.beginArray(); 1723 CodeGenTypes &Types = CGM.getTypes(); 1724 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD; 1725 IVD = IVD->getNextIvar()) { 1726 auto ivarTy = IVD->getType(); 1727 auto ivarBuilder = ivarArrayBuilder.beginStruct(); 1728 // const char *name; 1729 ivarBuilder.add(MakeConstantString(IVD->getNameAsString())); 1730 // const char *type; 1731 std::string TypeStr; 1732 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true); 1733 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true); 1734 ivarBuilder.add(MakeConstantString(TypeStr)); 1735 // int *offset; 1736 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD); 1737 uint64_t Offset = BaseOffset - superInstanceSize; 1738 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset); 1739 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD); 1740 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName); 1741 if (OffsetVar) 1742 OffsetVar->setInitializer(OffsetValue); 1743 else 1744 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy, 1745 false, llvm::GlobalValue::ExternalLinkage, 1746 OffsetValue, OffsetName); 1747 auto ivarVisibility = 1748 (IVD->getAccessControl() == ObjCIvarDecl::Private || 1749 IVD->getAccessControl() == ObjCIvarDecl::Package || 1750 classDecl->getVisibility() == HiddenVisibility) ? 1751 llvm::GlobalValue::HiddenVisibility : 1752 llvm::GlobalValue::DefaultVisibility; 1753 OffsetVar->setVisibility(ivarVisibility); 1754 ivarBuilder.add(OffsetVar); 1755 // Ivar size 1756 ivarBuilder.addInt(Int32Ty, 1757 td.getTypeSizeInBits(Types.ConvertType(ivarTy)) / 1758 CGM.getContext().getCharWidth()); 1759 // Alignment will be stored as a base-2 log of the alignment. 1760 int align = llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity()); 1761 // Objects that require more than 2^64-byte alignment should be impossible! 1762 assert(align < 64); 1763 // uint32_t flags; 1764 // Bits 0-1 are ownership. 1765 // Bit 2 indicates an extended type encoding 1766 // Bits 3-8 contain log2(aligment) 1767 ivarBuilder.addInt(Int32Ty, 1768 (align << 3) | (1<<2) | 1769 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime())); 1770 ivarBuilder.finishAndAddTo(ivarArrayBuilder); 1771 } 1772 ivarArrayBuilder.finishAndAddTo(ivarListBuilder); 1773 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list", 1774 CGM.getPointerAlign(), /*constant*/ false, 1775 llvm::GlobalValue::PrivateLinkage); 1776 classFields.add(ivarList); 1777 } 1778 // struct objc_method_list *methods 1779 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods; 1780 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(), 1781 OID->instmeth_end()); 1782 for (auto *propImpl : OID->property_impls()) 1783 if (propImpl->getPropertyImplementation() == 1784 ObjCPropertyImplDecl::Synthesize) { 1785 ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 1786 auto addIfExists = [&](const ObjCMethodDecl* OMD) { 1787 if (OMD) 1788 InstanceMethods.push_back(OMD); 1789 }; 1790 addIfExists(prop->getGetterMethodDecl()); 1791 addIfExists(prop->getSetterMethodDecl()); 1792 } 1793 1794 if (InstanceMethods.size() == 0) 1795 classFields.addNullPointer(PtrTy); 1796 else 1797 classFields.addBitCast( 1798 GenerateMethodList(className, "", InstanceMethods, false), 1799 PtrTy); 1800 // void *dtable; 1801 classFields.addNullPointer(PtrTy); 1802 // IMP cxx_construct; 1803 classFields.addNullPointer(PtrTy); 1804 // IMP cxx_destruct; 1805 classFields.addNullPointer(PtrTy); 1806 // struct objc_class *subclass_list 1807 classFields.addNullPointer(PtrTy); 1808 // struct objc_class *sibling_class 1809 classFields.addNullPointer(PtrTy); 1810 // struct objc_protocol_list *protocols; 1811 SmallVector<llvm::Constant*, 16> Protocols; 1812 for (const auto *I : classDecl->protocols()) 1813 Protocols.push_back( 1814 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I), 1815 ProtocolPtrTy)); 1816 if (Protocols.empty()) 1817 classFields.addNullPointer(PtrTy); 1818 else 1819 classFields.add(GenerateProtocolList(Protocols)); 1820 // struct reference_list *extra_data; 1821 classFields.addNullPointer(PtrTy); 1822 // long abi_version; 1823 classFields.addInt(LongTy, 0); 1824 // struct objc_property_list *properties 1825 classFields.add(GeneratePropertyList(OID, classDecl)); 1826 1827 auto *classStruct = 1828 classFields.finishAndCreateGlobal(SymbolForClass(className), 1829 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage); 1830 1831 if (CGM.getTriple().isOSBinFormatCOFF()) { 1832 auto Storage = llvm::GlobalValue::DefaultStorageClass; 1833 if (OID->getClassInterface()->hasAttr<DLLImportAttr>()) 1834 Storage = llvm::GlobalValue::DLLImportStorageClass; 1835 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) 1836 Storage = llvm::GlobalValue::DLLExportStorageClass; 1837 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(Storage); 1838 } 1839 1840 auto *classRefSymbol = GetClassVar(className); 1841 classRefSymbol->setSection(sectionName<ClassReferenceSection>()); 1842 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy)); 1843 1844 1845 // Resolve the class aliases, if they exist. 1846 // FIXME: Class pointer aliases shouldn't exist! 1847 if (ClassPtrAlias) { 1848 ClassPtrAlias->replaceAllUsesWith( 1849 llvm::ConstantExpr::getBitCast(classStruct, IdTy)); 1850 ClassPtrAlias->eraseFromParent(); 1851 ClassPtrAlias = nullptr; 1852 } 1853 if (auto Placeholder = 1854 TheModule.getNamedGlobal(SymbolForClass(className))) 1855 if (Placeholder != classStruct) { 1856 Placeholder->replaceAllUsesWith( 1857 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType())); 1858 Placeholder->eraseFromParent(); 1859 classStruct->setName(SymbolForClass(className)); 1860 } 1861 if (MetaClassPtrAlias) { 1862 MetaClassPtrAlias->replaceAllUsesWith( 1863 llvm::ConstantExpr::getBitCast(metaclass, IdTy)); 1864 MetaClassPtrAlias->eraseFromParent(); 1865 MetaClassPtrAlias = nullptr; 1866 } 1867 assert(classStruct->getName() == SymbolForClass(className)); 1868 1869 auto classInitRef = new llvm::GlobalVariable(TheModule, 1870 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage, 1871 classStruct, "._OBJC_INIT_CLASS_" + className); 1872 classInitRef->setSection(sectionName<ClassSection>()); 1873 CGM.addUsedGlobal(classInitRef); 1874 1875 EmittedClass = true; 1876 } 1877 public: 1878 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) { 1879 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy, 1880 PtrToObjCSuperTy, SelectorTy); 1881 // struct objc_property 1882 // { 1883 // const char *name; 1884 // const char *attributes; 1885 // const char *type; 1886 // SEL getter; 1887 // SEL setter; 1888 // } 1889 PropertyMetadataTy = 1890 llvm::StructType::get(CGM.getLLVMContext(), 1891 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty }); 1892 } 1893 1894 }; 1895 1896 const char *const CGObjCGNUstep2::SectionsBaseNames[8] = 1897 { 1898 "__objc_selectors", 1899 "__objc_classes", 1900 "__objc_class_refs", 1901 "__objc_cats", 1902 "__objc_protocols", 1903 "__objc_protocol_refs", 1904 "__objc_class_aliases", 1905 "__objc_constant_string" 1906 }; 1907 1908 /// Support for the ObjFW runtime. 1909 class CGObjCObjFW: public CGObjCGNU { 1910 protected: 1911 /// The GCC ABI message lookup function. Returns an IMP pointing to the 1912 /// method implementation for this message. 1913 LazyRuntimeFunction MsgLookupFn; 1914 /// stret lookup function. While this does not seem to make sense at the 1915 /// first look, this is required to call the correct forwarding function. 1916 LazyRuntimeFunction MsgLookupFnSRet; 1917 /// The GCC ABI superclass message lookup function. Takes a pointer to a 1918 /// structure describing the receiver and the class, and a selector as 1919 /// arguments. Returns the IMP for the corresponding method. 1920 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet; 1921 1922 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver, 1923 llvm::Value *cmd, llvm::MDNode *node, 1924 MessageSendInfo &MSI) override { 1925 CGBuilderTy &Builder = CGF.Builder; 1926 llvm::Value *args[] = { 1927 EnforceType(Builder, Receiver, IdTy), 1928 EnforceType(Builder, cmd, SelectorTy) }; 1929 1930 llvm::CallSite imp; 1931 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) 1932 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args); 1933 else 1934 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args); 1935 1936 imp->setMetadata(msgSendMDKind, node); 1937 return imp.getInstruction(); 1938 } 1939 1940 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper, 1941 llvm::Value *cmd, MessageSendInfo &MSI) override { 1942 CGBuilderTy &Builder = CGF.Builder; 1943 llvm::Value *lookupArgs[] = { 1944 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd, 1945 }; 1946 1947 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) 1948 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs); 1949 else 1950 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs); 1951 } 1952 1953 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name, 1954 bool isWeak) override { 1955 if (isWeak) 1956 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak); 1957 1958 EmitClassRef(Name); 1959 std::string SymbolName = "_OBJC_CLASS_" + Name; 1960 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName); 1961 if (!ClassSymbol) 1962 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false, 1963 llvm::GlobalValue::ExternalLinkage, 1964 nullptr, SymbolName); 1965 return ClassSymbol; 1966 } 1967 1968 public: 1969 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) { 1970 // IMP objc_msg_lookup(id, SEL); 1971 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy); 1972 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy, 1973 SelectorTy); 1974 // IMP objc_msg_lookup_super(struct objc_super*, SEL); 1975 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy, 1976 PtrToObjCSuperTy, SelectorTy); 1977 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy, 1978 PtrToObjCSuperTy, SelectorTy); 1979 } 1980 }; 1981 } // end anonymous namespace 1982 1983 /// Emits a reference to a dummy variable which is emitted with each class. 1984 /// This ensures that a linker error will be generated when trying to link 1985 /// together modules where a referenced class is not defined. 1986 void CGObjCGNU::EmitClassRef(const std::string &className) { 1987 std::string symbolRef = "__objc_class_ref_" + className; 1988 // Don't emit two copies of the same symbol 1989 if (TheModule.getGlobalVariable(symbolRef)) 1990 return; 1991 std::string symbolName = "__objc_class_name_" + className; 1992 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName); 1993 if (!ClassSymbol) { 1994 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false, 1995 llvm::GlobalValue::ExternalLinkage, 1996 nullptr, symbolName); 1997 } 1998 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true, 1999 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef); 2000 } 2001 2002 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion, 2003 unsigned protocolClassVersion, unsigned classABI) 2004 : CGObjCRuntime(cgm), TheModule(CGM.getModule()), 2005 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr), 2006 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion), 2007 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) { 2008 2009 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend"); 2010 usesSEHExceptions = 2011 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment(); 2012 2013 CodeGenTypes &Types = CGM.getTypes(); 2014 IntTy = cast<llvm::IntegerType>( 2015 Types.ConvertType(CGM.getContext().IntTy)); 2016 LongTy = cast<llvm::IntegerType>( 2017 Types.ConvertType(CGM.getContext().LongTy)); 2018 SizeTy = cast<llvm::IntegerType>( 2019 Types.ConvertType(CGM.getContext().getSizeType())); 2020 PtrDiffTy = cast<llvm::IntegerType>( 2021 Types.ConvertType(CGM.getContext().getPointerDiffType())); 2022 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy); 2023 2024 Int8Ty = llvm::Type::getInt8Ty(VMContext); 2025 // C string type. Used in lots of places. 2026 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty); 2027 ProtocolPtrTy = llvm::PointerType::getUnqual( 2028 Types.ConvertType(CGM.getContext().getObjCProtoType())); 2029 2030 Zeros[0] = llvm::ConstantInt::get(LongTy, 0); 2031 Zeros[1] = Zeros[0]; 2032 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty); 2033 // Get the selector Type. 2034 QualType selTy = CGM.getContext().getObjCSelType(); 2035 if (QualType() == selTy) { 2036 SelectorTy = PtrToInt8Ty; 2037 } else { 2038 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy)); 2039 } 2040 2041 PtrToIntTy = llvm::PointerType::getUnqual(IntTy); 2042 PtrTy = PtrToInt8Ty; 2043 2044 Int32Ty = llvm::Type::getInt32Ty(VMContext); 2045 Int64Ty = llvm::Type::getInt64Ty(VMContext); 2046 2047 IntPtrTy = 2048 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty; 2049 2050 // Object type 2051 QualType UnqualIdTy = CGM.getContext().getObjCIdType(); 2052 ASTIdTy = CanQualType(); 2053 if (UnqualIdTy != QualType()) { 2054 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy); 2055 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy)); 2056 } else { 2057 IdTy = PtrToInt8Ty; 2058 } 2059 PtrToIdTy = llvm::PointerType::getUnqual(IdTy); 2060 ProtocolTy = llvm::StructType::get(IdTy, 2061 PtrToInt8Ty, // name 2062 PtrToInt8Ty, // protocols 2063 PtrToInt8Ty, // instance methods 2064 PtrToInt8Ty, // class methods 2065 PtrToInt8Ty, // optional instance methods 2066 PtrToInt8Ty, // optional class methods 2067 PtrToInt8Ty, // properties 2068 PtrToInt8Ty);// optional properties 2069 2070 // struct objc_property_gsv1 2071 // { 2072 // const char *name; 2073 // char attributes; 2074 // char attributes2; 2075 // char unused1; 2076 // char unused2; 2077 // const char *getter_name; 2078 // const char *getter_types; 2079 // const char *setter_name; 2080 // const char *setter_types; 2081 // } 2082 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), { 2083 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, 2084 PtrToInt8Ty, PtrToInt8Ty }); 2085 2086 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy); 2087 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy); 2088 2089 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); 2090 2091 // void objc_exception_throw(id); 2092 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy); 2093 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy); 2094 // int objc_sync_enter(id); 2095 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy); 2096 // int objc_sync_exit(id); 2097 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy); 2098 2099 // void objc_enumerationMutation (id) 2100 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy); 2101 2102 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL) 2103 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy, 2104 PtrDiffTy, BoolTy); 2105 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL) 2106 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy, 2107 PtrDiffTy, IdTy, BoolTy, BoolTy); 2108 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL) 2109 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy, 2110 PtrDiffTy, BoolTy, BoolTy); 2111 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL) 2112 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy, 2113 PtrDiffTy, BoolTy, BoolTy); 2114 2115 // IMP type 2116 llvm::Type *IMPArgs[] = { IdTy, SelectorTy }; 2117 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs, 2118 true)); 2119 2120 const LangOptions &Opts = CGM.getLangOpts(); 2121 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount) 2122 RuntimeVersion = 10; 2123 2124 // Don't bother initialising the GC stuff unless we're compiling in GC mode 2125 if (Opts.getGC() != LangOptions::NonGC) { 2126 // This is a bit of an hack. We should sort this out by having a proper 2127 // CGObjCGNUstep subclass for GC, but we may want to really support the old 2128 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now 2129 // Get selectors needed in GC mode 2130 RetainSel = GetNullarySelector("retain", CGM.getContext()); 2131 ReleaseSel = GetNullarySelector("release", CGM.getContext()); 2132 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext()); 2133 2134 // Get functions needed in GC mode 2135 2136 // id objc_assign_ivar(id, id, ptrdiff_t); 2137 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy); 2138 // id objc_assign_strongCast (id, id*) 2139 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy, 2140 PtrToIdTy); 2141 // id objc_assign_global(id, id*); 2142 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy); 2143 // id objc_assign_weak(id, id*); 2144 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy); 2145 // id objc_read_weak(id*); 2146 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy); 2147 // void *objc_memmove_collectable(void*, void *, size_t); 2148 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy, 2149 SizeTy); 2150 } 2151 } 2152 2153 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF, 2154 const std::string &Name, bool isWeak) { 2155 llvm::Constant *ClassName = MakeConstantString(Name); 2156 // With the incompatible ABI, this will need to be replaced with a direct 2157 // reference to the class symbol. For the compatible nonfragile ABI we are 2158 // still performing this lookup at run time but emitting the symbol for the 2159 // class externally so that we can make the switch later. 2160 // 2161 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class 2162 // with memoized versions or with static references if it's safe to do so. 2163 if (!isWeak) 2164 EmitClassRef(Name); 2165 2166 llvm::Constant *ClassLookupFn = 2167 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), 2168 "objc_lookup_class"); 2169 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName); 2170 } 2171 2172 // This has to perform the lookup every time, since posing and related 2173 // techniques can modify the name -> class mapping. 2174 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF, 2175 const ObjCInterfaceDecl *OID) { 2176 auto *Value = 2177 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported()); 2178 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) 2179 CGM.setGVProperties(ClassSymbol, OID); 2180 return Value; 2181 } 2182 2183 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) { 2184 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false); 2185 if (CGM.getTriple().isOSBinFormatCOFF()) { 2186 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) { 2187 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool"); 2188 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl(); 2189 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 2190 2191 const VarDecl *VD = nullptr; 2192 for (const auto &Result : DC->lookup(&II)) 2193 if ((VD = dyn_cast<VarDecl>(Result))) 2194 break; 2195 2196 CGM.setGVProperties(ClassSymbol, VD); 2197 } 2198 } 2199 return Value; 2200 } 2201 2202 llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel, 2203 const std::string &TypeEncoding) { 2204 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel]; 2205 llvm::GlobalAlias *SelValue = nullptr; 2206 2207 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(), 2208 e = Types.end() ; i!=e ; i++) { 2209 if (i->first == TypeEncoding) { 2210 SelValue = i->second; 2211 break; 2212 } 2213 } 2214 if (!SelValue) { 2215 SelValue = llvm::GlobalAlias::create( 2216 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage, 2217 ".objc_selector_" + Sel.getAsString(), &TheModule); 2218 Types.emplace_back(TypeEncoding, SelValue); 2219 } 2220 2221 return SelValue; 2222 } 2223 2224 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) { 2225 llvm::Value *SelValue = GetSelector(CGF, Sel); 2226 2227 // Store it to a temporary. Does this satisfy the semantics of 2228 // GetAddrOfSelector? Hopefully. 2229 Address tmp = CGF.CreateTempAlloca(SelValue->getType(), 2230 CGF.getPointerAlign()); 2231 CGF.Builder.CreateStore(SelValue, tmp); 2232 return tmp; 2233 } 2234 2235 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) { 2236 return GetTypedSelector(CGF, Sel, std::string()); 2237 } 2238 2239 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, 2240 const ObjCMethodDecl *Method) { 2241 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method); 2242 return GetTypedSelector(CGF, Method->getSelector(), SelTypes); 2243 } 2244 2245 llvm::Constant *CGObjCGNU::GetEHType(QualType T) { 2246 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) { 2247 // With the old ABI, there was only one kind of catchall, which broke 2248 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as 2249 // a pointer indicating object catchalls, and NULL to indicate real 2250 // catchalls 2251 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 2252 return MakeConstantString("@id"); 2253 } else { 2254 return nullptr; 2255 } 2256 } 2257 2258 // All other types should be Objective-C interface pointer types. 2259 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>(); 2260 assert(OPT && "Invalid @catch type."); 2261 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface(); 2262 assert(IDecl && "Invalid @catch type."); 2263 return MakeConstantString(IDecl->getIdentifier()->getName()); 2264 } 2265 2266 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) { 2267 if (usesSEHExceptions) 2268 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T); 2269 2270 if (!CGM.getLangOpts().CPlusPlus) 2271 return CGObjCGNU::GetEHType(T); 2272 2273 // For Objective-C++, we want to provide the ability to catch both C++ and 2274 // Objective-C objects in the same function. 2275 2276 // There's a particular fixed type info for 'id'. 2277 if (T->isObjCIdType() || 2278 T->isObjCQualifiedIdType()) { 2279 llvm::Constant *IDEHType = 2280 CGM.getModule().getGlobalVariable("__objc_id_type_info"); 2281 if (!IDEHType) 2282 IDEHType = 2283 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty, 2284 false, 2285 llvm::GlobalValue::ExternalLinkage, 2286 nullptr, "__objc_id_type_info"); 2287 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty); 2288 } 2289 2290 const ObjCObjectPointerType *PT = 2291 T->getAs<ObjCObjectPointerType>(); 2292 assert(PT && "Invalid @catch type."); 2293 const ObjCInterfaceType *IT = PT->getInterfaceType(); 2294 assert(IT && "Invalid @catch type."); 2295 std::string className = IT->getDecl()->getIdentifier()->getName(); 2296 2297 std::string typeinfoName = "__objc_eh_typeinfo_" + className; 2298 2299 // Return the existing typeinfo if it exists 2300 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName); 2301 if (typeinfo) 2302 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty); 2303 2304 // Otherwise create it. 2305 2306 // vtable for gnustep::libobjc::__objc_class_type_info 2307 // It's quite ugly hard-coding this. Ideally we'd generate it using the host 2308 // platform's name mangling. 2309 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE"; 2310 auto *Vtable = TheModule.getGlobalVariable(vtableName); 2311 if (!Vtable) { 2312 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true, 2313 llvm::GlobalValue::ExternalLinkage, 2314 nullptr, vtableName); 2315 } 2316 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2); 2317 auto *BVtable = llvm::ConstantExpr::getBitCast( 2318 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two), 2319 PtrToInt8Ty); 2320 2321 llvm::Constant *typeName = 2322 ExportUniqueString(className, "__objc_eh_typename_"); 2323 2324 ConstantInitBuilder builder(CGM); 2325 auto fields = builder.beginStruct(); 2326 fields.add(BVtable); 2327 fields.add(typeName); 2328 llvm::Constant *TI = 2329 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className, 2330 CGM.getPointerAlign(), 2331 /*constant*/ false, 2332 llvm::GlobalValue::LinkOnceODRLinkage); 2333 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty); 2334 } 2335 2336 /// Generate an NSConstantString object. 2337 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) { 2338 2339 std::string Str = SL->getString().str(); 2340 CharUnits Align = CGM.getPointerAlign(); 2341 2342 // Look for an existing one 2343 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str); 2344 if (old != ObjCStrings.end()) 2345 return ConstantAddress(old->getValue(), Align); 2346 2347 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass; 2348 2349 if (StringClass.empty()) StringClass = "NSConstantString"; 2350 2351 std::string Sym = "_OBJC_CLASS_"; 2352 Sym += StringClass; 2353 2354 llvm::Constant *isa = TheModule.getNamedGlobal(Sym); 2355 2356 if (!isa) 2357 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false, 2358 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym); 2359 else if (isa->getType() != PtrToIdTy) 2360 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy); 2361 2362 ConstantInitBuilder Builder(CGM); 2363 auto Fields = Builder.beginStruct(); 2364 Fields.add(isa); 2365 Fields.add(MakeConstantString(Str)); 2366 Fields.addInt(IntTy, Str.size()); 2367 llvm::Constant *ObjCStr = 2368 Fields.finishAndCreateGlobal(".objc_str", Align); 2369 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty); 2370 ObjCStrings[Str] = ObjCStr; 2371 ConstantStrings.push_back(ObjCStr); 2372 return ConstantAddress(ObjCStr, Align); 2373 } 2374 2375 ///Generates a message send where the super is the receiver. This is a message 2376 ///send to self with special delivery semantics indicating which class's method 2377 ///should be called. 2378 RValue 2379 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF, 2380 ReturnValueSlot Return, 2381 QualType ResultType, 2382 Selector Sel, 2383 const ObjCInterfaceDecl *Class, 2384 bool isCategoryImpl, 2385 llvm::Value *Receiver, 2386 bool IsClassMessage, 2387 const CallArgList &CallArgs, 2388 const ObjCMethodDecl *Method) { 2389 CGBuilderTy &Builder = CGF.Builder; 2390 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { 2391 if (Sel == RetainSel || Sel == AutoreleaseSel) { 2392 return RValue::get(EnforceType(Builder, Receiver, 2393 CGM.getTypes().ConvertType(ResultType))); 2394 } 2395 if (Sel == ReleaseSel) { 2396 return RValue::get(nullptr); 2397 } 2398 } 2399 2400 llvm::Value *cmd = GetSelector(CGF, Sel); 2401 CallArgList ActualArgs; 2402 2403 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy); 2404 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType()); 2405 ActualArgs.addFrom(CallArgs); 2406 2407 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs); 2408 2409 llvm::Value *ReceiverClass = nullptr; 2410 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2); 2411 if (isV2ABI) { 2412 ReceiverClass = GetClassNamed(CGF, 2413 Class->getSuperClass()->getNameAsString(), /*isWeak*/false); 2414 if (IsClassMessage) { 2415 // Load the isa pointer of the superclass is this is a class method. 2416 ReceiverClass = Builder.CreateBitCast(ReceiverClass, 2417 llvm::PointerType::getUnqual(IdTy)); 2418 ReceiverClass = 2419 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign()); 2420 } 2421 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy); 2422 } else { 2423 if (isCategoryImpl) { 2424 llvm::Constant *classLookupFunction = nullptr; 2425 if (IsClassMessage) { 2426 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 2427 IdTy, PtrTy, true), "objc_get_meta_class"); 2428 } else { 2429 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 2430 IdTy, PtrTy, true), "objc_get_class"); 2431 } 2432 ReceiverClass = Builder.CreateCall(classLookupFunction, 2433 MakeConstantString(Class->getNameAsString())); 2434 } else { 2435 // Set up global aliases for the metaclass or class pointer if they do not 2436 // already exist. These will are forward-references which will be set to 2437 // pointers to the class and metaclass structure created for the runtime 2438 // load function. To send a message to super, we look up the value of the 2439 // super_class pointer from either the class or metaclass structure. 2440 if (IsClassMessage) { 2441 if (!MetaClassPtrAlias) { 2442 MetaClassPtrAlias = llvm::GlobalAlias::create( 2443 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage, 2444 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule); 2445 } 2446 ReceiverClass = MetaClassPtrAlias; 2447 } else { 2448 if (!ClassPtrAlias) { 2449 ClassPtrAlias = llvm::GlobalAlias::create( 2450 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage, 2451 ".objc_class_ref" + Class->getNameAsString(), &TheModule); 2452 } 2453 ReceiverClass = ClassPtrAlias; 2454 } 2455 } 2456 // Cast the pointer to a simplified version of the class structure 2457 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy); 2458 ReceiverClass = Builder.CreateBitCast(ReceiverClass, 2459 llvm::PointerType::getUnqual(CastTy)); 2460 // Get the superclass pointer 2461 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1); 2462 // Load the superclass pointer 2463 ReceiverClass = 2464 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign()); 2465 } 2466 // Construct the structure used to look up the IMP 2467 llvm::StructType *ObjCSuperTy = 2468 llvm::StructType::get(Receiver->getType(), IdTy); 2469 2470 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy, 2471 CGF.getPointerAlign()); 2472 2473 Builder.CreateStore(Receiver, 2474 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero())); 2475 Builder.CreateStore(ReceiverClass, 2476 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize())); 2477 2478 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy); 2479 2480 // Get the IMP 2481 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI); 2482 imp = EnforceType(Builder, imp, MSI.MessengerType); 2483 2484 llvm::Metadata *impMD[] = { 2485 llvm::MDString::get(VMContext, Sel.getAsString()), 2486 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()), 2487 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 2488 llvm::Type::getInt1Ty(VMContext), IsClassMessage))}; 2489 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD); 2490 2491 CGCallee callee(CGCalleeInfo(), imp); 2492 2493 llvm::Instruction *call; 2494 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call); 2495 call->setMetadata(msgSendMDKind, node); 2496 return msgRet; 2497 } 2498 2499 /// Generate code for a message send expression. 2500 RValue 2501 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF, 2502 ReturnValueSlot Return, 2503 QualType ResultType, 2504 Selector Sel, 2505 llvm::Value *Receiver, 2506 const CallArgList &CallArgs, 2507 const ObjCInterfaceDecl *Class, 2508 const ObjCMethodDecl *Method) { 2509 CGBuilderTy &Builder = CGF.Builder; 2510 2511 // Strip out message sends to retain / release in GC mode 2512 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { 2513 if (Sel == RetainSel || Sel == AutoreleaseSel) { 2514 return RValue::get(EnforceType(Builder, Receiver, 2515 CGM.getTypes().ConvertType(ResultType))); 2516 } 2517 if (Sel == ReleaseSel) { 2518 return RValue::get(nullptr); 2519 } 2520 } 2521 2522 // If the return type is something that goes in an integer register, the 2523 // runtime will handle 0 returns. For other cases, we fill in the 0 value 2524 // ourselves. 2525 // 2526 // The language spec says the result of this kind of message send is 2527 // undefined, but lots of people seem to have forgotten to read that 2528 // paragraph and insist on sending messages to nil that have structure 2529 // returns. With GCC, this generates a random return value (whatever happens 2530 // to be on the stack / in those registers at the time) on most platforms, 2531 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts 2532 // the stack. 2533 bool isPointerSizedReturn = (ResultType->isAnyPointerType() || 2534 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType()); 2535 2536 llvm::BasicBlock *startBB = nullptr; 2537 llvm::BasicBlock *messageBB = nullptr; 2538 llvm::BasicBlock *continueBB = nullptr; 2539 2540 if (!isPointerSizedReturn) { 2541 startBB = Builder.GetInsertBlock(); 2542 messageBB = CGF.createBasicBlock("msgSend"); 2543 continueBB = CGF.createBasicBlock("continue"); 2544 2545 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, 2546 llvm::Constant::getNullValue(Receiver->getType())); 2547 Builder.CreateCondBr(isNil, continueBB, messageBB); 2548 CGF.EmitBlock(messageBB); 2549 } 2550 2551 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy)); 2552 llvm::Value *cmd; 2553 if (Method) 2554 cmd = GetSelector(CGF, Method); 2555 else 2556 cmd = GetSelector(CGF, Sel); 2557 cmd = EnforceType(Builder, cmd, SelectorTy); 2558 Receiver = EnforceType(Builder, Receiver, IdTy); 2559 2560 llvm::Metadata *impMD[] = { 2561 llvm::MDString::get(VMContext, Sel.getAsString()), 2562 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""), 2563 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 2564 llvm::Type::getInt1Ty(VMContext), Class != nullptr))}; 2565 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD); 2566 2567 CallArgList ActualArgs; 2568 ActualArgs.add(RValue::get(Receiver), ASTIdTy); 2569 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType()); 2570 ActualArgs.addFrom(CallArgs); 2571 2572 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs); 2573 2574 // Get the IMP to call 2575 llvm::Value *imp; 2576 2577 // If we have non-legacy dispatch specified, we try using the objc_msgSend() 2578 // functions. These are not supported on all platforms (or all runtimes on a 2579 // given platform), so we 2580 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) { 2581 case CodeGenOptions::Legacy: 2582 imp = LookupIMP(CGF, Receiver, cmd, node, MSI); 2583 break; 2584 case CodeGenOptions::Mixed: 2585 case CodeGenOptions::NonLegacy: 2586 if (CGM.ReturnTypeUsesFPRet(ResultType)) { 2587 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true), 2588 "objc_msgSend_fpret"); 2589 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) { 2590 // The actual types here don't matter - we're going to bitcast the 2591 // function anyway 2592 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true), 2593 "objc_msgSend_stret"); 2594 } else { 2595 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true), 2596 "objc_msgSend"); 2597 } 2598 } 2599 2600 // Reset the receiver in case the lookup modified it 2601 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy); 2602 2603 imp = EnforceType(Builder, imp, MSI.MessengerType); 2604 2605 llvm::Instruction *call; 2606 CGCallee callee(CGCalleeInfo(), imp); 2607 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call); 2608 call->setMetadata(msgSendMDKind, node); 2609 2610 2611 if (!isPointerSizedReturn) { 2612 messageBB = CGF.Builder.GetInsertBlock(); 2613 CGF.Builder.CreateBr(continueBB); 2614 CGF.EmitBlock(continueBB); 2615 if (msgRet.isScalar()) { 2616 llvm::Value *v = msgRet.getScalarVal(); 2617 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2); 2618 phi->addIncoming(v, messageBB); 2619 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB); 2620 msgRet = RValue::get(phi); 2621 } else if (msgRet.isAggregate()) { 2622 Address v = msgRet.getAggregateAddress(); 2623 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2); 2624 llvm::Type *RetTy = v.getElementType(); 2625 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null"); 2626 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy)); 2627 phi->addIncoming(v.getPointer(), messageBB); 2628 phi->addIncoming(NullVal.getPointer(), startBB); 2629 msgRet = RValue::getAggregate(Address(phi, v.getAlignment())); 2630 } else /* isComplex() */ { 2631 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal(); 2632 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2); 2633 phi->addIncoming(v.first, messageBB); 2634 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()), 2635 startBB); 2636 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2); 2637 phi2->addIncoming(v.second, messageBB); 2638 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()), 2639 startBB); 2640 msgRet = RValue::getComplex(phi, phi2); 2641 } 2642 } 2643 return msgRet; 2644 } 2645 2646 /// Generates a MethodList. Used in construction of a objc_class and 2647 /// objc_category structures. 2648 llvm::Constant *CGObjCGNU:: 2649 GenerateMethodList(StringRef ClassName, 2650 StringRef CategoryName, 2651 ArrayRef<const ObjCMethodDecl*> Methods, 2652 bool isClassMethodList) { 2653 if (Methods.empty()) 2654 return NULLPtr; 2655 2656 ConstantInitBuilder Builder(CGM); 2657 2658 auto MethodList = Builder.beginStruct(); 2659 MethodList.addNullPointer(CGM.Int8PtrTy); 2660 MethodList.addInt(Int32Ty, Methods.size()); 2661 2662 // Get the method structure type. 2663 llvm::StructType *ObjCMethodTy = 2664 llvm::StructType::get(CGM.getLLVMContext(), { 2665 PtrToInt8Ty, // Really a selector, but the runtime creates it us. 2666 PtrToInt8Ty, // Method types 2667 IMPTy // Method pointer 2668 }); 2669 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2); 2670 if (isV2ABI) { 2671 // size_t size; 2672 llvm::DataLayout td(&TheModule); 2673 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) / 2674 CGM.getContext().getCharWidth()); 2675 ObjCMethodTy = 2676 llvm::StructType::get(CGM.getLLVMContext(), { 2677 IMPTy, // Method pointer 2678 PtrToInt8Ty, // Selector 2679 PtrToInt8Ty // Extended type encoding 2680 }); 2681 } else { 2682 ObjCMethodTy = 2683 llvm::StructType::get(CGM.getLLVMContext(), { 2684 PtrToInt8Ty, // Really a selector, but the runtime creates it us. 2685 PtrToInt8Ty, // Method types 2686 IMPTy // Method pointer 2687 }); 2688 } 2689 auto MethodArray = MethodList.beginArray(); 2690 ASTContext &Context = CGM.getContext(); 2691 for (const auto *OMD : Methods) { 2692 llvm::Constant *FnPtr = 2693 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName, 2694 OMD->getSelector(), 2695 isClassMethodList)); 2696 assert(FnPtr && "Can't generate metadata for method that doesn't exist"); 2697 auto Method = MethodArray.beginStruct(ObjCMethodTy); 2698 if (isV2ABI) { 2699 Method.addBitCast(FnPtr, IMPTy); 2700 Method.add(GetConstantSelector(OMD->getSelector(), 2701 Context.getObjCEncodingForMethodDecl(OMD))); 2702 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true))); 2703 } else { 2704 Method.add(MakeConstantString(OMD->getSelector().getAsString())); 2705 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD))); 2706 Method.addBitCast(FnPtr, IMPTy); 2707 } 2708 Method.finishAndAddTo(MethodArray); 2709 } 2710 MethodArray.finishAndAddTo(MethodList); 2711 2712 // Create an instance of the structure 2713 return MethodList.finishAndCreateGlobal(".objc_method_list", 2714 CGM.getPointerAlign()); 2715 } 2716 2717 /// Generates an IvarList. Used in construction of a objc_class. 2718 llvm::Constant *CGObjCGNU:: 2719 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames, 2720 ArrayRef<llvm::Constant *> IvarTypes, 2721 ArrayRef<llvm::Constant *> IvarOffsets, 2722 ArrayRef<llvm::Constant *> IvarAlign, 2723 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) { 2724 if (IvarNames.empty()) 2725 return NULLPtr; 2726 2727 ConstantInitBuilder Builder(CGM); 2728 2729 // Structure containing array count followed by array. 2730 auto IvarList = Builder.beginStruct(); 2731 IvarList.addInt(IntTy, (int)IvarNames.size()); 2732 2733 // Get the ivar structure type. 2734 llvm::StructType *ObjCIvarTy = 2735 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy); 2736 2737 // Array of ivar structures. 2738 auto Ivars = IvarList.beginArray(ObjCIvarTy); 2739 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) { 2740 auto Ivar = Ivars.beginStruct(ObjCIvarTy); 2741 Ivar.add(IvarNames[i]); 2742 Ivar.add(IvarTypes[i]); 2743 Ivar.add(IvarOffsets[i]); 2744 Ivar.finishAndAddTo(Ivars); 2745 } 2746 Ivars.finishAndAddTo(IvarList); 2747 2748 // Create an instance of the structure 2749 return IvarList.finishAndCreateGlobal(".objc_ivar_list", 2750 CGM.getPointerAlign()); 2751 } 2752 2753 /// Generate a class structure 2754 llvm::Constant *CGObjCGNU::GenerateClassStructure( 2755 llvm::Constant *MetaClass, 2756 llvm::Constant *SuperClass, 2757 unsigned info, 2758 const char *Name, 2759 llvm::Constant *Version, 2760 llvm::Constant *InstanceSize, 2761 llvm::Constant *IVars, 2762 llvm::Constant *Methods, 2763 llvm::Constant *Protocols, 2764 llvm::Constant *IvarOffsets, 2765 llvm::Constant *Properties, 2766 llvm::Constant *StrongIvarBitmap, 2767 llvm::Constant *WeakIvarBitmap, 2768 bool isMeta) { 2769 // Set up the class structure 2770 // Note: Several of these are char*s when they should be ids. This is 2771 // because the runtime performs this translation on load. 2772 // 2773 // Fields marked New ABI are part of the GNUstep runtime. We emit them 2774 // anyway; the classes will still work with the GNU runtime, they will just 2775 // be ignored. 2776 llvm::StructType *ClassTy = llvm::StructType::get( 2777 PtrToInt8Ty, // isa 2778 PtrToInt8Ty, // super_class 2779 PtrToInt8Ty, // name 2780 LongTy, // version 2781 LongTy, // info 2782 LongTy, // instance_size 2783 IVars->getType(), // ivars 2784 Methods->getType(), // methods 2785 // These are all filled in by the runtime, so we pretend 2786 PtrTy, // dtable 2787 PtrTy, // subclass_list 2788 PtrTy, // sibling_class 2789 PtrTy, // protocols 2790 PtrTy, // gc_object_type 2791 // New ABI: 2792 LongTy, // abi_version 2793 IvarOffsets->getType(), // ivar_offsets 2794 Properties->getType(), // properties 2795 IntPtrTy, // strong_pointers 2796 IntPtrTy // weak_pointers 2797 ); 2798 2799 ConstantInitBuilder Builder(CGM); 2800 auto Elements = Builder.beginStruct(ClassTy); 2801 2802 // Fill in the structure 2803 2804 // isa 2805 Elements.addBitCast(MetaClass, PtrToInt8Ty); 2806 // super_class 2807 Elements.add(SuperClass); 2808 // name 2809 Elements.add(MakeConstantString(Name, ".class_name")); 2810 // version 2811 Elements.addInt(LongTy, 0); 2812 // info 2813 Elements.addInt(LongTy, info); 2814 // instance_size 2815 if (isMeta) { 2816 llvm::DataLayout td(&TheModule); 2817 Elements.addInt(LongTy, 2818 td.getTypeSizeInBits(ClassTy) / 2819 CGM.getContext().getCharWidth()); 2820 } else 2821 Elements.add(InstanceSize); 2822 // ivars 2823 Elements.add(IVars); 2824 // methods 2825 Elements.add(Methods); 2826 // These are all filled in by the runtime, so we pretend 2827 // dtable 2828 Elements.add(NULLPtr); 2829 // subclass_list 2830 Elements.add(NULLPtr); 2831 // sibling_class 2832 Elements.add(NULLPtr); 2833 // protocols 2834 Elements.addBitCast(Protocols, PtrTy); 2835 // gc_object_type 2836 Elements.add(NULLPtr); 2837 // abi_version 2838 Elements.addInt(LongTy, ClassABIVersion); 2839 // ivar_offsets 2840 Elements.add(IvarOffsets); 2841 // properties 2842 Elements.add(Properties); 2843 // strong_pointers 2844 Elements.add(StrongIvarBitmap); 2845 // weak_pointers 2846 Elements.add(WeakIvarBitmap); 2847 // Create an instance of the structure 2848 // This is now an externally visible symbol, so that we can speed up class 2849 // messages in the next ABI. We may already have some weak references to 2850 // this, so check and fix them properly. 2851 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") + 2852 std::string(Name)); 2853 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym); 2854 llvm::Constant *Class = 2855 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false, 2856 llvm::GlobalValue::ExternalLinkage); 2857 if (ClassRef) { 2858 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class, 2859 ClassRef->getType())); 2860 ClassRef->removeFromParent(); 2861 Class->setName(ClassSym); 2862 } 2863 return Class; 2864 } 2865 2866 llvm::Constant *CGObjCGNU:: 2867 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) { 2868 // Get the method structure type. 2869 llvm::StructType *ObjCMethodDescTy = 2870 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty }); 2871 ASTContext &Context = CGM.getContext(); 2872 ConstantInitBuilder Builder(CGM); 2873 auto MethodList = Builder.beginStruct(); 2874 MethodList.addInt(IntTy, Methods.size()); 2875 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy); 2876 for (auto *M : Methods) { 2877 auto Method = MethodArray.beginStruct(ObjCMethodDescTy); 2878 Method.add(MakeConstantString(M->getSelector().getAsString())); 2879 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M))); 2880 Method.finishAndAddTo(MethodArray); 2881 } 2882 MethodArray.finishAndAddTo(MethodList); 2883 return MethodList.finishAndCreateGlobal(".objc_method_list", 2884 CGM.getPointerAlign()); 2885 } 2886 2887 // Create the protocol list structure used in classes, categories and so on 2888 llvm::Constant * 2889 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) { 2890 2891 ConstantInitBuilder Builder(CGM); 2892 auto ProtocolList = Builder.beginStruct(); 2893 ProtocolList.add(NULLPtr); 2894 ProtocolList.addInt(LongTy, Protocols.size()); 2895 2896 auto Elements = ProtocolList.beginArray(PtrToInt8Ty); 2897 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end(); 2898 iter != endIter ; iter++) { 2899 llvm::Constant *protocol = nullptr; 2900 llvm::StringMap<llvm::Constant*>::iterator value = 2901 ExistingProtocols.find(*iter); 2902 if (value == ExistingProtocols.end()) { 2903 protocol = GenerateEmptyProtocol(*iter); 2904 } else { 2905 protocol = value->getValue(); 2906 } 2907 Elements.addBitCast(protocol, PtrToInt8Ty); 2908 } 2909 Elements.finishAndAddTo(ProtocolList); 2910 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list", 2911 CGM.getPointerAlign()); 2912 } 2913 2914 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF, 2915 const ObjCProtocolDecl *PD) { 2916 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()]; 2917 if (!protocol) 2918 GenerateProtocol(PD); 2919 llvm::Type *T = 2920 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType()); 2921 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T)); 2922 } 2923 2924 llvm::Constant * 2925 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) { 2926 llvm::Constant *ProtocolList = GenerateProtocolList({}); 2927 llvm::Constant *MethodList = GenerateProtocolMethodList({}); 2928 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty); 2929 // Protocols are objects containing lists of the methods implemented and 2930 // protocols adopted. 2931 ConstantInitBuilder Builder(CGM); 2932 auto Elements = Builder.beginStruct(); 2933 2934 // The isa pointer must be set to a magic number so the runtime knows it's 2935 // the correct layout. 2936 Elements.add(llvm::ConstantExpr::getIntToPtr( 2937 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy)); 2938 2939 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name")); 2940 Elements.add(ProtocolList); /* .protocol_list */ 2941 Elements.add(MethodList); /* .instance_methods */ 2942 Elements.add(MethodList); /* .class_methods */ 2943 Elements.add(MethodList); /* .optional_instance_methods */ 2944 Elements.add(MethodList); /* .optional_class_methods */ 2945 Elements.add(NULLPtr); /* .properties */ 2946 Elements.add(NULLPtr); /* .optional_properties */ 2947 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName), 2948 CGM.getPointerAlign()); 2949 } 2950 2951 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { 2952 std::string ProtocolName = PD->getNameAsString(); 2953 2954 // Use the protocol definition, if there is one. 2955 if (const ObjCProtocolDecl *Def = PD->getDefinition()) 2956 PD = Def; 2957 2958 SmallVector<std::string, 16> Protocols; 2959 for (const auto *PI : PD->protocols()) 2960 Protocols.push_back(PI->getNameAsString()); 2961 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods; 2962 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods; 2963 for (const auto *I : PD->instance_methods()) 2964 if (I->isOptional()) 2965 OptionalInstanceMethods.push_back(I); 2966 else 2967 InstanceMethods.push_back(I); 2968 // Collect information about class methods: 2969 SmallVector<const ObjCMethodDecl*, 16> ClassMethods; 2970 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods; 2971 for (const auto *I : PD->class_methods()) 2972 if (I->isOptional()) 2973 OptionalClassMethods.push_back(I); 2974 else 2975 ClassMethods.push_back(I); 2976 2977 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols); 2978 llvm::Constant *InstanceMethodList = 2979 GenerateProtocolMethodList(InstanceMethods); 2980 llvm::Constant *ClassMethodList = 2981 GenerateProtocolMethodList(ClassMethods); 2982 llvm::Constant *OptionalInstanceMethodList = 2983 GenerateProtocolMethodList(OptionalInstanceMethods); 2984 llvm::Constant *OptionalClassMethodList = 2985 GenerateProtocolMethodList(OptionalClassMethods); 2986 2987 // Property metadata: name, attributes, isSynthesized, setter name, setter 2988 // types, getter name, getter types. 2989 // The isSynthesized value is always set to 0 in a protocol. It exists to 2990 // simplify the runtime library by allowing it to use the same data 2991 // structures for protocol metadata everywhere. 2992 2993 llvm::Constant *PropertyList = 2994 GeneratePropertyList(nullptr, PD, false, false); 2995 llvm::Constant *OptionalPropertyList = 2996 GeneratePropertyList(nullptr, PD, false, true); 2997 2998 // Protocols are objects containing lists of the methods implemented and 2999 // protocols adopted. 3000 // The isa pointer must be set to a magic number so the runtime knows it's 3001 // the correct layout. 3002 ConstantInitBuilder Builder(CGM); 3003 auto Elements = Builder.beginStruct(); 3004 Elements.add( 3005 llvm::ConstantExpr::getIntToPtr( 3006 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy)); 3007 Elements.add(MakeConstantString(ProtocolName)); 3008 Elements.add(ProtocolList); 3009 Elements.add(InstanceMethodList); 3010 Elements.add(ClassMethodList); 3011 Elements.add(OptionalInstanceMethodList); 3012 Elements.add(OptionalClassMethodList); 3013 Elements.add(PropertyList); 3014 Elements.add(OptionalPropertyList); 3015 ExistingProtocols[ProtocolName] = 3016 llvm::ConstantExpr::getBitCast( 3017 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()), 3018 IdTy); 3019 } 3020 void CGObjCGNU::GenerateProtocolHolderCategory() { 3021 // Collect information about instance methods 3022 3023 ConstantInitBuilder Builder(CGM); 3024 auto Elements = Builder.beginStruct(); 3025 3026 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack"; 3027 const std::string CategoryName = "AnotherHack"; 3028 Elements.add(MakeConstantString(CategoryName)); 3029 Elements.add(MakeConstantString(ClassName)); 3030 // Instance method list 3031 Elements.addBitCast(GenerateMethodList( 3032 ClassName, CategoryName, {}, false), PtrTy); 3033 // Class method list 3034 Elements.addBitCast(GenerateMethodList( 3035 ClassName, CategoryName, {}, true), PtrTy); 3036 3037 // Protocol list 3038 ConstantInitBuilder ProtocolListBuilder(CGM); 3039 auto ProtocolList = ProtocolListBuilder.beginStruct(); 3040 ProtocolList.add(NULLPtr); 3041 ProtocolList.addInt(LongTy, ExistingProtocols.size()); 3042 auto ProtocolElements = ProtocolList.beginArray(PtrTy); 3043 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end(); 3044 iter != endIter ; iter++) { 3045 ProtocolElements.addBitCast(iter->getValue(), PtrTy); 3046 } 3047 ProtocolElements.finishAndAddTo(ProtocolList); 3048 Elements.addBitCast( 3049 ProtocolList.finishAndCreateGlobal(".objc_protocol_list", 3050 CGM.getPointerAlign()), 3051 PtrTy); 3052 Categories.push_back(llvm::ConstantExpr::getBitCast( 3053 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()), 3054 PtrTy)); 3055 } 3056 3057 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are 3058 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63 3059 /// bits set to their values, LSB first, while larger ones are stored in a 3060 /// structure of this / form: 3061 /// 3062 /// struct { int32_t length; int32_t values[length]; }; 3063 /// 3064 /// The values in the array are stored in host-endian format, with the least 3065 /// significant bit being assumed to come first in the bitfield. Therefore, a 3066 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a 3067 /// bitfield / with the 63rd bit set will be 1<<64. 3068 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) { 3069 int bitCount = bits.size(); 3070 int ptrBits = CGM.getDataLayout().getPointerSizeInBits(); 3071 if (bitCount < ptrBits) { 3072 uint64_t val = 1; 3073 for (int i=0 ; i<bitCount ; ++i) { 3074 if (bits[i]) val |= 1ULL<<(i+1); 3075 } 3076 return llvm::ConstantInt::get(IntPtrTy, val); 3077 } 3078 SmallVector<llvm::Constant *, 8> values; 3079 int v=0; 3080 while (v < bitCount) { 3081 int32_t word = 0; 3082 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) { 3083 if (bits[v]) word |= 1<<i; 3084 v++; 3085 } 3086 values.push_back(llvm::ConstantInt::get(Int32Ty, word)); 3087 } 3088 3089 ConstantInitBuilder builder(CGM); 3090 auto fields = builder.beginStruct(); 3091 fields.addInt(Int32Ty, values.size()); 3092 auto array = fields.beginArray(); 3093 for (auto v : values) array.add(v); 3094 array.finishAndAddTo(fields); 3095 3096 llvm::Constant *GS = 3097 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4)); 3098 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy); 3099 return ptr; 3100 } 3101 3102 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 3103 const ObjCInterfaceDecl *Class = OCD->getClassInterface(); 3104 std::string ClassName = Class->getNameAsString(); 3105 std::string CategoryName = OCD->getNameAsString(); 3106 3107 // Collect the names of referenced protocols 3108 SmallVector<std::string, 16> Protocols; 3109 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl(); 3110 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols(); 3111 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(), 3112 E = Protos.end(); I != E; ++I) 3113 Protocols.push_back((*I)->getNameAsString()); 3114 3115 ConstantInitBuilder Builder(CGM); 3116 auto Elements = Builder.beginStruct(); 3117 Elements.add(MakeConstantString(CategoryName)); 3118 Elements.add(MakeConstantString(ClassName)); 3119 // Instance method list 3120 SmallVector<ObjCMethodDecl*, 16> InstanceMethods; 3121 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(), 3122 OCD->instmeth_end()); 3123 Elements.addBitCast( 3124 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false), 3125 PtrTy); 3126 // Class method list 3127 3128 SmallVector<ObjCMethodDecl*, 16> ClassMethods; 3129 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(), 3130 OCD->classmeth_end()); 3131 Elements.addBitCast( 3132 GenerateMethodList(ClassName, CategoryName, ClassMethods, true), 3133 PtrTy); 3134 // Protocol list 3135 Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy); 3136 if (isRuntime(ObjCRuntime::GNUstep, 2)) { 3137 const ObjCCategoryDecl *Category = 3138 Class->FindCategoryDeclaration(OCD->getIdentifier()); 3139 if (Category) { 3140 // Instance properties 3141 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy); 3142 // Class properties 3143 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy); 3144 } else { 3145 Elements.addNullPointer(PtrTy); 3146 Elements.addNullPointer(PtrTy); 3147 } 3148 } 3149 3150 Categories.push_back(llvm::ConstantExpr::getBitCast( 3151 Elements.finishAndCreateGlobal( 3152 std::string(".objc_category_")+ClassName+CategoryName, 3153 CGM.getPointerAlign()), 3154 PtrTy)); 3155 } 3156 3157 llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container, 3158 const ObjCContainerDecl *OCD, 3159 bool isClassProperty, 3160 bool protocolOptionalProperties) { 3161 3162 SmallVector<const ObjCPropertyDecl *, 16> Properties; 3163 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet; 3164 bool isProtocol = isa<ObjCProtocolDecl>(OCD); 3165 ASTContext &Context = CGM.getContext(); 3166 3167 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties 3168 = [&](const ObjCProtocolDecl *Proto) { 3169 for (const auto *P : Proto->protocols()) 3170 collectProtocolProperties(P); 3171 for (const auto *PD : Proto->properties()) { 3172 if (isClassProperty != PD->isClassProperty()) 3173 continue; 3174 // Skip any properties that are declared in protocols that this class 3175 // conforms to but are not actually implemented by this class. 3176 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container)) 3177 continue; 3178 if (!PropertySet.insert(PD->getIdentifier()).second) 3179 continue; 3180 Properties.push_back(PD); 3181 } 3182 }; 3183 3184 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) 3185 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions()) 3186 for (auto *PD : ClassExt->properties()) { 3187 if (isClassProperty != PD->isClassProperty()) 3188 continue; 3189 PropertySet.insert(PD->getIdentifier()); 3190 Properties.push_back(PD); 3191 } 3192 3193 for (const auto *PD : OCD->properties()) { 3194 if (isClassProperty != PD->isClassProperty()) 3195 continue; 3196 // If we're generating a list for a protocol, skip optional / required ones 3197 // when generating the other list. 3198 if (isProtocol && (protocolOptionalProperties != PD->isOptional())) 3199 continue; 3200 // Don't emit duplicate metadata for properties that were already in a 3201 // class extension. 3202 if (!PropertySet.insert(PD->getIdentifier()).second) 3203 continue; 3204 3205 Properties.push_back(PD); 3206 } 3207 3208 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) 3209 for (const auto *P : OID->all_referenced_protocols()) 3210 collectProtocolProperties(P); 3211 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) 3212 for (const auto *P : CD->protocols()) 3213 collectProtocolProperties(P); 3214 3215 auto numProperties = Properties.size(); 3216 3217 if (numProperties == 0) 3218 return NULLPtr; 3219 3220 ConstantInitBuilder builder(CGM); 3221 auto propertyList = builder.beginStruct(); 3222 auto properties = PushPropertyListHeader(propertyList, numProperties); 3223 3224 // Add all of the property methods need adding to the method list and to the 3225 // property metadata list. 3226 for (auto *property : Properties) { 3227 bool isSynthesized = false; 3228 bool isDynamic = false; 3229 if (!isProtocol) { 3230 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container); 3231 if (propertyImpl) { 3232 isSynthesized = (propertyImpl->getPropertyImplementation() == 3233 ObjCPropertyImplDecl::Synthesize); 3234 isDynamic = (propertyImpl->getPropertyImplementation() == 3235 ObjCPropertyImplDecl::Dynamic); 3236 } 3237 } 3238 PushProperty(properties, property, Container, isSynthesized, isDynamic); 3239 } 3240 properties.finishAndAddTo(propertyList); 3241 3242 return propertyList.finishAndCreateGlobal(".objc_property_list", 3243 CGM.getPointerAlign()); 3244 } 3245 3246 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) { 3247 // Get the class declaration for which the alias is specified. 3248 ObjCInterfaceDecl *ClassDecl = 3249 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface()); 3250 ClassAliases.emplace_back(ClassDecl->getNameAsString(), 3251 OAD->getNameAsString()); 3252 } 3253 3254 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { 3255 ASTContext &Context = CGM.getContext(); 3256 3257 // Get the superclass name. 3258 const ObjCInterfaceDecl * SuperClassDecl = 3259 OID->getClassInterface()->getSuperClass(); 3260 std::string SuperClassName; 3261 if (SuperClassDecl) { 3262 SuperClassName = SuperClassDecl->getNameAsString(); 3263 EmitClassRef(SuperClassName); 3264 } 3265 3266 // Get the class name 3267 ObjCInterfaceDecl *ClassDecl = 3268 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface()); 3269 std::string ClassName = ClassDecl->getNameAsString(); 3270 3271 // Emit the symbol that is used to generate linker errors if this class is 3272 // referenced in other modules but not declared. 3273 std::string classSymbolName = "__objc_class_name_" + ClassName; 3274 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) { 3275 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0)); 3276 } else { 3277 new llvm::GlobalVariable(TheModule, LongTy, false, 3278 llvm::GlobalValue::ExternalLinkage, 3279 llvm::ConstantInt::get(LongTy, 0), 3280 classSymbolName); 3281 } 3282 3283 // Get the size of instances. 3284 int instanceSize = 3285 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity(); 3286 3287 // Collect information about instance variables. 3288 SmallVector<llvm::Constant*, 16> IvarNames; 3289 SmallVector<llvm::Constant*, 16> IvarTypes; 3290 SmallVector<llvm::Constant*, 16> IvarOffsets; 3291 SmallVector<llvm::Constant*, 16> IvarAligns; 3292 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership; 3293 3294 ConstantInitBuilder IvarOffsetBuilder(CGM); 3295 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy); 3296 SmallVector<bool, 16> WeakIvars; 3297 SmallVector<bool, 16> StrongIvars; 3298 3299 int superInstanceSize = !SuperClassDecl ? 0 : 3300 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity(); 3301 // For non-fragile ivars, set the instance size to 0 - {the size of just this 3302 // class}. The runtime will then set this to the correct value on load. 3303 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 3304 instanceSize = 0 - (instanceSize - superInstanceSize); 3305 } 3306 3307 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD; 3308 IVD = IVD->getNextIvar()) { 3309 // Store the name 3310 IvarNames.push_back(MakeConstantString(IVD->getNameAsString())); 3311 // Get the type encoding for this ivar 3312 std::string TypeStr; 3313 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD); 3314 IvarTypes.push_back(MakeConstantString(TypeStr)); 3315 IvarAligns.push_back(llvm::ConstantInt::get(IntTy, 3316 Context.getTypeSize(IVD->getType()))); 3317 // Get the offset 3318 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD); 3319 uint64_t Offset = BaseOffset; 3320 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 3321 Offset = BaseOffset - superInstanceSize; 3322 } 3323 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset); 3324 // Create the direct offset value 3325 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." + 3326 IVD->getNameAsString(); 3327 3328 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName); 3329 if (OffsetVar) { 3330 OffsetVar->setInitializer(OffsetValue); 3331 // If this is the real definition, change its linkage type so that 3332 // different modules will use this one, rather than their private 3333 // copy. 3334 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage); 3335 } else 3336 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty, 3337 false, llvm::GlobalValue::ExternalLinkage, 3338 OffsetValue, OffsetName); 3339 IvarOffsets.push_back(OffsetValue); 3340 IvarOffsetValues.add(OffsetVar); 3341 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime(); 3342 IvarOwnership.push_back(lt); 3343 switch (lt) { 3344 case Qualifiers::OCL_Strong: 3345 StrongIvars.push_back(true); 3346 WeakIvars.push_back(false); 3347 break; 3348 case Qualifiers::OCL_Weak: 3349 StrongIvars.push_back(false); 3350 WeakIvars.push_back(true); 3351 break; 3352 default: 3353 StrongIvars.push_back(false); 3354 WeakIvars.push_back(false); 3355 } 3356 } 3357 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars); 3358 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars); 3359 llvm::GlobalVariable *IvarOffsetArray = 3360 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets", 3361 CGM.getPointerAlign()); 3362 3363 // Collect information about instance methods 3364 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods; 3365 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(), 3366 OID->instmeth_end()); 3367 3368 SmallVector<const ObjCMethodDecl*, 16> ClassMethods; 3369 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(), 3370 OID->classmeth_end()); 3371 3372 // Collect the same information about synthesized properties, which don't 3373 // show up in the instance method lists. 3374 for (auto *propertyImpl : OID->property_impls()) 3375 if (propertyImpl->getPropertyImplementation() == 3376 ObjCPropertyImplDecl::Synthesize) { 3377 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl(); 3378 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) { 3379 if (accessor) 3380 InstanceMethods.push_back(accessor); 3381 }; 3382 addPropertyMethod(property->getGetterMethodDecl()); 3383 addPropertyMethod(property->getSetterMethodDecl()); 3384 } 3385 3386 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl); 3387 3388 // Collect the names of referenced protocols 3389 SmallVector<std::string, 16> Protocols; 3390 for (const auto *I : ClassDecl->protocols()) 3391 Protocols.push_back(I->getNameAsString()); 3392 3393 // Get the superclass pointer. 3394 llvm::Constant *SuperClass; 3395 if (!SuperClassName.empty()) { 3396 SuperClass = MakeConstantString(SuperClassName, ".super_class_name"); 3397 } else { 3398 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty); 3399 } 3400 // Empty vector used to construct empty method lists 3401 SmallVector<llvm::Constant*, 1> empty; 3402 // Generate the method and instance variable lists 3403 llvm::Constant *MethodList = GenerateMethodList(ClassName, "", 3404 InstanceMethods, false); 3405 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "", 3406 ClassMethods, true); 3407 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes, 3408 IvarOffsets, IvarAligns, IvarOwnership); 3409 // Irrespective of whether we are compiling for a fragile or non-fragile ABI, 3410 // we emit a symbol containing the offset for each ivar in the class. This 3411 // allows code compiled for the non-Fragile ABI to inherit from code compiled 3412 // for the legacy ABI, without causing problems. The converse is also 3413 // possible, but causes all ivar accesses to be fragile. 3414 3415 // Offset pointer for getting at the correct field in the ivar list when 3416 // setting up the alias. These are: The base address for the global, the 3417 // ivar array (second field), the ivar in this list (set for each ivar), and 3418 // the offset (third field in ivar structure) 3419 llvm::Type *IndexTy = Int32Ty; 3420 llvm::Constant *offsetPointerIndexes[] = {Zeros[0], 3421 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr, 3422 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) }; 3423 3424 unsigned ivarIndex = 0; 3425 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD; 3426 IVD = IVD->getNextIvar()) { 3427 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD); 3428 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex); 3429 // Get the correct ivar field 3430 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr( 3431 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList, 3432 offsetPointerIndexes); 3433 // Get the existing variable, if one exists. 3434 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name); 3435 if (offset) { 3436 offset->setInitializer(offsetValue); 3437 // If this is the real definition, change its linkage type so that 3438 // different modules will use this one, rather than their private 3439 // copy. 3440 offset->setLinkage(llvm::GlobalValue::ExternalLinkage); 3441 } else 3442 // Add a new alias if there isn't one already. 3443 new llvm::GlobalVariable(TheModule, offsetValue->getType(), 3444 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name); 3445 ++ivarIndex; 3446 } 3447 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0); 3448 3449 //Generate metaclass for class methods 3450 llvm::Constant *MetaClassStruct = GenerateClassStructure( 3451 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], 3452 NULLPtr, ClassMethodList, NULLPtr, NULLPtr, 3453 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true); 3454 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct), 3455 OID->getClassInterface()); 3456 3457 // Generate the class structure 3458 llvm::Constant *ClassStruct = GenerateClassStructure( 3459 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr, 3460 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList, 3461 GenerateProtocolList(Protocols), IvarOffsetArray, Properties, 3462 StrongIvarBitmap, WeakIvarBitmap); 3463 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct), 3464 OID->getClassInterface()); 3465 3466 // Resolve the class aliases, if they exist. 3467 if (ClassPtrAlias) { 3468 ClassPtrAlias->replaceAllUsesWith( 3469 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy)); 3470 ClassPtrAlias->eraseFromParent(); 3471 ClassPtrAlias = nullptr; 3472 } 3473 if (MetaClassPtrAlias) { 3474 MetaClassPtrAlias->replaceAllUsesWith( 3475 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy)); 3476 MetaClassPtrAlias->eraseFromParent(); 3477 MetaClassPtrAlias = nullptr; 3478 } 3479 3480 // Add class structure to list to be added to the symtab later 3481 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty); 3482 Classes.push_back(ClassStruct); 3483 } 3484 3485 llvm::Function *CGObjCGNU::ModuleInitFunction() { 3486 // Only emit an ObjC load function if no Objective-C stuff has been called 3487 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() && 3488 ExistingProtocols.empty() && SelectorTable.empty()) 3489 return nullptr; 3490 3491 // Add all referenced protocols to a category. 3492 GenerateProtocolHolderCategory(); 3493 3494 llvm::StructType *selStructTy = 3495 dyn_cast<llvm::StructType>(SelectorTy->getElementType()); 3496 llvm::Type *selStructPtrTy = SelectorTy; 3497 if (!selStructTy) { 3498 selStructTy = llvm::StructType::get(CGM.getLLVMContext(), 3499 { PtrToInt8Ty, PtrToInt8Ty }); 3500 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy); 3501 } 3502 3503 // Generate statics list: 3504 llvm::Constant *statics = NULLPtr; 3505 if (!ConstantStrings.empty()) { 3506 llvm::GlobalVariable *fileStatics = [&] { 3507 ConstantInitBuilder builder(CGM); 3508 auto staticsStruct = builder.beginStruct(); 3509 3510 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass; 3511 if (stringClass.empty()) stringClass = "NXConstantString"; 3512 staticsStruct.add(MakeConstantString(stringClass, 3513 ".objc_static_class_name")); 3514 3515 auto array = staticsStruct.beginArray(); 3516 array.addAll(ConstantStrings); 3517 array.add(NULLPtr); 3518 array.finishAndAddTo(staticsStruct); 3519 3520 return staticsStruct.finishAndCreateGlobal(".objc_statics", 3521 CGM.getPointerAlign()); 3522 }(); 3523 3524 ConstantInitBuilder builder(CGM); 3525 auto allStaticsArray = builder.beginArray(fileStatics->getType()); 3526 allStaticsArray.add(fileStatics); 3527 allStaticsArray.addNullPointer(fileStatics->getType()); 3528 3529 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr", 3530 CGM.getPointerAlign()); 3531 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy); 3532 } 3533 3534 // Array of classes, categories, and constant objects. 3535 3536 SmallVector<llvm::GlobalAlias*, 16> selectorAliases; 3537 unsigned selectorCount; 3538 3539 // Pointer to an array of selectors used in this module. 3540 llvm::GlobalVariable *selectorList = [&] { 3541 ConstantInitBuilder builder(CGM); 3542 auto selectors = builder.beginArray(selStructTy); 3543 auto &table = SelectorTable; // MSVC workaround 3544 std::vector<Selector> allSelectors; 3545 for (auto &entry : table) 3546 allSelectors.push_back(entry.first); 3547 llvm::sort(allSelectors); 3548 3549 for (auto &untypedSel : allSelectors) { 3550 std::string selNameStr = untypedSel.getAsString(); 3551 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name"); 3552 3553 for (TypedSelector &sel : table[untypedSel]) { 3554 llvm::Constant *selectorTypeEncoding = NULLPtr; 3555 if (!sel.first.empty()) 3556 selectorTypeEncoding = 3557 MakeConstantString(sel.first, ".objc_sel_types"); 3558 3559 auto selStruct = selectors.beginStruct(selStructTy); 3560 selStruct.add(selName); 3561 selStruct.add(selectorTypeEncoding); 3562 selStruct.finishAndAddTo(selectors); 3563 3564 // Store the selector alias for later replacement 3565 selectorAliases.push_back(sel.second); 3566 } 3567 } 3568 3569 // Remember the number of entries in the selector table. 3570 selectorCount = selectors.size(); 3571 3572 // NULL-terminate the selector list. This should not actually be required, 3573 // because the selector list has a length field. Unfortunately, the GCC 3574 // runtime decides to ignore the length field and expects a NULL terminator, 3575 // and GCC cooperates with this by always setting the length to 0. 3576 auto selStruct = selectors.beginStruct(selStructTy); 3577 selStruct.add(NULLPtr); 3578 selStruct.add(NULLPtr); 3579 selStruct.finishAndAddTo(selectors); 3580 3581 return selectors.finishAndCreateGlobal(".objc_selector_list", 3582 CGM.getPointerAlign()); 3583 }(); 3584 3585 // Now that all of the static selectors exist, create pointers to them. 3586 for (unsigned i = 0; i < selectorCount; ++i) { 3587 llvm::Constant *idxs[] = { 3588 Zeros[0], 3589 llvm::ConstantInt::get(Int32Ty, i) 3590 }; 3591 // FIXME: We're generating redundant loads and stores here! 3592 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr( 3593 selectorList->getValueType(), selectorList, idxs); 3594 // If selectors are defined as an opaque type, cast the pointer to this 3595 // type. 3596 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy); 3597 selectorAliases[i]->replaceAllUsesWith(selPtr); 3598 selectorAliases[i]->eraseFromParent(); 3599 } 3600 3601 llvm::GlobalVariable *symtab = [&] { 3602 ConstantInitBuilder builder(CGM); 3603 auto symtab = builder.beginStruct(); 3604 3605 // Number of static selectors 3606 symtab.addInt(LongTy, selectorCount); 3607 3608 symtab.addBitCast(selectorList, selStructPtrTy); 3609 3610 // Number of classes defined. 3611 symtab.addInt(CGM.Int16Ty, Classes.size()); 3612 // Number of categories defined 3613 symtab.addInt(CGM.Int16Ty, Categories.size()); 3614 3615 // Create an array of classes, then categories, then static object instances 3616 auto classList = symtab.beginArray(PtrToInt8Ty); 3617 classList.addAll(Classes); 3618 classList.addAll(Categories); 3619 // NULL-terminated list of static object instances (mainly constant strings) 3620 classList.add(statics); 3621 classList.add(NULLPtr); 3622 classList.finishAndAddTo(symtab); 3623 3624 // Construct the symbol table. 3625 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign()); 3626 }(); 3627 3628 // The symbol table is contained in a module which has some version-checking 3629 // constants 3630 llvm::Constant *module = [&] { 3631 llvm::Type *moduleEltTys[] = { 3632 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy 3633 }; 3634 llvm::StructType *moduleTy = 3635 llvm::StructType::get(CGM.getLLVMContext(), 3636 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10))); 3637 3638 ConstantInitBuilder builder(CGM); 3639 auto module = builder.beginStruct(moduleTy); 3640 // Runtime version, used for ABI compatibility checking. 3641 module.addInt(LongTy, RuntimeVersion); 3642 // sizeof(ModuleTy) 3643 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy)); 3644 3645 // The path to the source file where this module was declared 3646 SourceManager &SM = CGM.getContext().getSourceManager(); 3647 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID()); 3648 std::string path = 3649 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str(); 3650 module.add(MakeConstantString(path, ".objc_source_file_name")); 3651 module.add(symtab); 3652 3653 if (RuntimeVersion >= 10) { 3654 switch (CGM.getLangOpts().getGC()) { 3655 case LangOptions::GCOnly: 3656 module.addInt(IntTy, 2); 3657 break; 3658 case LangOptions::NonGC: 3659 if (CGM.getLangOpts().ObjCAutoRefCount) 3660 module.addInt(IntTy, 1); 3661 else 3662 module.addInt(IntTy, 0); 3663 break; 3664 case LangOptions::HybridGC: 3665 module.addInt(IntTy, 1); 3666 break; 3667 } 3668 } 3669 3670 return module.finishAndCreateGlobal("", CGM.getPointerAlign()); 3671 }(); 3672 3673 // Create the load function calling the runtime entry point with the module 3674 // structure 3675 llvm::Function * LoadFunction = llvm::Function::Create( 3676 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false), 3677 llvm::GlobalValue::InternalLinkage, ".objc_load_function", 3678 &TheModule); 3679 llvm::BasicBlock *EntryBB = 3680 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction); 3681 CGBuilderTy Builder(CGM, VMContext); 3682 Builder.SetInsertPoint(EntryBB); 3683 3684 llvm::FunctionType *FT = 3685 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true); 3686 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class"); 3687 Builder.CreateCall(Register, module); 3688 3689 if (!ClassAliases.empty()) { 3690 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty}; 3691 llvm::FunctionType *RegisterAliasTy = 3692 llvm::FunctionType::get(Builder.getVoidTy(), 3693 ArgTypes, false); 3694 llvm::Function *RegisterAlias = llvm::Function::Create( 3695 RegisterAliasTy, 3696 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np", 3697 &TheModule); 3698 llvm::BasicBlock *AliasBB = 3699 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction); 3700 llvm::BasicBlock *NoAliasBB = 3701 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction); 3702 3703 // Branch based on whether the runtime provided class_registerAlias_np() 3704 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias, 3705 llvm::Constant::getNullValue(RegisterAlias->getType())); 3706 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB); 3707 3708 // The true branch (has alias registration function): 3709 Builder.SetInsertPoint(AliasBB); 3710 // Emit alias registration calls: 3711 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin(); 3712 iter != ClassAliases.end(); ++iter) { 3713 llvm::Constant *TheClass = 3714 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true); 3715 if (TheClass) { 3716 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy); 3717 Builder.CreateCall(RegisterAlias, 3718 {TheClass, MakeConstantString(iter->second)}); 3719 } 3720 } 3721 // Jump to end: 3722 Builder.CreateBr(NoAliasBB); 3723 3724 // Missing alias registration function, just return from the function: 3725 Builder.SetInsertPoint(NoAliasBB); 3726 } 3727 Builder.CreateRetVoid(); 3728 3729 return LoadFunction; 3730 } 3731 3732 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD, 3733 const ObjCContainerDecl *CD) { 3734 const ObjCCategoryImplDecl *OCD = 3735 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext()); 3736 StringRef CategoryName = OCD ? OCD->getName() : ""; 3737 StringRef ClassName = CD->getName(); 3738 Selector MethodName = OMD->getSelector(); 3739 bool isClassMethod = !OMD->isInstanceMethod(); 3740 3741 CodeGenTypes &Types = CGM.getTypes(); 3742 llvm::FunctionType *MethodTy = 3743 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD)); 3744 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName, 3745 MethodName, isClassMethod); 3746 3747 llvm::Function *Method 3748 = llvm::Function::Create(MethodTy, 3749 llvm::GlobalValue::InternalLinkage, 3750 FunctionName, 3751 &TheModule); 3752 return Method; 3753 } 3754 3755 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() { 3756 return GetPropertyFn; 3757 } 3758 3759 llvm::Constant *CGObjCGNU::GetPropertySetFunction() { 3760 return SetPropertyFn; 3761 } 3762 3763 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic, 3764 bool copy) { 3765 return nullptr; 3766 } 3767 3768 llvm::Constant *CGObjCGNU::GetGetStructFunction() { 3769 return GetStructPropertyFn; 3770 } 3771 3772 llvm::Constant *CGObjCGNU::GetSetStructFunction() { 3773 return SetStructPropertyFn; 3774 } 3775 3776 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() { 3777 return nullptr; 3778 } 3779 3780 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() { 3781 return nullptr; 3782 } 3783 3784 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() { 3785 return EnumerationMutationFn; 3786 } 3787 3788 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF, 3789 const ObjCAtSynchronizedStmt &S) { 3790 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn); 3791 } 3792 3793 3794 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF, 3795 const ObjCAtTryStmt &S) { 3796 // Unlike the Apple non-fragile runtimes, which also uses 3797 // unwind-based zero cost exceptions, the GNU Objective C runtime's 3798 // EH support isn't a veneer over C++ EH. Instead, exception 3799 // objects are created by objc_exception_throw and destroyed by 3800 // the personality function; this avoids the need for bracketing 3801 // catch handlers with calls to __blah_begin_catch/__blah_end_catch 3802 // (or even _Unwind_DeleteException), but probably doesn't 3803 // interoperate very well with foreign exceptions. 3804 // 3805 // In Objective-C++ mode, we actually emit something equivalent to the C++ 3806 // exception handler. 3807 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn); 3808 } 3809 3810 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF, 3811 const ObjCAtThrowStmt &S, 3812 bool ClearInsertionPoint) { 3813 llvm::Value *ExceptionAsObject; 3814 bool isRethrow = false; 3815 3816 if (const Expr *ThrowExpr = S.getThrowExpr()) { 3817 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr); 3818 ExceptionAsObject = Exception; 3819 } else { 3820 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 3821 "Unexpected rethrow outside @catch block."); 3822 ExceptionAsObject = CGF.ObjCEHValueStack.back(); 3823 isRethrow = true; 3824 } 3825 if (isRethrow && usesSEHExceptions) { 3826 // For SEH, ExceptionAsObject may be undef, because the catch handler is 3827 // not passed it for catchalls and so it is not visible to the catch 3828 // funclet. The real thrown object will still be live on the stack at this 3829 // point and will be rethrown. If we are explicitly rethrowing the object 3830 // that was passed into the `@catch` block, then this code path is not 3831 // reached and we will instead call `objc_exception_throw` with an explicit 3832 // argument. 3833 CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn).setDoesNotReturn(); 3834 } 3835 else { 3836 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy); 3837 llvm::CallSite Throw = 3838 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject); 3839 Throw.setDoesNotReturn(); 3840 } 3841 CGF.Builder.CreateUnreachable(); 3842 if (ClearInsertionPoint) 3843 CGF.Builder.ClearInsertionPoint(); 3844 } 3845 3846 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF, 3847 Address AddrWeakObj) { 3848 CGBuilderTy &B = CGF.Builder; 3849 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy); 3850 return B.CreateCall(WeakReadFn.getType(), WeakReadFn, 3851 AddrWeakObj.getPointer()); 3852 } 3853 3854 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF, 3855 llvm::Value *src, Address dst) { 3856 CGBuilderTy &B = CGF.Builder; 3857 src = EnforceType(B, src, IdTy); 3858 dst = EnforceType(B, dst, PtrToIdTy); 3859 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn, 3860 {src, dst.getPointer()}); 3861 } 3862 3863 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF, 3864 llvm::Value *src, Address dst, 3865 bool threadlocal) { 3866 CGBuilderTy &B = CGF.Builder; 3867 src = EnforceType(B, src, IdTy); 3868 dst = EnforceType(B, dst, PtrToIdTy); 3869 // FIXME. Add threadloca assign API 3870 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI"); 3871 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn, 3872 {src, dst.getPointer()}); 3873 } 3874 3875 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF, 3876 llvm::Value *src, Address dst, 3877 llvm::Value *ivarOffset) { 3878 CGBuilderTy &B = CGF.Builder; 3879 src = EnforceType(B, src, IdTy); 3880 dst = EnforceType(B, dst, IdTy); 3881 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn, 3882 {src, dst.getPointer(), ivarOffset}); 3883 } 3884 3885 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF, 3886 llvm::Value *src, Address dst) { 3887 CGBuilderTy &B = CGF.Builder; 3888 src = EnforceType(B, src, IdTy); 3889 dst = EnforceType(B, dst, PtrToIdTy); 3890 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn, 3891 {src, dst.getPointer()}); 3892 } 3893 3894 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF, 3895 Address DestPtr, 3896 Address SrcPtr, 3897 llvm::Value *Size) { 3898 CGBuilderTy &B = CGF.Builder; 3899 DestPtr = EnforceType(B, DestPtr, PtrTy); 3900 SrcPtr = EnforceType(B, SrcPtr, PtrTy); 3901 3902 B.CreateCall(MemMoveFn.getType(), MemMoveFn, 3903 {DestPtr.getPointer(), SrcPtr.getPointer(), Size}); 3904 } 3905 3906 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable( 3907 const ObjCInterfaceDecl *ID, 3908 const ObjCIvarDecl *Ivar) { 3909 const std::string Name = GetIVarOffsetVariableName(ID, Ivar); 3910 // Emit the variable and initialize it with what we think the correct value 3911 // is. This allows code compiled with non-fragile ivars to work correctly 3912 // when linked against code which isn't (most of the time). 3913 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name); 3914 if (!IvarOffsetPointer) 3915 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, 3916 llvm::Type::getInt32PtrTy(VMContext), false, 3917 llvm::GlobalValue::ExternalLinkage, nullptr, Name); 3918 return IvarOffsetPointer; 3919 } 3920 3921 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF, 3922 QualType ObjectTy, 3923 llvm::Value *BaseValue, 3924 const ObjCIvarDecl *Ivar, 3925 unsigned CVRQualifiers) { 3926 const ObjCInterfaceDecl *ID = 3927 ObjectTy->getAs<ObjCObjectType>()->getInterface(); 3928 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, 3929 EmitIvarOffset(CGF, ID, Ivar)); 3930 } 3931 3932 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context, 3933 const ObjCInterfaceDecl *OID, 3934 const ObjCIvarDecl *OIVD) { 3935 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next; 3936 next = next->getNextIvar()) { 3937 if (OIVD == next) 3938 return OID; 3939 } 3940 3941 // Otherwise check in the super class. 3942 if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) 3943 return FindIvarInterface(Context, Super, OIVD); 3944 3945 return nullptr; 3946 } 3947 3948 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF, 3949 const ObjCInterfaceDecl *Interface, 3950 const ObjCIvarDecl *Ivar) { 3951 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 3952 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar); 3953 3954 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage 3955 // and ExternalLinkage, so create a reference to the ivar global and rely on 3956 // the definition being created as part of GenerateClass. 3957 if (RuntimeVersion < 10 || 3958 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) 3959 return CGF.Builder.CreateZExtOrBitCast( 3960 CGF.Builder.CreateAlignedLoad( 3961 Int32Ty, CGF.Builder.CreateAlignedLoad( 3962 ObjCIvarOffsetVariable(Interface, Ivar), 3963 CGF.getPointerAlign(), "ivar"), 3964 CharUnits::fromQuantity(4)), 3965 PtrDiffTy); 3966 std::string name = "__objc_ivar_offset_value_" + 3967 Interface->getNameAsString() +"." + Ivar->getNameAsString(); 3968 CharUnits Align = CGM.getIntAlign(); 3969 llvm::Value *Offset = TheModule.getGlobalVariable(name); 3970 if (!Offset) { 3971 auto GV = new llvm::GlobalVariable(TheModule, IntTy, 3972 false, llvm::GlobalValue::LinkOnceAnyLinkage, 3973 llvm::Constant::getNullValue(IntTy), name); 3974 GV->setAlignment(Align.getQuantity()); 3975 Offset = GV; 3976 } 3977 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align); 3978 if (Offset->getType() != PtrDiffTy) 3979 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy); 3980 return Offset; 3981 } 3982 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar); 3983 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true); 3984 } 3985 3986 CGObjCRuntime * 3987 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) { 3988 auto Runtime = CGM.getLangOpts().ObjCRuntime; 3989 switch (Runtime.getKind()) { 3990 case ObjCRuntime::GNUstep: 3991 if (Runtime.getVersion() >= VersionTuple(2, 0)) 3992 return new CGObjCGNUstep2(CGM); 3993 return new CGObjCGNUstep(CGM); 3994 3995 case ObjCRuntime::GCC: 3996 return new CGObjCGCC(CGM); 3997 3998 case ObjCRuntime::ObjFW: 3999 return new CGObjCObjFW(CGM); 4000 4001 case ObjCRuntime::FragileMacOSX: 4002 case ObjCRuntime::MacOSX: 4003 case ObjCRuntime::iOS: 4004 case ObjCRuntime::WatchOS: 4005 llvm_unreachable("these runtimes are not GNU runtimes"); 4006 } 4007 llvm_unreachable("bad runtime"); 4008 } 4009