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