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