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