CGObjCMac.cpp revision 96508e1fea58347b6401ca9a4728c0b268174603
1//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===// 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 targetting the Apple runtime. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CGObjCRuntime.h" 15 16#include "CodeGenModule.h" 17#include "CodeGenFunction.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/Decl.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/Basic/LangOptions.h" 22 23#include "llvm/Intrinsics.h" 24#include "llvm/Module.h" 25#include "llvm/ADT/DenseSet.h" 26#include "llvm/Target/TargetData.h" 27#include <sstream> 28 29using namespace clang; 30using namespace CodeGen; 31 32namespace { 33 34 typedef std::vector<llvm::Constant*> ConstantVector; 35 36 // FIXME: We should find a nicer way to make the labels for 37 // metadata, string concatenation is lame. 38 39class ObjCCommonTypesHelper { 40protected: 41 CodeGen::CodeGenModule &CGM; 42 43public: 44 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy; 45 const llvm::Type *Int8PtrTy; 46 47 /// ObjectPtrTy - LLVM type for object handles (typeof(id)) 48 const llvm::Type *ObjectPtrTy; 49 50 /// PtrObjectPtrTy - LLVM type for id * 51 const llvm::Type *PtrObjectPtrTy; 52 53 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL)) 54 const llvm::Type *SelectorPtrTy; 55 /// ProtocolPtrTy - LLVM type for external protocol handles 56 /// (typeof(Protocol)) 57 const llvm::Type *ExternalProtocolPtrTy; 58 59 // SuperCTy - clang type for struct objc_super. 60 QualType SuperCTy; 61 // SuperPtrCTy - clang type for struct objc_super *. 62 QualType SuperPtrCTy; 63 64 /// SuperTy - LLVM type for struct objc_super. 65 const llvm::StructType *SuperTy; 66 /// SuperPtrTy - LLVM type for struct objc_super *. 67 const llvm::Type *SuperPtrTy; 68 69 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t 70 /// in GCC parlance). 71 const llvm::StructType *PropertyTy; 72 73 /// PropertyListTy - LLVM type for struct objc_property_list 74 /// (_prop_list_t in GCC parlance). 75 const llvm::StructType *PropertyListTy; 76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*. 77 const llvm::Type *PropertyListPtrTy; 78 79 // MethodTy - LLVM type for struct objc_method. 80 const llvm::StructType *MethodTy; 81 82 /// CacheTy - LLVM type for struct objc_cache. 83 const llvm::Type *CacheTy; 84 /// CachePtrTy - LLVM type for struct objc_cache *. 85 const llvm::Type *CachePtrTy; 86 87 llvm::Constant *GetPropertyFn, *SetPropertyFn; 88 89 llvm::Constant *EnumerationMutationFn; 90 91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function. 92 llvm::Constant *GcReadWeakFn; 93 94 /// GcAssignWeakFn -- LLVM objc_assign_weak function. 95 llvm::Constant *getGcAssignWeakFn() { 96 // id objc_assign_weak (id, id *) 97 std::vector<const llvm::Type*> Args(1, ObjectPtrTy); 98 Args.push_back(ObjectPtrTy->getPointerTo()); 99 llvm::FunctionType *FTy = 100 llvm::FunctionType::get(ObjectPtrTy, Args, false); 101 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak"); 102 } 103 104 /// GcAssignGlobalFn -- LLVM objc_assign_global function. 105 llvm::Constant *GcAssignGlobalFn; 106 107 /// GcAssignIvarFn -- LLVM objc_assign_ivar function. 108 llvm::Constant *GcAssignIvarFn; 109 110 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function. 111 llvm::Constant *GcAssignStrongCastFn; 112 113 /// ExceptionThrowFn - LLVM objc_exception_throw function. 114 llvm::Constant *ExceptionThrowFn; 115 116 /// SyncEnterFn - LLVM object_sync_enter function. 117 llvm::Constant *getSyncEnterFn() { 118 // void objc_sync_enter (id) 119 std::vector<const llvm::Type*> Args(1, ObjectPtrTy); 120 llvm::FunctionType *FTy = 121 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false); 122 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter"); 123 } 124 125 /// SyncExitFn - LLVM object_sync_exit function. 126 llvm::Constant *SyncExitFn; 127 128 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm); 129 ~ObjCCommonTypesHelper(){} 130}; 131 132/// ObjCTypesHelper - Helper class that encapsulates lazy 133/// construction of varies types used during ObjC generation. 134class ObjCTypesHelper : public ObjCCommonTypesHelper { 135private: 136 137 llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn; 138 llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn, 139 *MessageSendSuperFpretFn; 140 141public: 142 /// SymtabTy - LLVM type for struct objc_symtab. 143 const llvm::StructType *SymtabTy; 144 /// SymtabPtrTy - LLVM type for struct objc_symtab *. 145 const llvm::Type *SymtabPtrTy; 146 /// ModuleTy - LLVM type for struct objc_module. 147 const llvm::StructType *ModuleTy; 148 149 /// ProtocolTy - LLVM type for struct objc_protocol. 150 const llvm::StructType *ProtocolTy; 151 /// ProtocolPtrTy - LLVM type for struct objc_protocol *. 152 const llvm::Type *ProtocolPtrTy; 153 /// ProtocolExtensionTy - LLVM type for struct 154 /// objc_protocol_extension. 155 const llvm::StructType *ProtocolExtensionTy; 156 /// ProtocolExtensionTy - LLVM type for struct 157 /// objc_protocol_extension *. 158 const llvm::Type *ProtocolExtensionPtrTy; 159 /// MethodDescriptionTy - LLVM type for struct 160 /// objc_method_description. 161 const llvm::StructType *MethodDescriptionTy; 162 /// MethodDescriptionListTy - LLVM type for struct 163 /// objc_method_description_list. 164 const llvm::StructType *MethodDescriptionListTy; 165 /// MethodDescriptionListPtrTy - LLVM type for struct 166 /// objc_method_description_list *. 167 const llvm::Type *MethodDescriptionListPtrTy; 168 /// ProtocolListTy - LLVM type for struct objc_property_list. 169 const llvm::Type *ProtocolListTy; 170 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*. 171 const llvm::Type *ProtocolListPtrTy; 172 /// CategoryTy - LLVM type for struct objc_category. 173 const llvm::StructType *CategoryTy; 174 /// ClassTy - LLVM type for struct objc_class. 175 const llvm::StructType *ClassTy; 176 /// ClassPtrTy - LLVM type for struct objc_class *. 177 const llvm::Type *ClassPtrTy; 178 /// ClassExtensionTy - LLVM type for struct objc_class_ext. 179 const llvm::StructType *ClassExtensionTy; 180 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *. 181 const llvm::Type *ClassExtensionPtrTy; 182 // IvarTy - LLVM type for struct objc_ivar. 183 const llvm::StructType *IvarTy; 184 /// IvarListTy - LLVM type for struct objc_ivar_list. 185 const llvm::Type *IvarListTy; 186 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *. 187 const llvm::Type *IvarListPtrTy; 188 /// MethodListTy - LLVM type for struct objc_method_list. 189 const llvm::Type *MethodListTy; 190 /// MethodListPtrTy - LLVM type for struct objc_method_list *. 191 const llvm::Type *MethodListPtrTy; 192 193 /// ExceptionDataTy - LLVM type for struct _objc_exception_data. 194 const llvm::Type *ExceptionDataTy; 195 196 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function. 197 llvm::Constant *ExceptionTryEnterFn; 198 199 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function. 200 llvm::Constant *ExceptionTryExitFn; 201 202 /// ExceptionExtractFn - LLVM objc_exception_extract function. 203 llvm::Constant *ExceptionExtractFn; 204 205 /// ExceptionMatchFn - LLVM objc_exception_match function. 206 llvm::Constant *ExceptionMatchFn; 207 208 /// SetJmpFn - LLVM _setjmp function. 209 llvm::Constant *SetJmpFn; 210 211public: 212 ObjCTypesHelper(CodeGen::CodeGenModule &cgm); 213 ~ObjCTypesHelper() {} 214 215 216 llvm::Constant *getSendFn(bool IsSuper) { 217 return IsSuper ? MessageSendSuperFn : MessageSendFn; 218 } 219 220 llvm::Constant *getSendStretFn(bool IsSuper) { 221 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn; 222 } 223 224 llvm::Constant *getSendFpretFn(bool IsSuper) { 225 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn; 226 } 227}; 228 229/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's 230/// modern abi 231class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper { 232public: 233 llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn, 234 *MessageSendStretFixupFn, *MessageSendIdFixupFn, 235 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn, 236 *MessageSendSuper2StretFixupFn; 237 238 // MethodListnfABITy - LLVM for struct _method_list_t 239 const llvm::StructType *MethodListnfABITy; 240 241 // MethodListnfABIPtrTy - LLVM for struct _method_list_t* 242 const llvm::Type *MethodListnfABIPtrTy; 243 244 // ProtocolnfABITy = LLVM for struct _protocol_t 245 const llvm::StructType *ProtocolnfABITy; 246 247 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t* 248 const llvm::Type *ProtocolnfABIPtrTy; 249 250 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list 251 const llvm::StructType *ProtocolListnfABITy; 252 253 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list* 254 const llvm::Type *ProtocolListnfABIPtrTy; 255 256 // ClassnfABITy - LLVM for struct _class_t 257 const llvm::StructType *ClassnfABITy; 258 259 // ClassnfABIPtrTy - LLVM for struct _class_t* 260 const llvm::Type *ClassnfABIPtrTy; 261 262 // IvarnfABITy - LLVM for struct _ivar_t 263 const llvm::StructType *IvarnfABITy; 264 265 // IvarListnfABITy - LLVM for struct _ivar_list_t 266 const llvm::StructType *IvarListnfABITy; 267 268 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t* 269 const llvm::Type *IvarListnfABIPtrTy; 270 271 // ClassRonfABITy - LLVM for struct _class_ro_t 272 const llvm::StructType *ClassRonfABITy; 273 274 // ImpnfABITy - LLVM for id (*)(id, SEL, ...) 275 const llvm::Type *ImpnfABITy; 276 277 // CategorynfABITy - LLVM for struct _category_t 278 const llvm::StructType *CategorynfABITy; 279 280 // New types for nonfragile abi messaging. 281 282 // MessageRefTy - LLVM for: 283 // struct _message_ref_t { 284 // IMP messenger; 285 // SEL name; 286 // }; 287 const llvm::StructType *MessageRefTy; 288 // MessageRefCTy - clang type for struct _message_ref_t 289 QualType MessageRefCTy; 290 291 // MessageRefPtrTy - LLVM for struct _message_ref_t* 292 const llvm::Type *MessageRefPtrTy; 293 // MessageRefCPtrTy - clang type for struct _message_ref_t* 294 QualType MessageRefCPtrTy; 295 296 // MessengerTy - Type of the messenger (shown as IMP above) 297 const llvm::FunctionType *MessengerTy; 298 299 // SuperMessageRefTy - LLVM for: 300 // struct _super_message_ref_t { 301 // SUPER_IMP messenger; 302 // SEL name; 303 // }; 304 const llvm::StructType *SuperMessageRefTy; 305 306 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* 307 const llvm::Type *SuperMessageRefPtrTy; 308 309 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C 310 /// exception personality function. 311 llvm::Value *getEHPersonalityPtr() { 312 llvm::Constant *Personality = 313 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 314 std::vector<const llvm::Type*>(), 315 true), 316 "__objc_personality_v0"); 317 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy); 318 } 319 320 llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn; 321 322 const llvm::StructType *EHTypeTy; 323 const llvm::Type *EHTypePtrTy; 324 325 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm); 326 ~ObjCNonFragileABITypesHelper(){} 327}; 328 329class CGObjCCommonMac : public CodeGen::CGObjCRuntime { 330public: 331 // FIXME - accessibility 332 class GC_IVAR { 333 public: 334 unsigned int ivar_bytepos; 335 unsigned int ivar_size; 336 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {} 337 }; 338 339 class SKIP_SCAN { 340 public: 341 unsigned int skip; 342 unsigned int scan; 343 SKIP_SCAN() : skip(0), scan(0) {} 344 }; 345 346protected: 347 CodeGen::CodeGenModule &CGM; 348 // FIXME! May not be needing this after all. 349 unsigned ObjCABI; 350 351 // gc ivar layout bitmap calculation helper caches. 352 llvm::SmallVector<GC_IVAR, 16> SkipIvars; 353 llvm::SmallVector<GC_IVAR, 16> IvarsInfo; 354 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars; 355 356 /// LazySymbols - Symbols to generate a lazy reference for. See 357 /// DefinedSymbols and FinishModule(). 358 std::set<IdentifierInfo*> LazySymbols; 359 360 /// DefinedSymbols - External symbols which are defined by this 361 /// module. The symbols in this list and LazySymbols are used to add 362 /// special linker symbols which ensure that Objective-C modules are 363 /// linked properly. 364 std::set<IdentifierInfo*> DefinedSymbols; 365 366 /// ClassNames - uniqued class names. 367 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames; 368 369 /// MethodVarNames - uniqued method variable names. 370 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames; 371 372 /// MethodVarTypes - uniqued method type signatures. We have to use 373 /// a StringMap here because have no other unique reference. 374 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes; 375 376 /// MethodDefinitions - map of methods which have been defined in 377 /// this translation unit. 378 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions; 379 380 /// PropertyNames - uniqued method variable names. 381 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames; 382 383 /// ClassReferences - uniqued class references. 384 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences; 385 386 /// SelectorReferences - uniqued selector references. 387 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences; 388 389 /// Protocols - Protocols for which an objc_protocol structure has 390 /// been emitted. Forward declarations are handled by creating an 391 /// empty structure whose initializer is filled in when/if defined. 392 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols; 393 394 /// DefinedProtocols - Protocols which have actually been 395 /// defined. We should not need this, see FIXME in GenerateProtocol. 396 llvm::DenseSet<IdentifierInfo*> DefinedProtocols; 397 398 /// DefinedClasses - List of defined classes. 399 std::vector<llvm::GlobalValue*> DefinedClasses; 400 401 /// DefinedCategories - List of defined categories. 402 std::vector<llvm::GlobalValue*> DefinedCategories; 403 404 /// UsedGlobals - List of globals to pack into the llvm.used metadata 405 /// to prevent them from being clobbered. 406 std::vector<llvm::GlobalVariable*> UsedGlobals; 407 408 /// GetNameForMethod - Return a name for the given method. 409 /// \param[out] NameOut - The return value. 410 void GetNameForMethod(const ObjCMethodDecl *OMD, 411 const ObjCContainerDecl *CD, 412 std::string &NameOut); 413 414 /// GetMethodVarName - Return a unique constant for the given 415 /// selector's name. The return value has type char *. 416 llvm::Constant *GetMethodVarName(Selector Sel); 417 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident); 418 llvm::Constant *GetMethodVarName(const std::string &Name); 419 420 /// GetMethodVarType - Return a unique constant for the given 421 /// selector's name. The return value has type char *. 422 423 // FIXME: This is a horrible name. 424 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D); 425 llvm::Constant *GetMethodVarType(FieldDecl *D); 426 427 /// GetPropertyName - Return a unique constant for the given 428 /// name. The return value has type char *. 429 llvm::Constant *GetPropertyName(IdentifierInfo *Ident); 430 431 // FIXME: This can be dropped once string functions are unified. 432 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD, 433 const Decl *Container); 434 435 /// GetClassName - Return a unique constant for the given selector's 436 /// name. The return value has type char *. 437 llvm::Constant *GetClassName(IdentifierInfo *Ident); 438 439 /// GetInterfaceDeclStructLayout - Get layout for ivars of given 440 /// interface declaration. 441 const llvm::StructLayout *GetInterfaceDeclStructLayout( 442 const ObjCInterfaceDecl *ID) const; 443 444 /// BuildIvarLayout - Builds ivar layout bitmap for the class 445 /// implementation for the __strong or __weak case. 446 /// 447 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI, 448 bool ForStrongLayout); 449 450 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI, 451 const llvm::StructLayout *Layout, 452 const RecordDecl *RD, 453 const llvm::SmallVectorImpl<FieldDecl*> &RecFields, 454 unsigned int BytePos, bool ForStrongLayout, 455 int &Index, int &SkIndex, bool &HasUnion); 456 457 /// GetIvarLayoutName - Returns a unique constant for the given 458 /// ivar layout bitmap. 459 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident, 460 const ObjCCommonTypesHelper &ObjCTypes); 461 462 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID, 463 RecordDecl::field_iterator &FIV, 464 RecordDecl::field_iterator &PIV); 465 /// EmitPropertyList - Emit the given property list. The return 466 /// value has type PropertyListPtrTy. 467 llvm::Constant *EmitPropertyList(const std::string &Name, 468 const Decl *Container, 469 const ObjCContainerDecl *OCD, 470 const ObjCCommonTypesHelper &ObjCTypes); 471 472 /// GetProtocolRef - Return a reference to the internal protocol 473 /// description, creating an empty one if it has not been 474 /// defined. The return value has type ProtocolPtrTy. 475 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD); 476 477 /// GetIvarBaseOffset - returns ivars byte offset. 478 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout, 479 const FieldDecl *Field); 480 481 /// GetFieldBaseOffset - return's field byte offset. 482 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI, 483 const llvm::StructLayout *Layout, 484 const FieldDecl *Field); 485 486 /// CreateMetadataVar - Create a global variable with internal 487 /// linkage for use by the Objective-C runtime. 488 /// 489 /// This is a convenience wrapper which not only creates the 490 /// variable, but also sets the section and alignment and adds the 491 /// global to the UsedGlobals list. 492 /// 493 /// \param Name - The variable name. 494 /// \param Init - The variable initializer; this is also used to 495 /// define the type of the variable. 496 /// \param Section - The section the variable should go into, or 0. 497 /// \param Align - The alignment for the variable, or 0. 498 /// \param AddToUsed - Whether the variable should be added to 499 /// "llvm.used". 500 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name, 501 llvm::Constant *Init, 502 const char *Section, 503 unsigned Align, 504 bool AddToUsed); 505 506public: 507 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm) 508 { } 509 510 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL); 511 512 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 513 const ObjCContainerDecl *CD=0); 514 515 virtual void GenerateProtocol(const ObjCProtocolDecl *PD); 516 517 /// GetOrEmitProtocol - Get the protocol object for the given 518 /// declaration, emitting it if necessary. The return value has type 519 /// ProtocolPtrTy. 520 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0; 521 522 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 523 /// object for the given declaration, emitting it if needed. These 524 /// forward references will be filled in with empty bodies if no 525 /// definition is seen. The return value has type ProtocolPtrTy. 526 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0; 527}; 528 529class CGObjCMac : public CGObjCCommonMac { 530private: 531 ObjCTypesHelper ObjCTypes; 532 /// EmitImageInfo - Emit the image info marker used to encode some module 533 /// level information. 534 void EmitImageInfo(); 535 536 /// EmitModuleInfo - Another marker encoding module level 537 /// information. 538 void EmitModuleInfo(); 539 540 /// EmitModuleSymols - Emit module symbols, the list of defined 541 /// classes and categories. The result has type SymtabPtrTy. 542 llvm::Constant *EmitModuleSymbols(); 543 544 /// FinishModule - Write out global data structures at the end of 545 /// processing a translation unit. 546 void FinishModule(); 547 548 /// EmitClassExtension - Generate the class extension structure used 549 /// to store the weak ivar layout and properties. The return value 550 /// has type ClassExtensionPtrTy. 551 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID); 552 553 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 554 /// for the given class. 555 llvm::Value *EmitClassRef(CGBuilderTy &Builder, 556 const ObjCInterfaceDecl *ID); 557 558 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, 559 QualType ResultType, 560 Selector Sel, 561 llvm::Value *Arg0, 562 QualType Arg0Ty, 563 bool IsSuper, 564 const CallArgList &CallArgs); 565 566 /// EmitIvarList - Emit the ivar list for the given 567 /// implementation. If ForClass is true the list of class ivars 568 /// (i.e. metaclass ivars) is emitted, otherwise the list of 569 /// interface ivars will be emitted. The return value has type 570 /// IvarListPtrTy. 571 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID, 572 bool ForClass); 573 574 /// EmitMetaClass - Emit a forward reference to the class structure 575 /// for the metaclass of the given interface. The return value has 576 /// type ClassPtrTy. 577 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID); 578 579 /// EmitMetaClass - Emit a class structure for the metaclass of the 580 /// given implementation. The return value has type ClassPtrTy. 581 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID, 582 llvm::Constant *Protocols, 583 const llvm::Type *InterfaceTy, 584 const ConstantVector &Methods); 585 586 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); 587 588 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); 589 590 /// EmitMethodList - Emit the method list for the given 591 /// implementation. The return value has type MethodListPtrTy. 592 llvm::Constant *EmitMethodList(const std::string &Name, 593 const char *Section, 594 const ConstantVector &Methods); 595 596 /// EmitMethodDescList - Emit a method description list for a list of 597 /// method declarations. 598 /// - TypeName: The name for the type containing the methods. 599 /// - IsProtocol: True iff these methods are for a protocol. 600 /// - ClassMethds: True iff these are class methods. 601 /// - Required: When true, only "required" methods are 602 /// listed. Similarly, when false only "optional" methods are 603 /// listed. For classes this should always be true. 604 /// - begin, end: The method list to output. 605 /// 606 /// The return value has type MethodDescriptionListPtrTy. 607 llvm::Constant *EmitMethodDescList(const std::string &Name, 608 const char *Section, 609 const ConstantVector &Methods); 610 611 /// GetOrEmitProtocol - Get the protocol object for the given 612 /// declaration, emitting it if necessary. The return value has type 613 /// ProtocolPtrTy. 614 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD); 615 616 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 617 /// object for the given declaration, emitting it if needed. These 618 /// forward references will be filled in with empty bodies if no 619 /// definition is seen. The return value has type ProtocolPtrTy. 620 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD); 621 622 /// EmitProtocolExtension - Generate the protocol extension 623 /// structure used to store optional instance and class methods, and 624 /// protocol properties. The return value has type 625 /// ProtocolExtensionPtrTy. 626 llvm::Constant * 627 EmitProtocolExtension(const ObjCProtocolDecl *PD, 628 const ConstantVector &OptInstanceMethods, 629 const ConstantVector &OptClassMethods); 630 631 /// EmitProtocolList - Generate the list of referenced 632 /// protocols. The return value has type ProtocolListPtrTy. 633 llvm::Constant *EmitProtocolList(const std::string &Name, 634 ObjCProtocolDecl::protocol_iterator begin, 635 ObjCProtocolDecl::protocol_iterator end); 636 637 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, 638 /// for the given selector. 639 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel); 640 641 public: 642 CGObjCMac(CodeGen::CodeGenModule &cgm); 643 644 virtual llvm::Function *ModuleInitFunction(); 645 646 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 647 QualType ResultType, 648 Selector Sel, 649 llvm::Value *Receiver, 650 bool IsClassMessage, 651 const CallArgList &CallArgs); 652 653 virtual CodeGen::RValue 654 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 655 QualType ResultType, 656 Selector Sel, 657 const ObjCInterfaceDecl *Class, 658 bool isCategoryImpl, 659 llvm::Value *Receiver, 660 bool IsClassMessage, 661 const CallArgList &CallArgs); 662 663 virtual llvm::Value *GetClass(CGBuilderTy &Builder, 664 const ObjCInterfaceDecl *ID); 665 666 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel); 667 668 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 669 670 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 671 672 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, 673 const ObjCProtocolDecl *PD); 674 675 virtual llvm::Constant *GetPropertyGetFunction(); 676 virtual llvm::Constant *GetPropertySetFunction(); 677 virtual llvm::Constant *EnumerationMutationFunction(); 678 679 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 680 const Stmt &S); 681 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 682 const ObjCAtThrowStmt &S); 683 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 684 llvm::Value *AddrWeakObj); 685 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 686 llvm::Value *src, llvm::Value *dst); 687 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 688 llvm::Value *src, llvm::Value *dest); 689 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 690 llvm::Value *src, llvm::Value *dest); 691 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 692 llvm::Value *src, llvm::Value *dest); 693 694 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 695 QualType ObjectTy, 696 llvm::Value *BaseValue, 697 const ObjCIvarDecl *Ivar, 698 const FieldDecl *Field, 699 unsigned CVRQualifiers); 700 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 701 ObjCInterfaceDecl *Interface, 702 const ObjCIvarDecl *Ivar); 703}; 704 705class CGObjCNonFragileABIMac : public CGObjCCommonMac { 706private: 707 ObjCNonFragileABITypesHelper ObjCTypes; 708 llvm::GlobalVariable* ObjCEmptyCacheVar; 709 llvm::GlobalVariable* ObjCEmptyVtableVar; 710 711 /// MetaClassReferences - uniqued meta class references. 712 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences; 713 714 /// EHTypeReferences - uniqued class ehtype references. 715 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences; 716 717 /// FinishNonFragileABIModule - Write out global data structures at the end of 718 /// processing a translation unit. 719 void FinishNonFragileABIModule(); 720 721 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags, 722 unsigned InstanceStart, 723 unsigned InstanceSize, 724 const ObjCImplementationDecl *ID); 725 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName, 726 llvm::Constant *IsAGV, 727 llvm::Constant *SuperClassGV, 728 llvm::Constant *ClassRoGV, 729 bool HiddenVisibility); 730 731 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); 732 733 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); 734 735 /// EmitMethodList - Emit the method list for the given 736 /// implementation. The return value has type MethodListnfABITy. 737 llvm::Constant *EmitMethodList(const std::string &Name, 738 const char *Section, 739 const ConstantVector &Methods); 740 /// EmitIvarList - Emit the ivar list for the given 741 /// implementation. If ForClass is true the list of class ivars 742 /// (i.e. metaclass ivars) is emitted, otherwise the list of 743 /// interface ivars will be emitted. The return value has type 744 /// IvarListnfABIPtrTy. 745 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID); 746 747 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID, 748 const ObjCIvarDecl *Ivar, 749 unsigned long int offset); 750 751 /// GetOrEmitProtocol - Get the protocol object for the given 752 /// declaration, emitting it if necessary. The return value has type 753 /// ProtocolPtrTy. 754 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD); 755 756 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 757 /// object for the given declaration, emitting it if needed. These 758 /// forward references will be filled in with empty bodies if no 759 /// definition is seen. The return value has type ProtocolPtrTy. 760 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD); 761 762 /// EmitProtocolList - Generate the list of referenced 763 /// protocols. The return value has type ProtocolListPtrTy. 764 llvm::Constant *EmitProtocolList(const std::string &Name, 765 ObjCProtocolDecl::protocol_iterator begin, 766 ObjCProtocolDecl::protocol_iterator end); 767 768 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, 769 QualType ResultType, 770 Selector Sel, 771 llvm::Value *Receiver, 772 QualType Arg0Ty, 773 bool IsSuper, 774 const CallArgList &CallArgs); 775 776 /// GetClassGlobal - Return the global variable for the Objective-C 777 /// class of the given name. 778 llvm::GlobalVariable *GetClassGlobal(const std::string &Name); 779 780 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 781 /// for the given class. 782 llvm::Value *EmitClassRef(CGBuilderTy &Builder, 783 const ObjCInterfaceDecl *ID, 784 bool IsSuper = false); 785 786 /// EmitMetaClassRef - Return a Value * of the address of _class_t 787 /// meta-data 788 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder, 789 const ObjCInterfaceDecl *ID); 790 791 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for 792 /// the given ivar. 793 /// 794 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name, 795 const ObjCInterfaceDecl *ID, 796 const ObjCIvarDecl *Ivar); 797 798 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, 799 /// for the given selector. 800 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel); 801 802 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C 803 /// interface. The return value has type EHTypePtrTy. 804 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID, 805 bool ForDefinition); 806 807 const char *getMetaclassSymbolPrefix() const { 808 return "OBJC_METACLASS_$_"; 809 } 810 811 const char *getClassSymbolPrefix() const { 812 return "OBJC_CLASS_$_"; 813 } 814 815public: 816 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm); 817 // FIXME. All stubs for now! 818 virtual llvm::Function *ModuleInitFunction(); 819 820 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 821 QualType ResultType, 822 Selector Sel, 823 llvm::Value *Receiver, 824 bool IsClassMessage, 825 const CallArgList &CallArgs); 826 827 virtual CodeGen::RValue 828 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 829 QualType ResultType, 830 Selector Sel, 831 const ObjCInterfaceDecl *Class, 832 bool isCategoryImpl, 833 llvm::Value *Receiver, 834 bool IsClassMessage, 835 const CallArgList &CallArgs); 836 837 virtual llvm::Value *GetClass(CGBuilderTy &Builder, 838 const ObjCInterfaceDecl *ID); 839 840 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel) 841 { return EmitSelector(Builder, Sel); } 842 843 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 844 845 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 846 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, 847 const ObjCProtocolDecl *PD); 848 849 virtual llvm::Constant *GetPropertyGetFunction() { 850 return ObjCTypes.GetPropertyFn; 851 } 852 virtual llvm::Constant *GetPropertySetFunction() { 853 return ObjCTypes.SetPropertyFn; 854 } 855 virtual llvm::Constant *EnumerationMutationFunction() { 856 return ObjCTypes.EnumerationMutationFn; 857 } 858 859 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 860 const Stmt &S); 861 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 862 const ObjCAtThrowStmt &S); 863 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 864 llvm::Value *AddrWeakObj); 865 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 866 llvm::Value *src, llvm::Value *dst); 867 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 868 llvm::Value *src, llvm::Value *dest); 869 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 870 llvm::Value *src, llvm::Value *dest); 871 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 872 llvm::Value *src, llvm::Value *dest); 873 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 874 QualType ObjectTy, 875 llvm::Value *BaseValue, 876 const ObjCIvarDecl *Ivar, 877 const FieldDecl *Field, 878 unsigned CVRQualifiers); 879 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 880 ObjCInterfaceDecl *Interface, 881 const ObjCIvarDecl *Ivar); 882}; 883 884} // end anonymous namespace 885 886/* *** Helper Functions *** */ 887 888/// getConstantGEP() - Help routine to construct simple GEPs. 889static llvm::Constant *getConstantGEP(llvm::Constant *C, 890 unsigned idx0, 891 unsigned idx1) { 892 llvm::Value *Idxs[] = { 893 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0), 894 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1) 895 }; 896 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2); 897} 898 899/// hasObjCExceptionAttribute - Return true if this class or any super 900/// class has the __objc_exception__ attribute. 901static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) { 902 if (OID->hasAttr<ObjCExceptionAttr>()) 903 return true; 904 if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) 905 return hasObjCExceptionAttribute(Super); 906 return false; 907} 908 909/* *** CGObjCMac Public Interface *** */ 910 911CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), 912 ObjCTypes(cgm) 913{ 914 ObjCABI = 1; 915 EmitImageInfo(); 916} 917 918/// GetClass - Return a reference to the class for the given interface 919/// decl. 920llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder, 921 const ObjCInterfaceDecl *ID) { 922 return EmitClassRef(Builder, ID); 923} 924 925/// GetSelector - Return the pointer to the unique'd string for this selector. 926llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) { 927 return EmitSelector(Builder, Sel); 928} 929 930/// Generate a constant CFString object. 931/* 932 struct __builtin_CFString { 933 const int *isa; // point to __CFConstantStringClassReference 934 int flags; 935 const char *str; 936 long length; 937 }; 938*/ 939 940llvm::Constant *CGObjCCommonMac::GenerateConstantString( 941 const ObjCStringLiteral *SL) { 942 return CGM.GetAddrOfConstantCFString(SL->getString()); 943} 944 945/// Generates a message send where the super is the receiver. This is 946/// a message send to self with special delivery semantics indicating 947/// which class's method should be called. 948CodeGen::RValue 949CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 950 QualType ResultType, 951 Selector Sel, 952 const ObjCInterfaceDecl *Class, 953 bool isCategoryImpl, 954 llvm::Value *Receiver, 955 bool IsClassMessage, 956 const CodeGen::CallArgList &CallArgs) { 957 // Create and init a super structure; this is a (receiver, class) 958 // pair we will pass to objc_msgSendSuper. 959 llvm::Value *ObjCSuper = 960 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super"); 961 llvm::Value *ReceiverAsObject = 962 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); 963 CGF.Builder.CreateStore(ReceiverAsObject, 964 CGF.Builder.CreateStructGEP(ObjCSuper, 0)); 965 966 // If this is a class message the metaclass is passed as the target. 967 llvm::Value *Target; 968 if (IsClassMessage) { 969 if (isCategoryImpl) { 970 // Message sent to 'super' in a class method defined in a category 971 // implementation requires an odd treatment. 972 // If we are in a class method, we must retrieve the 973 // _metaclass_ for the current class, pointed at by 974 // the class's "isa" pointer. The following assumes that 975 // isa" is the first ivar in a class (which it must be). 976 Target = EmitClassRef(CGF.Builder, Class->getSuperClass()); 977 Target = CGF.Builder.CreateStructGEP(Target, 0); 978 Target = CGF.Builder.CreateLoad(Target); 979 } 980 else { 981 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class); 982 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1); 983 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr); 984 Target = Super; 985 } 986 } else { 987 Target = EmitClassRef(CGF.Builder, Class->getSuperClass()); 988 } 989 // FIXME: We shouldn't need to do this cast, rectify the ASTContext 990 // and ObjCTypes types. 991 const llvm::Type *ClassTy = 992 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); 993 Target = CGF.Builder.CreateBitCast(Target, ClassTy); 994 CGF.Builder.CreateStore(Target, 995 CGF.Builder.CreateStructGEP(ObjCSuper, 1)); 996 997 return EmitMessageSend(CGF, ResultType, Sel, 998 ObjCSuper, ObjCTypes.SuperPtrCTy, 999 true, CallArgs); 1000} 1001 1002/// Generate code for a message send expression. 1003CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 1004 QualType ResultType, 1005 Selector Sel, 1006 llvm::Value *Receiver, 1007 bool IsClassMessage, 1008 const CallArgList &CallArgs) { 1009 llvm::Value *Arg0 = 1010 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp"); 1011 return EmitMessageSend(CGF, ResultType, Sel, 1012 Arg0, CGF.getContext().getObjCIdType(), 1013 false, CallArgs); 1014} 1015 1016CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, 1017 QualType ResultType, 1018 Selector Sel, 1019 llvm::Value *Arg0, 1020 QualType Arg0Ty, 1021 bool IsSuper, 1022 const CallArgList &CallArgs) { 1023 CallArgList ActualArgs; 1024 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty)); 1025 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder, 1026 Sel)), 1027 CGF.getContext().getObjCSelType())); 1028 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 1029 1030 CodeGenTypes &Types = CGM.getTypes(); 1031 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs); 1032 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false); 1033 1034 llvm::Constant *Fn; 1035 if (CGM.ReturnTypeUsesSret(FnInfo)) { 1036 Fn = ObjCTypes.getSendStretFn(IsSuper); 1037 } else if (ResultType->isFloatingType()) { 1038 // FIXME: Sadly, this is wrong. This actually depends on the 1039 // architecture. This happens to be right for x86-32 though. 1040 Fn = ObjCTypes.getSendFpretFn(IsSuper); 1041 } else { 1042 Fn = ObjCTypes.getSendFn(IsSuper); 1043 } 1044 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy)); 1045 return CGF.EmitCall(FnInfo, Fn, ActualArgs); 1046} 1047 1048llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder, 1049 const ObjCProtocolDecl *PD) { 1050 // FIXME: I don't understand why gcc generates this, or where it is 1051 // resolved. Investigate. Its also wasteful to look this up over and 1052 // over. 1053 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 1054 1055 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD), 1056 ObjCTypes.ExternalProtocolPtrTy); 1057} 1058 1059void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) { 1060 // FIXME: We shouldn't need this, the protocol decl should contain 1061 // enough information to tell us whether this was a declaration or a 1062 // definition. 1063 DefinedProtocols.insert(PD->getIdentifier()); 1064 1065 // If we have generated a forward reference to this protocol, emit 1066 // it now. Otherwise do nothing, the protocol objects are lazily 1067 // emitted. 1068 if (Protocols.count(PD->getIdentifier())) 1069 GetOrEmitProtocol(PD); 1070} 1071 1072llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) { 1073 if (DefinedProtocols.count(PD->getIdentifier())) 1074 return GetOrEmitProtocol(PD); 1075 return GetOrEmitProtocolRef(PD); 1076} 1077 1078/* 1079 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions 1080 struct _objc_protocol { 1081 struct _objc_protocol_extension *isa; 1082 char *protocol_name; 1083 struct _objc_protocol_list *protocol_list; 1084 struct _objc__method_prototype_list *instance_methods; 1085 struct _objc__method_prototype_list *class_methods 1086 }; 1087 1088 See EmitProtocolExtension(). 1089*/ 1090llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) { 1091 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 1092 1093 // Early exit if a defining object has already been generated. 1094 if (Entry && Entry->hasInitializer()) 1095 return Entry; 1096 1097 // FIXME: I don't understand why gcc generates this, or where it is 1098 // resolved. Investigate. Its also wasteful to look this up over and 1099 // over. 1100 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 1101 1102 const char *ProtocolName = PD->getNameAsCString(); 1103 1104 // Construct method lists. 1105 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 1106 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; 1107 for (ObjCProtocolDecl::instmeth_iterator 1108 i = PD->instmeth_begin(CGM.getContext()), 1109 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) { 1110 ObjCMethodDecl *MD = *i; 1111 llvm::Constant *C = GetMethodDescriptionConstant(MD); 1112 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 1113 OptInstanceMethods.push_back(C); 1114 } else { 1115 InstanceMethods.push_back(C); 1116 } 1117 } 1118 1119 for (ObjCProtocolDecl::classmeth_iterator 1120 i = PD->classmeth_begin(CGM.getContext()), 1121 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) { 1122 ObjCMethodDecl *MD = *i; 1123 llvm::Constant *C = GetMethodDescriptionConstant(MD); 1124 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 1125 OptClassMethods.push_back(C); 1126 } else { 1127 ClassMethods.push_back(C); 1128 } 1129 } 1130 1131 std::vector<llvm::Constant*> Values(5); 1132 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods); 1133 Values[1] = GetClassName(PD->getIdentifier()); 1134 Values[2] = 1135 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(), 1136 PD->protocol_begin(), 1137 PD->protocol_end()); 1138 Values[3] = 1139 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" 1140 + PD->getNameAsString(), 1141 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 1142 InstanceMethods); 1143 Values[4] = 1144 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" 1145 + PD->getNameAsString(), 1146 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 1147 ClassMethods); 1148 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 1149 Values); 1150 1151 if (Entry) { 1152 // Already created, fix the linkage and update the initializer. 1153 Entry->setLinkage(llvm::GlobalValue::InternalLinkage); 1154 Entry->setInitializer(Init); 1155 } else { 1156 Entry = 1157 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, 1158 llvm::GlobalValue::InternalLinkage, 1159 Init, 1160 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName, 1161 &CGM.getModule()); 1162 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 1163 Entry->setAlignment(4); 1164 UsedGlobals.push_back(Entry); 1165 // FIXME: Is this necessary? Why only for protocol? 1166 Entry->setAlignment(4); 1167 } 1168 1169 return Entry; 1170} 1171 1172llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) { 1173 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 1174 1175 if (!Entry) { 1176 // We use the initializer as a marker of whether this is a forward 1177 // reference or not. At module finalization we add the empty 1178 // contents for protocols which were referenced but never defined. 1179 Entry = 1180 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, 1181 llvm::GlobalValue::ExternalLinkage, 1182 0, 1183 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(), 1184 &CGM.getModule()); 1185 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 1186 Entry->setAlignment(4); 1187 UsedGlobals.push_back(Entry); 1188 // FIXME: Is this necessary? Why only for protocol? 1189 Entry->setAlignment(4); 1190 } 1191 1192 return Entry; 1193} 1194 1195/* 1196 struct _objc_protocol_extension { 1197 uint32_t size; 1198 struct objc_method_description_list *optional_instance_methods; 1199 struct objc_method_description_list *optional_class_methods; 1200 struct objc_property_list *instance_properties; 1201 }; 1202*/ 1203llvm::Constant * 1204CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD, 1205 const ConstantVector &OptInstanceMethods, 1206 const ConstantVector &OptClassMethods) { 1207 uint64_t Size = 1208 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy); 1209 std::vector<llvm::Constant*> Values(4); 1210 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 1211 Values[1] = 1212 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" 1213 + PD->getNameAsString(), 1214 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 1215 OptInstanceMethods); 1216 Values[2] = 1217 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" 1218 + PD->getNameAsString(), 1219 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 1220 OptClassMethods); 1221 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + 1222 PD->getNameAsString(), 1223 0, PD, ObjCTypes); 1224 1225 // Return null if no extension bits are used. 1226 if (Values[1]->isNullValue() && Values[2]->isNullValue() && 1227 Values[3]->isNullValue()) 1228 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 1229 1230 llvm::Constant *Init = 1231 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values); 1232 1233 // No special section, but goes in llvm.used 1234 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(), 1235 Init, 1236 0, 0, true); 1237} 1238 1239/* 1240 struct objc_protocol_list { 1241 struct objc_protocol_list *next; 1242 long count; 1243 Protocol *list[]; 1244 }; 1245*/ 1246llvm::Constant * 1247CGObjCMac::EmitProtocolList(const std::string &Name, 1248 ObjCProtocolDecl::protocol_iterator begin, 1249 ObjCProtocolDecl::protocol_iterator end) { 1250 std::vector<llvm::Constant*> ProtocolRefs; 1251 1252 for (; begin != end; ++begin) 1253 ProtocolRefs.push_back(GetProtocolRef(*begin)); 1254 1255 // Just return null for empty protocol lists 1256 if (ProtocolRefs.empty()) 1257 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 1258 1259 // This list is null terminated. 1260 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy)); 1261 1262 std::vector<llvm::Constant*> Values(3); 1263 // This field is only used by the runtime. 1264 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 1265 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); 1266 Values[2] = 1267 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy, 1268 ProtocolRefs.size()), 1269 ProtocolRefs); 1270 1271 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1272 llvm::GlobalVariable *GV = 1273 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip", 1274 4, false); 1275 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy); 1276} 1277 1278/* 1279 struct _objc_property { 1280 const char * const name; 1281 const char * const attributes; 1282 }; 1283 1284 struct _objc_property_list { 1285 uint32_t entsize; // sizeof (struct _objc_property) 1286 uint32_t prop_count; 1287 struct _objc_property[prop_count]; 1288 }; 1289*/ 1290llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name, 1291 const Decl *Container, 1292 const ObjCContainerDecl *OCD, 1293 const ObjCCommonTypesHelper &ObjCTypes) { 1294 std::vector<llvm::Constant*> Properties, Prop(2); 1295 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()), 1296 E = OCD->prop_end(CGM.getContext()); I != E; ++I) { 1297 const ObjCPropertyDecl *PD = *I; 1298 Prop[0] = GetPropertyName(PD->getIdentifier()); 1299 Prop[1] = GetPropertyTypeString(PD, Container); 1300 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, 1301 Prop)); 1302 } 1303 1304 // Return null for empty list. 1305 if (Properties.empty()) 1306 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 1307 1308 unsigned PropertySize = 1309 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy); 1310 std::vector<llvm::Constant*> Values(3); 1311 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize); 1312 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size()); 1313 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy, 1314 Properties.size()); 1315 Values[2] = llvm::ConstantArray::get(AT, Properties); 1316 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1317 1318 llvm::GlobalVariable *GV = 1319 CreateMetadataVar(Name, Init, 1320 (ObjCABI == 2) ? "__DATA, __objc_const" : 1321 "__OBJC,__property,regular,no_dead_strip", 1322 (ObjCABI == 2) ? 8 : 4, 1323 true); 1324 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy); 1325} 1326 1327/* 1328 struct objc_method_description_list { 1329 int count; 1330 struct objc_method_description list[]; 1331 }; 1332*/ 1333llvm::Constant * 1334CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { 1335 std::vector<llvm::Constant*> Desc(2); 1336 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 1337 ObjCTypes.SelectorPtrTy); 1338 Desc[1] = GetMethodVarType(MD); 1339 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy, 1340 Desc); 1341} 1342 1343llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name, 1344 const char *Section, 1345 const ConstantVector &Methods) { 1346 // Return null for empty list. 1347 if (Methods.empty()) 1348 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 1349 1350 std::vector<llvm::Constant*> Values(2); 1351 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 1352 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy, 1353 Methods.size()); 1354 Values[1] = llvm::ConstantArray::get(AT, Methods); 1355 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1356 1357 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true); 1358 return llvm::ConstantExpr::getBitCast(GV, 1359 ObjCTypes.MethodDescriptionListPtrTy); 1360} 1361 1362/* 1363 struct _objc_category { 1364 char *category_name; 1365 char *class_name; 1366 struct _objc_method_list *instance_methods; 1367 struct _objc_method_list *class_methods; 1368 struct _objc_protocol_list *protocols; 1369 uint32_t size; // <rdar://4585769> 1370 struct _objc_property_list *instance_properties; 1371 }; 1372 */ 1373void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 1374 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy); 1375 1376 // FIXME: This is poor design, the OCD should have a pointer to the 1377 // category decl. Additionally, note that Category can be null for 1378 // the @implementation w/o an @interface case. Sema should just 1379 // create one for us as it does for @implementation so everyone else 1380 // can live life under a clear blue sky. 1381 const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); 1382 const ObjCCategoryDecl *Category = 1383 Interface->FindCategoryDeclaration(OCD->getIdentifier()); 1384 std::string ExtName(Interface->getNameAsString() + "_" + 1385 OCD->getNameAsString()); 1386 1387 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 1388 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(), 1389 e = OCD->instmeth_end(); i != e; ++i) { 1390 // Instance methods should always be defined. 1391 InstanceMethods.push_back(GetMethodConstant(*i)); 1392 } 1393 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(), 1394 e = OCD->classmeth_end(); i != e; ++i) { 1395 // Class methods should always be defined. 1396 ClassMethods.push_back(GetMethodConstant(*i)); 1397 } 1398 1399 std::vector<llvm::Constant*> Values(7); 1400 Values[0] = GetClassName(OCD->getIdentifier()); 1401 Values[1] = GetClassName(Interface->getIdentifier()); 1402 Values[2] = 1403 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") + 1404 ExtName, 1405 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 1406 InstanceMethods); 1407 Values[3] = 1408 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName, 1409 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 1410 ClassMethods); 1411 if (Category) { 1412 Values[4] = 1413 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName, 1414 Category->protocol_begin(), 1415 Category->protocol_end()); 1416 } else { 1417 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 1418 } 1419 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 1420 1421 // If there is no category @interface then there can be no properties. 1422 if (Category) { 1423 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName, 1424 OCD, Category, ObjCTypes); 1425 } else { 1426 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 1427 } 1428 1429 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy, 1430 Values); 1431 1432 llvm::GlobalVariable *GV = 1433 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init, 1434 "__OBJC,__category,regular,no_dead_strip", 1435 4, true); 1436 DefinedCategories.push_back(GV); 1437} 1438 1439// FIXME: Get from somewhere? 1440enum ClassFlags { 1441 eClassFlags_Factory = 0x00001, 1442 eClassFlags_Meta = 0x00002, 1443 // <rdr://5142207> 1444 eClassFlags_HasCXXStructors = 0x02000, 1445 eClassFlags_Hidden = 0x20000, 1446 eClassFlags_ABI2_Hidden = 0x00010, 1447 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634> 1448}; 1449 1450/* 1451 struct _objc_class { 1452 Class isa; 1453 Class super_class; 1454 const char *name; 1455 long version; 1456 long info; 1457 long instance_size; 1458 struct _objc_ivar_list *ivars; 1459 struct _objc_method_list *methods; 1460 struct _objc_cache *cache; 1461 struct _objc_protocol_list *protocols; 1462 // Objective-C 1.0 extensions (<rdr://4585769>) 1463 const char *ivar_layout; 1464 struct _objc_class_ext *ext; 1465 }; 1466 1467 See EmitClassExtension(); 1468 */ 1469void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) { 1470 DefinedSymbols.insert(ID->getIdentifier()); 1471 1472 std::string ClassName = ID->getNameAsString(); 1473 // FIXME: Gross 1474 ObjCInterfaceDecl *Interface = 1475 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); 1476 llvm::Constant *Protocols = 1477 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(), 1478 Interface->protocol_begin(), 1479 Interface->protocol_end()); 1480 const llvm::Type *InterfaceTy = 1481 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface)); 1482 unsigned Flags = eClassFlags_Factory; 1483 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy); 1484 1485 // FIXME: Set CXX-structors flag. 1486 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden) 1487 Flags |= eClassFlags_Hidden; 1488 1489 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 1490 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(), 1491 e = ID->instmeth_end(); i != e; ++i) { 1492 // Instance methods should always be defined. 1493 InstanceMethods.push_back(GetMethodConstant(*i)); 1494 } 1495 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(), 1496 e = ID->classmeth_end(); i != e; ++i) { 1497 // Class methods should always be defined. 1498 ClassMethods.push_back(GetMethodConstant(*i)); 1499 } 1500 1501 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(), 1502 e = ID->propimpl_end(); i != e; ++i) { 1503 ObjCPropertyImplDecl *PID = *i; 1504 1505 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1506 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1507 1508 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) 1509 if (llvm::Constant *C = GetMethodConstant(MD)) 1510 InstanceMethods.push_back(C); 1511 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) 1512 if (llvm::Constant *C = GetMethodConstant(MD)) 1513 InstanceMethods.push_back(C); 1514 } 1515 } 1516 1517 std::vector<llvm::Constant*> Values(12); 1518 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods); 1519 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) { 1520 // Record a reference to the super class. 1521 LazySymbols.insert(Super->getIdentifier()); 1522 1523 Values[ 1] = 1524 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), 1525 ObjCTypes.ClassPtrTy); 1526 } else { 1527 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 1528 } 1529 Values[ 2] = GetClassName(ID->getIdentifier()); 1530 // Version is always 0. 1531 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1532 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 1533 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1534 Values[ 6] = EmitIvarList(ID, false); 1535 Values[ 7] = 1536 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(), 1537 "__OBJC,__inst_meth,regular,no_dead_strip", 1538 InstanceMethods); 1539 // cache is always NULL. 1540 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 1541 Values[ 9] = Protocols; 1542 // FIXME: Set ivar_layout 1543 // Values[10] = BuildIvarLayout(ID, true); 1544 Values[10] = GetIvarLayoutName(0, ObjCTypes); 1545 Values[11] = EmitClassExtension(ID); 1546 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 1547 Values); 1548 1549 llvm::GlobalVariable *GV = 1550 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init, 1551 "__OBJC,__class,regular,no_dead_strip", 1552 4, true); 1553 DefinedClasses.push_back(GV); 1554} 1555 1556llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID, 1557 llvm::Constant *Protocols, 1558 const llvm::Type *InterfaceTy, 1559 const ConstantVector &Methods) { 1560 unsigned Flags = eClassFlags_Meta; 1561 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy); 1562 1563 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden) 1564 Flags |= eClassFlags_Hidden; 1565 1566 std::vector<llvm::Constant*> Values(12); 1567 // The isa for the metaclass is the root of the hierarchy. 1568 const ObjCInterfaceDecl *Root = ID->getClassInterface(); 1569 while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) 1570 Root = Super; 1571 Values[ 0] = 1572 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()), 1573 ObjCTypes.ClassPtrTy); 1574 // The super class for the metaclass is emitted as the name of the 1575 // super class. The runtime fixes this up to point to the 1576 // *metaclass* for the super class. 1577 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) { 1578 Values[ 1] = 1579 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), 1580 ObjCTypes.ClassPtrTy); 1581 } else { 1582 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 1583 } 1584 Values[ 2] = GetClassName(ID->getIdentifier()); 1585 // Version is always 0. 1586 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1587 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 1588 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1589 Values[ 6] = EmitIvarList(ID, true); 1590 Values[ 7] = 1591 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(), 1592 "__OBJC,__cls_meth,regular,no_dead_strip", 1593 Methods); 1594 // cache is always NULL. 1595 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 1596 Values[ 9] = Protocols; 1597 // ivar_layout for metaclass is always NULL. 1598 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1599 // The class extension is always unused for metaclasses. 1600 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 1601 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 1602 Values); 1603 1604 std::string Name("\01L_OBJC_METACLASS_"); 1605 Name += ID->getNameAsCString(); 1606 1607 // Check for a forward reference. 1608 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); 1609 if (GV) { 1610 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 1611 "Forward metaclass reference has incorrect type."); 1612 GV->setLinkage(llvm::GlobalValue::InternalLinkage); 1613 GV->setInitializer(Init); 1614 } else { 1615 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1616 llvm::GlobalValue::InternalLinkage, 1617 Init, Name, 1618 &CGM.getModule()); 1619 } 1620 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip"); 1621 GV->setAlignment(4); 1622 UsedGlobals.push_back(GV); 1623 1624 return GV; 1625} 1626 1627llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) { 1628 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString(); 1629 1630 // FIXME: Should we look these up somewhere other than the 1631 // module. Its a bit silly since we only generate these while 1632 // processing an implementation, so exactly one pointer would work 1633 // if know when we entered/exitted an implementation block. 1634 1635 // Check for an existing forward reference. 1636 // Previously, metaclass with internal linkage may have been defined. 1637 // pass 'true' as 2nd argument so it is returned. 1638 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) { 1639 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 1640 "Forward metaclass reference has incorrect type."); 1641 return GV; 1642 } else { 1643 // Generate as an external reference to keep a consistent 1644 // module. This will be patched up when we emit the metaclass. 1645 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1646 llvm::GlobalValue::ExternalLinkage, 1647 0, 1648 Name, 1649 &CGM.getModule()); 1650 } 1651} 1652 1653/* 1654 struct objc_class_ext { 1655 uint32_t size; 1656 const char *weak_ivar_layout; 1657 struct _objc_property_list *properties; 1658 }; 1659*/ 1660llvm::Constant * 1661CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) { 1662 uint64_t Size = 1663 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy); 1664 1665 std::vector<llvm::Constant*> Values(3); 1666 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 1667 // FIXME: Output weak_ivar_layout string. 1668 // Values[1] = BuildIvarLayout(ID, false); 1669 Values[1] = GetIvarLayoutName(0, ObjCTypes); 1670 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(), 1671 ID, ID->getClassInterface(), ObjCTypes); 1672 1673 // Return null if no extension bits are used. 1674 if (Values[1]->isNullValue() && Values[2]->isNullValue()) 1675 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 1676 1677 llvm::Constant *Init = 1678 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values); 1679 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(), 1680 Init, "__OBJC,__class_ext,regular,no_dead_strip", 1681 4, true); 1682} 1683 1684/// countInheritedIvars - count number of ivars in class and its super class(s) 1685/// 1686static int countInheritedIvars(const ObjCInterfaceDecl *OI, 1687 ASTContext &Context) { 1688 int count = 0; 1689 if (!OI) 1690 return 0; 1691 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass(); 1692 if (SuperClass) 1693 count += countInheritedIvars(SuperClass, Context); 1694 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 1695 E = OI->ivar_end(); I != E; ++I) 1696 ++count; 1697 // look into properties. 1698 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context), 1699 E = OI->prop_end(Context); I != E; ++I) { 1700 if ((*I)->getPropertyIvarDecl()) 1701 ++count; 1702 } 1703 return count; 1704} 1705 1706/// getInterfaceDeclForIvar - Get the interface declaration node where 1707/// this ivar is declared in. 1708/// FIXME. Ideally, this info should be in the ivar node. But currently 1709/// it is not and prevailing wisdom is that ASTs should not have more 1710/// info than is absolutely needed, even though this info reflects the 1711/// source language. 1712/// 1713static const ObjCInterfaceDecl *getInterfaceDeclForIvar( 1714 const ObjCInterfaceDecl *OI, 1715 const ObjCIvarDecl *IVD, 1716 ASTContext &Context) { 1717 if (!OI) 1718 return 0; 1719 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface"); 1720 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 1721 E = OI->ivar_end(); I != E; ++I) 1722 if ((*I)->getIdentifier() == IVD->getIdentifier()) 1723 return OI; 1724 // look into properties. 1725 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context), 1726 E = OI->prop_end(Context); I != E; ++I) { 1727 ObjCPropertyDecl *PDecl = (*I); 1728 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) 1729 if (IV->getIdentifier() == IVD->getIdentifier()) 1730 return OI; 1731 } 1732 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context); 1733} 1734 1735/* 1736 struct objc_ivar { 1737 char *ivar_name; 1738 char *ivar_type; 1739 int ivar_offset; 1740 }; 1741 1742 struct objc_ivar_list { 1743 int ivar_count; 1744 struct objc_ivar list[count]; 1745 }; 1746 */ 1747llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID, 1748 bool ForClass) { 1749 std::vector<llvm::Constant*> Ivars, Ivar(3); 1750 1751 // When emitting the root class GCC emits ivar entries for the 1752 // actual class structure. It is not clear if we need to follow this 1753 // behavior; for now lets try and get away with not doing it. If so, 1754 // the cleanest solution would be to make up an ObjCInterfaceDecl 1755 // for the class. 1756 if (ForClass) 1757 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 1758 1759 ObjCInterfaceDecl *OID = 1760 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); 1761 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID); 1762 1763 RecordDecl::field_iterator ifield, pfield; 1764 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield); 1765 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()); 1766 ifield != e; ++ifield) { 1767 FieldDecl *Field = *ifield; 1768 uint64_t Offset = GetIvarBaseOffset(Layout, Field); 1769 if (Field->getIdentifier()) 1770 Ivar[0] = GetMethodVarName(Field->getIdentifier()); 1771 else 1772 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1773 Ivar[1] = GetMethodVarType(Field); 1774 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset); 1775 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar)); 1776 } 1777 1778 // Return null for empty list. 1779 if (Ivars.empty()) 1780 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 1781 1782 std::vector<llvm::Constant*> Values(2); 1783 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); 1784 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy, 1785 Ivars.size()); 1786 Values[1] = llvm::ConstantArray::get(AT, Ivars); 1787 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1788 1789 llvm::GlobalVariable *GV; 1790 if (ForClass) 1791 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(), 1792 Init, "__OBJC,__class_vars,regular,no_dead_strip", 1793 4, true); 1794 else 1795 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_" 1796 + ID->getNameAsString(), 1797 Init, "__OBJC,__instance_vars,regular,no_dead_strip", 1798 4, true); 1799 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy); 1800} 1801 1802/* 1803 struct objc_method { 1804 SEL method_name; 1805 char *method_types; 1806 void *method; 1807 }; 1808 1809 struct objc_method_list { 1810 struct objc_method_list *obsolete; 1811 int count; 1812 struct objc_method methods_list[count]; 1813 }; 1814*/ 1815 1816/// GetMethodConstant - Return a struct objc_method constant for the 1817/// given method if it has been defined. The result is null if the 1818/// method has not been defined. The return value has type MethodPtrTy. 1819llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) { 1820 // FIXME: Use DenseMap::lookup 1821 llvm::Function *Fn = MethodDefinitions[MD]; 1822 if (!Fn) 1823 return 0; 1824 1825 std::vector<llvm::Constant*> Method(3); 1826 Method[0] = 1827 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 1828 ObjCTypes.SelectorPtrTy); 1829 Method[1] = GetMethodVarType(MD); 1830 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy); 1831 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); 1832} 1833 1834llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name, 1835 const char *Section, 1836 const ConstantVector &Methods) { 1837 // Return null for empty list. 1838 if (Methods.empty()) 1839 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy); 1840 1841 std::vector<llvm::Constant*> Values(3); 1842 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1843 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 1844 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, 1845 Methods.size()); 1846 Values[2] = llvm::ConstantArray::get(AT, Methods); 1847 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1848 1849 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true); 1850 return llvm::ConstantExpr::getBitCast(GV, 1851 ObjCTypes.MethodListPtrTy); 1852} 1853 1854llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD, 1855 const ObjCContainerDecl *CD) { 1856 std::string Name; 1857 GetNameForMethod(OMD, CD, Name); 1858 1859 CodeGenTypes &Types = CGM.getTypes(); 1860 const llvm::FunctionType *MethodTy = 1861 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic()); 1862 llvm::Function *Method = 1863 llvm::Function::Create(MethodTy, 1864 llvm::GlobalValue::InternalLinkage, 1865 Name, 1866 &CGM.getModule()); 1867 MethodDefinitions.insert(std::make_pair(OMD, Method)); 1868 1869 return Method; 1870} 1871 1872uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout, 1873 const FieldDecl *Field) { 1874 if (!Field->isBitField()) 1875 return Layout->getElementOffset( 1876 CGM.getTypes().getLLVMFieldNo(Field)); 1877 // FIXME. Must be a better way of getting a bitfield base offset. 1878 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field); 1879 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType()); 1880 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty); 1881 offset = (offset*size)/8; 1882 return offset; 1883} 1884 1885/// GetFieldBaseOffset - return's field byt offset. 1886uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI, 1887 const llvm::StructLayout *Layout, 1888 const FieldDecl *Field) { 1889 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); 1890 const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar); 1891 return GetIvarBaseOffset(Layout, FD); 1892} 1893 1894llvm::GlobalVariable * 1895CGObjCCommonMac::CreateMetadataVar(const std::string &Name, 1896 llvm::Constant *Init, 1897 const char *Section, 1898 unsigned Align, 1899 bool AddToUsed) { 1900 const llvm::Type *Ty = Init->getType(); 1901 llvm::GlobalVariable *GV = 1902 new llvm::GlobalVariable(Ty, false, 1903 llvm::GlobalValue::InternalLinkage, 1904 Init, 1905 Name, 1906 &CGM.getModule()); 1907 if (Section) 1908 GV->setSection(Section); 1909 if (Align) 1910 GV->setAlignment(Align); 1911 if (AddToUsed) 1912 UsedGlobals.push_back(GV); 1913 return GV; 1914} 1915 1916llvm::Function *CGObjCMac::ModuleInitFunction() { 1917 // Abuse this interface function as a place to finalize. 1918 FinishModule(); 1919 1920 return NULL; 1921} 1922 1923llvm::Constant *CGObjCMac::GetPropertyGetFunction() { 1924 return ObjCTypes.GetPropertyFn; 1925} 1926 1927llvm::Constant *CGObjCMac::GetPropertySetFunction() { 1928 return ObjCTypes.SetPropertyFn; 1929} 1930 1931llvm::Constant *CGObjCMac::EnumerationMutationFunction() { 1932 return ObjCTypes.EnumerationMutationFn; 1933} 1934 1935/* 1936 1937Objective-C setjmp-longjmp (sjlj) Exception Handling 1938-- 1939 1940The basic framework for a @try-catch-finally is as follows: 1941{ 1942 objc_exception_data d; 1943 id _rethrow = null; 1944 bool _call_try_exit = true; 1945 1946 objc_exception_try_enter(&d); 1947 if (!setjmp(d.jmp_buf)) { 1948 ... try body ... 1949 } else { 1950 // exception path 1951 id _caught = objc_exception_extract(&d); 1952 1953 // enter new try scope for handlers 1954 if (!setjmp(d.jmp_buf)) { 1955 ... match exception and execute catch blocks ... 1956 1957 // fell off end, rethrow. 1958 _rethrow = _caught; 1959 ... jump-through-finally to finally_rethrow ... 1960 } else { 1961 // exception in catch block 1962 _rethrow = objc_exception_extract(&d); 1963 _call_try_exit = false; 1964 ... jump-through-finally to finally_rethrow ... 1965 } 1966 } 1967 ... jump-through-finally to finally_end ... 1968 1969finally: 1970 if (_call_try_exit) 1971 objc_exception_try_exit(&d); 1972 1973 ... finally block .... 1974 ... dispatch to finally destination ... 1975 1976finally_rethrow: 1977 objc_exception_throw(_rethrow); 1978 1979finally_end: 1980} 1981 1982This framework differs slightly from the one gcc uses, in that gcc 1983uses _rethrow to determine if objc_exception_try_exit should be called 1984and if the object should be rethrown. This breaks in the face of 1985throwing nil and introduces unnecessary branches. 1986 1987We specialize this framework for a few particular circumstances: 1988 1989 - If there are no catch blocks, then we avoid emitting the second 1990 exception handling context. 1991 1992 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id 1993 e)) we avoid emitting the code to rethrow an uncaught exception. 1994 1995 - FIXME: If there is no @finally block we can do a few more 1996 simplifications. 1997 1998Rethrows and Jumps-Through-Finally 1999-- 2000 2001Support for implicit rethrows and jumping through the finally block is 2002handled by storing the current exception-handling context in 2003ObjCEHStack. 2004 2005In order to implement proper @finally semantics, we support one basic 2006mechanism for jumping through the finally block to an arbitrary 2007destination. Constructs which generate exits from a @try or @catch 2008block use this mechanism to implement the proper semantics by chaining 2009jumps, as necessary. 2010 2011This mechanism works like the one used for indirect goto: we 2012arbitrarily assign an ID to each destination and store the ID for the 2013destination in a variable prior to entering the finally block. At the 2014end of the finally block we simply create a switch to the proper 2015destination. 2016 2017Code gen for @synchronized(expr) stmt; 2018Effectively generating code for: 2019objc_sync_enter(expr); 2020@try stmt @finally { objc_sync_exit(expr); } 2021*/ 2022 2023void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 2024 const Stmt &S) { 2025 bool isTry = isa<ObjCAtTryStmt>(S); 2026 // Create various blocks we refer to for handling @finally. 2027 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally"); 2028 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit"); 2029 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit"); 2030 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw"); 2031 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end"); 2032 2033 // For @synchronized, call objc_sync_enter(sync.expr). The 2034 // evaluation of the expression must occur before we enter the 2035 // @synchronized. We can safely avoid a temp here because jumps into 2036 // @synchronized are illegal & this will dominate uses. 2037 llvm::Value *SyncArg = 0; 2038 if (!isTry) { 2039 SyncArg = 2040 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 2041 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy); 2042 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg); 2043 } 2044 2045 // Push an EH context entry, used for handling rethrows and jumps 2046 // through finally. 2047 CGF.PushCleanupBlock(FinallyBlock); 2048 2049 CGF.ObjCEHValueStack.push_back(0); 2050 2051 // Allocate memory for the exception data and rethrow pointer. 2052 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy, 2053 "exceptiondata.ptr"); 2054 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy, 2055 "_rethrow"); 2056 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty, 2057 "_call_try_exit"); 2058 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr); 2059 2060 // Enter a new try block and call setjmp. 2061 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData); 2062 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0, 2063 "jmpbufarray"); 2064 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp"); 2065 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn, 2066 JmpBufPtr, "result"); 2067 2068 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); 2069 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); 2070 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"), 2071 TryHandler, TryBlock); 2072 2073 // Emit the @try block. 2074 CGF.EmitBlock(TryBlock); 2075 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() 2076 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); 2077 CGF.EmitBranchThroughCleanup(FinallyEnd); 2078 2079 // Emit the "exception in @try" block. 2080 CGF.EmitBlock(TryHandler); 2081 2082 // Retrieve the exception object. We may emit multiple blocks but 2083 // nothing can cross this so the value is already in SSA form. 2084 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn, 2085 ExceptionData, 2086 "caught"); 2087 CGF.ObjCEHValueStack.back() = Caught; 2088 if (!isTry) 2089 { 2090 CGF.Builder.CreateStore(Caught, RethrowPtr); 2091 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr); 2092 CGF.EmitBranchThroughCleanup(FinallyRethrow); 2093 } 2094 else if (const ObjCAtCatchStmt* CatchStmt = 2095 cast<ObjCAtTryStmt>(S).getCatchStmts()) 2096 { 2097 // Enter a new exception try block (in case a @catch block throws 2098 // an exception). 2099 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData); 2100 2101 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn, 2102 JmpBufPtr, "result"); 2103 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"); 2104 2105 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch"); 2106 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler"); 2107 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock); 2108 2109 CGF.EmitBlock(CatchBlock); 2110 2111 // Handle catch list. As a special case we check if everything is 2112 // matched and avoid generating code for falling off the end if 2113 // so. 2114 bool AllMatched = false; 2115 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) { 2116 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch"); 2117 2118 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl(); 2119 const PointerType *PT = 0; 2120 2121 // catch(...) always matches. 2122 if (!CatchParam) { 2123 AllMatched = true; 2124 } else { 2125 PT = CatchParam->getType()->getAsPointerType(); 2126 2127 // catch(id e) always matches. 2128 // FIXME: For the time being we also match id<X>; this should 2129 // be rejected by Sema instead. 2130 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) || 2131 CatchParam->getType()->isObjCQualifiedIdType()) 2132 AllMatched = true; 2133 } 2134 2135 if (AllMatched) { 2136 if (CatchParam) { 2137 CGF.EmitLocalBlockVarDecl(*CatchParam); 2138 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); 2139 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam)); 2140 } 2141 2142 CGF.EmitStmt(CatchStmt->getCatchBody()); 2143 CGF.EmitBranchThroughCleanup(FinallyEnd); 2144 break; 2145 } 2146 2147 assert(PT && "Unexpected non-pointer type in @catch"); 2148 QualType T = PT->getPointeeType(); 2149 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType(); 2150 assert(ObjCType && "Catch parameter must have Objective-C type!"); 2151 2152 // Check if the @catch block matches the exception object. 2153 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl()); 2154 2155 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn, 2156 Class, Caught, "match"); 2157 2158 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched"); 2159 2160 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"), 2161 MatchedBlock, NextCatchBlock); 2162 2163 // Emit the @catch block. 2164 CGF.EmitBlock(MatchedBlock); 2165 CGF.EmitLocalBlockVarDecl(*CatchParam); 2166 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); 2167 2168 llvm::Value *Tmp = 2169 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()), 2170 "tmp"); 2171 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam)); 2172 2173 CGF.EmitStmt(CatchStmt->getCatchBody()); 2174 CGF.EmitBranchThroughCleanup(FinallyEnd); 2175 2176 CGF.EmitBlock(NextCatchBlock); 2177 } 2178 2179 if (!AllMatched) { 2180 // None of the handlers caught the exception, so store it to be 2181 // rethrown at the end of the @finally block. 2182 CGF.Builder.CreateStore(Caught, RethrowPtr); 2183 CGF.EmitBranchThroughCleanup(FinallyRethrow); 2184 } 2185 2186 // Emit the exception handler for the @catch blocks. 2187 CGF.EmitBlock(CatchHandler); 2188 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn, 2189 ExceptionData), 2190 RethrowPtr); 2191 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr); 2192 CGF.EmitBranchThroughCleanup(FinallyRethrow); 2193 } else { 2194 CGF.Builder.CreateStore(Caught, RethrowPtr); 2195 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr); 2196 CGF.EmitBranchThroughCleanup(FinallyRethrow); 2197 } 2198 2199 // Pop the exception-handling stack entry. It is important to do 2200 // this now, because the code in the @finally block is not in this 2201 // context. 2202 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); 2203 2204 CGF.ObjCEHValueStack.pop_back(); 2205 2206 // Emit the @finally block. 2207 CGF.EmitBlock(FinallyBlock); 2208 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp"); 2209 2210 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit); 2211 2212 CGF.EmitBlock(FinallyExit); 2213 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData); 2214 2215 CGF.EmitBlock(FinallyNoExit); 2216 if (isTry) { 2217 if (const ObjCAtFinallyStmt* FinallyStmt = 2218 cast<ObjCAtTryStmt>(S).getFinallyStmt()) 2219 CGF.EmitStmt(FinallyStmt->getFinallyBody()); 2220 } else { 2221 // Emit objc_sync_exit(expr); as finally's sole statement for 2222 // @synchronized. 2223 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg); 2224 } 2225 2226 // Emit the switch block 2227 if (Info.SwitchBlock) 2228 CGF.EmitBlock(Info.SwitchBlock); 2229 if (Info.EndBlock) 2230 CGF.EmitBlock(Info.EndBlock); 2231 2232 CGF.EmitBlock(FinallyRethrow); 2233 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, 2234 CGF.Builder.CreateLoad(RethrowPtr)); 2235 CGF.Builder.CreateUnreachable(); 2236 2237 CGF.EmitBlock(FinallyEnd); 2238} 2239 2240void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 2241 const ObjCAtThrowStmt &S) { 2242 llvm::Value *ExceptionAsObject; 2243 2244 if (const Expr *ThrowExpr = S.getThrowExpr()) { 2245 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr); 2246 ExceptionAsObject = 2247 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp"); 2248 } else { 2249 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 2250 "Unexpected rethrow outside @catch block."); 2251 ExceptionAsObject = CGF.ObjCEHValueStack.back(); 2252 } 2253 2254 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject); 2255 CGF.Builder.CreateUnreachable(); 2256 2257 // Clear the insertion point to indicate we are in unreachable code. 2258 CGF.Builder.ClearInsertionPoint(); 2259} 2260 2261/// EmitObjCWeakRead - Code gen for loading value of a __weak 2262/// object: objc_read_weak (id *src) 2263/// 2264llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 2265 llvm::Value *AddrWeakObj) 2266{ 2267 const llvm::Type* DestTy = 2268 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType(); 2269 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); 2270 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn, 2271 AddrWeakObj, "weakread"); 2272 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy); 2273 return read_weak; 2274} 2275 2276/// EmitObjCWeakAssign - Code gen for assigning to a __weak object. 2277/// objc_assign_weak (id src, id *dst) 2278/// 2279void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 2280 llvm::Value *src, llvm::Value *dst) 2281{ 2282 const llvm::Type * SrcTy = src->getType(); 2283 if (!isa<llvm::PointerType>(SrcTy)) { 2284 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 2285 assert(Size <= 8 && "does not support size > 8"); 2286 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 2287 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 2288 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 2289 } 2290 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2291 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2292 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(), 2293 src, dst, "weakassign"); 2294 return; 2295} 2296 2297/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. 2298/// objc_assign_global (id src, id *dst) 2299/// 2300void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 2301 llvm::Value *src, llvm::Value *dst) 2302{ 2303 const llvm::Type * SrcTy = src->getType(); 2304 if (!isa<llvm::PointerType>(SrcTy)) { 2305 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 2306 assert(Size <= 8 && "does not support size > 8"); 2307 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 2308 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 2309 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 2310 } 2311 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2312 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2313 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn, 2314 src, dst, "globalassign"); 2315 return; 2316} 2317 2318/// EmitObjCIvarAssign - Code gen for assigning to a __strong object. 2319/// objc_assign_ivar (id src, id *dst) 2320/// 2321void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 2322 llvm::Value *src, llvm::Value *dst) 2323{ 2324 const llvm::Type * SrcTy = src->getType(); 2325 if (!isa<llvm::PointerType>(SrcTy)) { 2326 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 2327 assert(Size <= 8 && "does not support size > 8"); 2328 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 2329 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 2330 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 2331 } 2332 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2333 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2334 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn, 2335 src, dst, "assignivar"); 2336 return; 2337} 2338 2339/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. 2340/// objc_assign_strongCast (id src, id *dst) 2341/// 2342void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 2343 llvm::Value *src, llvm::Value *dst) 2344{ 2345 const llvm::Type * SrcTy = src->getType(); 2346 if (!isa<llvm::PointerType>(SrcTy)) { 2347 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 2348 assert(Size <= 8 && "does not support size > 8"); 2349 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 2350 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 2351 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 2352 } 2353 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2354 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2355 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn, 2356 src, dst, "weakassign"); 2357 return; 2358} 2359 2360/// EmitObjCValueForIvar - Code Gen for ivar reference. 2361/// 2362LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 2363 QualType ObjectTy, 2364 llvm::Value *BaseValue, 2365 const ObjCIvarDecl *Ivar, 2366 const FieldDecl *Field, 2367 unsigned CVRQualifiers) { 2368 if (Ivar->isBitField()) 2369 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field), 2370 CVRQualifiers); 2371 // TODO: Add a special case for isa (index 0) 2372 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field); 2373 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp"); 2374 LValue LV = LValue::MakeAddr(V, 2375 Ivar->getType().getCVRQualifiers()|CVRQualifiers, 2376 CGM.getContext().getObjCGCAttrKind(Ivar->getType())); 2377 LValue::SetObjCIvar(LV, true); 2378 return LV; 2379} 2380 2381llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 2382 ObjCInterfaceDecl *Interface, 2383 const ObjCIvarDecl *Ivar) { 2384 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface); 2385 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar); 2386 uint64_t Offset = GetIvarBaseOffset(Layout, Field); 2387 return llvm::ConstantInt::get( 2388 CGM.getTypes().ConvertType(CGM.getContext().LongTy), 2389 Offset); 2390} 2391 2392/* *** Private Interface *** */ 2393 2394/// EmitImageInfo - Emit the image info marker used to encode some module 2395/// level information. 2396/// 2397/// See: <rdr://4810609&4810587&4810587> 2398/// struct IMAGE_INFO { 2399/// unsigned version; 2400/// unsigned flags; 2401/// }; 2402enum ImageInfoFlags { 2403 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies 2404 eImageInfo_GarbageCollected = (1 << 1), 2405 eImageInfo_GCOnly = (1 << 2) 2406}; 2407 2408void CGObjCMac::EmitImageInfo() { 2409 unsigned version = 0; // Version is unused? 2410 unsigned flags = 0; 2411 2412 // FIXME: Fix and continue? 2413 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) 2414 flags |= eImageInfo_GarbageCollected; 2415 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) 2416 flags |= eImageInfo_GCOnly; 2417 2418 // Emitted as int[2]; 2419 llvm::Constant *values[2] = { 2420 llvm::ConstantInt::get(llvm::Type::Int32Ty, version), 2421 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags) 2422 }; 2423 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2); 2424 2425 const char *Section; 2426 if (ObjCABI == 1) 2427 Section = "__OBJC, __image_info,regular"; 2428 else 2429 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip"; 2430 llvm::GlobalVariable *GV = 2431 CreateMetadataVar("\01L_OBJC_IMAGE_INFO", 2432 llvm::ConstantArray::get(AT, values, 2), 2433 Section, 2434 0, 2435 true); 2436 GV->setConstant(true); 2437} 2438 2439 2440// struct objc_module { 2441// unsigned long version; 2442// unsigned long size; 2443// const char *name; 2444// Symtab symtab; 2445// }; 2446 2447// FIXME: Get from somewhere 2448static const int ModuleVersion = 7; 2449 2450void CGObjCMac::EmitModuleInfo() { 2451 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy); 2452 2453 std::vector<llvm::Constant*> Values(4); 2454 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion); 2455 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 2456 // This used to be the filename, now it is unused. <rdr://4327263> 2457 Values[2] = GetClassName(&CGM.getContext().Idents.get("")); 2458 Values[3] = EmitModuleSymbols(); 2459 CreateMetadataVar("\01L_OBJC_MODULES", 2460 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values), 2461 "__OBJC,__module_info,regular,no_dead_strip", 2462 4, true); 2463} 2464 2465llvm::Constant *CGObjCMac::EmitModuleSymbols() { 2466 unsigned NumClasses = DefinedClasses.size(); 2467 unsigned NumCategories = DefinedCategories.size(); 2468 2469 // Return null if no symbols were defined. 2470 if (!NumClasses && !NumCategories) 2471 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy); 2472 2473 std::vector<llvm::Constant*> Values(5); 2474 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 2475 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy); 2476 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses); 2477 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories); 2478 2479 // The runtime expects exactly the list of defined classes followed 2480 // by the list of defined categories, in a single array. 2481 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories); 2482 for (unsigned i=0; i<NumClasses; i++) 2483 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], 2484 ObjCTypes.Int8PtrTy); 2485 for (unsigned i=0; i<NumCategories; i++) 2486 Symbols[NumClasses + i] = 2487 llvm::ConstantExpr::getBitCast(DefinedCategories[i], 2488 ObjCTypes.Int8PtrTy); 2489 2490 Values[4] = 2491 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 2492 NumClasses + NumCategories), 2493 Symbols); 2494 2495 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 2496 2497 llvm::GlobalVariable *GV = 2498 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init, 2499 "__OBJC,__symbols,regular,no_dead_strip", 2500 4, true); 2501 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy); 2502} 2503 2504llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder, 2505 const ObjCInterfaceDecl *ID) { 2506 LazySymbols.insert(ID->getIdentifier()); 2507 2508 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()]; 2509 2510 if (!Entry) { 2511 llvm::Constant *Casted = 2512 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()), 2513 ObjCTypes.ClassPtrTy); 2514 Entry = 2515 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted, 2516 "__OBJC,__cls_refs,literal_pointers,no_dead_strip", 2517 4, true); 2518 } 2519 2520 return Builder.CreateLoad(Entry, false, "tmp"); 2521} 2522 2523llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) { 2524 llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; 2525 2526 if (!Entry) { 2527 llvm::Constant *Casted = 2528 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), 2529 ObjCTypes.SelectorPtrTy); 2530 Entry = 2531 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted, 2532 "__OBJC,__message_refs,literal_pointers,no_dead_strip", 2533 4, true); 2534 } 2535 2536 return Builder.CreateLoad(Entry, false, "tmp"); 2537} 2538 2539llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) { 2540 llvm::GlobalVariable *&Entry = ClassNames[Ident]; 2541 2542 if (!Entry) 2543 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_", 2544 llvm::ConstantArray::get(Ident->getName()), 2545 "__TEXT,__cstring,cstring_literals", 2546 1, true); 2547 2548 return getConstantGEP(Entry, 0, 0); 2549} 2550 2551/// GetInterfaceDeclStructLayout - Get layout for ivars of given 2552/// interface declaration. 2553const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout( 2554 const ObjCInterfaceDecl *OID) const { 2555 const llvm::Type *InterfaceTy = 2556 CGM.getTypes().ConvertType( 2557 CGM.getContext().getObjCInterfaceType( 2558 const_cast<ObjCInterfaceDecl*>(OID))); 2559 const llvm::StructLayout *Layout = 2560 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy)); 2561 return Layout; 2562} 2563 2564/// GetIvarLayoutName - Returns a unique constant for the given 2565/// ivar layout bitmap. 2566llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident, 2567 const ObjCCommonTypesHelper &ObjCTypes) { 2568 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 2569} 2570 2571void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI, 2572 const llvm::StructLayout *Layout, 2573 const RecordDecl *RD, 2574 const llvm::SmallVectorImpl<FieldDecl*> &RecFields, 2575 unsigned int BytePos, bool ForStrongLayout, 2576 int &Index, int &SkIndex, bool &HasUnion) { 2577 bool IsUnion = (RD && RD->isUnion()); 2578 uint64_t MaxUnionIvarSize = 0; 2579 uint64_t MaxSkippedUnionIvarSize = 0; 2580 FieldDecl *MaxField = 0; 2581 FieldDecl *MaxSkippedField = 0; 2582 unsigned base = 0; 2583 if (RecFields.empty()) 2584 return; 2585 if (IsUnion) 2586 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]); 2587 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0); 2588 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth(); 2589 2590 llvm::SmallVector<FieldDecl*, 16> TmpRecFields; 2591 2592 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 2593 FieldDecl *Field = RecFields[i]; 2594 // Skip over unnamed or bitfields 2595 if (!Field->getIdentifier() || Field->isBitField()) 2596 continue; 2597 QualType FQT = Field->getType(); 2598 if (FQT->isRecordType() || FQT->isUnionType()) { 2599 if (FQT->isUnionType()) 2600 HasUnion = true; 2601 else 2602 assert(FQT->isRecordType() && 2603 "only union/record is supported for ivar layout bitmap"); 2604 2605 const RecordType *RT = FQT->getAsRecordType(); 2606 const RecordDecl *RD = RT->getDecl(); 2607 // FIXME - Find a more efficiant way of passing records down. 2608 TmpRecFields.append(RD->field_begin(CGM.getContext()), 2609 RD->field_end(CGM.getContext())); 2610 // FIXME - Is Layout correct? 2611 BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields, 2612 BytePos + GetFieldBaseOffset(OI, Layout, Field), 2613 ForStrongLayout, Index, SkIndex, 2614 HasUnion); 2615 TmpRecFields.clear(); 2616 continue; 2617 } 2618 2619 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { 2620 const ConstantArrayType *CArray = 2621 dyn_cast_or_null<ConstantArrayType>(Array); 2622 assert(CArray && "only array with know element size is supported"); 2623 FQT = CArray->getElementType(); 2624 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { 2625 const ConstantArrayType *CArray = 2626 dyn_cast_or_null<ConstantArrayType>(Array); 2627 FQT = CArray->getElementType(); 2628 } 2629 2630 assert(!FQT->isUnionType() && 2631 "layout for array of unions not supported"); 2632 if (FQT->isRecordType()) { 2633 uint64_t ElCount = CArray->getSize().getZExtValue(); 2634 int OldIndex = Index; 2635 int OldSkIndex = SkIndex; 2636 2637 // FIXME - Use a common routine with the above! 2638 const RecordType *RT = FQT->getAsRecordType(); 2639 const RecordDecl *RD = RT->getDecl(); 2640 // FIXME - Find a more efficiant way of passing records down. 2641 TmpRecFields.append(RD->field_begin(CGM.getContext()), 2642 RD->field_end(CGM.getContext())); 2643 2644 BuildAggrIvarLayout(OI, Layout, RD, 2645 TmpRecFields, 2646 BytePos + GetFieldBaseOffset(OI, Layout, Field), 2647 ForStrongLayout, Index, SkIndex, 2648 HasUnion); 2649 TmpRecFields.clear(); 2650 2651 // Replicate layout information for each array element. Note that 2652 // one element is already done. 2653 uint64_t ElIx = 1; 2654 for (int FirstIndex = Index, FirstSkIndex = SkIndex; 2655 ElIx < ElCount; ElIx++) { 2656 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits; 2657 for (int i = OldIndex+1; i <= FirstIndex; ++i) 2658 { 2659 GC_IVAR gcivar; 2660 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx; 2661 gcivar.ivar_size = IvarsInfo[i].ivar_size; 2662 IvarsInfo.push_back(gcivar); ++Index; 2663 } 2664 2665 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) { 2666 GC_IVAR skivar; 2667 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx; 2668 skivar.ivar_size = SkipIvars[i].ivar_size; 2669 SkipIvars.push_back(skivar); ++SkIndex; 2670 } 2671 } 2672 continue; 2673 } 2674 } 2675 // At this point, we are done with Record/Union and array there of. 2676 // For other arrays we are down to its element type. 2677 QualType::GCAttrTypes GCAttr = QualType::GCNone; 2678 do { 2679 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) { 2680 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak; 2681 break; 2682 } 2683 else if (CGM.getContext().isObjCObjectPointerType(FQT)) { 2684 GCAttr = QualType::Strong; 2685 break; 2686 } 2687 else if (const PointerType *PT = FQT->getAsPointerType()) { 2688 FQT = PT->getPointeeType(); 2689 } 2690 else { 2691 break; 2692 } 2693 } while (true); 2694 2695 if ((ForStrongLayout && GCAttr == QualType::Strong) 2696 || (!ForStrongLayout && GCAttr == QualType::Weak)) { 2697 if (IsUnion) 2698 { 2699 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType()) 2700 / WordSizeInBits; 2701 if (UnionIvarSize > MaxUnionIvarSize) 2702 { 2703 MaxUnionIvarSize = UnionIvarSize; 2704 MaxField = Field; 2705 } 2706 } 2707 else 2708 { 2709 GC_IVAR gcivar; 2710 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field); 2711 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) / 2712 WordSizeInBits; 2713 IvarsInfo.push_back(gcivar); ++Index; 2714 } 2715 } 2716 else if ((ForStrongLayout && 2717 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak)) 2718 || (!ForStrongLayout && GCAttr != QualType::Weak)) { 2719 if (IsUnion) 2720 { 2721 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType()); 2722 if (UnionIvarSize > MaxSkippedUnionIvarSize) 2723 { 2724 MaxSkippedUnionIvarSize = UnionIvarSize; 2725 MaxSkippedField = Field; 2726 } 2727 } 2728 else 2729 { 2730 GC_IVAR skivar; 2731 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field); 2732 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) / 2733 WordSizeInBits; 2734 SkipIvars.push_back(skivar); ++SkIndex; 2735 } 2736 } 2737 } 2738 if (MaxField) { 2739 GC_IVAR gcivar; 2740 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField); 2741 gcivar.ivar_size = MaxUnionIvarSize; 2742 IvarsInfo.push_back(gcivar); ++Index; 2743 } 2744 2745 if (MaxSkippedField) { 2746 GC_IVAR skivar; 2747 skivar.ivar_bytepos = BytePos + 2748 GetFieldBaseOffset(OI, Layout, MaxSkippedField); 2749 skivar.ivar_size = MaxSkippedUnionIvarSize; 2750 SkipIvars.push_back(skivar); ++SkIndex; 2751 } 2752} 2753 2754static int 2755IvarBytePosCompare(const void *a, const void *b) 2756{ 2757 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos; 2758 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos; 2759 2760 if (sa < sb) 2761 return -1; 2762 if (sa > sb) 2763 return 1; 2764 return 0; 2765} 2766 2767/// BuildIvarLayout - Builds ivar layout bitmap for the class 2768/// implementation for the __strong or __weak case. 2769/// The layout map displays which words in ivar list must be skipped 2770/// and which must be scanned by GC (see below). String is built of bytes. 2771/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count 2772/// of words to skip and right nibble is count of words to scan. So, each 2773/// nibble represents up to 15 workds to skip or scan. Skipping the rest is 2774/// represented by a 0x00 byte which also ends the string. 2775/// 1. when ForStrongLayout is true, following ivars are scanned: 2776/// - id, Class 2777/// - object * 2778/// - __strong anything 2779/// 2780/// 2. When ForStrongLayout is false, following ivars are scanned: 2781/// - __weak anything 2782/// 2783llvm::Constant *CGObjCCommonMac::BuildIvarLayout( 2784 const ObjCImplementationDecl *OMD, 2785 bool ForStrongLayout) { 2786 int Index = -1; 2787 int SkIndex = -1; 2788 bool hasUnion = false; 2789 int SkipScan; 2790 unsigned int WordsToScan, WordsToSkip; 2791 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 2792 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC) 2793 return llvm::Constant::getNullValue(PtrTy); 2794 2795 llvm::SmallVector<FieldDecl*, 32> RecFields; 2796 const ObjCInterfaceDecl *OI = OMD->getClassInterface(); 2797 CGM.getContext().CollectObjCIvars(OI, RecFields); 2798 if (RecFields.empty()) 2799 return llvm::Constant::getNullValue(PtrTy); 2800 2801 SkipIvars.clear(); 2802 IvarsInfo.clear(); 2803 2804 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI); 2805 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout, 2806 Index, SkIndex, hasUnion); 2807 if (Index == -1) 2808 return llvm::Constant::getNullValue(PtrTy); 2809 2810 // Sort on byte position in case we encounterred a union nested in 2811 // the ivar list. 2812 if (hasUnion && !IvarsInfo.empty()) 2813 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare); 2814 if (hasUnion && !SkipIvars.empty()) 2815 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare); 2816 2817 // Build the string of skip/scan nibbles 2818 SkipScan = -1; 2819 SkipScanIvars.clear(); 2820 unsigned int WordSize = 2821 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy); 2822 if (IvarsInfo[0].ivar_bytepos == 0) { 2823 WordsToSkip = 0; 2824 WordsToScan = IvarsInfo[0].ivar_size; 2825 } 2826 else { 2827 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize; 2828 WordsToScan = IvarsInfo[0].ivar_size; 2829 } 2830 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) 2831 { 2832 unsigned int TailPrevGCObjC = 2833 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize; 2834 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) 2835 { 2836 // consecutive 'scanned' object pointers. 2837 WordsToScan += IvarsInfo[i].ivar_size; 2838 } 2839 else 2840 { 2841 // Skip over 'gc'able object pointer which lay over each other. 2842 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos) 2843 continue; 2844 // Must skip over 1 or more words. We save current skip/scan values 2845 // and start a new pair. 2846 SKIP_SCAN SkScan; 2847 SkScan.skip = WordsToSkip; 2848 SkScan.scan = WordsToScan; 2849 SkipScanIvars.push_back(SkScan); ++SkipScan; 2850 2851 // Skip the hole. 2852 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize; 2853 SkScan.scan = 0; 2854 SkipScanIvars.push_back(SkScan); ++SkipScan; 2855 WordsToSkip = 0; 2856 WordsToScan = IvarsInfo[i].ivar_size; 2857 } 2858 } 2859 if (WordsToScan > 0) 2860 { 2861 SKIP_SCAN SkScan; 2862 SkScan.skip = WordsToSkip; 2863 SkScan.scan = WordsToScan; 2864 SkipScanIvars.push_back(SkScan); ++SkipScan; 2865 } 2866 2867 bool BytesSkipped = false; 2868 if (!SkipIvars.empty()) 2869 { 2870 int LastByteSkipped = 2871 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size; 2872 int LastByteScanned = 2873 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize; 2874 BytesSkipped = (LastByteSkipped > LastByteScanned); 2875 // Compute number of bytes to skip at the tail end of the last ivar scanned. 2876 if (BytesSkipped) 2877 { 2878 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize; 2879 SKIP_SCAN SkScan; 2880 SkScan.skip = TotalWords - (LastByteScanned/WordSize); 2881 SkScan.scan = 0; 2882 SkipScanIvars.push_back(SkScan); ++SkipScan; 2883 } 2884 } 2885 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced 2886 // as 0xMN. 2887 for (int i = 0; i <= SkipScan; i++) 2888 { 2889 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0 2890 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) { 2891 // 0xM0 followed by 0x0N detected. 2892 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan; 2893 for (int j = i+1; j < SkipScan; j++) 2894 SkipScanIvars[j] = SkipScanIvars[j+1]; 2895 --SkipScan; 2896 } 2897 } 2898 2899 // Generate the string. 2900 std::string BitMap; 2901 for (int i = 0; i <= SkipScan; i++) 2902 { 2903 unsigned char byte; 2904 unsigned int skip_small = SkipScanIvars[i].skip % 0xf; 2905 unsigned int scan_small = SkipScanIvars[i].scan % 0xf; 2906 unsigned int skip_big = SkipScanIvars[i].skip / 0xf; 2907 unsigned int scan_big = SkipScanIvars[i].scan / 0xf; 2908 2909 if (skip_small > 0 || skip_big > 0) 2910 BytesSkipped = true; 2911 // first skip big. 2912 for (unsigned int ix = 0; ix < skip_big; ix++) 2913 BitMap += (unsigned char)(0xf0); 2914 2915 // next (skip small, scan) 2916 if (skip_small) 2917 { 2918 byte = skip_small << 4; 2919 if (scan_big > 0) 2920 { 2921 byte |= 0xf; 2922 --scan_big; 2923 } 2924 else if (scan_small) 2925 { 2926 byte |= scan_small; 2927 scan_small = 0; 2928 } 2929 BitMap += byte; 2930 } 2931 // next scan big 2932 for (unsigned int ix = 0; ix < scan_big; ix++) 2933 BitMap += (unsigned char)(0x0f); 2934 // last scan small 2935 if (scan_small) 2936 { 2937 byte = scan_small; 2938 BitMap += byte; 2939 } 2940 } 2941 // null terminate string. 2942 unsigned char zero = 0; 2943 BitMap += zero; 2944 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as 2945 // final layout. 2946 if (ForStrongLayout && !BytesSkipped) 2947 return llvm::Constant::getNullValue(PtrTy); 2948 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_", 2949 llvm::ConstantArray::get(BitMap.c_str()), 2950 "__TEXT,__cstring,cstring_literals", 2951 1, true); 2952 // FIXME. Need a commomand-line option for this eventually. 2953 if (ForStrongLayout) 2954 printf("\nstrong ivar layout: "); 2955 else 2956 printf("\nweak ivar layout: "); 2957 const unsigned char *s = (unsigned char*)BitMap.c_str(); 2958 for (unsigned i = 0; i < BitMap.size(); i++) 2959 if (!(s[i] & 0xf0)) 2960 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : ""); 2961 else 2962 printf("0x%x%s", s[i], s[i] != 0 ? ", " : ""); 2963 printf("\n"); 2964 2965 return getConstantGEP(Entry, 0, 0); 2966} 2967 2968llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) { 2969 llvm::GlobalVariable *&Entry = MethodVarNames[Sel]; 2970 2971 // FIXME: Avoid std::string copying. 2972 if (!Entry) 2973 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_", 2974 llvm::ConstantArray::get(Sel.getAsString()), 2975 "__TEXT,__cstring,cstring_literals", 2976 1, true); 2977 2978 return getConstantGEP(Entry, 0, 0); 2979} 2980 2981// FIXME: Merge into a single cstring creation function. 2982llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) { 2983 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID)); 2984} 2985 2986// FIXME: Merge into a single cstring creation function. 2987llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) { 2988 return GetMethodVarName(&CGM.getContext().Idents.get(Name)); 2989} 2990 2991llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) { 2992 std::string TypeStr; 2993 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field); 2994 2995 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr]; 2996 2997 if (!Entry) 2998 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_", 2999 llvm::ConstantArray::get(TypeStr), 3000 "__TEXT,__cstring,cstring_literals", 3001 1, true); 3002 3003 return getConstantGEP(Entry, 0, 0); 3004} 3005 3006llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) { 3007 std::string TypeStr; 3008 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D), 3009 TypeStr); 3010 3011 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr]; 3012 3013 if (!Entry) 3014 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_", 3015 llvm::ConstantArray::get(TypeStr), 3016 "__TEXT,__cstring,cstring_literals", 3017 1, true); 3018 3019 return getConstantGEP(Entry, 0, 0); 3020} 3021 3022// FIXME: Merge into a single cstring creation function. 3023llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) { 3024 llvm::GlobalVariable *&Entry = PropertyNames[Ident]; 3025 3026 if (!Entry) 3027 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_", 3028 llvm::ConstantArray::get(Ident->getName()), 3029 "__TEXT,__cstring,cstring_literals", 3030 1, true); 3031 3032 return getConstantGEP(Entry, 0, 0); 3033} 3034 3035// FIXME: Merge into a single cstring creation function. 3036// FIXME: This Decl should be more precise. 3037llvm::Constant * 3038 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD, 3039 const Decl *Container) { 3040 std::string TypeStr; 3041 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr); 3042 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr)); 3043} 3044 3045void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D, 3046 const ObjCContainerDecl *CD, 3047 std::string &NameOut) { 3048 NameOut = '\01'; 3049 NameOut += (D->isInstanceMethod() ? '-' : '+'); 3050 NameOut += '['; 3051 assert (CD && "Missing container decl in GetNameForMethod"); 3052 NameOut += CD->getNameAsString(); 3053 if (const ObjCCategoryImplDecl *CID = 3054 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) { 3055 NameOut += '('; 3056 NameOut += CID->getNameAsString(); 3057 NameOut+= ')'; 3058 } 3059 NameOut += ' '; 3060 NameOut += D->getSelector().getAsString(); 3061 NameOut += ']'; 3062} 3063 3064/// GetFirstIvarInRecord - This routine returns the record for the 3065/// implementation of the fiven class OID. It also returns field 3066/// corresponding to the first ivar in the class in FIV. It also 3067/// returns the one before the first ivar. 3068/// 3069const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord( 3070 const ObjCInterfaceDecl *OID, 3071 RecordDecl::field_iterator &FIV, 3072 RecordDecl::field_iterator &PIV) { 3073 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(), 3074 CGM.getContext()); 3075 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID); 3076 RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext()); 3077 RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext()); 3078 while (countSuperClassIvars-- > 0) { 3079 pfield = ifield; 3080 ++ifield; 3081 } 3082 FIV = ifield; 3083 PIV = pfield; 3084 return RD; 3085} 3086 3087void CGObjCMac::FinishModule() { 3088 EmitModuleInfo(); 3089 3090 // Emit the dummy bodies for any protocols which were referenced but 3091 // never defined. 3092 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator 3093 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) { 3094 if (i->second->hasInitializer()) 3095 continue; 3096 3097 std::vector<llvm::Constant*> Values(5); 3098 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 3099 Values[1] = GetClassName(i->first); 3100 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 3101 Values[3] = Values[4] = 3102 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 3103 i->second->setLinkage(llvm::GlobalValue::InternalLinkage); 3104 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 3105 Values)); 3106 } 3107 3108 std::vector<llvm::Constant*> Used; 3109 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(), 3110 e = UsedGlobals.end(); i != e; ++i) { 3111 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy)); 3112 } 3113 3114 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size()); 3115 llvm::GlobalValue *GV = 3116 new llvm::GlobalVariable(AT, false, 3117 llvm::GlobalValue::AppendingLinkage, 3118 llvm::ConstantArray::get(AT, Used), 3119 "llvm.used", 3120 &CGM.getModule()); 3121 3122 GV->setSection("llvm.metadata"); 3123 3124 // Add assembler directives to add lazy undefined symbol references 3125 // for classes which are referenced but not defined. This is 3126 // important for correct linker interaction. 3127 3128 // FIXME: Uh, this isn't particularly portable. 3129 std::stringstream s; 3130 3131 if (!CGM.getModule().getModuleInlineAsm().empty()) 3132 s << "\n"; 3133 3134 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(), 3135 e = LazySymbols.end(); i != e; ++i) { 3136 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n"; 3137 } 3138 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(), 3139 e = DefinedSymbols.end(); i != e; ++i) { 3140 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n" 3141 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n"; 3142 } 3143 3144 CGM.getModule().appendModuleInlineAsm(s.str()); 3145} 3146 3147CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm) 3148 : CGObjCCommonMac(cgm), 3149 ObjCTypes(cgm) 3150{ 3151 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL; 3152 ObjCABI = 2; 3153} 3154 3155/* *** */ 3156 3157ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) 3158: CGM(cgm) 3159{ 3160 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 3161 ASTContext &Ctx = CGM.getContext(); 3162 3163 ShortTy = Types.ConvertType(Ctx.ShortTy); 3164 IntTy = Types.ConvertType(Ctx.IntTy); 3165 LongTy = Types.ConvertType(Ctx.LongTy); 3166 LongLongTy = Types.ConvertType(Ctx.LongLongTy); 3167 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 3168 3169 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType()); 3170 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy); 3171 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType()); 3172 3173 // FIXME: It would be nice to unify this with the opaque type, so 3174 // that the IR comes out a bit cleaner. 3175 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType()); 3176 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T); 3177 3178 // I'm not sure I like this. The implicit coordination is a bit 3179 // gross. We should solve this in a reasonable fashion because this 3180 // is a pretty common task (match some runtime data structure with 3181 // an LLVM data structure). 3182 3183 // FIXME: This is leaked. 3184 // FIXME: Merge with rewriter code? 3185 3186 // struct _objc_super { 3187 // id self; 3188 // Class cls; 3189 // } 3190 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0, 3191 SourceLocation(), 3192 &Ctx.Idents.get("_objc_super")); 3193 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 3194 Ctx.getObjCIdType(), 0, false)); 3195 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 3196 Ctx.getObjCClassType(), 0, false)); 3197 RD->completeDefinition(Ctx); 3198 3199 SuperCTy = Ctx.getTagDeclType(RD); 3200 SuperPtrCTy = Ctx.getPointerType(SuperCTy); 3201 3202 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy)); 3203 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy); 3204 3205 // struct _prop_t { 3206 // char *name; 3207 // char *attributes; 3208 // } 3209 PropertyTy = llvm::StructType::get(Int8PtrTy, 3210 Int8PtrTy, 3211 NULL); 3212 CGM.getModule().addTypeName("struct._prop_t", 3213 PropertyTy); 3214 3215 // struct _prop_list_t { 3216 // uint32_t entsize; // sizeof(struct _prop_t) 3217 // uint32_t count_of_properties; 3218 // struct _prop_t prop_list[count_of_properties]; 3219 // } 3220 PropertyListTy = llvm::StructType::get(IntTy, 3221 IntTy, 3222 llvm::ArrayType::get(PropertyTy, 0), 3223 NULL); 3224 CGM.getModule().addTypeName("struct._prop_list_t", 3225 PropertyListTy); 3226 // struct _prop_list_t * 3227 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy); 3228 3229 // struct _objc_method { 3230 // SEL _cmd; 3231 // char *method_type; 3232 // char *_imp; 3233 // } 3234 MethodTy = llvm::StructType::get(SelectorPtrTy, 3235 Int8PtrTy, 3236 Int8PtrTy, 3237 NULL); 3238 CGM.getModule().addTypeName("struct._objc_method", MethodTy); 3239 3240 // struct _objc_cache * 3241 CacheTy = llvm::OpaqueType::get(); 3242 CGM.getModule().addTypeName("struct._objc_cache", CacheTy); 3243 CachePtrTy = llvm::PointerType::getUnqual(CacheTy); 3244 3245 // Property manipulation functions. 3246 3247 QualType IdType = Ctx.getObjCIdType(); 3248 QualType SelType = Ctx.getObjCSelType(); 3249 llvm::SmallVector<QualType,16> Params; 3250 const llvm::FunctionType *FTy; 3251 3252 // id objc_getProperty (id, SEL, ptrdiff_t, bool) 3253 Params.push_back(IdType); 3254 Params.push_back(SelType); 3255 Params.push_back(Ctx.LongTy); 3256 Params.push_back(Ctx.BoolTy); 3257 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), 3258 false); 3259 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty"); 3260 3261 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) 3262 Params.clear(); 3263 Params.push_back(IdType); 3264 Params.push_back(SelType); 3265 Params.push_back(Ctx.LongTy); 3266 Params.push_back(IdType); 3267 Params.push_back(Ctx.BoolTy); 3268 Params.push_back(Ctx.BoolTy); 3269 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false); 3270 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty"); 3271 3272 // Enumeration mutation. 3273 3274 // void objc_enumerationMutation (id) 3275 Params.clear(); 3276 Params.push_back(IdType); 3277 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false); 3278 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy, 3279 "objc_enumerationMutation"); 3280 3281 // gc's API 3282 // id objc_read_weak (id *) 3283 Params.clear(); 3284 Params.push_back(Ctx.getPointerType(IdType)); 3285 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false); 3286 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak"); 3287 3288 // id objc_assign_global (id, id *) 3289 Params.clear(); 3290 Params.push_back(IdType); 3291 Params.push_back(Ctx.getPointerType(IdType)); 3292 3293 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false); 3294 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global"); 3295 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar"); 3296 GcAssignStrongCastFn = 3297 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast"); 3298 3299 // void objc_exception_throw(id) 3300 Params.clear(); 3301 Params.push_back(IdType); 3302 3303 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false); 3304 ExceptionThrowFn = 3305 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw"); 3306 3307 // synchronized APIs 3308 // void objc_sync_exit (id) 3309 Params.clear(); 3310 Params.push_back(IdType); 3311 3312 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false); 3313 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit"); 3314} 3315 3316ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) 3317 : ObjCCommonTypesHelper(cgm) 3318{ 3319 // struct _objc_method_description { 3320 // SEL name; 3321 // char *types; 3322 // } 3323 MethodDescriptionTy = 3324 llvm::StructType::get(SelectorPtrTy, 3325 Int8PtrTy, 3326 NULL); 3327 CGM.getModule().addTypeName("struct._objc_method_description", 3328 MethodDescriptionTy); 3329 3330 // struct _objc_method_description_list { 3331 // int count; 3332 // struct _objc_method_description[1]; 3333 // } 3334 MethodDescriptionListTy = 3335 llvm::StructType::get(IntTy, 3336 llvm::ArrayType::get(MethodDescriptionTy, 0), 3337 NULL); 3338 CGM.getModule().addTypeName("struct._objc_method_description_list", 3339 MethodDescriptionListTy); 3340 3341 // struct _objc_method_description_list * 3342 MethodDescriptionListPtrTy = 3343 llvm::PointerType::getUnqual(MethodDescriptionListTy); 3344 3345 // Protocol description structures 3346 3347 // struct _objc_protocol_extension { 3348 // uint32_t size; // sizeof(struct _objc_protocol_extension) 3349 // struct _objc_method_description_list *optional_instance_methods; 3350 // struct _objc_method_description_list *optional_class_methods; 3351 // struct _objc_property_list *instance_properties; 3352 // } 3353 ProtocolExtensionTy = 3354 llvm::StructType::get(IntTy, 3355 MethodDescriptionListPtrTy, 3356 MethodDescriptionListPtrTy, 3357 PropertyListPtrTy, 3358 NULL); 3359 CGM.getModule().addTypeName("struct._objc_protocol_extension", 3360 ProtocolExtensionTy); 3361 3362 // struct _objc_protocol_extension * 3363 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy); 3364 3365 // Handle recursive construction of Protocol and ProtocolList types 3366 3367 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get(); 3368 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); 3369 3370 const llvm::Type *T = 3371 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder), 3372 LongTy, 3373 llvm::ArrayType::get(ProtocolTyHolder, 0), 3374 NULL); 3375 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T); 3376 3377 // struct _objc_protocol { 3378 // struct _objc_protocol_extension *isa; 3379 // char *protocol_name; 3380 // struct _objc_protocol **_objc_protocol_list; 3381 // struct _objc_method_description_list *instance_methods; 3382 // struct _objc_method_description_list *class_methods; 3383 // } 3384 T = llvm::StructType::get(ProtocolExtensionPtrTy, 3385 Int8PtrTy, 3386 llvm::PointerType::getUnqual(ProtocolListTyHolder), 3387 MethodDescriptionListPtrTy, 3388 MethodDescriptionListPtrTy, 3389 NULL); 3390 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T); 3391 3392 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get()); 3393 CGM.getModule().addTypeName("struct._objc_protocol_list", 3394 ProtocolListTy); 3395 // struct _objc_protocol_list * 3396 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy); 3397 3398 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get()); 3399 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy); 3400 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy); 3401 3402 // Class description structures 3403 3404 // struct _objc_ivar { 3405 // char *ivar_name; 3406 // char *ivar_type; 3407 // int ivar_offset; 3408 // } 3409 IvarTy = llvm::StructType::get(Int8PtrTy, 3410 Int8PtrTy, 3411 IntTy, 3412 NULL); 3413 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy); 3414 3415 // struct _objc_ivar_list * 3416 IvarListTy = llvm::OpaqueType::get(); 3417 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy); 3418 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy); 3419 3420 // struct _objc_method_list * 3421 MethodListTy = llvm::OpaqueType::get(); 3422 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy); 3423 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy); 3424 3425 // struct _objc_class_extension * 3426 ClassExtensionTy = 3427 llvm::StructType::get(IntTy, 3428 Int8PtrTy, 3429 PropertyListPtrTy, 3430 NULL); 3431 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy); 3432 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy); 3433 3434 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); 3435 3436 // struct _objc_class { 3437 // Class isa; 3438 // Class super_class; 3439 // char *name; 3440 // long version; 3441 // long info; 3442 // long instance_size; 3443 // struct _objc_ivar_list *ivars; 3444 // struct _objc_method_list *methods; 3445 // struct _objc_cache *cache; 3446 // struct _objc_protocol_list *protocols; 3447 // char *ivar_layout; 3448 // struct _objc_class_ext *ext; 3449 // }; 3450 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), 3451 llvm::PointerType::getUnqual(ClassTyHolder), 3452 Int8PtrTy, 3453 LongTy, 3454 LongTy, 3455 LongTy, 3456 IvarListPtrTy, 3457 MethodListPtrTy, 3458 CachePtrTy, 3459 ProtocolListPtrTy, 3460 Int8PtrTy, 3461 ClassExtensionPtrTy, 3462 NULL); 3463 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T); 3464 3465 ClassTy = cast<llvm::StructType>(ClassTyHolder.get()); 3466 CGM.getModule().addTypeName("struct._objc_class", ClassTy); 3467 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy); 3468 3469 // struct _objc_category { 3470 // char *category_name; 3471 // char *class_name; 3472 // struct _objc_method_list *instance_method; 3473 // struct _objc_method_list *class_method; 3474 // uint32_t size; // sizeof(struct _objc_category) 3475 // struct _objc_property_list *instance_properties;// category's @property 3476 // } 3477 CategoryTy = llvm::StructType::get(Int8PtrTy, 3478 Int8PtrTy, 3479 MethodListPtrTy, 3480 MethodListPtrTy, 3481 ProtocolListPtrTy, 3482 IntTy, 3483 PropertyListPtrTy, 3484 NULL); 3485 CGM.getModule().addTypeName("struct._objc_category", CategoryTy); 3486 3487 // Global metadata structures 3488 3489 // struct _objc_symtab { 3490 // long sel_ref_cnt; 3491 // SEL *refs; 3492 // short cls_def_cnt; 3493 // short cat_def_cnt; 3494 // char *defs[cls_def_cnt + cat_def_cnt]; 3495 // } 3496 SymtabTy = llvm::StructType::get(LongTy, 3497 SelectorPtrTy, 3498 ShortTy, 3499 ShortTy, 3500 llvm::ArrayType::get(Int8PtrTy, 0), 3501 NULL); 3502 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy); 3503 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy); 3504 3505 // struct _objc_module { 3506 // long version; 3507 // long size; // sizeof(struct _objc_module) 3508 // char *name; 3509 // struct _objc_symtab* symtab; 3510 // } 3511 ModuleTy = 3512 llvm::StructType::get(LongTy, 3513 LongTy, 3514 Int8PtrTy, 3515 SymtabPtrTy, 3516 NULL); 3517 CGM.getModule().addTypeName("struct._objc_module", ModuleTy); 3518 3519 // Message send functions. 3520 3521 // id objc_msgSend (id, SEL, ...) 3522 std::vector<const llvm::Type*> Params; 3523 Params.push_back(ObjectPtrTy); 3524 Params.push_back(SelectorPtrTy); 3525 MessageSendFn = 3526 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 3527 Params, 3528 true), 3529 "objc_msgSend"); 3530 3531 // id objc_msgSend_stret (id, SEL, ...) 3532 Params.clear(); 3533 Params.push_back(ObjectPtrTy); 3534 Params.push_back(SelectorPtrTy); 3535 MessageSendStretFn = 3536 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 3537 Params, 3538 true), 3539 "objc_msgSend_stret"); 3540 3541 // 3542 Params.clear(); 3543 Params.push_back(ObjectPtrTy); 3544 Params.push_back(SelectorPtrTy); 3545 // FIXME: This should be long double on x86_64? 3546 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...) 3547 MessageSendFpretFn = 3548 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy, 3549 Params, 3550 true), 3551 "objc_msgSend_fpret"); 3552 3553 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...) 3554 Params.clear(); 3555 Params.push_back(SuperPtrTy); 3556 Params.push_back(SelectorPtrTy); 3557 MessageSendSuperFn = 3558 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 3559 Params, 3560 true), 3561 "objc_msgSendSuper"); 3562 3563 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super, 3564 // SEL op, ...) 3565 Params.clear(); 3566 Params.push_back(Int8PtrTy); 3567 Params.push_back(SuperPtrTy); 3568 Params.push_back(SelectorPtrTy); 3569 MessageSendSuperStretFn = 3570 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 3571 Params, 3572 true), 3573 "objc_msgSendSuper_stret"); 3574 3575 // There is no objc_msgSendSuper_fpret? How can that work? 3576 MessageSendSuperFpretFn = MessageSendSuperFn; 3577 3578 // FIXME: This is the size of the setjmp buffer and should be 3579 // target specific. 18 is what's used on 32-bit X86. 3580 uint64_t SetJmpBufferSize = 18; 3581 3582 // Exceptions 3583 const llvm::Type *StackPtrTy = 3584 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4); 3585 3586 ExceptionDataTy = 3587 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty, 3588 SetJmpBufferSize), 3589 StackPtrTy, NULL); 3590 CGM.getModule().addTypeName("struct._objc_exception_data", 3591 ExceptionDataTy); 3592 3593 Params.clear(); 3594 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy)); 3595 ExceptionTryEnterFn = 3596 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 3597 Params, 3598 false), 3599 "objc_exception_try_enter"); 3600 ExceptionTryExitFn = 3601 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 3602 Params, 3603 false), 3604 "objc_exception_try_exit"); 3605 ExceptionExtractFn = 3606 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 3607 Params, 3608 false), 3609 "objc_exception_extract"); 3610 3611 Params.clear(); 3612 Params.push_back(ClassPtrTy); 3613 Params.push_back(ObjectPtrTy); 3614 ExceptionMatchFn = 3615 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 3616 Params, 3617 false), 3618 "objc_exception_match"); 3619 3620 Params.clear(); 3621 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty)); 3622 SetJmpFn = 3623 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 3624 Params, 3625 false), 3626 "_setjmp"); 3627 3628} 3629 3630ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm) 3631: ObjCCommonTypesHelper(cgm) 3632{ 3633 // struct _method_list_t { 3634 // uint32_t entsize; // sizeof(struct _objc_method) 3635 // uint32_t method_count; 3636 // struct _objc_method method_list[method_count]; 3637 // } 3638 MethodListnfABITy = llvm::StructType::get(IntTy, 3639 IntTy, 3640 llvm::ArrayType::get(MethodTy, 0), 3641 NULL); 3642 CGM.getModule().addTypeName("struct.__method_list_t", 3643 MethodListnfABITy); 3644 // struct method_list_t * 3645 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy); 3646 3647 // struct _protocol_t { 3648 // id isa; // NULL 3649 // const char * const protocol_name; 3650 // const struct _protocol_list_t * protocol_list; // super protocols 3651 // const struct method_list_t * const instance_methods; 3652 // const struct method_list_t * const class_methods; 3653 // const struct method_list_t *optionalInstanceMethods; 3654 // const struct method_list_t *optionalClassMethods; 3655 // const struct _prop_list_t * properties; 3656 // const uint32_t size; // sizeof(struct _protocol_t) 3657 // const uint32_t flags; // = 0 3658 // } 3659 3660 // Holder for struct _protocol_list_t * 3661 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); 3662 3663 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy, 3664 Int8PtrTy, 3665 llvm::PointerType::getUnqual( 3666 ProtocolListTyHolder), 3667 MethodListnfABIPtrTy, 3668 MethodListnfABIPtrTy, 3669 MethodListnfABIPtrTy, 3670 MethodListnfABIPtrTy, 3671 PropertyListPtrTy, 3672 IntTy, 3673 IntTy, 3674 NULL); 3675 CGM.getModule().addTypeName("struct._protocol_t", 3676 ProtocolnfABITy); 3677 3678 // struct _protocol_t* 3679 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy); 3680 3681 // struct _protocol_list_t { 3682 // long protocol_count; // Note, this is 32/64 bit 3683 // struct _protocol_t *[protocol_count]; 3684 // } 3685 ProtocolListnfABITy = llvm::StructType::get(LongTy, 3686 llvm::ArrayType::get( 3687 ProtocolnfABIPtrTy, 0), 3688 NULL); 3689 CGM.getModule().addTypeName("struct._objc_protocol_list", 3690 ProtocolListnfABITy); 3691 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo( 3692 ProtocolListnfABITy); 3693 3694 // struct _objc_protocol_list* 3695 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy); 3696 3697 // struct _ivar_t { 3698 // unsigned long int *offset; // pointer to ivar offset location 3699 // char *name; 3700 // char *type; 3701 // uint32_t alignment; 3702 // uint32_t size; 3703 // } 3704 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy), 3705 Int8PtrTy, 3706 Int8PtrTy, 3707 IntTy, 3708 IntTy, 3709 NULL); 3710 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy); 3711 3712 // struct _ivar_list_t { 3713 // uint32 entsize; // sizeof(struct _ivar_t) 3714 // uint32 count; 3715 // struct _iver_t list[count]; 3716 // } 3717 IvarListnfABITy = llvm::StructType::get(IntTy, 3718 IntTy, 3719 llvm::ArrayType::get( 3720 IvarnfABITy, 0), 3721 NULL); 3722 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy); 3723 3724 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy); 3725 3726 // struct _class_ro_t { 3727 // uint32_t const flags; 3728 // uint32_t const instanceStart; 3729 // uint32_t const instanceSize; 3730 // uint32_t const reserved; // only when building for 64bit targets 3731 // const uint8_t * const ivarLayout; 3732 // const char *const name; 3733 // const struct _method_list_t * const baseMethods; 3734 // const struct _objc_protocol_list *const baseProtocols; 3735 // const struct _ivar_list_t *const ivars; 3736 // const uint8_t * const weakIvarLayout; 3737 // const struct _prop_list_t * const properties; 3738 // } 3739 3740 // FIXME. Add 'reserved' field in 64bit abi mode! 3741 ClassRonfABITy = llvm::StructType::get(IntTy, 3742 IntTy, 3743 IntTy, 3744 Int8PtrTy, 3745 Int8PtrTy, 3746 MethodListnfABIPtrTy, 3747 ProtocolListnfABIPtrTy, 3748 IvarListnfABIPtrTy, 3749 Int8PtrTy, 3750 PropertyListPtrTy, 3751 NULL); 3752 CGM.getModule().addTypeName("struct._class_ro_t", 3753 ClassRonfABITy); 3754 3755 // ImpnfABITy - LLVM for id (*)(id, SEL, ...) 3756 std::vector<const llvm::Type*> Params; 3757 Params.push_back(ObjectPtrTy); 3758 Params.push_back(SelectorPtrTy); 3759 ImpnfABITy = llvm::PointerType::getUnqual( 3760 llvm::FunctionType::get(ObjectPtrTy, Params, false)); 3761 3762 // struct _class_t { 3763 // struct _class_t *isa; 3764 // struct _class_t * const superclass; 3765 // void *cache; 3766 // IMP *vtable; 3767 // struct class_ro_t *ro; 3768 // } 3769 3770 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); 3771 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), 3772 llvm::PointerType::getUnqual(ClassTyHolder), 3773 CachePtrTy, 3774 llvm::PointerType::getUnqual(ImpnfABITy), 3775 llvm::PointerType::getUnqual( 3776 ClassRonfABITy), 3777 NULL); 3778 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy); 3779 3780 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo( 3781 ClassnfABITy); 3782 3783 // LLVM for struct _class_t * 3784 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy); 3785 3786 // struct _category_t { 3787 // const char * const name; 3788 // struct _class_t *const cls; 3789 // const struct _method_list_t * const instance_methods; 3790 // const struct _method_list_t * const class_methods; 3791 // const struct _protocol_list_t * const protocols; 3792 // const struct _prop_list_t * const properties; 3793 // } 3794 CategorynfABITy = llvm::StructType::get(Int8PtrTy, 3795 ClassnfABIPtrTy, 3796 MethodListnfABIPtrTy, 3797 MethodListnfABIPtrTy, 3798 ProtocolListnfABIPtrTy, 3799 PropertyListPtrTy, 3800 NULL); 3801 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy); 3802 3803 // New types for nonfragile abi messaging. 3804 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 3805 ASTContext &Ctx = CGM.getContext(); 3806 3807 // MessageRefTy - LLVM for: 3808 // struct _message_ref_t { 3809 // IMP messenger; 3810 // SEL name; 3811 // }; 3812 3813 // First the clang type for struct _message_ref_t 3814 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0, 3815 SourceLocation(), 3816 &Ctx.Idents.get("_message_ref_t")); 3817 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 3818 Ctx.VoidPtrTy, 0, false)); 3819 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 3820 Ctx.getObjCSelType(), 0, false)); 3821 RD->completeDefinition(Ctx); 3822 3823 MessageRefCTy = Ctx.getTagDeclType(RD); 3824 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy); 3825 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy)); 3826 3827 // MessageRefPtrTy - LLVM for struct _message_ref_t* 3828 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy); 3829 3830 // SuperMessageRefTy - LLVM for: 3831 // struct _super_message_ref_t { 3832 // SUPER_IMP messenger; 3833 // SEL name; 3834 // }; 3835 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy, 3836 SelectorPtrTy, 3837 NULL); 3838 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy); 3839 3840 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* 3841 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy); 3842 3843 // id objc_msgSend_fixup (id, struct message_ref_t*, ...) 3844 Params.clear(); 3845 Params.push_back(ObjectPtrTy); 3846 Params.push_back(MessageRefPtrTy); 3847 MessengerTy = llvm::FunctionType::get(ObjectPtrTy, 3848 Params, 3849 true); 3850 MessageSendFixupFn = 3851 CGM.CreateRuntimeFunction(MessengerTy, 3852 "objc_msgSend_fixup"); 3853 3854 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...) 3855 MessageSendFpretFixupFn = 3856 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 3857 Params, 3858 true), 3859 "objc_msgSend_fpret_fixup"); 3860 3861 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...) 3862 MessageSendStretFixupFn = 3863 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 3864 Params, 3865 true), 3866 "objc_msgSend_stret_fixup"); 3867 3868 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...) 3869 MessageSendIdFixupFn = 3870 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 3871 Params, 3872 true), 3873 "objc_msgSendId_fixup"); 3874 3875 3876 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...) 3877 MessageSendIdStretFixupFn = 3878 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 3879 Params, 3880 true), 3881 "objc_msgSendId_stret_fixup"); 3882 3883 // id objc_msgSendSuper2_fixup (struct objc_super *, 3884 // struct _super_message_ref_t*, ...) 3885 Params.clear(); 3886 Params.push_back(SuperPtrTy); 3887 Params.push_back(SuperMessageRefPtrTy); 3888 MessageSendSuper2FixupFn = 3889 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 3890 Params, 3891 true), 3892 "objc_msgSendSuper2_fixup"); 3893 3894 3895 // id objc_msgSendSuper2_stret_fixup (struct objc_super *, 3896 // struct _super_message_ref_t*, ...) 3897 MessageSendSuper2StretFixupFn = 3898 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 3899 Params, 3900 true), 3901 "objc_msgSendSuper2_stret_fixup"); 3902 3903 Params.clear(); 3904 Params.push_back(Int8PtrTy); 3905 UnwindResumeOrRethrowFn = 3906 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 3907 Params, 3908 false), 3909 "_Unwind_Resume_or_Rethrow"); 3910 ObjCBeginCatchFn = 3911 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy, 3912 Params, 3913 false), 3914 "objc_begin_catch"); 3915 3916 Params.clear(); 3917 ObjCEndCatchFn = 3918 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 3919 Params, 3920 false), 3921 "objc_end_catch"); 3922 3923 // struct objc_typeinfo { 3924 // const void** vtable; // objc_ehtype_vtable + 2 3925 // const char* name; // c++ typeinfo string 3926 // Class cls; 3927 // }; 3928 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy), 3929 Int8PtrTy, 3930 ClassnfABIPtrTy, 3931 NULL); 3932 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy); 3933 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy); 3934} 3935 3936llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() { 3937 FinishNonFragileABIModule(); 3938 3939 return NULL; 3940} 3941 3942void CGObjCNonFragileABIMac::FinishNonFragileABIModule() { 3943 // nonfragile abi has no module definition. 3944 3945 // Build list of all implemented classe addresses in array 3946 // L_OBJC_LABEL_CLASS_$. 3947 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$ 3948 // list of 'nonlazy' implementations (defined as those with a +load{} 3949 // method!!). 3950 unsigned NumClasses = DefinedClasses.size(); 3951 if (NumClasses) { 3952 std::vector<llvm::Constant*> Symbols(NumClasses); 3953 for (unsigned i=0; i<NumClasses; i++) 3954 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], 3955 ObjCTypes.Int8PtrTy); 3956 llvm::Constant* Init = 3957 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 3958 NumClasses), 3959 Symbols); 3960 3961 llvm::GlobalVariable *GV = 3962 new llvm::GlobalVariable(Init->getType(), false, 3963 llvm::GlobalValue::InternalLinkage, 3964 Init, 3965 "\01L_OBJC_LABEL_CLASS_$", 3966 &CGM.getModule()); 3967 GV->setAlignment(8); 3968 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip"); 3969 UsedGlobals.push_back(GV); 3970 } 3971 3972 // Build list of all implemented category addresses in array 3973 // L_OBJC_LABEL_CATEGORY_$. 3974 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$ 3975 // list of 'nonlazy' category implementations (defined as those with a +load{} 3976 // method!!). 3977 unsigned NumCategory = DefinedCategories.size(); 3978 if (NumCategory) { 3979 std::vector<llvm::Constant*> Symbols(NumCategory); 3980 for (unsigned i=0; i<NumCategory; i++) 3981 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i], 3982 ObjCTypes.Int8PtrTy); 3983 llvm::Constant* Init = 3984 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 3985 NumCategory), 3986 Symbols); 3987 3988 llvm::GlobalVariable *GV = 3989 new llvm::GlobalVariable(Init->getType(), false, 3990 llvm::GlobalValue::InternalLinkage, 3991 Init, 3992 "\01L_OBJC_LABEL_CATEGORY_$", 3993 &CGM.getModule()); 3994 GV->setAlignment(8); 3995 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip"); 3996 UsedGlobals.push_back(GV); 3997 } 3998 3999 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags }; 4000 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0 4001 std::vector<llvm::Constant*> Values(2); 4002 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0); 4003 unsigned int flags = 0; 4004 // FIXME: Fix and continue? 4005 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) 4006 flags |= eImageInfo_GarbageCollected; 4007 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) 4008 flags |= eImageInfo_GCOnly; 4009 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags); 4010 llvm::Constant* Init = llvm::ConstantArray::get( 4011 llvm::ArrayType::get(ObjCTypes.IntTy, 2), 4012 Values); 4013 llvm::GlobalVariable *IMGV = 4014 new llvm::GlobalVariable(Init->getType(), false, 4015 llvm::GlobalValue::InternalLinkage, 4016 Init, 4017 "\01L_OBJC_IMAGE_INFO", 4018 &CGM.getModule()); 4019 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip"); 4020 UsedGlobals.push_back(IMGV); 4021 4022 std::vector<llvm::Constant*> Used; 4023 4024 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(), 4025 e = UsedGlobals.end(); i != e; ++i) { 4026 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy)); 4027 } 4028 4029 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size()); 4030 llvm::GlobalValue *GV = 4031 new llvm::GlobalVariable(AT, false, 4032 llvm::GlobalValue::AppendingLinkage, 4033 llvm::ConstantArray::get(AT, Used), 4034 "llvm.used", 4035 &CGM.getModule()); 4036 4037 GV->setSection("llvm.metadata"); 4038 4039} 4040 4041// Metadata flags 4042enum MetaDataDlags { 4043 CLS = 0x0, 4044 CLS_META = 0x1, 4045 CLS_ROOT = 0x2, 4046 OBJC2_CLS_HIDDEN = 0x10, 4047 CLS_EXCEPTION = 0x20 4048}; 4049/// BuildClassRoTInitializer - generate meta-data for: 4050/// struct _class_ro_t { 4051/// uint32_t const flags; 4052/// uint32_t const instanceStart; 4053/// uint32_t const instanceSize; 4054/// uint32_t const reserved; // only when building for 64bit targets 4055/// const uint8_t * const ivarLayout; 4056/// const char *const name; 4057/// const struct _method_list_t * const baseMethods; 4058/// const struct _protocol_list_t *const baseProtocols; 4059/// const struct _ivar_list_t *const ivars; 4060/// const uint8_t * const weakIvarLayout; 4061/// const struct _prop_list_t * const properties; 4062/// } 4063/// 4064llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer( 4065 unsigned flags, 4066 unsigned InstanceStart, 4067 unsigned InstanceSize, 4068 const ObjCImplementationDecl *ID) { 4069 std::string ClassName = ID->getNameAsString(); 4070 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets! 4071 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags); 4072 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart); 4073 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize); 4074 // FIXME. For 64bit targets add 0 here. 4075 // FIXME. ivarLayout is currently null! 4076 Values[ 3] = GetIvarLayoutName(0, ObjCTypes); 4077 Values[ 4] = GetClassName(ID->getIdentifier()); 4078 // const struct _method_list_t * const baseMethods; 4079 std::vector<llvm::Constant*> Methods; 4080 std::string MethodListName("\01l_OBJC_$_"); 4081 if (flags & CLS_META) { 4082 MethodListName += "CLASS_METHODS_" + ID->getNameAsString(); 4083 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(), 4084 e = ID->classmeth_end(); i != e; ++i) { 4085 // Class methods should always be defined. 4086 Methods.push_back(GetMethodConstant(*i)); 4087 } 4088 } else { 4089 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString(); 4090 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(), 4091 e = ID->instmeth_end(); i != e; ++i) { 4092 // Instance methods should always be defined. 4093 Methods.push_back(GetMethodConstant(*i)); 4094 } 4095 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(), 4096 e = ID->propimpl_end(); i != e; ++i) { 4097 ObjCPropertyImplDecl *PID = *i; 4098 4099 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){ 4100 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 4101 4102 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) 4103 if (llvm::Constant *C = GetMethodConstant(MD)) 4104 Methods.push_back(C); 4105 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) 4106 if (llvm::Constant *C = GetMethodConstant(MD)) 4107 Methods.push_back(C); 4108 } 4109 } 4110 } 4111 Values[ 5] = EmitMethodList(MethodListName, 4112 "__DATA, __objc_const", Methods); 4113 4114 const ObjCInterfaceDecl *OID = ID->getClassInterface(); 4115 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer"); 4116 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_" 4117 + OID->getNameAsString(), 4118 OID->protocol_begin(), 4119 OID->protocol_end()); 4120 4121 if (flags & CLS_META) 4122 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); 4123 else 4124 Values[ 7] = EmitIvarList(ID); 4125 // FIXME. weakIvarLayout is currently null. 4126 Values[ 8] = GetIvarLayoutName(0, ObjCTypes); 4127 if (flags & CLS_META) 4128 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 4129 else 4130 Values[ 9] = 4131 EmitPropertyList( 4132 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(), 4133 ID, ID->getClassInterface(), ObjCTypes); 4134 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy, 4135 Values); 4136 llvm::GlobalVariable *CLASS_RO_GV = 4137 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false, 4138 llvm::GlobalValue::InternalLinkage, 4139 Init, 4140 (flags & CLS_META) ? 4141 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName : 4142 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName, 4143 &CGM.getModule()); 4144 CLASS_RO_GV->setAlignment( 4145 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy)); 4146 CLASS_RO_GV->setSection("__DATA, __objc_const"); 4147 return CLASS_RO_GV; 4148 4149} 4150 4151/// BuildClassMetaData - This routine defines that to-level meta-data 4152/// for the given ClassName for: 4153/// struct _class_t { 4154/// struct _class_t *isa; 4155/// struct _class_t * const superclass; 4156/// void *cache; 4157/// IMP *vtable; 4158/// struct class_ro_t *ro; 4159/// } 4160/// 4161llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData( 4162 std::string &ClassName, 4163 llvm::Constant *IsAGV, 4164 llvm::Constant *SuperClassGV, 4165 llvm::Constant *ClassRoGV, 4166 bool HiddenVisibility) { 4167 std::vector<llvm::Constant*> Values(5); 4168 Values[0] = IsAGV; 4169 Values[1] = SuperClassGV 4170 ? SuperClassGV 4171 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy); 4172 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar 4173 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar 4174 Values[4] = ClassRoGV; // &CLASS_RO_GV 4175 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy, 4176 Values); 4177 llvm::GlobalVariable *GV = GetClassGlobal(ClassName); 4178 GV->setInitializer(Init); 4179 GV->setSection("__DATA, __objc_data"); 4180 GV->setAlignment( 4181 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy)); 4182 if (HiddenVisibility) 4183 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 4184 return GV; 4185} 4186 4187void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) { 4188 std::string ClassName = ID->getNameAsString(); 4189 if (!ObjCEmptyCacheVar) { 4190 ObjCEmptyCacheVar = new llvm::GlobalVariable( 4191 ObjCTypes.CacheTy, 4192 false, 4193 llvm::GlobalValue::ExternalLinkage, 4194 0, 4195 "_objc_empty_cache", 4196 &CGM.getModule()); 4197 4198 ObjCEmptyVtableVar = new llvm::GlobalVariable( 4199 ObjCTypes.ImpnfABITy, 4200 false, 4201 llvm::GlobalValue::ExternalLinkage, 4202 0, 4203 "_objc_empty_vtable", 4204 &CGM.getModule()); 4205 } 4206 assert(ID->getClassInterface() && 4207 "CGObjCNonFragileABIMac::GenerateClass - class is 0"); 4208 uint32_t InstanceStart = 4209 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy); 4210 uint32_t InstanceSize = InstanceStart; 4211 uint32_t flags = CLS_META; 4212 std::string ObjCMetaClassName(getMetaclassSymbolPrefix()); 4213 std::string ObjCClassName(getClassSymbolPrefix()); 4214 4215 llvm::GlobalVariable *SuperClassGV, *IsAGV; 4216 4217 bool classIsHidden = 4218 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden; 4219 if (classIsHidden) 4220 flags |= OBJC2_CLS_HIDDEN; 4221 if (!ID->getClassInterface()->getSuperClass()) { 4222 // class is root 4223 flags |= CLS_ROOT; 4224 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName); 4225 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName); 4226 } else { 4227 // Has a root. Current class is not a root. 4228 const ObjCInterfaceDecl *Root = ID->getClassInterface(); 4229 while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) 4230 Root = Super; 4231 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString()); 4232 // work on super class metadata symbol. 4233 std::string SuperClassName = 4234 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString(); 4235 SuperClassGV = GetClassGlobal(SuperClassName); 4236 } 4237 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags, 4238 InstanceStart, 4239 InstanceSize,ID); 4240 std::string TClassName = ObjCMetaClassName + ClassName; 4241 llvm::GlobalVariable *MetaTClass = 4242 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV, 4243 classIsHidden); 4244 4245 // Metadata for the class 4246 flags = CLS; 4247 if (classIsHidden) 4248 flags |= OBJC2_CLS_HIDDEN; 4249 4250 if (hasObjCExceptionAttribute(ID->getClassInterface())) 4251 flags |= CLS_EXCEPTION; 4252 4253 if (!ID->getClassInterface()->getSuperClass()) { 4254 flags |= CLS_ROOT; 4255 SuperClassGV = 0; 4256 } 4257 else { 4258 // Has a root. Current class is not a root. 4259 std::string RootClassName = 4260 ID->getClassInterface()->getSuperClass()->getNameAsString(); 4261 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName); 4262 } 4263 // FIXME: Gross 4264 InstanceStart = InstanceSize = 0; 4265 if (ObjCInterfaceDecl *OID = 4266 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) { 4267 // FIXME. Share this with the one in EmitIvarList. 4268 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID); 4269 4270 RecordDecl::field_iterator firstField, lastField; 4271 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField); 4272 4273 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()), 4274 ifield = firstField; ifield != e; ++ifield) 4275 lastField = ifield; 4276 4277 if (lastField != RD->field_end(CGM.getContext())) { 4278 FieldDecl *Field = *lastField; 4279 const llvm::Type *FieldTy = 4280 CGM.getTypes().ConvertTypeForMem(Field->getType()); 4281 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy); 4282 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size; 4283 if (firstField == RD->field_end(CGM.getContext())) 4284 InstanceStart = InstanceSize; 4285 else { 4286 Field = *firstField; 4287 InstanceStart = GetIvarBaseOffset(Layout, Field); 4288 } 4289 } 4290 } 4291 CLASS_RO_GV = BuildClassRoTInitializer(flags, 4292 InstanceStart, 4293 InstanceSize, 4294 ID); 4295 4296 TClassName = ObjCClassName + ClassName; 4297 llvm::GlobalVariable *ClassMD = 4298 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV, 4299 classIsHidden); 4300 DefinedClasses.push_back(ClassMD); 4301 4302 // Force the definition of the EHType if necessary. 4303 if (flags & CLS_EXCEPTION) 4304 GetInterfaceEHType(ID->getClassInterface(), true); 4305} 4306 4307/// GenerateProtocolRef - This routine is called to generate code for 4308/// a protocol reference expression; as in: 4309/// @code 4310/// @protocol(Proto1); 4311/// @endcode 4312/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1 4313/// which will hold address of the protocol meta-data. 4314/// 4315llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder, 4316 const ObjCProtocolDecl *PD) { 4317 4318 // This routine is called for @protocol only. So, we must build definition 4319 // of protocol's meta-data (not a reference to it!) 4320 // 4321 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD), 4322 ObjCTypes.ExternalProtocolPtrTy); 4323 4324 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_"); 4325 ProtocolName += PD->getNameAsCString(); 4326 4327 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName); 4328 if (PTGV) 4329 return Builder.CreateLoad(PTGV, false, "tmp"); 4330 PTGV = new llvm::GlobalVariable( 4331 Init->getType(), false, 4332 llvm::GlobalValue::WeakAnyLinkage, 4333 Init, 4334 ProtocolName, 4335 &CGM.getModule()); 4336 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip"); 4337 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 4338 UsedGlobals.push_back(PTGV); 4339 return Builder.CreateLoad(PTGV, false, "tmp"); 4340} 4341 4342/// GenerateCategory - Build metadata for a category implementation. 4343/// struct _category_t { 4344/// const char * const name; 4345/// struct _class_t *const cls; 4346/// const struct _method_list_t * const instance_methods; 4347/// const struct _method_list_t * const class_methods; 4348/// const struct _protocol_list_t * const protocols; 4349/// const struct _prop_list_t * const properties; 4350/// } 4351/// 4352void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) 4353{ 4354 const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); 4355 const char *Prefix = "\01l_OBJC_$_CATEGORY_"; 4356 std::string ExtCatName(Prefix + Interface->getNameAsString()+ 4357 "_$_" + OCD->getNameAsString()); 4358 std::string ExtClassName(getClassSymbolPrefix() + 4359 Interface->getNameAsString()); 4360 4361 std::vector<llvm::Constant*> Values(6); 4362 Values[0] = GetClassName(OCD->getIdentifier()); 4363 // meta-class entry symbol 4364 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName); 4365 Values[1] = ClassGV; 4366 std::vector<llvm::Constant*> Methods; 4367 std::string MethodListName(Prefix); 4368 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() + 4369 "_$_" + OCD->getNameAsString(); 4370 4371 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(), 4372 e = OCD->instmeth_end(); i != e; ++i) { 4373 // Instance methods should always be defined. 4374 Methods.push_back(GetMethodConstant(*i)); 4375 } 4376 4377 Values[2] = EmitMethodList(MethodListName, 4378 "__DATA, __objc_const", 4379 Methods); 4380 4381 MethodListName = Prefix; 4382 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" + 4383 OCD->getNameAsString(); 4384 Methods.clear(); 4385 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(), 4386 e = OCD->classmeth_end(); i != e; ++i) { 4387 // Class methods should always be defined. 4388 Methods.push_back(GetMethodConstant(*i)); 4389 } 4390 4391 Values[3] = EmitMethodList(MethodListName, 4392 "__DATA, __objc_const", 4393 Methods); 4394 const ObjCCategoryDecl *Category = 4395 Interface->FindCategoryDeclaration(OCD->getIdentifier()); 4396 if (Category) { 4397 std::string ExtName(Interface->getNameAsString() + "_$_" + 4398 OCD->getNameAsString()); 4399 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_" 4400 + Interface->getNameAsString() + "_$_" 4401 + Category->getNameAsString(), 4402 Category->protocol_begin(), 4403 Category->protocol_end()); 4404 Values[5] = 4405 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName, 4406 OCD, Category, ObjCTypes); 4407 } 4408 else { 4409 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy); 4410 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 4411 } 4412 4413 llvm::Constant *Init = 4414 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy, 4415 Values); 4416 llvm::GlobalVariable *GCATV 4417 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy, 4418 false, 4419 llvm::GlobalValue::InternalLinkage, 4420 Init, 4421 ExtCatName, 4422 &CGM.getModule()); 4423 GCATV->setAlignment( 4424 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy)); 4425 GCATV->setSection("__DATA, __objc_const"); 4426 UsedGlobals.push_back(GCATV); 4427 DefinedCategories.push_back(GCATV); 4428} 4429 4430/// GetMethodConstant - Return a struct objc_method constant for the 4431/// given method if it has been defined. The result is null if the 4432/// method has not been defined. The return value has type MethodPtrTy. 4433llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant( 4434 const ObjCMethodDecl *MD) { 4435 // FIXME: Use DenseMap::lookup 4436 llvm::Function *Fn = MethodDefinitions[MD]; 4437 if (!Fn) 4438 return 0; 4439 4440 std::vector<llvm::Constant*> Method(3); 4441 Method[0] = 4442 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 4443 ObjCTypes.SelectorPtrTy); 4444 Method[1] = GetMethodVarType(MD); 4445 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy); 4446 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); 4447} 4448 4449/// EmitMethodList - Build meta-data for method declarations 4450/// struct _method_list_t { 4451/// uint32_t entsize; // sizeof(struct _objc_method) 4452/// uint32_t method_count; 4453/// struct _objc_method method_list[method_count]; 4454/// } 4455/// 4456llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList( 4457 const std::string &Name, 4458 const char *Section, 4459 const ConstantVector &Methods) { 4460 // Return null for empty list. 4461 if (Methods.empty()) 4462 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy); 4463 4464 std::vector<llvm::Constant*> Values(3); 4465 // sizeof(struct _objc_method) 4466 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy); 4467 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 4468 // method_count 4469 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 4470 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, 4471 Methods.size()); 4472 Values[2] = llvm::ConstantArray::get(AT, Methods); 4473 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 4474 4475 llvm::GlobalVariable *GV = 4476 new llvm::GlobalVariable(Init->getType(), false, 4477 llvm::GlobalValue::InternalLinkage, 4478 Init, 4479 Name, 4480 &CGM.getModule()); 4481 GV->setAlignment( 4482 CGM.getTargetData().getPrefTypeAlignment(Init->getType())); 4483 GV->setSection(Section); 4484 UsedGlobals.push_back(GV); 4485 return llvm::ConstantExpr::getBitCast(GV, 4486 ObjCTypes.MethodListnfABIPtrTy); 4487} 4488 4489/// ObjCIvarOffsetVariable - Returns the ivar offset variable for 4490/// the given ivar. 4491/// 4492llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable( 4493 std::string &Name, 4494 const ObjCInterfaceDecl *ID, 4495 const ObjCIvarDecl *Ivar) { 4496 Name += "OBJC_IVAR_$_" + 4497 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() + 4498 '.' + Ivar->getNameAsString(); 4499 llvm::GlobalVariable *IvarOffsetGV = 4500 CGM.getModule().getGlobalVariable(Name); 4501 if (!IvarOffsetGV) 4502 IvarOffsetGV = 4503 new llvm::GlobalVariable(ObjCTypes.LongTy, 4504 false, 4505 llvm::GlobalValue::ExternalLinkage, 4506 0, 4507 Name, 4508 &CGM.getModule()); 4509 return IvarOffsetGV; 4510} 4511 4512llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar( 4513 const ObjCInterfaceDecl *ID, 4514 const ObjCIvarDecl *Ivar, 4515 unsigned long int Offset) { 4516 4517 assert(ID && "EmitIvarOffsetVar - null interface decl."); 4518 std::string ExternalName("OBJC_IVAR_$_" + ID->getNameAsString() + '.' 4519 + Ivar->getNameAsString()); 4520 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset); 4521 llvm::GlobalVariable *IvarOffsetGV = 4522 CGM.getModule().getGlobalVariable(ExternalName); 4523 if (IvarOffsetGV) 4524 // ivar offset symbol already built due to user code referencing it. 4525 IvarOffsetGV->setInitializer(Init); 4526 else 4527 IvarOffsetGV = 4528 new llvm::GlobalVariable(Init->getType(), 4529 false, 4530 llvm::GlobalValue::ExternalLinkage, 4531 Init, 4532 ExternalName, 4533 &CGM.getModule()); 4534 IvarOffsetGV->setAlignment( 4535 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy)); 4536 // @private and @package have hidden visibility. 4537 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public || 4538 Ivar->getAccessControl() == ObjCIvarDecl::Protected); 4539 if (!globalVisibility || CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden) 4540 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 4541 else 4542 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility); 4543 IvarOffsetGV->setSection("__DATA, __objc_const"); 4544 return IvarOffsetGV; 4545} 4546 4547/// EmitIvarList - Emit the ivar list for the given 4548/// implementation. If ForClass is true the list of class ivars 4549/// (i.e. metaclass ivars) is emitted, otherwise the list of 4550/// interface ivars will be emitted. The return value has type 4551/// IvarListnfABIPtrTy. 4552/// struct _ivar_t { 4553/// unsigned long int *offset; // pointer to ivar offset location 4554/// char *name; 4555/// char *type; 4556/// uint32_t alignment; 4557/// uint32_t size; 4558/// } 4559/// struct _ivar_list_t { 4560/// uint32 entsize; // sizeof(struct _ivar_t) 4561/// uint32 count; 4562/// struct _iver_t list[count]; 4563/// } 4564/// 4565llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList( 4566 const ObjCImplementationDecl *ID) { 4567 4568 std::vector<llvm::Constant*> Ivars, Ivar(5); 4569 4570 const ObjCInterfaceDecl *OID = ID->getClassInterface(); 4571 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface"); 4572 4573 // FIXME. Consolidate this with similar code in GenerateClass. 4574 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID); 4575 4576 RecordDecl::field_iterator i,p; 4577 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p); 4578 // collect declared and synthesized ivars in a small vector. 4579 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars; 4580 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(), 4581 E = OID->ivar_end(); I != E; ++I) 4582 OIvars.push_back(*I); 4583 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()), 4584 E = OID->prop_end(CGM.getContext()); I != E; ++I) 4585 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl()) 4586 OIvars.push_back(IV); 4587 4588 unsigned iv = 0; 4589 for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()); 4590 i != e; ++i) { 4591 FieldDecl *Field = *i; 4592 uint64_t offset = GetIvarBaseOffset(Layout, Field); 4593 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset); 4594 if (Field->getIdentifier()) 4595 Ivar[1] = GetMethodVarName(Field->getIdentifier()); 4596 else 4597 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 4598 Ivar[2] = GetMethodVarType(Field); 4599 const llvm::Type *FieldTy = 4600 CGM.getTypes().ConvertTypeForMem(Field->getType()); 4601 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy); 4602 unsigned Align = CGM.getContext().getPreferredTypeAlign( 4603 Field->getType().getTypePtr()) >> 3; 4604 Align = llvm::Log2_32(Align); 4605 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align); 4606 // NOTE. Size of a bitfield does not match gcc's, because of the way 4607 // bitfields are treated special in each. But I am told that 'size' 4608 // for bitfield ivars is ignored by the runtime so it does not matter. 4609 // (even if it matters, some day, there is enough info. to get the bitfield 4610 // right! 4611 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 4612 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar)); 4613 } 4614 // Return null for empty list. 4615 if (Ivars.empty()) 4616 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); 4617 std::vector<llvm::Constant*> Values(3); 4618 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy); 4619 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 4620 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); 4621 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy, 4622 Ivars.size()); 4623 Values[2] = llvm::ConstantArray::get(AT, Ivars); 4624 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 4625 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_"; 4626 llvm::GlobalVariable *GV = 4627 new llvm::GlobalVariable(Init->getType(), false, 4628 llvm::GlobalValue::InternalLinkage, 4629 Init, 4630 Prefix + OID->getNameAsString(), 4631 &CGM.getModule()); 4632 GV->setAlignment( 4633 CGM.getTargetData().getPrefTypeAlignment(Init->getType())); 4634 GV->setSection("__DATA, __objc_const"); 4635 4636 UsedGlobals.push_back(GV); 4637 return llvm::ConstantExpr::getBitCast(GV, 4638 ObjCTypes.IvarListnfABIPtrTy); 4639} 4640 4641llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef( 4642 const ObjCProtocolDecl *PD) { 4643 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 4644 4645 if (!Entry) { 4646 // We use the initializer as a marker of whether this is a forward 4647 // reference or not. At module finalization we add the empty 4648 // contents for protocols which were referenced but never defined. 4649 Entry = 4650 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false, 4651 llvm::GlobalValue::ExternalLinkage, 4652 0, 4653 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(), 4654 &CGM.getModule()); 4655 Entry->setSection("__DATA,__datacoal_nt,coalesced"); 4656 UsedGlobals.push_back(Entry); 4657 } 4658 4659 return Entry; 4660} 4661 4662/// GetOrEmitProtocol - Generate the protocol meta-data: 4663/// @code 4664/// struct _protocol_t { 4665/// id isa; // NULL 4666/// const char * const protocol_name; 4667/// const struct _protocol_list_t * protocol_list; // super protocols 4668/// const struct method_list_t * const instance_methods; 4669/// const struct method_list_t * const class_methods; 4670/// const struct method_list_t *optionalInstanceMethods; 4671/// const struct method_list_t *optionalClassMethods; 4672/// const struct _prop_list_t * properties; 4673/// const uint32_t size; // sizeof(struct _protocol_t) 4674/// const uint32_t flags; // = 0 4675/// } 4676/// @endcode 4677/// 4678 4679llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol( 4680 const ObjCProtocolDecl *PD) { 4681 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 4682 4683 // Early exit if a defining object has already been generated. 4684 if (Entry && Entry->hasInitializer()) 4685 return Entry; 4686 4687 const char *ProtocolName = PD->getNameAsCString(); 4688 4689 // Construct method lists. 4690 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 4691 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; 4692 for (ObjCProtocolDecl::instmeth_iterator 4693 i = PD->instmeth_begin(CGM.getContext()), 4694 e = PD->instmeth_end(CGM.getContext()); 4695 i != e; ++i) { 4696 ObjCMethodDecl *MD = *i; 4697 llvm::Constant *C = GetMethodDescriptionConstant(MD); 4698 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 4699 OptInstanceMethods.push_back(C); 4700 } else { 4701 InstanceMethods.push_back(C); 4702 } 4703 } 4704 4705 for (ObjCProtocolDecl::classmeth_iterator 4706 i = PD->classmeth_begin(CGM.getContext()), 4707 e = PD->classmeth_end(CGM.getContext()); 4708 i != e; ++i) { 4709 ObjCMethodDecl *MD = *i; 4710 llvm::Constant *C = GetMethodDescriptionConstant(MD); 4711 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 4712 OptClassMethods.push_back(C); 4713 } else { 4714 ClassMethods.push_back(C); 4715 } 4716 } 4717 4718 std::vector<llvm::Constant*> Values(10); 4719 // isa is NULL 4720 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy); 4721 Values[1] = GetClassName(PD->getIdentifier()); 4722 Values[2] = EmitProtocolList( 4723 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(), 4724 PD->protocol_begin(), 4725 PD->protocol_end()); 4726 4727 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_" 4728 + PD->getNameAsString(), 4729 "__DATA, __objc_const", 4730 InstanceMethods); 4731 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_" 4732 + PD->getNameAsString(), 4733 "__DATA, __objc_const", 4734 ClassMethods); 4735 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_" 4736 + PD->getNameAsString(), 4737 "__DATA, __objc_const", 4738 OptInstanceMethods); 4739 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_" 4740 + PD->getNameAsString(), 4741 "__DATA, __objc_const", 4742 OptClassMethods); 4743 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(), 4744 0, PD, ObjCTypes); 4745 uint32_t Size = 4746 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy); 4747 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 4748 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy); 4749 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy, 4750 Values); 4751 4752 if (Entry) { 4753 // Already created, fix the linkage and update the initializer. 4754 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage); 4755 Entry->setInitializer(Init); 4756 } else { 4757 Entry = 4758 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false, 4759 llvm::GlobalValue::WeakAnyLinkage, 4760 Init, 4761 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName, 4762 &CGM.getModule()); 4763 Entry->setAlignment( 4764 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy)); 4765 Entry->setSection("__DATA,__datacoal_nt,coalesced"); 4766 } 4767 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); 4768 4769 // Use this protocol meta-data to build protocol list table in section 4770 // __DATA, __objc_protolist 4771 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable( 4772 ObjCTypes.ProtocolnfABIPtrTy, false, 4773 llvm::GlobalValue::WeakAnyLinkage, 4774 Entry, 4775 std::string("\01l_OBJC_LABEL_PROTOCOL_$_") 4776 +ProtocolName, 4777 &CGM.getModule()); 4778 PTGV->setAlignment( 4779 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy)); 4780 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip"); 4781 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 4782 UsedGlobals.push_back(PTGV); 4783 return Entry; 4784} 4785 4786/// EmitProtocolList - Generate protocol list meta-data: 4787/// @code 4788/// struct _protocol_list_t { 4789/// long protocol_count; // Note, this is 32/64 bit 4790/// struct _protocol_t[protocol_count]; 4791/// } 4792/// @endcode 4793/// 4794llvm::Constant * 4795CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name, 4796 ObjCProtocolDecl::protocol_iterator begin, 4797 ObjCProtocolDecl::protocol_iterator end) { 4798 std::vector<llvm::Constant*> ProtocolRefs; 4799 4800 // Just return null for empty protocol lists 4801 if (begin == end) 4802 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy); 4803 4804 // FIXME: We shouldn't need to do this lookup here, should we? 4805 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); 4806 if (GV) 4807 return llvm::ConstantExpr::getBitCast(GV, 4808 ObjCTypes.ProtocolListnfABIPtrTy); 4809 4810 for (; begin != end; ++begin) 4811 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented??? 4812 4813 // This list is null terminated. 4814 ProtocolRefs.push_back(llvm::Constant::getNullValue( 4815 ObjCTypes.ProtocolnfABIPtrTy)); 4816 4817 std::vector<llvm::Constant*> Values(2); 4818 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); 4819 Values[1] = 4820 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy, 4821 ProtocolRefs.size()), 4822 ProtocolRefs); 4823 4824 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 4825 GV = new llvm::GlobalVariable(Init->getType(), false, 4826 llvm::GlobalValue::InternalLinkage, 4827 Init, 4828 Name, 4829 &CGM.getModule()); 4830 GV->setSection("__DATA, __objc_const"); 4831 GV->setAlignment( 4832 CGM.getTargetData().getPrefTypeAlignment(Init->getType())); 4833 UsedGlobals.push_back(GV); 4834 return llvm::ConstantExpr::getBitCast(GV, 4835 ObjCTypes.ProtocolListnfABIPtrTy); 4836} 4837 4838/// GetMethodDescriptionConstant - This routine build following meta-data: 4839/// struct _objc_method { 4840/// SEL _cmd; 4841/// char *method_type; 4842/// char *_imp; 4843/// } 4844 4845llvm::Constant * 4846CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { 4847 std::vector<llvm::Constant*> Desc(3); 4848 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 4849 ObjCTypes.SelectorPtrTy); 4850 Desc[1] = GetMethodVarType(MD); 4851 // Protocol methods have no implementation. So, this entry is always NULL. 4852 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 4853 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc); 4854} 4855 4856/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference. 4857/// This code gen. amounts to generating code for: 4858/// @code 4859/// (type *)((char *)base + _OBJC_IVAR_$_.ivar; 4860/// @encode 4861/// 4862LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar( 4863 CodeGen::CodeGenFunction &CGF, 4864 QualType ObjectTy, 4865 llvm::Value *BaseValue, 4866 const ObjCIvarDecl *Ivar, 4867 const FieldDecl *Field, 4868 unsigned CVRQualifiers) { 4869 assert(ObjectTy->isObjCInterfaceType() && 4870 "CGObjCNonFragileABIMac::EmitObjCValueForIvar"); 4871 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl(); 4872 std::string ExternalName; 4873 llvm::GlobalVariable *IvarOffsetGV = 4874 ObjCIvarOffsetVariable(ExternalName, ID, Ivar); 4875 4876 // (char *) BaseValue 4877 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy); 4878 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV); 4879 // (char*)BaseValue + Offset_symbol 4880 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr"); 4881 // (type *)((char*)BaseValue + Offset_symbol) 4882 const llvm::Type *IvarTy = 4883 CGM.getTypes().ConvertTypeForMem(Ivar->getType()); 4884 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy); 4885 V = CGF.Builder.CreateBitCast(V, ptrIvarTy); 4886 4887 if (Ivar->isBitField()) { 4888 QualType FieldTy = Field->getType(); 4889 CodeGenTypes::BitFieldInfo bitFieldInfo = 4890 CGM.getTypes().getBitFieldInfo(Field); 4891 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size, 4892 FieldTy->isSignedIntegerType(), 4893 FieldTy.getCVRQualifiers()|CVRQualifiers); 4894 } 4895 4896 LValue LV = LValue::MakeAddr(V, 4897 Ivar->getType().getCVRQualifiers()|CVRQualifiers, 4898 CGM.getContext().getObjCGCAttrKind(Ivar->getType())); 4899 LValue::SetObjCIvar(LV, true); 4900 return LV; 4901} 4902 4903llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset( 4904 CodeGen::CodeGenFunction &CGF, 4905 ObjCInterfaceDecl *Interface, 4906 const ObjCIvarDecl *Ivar) { 4907 std::string ExternalName; 4908 llvm::GlobalVariable *IvarOffsetGV = 4909 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar); 4910 4911 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar"); 4912} 4913 4914CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend( 4915 CodeGen::CodeGenFunction &CGF, 4916 QualType ResultType, 4917 Selector Sel, 4918 llvm::Value *Receiver, 4919 QualType Arg0Ty, 4920 bool IsSuper, 4921 const CallArgList &CallArgs) { 4922 // FIXME. Even though IsSuper is passes. This function doese not 4923 // handle calls to 'super' receivers. 4924 CodeGenTypes &Types = CGM.getTypes(); 4925 llvm::Value *Arg0 = Receiver; 4926 if (!IsSuper) 4927 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp"); 4928 4929 // Find the message function name. 4930 // FIXME. This is too much work to get the ABI-specific result type 4931 // needed to find the message name. 4932 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, 4933 llvm::SmallVector<QualType, 16>()); 4934 llvm::Constant *Fn; 4935 std::string Name("\01l_"); 4936 if (CGM.ReturnTypeUsesSret(FnInfo)) { 4937#if 0 4938 // unlike what is documented. gcc never generates this API!! 4939 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) { 4940 Fn = ObjCTypes.MessageSendIdStretFixupFn; 4941 // FIXME. Is there a better way of getting these names. 4942 // They are available in RuntimeFunctions vector pair. 4943 Name += "objc_msgSendId_stret_fixup"; 4944 } 4945 else 4946#endif 4947 if (IsSuper) { 4948 Fn = ObjCTypes.MessageSendSuper2StretFixupFn; 4949 Name += "objc_msgSendSuper2_stret_fixup"; 4950 } 4951 else 4952 { 4953 Fn = ObjCTypes.MessageSendStretFixupFn; 4954 Name += "objc_msgSend_stret_fixup"; 4955 } 4956 } 4957 else if (ResultType->isFloatingType() && 4958 // Selection of frret API only happens in 32bit nonfragile ABI. 4959 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) { 4960 Fn = ObjCTypes.MessageSendFpretFixupFn; 4961 Name += "objc_msgSend_fpret_fixup"; 4962 } 4963 else { 4964#if 0 4965// unlike what is documented. gcc never generates this API!! 4966 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) { 4967 Fn = ObjCTypes.MessageSendIdFixupFn; 4968 Name += "objc_msgSendId_fixup"; 4969 } 4970 else 4971#endif 4972 if (IsSuper) { 4973 Fn = ObjCTypes.MessageSendSuper2FixupFn; 4974 Name += "objc_msgSendSuper2_fixup"; 4975 } 4976 else 4977 { 4978 Fn = ObjCTypes.MessageSendFixupFn; 4979 Name += "objc_msgSend_fixup"; 4980 } 4981 } 4982 Name += '_'; 4983 std::string SelName(Sel.getAsString()); 4984 // Replace all ':' in selector name with '_' ouch! 4985 for(unsigned i = 0; i < SelName.size(); i++) 4986 if (SelName[i] == ':') 4987 SelName[i] = '_'; 4988 Name += SelName; 4989 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); 4990 if (!GV) { 4991 // Build message ref table entry. 4992 std::vector<llvm::Constant*> Values(2); 4993 Values[0] = Fn; 4994 Values[1] = GetMethodVarName(Sel); 4995 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 4996 GV = new llvm::GlobalVariable(Init->getType(), false, 4997 llvm::GlobalValue::WeakAnyLinkage, 4998 Init, 4999 Name, 5000 &CGM.getModule()); 5001 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 5002 GV->setAlignment(16); 5003 GV->setSection("__DATA, __objc_msgrefs, coalesced"); 5004 } 5005 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy); 5006 5007 CallArgList ActualArgs; 5008 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty)); 5009 ActualArgs.push_back(std::make_pair(RValue::get(Arg1), 5010 ObjCTypes.MessageRefCPtrTy)); 5011 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 5012 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs); 5013 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0); 5014 Callee = CGF.Builder.CreateLoad(Callee); 5015 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true); 5016 Callee = CGF.Builder.CreateBitCast(Callee, 5017 llvm::PointerType::getUnqual(FTy)); 5018 return CGF.EmitCall(FnInfo1, Callee, ActualArgs); 5019} 5020 5021/// Generate code for a message send expression in the nonfragile abi. 5022CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend( 5023 CodeGen::CodeGenFunction &CGF, 5024 QualType ResultType, 5025 Selector Sel, 5026 llvm::Value *Receiver, 5027 bool IsClassMessage, 5028 const CallArgList &CallArgs) { 5029 return EmitMessageSend(CGF, ResultType, Sel, 5030 Receiver, CGF.getContext().getObjCIdType(), 5031 false, CallArgs); 5032} 5033 5034llvm::GlobalVariable * 5035CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) { 5036 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); 5037 5038 if (!GV) { 5039 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, 5040 llvm::GlobalValue::ExternalLinkage, 5041 0, Name, &CGM.getModule()); 5042 } 5043 5044 return GV; 5045} 5046 5047llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder, 5048 const ObjCInterfaceDecl *ID, 5049 bool IsSuper) { 5050 5051 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()]; 5052 5053 if (!Entry) { 5054 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString()); 5055 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName); 5056 Entry = 5057 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false, 5058 llvm::GlobalValue::InternalLinkage, 5059 ClassGV, 5060 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_" 5061 : "\01L_OBJC_CLASSLIST_REFERENCES_$_", 5062 &CGM.getModule()); 5063 Entry->setAlignment( 5064 CGM.getTargetData().getPrefTypeAlignment( 5065 ObjCTypes.ClassnfABIPtrTy)); 5066 5067 if (IsSuper) 5068 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip"); 5069 else 5070 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip"); 5071 UsedGlobals.push_back(Entry); 5072 } 5073 5074 return Builder.CreateLoad(Entry, false, "tmp"); 5075} 5076 5077/// EmitMetaClassRef - Return a Value * of the address of _class_t 5078/// meta-data 5079/// 5080llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder, 5081 const ObjCInterfaceDecl *ID) { 5082 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()]; 5083 if (Entry) 5084 return Builder.CreateLoad(Entry, false, "tmp"); 5085 5086 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString()); 5087 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName); 5088 Entry = 5089 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false, 5090 llvm::GlobalValue::InternalLinkage, 5091 MetaClassGV, 5092 "\01L_OBJC_CLASSLIST_SUP_REFS_$_", 5093 &CGM.getModule()); 5094 Entry->setAlignment( 5095 CGM.getTargetData().getPrefTypeAlignment( 5096 ObjCTypes.ClassnfABIPtrTy)); 5097 5098 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip"); 5099 UsedGlobals.push_back(Entry); 5100 5101 return Builder.CreateLoad(Entry, false, "tmp"); 5102} 5103 5104/// GetClass - Return a reference to the class for the given interface 5105/// decl. 5106llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder, 5107 const ObjCInterfaceDecl *ID) { 5108 return EmitClassRef(Builder, ID); 5109} 5110 5111/// Generates a message send where the super is the receiver. This is 5112/// a message send to self with special delivery semantics indicating 5113/// which class's method should be called. 5114CodeGen::RValue 5115CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 5116 QualType ResultType, 5117 Selector Sel, 5118 const ObjCInterfaceDecl *Class, 5119 bool isCategoryImpl, 5120 llvm::Value *Receiver, 5121 bool IsClassMessage, 5122 const CodeGen::CallArgList &CallArgs) { 5123 // ... 5124 // Create and init a super structure; this is a (receiver, class) 5125 // pair we will pass to objc_msgSendSuper. 5126 llvm::Value *ObjCSuper = 5127 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super"); 5128 5129 llvm::Value *ReceiverAsObject = 5130 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); 5131 CGF.Builder.CreateStore(ReceiverAsObject, 5132 CGF.Builder.CreateStructGEP(ObjCSuper, 0)); 5133 5134 // If this is a class message the metaclass is passed as the target. 5135 llvm::Value *Target; 5136 if (IsClassMessage) { 5137 if (isCategoryImpl) { 5138 // Message sent to "super' in a class method defined in 5139 // a category implementation. 5140 Target = EmitClassRef(CGF.Builder, Class, false); 5141 Target = CGF.Builder.CreateStructGEP(Target, 0); 5142 Target = CGF.Builder.CreateLoad(Target); 5143 } 5144 else 5145 Target = EmitMetaClassRef(CGF.Builder, Class); 5146 } 5147 else 5148 Target = EmitClassRef(CGF.Builder, Class, true); 5149 5150 // FIXME: We shouldn't need to do this cast, rectify the ASTContext 5151 // and ObjCTypes types. 5152 const llvm::Type *ClassTy = 5153 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); 5154 Target = CGF.Builder.CreateBitCast(Target, ClassTy); 5155 CGF.Builder.CreateStore(Target, 5156 CGF.Builder.CreateStructGEP(ObjCSuper, 1)); 5157 5158 return EmitMessageSend(CGF, ResultType, Sel, 5159 ObjCSuper, ObjCTypes.SuperPtrCTy, 5160 true, CallArgs); 5161} 5162 5163llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder, 5164 Selector Sel) { 5165 llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; 5166 5167 if (!Entry) { 5168 llvm::Constant *Casted = 5169 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), 5170 ObjCTypes.SelectorPtrTy); 5171 Entry = 5172 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false, 5173 llvm::GlobalValue::InternalLinkage, 5174 Casted, "\01L_OBJC_SELECTOR_REFERENCES_", 5175 &CGM.getModule()); 5176 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip"); 5177 UsedGlobals.push_back(Entry); 5178 } 5179 5180 return Builder.CreateLoad(Entry, false, "tmp"); 5181} 5182/// EmitObjCIvarAssign - Code gen for assigning to a __strong object. 5183/// objc_assign_ivar (id src, id *dst) 5184/// 5185void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 5186 llvm::Value *src, llvm::Value *dst) 5187{ 5188 const llvm::Type * SrcTy = src->getType(); 5189 if (!isa<llvm::PointerType>(SrcTy)) { 5190 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 5191 assert(Size <= 8 && "does not support size > 8"); 5192 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 5193 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 5194 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 5195 } 5196 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 5197 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 5198 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn, 5199 src, dst, "assignivar"); 5200 return; 5201} 5202 5203/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. 5204/// objc_assign_strongCast (id src, id *dst) 5205/// 5206void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign( 5207 CodeGen::CodeGenFunction &CGF, 5208 llvm::Value *src, llvm::Value *dst) 5209{ 5210 const llvm::Type * SrcTy = src->getType(); 5211 if (!isa<llvm::PointerType>(SrcTy)) { 5212 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 5213 assert(Size <= 8 && "does not support size > 8"); 5214 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 5215 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 5216 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 5217 } 5218 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 5219 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 5220 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn, 5221 src, dst, "weakassign"); 5222 return; 5223} 5224 5225/// EmitObjCWeakRead - Code gen for loading value of a __weak 5226/// object: objc_read_weak (id *src) 5227/// 5228llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead( 5229 CodeGen::CodeGenFunction &CGF, 5230 llvm::Value *AddrWeakObj) 5231{ 5232 const llvm::Type* DestTy = 5233 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType(); 5234 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); 5235 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn, 5236 AddrWeakObj, "weakread"); 5237 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy); 5238 return read_weak; 5239} 5240 5241/// EmitObjCWeakAssign - Code gen for assigning to a __weak object. 5242/// objc_assign_weak (id src, id *dst) 5243/// 5244void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 5245 llvm::Value *src, llvm::Value *dst) 5246{ 5247 const llvm::Type * SrcTy = src->getType(); 5248 if (!isa<llvm::PointerType>(SrcTy)) { 5249 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 5250 assert(Size <= 8 && "does not support size > 8"); 5251 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 5252 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 5253 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 5254 } 5255 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 5256 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 5257 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(), 5258 src, dst, "weakassign"); 5259 return; 5260} 5261 5262/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. 5263/// objc_assign_global (id src, id *dst) 5264/// 5265void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 5266 llvm::Value *src, llvm::Value *dst) 5267{ 5268 const llvm::Type * SrcTy = src->getType(); 5269 if (!isa<llvm::PointerType>(SrcTy)) { 5270 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 5271 assert(Size <= 8 && "does not support size > 8"); 5272 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 5273 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 5274 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 5275 } 5276 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 5277 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 5278 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn, 5279 src, dst, "globalassign"); 5280 return; 5281} 5282 5283void 5284CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 5285 const Stmt &S) { 5286 bool isTry = isa<ObjCAtTryStmt>(S); 5287 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); 5288 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest(); 5289 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); 5290 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally"); 5291 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw"); 5292 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end"); 5293 5294 // For @synchronized, call objc_sync_enter(sync.expr). The 5295 // evaluation of the expression must occur before we enter the 5296 // @synchronized. We can safely avoid a temp here because jumps into 5297 // @synchronized are illegal & this will dominate uses. 5298 llvm::Value *SyncArg = 0; 5299 if (!isTry) { 5300 SyncArg = 5301 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 5302 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy); 5303 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg); 5304 } 5305 5306 // Push an EH context entry, used for handling rethrows and jumps 5307 // through finally. 5308 CGF.PushCleanupBlock(FinallyBlock); 5309 5310 CGF.setInvokeDest(TryHandler); 5311 5312 CGF.EmitBlock(TryBlock); 5313 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() 5314 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); 5315 CGF.EmitBranchThroughCleanup(FinallyEnd); 5316 5317 // Emit the exception handler. 5318 5319 CGF.EmitBlock(TryHandler); 5320 5321 llvm::Value *llvm_eh_exception = 5322 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception); 5323 llvm::Value *llvm_eh_selector_i64 = 5324 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64); 5325 llvm::Value *llvm_eh_typeid_for_i64 = 5326 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64); 5327 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); 5328 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow"); 5329 5330 llvm::SmallVector<llvm::Value*, 8> SelectorArgs; 5331 SelectorArgs.push_back(Exc); 5332 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr()); 5333 5334 // Construct the lists of (type, catch body) to handle. 5335 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers; 5336 bool HasCatchAll = false; 5337 if (isTry) { 5338 if (const ObjCAtCatchStmt* CatchStmt = 5339 cast<ObjCAtTryStmt>(S).getCatchStmts()) { 5340 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) { 5341 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); 5342 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody())); 5343 5344 // catch(...) always matches. 5345 if (!CatchDecl) { 5346 // Use i8* null here to signal this is a catch all, not a cleanup. 5347 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 5348 SelectorArgs.push_back(Null); 5349 HasCatchAll = true; 5350 break; 5351 } 5352 5353 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) || 5354 CatchDecl->getType()->isObjCQualifiedIdType()) { 5355 llvm::Value *IDEHType = 5356 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id"); 5357 if (!IDEHType) 5358 IDEHType = 5359 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false, 5360 llvm::GlobalValue::ExternalLinkage, 5361 0, "OBJC_EHTYPE_id", &CGM.getModule()); 5362 SelectorArgs.push_back(IDEHType); 5363 HasCatchAll = true; 5364 break; 5365 } 5366 5367 // All other types should be Objective-C interface pointer types. 5368 const PointerType *PT = CatchDecl->getType()->getAsPointerType(); 5369 assert(PT && "Invalid @catch type."); 5370 const ObjCInterfaceType *IT = 5371 PT->getPointeeType()->getAsObjCInterfaceType(); 5372 assert(IT && "Invalid @catch type."); 5373 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false); 5374 SelectorArgs.push_back(EHType); 5375 } 5376 } 5377 } 5378 5379 // We use a cleanup unless there was already a catch all. 5380 if (!HasCatchAll) { 5381 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 5382 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0)); 5383 } 5384 5385 llvm::Value *Selector = 5386 CGF.Builder.CreateCall(llvm_eh_selector_i64, 5387 SelectorArgs.begin(), SelectorArgs.end(), 5388 "selector"); 5389 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) { 5390 const ParmVarDecl *CatchParam = Handlers[i].first; 5391 const Stmt *CatchBody = Handlers[i].second; 5392 5393 llvm::BasicBlock *Next = 0; 5394 5395 // The last handler always matches. 5396 if (i + 1 != e) { 5397 assert(CatchParam && "Only last handler can be a catch all."); 5398 5399 llvm::BasicBlock *Match = CGF.createBasicBlock("match"); 5400 Next = CGF.createBasicBlock("catch.next"); 5401 llvm::Value *Id = 5402 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64, 5403 CGF.Builder.CreateBitCast(SelectorArgs[i+2], 5404 ObjCTypes.Int8PtrTy)); 5405 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id), 5406 Match, Next); 5407 5408 CGF.EmitBlock(Match); 5409 } 5410 5411 if (CatchBody) { 5412 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end"); 5413 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler"); 5414 5415 // Cleanups must call objc_end_catch. 5416 // 5417 // FIXME: It seems incorrect for objc_begin_catch to be inside 5418 // this context, but this matches gcc. 5419 CGF.PushCleanupBlock(MatchEnd); 5420 CGF.setInvokeDest(MatchHandler); 5421 5422 llvm::Value *ExcObject = 5423 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc); 5424 5425 // Bind the catch parameter if it exists. 5426 if (CatchParam) { 5427 ExcObject = 5428 CGF.Builder.CreateBitCast(ExcObject, 5429 CGF.ConvertType(CatchParam->getType())); 5430 // CatchParam is a ParmVarDecl because of the grammar 5431 // construction used to handle this, but for codegen purposes 5432 // we treat this as a local decl. 5433 CGF.EmitLocalBlockVarDecl(*CatchParam); 5434 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam)); 5435 } 5436 5437 CGF.ObjCEHValueStack.push_back(ExcObject); 5438 CGF.EmitStmt(CatchBody); 5439 CGF.ObjCEHValueStack.pop_back(); 5440 5441 CGF.EmitBranchThroughCleanup(FinallyEnd); 5442 5443 CGF.EmitBlock(MatchHandler); 5444 5445 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); 5446 // We are required to emit this call to satisfy LLVM, even 5447 // though we don't use the result. 5448 llvm::SmallVector<llvm::Value*, 8> Args; 5449 Args.push_back(Exc); 5450 Args.push_back(ObjCTypes.getEHPersonalityPtr()); 5451 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 5452 0)); 5453 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end()); 5454 CGF.Builder.CreateStore(Exc, RethrowPtr); 5455 CGF.EmitBranchThroughCleanup(FinallyRethrow); 5456 5457 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); 5458 5459 CGF.EmitBlock(MatchEnd); 5460 5461 // Unfortunately, we also have to generate another EH frame here 5462 // in case this throws. 5463 llvm::BasicBlock *MatchEndHandler = 5464 CGF.createBasicBlock("match.end.handler"); 5465 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont"); 5466 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn, 5467 Cont, MatchEndHandler, 5468 Args.begin(), Args.begin()); 5469 5470 CGF.EmitBlock(Cont); 5471 if (Info.SwitchBlock) 5472 CGF.EmitBlock(Info.SwitchBlock); 5473 if (Info.EndBlock) 5474 CGF.EmitBlock(Info.EndBlock); 5475 5476 CGF.EmitBlock(MatchEndHandler); 5477 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); 5478 // We are required to emit this call to satisfy LLVM, even 5479 // though we don't use the result. 5480 Args.clear(); 5481 Args.push_back(Exc); 5482 Args.push_back(ObjCTypes.getEHPersonalityPtr()); 5483 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 5484 0)); 5485 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end()); 5486 CGF.Builder.CreateStore(Exc, RethrowPtr); 5487 CGF.EmitBranchThroughCleanup(FinallyRethrow); 5488 5489 if (Next) 5490 CGF.EmitBlock(Next); 5491 } else { 5492 assert(!Next && "catchup should be last handler."); 5493 5494 CGF.Builder.CreateStore(Exc, RethrowPtr); 5495 CGF.EmitBranchThroughCleanup(FinallyRethrow); 5496 } 5497 } 5498 5499 // Pop the cleanup entry, the @finally is outside this cleanup 5500 // scope. 5501 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); 5502 CGF.setInvokeDest(PrevLandingPad); 5503 5504 CGF.EmitBlock(FinallyBlock); 5505 5506 if (isTry) { 5507 if (const ObjCAtFinallyStmt* FinallyStmt = 5508 cast<ObjCAtTryStmt>(S).getFinallyStmt()) 5509 CGF.EmitStmt(FinallyStmt->getFinallyBody()); 5510 } else { 5511 // Emit 'objc_sync_exit(expr)' as finally's sole statement for 5512 // @synchronized. 5513 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg); 5514 } 5515 5516 if (Info.SwitchBlock) 5517 CGF.EmitBlock(Info.SwitchBlock); 5518 if (Info.EndBlock) 5519 CGF.EmitBlock(Info.EndBlock); 5520 5521 // Branch around the rethrow code. 5522 CGF.EmitBranch(FinallyEnd); 5523 5524 CGF.EmitBlock(FinallyRethrow); 5525 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn, 5526 CGF.Builder.CreateLoad(RethrowPtr)); 5527 CGF.Builder.CreateUnreachable(); 5528 5529 CGF.EmitBlock(FinallyEnd); 5530} 5531 5532/// EmitThrowStmt - Generate code for a throw statement. 5533void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 5534 const ObjCAtThrowStmt &S) { 5535 llvm::Value *Exception; 5536 if (const Expr *ThrowExpr = S.getThrowExpr()) { 5537 Exception = CGF.EmitScalarExpr(ThrowExpr); 5538 } else { 5539 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 5540 "Unexpected rethrow outside @catch block."); 5541 Exception = CGF.ObjCEHValueStack.back(); 5542 } 5543 5544 llvm::Value *ExceptionAsObject = 5545 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp"); 5546 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest(); 5547 if (InvokeDest) { 5548 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont"); 5549 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn, 5550 Cont, InvokeDest, 5551 &ExceptionAsObject, &ExceptionAsObject + 1); 5552 CGF.EmitBlock(Cont); 5553 } else 5554 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject); 5555 CGF.Builder.CreateUnreachable(); 5556 5557 // Clear the insertion point to indicate we are in unreachable code. 5558 CGF.Builder.ClearInsertionPoint(); 5559} 5560 5561llvm::Value * 5562CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID, 5563 bool ForDefinition) { 5564 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()]; 5565 5566 // If we don't need a definition, return the entry if found or check 5567 // if we use an external reference. 5568 if (!ForDefinition) { 5569 if (Entry) 5570 return Entry; 5571 5572 // If this type (or a super class) has the __objc_exception__ 5573 // attribute, emit an external reference. 5574 if (hasObjCExceptionAttribute(ID)) 5575 return Entry = 5576 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false, 5577 llvm::GlobalValue::ExternalLinkage, 5578 0, 5579 (std::string("OBJC_EHTYPE_$_") + 5580 ID->getIdentifier()->getName()), 5581 &CGM.getModule()); 5582 } 5583 5584 // Otherwise we need to either make a new entry or fill in the 5585 // initializer. 5586 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition"); 5587 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString()); 5588 std::string VTableName = "objc_ehtype_vtable"; 5589 llvm::GlobalVariable *VTableGV = 5590 CGM.getModule().getGlobalVariable(VTableName); 5591 if (!VTableGV) 5592 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false, 5593 llvm::GlobalValue::ExternalLinkage, 5594 0, VTableName, &CGM.getModule()); 5595 5596 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2); 5597 5598 std::vector<llvm::Constant*> Values(3); 5599 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1); 5600 Values[1] = GetClassName(ID->getIdentifier()); 5601 Values[2] = GetClassGlobal(ClassName); 5602 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values); 5603 5604 if (Entry) { 5605 Entry->setInitializer(Init); 5606 } else { 5607 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false, 5608 llvm::GlobalValue::WeakAnyLinkage, 5609 Init, 5610 (std::string("OBJC_EHTYPE_$_") + 5611 ID->getIdentifier()->getName()), 5612 &CGM.getModule()); 5613 } 5614 5615 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden) 5616 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); 5617 Entry->setAlignment(8); 5618 5619 if (ForDefinition) { 5620 Entry->setSection("__DATA,__objc_const"); 5621 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage); 5622 } else { 5623 Entry->setSection("__DATA,__datacoal_nt,coalesced"); 5624 } 5625 5626 return Entry; 5627} 5628 5629/* *** */ 5630 5631CodeGen::CGObjCRuntime * 5632CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) { 5633 return new CGObjCMac(CGM); 5634} 5635 5636CodeGen::CGObjCRuntime * 5637CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) { 5638 return new CGObjCNonFragileABIMac(CGM); 5639} 5640