CGObjCGNU.cpp revision 1eb4433ac451dc16f4133a88af2d002ac26c58ef
1//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This provides Objective-C code generation targetting the GNU runtime. The 11// class in this file generates structures used by the GNU Objective-C runtime 12// library. These structures are defined in objc/objc.h and objc/objc-api.h in 13// the GNU runtime distribution. 14// 15//===----------------------------------------------------------------------===// 16 17#include "CGObjCRuntime.h" 18#include "CodeGenModule.h" 19#include "CodeGenFunction.h" 20 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/Decl.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/RecordLayout.h" 25#include "clang/AST/StmtObjC.h" 26 27#include "llvm/Intrinsics.h" 28#include "llvm/Module.h" 29#include "llvm/ADT/SmallVector.h" 30#include "llvm/ADT/StringMap.h" 31#include "llvm/Support/Compiler.h" 32#include "llvm/Target/TargetData.h" 33 34#include <map> 35 36 37using namespace clang; 38using namespace CodeGen; 39using llvm::dyn_cast; 40 41// The version of the runtime that this class targets. Must match the version 42// in the runtime. 43static const int RuntimeVersion = 8; 44static const int NonFragileRuntimeVersion = 9; 45static const int ProtocolVersion = 2; 46 47namespace { 48class CGObjCGNU : public CodeGen::CGObjCRuntime { 49private: 50 CodeGen::CodeGenModule &CGM; 51 llvm::Module &TheModule; 52 const llvm::PointerType *SelectorTy; 53 const llvm::PointerType *PtrToInt8Ty; 54 const llvm::FunctionType *IMPTy; 55 const llvm::PointerType *IdTy; 56 QualType ASTIdTy; 57 const llvm::IntegerType *IntTy; 58 const llvm::PointerType *PtrTy; 59 const llvm::IntegerType *LongTy; 60 const llvm::PointerType *PtrToIntTy; 61 llvm::GlobalAlias *ClassPtrAlias; 62 llvm::GlobalAlias *MetaClassPtrAlias; 63 std::vector<llvm::Constant*> Classes; 64 std::vector<llvm::Constant*> Categories; 65 std::vector<llvm::Constant*> ConstantStrings; 66 llvm::Function *LoadFunction; 67 llvm::StringMap<llvm::Constant*> ExistingProtocols; 68 typedef std::pair<std::string, std::string> TypedSelector; 69 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors; 70 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors; 71 // Some zeros used for GEPs in lots of places. 72 llvm::Constant *Zeros[2]; 73 llvm::Constant *NULLPtr; 74 llvm::LLVMContext &VMContext; 75private: 76 llvm::Constant *GenerateIvarList( 77 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames, 78 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes, 79 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets); 80 llvm::Constant *GenerateMethodList(const std::string &ClassName, 81 const std::string &CategoryName, 82 const llvm::SmallVectorImpl<Selector> &MethodSels, 83 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes, 84 bool isClassMethodList); 85 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName); 86 llvm::Constant *GenerateProtocolList( 87 const llvm::SmallVectorImpl<std::string> &Protocols); 88 llvm::Constant *GenerateClassStructure( 89 llvm::Constant *MetaClass, 90 llvm::Constant *SuperClass, 91 unsigned info, 92 const char *Name, 93 llvm::Constant *Version, 94 llvm::Constant *InstanceSize, 95 llvm::Constant *IVars, 96 llvm::Constant *Methods, 97 llvm::Constant *Protocols); 98 llvm::Constant *GenerateProtocolMethodList( 99 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames, 100 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes); 101 llvm::Constant *MakeConstantString(const std::string &Str, const std::string 102 &Name=""); 103 llvm::Constant *MakeGlobal(const llvm::StructType *Ty, 104 std::vector<llvm::Constant*> &V, const std::string &Name=""); 105 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty, 106 std::vector<llvm::Constant*> &V, const std::string &Name=""); 107 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID, 108 const ObjCIvarDecl *Ivar); 109 void EmitClassRef(const std::string &className); 110public: 111 CGObjCGNU(CodeGen::CodeGenModule &cgm); 112 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *); 113 virtual CodeGen::RValue 114 GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 115 QualType ResultType, 116 Selector Sel, 117 llvm::Value *Receiver, 118 bool IsClassMessage, 119 const CallArgList &CallArgs, 120 const ObjCMethodDecl *Method); 121 virtual CodeGen::RValue 122 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 123 QualType ResultType, 124 Selector Sel, 125 const ObjCInterfaceDecl *Class, 126 bool isCategoryImpl, 127 llvm::Value *Receiver, 128 bool IsClassMessage, 129 const CallArgList &CallArgs); 130 virtual llvm::Value *GetClass(CGBuilderTy &Builder, 131 const ObjCInterfaceDecl *OID); 132 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel); 133 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl 134 *Method); 135 136 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 137 const ObjCContainerDecl *CD); 138 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 139 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 140 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, 141 const ObjCProtocolDecl *PD); 142 virtual void GenerateProtocol(const ObjCProtocolDecl *PD); 143 virtual llvm::Function *ModuleInitFunction(); 144 virtual llvm::Function *GetPropertyGetFunction(); 145 virtual llvm::Function *GetPropertySetFunction(); 146 virtual llvm::Constant *EnumerationMutationFunction(); 147 148 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 149 const Stmt &S); 150 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 151 const ObjCAtThrowStmt &S); 152 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 153 llvm::Value *AddrWeakObj); 154 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 155 llvm::Value *src, llvm::Value *dst); 156 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 157 llvm::Value *src, llvm::Value *dest); 158 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 159 llvm::Value *src, llvm::Value *dest); 160 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 161 llvm::Value *src, llvm::Value *dest); 162 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, 163 llvm::Value *DestPtr, 164 llvm::Value *SrcPtr, 165 QualType Ty); 166 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 167 QualType ObjectTy, 168 llvm::Value *BaseValue, 169 const ObjCIvarDecl *Ivar, 170 unsigned CVRQualifiers); 171 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 172 const ObjCInterfaceDecl *Interface, 173 const ObjCIvarDecl *Ivar); 174}; 175} // end anonymous namespace 176 177 178/// Emits a reference to a dummy variable which is emitted with each class. 179/// This ensures that a linker error will be generated when trying to link 180/// together modules where a referenced class is not defined. 181void CGObjCGNU::EmitClassRef(const std::string &className) { 182 std::string symbolRef = "__objc_class_ref_" + className; 183 // Don't emit two copies of the same symbol 184 if (TheModule.getGlobalVariable(symbolRef)) 185 return; 186 std::string symbolName = "__objc_class_name_" + className; 187 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName); 188 if (!ClassSymbol) { 189 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false, 190 llvm::GlobalValue::ExternalLinkage, 0, symbolName); 191 } 192 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true, 193 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef); 194} 195 196static std::string SymbolNameForClass(const std::string &ClassName) { 197 return "_OBJC_CLASS_" + ClassName; 198} 199 200static std::string SymbolNameForMethod(const std::string &ClassName, 201 const std::string &CategoryName, 202 const std::string &MethodName, 203 bool isClassMethod) { 204 return "_OBJC_METHOD_" + ClassName + "("+CategoryName+")"+ 205 (isClassMethod ? "+" : "-") + MethodName; 206} 207 208CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm) 209 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0), 210 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) { 211 IntTy = cast<llvm::IntegerType>( 212 CGM.getTypes().ConvertType(CGM.getContext().IntTy)); 213 LongTy = cast<llvm::IntegerType>( 214 CGM.getTypes().ConvertType(CGM.getContext().LongTy)); 215 216 Zeros[0] = llvm::ConstantInt::get(LongTy, 0); 217 Zeros[1] = Zeros[0]; 218 NULLPtr = llvm::ConstantPointerNull::get( 219 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext))); 220 // C string type. Used in lots of places. 221 PtrToInt8Ty = 222 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 223 // Get the selector Type. 224 SelectorTy = cast<llvm::PointerType>( 225 CGM.getTypes().ConvertType(CGM.getContext().getObjCSelType())); 226 227 PtrToIntTy = llvm::PointerType::getUnqual(IntTy); 228 PtrTy = PtrToInt8Ty; 229 230 // Object type 231 ASTIdTy = CGM.getContext().getObjCIdType(); 232 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy)); 233 234 // IMP type 235 std::vector<const llvm::Type*> IMPArgs; 236 IMPArgs.push_back(IdTy); 237 IMPArgs.push_back(SelectorTy); 238 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true); 239} 240 241// This has to perform the lookup every time, since posing and related 242// techniques can modify the name -> class mapping. 243llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder, 244 const ObjCInterfaceDecl *OID) { 245 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString()); 246 EmitClassRef(OID->getNameAsString()); 247 ClassName = Builder.CreateStructGEP(ClassName, 0); 248 249 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty); 250 llvm::Constant *ClassLookupFn = 251 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, 252 Params, 253 true), 254 "objc_lookup_class"); 255 return Builder.CreateCall(ClassLookupFn, ClassName); 256} 257 258llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) { 259 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()]; 260 if (US == 0) 261 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy), 262 llvm::GlobalValue::PrivateLinkage, 263 ".objc_untyped_selector_alias"+Sel.getAsString(), 264 NULL, &TheModule); 265 266 return Builder.CreateLoad(US); 267} 268 269llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl 270 *Method) { 271 272 std::string SelName = Method->getSelector().getAsString(); 273 std::string SelTypes; 274 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes); 275 // Typed selectors 276 TypedSelector Selector = TypedSelector(SelName, 277 SelTypes); 278 279 // If it's already cached, return it. 280 if (TypedSelectors[Selector]) { 281 return Builder.CreateLoad(TypedSelectors[Selector]); 282 } 283 284 // If it isn't, cache it. 285 llvm::GlobalAlias *Sel = new llvm::GlobalAlias( 286 llvm::PointerType::getUnqual(SelectorTy), 287 llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName, 288 NULL, &TheModule); 289 TypedSelectors[Selector] = Sel; 290 291 return Builder.CreateLoad(Sel); 292} 293 294llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str, 295 const std::string &Name) { 296 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str()); 297 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2); 298} 299 300llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty, 301 std::vector<llvm::Constant*> &V, const std::string &Name) { 302 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V); 303 return new llvm::GlobalVariable(TheModule, Ty, false, 304 llvm::GlobalValue::InternalLinkage, C, Name); 305} 306 307llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty, 308 std::vector<llvm::Constant*> &V, const std::string &Name) { 309 llvm::Constant *C = llvm::ConstantArray::get(Ty, V); 310 return new llvm::GlobalVariable(TheModule, Ty, false, 311 llvm::GlobalValue::InternalLinkage, C, Name); 312} 313 314/// Generate an NSConstantString object. 315//TODO: In case there are any crazy people still using the GNU runtime without 316//an OpenStep implementation, this should let them select their own class for 317//constant strings. 318llvm::Constant *CGObjCGNU::GenerateConstantString(const ObjCStringLiteral *SL) { 319 std::string Str(SL->getString()->getStrData(), 320 SL->getString()->getByteLength()); 321 std::vector<llvm::Constant*> Ivars; 322 Ivars.push_back(NULLPtr); 323 Ivars.push_back(MakeConstantString(Str)); 324 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size())); 325 llvm::Constant *ObjCStr = MakeGlobal( 326 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL), 327 Ivars, ".objc_str"); 328 ConstantStrings.push_back( 329 llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty)); 330 return ObjCStr; 331} 332 333///Generates a message send where the super is the receiver. This is a message 334///send to self with special delivery semantics indicating which class's method 335///should be called. 336CodeGen::RValue 337CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 338 QualType ResultType, 339 Selector Sel, 340 const ObjCInterfaceDecl *Class, 341 bool isCategoryImpl, 342 llvm::Value *Receiver, 343 bool IsClassMessage, 344 const CallArgList &CallArgs) { 345 llvm::Value *cmd = GetSelector(CGF.Builder, Sel); 346 347 CallArgList ActualArgs; 348 349 ActualArgs.push_back( 350 std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)), 351 ASTIdTy)); 352 ActualArgs.push_back(std::make_pair(RValue::get(cmd), 353 CGF.getContext().getObjCSelType())); 354 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 355 356 CodeGenTypes &Types = CGM.getTypes(); 357 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs); 358 const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false); 359 360 llvm::Value *ReceiverClass = 0; 361 if (isCategoryImpl) { 362 llvm::Constant *classLookupFunction = 0; 363 std::vector<const llvm::Type*> Params; 364 Params.push_back(PtrTy); 365 if (IsClassMessage) { 366 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 367 IdTy, Params, true), "objc_get_meta_class"); 368 } else { 369 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 370 IdTy, Params, true), "objc_get_class"); 371 } 372 ReceiverClass = CGF.Builder.CreateCall(classLookupFunction, 373 MakeConstantString(Class->getNameAsString())); 374 } else { 375 // Set up global aliases for the metaclass or class pointer if they do not 376 // already exist. These will are forward-references which will be set to 377 // pointers to the class and metaclass structure created for the runtime 378 // load function. To send a message to super, we look up the value of the 379 // super_class pointer from either the class or metaclass structure. 380 if (IsClassMessage) { 381 if (!MetaClassPtrAlias) { 382 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy, 383 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" + 384 Class->getNameAsString(), NULL, &TheModule); 385 } 386 ReceiverClass = MetaClassPtrAlias; 387 } else { 388 if (!ClassPtrAlias) { 389 ClassPtrAlias = new llvm::GlobalAlias(IdTy, 390 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" + 391 Class->getNameAsString(), NULL, &TheModule); 392 } 393 ReceiverClass = ClassPtrAlias; 394 } 395 } 396 // Cast the pointer to a simplified version of the class structure 397 ReceiverClass = CGF.Builder.CreateBitCast(ReceiverClass, 398 llvm::PointerType::getUnqual( 399 llvm::StructType::get(VMContext, IdTy, IdTy, NULL))); 400 // Get the superclass pointer 401 ReceiverClass = CGF.Builder.CreateStructGEP(ReceiverClass, 1); 402 // Load the superclass pointer 403 ReceiverClass = CGF.Builder.CreateLoad(ReceiverClass); 404 // Construct the structure used to look up the IMP 405 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext, 406 Receiver->getType(), IdTy, NULL); 407 llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy); 408 409 CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0)); 410 CGF.Builder.CreateStore(ReceiverClass, 411 CGF.Builder.CreateStructGEP(ObjCSuper, 1)); 412 413 // Get the IMP 414 std::vector<const llvm::Type*> Params; 415 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy)); 416 Params.push_back(SelectorTy); 417 llvm::Constant *lookupFunction = 418 CGM.CreateRuntimeFunction(llvm::FunctionType::get( 419 llvm::PointerType::getUnqual(impType), Params, true), 420 "objc_msg_lookup_super"); 421 422 llvm::Value *lookupArgs[] = {ObjCSuper, cmd}; 423 llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs, 424 lookupArgs+2); 425 426 return CGF.EmitCall(FnInfo, imp, ActualArgs); 427} 428 429/// Generate code for a message send expression. 430CodeGen::RValue 431CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 432 QualType ResultType, 433 Selector Sel, 434 llvm::Value *Receiver, 435 bool IsClassMessage, 436 const CallArgList &CallArgs, 437 const ObjCMethodDecl *Method) { 438 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy)); 439 llvm::Value *cmd; 440 if (Method) 441 cmd = GetSelector(CGF.Builder, Method); 442 else 443 cmd = GetSelector(CGF.Builder, Sel); 444 CallArgList ActualArgs; 445 446 ActualArgs.push_back( 447 std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)), ASTIdTy)); 448 ActualArgs.push_back(std::make_pair(RValue::get(cmd), 449 CGF.getContext().getObjCSelType())); 450 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 451 452 CodeGenTypes &Types = CGM.getTypes(); 453 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs); 454 const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false); 455 456 llvm::Value *imp; 457 std::vector<const llvm::Type*> Params; 458 Params.push_back(Receiver->getType()); 459 Params.push_back(SelectorTy); 460 // For sender-aware dispatch, we pass the sender as the third argument to a 461 // lookup function. When sending messages from C code, the sender is nil. 462 // objc_msg_lookup_sender(id receiver, SEL selector, id sender); 463 if (CGM.getContext().getLangOptions().ObjCSenderDispatch) { 464 llvm::Value *self; 465 466 if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) { 467 self = CGF.LoadObjCSelf(); 468 } else { 469 self = llvm::ConstantPointerNull::get(IdTy); 470 } 471 Params.push_back(self->getType()); 472 llvm::Constant *lookupFunction = 473 CGM.CreateRuntimeFunction(llvm::FunctionType::get( 474 llvm::PointerType::getUnqual(impType), Params, true), 475 "objc_msg_lookup_sender"); 476 477 imp = CGF.Builder.CreateCall3(lookupFunction, Receiver, cmd, self); 478 } else { 479 llvm::Constant *lookupFunction = 480 CGM.CreateRuntimeFunction(llvm::FunctionType::get( 481 llvm::PointerType::getUnqual(impType), Params, true), 482 "objc_msg_lookup"); 483 484 imp = CGF.Builder.CreateCall2(lookupFunction, Receiver, cmd); 485 } 486 487 return CGF.EmitCall(FnInfo, imp, ActualArgs); 488} 489 490/// Generates a MethodList. Used in construction of a objc_class and 491/// objc_category structures. 492llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName, 493 const std::string &CategoryName, 494 const llvm::SmallVectorImpl<Selector> &MethodSels, 495 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes, 496 bool isClassMethodList) { 497 if (MethodSels.empty()) 498 return NULLPtr; 499 // Get the method structure type. 500 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext, 501 PtrToInt8Ty, // Really a selector, but the runtime creates it us. 502 PtrToInt8Ty, // Method types 503 llvm::PointerType::getUnqual(IMPTy), //Method pointer 504 NULL); 505 std::vector<llvm::Constant*> Methods; 506 std::vector<llvm::Constant*> Elements; 507 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) { 508 Elements.clear(); 509 if (llvm::Constant *Method = 510 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName, 511 MethodSels[i].getAsString(), 512 isClassMethodList))) { 513 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString()); 514 Elements.push_back(C); 515 Elements.push_back(MethodTypes[i]); 516 Method = llvm::ConstantExpr::getBitCast(Method, 517 llvm::PointerType::getUnqual(IMPTy)); 518 Elements.push_back(Method); 519 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements)); 520 } 521 } 522 523 // Array of method structures 524 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy, 525 Methods.size()); 526 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy, 527 Methods); 528 529 // Structure containing list pointer, array and array count 530 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields; 531 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext); 532 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy); 533 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext, 534 NextPtrTy, 535 IntTy, 536 ObjCMethodArrayTy, 537 NULL); 538 // Refine next pointer type to concrete type 539 llvm::cast<llvm::OpaqueType>( 540 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy); 541 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get()); 542 543 Methods.clear(); 544 Methods.push_back(llvm::ConstantPointerNull::get( 545 llvm::PointerType::getUnqual(ObjCMethodListTy))); 546 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 547 MethodTypes.size())); 548 Methods.push_back(MethodArray); 549 550 // Create an instance of the structure 551 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list"); 552} 553 554/// Generates an IvarList. Used in construction of a objc_class. 555llvm::Constant *CGObjCGNU::GenerateIvarList( 556 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames, 557 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes, 558 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) { 559 // Get the method structure type. 560 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext, 561 PtrToInt8Ty, 562 PtrToInt8Ty, 563 IntTy, 564 NULL); 565 std::vector<llvm::Constant*> Ivars; 566 std::vector<llvm::Constant*> Elements; 567 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) { 568 Elements.clear(); 569 Elements.push_back(IvarNames[i]); 570 Elements.push_back(IvarTypes[i]); 571 Elements.push_back(IvarOffsets[i]); 572 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements)); 573 } 574 575 // Array of method structures 576 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy, 577 IvarNames.size()); 578 579 580 Elements.clear(); 581 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size())); 582 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars)); 583 // Structure containing array and array count 584 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy, 585 ObjCIvarArrayTy, 586 NULL); 587 588 // Create an instance of the structure 589 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list"); 590} 591 592/// Generate a class structure 593llvm::Constant *CGObjCGNU::GenerateClassStructure( 594 llvm::Constant *MetaClass, 595 llvm::Constant *SuperClass, 596 unsigned info, 597 const char *Name, 598 llvm::Constant *Version, 599 llvm::Constant *InstanceSize, 600 llvm::Constant *IVars, 601 llvm::Constant *Methods, 602 llvm::Constant *Protocols) { 603 // Set up the class structure 604 // Note: Several of these are char*s when they should be ids. This is 605 // because the runtime performs this translation on load. 606 llvm::StructType *ClassTy = llvm::StructType::get(VMContext, 607 PtrToInt8Ty, // class_pointer 608 PtrToInt8Ty, // super_class 609 PtrToInt8Ty, // name 610 LongTy, // version 611 LongTy, // info 612 LongTy, // instance_size 613 IVars->getType(), // ivars 614 Methods->getType(), // methods 615 // These are all filled in by the runtime, so we pretend 616 PtrTy, // dtable 617 PtrTy, // subclass_list 618 PtrTy, // sibling_class 619 PtrTy, // protocols 620 PtrTy, // gc_object_type 621 NULL); 622 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0); 623 llvm::Constant *NullP = 624 llvm::ConstantPointerNull::get(PtrTy); 625 // Fill in the structure 626 std::vector<llvm::Constant*> Elements; 627 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty)); 628 Elements.push_back(SuperClass); 629 Elements.push_back(MakeConstantString(Name, ".class_name")); 630 Elements.push_back(Zero); 631 Elements.push_back(llvm::ConstantInt::get(LongTy, info)); 632 Elements.push_back(InstanceSize); 633 Elements.push_back(IVars); 634 Elements.push_back(Methods); 635 Elements.push_back(NullP); 636 Elements.push_back(NullP); 637 Elements.push_back(NullP); 638 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy)); 639 Elements.push_back(NullP); 640 // Create an instance of the structure 641 return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name)); 642} 643 644llvm::Constant *CGObjCGNU::GenerateProtocolMethodList( 645 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames, 646 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) { 647 // Get the method structure type. 648 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext, 649 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us. 650 PtrToInt8Ty, 651 NULL); 652 std::vector<llvm::Constant*> Methods; 653 std::vector<llvm::Constant*> Elements; 654 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) { 655 Elements.clear(); 656 Elements.push_back(MethodNames[i]); 657 Elements.push_back(MethodTypes[i]); 658 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements)); 659 } 660 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy, 661 MethodNames.size()); 662 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, 663 Methods); 664 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext, 665 IntTy, ObjCMethodArrayTy, NULL); 666 Methods.clear(); 667 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size())); 668 Methods.push_back(Array); 669 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list"); 670} 671 672// Create the protocol list structure used in classes, categories and so on 673llvm::Constant *CGObjCGNU::GenerateProtocolList( 674 const llvm::SmallVectorImpl<std::string> &Protocols) { 675 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty, 676 Protocols.size()); 677 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext, 678 PtrTy, //Should be a recurisve pointer, but it's always NULL here. 679 LongTy,//FIXME: Should be size_t 680 ProtocolArrayTy, 681 NULL); 682 std::vector<llvm::Constant*> Elements; 683 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end(); 684 iter != endIter ; iter++) { 685 llvm::Constant *protocol = ExistingProtocols[*iter]; 686 if (!protocol) 687 protocol = GenerateEmptyProtocol(*iter); 688 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol, 689 PtrToInt8Ty); 690 Elements.push_back(Ptr); 691 } 692 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy, 693 Elements); 694 Elements.clear(); 695 Elements.push_back(NULLPtr); 696 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size())); 697 Elements.push_back(ProtocolArray); 698 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list"); 699} 700 701llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder, 702 const ObjCProtocolDecl *PD) { 703 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()]; 704 const llvm::Type *T = 705 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType()); 706 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T)); 707} 708 709llvm::Constant *CGObjCGNU::GenerateEmptyProtocol( 710 const std::string &ProtocolName) { 711 llvm::SmallVector<std::string, 0> EmptyStringVector; 712 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector; 713 714 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector); 715 llvm::Constant *InstanceMethodList = 716 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector); 717 llvm::Constant *ClassMethodList = 718 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector); 719 // Protocols are objects containing lists of the methods implemented and 720 // protocols adopted. 721 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy, 722 PtrToInt8Ty, 723 ProtocolList->getType(), 724 InstanceMethodList->getType(), 725 ClassMethodList->getType(), 726 NULL); 727 std::vector<llvm::Constant*> Elements; 728 // The isa pointer must be set to a magic number so the runtime knows it's 729 // the correct layout. 730 Elements.push_back(llvm::ConstantExpr::getIntToPtr( 731 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ProtocolVersion), IdTy)); 732 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name")); 733 Elements.push_back(ProtocolList); 734 Elements.push_back(InstanceMethodList); 735 Elements.push_back(ClassMethodList); 736 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol"); 737} 738 739void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { 740 ASTContext &Context = CGM.getContext(); 741 std::string ProtocolName = PD->getNameAsString(); 742 llvm::SmallVector<std::string, 16> Protocols; 743 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(), 744 E = PD->protocol_end(); PI != E; ++PI) 745 Protocols.push_back((*PI)->getNameAsString()); 746 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames; 747 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 748 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(), 749 E = PD->instmeth_end(); iter != E; iter++) { 750 std::string TypeStr; 751 Context.getObjCEncodingForMethodDecl(*iter, TypeStr); 752 InstanceMethodNames.push_back( 753 MakeConstantString((*iter)->getSelector().getAsString())); 754 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 755 } 756 // Collect information about class methods: 757 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames; 758 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes; 759 for (ObjCProtocolDecl::classmeth_iterator 760 iter = PD->classmeth_begin(), endIter = PD->classmeth_end(); 761 iter != endIter ; iter++) { 762 std::string TypeStr; 763 Context.getObjCEncodingForMethodDecl((*iter),TypeStr); 764 ClassMethodNames.push_back( 765 MakeConstantString((*iter)->getSelector().getAsString())); 766 ClassMethodTypes.push_back(MakeConstantString(TypeStr)); 767 } 768 769 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols); 770 llvm::Constant *InstanceMethodList = 771 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes); 772 llvm::Constant *ClassMethodList = 773 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes); 774 // Protocols are objects containing lists of the methods implemented and 775 // protocols adopted. 776 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy, 777 PtrToInt8Ty, 778 ProtocolList->getType(), 779 InstanceMethodList->getType(), 780 ClassMethodList->getType(), 781 NULL); 782 std::vector<llvm::Constant*> Elements; 783 // The isa pointer must be set to a magic number so the runtime knows it's 784 // the correct layout. 785 Elements.push_back(llvm::ConstantExpr::getIntToPtr( 786 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ProtocolVersion), IdTy)); 787 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name")); 788 Elements.push_back(ProtocolList); 789 Elements.push_back(InstanceMethodList); 790 Elements.push_back(ClassMethodList); 791 ExistingProtocols[ProtocolName] = 792 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements, 793 ".objc_protocol"), IdTy); 794} 795 796void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 797 std::string ClassName = OCD->getClassInterface()->getNameAsString(); 798 std::string CategoryName = OCD->getNameAsString(); 799 // Collect information about instance methods 800 llvm::SmallVector<Selector, 16> InstanceMethodSels; 801 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 802 for (ObjCCategoryImplDecl::instmeth_iterator 803 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end(); 804 iter != endIter ; iter++) { 805 InstanceMethodSels.push_back((*iter)->getSelector()); 806 std::string TypeStr; 807 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr); 808 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 809 } 810 811 // Collect information about class methods 812 llvm::SmallVector<Selector, 16> ClassMethodSels; 813 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes; 814 for (ObjCCategoryImplDecl::classmeth_iterator 815 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end(); 816 iter != endIter ; iter++) { 817 ClassMethodSels.push_back((*iter)->getSelector()); 818 std::string TypeStr; 819 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr); 820 ClassMethodTypes.push_back(MakeConstantString(TypeStr)); 821 } 822 823 // Collect the names of referenced protocols 824 llvm::SmallVector<std::string, 16> Protocols; 825 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface(); 826 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols(); 827 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(), 828 E = Protos.end(); I != E; ++I) 829 Protocols.push_back((*I)->getNameAsString()); 830 831 std::vector<llvm::Constant*> Elements; 832 Elements.push_back(MakeConstantString(CategoryName)); 833 Elements.push_back(MakeConstantString(ClassName)); 834 // Instance method list 835 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( 836 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes, 837 false), PtrTy)); 838 // Class method list 839 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList( 840 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true), 841 PtrTy)); 842 // Protocol list 843 Elements.push_back(llvm::ConstantExpr::getBitCast( 844 GenerateProtocolList(Protocols), PtrTy)); 845 Categories.push_back(llvm::ConstantExpr::getBitCast( 846 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, 847 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy)); 848} 849 850void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { 851 ASTContext &Context = CGM.getContext(); 852 853 // Get the superclass name. 854 const ObjCInterfaceDecl * SuperClassDecl = 855 OID->getClassInterface()->getSuperClass(); 856 std::string SuperClassName; 857 if (SuperClassDecl) { 858 SuperClassName = SuperClassDecl->getNameAsString(); 859 EmitClassRef(SuperClassName); 860 } 861 862 // Get the class name 863 ObjCInterfaceDecl *ClassDecl = 864 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface()); 865 std::string ClassName = ClassDecl->getNameAsString(); 866 // Emit the symbol that is used to generate linker errors if this class is 867 // referenced in other modules but not declared. 868 std::string classSymbolName = "__objc_class_name_" + ClassName; 869 if (llvm::GlobalVariable *symbol = 870 TheModule.getGlobalVariable(classSymbolName)) { 871 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0)); 872 } else { 873 new llvm::GlobalVariable(TheModule, LongTy, false, 874 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0), 875 classSymbolName); 876 } 877 878 // Get the size of instances. 879 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8; 880 881 // Collect information about instance variables. 882 llvm::SmallVector<llvm::Constant*, 16> IvarNames; 883 llvm::SmallVector<llvm::Constant*, 16> IvarTypes; 884 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets; 885 886 int superInstanceSize = !SuperClassDecl ? 0 : 887 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8; 888 // For non-fragile ivars, set the instance size to 0 - {the size of just this 889 // class}. The runtime will then set this to the correct value on load. 890 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 891 instanceSize = 0 - (instanceSize - superInstanceSize); 892 } 893 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(), 894 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) { 895 // Store the name 896 IvarNames.push_back(MakeConstantString((*iter)->getNameAsString())); 897 // Get the type encoding for this ivar 898 std::string TypeStr; 899 Context.getObjCEncodingForType((*iter)->getType(), TypeStr); 900 IvarTypes.push_back(MakeConstantString(TypeStr)); 901 // Get the offset 902 uint64_t Offset; 903 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 904 Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter) - 905 superInstanceSize; 906 } else { 907 Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter); 908 } 909 IvarOffsets.push_back( 910 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset)); 911 } 912 913 // Collect information about instance methods 914 llvm::SmallVector<Selector, 16> InstanceMethodSels; 915 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes; 916 for (ObjCImplementationDecl::instmeth_iterator 917 iter = OID->instmeth_begin(), endIter = OID->instmeth_end(); 918 iter != endIter ; iter++) { 919 InstanceMethodSels.push_back((*iter)->getSelector()); 920 std::string TypeStr; 921 Context.getObjCEncodingForMethodDecl((*iter),TypeStr); 922 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 923 } 924 for (ObjCImplDecl::propimpl_iterator 925 iter = OID->propimpl_begin(), endIter = OID->propimpl_end(); 926 iter != endIter ; iter++) { 927 ObjCPropertyDecl *property = (*iter)->getPropertyDecl(); 928 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) { 929 InstanceMethodSels.push_back(getter->getSelector()); 930 std::string TypeStr; 931 Context.getObjCEncodingForMethodDecl(getter,TypeStr); 932 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 933 } 934 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) { 935 InstanceMethodSels.push_back(setter->getSelector()); 936 std::string TypeStr; 937 Context.getObjCEncodingForMethodDecl(setter,TypeStr); 938 InstanceMethodTypes.push_back(MakeConstantString(TypeStr)); 939 } 940 } 941 942 // Collect information about class methods 943 llvm::SmallVector<Selector, 16> ClassMethodSels; 944 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes; 945 for (ObjCImplementationDecl::classmeth_iterator 946 iter = OID->classmeth_begin(), endIter = OID->classmeth_end(); 947 iter != endIter ; iter++) { 948 ClassMethodSels.push_back((*iter)->getSelector()); 949 std::string TypeStr; 950 Context.getObjCEncodingForMethodDecl((*iter),TypeStr); 951 ClassMethodTypes.push_back(MakeConstantString(TypeStr)); 952 } 953 // Collect the names of referenced protocols 954 llvm::SmallVector<std::string, 16> Protocols; 955 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols(); 956 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(), 957 E = Protos.end(); I != E; ++I) 958 Protocols.push_back((*I)->getNameAsString()); 959 960 961 962 // Get the superclass pointer. 963 llvm::Constant *SuperClass; 964 if (!SuperClassName.empty()) { 965 SuperClass = MakeConstantString(SuperClassName, ".super_class_name"); 966 } else { 967 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty); 968 } 969 // Empty vector used to construct empty method lists 970 llvm::SmallVector<llvm::Constant*, 1> empty; 971 // Generate the method and instance variable lists 972 llvm::Constant *MethodList = GenerateMethodList(ClassName, "", 973 InstanceMethodSels, InstanceMethodTypes, false); 974 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "", 975 ClassMethodSels, ClassMethodTypes, true); 976 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes, 977 IvarOffsets); 978 // Irrespective of whether we are compiling for a fragile or non-fragile ABI, 979 // we emit a symbol containing the offset for each ivar in the class. This 980 // allows code compiled for the non-Fragile ABI to inherit from code compiled 981 // for the legacy ABI, without causing problems. The converse is also 982 // possible, but causes all ivar accesses to be fragile. 983 int i = 0; 984 // Offset pointer for getting at the correct field in the ivar list when 985 // setting up the alias. These are: The base address for the global, the 986 // ivar array (second field), the ivar in this list (set for each ivar), and 987 // the offset (third field in ivar structure) 988 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext); 989 llvm::Constant *offsetPointerIndexes[] = {Zeros[0], 990 llvm::ConstantInt::get(IndexTy, 1), 0, 991 llvm::ConstantInt::get(IndexTy, 2) }; 992 993 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(), 994 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) { 995 const std::string Name = "__objc_ivar_offset_" + ClassName + '.' 996 +(*iter)->getNameAsString(); 997 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i++); 998 // Get the correct ivar field 999 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr( 1000 IvarList, offsetPointerIndexes, 4); 1001 // Get the existing alias, if one exists. 1002 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name); 1003 if (offset) { 1004 offset->setInitializer(offsetValue); 1005 // If this is the real definition, change its linkage type so that 1006 // different modules will use this one, rather than their private 1007 // copy. 1008 offset->setLinkage(llvm::GlobalValue::ExternalLinkage); 1009 } else { 1010 // Add a new alias if there isn't one already. 1011 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(), 1012 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name); 1013 } 1014 } 1015 //Generate metaclass for class methods 1016 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr, 1017 NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList( 1018 empty, empty, empty), ClassMethodList, NULLPtr); 1019 1020 // Generate the class structure 1021 llvm::Constant *ClassStruct = 1022 GenerateClassStructure(MetaClassStruct, SuperClass, 0x1L, 1023 ClassName.c_str(), 0, 1024 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, 1025 MethodList, GenerateProtocolList(Protocols)); 1026 1027 // Resolve the class aliases, if they exist. 1028 if (ClassPtrAlias) { 1029 ClassPtrAlias->setAliasee( 1030 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy)); 1031 ClassPtrAlias = 0; 1032 } 1033 if (MetaClassPtrAlias) { 1034 MetaClassPtrAlias->setAliasee( 1035 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy)); 1036 MetaClassPtrAlias = 0; 1037 } 1038 1039 // Add class structure to list to be added to the symtab later 1040 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty); 1041 Classes.push_back(ClassStruct); 1042} 1043 1044 1045llvm::Function *CGObjCGNU::ModuleInitFunction() { 1046 // Only emit an ObjC load function if no Objective-C stuff has been called 1047 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() && 1048 ExistingProtocols.empty() && TypedSelectors.empty() && 1049 UntypedSelectors.empty()) 1050 return NULL; 1051 1052 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>( 1053 SelectorTy->getElementType()); 1054 const llvm::Type *SelStructPtrTy = SelectorTy; 1055 bool isSelOpaque = false; 1056 if (SelStructTy == 0) { 1057 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty, 1058 PtrToInt8Ty, NULL); 1059 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy); 1060 isSelOpaque = true; 1061 } 1062 1063 // Name the ObjC types to make the IR a bit easier to read 1064 TheModule.addTypeName(".objc_selector", SelStructPtrTy); 1065 TheModule.addTypeName(".objc_id", IdTy); 1066 TheModule.addTypeName(".objc_imp", IMPTy); 1067 1068 std::vector<llvm::Constant*> Elements; 1069 llvm::Constant *Statics = NULLPtr; 1070 // Generate statics list: 1071 if (ConstantStrings.size()) { 1072 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty, 1073 ConstantStrings.size() + 1); 1074 ConstantStrings.push_back(NULLPtr); 1075 1076 const char *StringClass = CGM.getLangOptions().ObjCConstantStringClass; 1077 if (!StringClass) StringClass = "NXConstantString"; 1078 Elements.push_back(MakeConstantString(StringClass, 1079 ".objc_static_class_name")); 1080 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy, 1081 ConstantStrings)); 1082 llvm::StructType *StaticsListTy = 1083 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL); 1084 llvm::Type *StaticsListPtrTy = 1085 llvm::PointerType::getUnqual(StaticsListTy); 1086 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics"); 1087 llvm::ArrayType *StaticsListArrayTy = 1088 llvm::ArrayType::get(StaticsListPtrTy, 2); 1089 Elements.clear(); 1090 Elements.push_back(Statics); 1091 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy)); 1092 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr"); 1093 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy); 1094 } 1095 // Array of classes, categories, and constant objects 1096 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty, 1097 Classes.size() + Categories.size() + 2); 1098 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext, 1099 LongTy, SelStructPtrTy, 1100 llvm::Type::getInt16Ty(VMContext), 1101 llvm::Type::getInt16Ty(VMContext), 1102 ClassListTy, NULL); 1103 1104 Elements.clear(); 1105 // Pointer to an array of selectors used in this module. 1106 std::vector<llvm::Constant*> Selectors; 1107 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator 1108 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end(); 1109 iter != iterEnd ; ++iter) { 1110 Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name")); 1111 Elements.push_back(MakeConstantString(iter->first.second, 1112 ".objc_sel_types")); 1113 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 1114 Elements.clear(); 1115 } 1116 for (llvm::StringMap<llvm::GlobalAlias*>::iterator 1117 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end(); 1118 iter != iterEnd; ++iter) { 1119 Elements.push_back( 1120 MakeConstantString(iter->getKeyData(), ".objc_sel_name")); 1121 Elements.push_back(NULLPtr); 1122 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 1123 Elements.clear(); 1124 } 1125 Elements.push_back(NULLPtr); 1126 Elements.push_back(NULLPtr); 1127 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements)); 1128 Elements.clear(); 1129 // Number of static selectors 1130 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() )); 1131 llvm::Constant *SelectorList = MakeGlobal( 1132 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors, 1133 ".objc_selector_list"); 1134 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, 1135 SelStructPtrTy)); 1136 1137 // Now that all of the static selectors exist, create pointers to them. 1138 int index = 0; 1139 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator 1140 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end(); 1141 iter != iterEnd; ++iter) { 1142 llvm::Constant *Idxs[] = {Zeros[0], 1143 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]}; 1144 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy, 1145 true, llvm::GlobalValue::InternalLinkage, 1146 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2), 1147 ".objc_sel_ptr"); 1148 // If selectors are defined as an opaque type, cast the pointer to this 1149 // type. 1150 if (isSelOpaque) { 1151 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, 1152 llvm::PointerType::getUnqual(SelectorTy)); 1153 } 1154 (*iter).second->setAliasee(SelPtr); 1155 } 1156 for (llvm::StringMap<llvm::GlobalAlias*>::iterator 1157 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end(); 1158 iter != iterEnd; iter++) { 1159 llvm::Constant *Idxs[] = {Zeros[0], 1160 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]}; 1161 llvm::Constant *SelPtr = new llvm::GlobalVariable 1162 (TheModule, SelStructPtrTy, 1163 true, llvm::GlobalValue::InternalLinkage, 1164 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2), 1165 ".objc_sel_ptr"); 1166 // If selectors are defined as an opaque type, cast the pointer to this 1167 // type. 1168 if (isSelOpaque) { 1169 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, 1170 llvm::PointerType::getUnqual(SelectorTy)); 1171 } 1172 (*iter).second->setAliasee(SelPtr); 1173 } 1174 // Number of classes defined. 1175 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext), 1176 Classes.size())); 1177 // Number of categories defined 1178 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext), 1179 Categories.size())); 1180 // Create an array of classes, then categories, then static object instances 1181 Classes.insert(Classes.end(), Categories.begin(), Categories.end()); 1182 // NULL-terminated list of static object instances (mainly constant strings) 1183 Classes.push_back(Statics); 1184 Classes.push_back(NULLPtr); 1185 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes); 1186 Elements.push_back(ClassList); 1187 // Construct the symbol table 1188 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements); 1189 1190 // The symbol table is contained in a module which has some version-checking 1191 // constants 1192 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy, 1193 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL); 1194 Elements.clear(); 1195 // Runtime version used for compatibility checking. 1196 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) { 1197 Elements.push_back(llvm::ConstantInt::get(LongTy, 1198 NonFragileRuntimeVersion)); 1199 } else { 1200 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion)); 1201 } 1202 // sizeof(ModuleTy) 1203 llvm::TargetData td = llvm::TargetData::TargetData(&TheModule); 1204 Elements.push_back(llvm::ConstantInt::get(LongTy, 1205 td.getTypeSizeInBits(ModuleTy)/8)); 1206 //FIXME: Should be the path to the file where this module was declared 1207 Elements.push_back(NULLPtr); 1208 Elements.push_back(SymTab); 1209 llvm::Value *Module = MakeGlobal(ModuleTy, Elements); 1210 1211 // Create the load function calling the runtime entry point with the module 1212 // structure 1213 llvm::Function * LoadFunction = llvm::Function::Create( 1214 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false), 1215 llvm::GlobalValue::InternalLinkage, ".objc_load_function", 1216 &TheModule); 1217 llvm::BasicBlock *EntryBB = 1218 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction); 1219 CGBuilderTy Builder(VMContext); 1220 Builder.SetInsertPoint(EntryBB); 1221 1222 std::vector<const llvm::Type*> Params(1, 1223 llvm::PointerType::getUnqual(ModuleTy)); 1224 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get( 1225 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class"); 1226 Builder.CreateCall(Register, Module); 1227 Builder.CreateRetVoid(); 1228 1229 return LoadFunction; 1230} 1231 1232llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD, 1233 const ObjCContainerDecl *CD) { 1234 const ObjCCategoryImplDecl *OCD = 1235 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext()); 1236 std::string CategoryName = OCD ? OCD->getNameAsString() : ""; 1237 std::string ClassName = OMD->getClassInterface()->getNameAsString(); 1238 std::string MethodName = OMD->getSelector().getAsString(); 1239 bool isClassMethod = !OMD->isInstanceMethod(); 1240 1241 CodeGenTypes &Types = CGM.getTypes(); 1242 const llvm::FunctionType *MethodTy = 1243 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic()); 1244 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName, 1245 MethodName, isClassMethod); 1246 1247 llvm::Function *Method 1248 = llvm::Function::Create(MethodTy, 1249 llvm::GlobalValue::InternalLinkage, 1250 FunctionName, 1251 &TheModule); 1252 return Method; 1253} 1254 1255llvm::Function *CGObjCGNU::GetPropertyGetFunction() { 1256 std::vector<const llvm::Type*> Params; 1257 const llvm::Type *BoolTy = 1258 CGM.getTypes().ConvertType(CGM.getContext().BoolTy); 1259 Params.push_back(IdTy); 1260 Params.push_back(SelectorTy); 1261 // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64 1262 Params.push_back(LongTy); 1263 Params.push_back(BoolTy); 1264 // void objc_getProperty (id, SEL, ptrdiff_t, bool) 1265 const llvm::FunctionType *FTy = 1266 llvm::FunctionType::get(IdTy, Params, false); 1267 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy, 1268 "objc_getProperty")); 1269} 1270 1271llvm::Function *CGObjCGNU::GetPropertySetFunction() { 1272 std::vector<const llvm::Type*> Params; 1273 const llvm::Type *BoolTy = 1274 CGM.getTypes().ConvertType(CGM.getContext().BoolTy); 1275 Params.push_back(IdTy); 1276 Params.push_back(SelectorTy); 1277 // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64 1278 Params.push_back(LongTy); 1279 Params.push_back(IdTy); 1280 Params.push_back(BoolTy); 1281 Params.push_back(BoolTy); 1282 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) 1283 const llvm::FunctionType *FTy = 1284 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false); 1285 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy, 1286 "objc_setProperty")); 1287} 1288 1289llvm::Constant *CGObjCGNU::EnumerationMutationFunction() { 1290 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 1291 ASTContext &Ctx = CGM.getContext(); 1292 // void objc_enumerationMutation (id) 1293 llvm::SmallVector<QualType,16> Params; 1294 Params.push_back(ASTIdTy); 1295 const llvm::FunctionType *FTy = 1296 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false); 1297 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation"); 1298} 1299 1300void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 1301 const Stmt &S) { 1302 // Pointer to the personality function 1303 llvm::Constant *Personality = 1304 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty(VMContext), 1305 true), 1306 "__gnu_objc_personality_v0"); 1307 Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy); 1308 std::vector<const llvm::Type*> Params; 1309 Params.push_back(PtrTy); 1310 llvm::Value *RethrowFn = 1311 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 1312 Params, false), "_Unwind_Resume_or_Rethrow"); 1313 1314 bool isTry = isa<ObjCAtTryStmt>(S); 1315 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); 1316 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest(); 1317 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); 1318 llvm::BasicBlock *CatchInCatch = CGF.createBasicBlock("catch.rethrow"); 1319 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally"); 1320 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw"); 1321 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end"); 1322 1323 // GNU runtime does not currently support @synchronized() 1324 if (!isTry) { 1325 std::vector<const llvm::Type*> Args(1, IdTy); 1326 llvm::FunctionType *FTy = 1327 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false); 1328 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter"); 1329 llvm::Value *SyncArg = 1330 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 1331 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy); 1332 CGF.Builder.CreateCall(SyncEnter, SyncArg); 1333 } 1334 1335 1336 // Push an EH context entry, used for handling rethrows and jumps 1337 // through finally. 1338 CGF.PushCleanupBlock(FinallyBlock); 1339 1340 // Emit the statements in the @try {} block 1341 CGF.setInvokeDest(TryHandler); 1342 1343 CGF.EmitBlock(TryBlock); 1344 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() 1345 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); 1346 1347 // Jump to @finally if there is no exception 1348 CGF.EmitBranchThroughCleanup(FinallyEnd); 1349 1350 // Emit the handlers 1351 CGF.EmitBlock(TryHandler); 1352 1353 // Get the correct versions of the exception handling intrinsics 1354 llvm::TargetData td = llvm::TargetData::TargetData(&TheModule); 1355 int PointerWidth = td.getTypeSizeInBits(PtrTy); 1356 assert((PointerWidth == 32 || PointerWidth == 64) && 1357 "Can't yet handle exceptions if pointers are not 32 or 64 bits"); 1358 llvm::Value *llvm_eh_exception = 1359 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception); 1360 llvm::Value *llvm_eh_selector = PointerWidth == 32 ? 1361 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i32) : 1362 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64); 1363 llvm::Value *llvm_eh_typeid_for = PointerWidth == 32 ? 1364 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i32) : 1365 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64); 1366 1367 // Exception object 1368 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); 1369 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow"); 1370 1371 llvm::SmallVector<llvm::Value*, 8> ESelArgs; 1372 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers; 1373 1374 ESelArgs.push_back(Exc); 1375 ESelArgs.push_back(Personality); 1376 1377 bool HasCatchAll = false; 1378 // Only @try blocks are allowed @catch blocks, but both can have @finally 1379 if (isTry) { 1380 if (const ObjCAtCatchStmt* CatchStmt = 1381 cast<ObjCAtTryStmt>(S).getCatchStmts()) { 1382 CGF.setInvokeDest(CatchInCatch); 1383 1384 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) { 1385 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); 1386 Handlers.push_back(std::make_pair(CatchDecl, 1387 CatchStmt->getCatchBody())); 1388 1389 // @catch() and @catch(id) both catch any ObjC exception 1390 if (!CatchDecl || CatchDecl->getType()->isObjCIdType() 1391 || CatchDecl->getType()->isObjCQualifiedIdType()) { 1392 // Use i8* null here to signal this is a catch all, not a cleanup. 1393 ESelArgs.push_back(NULLPtr); 1394 HasCatchAll = true; 1395 // No further catches after this one will ever by reached 1396 break; 1397 } 1398 1399 // All other types should be Objective-C interface pointer types. 1400 const ObjCObjectPointerType *OPT = 1401 CatchDecl->getType()->getAsObjCObjectPointerType(); 1402 assert(OPT && "Invalid @catch type."); 1403 const ObjCInterfaceType *IT = 1404 OPT->getPointeeType()->getAsObjCInterfaceType(); 1405 assert(IT && "Invalid @catch type."); 1406 llvm::Value *EHType = 1407 MakeConstantString(IT->getDecl()->getNameAsString()); 1408 ESelArgs.push_back(EHType); 1409 } 1410 } 1411 } 1412 1413 // We use a cleanup unless there was already a catch all. 1414 if (!HasCatchAll) { 1415 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0)); 1416 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0)); 1417 } 1418 1419 // Find which handler was matched. 1420 llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector, 1421 ESelArgs.begin(), ESelArgs.end(), "selector"); 1422 1423 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) { 1424 const ParmVarDecl *CatchParam = Handlers[i].first; 1425 const Stmt *CatchBody = Handlers[i].second; 1426 1427 llvm::BasicBlock *Next = 0; 1428 1429 // The last handler always matches. 1430 if (i + 1 != e) { 1431 assert(CatchParam && "Only last handler can be a catch all."); 1432 1433 // Test whether this block matches the type for the selector and branch 1434 // to Match if it does, or to the next BB if it doesn't. 1435 llvm::BasicBlock *Match = CGF.createBasicBlock("match"); 1436 Next = CGF.createBasicBlock("catch.next"); 1437 llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for, 1438 CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy)); 1439 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match, 1440 Next); 1441 1442 CGF.EmitBlock(Match); 1443 } 1444 1445 if (CatchBody) { 1446 llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc, 1447 CGF.ConvertType(CatchParam->getType())); 1448 1449 // Bind the catch parameter if it exists. 1450 if (CatchParam) { 1451 // CatchParam is a ParmVarDecl because of the grammar 1452 // construction used to handle this, but for codegen purposes 1453 // we treat this as a local decl. 1454 CGF.EmitLocalBlockVarDecl(*CatchParam); 1455 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam)); 1456 } 1457 1458 CGF.ObjCEHValueStack.push_back(ExcObject); 1459 CGF.EmitStmt(CatchBody); 1460 CGF.ObjCEHValueStack.pop_back(); 1461 1462 CGF.EmitBranchThroughCleanup(FinallyEnd); 1463 1464 if (Next) 1465 CGF.EmitBlock(Next); 1466 } else { 1467 assert(!Next && "catchup should be last handler."); 1468 1469 CGF.Builder.CreateStore(Exc, RethrowPtr); 1470 CGF.EmitBranchThroughCleanup(FinallyRethrow); 1471 } 1472 } 1473 // The @finally block is a secondary landing pad for any exceptions thrown in 1474 // @catch() blocks 1475 CGF.EmitBlock(CatchInCatch); 1476 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); 1477 ESelArgs.clear(); 1478 ESelArgs.push_back(Exc); 1479 ESelArgs.push_back(Personality); 1480 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0)); 1481 CGF.Builder.CreateCall(llvm_eh_selector, ESelArgs.begin(), ESelArgs.end(), 1482 "selector"); 1483 CGF.Builder.CreateCall(llvm_eh_typeid_for, 1484 CGF.Builder.CreateIntToPtr(ESelArgs[2], PtrTy)); 1485 CGF.Builder.CreateStore(Exc, RethrowPtr); 1486 CGF.EmitBranchThroughCleanup(FinallyRethrow); 1487 1488 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); 1489 1490 CGF.setInvokeDest(PrevLandingPad); 1491 1492 CGF.EmitBlock(FinallyBlock); 1493 1494 1495 if (isTry) { 1496 if (const ObjCAtFinallyStmt* FinallyStmt = 1497 cast<ObjCAtTryStmt>(S).getFinallyStmt()) 1498 CGF.EmitStmt(FinallyStmt->getFinallyBody()); 1499 } else { 1500 // Emit 'objc_sync_exit(expr)' as finally's sole statement for 1501 // @synchronized. 1502 std::vector<const llvm::Type*> Args(1, IdTy); 1503 llvm::FunctionType *FTy = 1504 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false); 1505 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit"); 1506 llvm::Value *SyncArg = 1507 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 1508 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy); 1509 CGF.Builder.CreateCall(SyncExit, SyncArg); 1510 } 1511 1512 if (Info.SwitchBlock) 1513 CGF.EmitBlock(Info.SwitchBlock); 1514 if (Info.EndBlock) 1515 CGF.EmitBlock(Info.EndBlock); 1516 1517 // Branch around the rethrow code. 1518 CGF.EmitBranch(FinallyEnd); 1519 1520 CGF.EmitBlock(FinallyRethrow); 1521 CGF.Builder.CreateCall(RethrowFn, CGF.Builder.CreateLoad(RethrowPtr)); 1522 CGF.Builder.CreateUnreachable(); 1523 1524 CGF.EmitBlock(FinallyEnd); 1525 1526} 1527 1528void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 1529 const ObjCAtThrowStmt &S) { 1530 llvm::Value *ExceptionAsObject; 1531 1532 std::vector<const llvm::Type*> Args(1, IdTy); 1533 llvm::FunctionType *FTy = 1534 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false); 1535 llvm::Value *ThrowFn = 1536 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw"); 1537 1538 if (const Expr *ThrowExpr = S.getThrowExpr()) { 1539 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr); 1540 ExceptionAsObject = Exception; 1541 } else { 1542 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 1543 "Unexpected rethrow outside @catch block."); 1544 ExceptionAsObject = CGF.ObjCEHValueStack.back(); 1545 } 1546 ExceptionAsObject = 1547 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp"); 1548 1549 // Note: This may have to be an invoke, if we want to support constructs like: 1550 // @try { 1551 // @throw(obj); 1552 // } 1553 // @catch(id) ... 1554 // 1555 // This is effectively turning @throw into an incredibly-expensive goto, but 1556 // it may happen as a result of inlining followed by missed optimizations, or 1557 // as a result of stupidity. 1558 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest(); 1559 if (!UnwindBB) { 1560 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject); 1561 CGF.Builder.CreateUnreachable(); 1562 } else { 1563 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject, 1564 &ExceptionAsObject+1); 1565 } 1566 // Clear the insertion point to indicate we are in unreachable code. 1567 CGF.Builder.ClearInsertionPoint(); 1568} 1569 1570llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 1571 llvm::Value *AddrWeakObj) { 1572 return 0; 1573} 1574 1575void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 1576 llvm::Value *src, llvm::Value *dst) { 1577 return; 1578} 1579 1580void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 1581 llvm::Value *src, llvm::Value *dst) { 1582 return; 1583} 1584 1585void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 1586 llvm::Value *src, llvm::Value *dst) { 1587 return; 1588} 1589 1590void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 1591 llvm::Value *src, llvm::Value *dst) { 1592 return; 1593} 1594 1595void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, 1596 llvm::Value *DestPtr, 1597 llvm::Value *SrcPtr, 1598 QualType Ty) { 1599 return; 1600} 1601 1602llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable( 1603 const ObjCInterfaceDecl *ID, 1604 const ObjCIvarDecl *Ivar) { 1605 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString() 1606 + '.' + Ivar->getNameAsString(); 1607 // Emit the variable and initialize it with what we think the correct value 1608 // is. This allows code compiled with non-fragile ivars to work correctly 1609 // when linked against code which isn't (most of the time). 1610 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name); 1611 if (!IvarOffsetPointer) { 1612 uint64_t Offset = ComputeIvarBaseOffset(CGM, ID, Ivar); 1613 llvm::ConstantInt *OffsetGuess = 1614 llvm::ConstantInt::get(LongTy, Offset, "ivar"); 1615 // Don't emit the guess in non-PIC code because the linker will not be able 1616 // to replace it with the real version for a library. In non-PIC code you 1617 // must compile with the fragile ABI if you want to use ivars from a 1618 // GCC-compiled class. 1619 if (CGM.getLangOptions().PICLevel) { 1620 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule, 1621 llvm::Type::getInt32Ty(VMContext), false, 1622 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess"); 1623 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, 1624 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage, 1625 IvarOffsetGV, Name); 1626 } else { 1627 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, 1628 llvm::PointerType::getUnqual(llvm::Type::getInt32Ty(VMContext)), 1629 false, llvm::GlobalValue::ExternalLinkage, 0, Name); 1630 } 1631 } 1632 return IvarOffsetPointer; 1633} 1634 1635LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 1636 QualType ObjectTy, 1637 llvm::Value *BaseValue, 1638 const ObjCIvarDecl *Ivar, 1639 unsigned CVRQualifiers) { 1640 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl(); 1641 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, 1642 EmitIvarOffset(CGF, ID, Ivar)); 1643} 1644 1645static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context, 1646 const ObjCInterfaceDecl *OID, 1647 const ObjCIvarDecl *OIVD) { 1648 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars; 1649 Context.ShallowCollectObjCIvars(OID, Ivars); 1650 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) { 1651 if (OIVD == Ivars[k]) 1652 return OID; 1653 } 1654 1655 // Otherwise check in the super class. 1656 if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) 1657 return FindIvarInterface(Context, Super, OIVD); 1658 1659 return 0; 1660} 1661 1662llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 1663 const ObjCInterfaceDecl *Interface, 1664 const ObjCIvarDecl *Ivar) { 1665 if (CGM.getLangOptions().ObjCNonFragileABI) { 1666 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar); 1667 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad( 1668 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")); 1669 } 1670 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar); 1671 return llvm::ConstantInt::get(LongTy, Offset, "ivar"); 1672} 1673 1674CodeGen::CGObjCRuntime * 1675CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) { 1676 return new CGObjCGNU(CGM); 1677} 1678