CGObjCMac.cpp revision 46f45b9bec4a265ad8400a538e5ec3a5683617f1
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/Module.h" 24#include "llvm/Support/IRBuilder.h" 25#include "llvm/Target/TargetData.h" 26#include <sstream> 27 28using namespace clang; 29using namespace CodeGen; 30 31namespace { 32 33 typedef std::vector<llvm::Constant*> ConstantVector; 34 35 // FIXME: We should find a nicer way to make the labels for 36 // metadata, string concatenation is lame. 37 38/// ObjCTypesHelper - Helper class that encapsulates lazy 39/// construction of varies types used during ObjC generation. 40class ObjCTypesHelper { 41private: 42 CodeGen::CodeGenModule &CGM; 43 44 llvm::Function *MessageSendFn, *MessageSendStretFn; 45 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn; 46 47public: 48 const llvm::Type *ShortTy, *IntTy, *LongTy; 49 const llvm::Type *Int8PtrTy; 50 51 /// ObjectPtrTy - LLVM type for object handles (typeof(id)) 52 const llvm::Type *ObjectPtrTy; 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 /// SymtabTy - LLVM type for struct objc_symtab. 70 const llvm::StructType *SymtabTy; 71 /// SymtabPtrTy - LLVM type for struct objc_symtab *. 72 const llvm::Type *SymtabPtrTy; 73 /// ModuleTy - LLVM type for struct objc_module. 74 const llvm::StructType *ModuleTy; 75 76 /// ProtocolTy - LLVM type for struct objc_protocol. 77 const llvm::StructType *ProtocolTy; 78 /// ProtocolPtrTy - LLVM type for struct objc_protocol *. 79 const llvm::Type *ProtocolPtrTy; 80 /// ProtocolExtensionTy - LLVM type for struct 81 /// objc_protocol_extension. 82 const llvm::StructType *ProtocolExtensionTy; 83 /// ProtocolExtensionTy - LLVM type for struct 84 /// objc_protocol_extension *. 85 const llvm::Type *ProtocolExtensionPtrTy; 86 /// MethodDescriptionTy - LLVM type for struct 87 /// objc_method_description. 88 const llvm::StructType *MethodDescriptionTy; 89 /// MethodDescriptionListTy - LLVM type for struct 90 /// objc_method_description_list. 91 const llvm::StructType *MethodDescriptionListTy; 92 /// MethodDescriptionListPtrTy - LLVM type for struct 93 /// objc_method_description_list *. 94 const llvm::Type *MethodDescriptionListPtrTy; 95 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t 96 /// in GCC parlance). 97 const llvm::StructType *PropertyTy; 98 /// PropertyListTy - LLVM type for struct objc_property_list 99 /// (_prop_list_t in GCC parlance). 100 const llvm::StructType *PropertyListTy; 101 /// PropertyListPtrTy - LLVM type for struct objc_property_list*. 102 const llvm::Type *PropertyListPtrTy; 103 /// ProtocolListTy - LLVM type for struct objc_property_list. 104 const llvm::Type *ProtocolListTy; 105 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*. 106 const llvm::Type *ProtocolListPtrTy; 107 /// CategoryTy - LLVM type for struct objc_category. 108 const llvm::StructType *CategoryTy; 109 /// ClassTy - LLVM type for struct objc_class. 110 const llvm::StructType *ClassTy; 111 /// ClassPtrTy - LLVM type for struct objc_class *. 112 const llvm::Type *ClassPtrTy; 113 /// ClassExtensionTy - LLVM type for struct objc_class_ext. 114 const llvm::StructType *ClassExtensionTy; 115 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *. 116 const llvm::Type *ClassExtensionPtrTy; 117 /// CacheTy - LLVM type for struct objc_cache. 118 const llvm::Type *CacheTy; 119 /// CachePtrTy - LLVM type for struct objc_cache *. 120 const llvm::Type *CachePtrTy; 121 // IvarTy - LLVM type for struct objc_ivar. 122 const llvm::StructType *IvarTy; 123 /// IvarListTy - LLVM type for struct objc_ivar_list. 124 const llvm::Type *IvarListTy; 125 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *. 126 const llvm::Type *IvarListPtrTy; 127 // MethodTy - LLVM type for struct objc_method. 128 const llvm::StructType *MethodTy; 129 /// MethodListTy - LLVM type for struct objc_method_list. 130 const llvm::Type *MethodListTy; 131 /// MethodListPtrTy - LLVM type for struct objc_method_list *. 132 const llvm::Type *MethodListPtrTy; 133 134 llvm::Function *EnumerationMutationFn; 135public: 136 ObjCTypesHelper(CodeGen::CodeGenModule &cgm); 137 ~ObjCTypesHelper(); 138 139 llvm::Value *getMessageSendFn(bool IsSuper, const llvm::Type *ReturnTy); 140}; 141 142class CGObjCMac : public CodeGen::CGObjCRuntime { 143private: 144 CodeGen::CodeGenModule &CGM; 145 ObjCTypesHelper ObjCTypes; 146 /// ObjCABI - FIXME: Not sure yet. 147 unsigned ObjCABI; 148 149 /// LazySymbols - Symbols to generate a lazy reference for. See 150 /// DefinedSymbols and FinishModule(). 151 std::set<IdentifierInfo*> LazySymbols; 152 153 /// DefinedSymbols - External symbols which are defined by this 154 /// module. The symbols in this list and LazySymbols are used to add 155 /// special linker symbols which ensure that Objective-C modules are 156 /// linked properly. 157 std::set<IdentifierInfo*> DefinedSymbols; 158 159 /// ClassNames - uniqued class names. 160 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames; 161 162 /// MethodVarNames - uniqued method variable names. 163 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames; 164 165 /// MethodVarTypes - uniqued method type signatures. We have to use 166 /// a StringMap here because have no other unique reference. 167 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes; 168 169 /// MethodDefinitions - map of methods which have been defined in 170 /// this translation unit. 171 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions; 172 173 /// PropertyNames - uniqued method variable names. 174 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames; 175 176 /// ClassReferences - uniqued class references. 177 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences; 178 179 /// SelectorReferences - uniqued selector references. 180 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences; 181 182 /// Protocols - Protocols for which an objc_protocol structure has 183 /// been emitted. Forward declarations are handled by creating an 184 /// empty structure whose initializer is filled in when/if defined. 185 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols; 186 187 /// DefinedClasses - List of defined classes. 188 std::vector<llvm::GlobalValue*> DefinedClasses; 189 190 /// DefinedCategories - List of defined categories. 191 std::vector<llvm::GlobalValue*> DefinedCategories; 192 193 /// UsedGlobals - List of globals to pack into the llvm.used metadata 194 /// to prevent them from being clobbered. 195 std::vector<llvm::GlobalVariable*> UsedGlobals; 196 197 /// EmitImageInfo - Emit the image info marker used to encode some module 198 /// level information. 199 void EmitImageInfo(); 200 201 /// EmitModuleInfo - Another marker encoding module level 202 /// information. 203 void EmitModuleInfo(); 204 205 /// EmitModuleSymols - Emit module symbols, the list of defined 206 /// classes and categories. The result has type SymtabPtrTy. 207 llvm::Constant *EmitModuleSymbols(); 208 209 /// FinishModule - Write out global data structures at the end of 210 /// processing a translation unit. 211 void FinishModule(); 212 213 /// EmitClassExtension - Generate the class extension structure used 214 /// to store the weak ivar layout and properties. The return value 215 /// has type ClassExtensionPtrTy. 216 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID); 217 218 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 219 /// for the given class. 220 llvm::Value *EmitClassRef(llvm::IRBuilder<> &Builder, 221 const ObjCInterfaceDecl *ID); 222 223 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, 224 QualType ResultType, 225 Selector Sel, 226 llvm::Value *Arg0, 227 QualType Arg0Ty, 228 bool IsSuper, 229 const CallArgList &CallArgs); 230 231 /// EmitIvarList - Emit the ivar list for the given 232 /// implementation. If ForClass is true the list of class ivars 233 /// (i.e. metaclass ivars) is emitted, otherwise the list of 234 /// interface ivars will be emitted. The return value has type 235 /// IvarListPtrTy. 236 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID, 237 bool ForClass, 238 const llvm::Type *InterfaceTy); 239 240 /// EmitMetaClass - Emit a forward reference to the class structure 241 /// for the metaclass of the given interface. The return value has 242 /// type ClassPtrTy. 243 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID); 244 245 /// EmitMetaClass - Emit a class structure for the metaclass of the 246 /// given implementation. The return value has type ClassPtrTy. 247 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID, 248 llvm::Constant *Protocols, 249 const llvm::Type *InterfaceTy, 250 const ConstantVector &Methods); 251 252 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); 253 254 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); 255 256 /// EmitMethodList - Emit the method list for the given 257 /// implementation. The return value has type MethodListPtrTy. 258 llvm::Constant *EmitMethodList(const std::string &Name, 259 const char *Section, 260 const ConstantVector &Methods); 261 262 /// EmitMethodDescList - Emit a method description list for a list of 263 /// method declarations. 264 /// - TypeName: The name for the type containing the methods. 265 /// - IsProtocol: True iff these methods are for a protocol. 266 /// - ClassMethds: True iff these are class methods. 267 /// - Required: When true, only "required" methods are 268 /// listed. Similarly, when false only "optional" methods are 269 /// listed. For classes this should always be true. 270 /// - begin, end: The method list to output. 271 /// 272 /// The return value has type MethodDescriptionListPtrTy. 273 llvm::Constant *EmitMethodDescList(const std::string &Name, 274 const char *Section, 275 const ConstantVector &Methods); 276 277 /// EmitPropertyList - Emit the given property list. The return 278 /// value has type PropertyListPtrTy. 279 llvm::Constant *EmitPropertyList(const std::string &Name, 280 const Decl *Container, 281 ObjCPropertyDecl * const *begin, 282 ObjCPropertyDecl * const *end); 283 284 /// EmitProtocolExtension - Generate the protocol extension 285 /// structure used to store optional instance and class methods, and 286 /// protocol properties. The return value has type 287 /// ProtocolExtensionPtrTy. 288 llvm::Constant * 289 EmitProtocolExtension(const ObjCProtocolDecl *PD, 290 const ConstantVector &OptInstanceMethods, 291 const ConstantVector &OptClassMethods); 292 293 /// EmitProtocolList - Generate the list of referenced 294 /// protocols. The return value has type ProtocolListPtrTy. 295 llvm::Constant *EmitProtocolList(const std::string &Name, 296 ObjCProtocolDecl::protocol_iterator begin, 297 ObjCProtocolDecl::protocol_iterator end); 298 299 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, 300 /// for the given selector. 301 llvm::Value *EmitSelector(llvm::IRBuilder<> &Builder, Selector Sel); 302 303 /// GetProtocolRef - Return a reference to the internal protocol 304 /// description, creating an empty one if it has not been 305 /// defined. The return value has type pointer-to ProtocolTy. 306 llvm::GlobalVariable *GetProtocolRef(const ObjCProtocolDecl *PD); 307 308 /// GetClassName - Return a unique constant for the given selector's 309 /// name. The return value has type char *. 310 llvm::Constant *GetClassName(IdentifierInfo *Ident); 311 312 /// GetMethodVarName - Return a unique constant for the given 313 /// selector's name. The return value has type char *. 314 llvm::Constant *GetMethodVarName(Selector Sel); 315 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident); 316 llvm::Constant *GetMethodVarName(const std::string &Name); 317 318 /// GetMethodVarType - Return a unique constant for the given 319 /// selector's name. The return value has type char *. 320 321 // FIXME: This is a horrible name. 322 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D); 323 llvm::Constant *GetMethodVarType(const std::string &Name); 324 325 /// GetPropertyName - Return a unique constant for the given 326 /// name. The return value has type char *. 327 llvm::Constant *GetPropertyName(IdentifierInfo *Ident); 328 329 // FIXME: This can be dropped once string functions are unified. 330 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD, 331 const Decl *Container); 332 333 /// GetNameForMethod - Return a name for the given method. 334 /// \param[out] NameOut - The return value. 335 void GetNameForMethod(const ObjCMethodDecl *OMD, 336 std::string &NameOut); 337 338public: 339 CGObjCMac(CodeGen::CodeGenModule &cgm); 340 virtual llvm::Constant *GenerateConstantString(const std::string &String); 341 342 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 343 QualType ResultType, 344 Selector Sel, 345 llvm::Value *Receiver, 346 bool IsClassMessage, 347 const CallArgList &CallArgs); 348 349 virtual CodeGen::RValue 350 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 351 QualType ResultType, 352 Selector Sel, 353 const ObjCInterfaceDecl *Class, 354 llvm::Value *Receiver, 355 bool IsClassMessage, 356 const CallArgList &CallArgs); 357 358 virtual llvm::Value *GetClass(llvm::IRBuilder<> &Builder, 359 const ObjCInterfaceDecl *ID); 360 361 virtual llvm::Value *GetSelector(llvm::IRBuilder<> &Builder, Selector Sel); 362 363 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD); 364 365 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 366 367 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 368 369 virtual llvm::Value *GenerateProtocolRef(llvm::IRBuilder<> &Builder, 370 const ObjCProtocolDecl *PD); 371 372 virtual void GenerateProtocol(const ObjCProtocolDecl *PD); 373 374 virtual llvm::Function *ModuleInitFunction(); 375 virtual llvm::Function *EnumerationMutationFunction(); 376}; 377} // end anonymous namespace 378 379/* *** Helper Functions *** */ 380 381/// getConstantGEP() - Help routine to construct simple GEPs. 382static llvm::Constant *getConstantGEP(llvm::Constant *C, 383 unsigned idx0, 384 unsigned idx1) { 385 llvm::Value *Idxs[] = { 386 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0), 387 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1) 388 }; 389 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2); 390} 391 392/* *** CGObjCMac Public Interface *** */ 393 394CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) 395 : CGM(cgm), 396 ObjCTypes(cgm), 397 ObjCABI(1) 398{ 399 // FIXME: How does this get set in GCC? And what does it even mean? 400 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy)) 401 ObjCABI = 2; 402 403 EmitImageInfo(); 404} 405 406/// GetClass - Return a reference to the class for the given interface 407/// decl. 408llvm::Value *CGObjCMac::GetClass(llvm::IRBuilder<> &Builder, 409 const ObjCInterfaceDecl *ID) { 410 return EmitClassRef(Builder, ID); 411} 412 413/// GetSelector - Return the pointer to the unique'd string for this selector. 414llvm::Value *CGObjCMac::GetSelector(llvm::IRBuilder<> &Builder, Selector Sel) { 415 return EmitSelector(Builder, Sel); 416} 417 418/// Generate a constant CFString object. 419/* 420 struct __builtin_CFString { 421 const int *isa; // point to __CFConstantStringClassReference 422 int flags; 423 const char *str; 424 long length; 425 }; 426*/ 427 428llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) { 429 return CGM.GetAddrOfConstantCFString(String); 430} 431 432/// Generates a message send where the super is the receiver. This is 433/// a message send to self with special delivery semantics indicating 434/// which class's method should be called. 435CodeGen::RValue 436CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 437 QualType ResultType, 438 Selector Sel, 439 const ObjCInterfaceDecl *Class, 440 llvm::Value *Receiver, 441 bool IsClassMessage, 442 const CodeGen::CallArgList &CallArgs) { 443 // Create and init a super structure; this is a (receiver, class) 444 // pair we will pass to objc_msgSendSuper. 445 llvm::Value *ObjCSuper = 446 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super"); 447 llvm::Value *ReceiverAsObject = 448 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); 449 CGF.Builder.CreateStore(ReceiverAsObject, 450 CGF.Builder.CreateStructGEP(ObjCSuper, 0)); 451 452 // If this is a class message the metaclass is passed as the target. 453 llvm::Value *Target; 454 if (IsClassMessage) { 455 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class); 456 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1); 457 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr); 458 Target = Super; 459 } else { 460 Target = EmitClassRef(CGF.Builder, Class->getSuperClass()); 461 } 462 // FIXME: We shouldn't need to do this cast, rectify the ASTContext 463 // and ObjCTypes types. 464 const llvm::Type *ClassTy = 465 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); 466 Target = CGF.Builder.CreateBitCast(Target, ClassTy); 467 CGF.Builder.CreateStore(Target, 468 CGF.Builder.CreateStructGEP(ObjCSuper, 1)); 469 470 return EmitMessageSend(CGF, ResultType, Sel, 471 ObjCSuper, ObjCTypes.SuperPtrCTy, 472 true, CallArgs); 473} 474 475/// Generate code for a message send expression. 476CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 477 QualType ResultType, 478 Selector Sel, 479 llvm::Value *Receiver, 480 bool IsClassMessage, 481 const CallArgList &CallArgs) { 482 llvm::Value *Arg0 = 483 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp"); 484 return EmitMessageSend(CGF, ResultType, Sel, 485 Arg0, CGF.getContext().getObjCIdType(), 486 false, CallArgs); 487} 488 489CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, 490 QualType ResultType, 491 Selector Sel, 492 llvm::Value *Arg0, 493 QualType Arg0Ty, 494 bool IsSuper, 495 const CallArgList &CallArgs) { 496 CallArgList ActualArgs; 497 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty)); 498 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder, 499 Sel)), 500 CGF.getContext().getObjCSelType())); 501 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 502 503 // FIXME: This is a hack, we are implicitly coordinating with 504 // EmitCall, which will move the return type to the first parameter 505 // and set the structure return flag. See getMessageSendFn(). 506 507 const llvm::Type *ReturnTy = CGM.getTypes().ConvertType(ResultType); 508 return CGF.EmitCall(ObjCTypes.getMessageSendFn(IsSuper, ReturnTy), 509 ResultType, ActualArgs); 510} 511 512llvm::Value *CGObjCMac::GenerateProtocolRef(llvm::IRBuilder<> &Builder, 513 const ObjCProtocolDecl *PD) { 514 // FIXME: I don't understand why gcc generates this, or where it is 515 // resolved. Investigate. Its also wasteful to look this up over and 516 // over. 517 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 518 519 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD), 520 ObjCTypes.ExternalProtocolPtrTy); 521} 522 523/* 524 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions 525 struct _objc_protocol { 526 struct _objc_protocol_extension *isa; 527 char *protocol_name; 528 struct _objc_protocol_list *protocol_list; 529 struct _objc__method_prototype_list *instance_methods; 530 struct _objc__method_prototype_list *class_methods 531 }; 532 533 See EmitProtocolExtension(). 534*/ 535void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) { 536 // FIXME: I don't understand why gcc generates this, or where it is 537 // resolved. Investigate. Its also wasteful to look this up over and 538 // over. 539 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 540 541 const char *ProtocolName = PD->getName(); 542 543 // Construct method lists. 544 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 545 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; 546 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(), 547 e = PD->instmeth_end(); i != e; ++i) { 548 ObjCMethodDecl *MD = *i; 549 llvm::Constant *C = GetMethodDescriptionConstant(MD); 550 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 551 OptInstanceMethods.push_back(C); 552 } else { 553 InstanceMethods.push_back(C); 554 } 555 } 556 557 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(), 558 e = PD->classmeth_end(); i != e; ++i) { 559 ObjCMethodDecl *MD = *i; 560 llvm::Constant *C = GetMethodDescriptionConstant(MD); 561 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 562 OptClassMethods.push_back(C); 563 } else { 564 ClassMethods.push_back(C); 565 } 566 } 567 568 std::vector<llvm::Constant*> Values(5); 569 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods); 570 Values[1] = GetClassName(PD->getIdentifier()); 571 Values[2] = 572 EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(), 573 PD->protocol_begin(), 574 PD->protocol_end()); 575 Values[3] = 576 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_") 577 + PD->getName(), 578 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 579 InstanceMethods); 580 Values[4] = 581 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_") 582 + PD->getName(), 583 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 584 ClassMethods); 585 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 586 Values); 587 588 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 589 if (Entry) { 590 // Already created, just update the initializer 591 Entry->setInitializer(Init); 592 } else { 593 Entry = 594 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, 595 llvm::GlobalValue::InternalLinkage, 596 Init, 597 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName, 598 &CGM.getModule()); 599 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 600 UsedGlobals.push_back(Entry); 601 // FIXME: Is this necessary? Why only for protocol? 602 Entry->setAlignment(4); 603 } 604} 605 606llvm::GlobalVariable *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) { 607 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 608 609 if (!Entry) { 610 std::vector<llvm::Constant*> Values(5); 611 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 612 Values[1] = GetClassName(PD->getIdentifier()); 613 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 614 Values[3] = Values[4] = 615 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 616 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 617 Values); 618 619 Entry = 620 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, 621 llvm::GlobalValue::InternalLinkage, 622 Init, 623 std::string("\01L_OBJC_PROTOCOL_")+PD->getName(), 624 &CGM.getModule()); 625 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 626 UsedGlobals.push_back(Entry); 627 // FIXME: Is this necessary? Why only for protocol? 628 Entry->setAlignment(4); 629 } 630 631 return Entry; 632} 633 634/* 635 struct _objc_protocol_extension { 636 uint32_t size; 637 struct objc_method_description_list *optional_instance_methods; 638 struct objc_method_description_list *optional_class_methods; 639 struct objc_property_list *instance_properties; 640 }; 641*/ 642llvm::Constant * 643CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD, 644 const ConstantVector &OptInstanceMethods, 645 const ConstantVector &OptClassMethods) { 646 uint64_t Size = 647 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy); 648 std::vector<llvm::Constant*> Values(4); 649 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 650 Values[1] = 651 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_") 652 + PD->getName(), 653 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 654 OptInstanceMethods); 655 Values[2] = 656 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_") 657 + PD->getName(), 658 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 659 OptClassMethods); 660 Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") + 661 PD->getName(), 662 0, 663 PD->classprop_begin(), 664 PD->classprop_end()); 665 666 // Return null if no extension bits are used. 667 if (Values[1]->isNullValue() && Values[2]->isNullValue() && 668 Values[3]->isNullValue()) 669 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 670 671 llvm::Constant *Init = 672 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values); 673 llvm::GlobalVariable *GV = 674 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false, 675 llvm::GlobalValue::InternalLinkage, 676 Init, 677 (std::string("\01L_OBJC_PROTOCOLEXT_") + 678 PD->getName()), 679 &CGM.getModule()); 680 // No special section, but goes in llvm.used 681 UsedGlobals.push_back(GV); 682 683 return GV; 684} 685 686/* 687 struct objc_protocol_list { 688 struct objc_protocol_list *next; 689 long count; 690 Protocol *list[]; 691 }; 692*/ 693llvm::Constant * 694CGObjCMac::EmitProtocolList(const std::string &Name, 695 ObjCProtocolDecl::protocol_iterator begin, 696 ObjCProtocolDecl::protocol_iterator end) { 697 std::vector<llvm::Constant*> ProtocolRefs; 698 699 for (; begin != end; ++begin) 700 ProtocolRefs.push_back(GetProtocolRef(*begin)); 701 702 // Just return null for empty protocol lists 703 if (ProtocolRefs.empty()) 704 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 705 706 // This list is null terminated. 707 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy)); 708 709 std::vector<llvm::Constant*> Values(3); 710 // This field is only used by the runtime. 711 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 712 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); 713 Values[2] = 714 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy, 715 ProtocolRefs.size()), 716 ProtocolRefs); 717 718 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 719 llvm::GlobalVariable *GV = 720 new llvm::GlobalVariable(Init->getType(), false, 721 llvm::GlobalValue::InternalLinkage, 722 Init, 723 Name, 724 &CGM.getModule()); 725 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip"); 726 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy); 727} 728 729/* 730 struct _objc_property { 731 const char * const name; 732 const char * const attributes; 733 }; 734 735 struct _objc_property_list { 736 uint32_t entsize; // sizeof (struct _objc_property) 737 uint32_t prop_count; 738 struct _objc_property[prop_count]; 739 }; 740*/ 741llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name, 742 const Decl *Container, 743 ObjCPropertyDecl * const *begin, 744 ObjCPropertyDecl * const *end) { 745 std::vector<llvm::Constant*> Properties, Prop(2); 746 for (; begin != end; ++begin) { 747 const ObjCPropertyDecl *PD = *begin; 748 Prop[0] = GetPropertyName(PD->getIdentifier()); 749 Prop[1] = GetPropertyTypeString(PD, Container); 750 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, 751 Prop)); 752 } 753 754 // Return null for empty list. 755 if (Properties.empty()) 756 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 757 758 unsigned PropertySize = 759 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy); 760 std::vector<llvm::Constant*> Values(3); 761 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize); 762 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size()); 763 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy, 764 Properties.size()); 765 Values[2] = llvm::ConstantArray::get(AT, Properties); 766 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 767 768 llvm::GlobalVariable *GV = 769 new llvm::GlobalVariable(Init->getType(), false, 770 llvm::GlobalValue::InternalLinkage, 771 Init, 772 Name, 773 &CGM.getModule()); 774 // No special section on property lists? 775 UsedGlobals.push_back(GV); 776 return llvm::ConstantExpr::getBitCast(GV, 777 ObjCTypes.PropertyListPtrTy); 778 779} 780 781/* 782 struct objc_method_description_list { 783 int count; 784 struct objc_method_description list[]; 785 }; 786*/ 787llvm::Constant * 788CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { 789 std::vector<llvm::Constant*> Desc(2); 790 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 791 ObjCTypes.SelectorPtrTy); 792 Desc[1] = GetMethodVarType(MD); 793 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy, 794 Desc); 795} 796 797llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name, 798 const char *Section, 799 const ConstantVector &Methods) { 800 // Return null for empty list. 801 if (Methods.empty()) 802 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 803 804 std::vector<llvm::Constant*> Values(2); 805 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 806 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy, 807 Methods.size()); 808 Values[1] = llvm::ConstantArray::get(AT, Methods); 809 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 810 811 llvm::GlobalVariable *GV = 812 new llvm::GlobalVariable(Init->getType(), false, 813 llvm::GlobalValue::InternalLinkage, 814 Init, Name, &CGM.getModule()); 815 GV->setSection(Section); 816 UsedGlobals.push_back(GV); 817 return llvm::ConstantExpr::getBitCast(GV, 818 ObjCTypes.MethodDescriptionListPtrTy); 819} 820 821/* 822 struct _objc_category { 823 char *category_name; 824 char *class_name; 825 struct _objc_method_list *instance_methods; 826 struct _objc_method_list *class_methods; 827 struct _objc_protocol_list *protocols; 828 uint32_t size; // <rdar://4585769> 829 struct _objc_property_list *instance_properties; 830 }; 831 */ 832void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 833 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy); 834 835 // FIXME: This is poor design, the OCD should have a pointer to the 836 // category decl. Additionally, note that Category can be null for 837 // the @implementation w/o an @interface case. Sema should just 838 // create one for us as it does for @implementation so everyone else 839 // can live life under a clear blue sky. 840 const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); 841 const ObjCCategoryDecl *Category = 842 Interface->FindCategoryDeclaration(OCD->getIdentifier()); 843 std::string ExtName(std::string(Interface->getName()) + 844 "_" + 845 OCD->getName()); 846 847 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 848 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(), 849 e = OCD->instmeth_end(); i != e; ++i) { 850 // Instance methods should always be defined. 851 InstanceMethods.push_back(GetMethodConstant(*i)); 852 } 853 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(), 854 e = OCD->classmeth_end(); i != e; ++i) { 855 // Class methods should always be defined. 856 ClassMethods.push_back(GetMethodConstant(*i)); 857 } 858 859 std::vector<llvm::Constant*> Values(7); 860 Values[0] = GetClassName(OCD->getIdentifier()); 861 Values[1] = GetClassName(Interface->getIdentifier()); 862 Values[2] = 863 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") + 864 ExtName, 865 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 866 InstanceMethods); 867 Values[3] = 868 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName, 869 "__OBJC,__cat_class_meth,regular,no_dead_strip", 870 ClassMethods); 871 if (Category) { 872 Values[4] = 873 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName, 874 Category->protocol_begin(), 875 Category->protocol_end()); 876 } else { 877 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 878 } 879 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 880 881 // If there is no category @interface then there can be no properties. 882 if (Category) { 883 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName, 884 OCD, 885 Category->classprop_begin(), 886 Category->classprop_end()); 887 } else { 888 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 889 } 890 891 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy, 892 Values); 893 894 llvm::GlobalVariable *GV = 895 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false, 896 llvm::GlobalValue::InternalLinkage, 897 Init, 898 std::string("\01L_OBJC_CATEGORY_")+ExtName, 899 &CGM.getModule()); 900 GV->setSection("__OBJC,__category,regular,no_dead_strip"); 901 UsedGlobals.push_back(GV); 902 DefinedCategories.push_back(GV); 903} 904 905// FIXME: Get from somewhere? 906enum ClassFlags { 907 eClassFlags_Factory = 0x00001, 908 eClassFlags_Meta = 0x00002, 909 // <rdr://5142207> 910 eClassFlags_HasCXXStructors = 0x02000, 911 eClassFlags_Hidden = 0x20000, 912 eClassFlags_ABI2_Hidden = 0x00010, 913 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634> 914}; 915 916// <rdr://5142207&4705298&4843145> 917static bool IsClassHidden(const ObjCInterfaceDecl *ID) { 918 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) { 919 // FIXME: Support -fvisibility 920 switch (attr->getVisibility()) { 921 default: 922 assert(0 && "Unknown visibility"); 923 return false; 924 case VisibilityAttr::DefaultVisibility: 925 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here? 926 return false; 927 case VisibilityAttr::HiddenVisibility: 928 return true; 929 } 930 } else { 931 return false; // FIXME: Support -fvisibility 932 } 933} 934 935/* 936 struct _objc_class { 937 Class isa; 938 Class super_class; 939 const char *name; 940 long version; 941 long info; 942 long instance_size; 943 struct _objc_ivar_list *ivars; 944 struct _objc_method_list *methods; 945 struct _objc_cache *cache; 946 struct _objc_protocol_list *protocols; 947 // Objective-C 1.0 extensions (<rdr://4585769>) 948 const char *ivar_layout; 949 struct _objc_class_ext *ext; 950 }; 951 952 See EmitClassExtension(); 953 */ 954void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) { 955 DefinedSymbols.insert(ID->getIdentifier()); 956 957 const char *ClassName = ID->getName(); 958 // FIXME: Gross 959 ObjCInterfaceDecl *Interface = 960 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); 961 llvm::Constant *Protocols = 962 EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(), 963 Interface->protocol_begin(), 964 Interface->protocol_end()); 965 const llvm::Type *InterfaceTy = 966 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface)); 967 unsigned Flags = eClassFlags_Factory; 968 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy); 969 970 // FIXME: Set CXX-structors flag. 971 if (IsClassHidden(ID->getClassInterface())) 972 Flags |= eClassFlags_Hidden; 973 974 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 975 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(), 976 e = ID->instmeth_end(); i != e; ++i) { 977 // Instance methods should always be defined. 978 InstanceMethods.push_back(GetMethodConstant(*i)); 979 } 980 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(), 981 e = ID->classmeth_end(); i != e; ++i) { 982 // Class methods should always be defined. 983 ClassMethods.push_back(GetMethodConstant(*i)); 984 } 985 986 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(), 987 e = ID->propimpl_end(); i != e; ++i) { 988 ObjCPropertyImplDecl *PID = *i; 989 990 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 991 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 992 993 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) 994 if (llvm::Constant *C = GetMethodConstant(MD)) 995 InstanceMethods.push_back(C); 996 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) 997 if (llvm::Constant *C = GetMethodConstant(MD)) 998 InstanceMethods.push_back(C); 999 } 1000 } 1001 1002 std::vector<llvm::Constant*> Values(12); 1003 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods); 1004 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) { 1005 // Record a reference to the super class. 1006 LazySymbols.insert(Super->getIdentifier()); 1007 1008 Values[ 1] = 1009 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), 1010 ObjCTypes.ClassPtrTy); 1011 } else { 1012 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 1013 } 1014 Values[ 2] = GetClassName(ID->getIdentifier()); 1015 // Version is always 0. 1016 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1017 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 1018 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1019 Values[ 6] = EmitIvarList(ID, false, InterfaceTy); 1020 Values[ 7] = 1021 EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(), 1022 "__OBJC,__inst_meth,regular,no_dead_strip", 1023 InstanceMethods); 1024 // cache is always NULL. 1025 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 1026 Values[ 9] = Protocols; 1027 // FIXME: Set ivar_layout 1028 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1029 Values[11] = EmitClassExtension(ID); 1030 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 1031 Values); 1032 1033 llvm::GlobalVariable *GV = 1034 new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1035 llvm::GlobalValue::InternalLinkage, 1036 Init, 1037 std::string("\01L_OBJC_CLASS_")+ClassName, 1038 &CGM.getModule()); 1039 GV->setSection("__OBJC,__class,regular,no_dead_strip"); 1040 UsedGlobals.push_back(GV); 1041 // FIXME: Why? 1042 GV->setAlignment(32); 1043 DefinedClasses.push_back(GV); 1044} 1045 1046llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID, 1047 llvm::Constant *Protocols, 1048 const llvm::Type *InterfaceTy, 1049 const ConstantVector &Methods) { 1050 const char *ClassName = ID->getName(); 1051 unsigned Flags = eClassFlags_Meta; 1052 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy); 1053 1054 if (IsClassHidden(ID->getClassInterface())) 1055 Flags |= eClassFlags_Hidden; 1056 1057 std::vector<llvm::Constant*> Values(12); 1058 // The isa for the metaclass is the root of the hierarchy. 1059 const ObjCInterfaceDecl *Root = ID->getClassInterface(); 1060 while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) 1061 Root = Super; 1062 Values[ 0] = 1063 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()), 1064 ObjCTypes.ClassPtrTy); 1065 // The super class for the metaclass is emitted as the name of the 1066 // super class. The runtime fixes this up to point to the 1067 // *metaclass* for the super class. 1068 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) { 1069 Values[ 1] = 1070 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), 1071 ObjCTypes.ClassPtrTy); 1072 } else { 1073 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 1074 } 1075 Values[ 2] = GetClassName(ID->getIdentifier()); 1076 // Version is always 0. 1077 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1078 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 1079 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1080 Values[ 6] = EmitIvarList(ID, true, InterfaceTy); 1081 Values[ 7] = 1082 EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(), 1083 "__OBJC,__inst_meth,regular,no_dead_strip", 1084 Methods); 1085 // cache is always NULL. 1086 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 1087 Values[ 9] = Protocols; 1088 // ivar_layout for metaclass is always NULL. 1089 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1090 // The class extension is always unused for metaclasses. 1091 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 1092 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 1093 Values); 1094 1095 std::string Name("\01L_OBJC_METACLASS_"); 1096 Name += ClassName; 1097 1098 // Check for a forward reference. 1099 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); 1100 if (GV) { 1101 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 1102 "Forward metaclass reference has incorrect type."); 1103 GV->setLinkage(llvm::GlobalValue::InternalLinkage); 1104 GV->setInitializer(Init); 1105 } else { 1106 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1107 llvm::GlobalValue::InternalLinkage, 1108 Init, Name, 1109 &CGM.getModule()); 1110 } 1111 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip"); 1112 UsedGlobals.push_back(GV); 1113 // FIXME: Why? 1114 GV->setAlignment(32); 1115 1116 return GV; 1117} 1118 1119llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) { 1120 std::string Name("\01L_OBJC_METACLASS_"); 1121 Name += ID->getName(); 1122 1123 // FIXME: Should we look these up somewhere other than the 1124 // module. Its a bit silly since we only generate these while 1125 // processing an implementation, so exactly one pointer would work 1126 // if know when we entered/exitted an implementation block. 1127 1128 // Check for an existing forward reference. 1129 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) { 1130 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 1131 "Forward metaclass reference has incorrect type."); 1132 return GV; 1133 } else { 1134 // Generate as an external reference to keep a consistent 1135 // module. This will be patched up when we emit the metaclass. 1136 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1137 llvm::GlobalValue::ExternalLinkage, 1138 0, 1139 Name, 1140 &CGM.getModule()); 1141 } 1142} 1143 1144/* 1145 struct objc_class_ext { 1146 uint32_t size; 1147 const char *weak_ivar_layout; 1148 struct _objc_property_list *properties; 1149 }; 1150*/ 1151llvm::Constant * 1152CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) { 1153 uint64_t Size = 1154 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy); 1155 1156 std::vector<llvm::Constant*> Values(3); 1157 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 1158 // FIXME: Output weak_ivar_layout string. 1159 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1160 Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + 1161 ID->getName(), 1162 ID, 1163 ID->getClassInterface()->classprop_begin(), 1164 ID->getClassInterface()->classprop_end()); 1165 1166 // Return null if no extension bits are used. 1167 if (Values[1]->isNullValue() && Values[2]->isNullValue()) 1168 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 1169 1170 llvm::Constant *Init = 1171 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values); 1172 llvm::GlobalVariable *GV = 1173 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false, 1174 llvm::GlobalValue::InternalLinkage, 1175 Init, 1176 (std::string("\01L_OBJC_CLASSEXT_") + 1177 ID->getName()), 1178 &CGM.getModule()); 1179 // No special section, but goes in llvm.used 1180 UsedGlobals.push_back(GV); 1181 1182 return GV; 1183} 1184 1185/* 1186 struct objc_ivar { 1187 char *ivar_name; 1188 char *ivar_type; 1189 int ivar_offset; 1190 }; 1191 1192 struct objc_ivar_list { 1193 int ivar_count; 1194 struct objc_ivar list[count]; 1195 }; 1196 */ 1197llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID, 1198 bool ForClass, 1199 const llvm::Type *InterfaceTy) { 1200 std::vector<llvm::Constant*> Ivars, Ivar(3); 1201 1202 // When emitting the root class GCC emits ivar entries for the 1203 // actual class structure. It is not clear if we need to follow this 1204 // behavior; for now lets try and get away with not doing it. If so, 1205 // the cleanest solution would be to make up an ObjCInterfaceDecl 1206 // for the class. 1207 if (ForClass) 1208 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 1209 1210 const llvm::StructLayout *Layout = 1211 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy)); 1212 for (ObjCInterfaceDecl::ivar_iterator 1213 i = ID->getClassInterface()->ivar_begin(), 1214 e = ID->getClassInterface()->ivar_end(); i != e; ++i) { 1215 ObjCIvarDecl *V = *i; 1216 unsigned Offset = 1217 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V)); 1218 std::string TypeStr; 1219 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes; 1220 Ivar[0] = GetMethodVarName(V->getIdentifier()); 1221 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, 1222 EncodingRecordTypes); 1223 Ivar[1] = GetMethodVarType(TypeStr); 1224 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset); 1225 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, 1226 Ivar)); 1227 } 1228 1229 // Return null for empty list. 1230 if (Ivars.empty()) 1231 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 1232 1233 std::vector<llvm::Constant*> Values(2); 1234 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); 1235 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy, 1236 Ivars.size()); 1237 Values[1] = llvm::ConstantArray::get(AT, Ivars); 1238 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1239 1240 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" : 1241 "\01L_OBJC_INSTANCE_VARIABLES_"); 1242 llvm::GlobalVariable *GV = 1243 new llvm::GlobalVariable(Init->getType(), false, 1244 llvm::GlobalValue::InternalLinkage, 1245 Init, 1246 std::string(Prefix) + ID->getName(), 1247 &CGM.getModule()); 1248 if (ForClass) { 1249 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip"); 1250 // FIXME: Why is this only here? 1251 GV->setAlignment(32); 1252 } else { 1253 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip"); 1254 } 1255 UsedGlobals.push_back(GV); 1256 return llvm::ConstantExpr::getBitCast(GV, 1257 ObjCTypes.IvarListPtrTy); 1258} 1259 1260/* 1261 struct objc_method { 1262 SEL method_name; 1263 char *method_types; 1264 void *method; 1265 }; 1266 1267 struct objc_method_list { 1268 struct objc_method_list *obsolete; 1269 int count; 1270 struct objc_method methods_list[count]; 1271 }; 1272*/ 1273 1274/// GetMethodConstant - Return a struct objc_method constant for the 1275/// given method if it has been defined. The result is null if the 1276/// method has not been defined. The return value has type MethodPtrTy. 1277llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) { 1278 // FIXME: Use DenseMap::lookup 1279 llvm::Function *Fn = MethodDefinitions[MD]; 1280 if (!Fn) 1281 return 0; 1282 1283 std::vector<llvm::Constant*> Method(3); 1284 Method[0] = 1285 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 1286 ObjCTypes.SelectorPtrTy); 1287 Method[1] = GetMethodVarType(MD); 1288 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy); 1289 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); 1290} 1291 1292llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name, 1293 const char *Section, 1294 const ConstantVector &Methods) { 1295 // Return null for empty list. 1296 if (Methods.empty()) 1297 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy); 1298 1299 std::vector<llvm::Constant*> Values(3); 1300 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1301 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 1302 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, 1303 Methods.size()); 1304 Values[2] = llvm::ConstantArray::get(AT, Methods); 1305 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1306 1307 llvm::GlobalVariable *GV = 1308 new llvm::GlobalVariable(Init->getType(), false, 1309 llvm::GlobalValue::InternalLinkage, 1310 Init, 1311 Name, 1312 &CGM.getModule()); 1313 GV->setSection(Section); 1314 UsedGlobals.push_back(GV); 1315 return llvm::ConstantExpr::getBitCast(GV, 1316 ObjCTypes.MethodListPtrTy); 1317} 1318 1319llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) { 1320 const llvm::Type *ReturnTy = 1321 CGM.getTypes().ConvertReturnType(OMD->getResultType()); 1322 const llvm::Type *SelfTy = 1323 CGM.getTypes().ConvertType(OMD->getSelfDecl()->getType()); 1324 1325 std::vector<const llvm::Type*> ArgTys; 1326 ArgTys.reserve(1 + 2 + OMD->param_size()); 1327 1328 // FIXME: This is not something we should have to be dealing with 1329 // here. 1330 bool useStructRet = 1331 CodeGen::CodeGenFunction::hasAggregateLLVMType(OMD->getResultType()); 1332 if (useStructRet) { 1333 ArgTys.push_back(llvm::PointerType::getUnqual(ReturnTy)); 1334 ReturnTy = llvm::Type::VoidTy; 1335 } 1336 1337 // Implicit arguments 1338 ArgTys.push_back(SelfTy); 1339 ArgTys.push_back(ObjCTypes.SelectorPtrTy); 1340 1341 for (ObjCMethodDecl::param_const_iterator 1342 i = OMD->param_begin(), e = OMD->param_end(); 1343 i != e; ++i) { 1344 const llvm::Type *Ty = CGM.getTypes().ConvertType((*i)->getType()); 1345 if (Ty->isSingleValueType()) { 1346 ArgTys.push_back(Ty); 1347 } else { 1348 ArgTys.push_back(llvm::PointerType::getUnqual(Ty)); 1349 } 1350 } 1351 1352 std::string Name; 1353 GetNameForMethod(OMD, Name); 1354 1355 llvm::Function *Method = 1356 llvm::Function::Create(llvm::FunctionType::get(ReturnTy, 1357 ArgTys, 1358 OMD->isVariadic()), 1359 llvm::GlobalValue::InternalLinkage, 1360 Name, 1361 &CGM.getModule()); 1362 MethodDefinitions.insert(std::make_pair(OMD, Method)); 1363 1364 unsigned Offset = 3; // Return plus self and selector implicit args. 1365 if (useStructRet) { 1366 Method->addParamAttr(1, llvm::ParamAttr::StructRet); 1367 ++Offset; 1368 } 1369 1370 // FIXME: This is horrible, we need to be reusing the machinery in 1371 // CodeGenModule.cpp (SetFunctionAttributes). 1372 for (ObjCMethodDecl::param_const_iterator 1373 i = OMD->param_begin(), e = OMD->param_end(); 1374 i != e; ++i, ++Offset) { 1375 const llvm::Type *Ty = CGM.getTypes().ConvertType((*i)->getType()); 1376 if (!Ty->isSingleValueType()) 1377 Method->addParamAttr(Offset, llvm::ParamAttr::ByVal); 1378 } 1379 1380 return Method; 1381} 1382 1383llvm::Function *CGObjCMac::ModuleInitFunction() { 1384 // Abuse this interface function as a place to finalize. 1385 FinishModule(); 1386 1387 return NULL; 1388} 1389 1390llvm::Function *CGObjCMac::EnumerationMutationFunction() 1391{ 1392 return ObjCTypes.EnumerationMutationFn; 1393} 1394 1395/* *** Private Interface *** */ 1396 1397/// EmitImageInfo - Emit the image info marker used to encode some module 1398/// level information. 1399/// 1400/// See: <rdr://4810609&4810587&4810587> 1401/// struct IMAGE_INFO { 1402/// unsigned version; 1403/// unsigned flags; 1404/// }; 1405enum ImageInfoFlags { 1406 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies 1407 eImageInfo_GarbageCollected = (1 << 1), 1408 eImageInfo_GCOnly = (1 << 2) 1409}; 1410 1411void CGObjCMac::EmitImageInfo() { 1412 unsigned version = 0; // Version is unused? 1413 unsigned flags = 0; 1414 1415 // FIXME: Fix and continue? 1416 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) 1417 flags |= eImageInfo_GarbageCollected; 1418 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) 1419 flags |= eImageInfo_GCOnly; 1420 1421 // Emitted as int[2]; 1422 llvm::Constant *values[2] = { 1423 llvm::ConstantInt::get(llvm::Type::Int32Ty, version), 1424 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags) 1425 }; 1426 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2); 1427 llvm::GlobalVariable *GV = 1428 new llvm::GlobalVariable(AT, true, 1429 llvm::GlobalValue::InternalLinkage, 1430 llvm::ConstantArray::get(AT, values, 2), 1431 "\01L_OBJC_IMAGE_INFO", 1432 &CGM.getModule()); 1433 1434 if (ObjCABI == 1) { 1435 GV->setSection("__OBJC, __image_info,regular"); 1436 } else { 1437 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip"); 1438 } 1439 1440 UsedGlobals.push_back(GV); 1441} 1442 1443 1444// struct objc_module { 1445// unsigned long version; 1446// unsigned long size; 1447// const char *name; 1448// Symtab symtab; 1449// }; 1450 1451// FIXME: Get from somewhere 1452static const int ModuleVersion = 7; 1453 1454void CGObjCMac::EmitModuleInfo() { 1455 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy); 1456 1457 std::vector<llvm::Constant*> Values(4); 1458 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion); 1459 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1460 // This used to be the filename, now it is unused. <rdr://4327263> 1461 Values[2] = GetClassName(&CGM.getContext().Idents.get("")); 1462 Values[3] = EmitModuleSymbols(); 1463 1464 llvm::GlobalVariable *GV = 1465 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false, 1466 llvm::GlobalValue::InternalLinkage, 1467 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, 1468 Values), 1469 "\01L_OBJC_MODULES", 1470 &CGM.getModule()); 1471 GV->setSection("__OBJC,__module_info,regular,no_dead_strip"); 1472 UsedGlobals.push_back(GV); 1473} 1474 1475llvm::Constant *CGObjCMac::EmitModuleSymbols() { 1476 unsigned NumClasses = DefinedClasses.size(); 1477 unsigned NumCategories = DefinedCategories.size(); 1478 1479 // Return null if no symbols were defined. 1480 if (!NumClasses && !NumCategories) 1481 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy); 1482 1483 std::vector<llvm::Constant*> Values(5); 1484 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1485 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy); 1486 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses); 1487 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories); 1488 1489 // The runtime expects exactly the list of defined classes followed 1490 // by the list of defined categories, in a single array. 1491 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories); 1492 for (unsigned i=0; i<NumClasses; i++) 1493 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], 1494 ObjCTypes.Int8PtrTy); 1495 for (unsigned i=0; i<NumCategories; i++) 1496 Symbols[NumClasses + i] = 1497 llvm::ConstantExpr::getBitCast(DefinedCategories[i], 1498 ObjCTypes.Int8PtrTy); 1499 1500 Values[4] = 1501 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 1502 NumClasses + NumCategories), 1503 Symbols); 1504 1505 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1506 1507 llvm::GlobalVariable *GV = 1508 new llvm::GlobalVariable(Init->getType(), false, 1509 llvm::GlobalValue::InternalLinkage, 1510 Init, 1511 "\01L_OBJC_SYMBOLS", 1512 &CGM.getModule()); 1513 GV->setSection("__OBJC,__symbols,regular,no_dead_strip"); 1514 UsedGlobals.push_back(GV); 1515 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy); 1516} 1517 1518llvm::Value *CGObjCMac::EmitClassRef(llvm::IRBuilder<> &Builder, 1519 const ObjCInterfaceDecl *ID) { 1520 LazySymbols.insert(ID->getIdentifier()); 1521 1522 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()]; 1523 1524 if (!Entry) { 1525 llvm::Constant *Casted = 1526 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()), 1527 ObjCTypes.ClassPtrTy); 1528 Entry = 1529 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false, 1530 llvm::GlobalValue::InternalLinkage, 1531 Casted, "\01L_OBJC_CLASS_REFERENCES_", 1532 &CGM.getModule()); 1533 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip"); 1534 UsedGlobals.push_back(Entry); 1535 } 1536 1537 return Builder.CreateLoad(Entry, false, "tmp"); 1538} 1539 1540llvm::Value *CGObjCMac::EmitSelector(llvm::IRBuilder<> &Builder, Selector Sel) { 1541 llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; 1542 1543 if (!Entry) { 1544 llvm::Constant *Casted = 1545 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), 1546 ObjCTypes.SelectorPtrTy); 1547 Entry = 1548 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false, 1549 llvm::GlobalValue::InternalLinkage, 1550 Casted, "\01L_OBJC_SELECTOR_REFERENCES_", 1551 &CGM.getModule()); 1552 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip"); 1553 UsedGlobals.push_back(Entry); 1554 } 1555 1556 return Builder.CreateLoad(Entry, false, "tmp"); 1557} 1558 1559llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) { 1560 llvm::GlobalVariable *&Entry = ClassNames[Ident]; 1561 1562 if (!Entry) { 1563 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName()); 1564 Entry = 1565 new llvm::GlobalVariable(C->getType(), false, 1566 llvm::GlobalValue::InternalLinkage, 1567 C, "\01L_OBJC_CLASS_NAME_", 1568 &CGM.getModule()); 1569 Entry->setSection("__TEXT,__cstring,cstring_literals"); 1570 UsedGlobals.push_back(Entry); 1571 } 1572 1573 return getConstantGEP(Entry, 0, 0); 1574} 1575 1576llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) { 1577 llvm::GlobalVariable *&Entry = MethodVarNames[Sel]; 1578 1579 if (!Entry) { 1580 llvm::Constant *C = llvm::ConstantArray::get(Sel.getName()); 1581 Entry = 1582 new llvm::GlobalVariable(C->getType(), false, 1583 llvm::GlobalValue::InternalLinkage, 1584 C, "\01L_OBJC_METH_VAR_NAME_", 1585 &CGM.getModule()); 1586 Entry->setSection("__TEXT,__cstring,cstring_literals"); 1587 UsedGlobals.push_back(Entry); 1588 } 1589 1590 return getConstantGEP(Entry, 0, 0); 1591} 1592 1593// FIXME: Merge into a single cstring creation function. 1594llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) { 1595 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID)); 1596} 1597 1598// FIXME: Merge into a single cstring creation function. 1599llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) { 1600 return GetMethodVarName(&CGM.getContext().Idents.get(Name)); 1601} 1602 1603llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) { 1604 llvm::GlobalVariable *&Entry = MethodVarTypes[Name]; 1605 1606 if (!Entry) { 1607 llvm::Constant *C = llvm::ConstantArray::get(Name); 1608 Entry = 1609 new llvm::GlobalVariable(C->getType(), false, 1610 llvm::GlobalValue::InternalLinkage, 1611 C, "\01L_OBJC_METH_VAR_TYPE_", 1612 &CGM.getModule()); 1613 Entry->setSection("__TEXT,__cstring,cstring_literals"); 1614 UsedGlobals.push_back(Entry); 1615 } 1616 1617 return getConstantGEP(Entry, 0, 0); 1618} 1619 1620// FIXME: Merge into a single cstring creation function. 1621llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) { 1622 std::string TypeStr; 1623 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D), 1624 TypeStr); 1625 return GetMethodVarType(TypeStr); 1626} 1627 1628// FIXME: Merge into a single cstring creation function. 1629llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) { 1630 llvm::GlobalVariable *&Entry = PropertyNames[Ident]; 1631 1632 if (!Entry) { 1633 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName()); 1634 Entry = 1635 new llvm::GlobalVariable(C->getType(), false, 1636 llvm::GlobalValue::InternalLinkage, 1637 C, "\01L_OBJC_PROP_NAME_ATTR_", 1638 &CGM.getModule()); 1639 Entry->setSection("__TEXT,__cstring,cstring_literals"); 1640 UsedGlobals.push_back(Entry); 1641 } 1642 1643 return getConstantGEP(Entry, 0, 0); 1644} 1645 1646// FIXME: Merge into a single cstring creation function. 1647// FIXME: This Decl should be more precise. 1648llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD, 1649 const Decl *Container) { 1650 std::string TypeStr; 1651 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr); 1652 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr)); 1653} 1654 1655void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D, 1656 std::string &NameOut) { 1657 // FIXME: Find the mangling GCC uses. 1658 std::stringstream s; 1659 s << (D->isInstance() ? "-" : "+"); 1660 s << "["; 1661 s << D->getClassInterface()->getName(); 1662 s << " "; 1663 s << D->getSelector().getName(); 1664 s << "]"; 1665 NameOut = s.str(); 1666} 1667 1668void CGObjCMac::FinishModule() { 1669 EmitModuleInfo(); 1670 1671 std::vector<llvm::Constant*> Used; 1672 1673 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(), 1674 e = UsedGlobals.end(); i != e; ++i) { 1675 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy)); 1676 } 1677 1678 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size()); 1679 llvm::GlobalValue *GV = 1680 new llvm::GlobalVariable(AT, false, 1681 llvm::GlobalValue::AppendingLinkage, 1682 llvm::ConstantArray::get(AT, Used), 1683 "llvm.used", 1684 &CGM.getModule()); 1685 1686 GV->setSection("llvm.metadata"); 1687 1688 // Add assembler directives to add lazy undefined symbol references 1689 // for classes which are referenced but not defined. This is 1690 // important for correct linker interaction. 1691 1692 // FIXME: Uh, this isn't particularly portable. 1693 std::stringstream s; 1694 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(), 1695 e = LazySymbols.end(); i != e; ++i) { 1696 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n"; 1697 } 1698 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(), 1699 e = DefinedSymbols.end(); i != e; ++i) { 1700 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n" 1701 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n"; 1702 } 1703 CGM.getModule().appendModuleInlineAsm(s.str()); 1704} 1705 1706/* *** */ 1707 1708ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) 1709 : CGM(cgm) 1710{ 1711 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 1712 ASTContext &Ctx = CGM.getContext(); 1713 1714 ShortTy = Types.ConvertType(Ctx.ShortTy); 1715 IntTy = Types.ConvertType(Ctx.IntTy); 1716 LongTy = Types.ConvertType(Ctx.LongTy); 1717 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 1718 1719 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType()); 1720 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType()); 1721 1722 // FIXME: It would be nice to unify this with the opaque type, so 1723 // that the IR comes out a bit cleaner. 1724 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType()); 1725 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T); 1726 1727 MethodDescriptionTy = 1728 llvm::StructType::get(SelectorPtrTy, 1729 Int8PtrTy, 1730 NULL); 1731 CGM.getModule().addTypeName("struct._objc_method_description", 1732 MethodDescriptionTy); 1733 1734 MethodDescriptionListTy = 1735 llvm::StructType::get(IntTy, 1736 llvm::ArrayType::get(MethodDescriptionTy, 0), 1737 NULL); 1738 CGM.getModule().addTypeName("struct._objc_method_description_list", 1739 MethodDescriptionListTy); 1740 MethodDescriptionListPtrTy = 1741 llvm::PointerType::getUnqual(MethodDescriptionListTy); 1742 1743 PropertyTy = llvm::StructType::get(Int8PtrTy, 1744 Int8PtrTy, 1745 NULL); 1746 CGM.getModule().addTypeName("struct._objc_property", 1747 PropertyTy); 1748 1749 PropertyListTy = llvm::StructType::get(IntTy, 1750 IntTy, 1751 llvm::ArrayType::get(PropertyTy, 0), 1752 NULL); 1753 CGM.getModule().addTypeName("struct._objc_property_list", 1754 PropertyListTy); 1755 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy); 1756 1757 // Protocol description structures 1758 1759 ProtocolExtensionTy = 1760 llvm::StructType::get(Types.ConvertType(Ctx.IntTy), 1761 llvm::PointerType::getUnqual(MethodDescriptionListTy), 1762 llvm::PointerType::getUnqual(MethodDescriptionListTy), 1763 PropertyListPtrTy, 1764 NULL); 1765 CGM.getModule().addTypeName("struct._objc_protocol_extension", 1766 ProtocolExtensionTy); 1767 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy); 1768 1769 // Handle recursive construction of Protocl and ProtocolList types 1770 1771 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get(); 1772 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); 1773 1774 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder), 1775 LongTy, 1776 llvm::ArrayType::get(ProtocolTyHolder, 0), 1777 NULL); 1778 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T); 1779 1780 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy), 1781 Int8PtrTy, 1782 llvm::PointerType::getUnqual(ProtocolListTyHolder), 1783 MethodDescriptionListPtrTy, 1784 MethodDescriptionListPtrTy, 1785 NULL); 1786 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T); 1787 1788 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get()); 1789 CGM.getModule().addTypeName("struct._objc_protocol_list", 1790 ProtocolListTy); 1791 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy); 1792 1793 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get()); 1794 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy); 1795 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy); 1796 1797 // Class description structures 1798 1799 IvarTy = llvm::StructType::get(Int8PtrTy, 1800 Int8PtrTy, 1801 IntTy, 1802 NULL); 1803 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy); 1804 1805 IvarListTy = llvm::OpaqueType::get(); 1806 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy); 1807 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy); 1808 1809 MethodTy = llvm::StructType::get(SelectorPtrTy, 1810 Int8PtrTy, 1811 Int8PtrTy, 1812 NULL); 1813 CGM.getModule().addTypeName("struct._objc_method", MethodTy); 1814 1815 MethodListTy = llvm::OpaqueType::get(); 1816 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy); 1817 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy); 1818 1819 CacheTy = llvm::OpaqueType::get(); 1820 CGM.getModule().addTypeName("struct._objc_cache", CacheTy); 1821 CachePtrTy = llvm::PointerType::getUnqual(CacheTy); 1822 1823 ClassExtensionTy = 1824 llvm::StructType::get(IntTy, 1825 Int8PtrTy, 1826 PropertyListPtrTy, 1827 NULL); 1828 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy); 1829 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy); 1830 1831 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); 1832 1833 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), 1834 llvm::PointerType::getUnqual(ClassTyHolder), 1835 Int8PtrTy, 1836 LongTy, 1837 LongTy, 1838 LongTy, 1839 IvarListPtrTy, 1840 MethodListPtrTy, 1841 CachePtrTy, 1842 ProtocolListPtrTy, 1843 Int8PtrTy, 1844 ClassExtensionPtrTy, 1845 NULL); 1846 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T); 1847 1848 ClassTy = cast<llvm::StructType>(ClassTyHolder.get()); 1849 CGM.getModule().addTypeName("struct._objc_class", ClassTy); 1850 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy); 1851 1852 CategoryTy = llvm::StructType::get(Int8PtrTy, 1853 Int8PtrTy, 1854 MethodListPtrTy, 1855 MethodListPtrTy, 1856 ProtocolListPtrTy, 1857 IntTy, 1858 PropertyListPtrTy, 1859 NULL); 1860 CGM.getModule().addTypeName("struct._objc_category", CategoryTy); 1861 1862 // I'm not sure I like this. The implicit coordination is a bit 1863 // gross. We should solve this in a reasonable fashion because this 1864 // is a pretty common task (match some runtime data structure with 1865 // an LLVM data structure). 1866 1867 // FIXME: This is leaked. 1868 // FIXME: Merge with rewriter code? 1869 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0, 1870 SourceLocation(), 1871 &Ctx.Idents.get("_objc_super")); 1872 FieldDecl *FieldDecls[2]; 1873 FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0, 1874 Ctx.getObjCIdType()); 1875 FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0, 1876 Ctx.getObjCClassType()); 1877 RD->defineBody(Ctx, FieldDecls, 2); 1878 1879 SuperCTy = Ctx.getTagDeclType(RD); 1880 SuperPtrCTy = Ctx.getPointerType(SuperCTy); 1881 1882 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy)); 1883 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy); 1884 1885 // Global metadata structures 1886 1887 SymtabTy = llvm::StructType::get(LongTy, 1888 SelectorPtrTy, 1889 ShortTy, 1890 ShortTy, 1891 llvm::ArrayType::get(Int8PtrTy, 0), 1892 NULL); 1893 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy); 1894 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy); 1895 1896 ModuleTy = 1897 llvm::StructType::get(LongTy, 1898 LongTy, 1899 Int8PtrTy, 1900 SymtabPtrTy, 1901 NULL); 1902 CGM.getModule().addTypeName("struct._objc_module", ModuleTy); 1903 1904 // Message send functions 1905 1906 std::vector<const llvm::Type*> Params; 1907 Params.push_back(ObjectPtrTy); 1908 Params.push_back(SelectorPtrTy); 1909 MessageSendFn = llvm::Function::Create(llvm::FunctionType::get(ObjectPtrTy, 1910 Params, 1911 true), 1912 llvm::Function::ExternalLinkage, 1913 "objc_msgSend", 1914 &CGM.getModule()); 1915 1916 Params.clear(); 1917 Params.push_back(Int8PtrTy); 1918 Params.push_back(ObjectPtrTy); 1919 Params.push_back(SelectorPtrTy); 1920 MessageSendStretFn = 1921 llvm::Function::Create(llvm::FunctionType::get(llvm::Type::VoidTy, 1922 Params, 1923 true), 1924 llvm::Function::ExternalLinkage, 1925 "objc_msgSend_stret", 1926 &CGM.getModule()); 1927 1928 Params.clear(); 1929 Params.push_back(SuperPtrTy); 1930 Params.push_back(SelectorPtrTy); 1931 MessageSendSuperFn = 1932 llvm::Function::Create(llvm::FunctionType::get(ObjectPtrTy, 1933 Params, 1934 true), 1935 llvm::Function::ExternalLinkage, 1936 "objc_msgSendSuper", 1937 &CGM.getModule()); 1938 1939 Params.clear(); 1940 Params.push_back(Int8PtrTy); 1941 Params.push_back(SuperPtrTy); 1942 Params.push_back(SelectorPtrTy); 1943 MessageSendSuperStretFn = 1944 llvm::Function::Create(llvm::FunctionType::get(llvm::Type::VoidTy, 1945 Params, 1946 true), 1947 llvm::Function::ExternalLinkage, 1948 "objc_msgSendSuper_stret", 1949 &CGM.getModule()); 1950 1951 // Enumeration mutation. 1952 1953 Params.clear(); 1954 Params.push_back(ObjectPtrTy); 1955 EnumerationMutationFn = 1956 llvm::Function::Create(llvm::FunctionType::get(llvm::Type::VoidTy, 1957 Params, 1958 false), 1959 llvm::Function::ExternalLinkage, 1960 "objc_enumerationMutation", 1961 &CGM.getModule()); 1962} 1963 1964ObjCTypesHelper::~ObjCTypesHelper() { 1965} 1966 1967llvm::Value *ObjCTypesHelper::getMessageSendFn(bool IsSuper, 1968 const llvm::Type *ReturnTy) { 1969 llvm::Function *F; 1970 llvm::FunctionType *CallFTy; 1971 1972 // FIXME: Should we be caching any of this? 1973 if (!ReturnTy->isSingleValueType()) { 1974 F = IsSuper ? MessageSendSuperStretFn : MessageSendStretFn; 1975 std::vector<const llvm::Type*> Params(3); 1976 Params[0] = llvm::PointerType::getUnqual(ReturnTy); 1977 Params[1] = IsSuper ? SuperPtrTy : ObjectPtrTy; 1978 Params[2] = SelectorPtrTy; 1979 CallFTy = llvm::FunctionType::get(llvm::Type::VoidTy, Params, true); 1980 } else { // FIXME: floating point? 1981 F = IsSuper ? MessageSendSuperFn : MessageSendFn; 1982 std::vector<const llvm::Type*> Params(2); 1983 Params[0] = IsSuper ? SuperPtrTy : ObjectPtrTy; 1984 Params[1] = SelectorPtrTy; 1985 CallFTy = llvm::FunctionType::get(ReturnTy, Params, true); 1986 } 1987 1988 return llvm::ConstantExpr::getBitCast(F, 1989 llvm::PointerType::getUnqual(CallFTy)); 1990} 1991 1992/* *** */ 1993 1994CodeGen::CGObjCRuntime * 1995CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) { 1996 return new CGObjCMac(CGM); 1997} 1998