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