Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGObjCGNU.cpp
35233 views
//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This provides Objective-C code generation targeting the GNU runtime. The9// class in this file generates structures used by the GNU Objective-C runtime10// library. These structures are defined in objc/objc.h and objc/objc-api.h in11// the GNU runtime distribution.12//13//===----------------------------------------------------------------------===//1415#include "CGCXXABI.h"16#include "CGCleanup.h"17#include "CGObjCRuntime.h"18#include "CodeGenFunction.h"19#include "CodeGenModule.h"20#include "CodeGenTypes.h"21#include "SanitizerMetadata.h"22#include "clang/AST/ASTContext.h"23#include "clang/AST/Attr.h"24#include "clang/AST/Decl.h"25#include "clang/AST/DeclObjC.h"26#include "clang/AST/RecordLayout.h"27#include "clang/AST/StmtObjC.h"28#include "clang/Basic/FileManager.h"29#include "clang/Basic/SourceManager.h"30#include "clang/CodeGen/ConstantInitBuilder.h"31#include "llvm/ADT/SmallVector.h"32#include "llvm/ADT/StringMap.h"33#include "llvm/IR/DataLayout.h"34#include "llvm/IR/Intrinsics.h"35#include "llvm/IR/LLVMContext.h"36#include "llvm/IR/Module.h"37#include "llvm/Support/Compiler.h"38#include "llvm/Support/ConvertUTF.h"39#include <cctype>4041using namespace clang;42using namespace CodeGen;4344namespace {4546/// Class that lazily initialises the runtime function. Avoids inserting the47/// types and the function declaration into a module if they're not used, and48/// avoids constructing the type more than once if it's used more than once.49class LazyRuntimeFunction {50CodeGenModule *CGM = nullptr;51llvm::FunctionType *FTy = nullptr;52const char *FunctionName = nullptr;53llvm::FunctionCallee Function = nullptr;5455public:56LazyRuntimeFunction() = default;5758/// Initialises the lazy function with the name, return type, and the types59/// of the arguments.60template <typename... Tys>61void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,62Tys *... Types) {63CGM = Mod;64FunctionName = name;65Function = nullptr;66if(sizeof...(Tys)) {67SmallVector<llvm::Type *, 8> ArgTys({Types...});68FTy = llvm::FunctionType::get(RetTy, ArgTys, false);69}70else {71FTy = llvm::FunctionType::get(RetTy, std::nullopt, false);72}73}7475llvm::FunctionType *getType() { return FTy; }7677/// Overloaded cast operator, allows the class to be implicitly cast to an78/// LLVM constant.79operator llvm::FunctionCallee() {80if (!Function) {81if (!FunctionName)82return nullptr;83Function = CGM->CreateRuntimeFunction(FTy, FunctionName);84}85return Function;86}87};888990/// GNU Objective-C runtime code generation. This class implements the parts of91/// Objective-C support that are specific to the GNU family of runtimes (GCC,92/// GNUstep and ObjFW).93class CGObjCGNU : public CGObjCRuntime {94protected:95/// The LLVM module into which output is inserted96llvm::Module &TheModule;97/// strut objc_super. Used for sending messages to super. This structure98/// contains the receiver (object) and the expected class.99llvm::StructType *ObjCSuperTy;100/// struct objc_super*. The type of the argument to the superclass message101/// lookup functions.102llvm::PointerType *PtrToObjCSuperTy;103/// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring104/// SEL is included in a header somewhere, in which case it will be whatever105/// type is declared in that header, most likely {i8*, i8*}.106llvm::PointerType *SelectorTy;107/// Element type of SelectorTy.108llvm::Type *SelectorElemTy;109/// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the110/// places where it's used111llvm::IntegerType *Int8Ty;112/// Pointer to i8 - LLVM type of char*, for all of the places where the113/// runtime needs to deal with C strings.114llvm::PointerType *PtrToInt8Ty;115/// struct objc_protocol type116llvm::StructType *ProtocolTy;117/// Protocol * type.118llvm::PointerType *ProtocolPtrTy;119/// Instance Method Pointer type. This is a pointer to a function that takes,120/// at a minimum, an object and a selector, and is the generic type for121/// Objective-C methods. Due to differences between variadic / non-variadic122/// calling conventions, it must always be cast to the correct type before123/// actually being used.124llvm::PointerType *IMPTy;125/// Type of an untyped Objective-C object. Clang treats id as a built-in type126/// when compiling Objective-C code, so this may be an opaque pointer (i8*),127/// but if the runtime header declaring it is included then it may be a128/// pointer to a structure.129llvm::PointerType *IdTy;130/// Element type of IdTy.131llvm::Type *IdElemTy;132/// Pointer to a pointer to an Objective-C object. Used in the new ABI133/// message lookup function and some GC-related functions.134llvm::PointerType *PtrToIdTy;135/// The clang type of id. Used when using the clang CGCall infrastructure to136/// call Objective-C methods.137CanQualType ASTIdTy;138/// LLVM type for C int type.139llvm::IntegerType *IntTy;140/// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is141/// used in the code to document the difference between i8* meaning a pointer142/// to a C string and i8* meaning a pointer to some opaque type.143llvm::PointerType *PtrTy;144/// LLVM type for C long type. The runtime uses this in a lot of places where145/// it should be using intptr_t, but we can't fix this without breaking146/// compatibility with GCC...147llvm::IntegerType *LongTy;148/// LLVM type for C size_t. Used in various runtime data structures.149llvm::IntegerType *SizeTy;150/// LLVM type for C intptr_t.151llvm::IntegerType *IntPtrTy;152/// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.153llvm::IntegerType *PtrDiffTy;154/// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance155/// variables.156llvm::PointerType *PtrToIntTy;157/// LLVM type for Objective-C BOOL type.158llvm::Type *BoolTy;159/// 32-bit integer type, to save us needing to look it up every time it's used.160llvm::IntegerType *Int32Ty;161/// 64-bit integer type, to save us needing to look it up every time it's used.162llvm::IntegerType *Int64Ty;163/// The type of struct objc_property.164llvm::StructType *PropertyMetadataTy;165/// Metadata kind used to tie method lookups to message sends. The GNUstep166/// runtime provides some LLVM passes that can use this to do things like167/// automatic IMP caching and speculative inlining.168unsigned msgSendMDKind;169/// Does the current target use SEH-based exceptions? False implies170/// Itanium-style DWARF unwinding.171bool usesSEHExceptions;172/// Does the current target uses C++-based exceptions?173bool usesCxxExceptions;174175/// Helper to check if we are targeting a specific runtime version or later.176bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {177const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;178return (R.getKind() == kind) &&179(R.getVersion() >= VersionTuple(major, minor));180}181182std::string ManglePublicSymbol(StringRef Name) {183return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();184}185186std::string SymbolForProtocol(Twine Name) {187return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();188}189190std::string SymbolForProtocolRef(StringRef Name) {191return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();192}193194195/// Helper function that generates a constant string and returns a pointer to196/// the start of the string. The result of this function can be used anywhere197/// where the C code specifies const char*.198llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {199ConstantAddress Array =200CGM.GetAddrOfConstantCString(std::string(Str), Name);201return Array.getPointer();202}203204/// Emits a linkonce_odr string, whose name is the prefix followed by the205/// string value. This allows the linker to combine the strings between206/// different modules. Used for EH typeinfo names, selector strings, and a207/// few other things.208llvm::Constant *ExportUniqueString(const std::string &Str,209const std::string &prefix,210bool Private=false) {211std::string name = prefix + Str;212auto *ConstStr = TheModule.getGlobalVariable(name);213if (!ConstStr) {214llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);215auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,216llvm::GlobalValue::LinkOnceODRLinkage, value, name);217GV->setComdat(TheModule.getOrInsertComdat(name));218if (Private)219GV->setVisibility(llvm::GlobalValue::HiddenVisibility);220ConstStr = GV;221}222return ConstStr;223}224225/// Returns a property name and encoding string.226llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,227const Decl *Container) {228assert(!isRuntime(ObjCRuntime::GNUstep, 2));229if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {230std::string NameAndAttributes;231std::string TypeStr =232CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);233NameAndAttributes += '\0';234NameAndAttributes += TypeStr.length() + 3;235NameAndAttributes += TypeStr;236NameAndAttributes += '\0';237NameAndAttributes += PD->getNameAsString();238return MakeConstantString(NameAndAttributes);239}240return MakeConstantString(PD->getNameAsString());241}242243/// Push the property attributes into two structure fields.244void PushPropertyAttributes(ConstantStructBuilder &Fields,245const ObjCPropertyDecl *property, bool isSynthesized=true, bool246isDynamic=true) {247int attrs = property->getPropertyAttributes();248// For read-only properties, clear the copy and retain flags249if (attrs & ObjCPropertyAttribute::kind_readonly) {250attrs &= ~ObjCPropertyAttribute::kind_copy;251attrs &= ~ObjCPropertyAttribute::kind_retain;252attrs &= ~ObjCPropertyAttribute::kind_weak;253attrs &= ~ObjCPropertyAttribute::kind_strong;254}255// The first flags field has the same attribute values as clang uses internally256Fields.addInt(Int8Ty, attrs & 0xff);257attrs >>= 8;258attrs <<= 2;259// For protocol properties, synthesized and dynamic have no meaning, so we260// reuse these flags to indicate that this is a protocol property (both set261// has no meaning, as a property can't be both synthesized and dynamic)262attrs |= isSynthesized ? (1<<0) : 0;263attrs |= isDynamic ? (1<<1) : 0;264// The second field is the next four fields left shifted by two, with the265// low bit set to indicate whether the field is synthesized or dynamic.266Fields.addInt(Int8Ty, attrs & 0xff);267// Two padding fields268Fields.addInt(Int8Ty, 0);269Fields.addInt(Int8Ty, 0);270}271272virtual llvm::Constant *GenerateCategoryProtocolList(const273ObjCCategoryDecl *OCD);274virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,275int count) {276// int count;277Fields.addInt(IntTy, count);278// int size; (only in GNUstep v2 ABI.279if (isRuntime(ObjCRuntime::GNUstep, 2)) {280llvm::DataLayout td(&TheModule);281Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /282CGM.getContext().getCharWidth());283}284// struct objc_property_list *next;285Fields.add(NULLPtr);286// struct objc_property properties[]287return Fields.beginArray(PropertyMetadataTy);288}289virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,290const ObjCPropertyDecl *property,291const Decl *OCD,292bool isSynthesized=true, bool293isDynamic=true) {294auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);295ASTContext &Context = CGM.getContext();296Fields.add(MakePropertyEncodingString(property, OCD));297PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);298auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {299if (accessor) {300std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);301llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);302Fields.add(MakeConstantString(accessor->getSelector().getAsString()));303Fields.add(TypeEncoding);304} else {305Fields.add(NULLPtr);306Fields.add(NULLPtr);307}308};309addPropertyMethod(property->getGetterMethodDecl());310addPropertyMethod(property->getSetterMethodDecl());311Fields.finishAndAddTo(PropertiesArray);312}313314/// Ensures that the value has the required type, by inserting a bitcast if315/// required. This function lets us avoid inserting bitcasts that are316/// redundant.317llvm::Value *EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {318if (V->getType() == Ty)319return V;320return B.CreateBitCast(V, Ty);321}322323// Some zeros used for GEPs in lots of places.324llvm::Constant *Zeros[2];325/// Null pointer value. Mainly used as a terminator in various arrays.326llvm::Constant *NULLPtr;327/// LLVM context.328llvm::LLVMContext &VMContext;329330protected:331332/// Placeholder for the class. Lots of things refer to the class before we've333/// actually emitted it. We use this alias as a placeholder, and then replace334/// it with a pointer to the class structure before finally emitting the335/// module.336llvm::GlobalAlias *ClassPtrAlias;337/// Placeholder for the metaclass. Lots of things refer to the class before338/// we've / actually emitted it. We use this alias as a placeholder, and then339/// replace / it with a pointer to the metaclass structure before finally340/// emitting the / module.341llvm::GlobalAlias *MetaClassPtrAlias;342/// All of the classes that have been generated for this compilation units.343std::vector<llvm::Constant*> Classes;344/// All of the categories that have been generated for this compilation units.345std::vector<llvm::Constant*> Categories;346/// All of the Objective-C constant strings that have been generated for this347/// compilation units.348std::vector<llvm::Constant*> ConstantStrings;349/// Map from string values to Objective-C constant strings in the output.350/// Used to prevent emitting Objective-C strings more than once. This should351/// not be required at all - CodeGenModule should manage this list.352llvm::StringMap<llvm::Constant*> ObjCStrings;353/// All of the protocols that have been declared.354llvm::StringMap<llvm::Constant*> ExistingProtocols;355/// For each variant of a selector, we store the type encoding and a356/// placeholder value. For an untyped selector, the type will be the empty357/// string. Selector references are all done via the module's selector table,358/// so we create an alias as a placeholder and then replace it with the real359/// value later.360typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;361/// Type of the selector map. This is roughly equivalent to the structure362/// used in the GNUstep runtime, which maintains a list of all of the valid363/// types for a selector in a table.364typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >365SelectorMap;366/// A map from selectors to selector types. This allows us to emit all367/// selectors of the same name and type together.368SelectorMap SelectorTable;369370/// Selectors related to memory management. When compiling in GC mode, we371/// omit these.372Selector RetainSel, ReleaseSel, AutoreleaseSel;373/// Runtime functions used for memory management in GC mode. Note that clang374/// supports code generation for calling these functions, but neither GNU375/// runtime actually supports this API properly yet.376LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,377WeakAssignFn, GlobalAssignFn;378379typedef std::pair<std::string, std::string> ClassAliasPair;380/// All classes that have aliases set for them.381std::vector<ClassAliasPair> ClassAliases;382383protected:384/// Function used for throwing Objective-C exceptions.385LazyRuntimeFunction ExceptionThrowFn;386/// Function used for rethrowing exceptions, used at the end of \@finally or387/// \@synchronize blocks.388LazyRuntimeFunction ExceptionReThrowFn;389/// Function called when entering a catch function. This is required for390/// differentiating Objective-C exceptions and foreign exceptions.391LazyRuntimeFunction EnterCatchFn;392/// Function called when exiting from a catch block. Used to do exception393/// cleanup.394LazyRuntimeFunction ExitCatchFn;395/// Function called when entering an \@synchronize block. Acquires the lock.396LazyRuntimeFunction SyncEnterFn;397/// Function called when exiting an \@synchronize block. Releases the lock.398LazyRuntimeFunction SyncExitFn;399400private:401/// Function called if fast enumeration detects that the collection is402/// modified during the update.403LazyRuntimeFunction EnumerationMutationFn;404/// Function for implementing synthesized property getters that return an405/// object.406LazyRuntimeFunction GetPropertyFn;407/// Function for implementing synthesized property setters that return an408/// object.409LazyRuntimeFunction SetPropertyFn;410/// Function used for non-object declared property getters.411LazyRuntimeFunction GetStructPropertyFn;412/// Function used for non-object declared property setters.413LazyRuntimeFunction SetStructPropertyFn;414415protected:416/// The version of the runtime that this class targets. Must match the417/// version in the runtime.418int RuntimeVersion;419/// The version of the protocol class. Used to differentiate between ObjC1420/// and ObjC2 protocols. Objective-C 1 protocols can not contain optional421/// components and can not contain declared properties. We always emit422/// Objective-C 2 property structures, but we have to pretend that they're423/// Objective-C 1 property structures when targeting the GCC runtime or it424/// will abort.425const int ProtocolVersion;426/// The version of the class ABI. This value is used in the class structure427/// and indicates how various fields should be interpreted.428const int ClassABIVersion;429/// Generates an instance variable list structure. This is a structure430/// containing a size and an array of structures containing instance variable431/// metadata. This is used purely for introspection in the fragile ABI. In432/// the non-fragile ABI, it's used for instance variable fixup.433virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,434ArrayRef<llvm::Constant *> IvarTypes,435ArrayRef<llvm::Constant *> IvarOffsets,436ArrayRef<llvm::Constant *> IvarAlign,437ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);438439/// Generates a method list structure. This is a structure containing a size440/// and an array of structures containing method metadata.441///442/// This structure is used by both classes and categories, and contains a next443/// pointer allowing them to be chained together in a linked list.444llvm::Constant *GenerateMethodList(StringRef ClassName,445StringRef CategoryName,446ArrayRef<const ObjCMethodDecl*> Methods,447bool isClassMethodList);448449/// Emits an empty protocol. This is used for \@protocol() where no protocol450/// is found. The runtime will (hopefully) fix up the pointer to refer to the451/// real protocol.452virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);453454/// Generates a list of property metadata structures. This follows the same455/// pattern as method and instance variable metadata lists.456llvm::Constant *GeneratePropertyList(const Decl *Container,457const ObjCContainerDecl *OCD,458bool isClassProperty=false,459bool protocolOptionalProperties=false);460461/// Generates a list of referenced protocols. Classes, categories, and462/// protocols all use this structure.463llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);464465/// To ensure that all protocols are seen by the runtime, we add a category on466/// a class defined in the runtime, declaring no methods, but adopting the467/// protocols. This is a horribly ugly hack, but it allows us to collect all468/// of the protocols without changing the ABI.469void GenerateProtocolHolderCategory();470471/// Generates a class structure.472llvm::Constant *GenerateClassStructure(473llvm::Constant *MetaClass,474llvm::Constant *SuperClass,475unsigned info,476const char *Name,477llvm::Constant *Version,478llvm::Constant *InstanceSize,479llvm::Constant *IVars,480llvm::Constant *Methods,481llvm::Constant *Protocols,482llvm::Constant *IvarOffsets,483llvm::Constant *Properties,484llvm::Constant *StrongIvarBitmap,485llvm::Constant *WeakIvarBitmap,486bool isMeta=false);487488/// Generates a method list. This is used by protocols to define the required489/// and optional methods.490virtual llvm::Constant *GenerateProtocolMethodList(491ArrayRef<const ObjCMethodDecl*> Methods);492/// Emits optional and required method lists.493template<class T>494void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,495llvm::Constant *&Optional) {496SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;497SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;498for (const auto *I : Methods)499if (I->isOptional())500OptionalMethods.push_back(I);501else502RequiredMethods.push_back(I);503Required = GenerateProtocolMethodList(RequiredMethods);504Optional = GenerateProtocolMethodList(OptionalMethods);505}506507/// Returns a selector with the specified type encoding. An empty string is508/// used to return an untyped selector (with the types field set to NULL).509virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,510const std::string &TypeEncoding);511512/// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this513/// contains the class and ivar names, in the v2 ABI this contains the type514/// encoding as well.515virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,516const ObjCIvarDecl *Ivar) {517const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()518+ '.' + Ivar->getNameAsString();519return Name;520}521/// Returns the variable used to store the offset of an instance variable.522llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,523const ObjCIvarDecl *Ivar);524/// Emits a reference to a class. This allows the linker to object if there525/// is no class of the matching name.526void EmitClassRef(const std::string &className);527528/// Emits a pointer to the named class529virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,530const std::string &Name, bool isWeak);531532/// Looks up the method for sending a message to the specified object. This533/// mechanism differs between the GCC and GNU runtimes, so this method must be534/// overridden in subclasses.535virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,536llvm::Value *&Receiver,537llvm::Value *cmd,538llvm::MDNode *node,539MessageSendInfo &MSI) = 0;540541/// Looks up the method for sending a message to a superclass. This542/// mechanism differs between the GCC and GNU runtimes, so this method must543/// be overridden in subclasses.544virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,545Address ObjCSuper,546llvm::Value *cmd,547MessageSendInfo &MSI) = 0;548549/// Libobjc2 uses a bitfield representation where small(ish) bitfields are550/// stored in a 64-bit value with the low bit set to 1 and the remaining 63551/// bits set to their values, LSB first, while larger ones are stored in a552/// structure of this / form:553///554/// struct { int32_t length; int32_t values[length]; };555///556/// The values in the array are stored in host-endian format, with the least557/// significant bit being assumed to come first in the bitfield. Therefore,558/// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },559/// while a bitfield / with the 63rd bit set will be 1<<64.560llvm::Constant *MakeBitField(ArrayRef<bool> bits);561562public:563CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,564unsigned protocolClassVersion, unsigned classABI=1);565566ConstantAddress GenerateConstantString(const StringLiteral *) override;567568RValue569GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,570QualType ResultType, Selector Sel,571llvm::Value *Receiver, const CallArgList &CallArgs,572const ObjCInterfaceDecl *Class,573const ObjCMethodDecl *Method) override;574RValue575GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,576QualType ResultType, Selector Sel,577const ObjCInterfaceDecl *Class,578bool isCategoryImpl, llvm::Value *Receiver,579bool IsClassMessage, const CallArgList &CallArgs,580const ObjCMethodDecl *Method) override;581llvm::Value *GetClass(CodeGenFunction &CGF,582const ObjCInterfaceDecl *OID) override;583llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;584Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;585llvm::Value *GetSelector(CodeGenFunction &CGF,586const ObjCMethodDecl *Method) override;587virtual llvm::Constant *GetConstantSelector(Selector Sel,588const std::string &TypeEncoding) {589llvm_unreachable("Runtime unable to generate constant selector");590}591llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {592return GetConstantSelector(M->getSelector(),593CGM.getContext().getObjCEncodingForMethodDecl(M));594}595llvm::Constant *GetEHType(QualType T) override;596597llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,598const ObjCContainerDecl *CD) override;599600// Map to unify direct method definitions.601llvm::DenseMap<const ObjCMethodDecl *, llvm::Function *>602DirectMethodDefinitions;603void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,604const ObjCMethodDecl *OMD,605const ObjCContainerDecl *CD) override;606void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;607void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;608void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;609llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,610const ObjCProtocolDecl *PD) override;611void GenerateProtocol(const ObjCProtocolDecl *PD) override;612613virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD);614615llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override {616return GenerateProtocolRef(PD);617}618619llvm::Function *ModuleInitFunction() override;620llvm::FunctionCallee GetPropertyGetFunction() override;621llvm::FunctionCallee GetPropertySetFunction() override;622llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,623bool copy) override;624llvm::FunctionCallee GetSetStructFunction() override;625llvm::FunctionCallee GetGetStructFunction() override;626llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;627llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;628llvm::FunctionCallee EnumerationMutationFunction() override;629630void EmitTryStmt(CodeGenFunction &CGF,631const ObjCAtTryStmt &S) override;632void EmitSynchronizedStmt(CodeGenFunction &CGF,633const ObjCAtSynchronizedStmt &S) override;634void EmitThrowStmt(CodeGenFunction &CGF,635const ObjCAtThrowStmt &S,636bool ClearInsertionPoint=true) override;637llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,638Address AddrWeakObj) override;639void EmitObjCWeakAssign(CodeGenFunction &CGF,640llvm::Value *src, Address dst) override;641void EmitObjCGlobalAssign(CodeGenFunction &CGF,642llvm::Value *src, Address dest,643bool threadlocal=false) override;644void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,645Address dest, llvm::Value *ivarOffset) override;646void EmitObjCStrongCastAssign(CodeGenFunction &CGF,647llvm::Value *src, Address dest) override;648void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,649Address SrcPtr,650llvm::Value *Size) override;651LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,652llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,653unsigned CVRQualifiers) override;654llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,655const ObjCInterfaceDecl *Interface,656const ObjCIvarDecl *Ivar) override;657llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;658llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,659const CGBlockInfo &blockInfo) override {660return NULLPtr;661}662llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,663const CGBlockInfo &blockInfo) override {664return NULLPtr;665}666667llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {668return NULLPtr;669}670};671672/// Class representing the legacy GCC Objective-C ABI. This is the default when673/// -fobjc-nonfragile-abi is not specified.674///675/// The GCC ABI target actually generates code that is approximately compatible676/// with the new GNUstep runtime ABI, but refrains from using any features that677/// would not work with the GCC runtime. For example, clang always generates678/// the extended form of the class structure, and the extra fields are simply679/// ignored by GCC libobjc.680class CGObjCGCC : public CGObjCGNU {681/// The GCC ABI message lookup function. Returns an IMP pointing to the682/// method implementation for this message.683LazyRuntimeFunction MsgLookupFn;684/// The GCC ABI superclass message lookup function. Takes a pointer to a685/// structure describing the receiver and the class, and a selector as686/// arguments. Returns the IMP for the corresponding method.687LazyRuntimeFunction MsgLookupSuperFn;688689protected:690llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,691llvm::Value *cmd, llvm::MDNode *node,692MessageSendInfo &MSI) override {693CGBuilderTy &Builder = CGF.Builder;694llvm::Value *args[] = {695EnforceType(Builder, Receiver, IdTy),696EnforceType(Builder, cmd, SelectorTy) };697llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);698imp->setMetadata(msgSendMDKind, node);699return imp;700}701702llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,703llvm::Value *cmd, MessageSendInfo &MSI) override {704CGBuilderTy &Builder = CGF.Builder;705llvm::Value *lookupArgs[] = {706EnforceType(Builder, ObjCSuper.emitRawPointer(CGF), PtrToObjCSuperTy),707cmd};708return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);709}710711public:712CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {713// IMP objc_msg_lookup(id, SEL);714MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);715// IMP objc_msg_lookup_super(struct objc_super*, SEL);716MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,717PtrToObjCSuperTy, SelectorTy);718}719};720721/// Class used when targeting the new GNUstep runtime ABI.722class CGObjCGNUstep : public CGObjCGNU {723/// The slot lookup function. Returns a pointer to a cacheable structure724/// that contains (among other things) the IMP.725LazyRuntimeFunction SlotLookupFn;726/// The GNUstep ABI superclass message lookup function. Takes a pointer to727/// a structure describing the receiver and the class, and a selector as728/// arguments. Returns the slot for the corresponding method. Superclass729/// message lookup rarely changes, so this is a good caching opportunity.730LazyRuntimeFunction SlotLookupSuperFn;731/// Specialised function for setting atomic retain properties732LazyRuntimeFunction SetPropertyAtomic;733/// Specialised function for setting atomic copy properties734LazyRuntimeFunction SetPropertyAtomicCopy;735/// Specialised function for setting nonatomic retain properties736LazyRuntimeFunction SetPropertyNonAtomic;737/// Specialised function for setting nonatomic copy properties738LazyRuntimeFunction SetPropertyNonAtomicCopy;739/// Function to perform atomic copies of C++ objects with nontrivial copy740/// constructors from Objective-C ivars.741LazyRuntimeFunction CxxAtomicObjectGetFn;742/// Function to perform atomic copies of C++ objects with nontrivial copy743/// constructors to Objective-C ivars.744LazyRuntimeFunction CxxAtomicObjectSetFn;745/// Type of a slot structure pointer. This is returned by the various746/// lookup functions.747llvm::Type *SlotTy;748/// Type of a slot structure.749llvm::Type *SlotStructTy;750751public:752llvm::Constant *GetEHType(QualType T) override;753754protected:755llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,756llvm::Value *cmd, llvm::MDNode *node,757MessageSendInfo &MSI) override {758CGBuilderTy &Builder = CGF.Builder;759llvm::FunctionCallee LookupFn = SlotLookupFn;760761// Store the receiver on the stack so that we can reload it later762RawAddress ReceiverPtr =763CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());764Builder.CreateStore(Receiver, ReceiverPtr);765766llvm::Value *self;767768if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {769self = CGF.LoadObjCSelf();770} else {771self = llvm::ConstantPointerNull::get(IdTy);772}773774// The lookup function is guaranteed not to capture the receiver pointer.775if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))776LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);777778llvm::Value *args[] = {779EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),780EnforceType(Builder, cmd, SelectorTy),781EnforceType(Builder, self, IdTy)};782llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);783slot->setOnlyReadsMemory();784slot->setMetadata(msgSendMDKind, node);785786// Load the imp from the slot787llvm::Value *imp = Builder.CreateAlignedLoad(788IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),789CGF.getPointerAlign());790791// The lookup function may have changed the receiver, so make sure we use792// the new one.793Receiver = Builder.CreateLoad(ReceiverPtr, true);794return imp;795}796797llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,798llvm::Value *cmd,799MessageSendInfo &MSI) override {800CGBuilderTy &Builder = CGF.Builder;801llvm::Value *lookupArgs[] = {ObjCSuper.emitRawPointer(CGF), cmd};802803llvm::CallInst *slot =804CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);805slot->setOnlyReadsMemory();806807return Builder.CreateAlignedLoad(808IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),809CGF.getPointerAlign());810}811812public:813CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}814CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,815unsigned ClassABI) :816CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {817const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;818819SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);820SlotTy = llvm::PointerType::getUnqual(SlotStructTy);821// Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);822SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,823SelectorTy, IdTy);824// Slot_t objc_slot_lookup_super(struct objc_super*, SEL);825SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,826PtrToObjCSuperTy, SelectorTy);827// If we're in ObjC++ mode, then we want to make828llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);829if (usesCxxExceptions) {830// void *__cxa_begin_catch(void *e)831EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);832// void __cxa_end_catch(void)833ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);834// void objc_exception_rethrow(void*)835ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);836} else if (usesSEHExceptions) {837// void objc_exception_rethrow(void)838ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);839} else if (CGM.getLangOpts().CPlusPlus) {840// void *__cxa_begin_catch(void *e)841EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);842// void __cxa_end_catch(void)843ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);844// void _Unwind_Resume_or_Rethrow(void*)845ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,846PtrTy);847} else if (R.getVersion() >= VersionTuple(1, 7)) {848// id objc_begin_catch(void *e)849EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);850// void objc_end_catch(void)851ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);852// void _Unwind_Resume_or_Rethrow(void*)853ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);854}855SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,856SelectorTy, IdTy, PtrDiffTy);857SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,858IdTy, SelectorTy, IdTy, PtrDiffTy);859SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,860IdTy, SelectorTy, IdTy, PtrDiffTy);861SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",862VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);863// void objc_setCppObjectAtomic(void *dest, const void *src, void864// *helper);865CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,866PtrTy, PtrTy);867// void objc_getCppObjectAtomic(void *dest, const void *src, void868// *helper);869CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,870PtrTy, PtrTy);871}872873llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {874// The optimised functions were added in version 1.7 of the GNUstep875// runtime.876assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=877VersionTuple(1, 7));878return CxxAtomicObjectGetFn;879}880881llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {882// The optimised functions were added in version 1.7 of the GNUstep883// runtime.884assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=885VersionTuple(1, 7));886return CxxAtomicObjectSetFn;887}888889llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,890bool copy) override {891// The optimised property functions omit the GC check, and so are not892// safe to use in GC mode. The standard functions are fast in GC mode,893// so there is less advantage in using them.894assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));895// The optimised functions were added in version 1.7 of the GNUstep896// runtime.897assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=898VersionTuple(1, 7));899900if (atomic) {901if (copy) return SetPropertyAtomicCopy;902return SetPropertyAtomic;903}904905return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;906}907};908909/// GNUstep Objective-C ABI version 2 implementation.910/// This is the ABI that provides a clean break with the legacy GCC ABI and911/// cleans up a number of things that were added to work around 1980s linkers.912class CGObjCGNUstep2 : public CGObjCGNUstep {913enum SectionKind914{915SelectorSection = 0,916ClassSection,917ClassReferenceSection,918CategorySection,919ProtocolSection,920ProtocolReferenceSection,921ClassAliasSection,922ConstantStringSection923};924/// The subset of `objc_class_flags` used at compile time.925enum ClassFlags {926/// This is a metaclass927ClassFlagMeta = (1 << 0),928/// This class has been initialised by the runtime (+initialize has been929/// sent if necessary).930ClassFlagInitialized = (1 << 8),931};932static const char *const SectionsBaseNames[8];933static const char *const PECOFFSectionsBaseNames[8];934template<SectionKind K>935std::string sectionName() {936if (CGM.getTriple().isOSBinFormatCOFF()) {937std::string name(PECOFFSectionsBaseNames[K]);938name += "$m";939return name;940}941return SectionsBaseNames[K];942}943/// The GCC ABI superclass message lookup function. Takes a pointer to a944/// structure describing the receiver and the class, and a selector as945/// arguments. Returns the IMP for the corresponding method.946LazyRuntimeFunction MsgLookupSuperFn;947/// Function to ensure that +initialize is sent to a class.948LazyRuntimeFunction SentInitializeFn;949/// A flag indicating if we've emitted at least one protocol.950/// If we haven't, then we need to emit an empty protocol, to ensure that the951/// __start__objc_protocols and __stop__objc_protocols sections exist.952bool EmittedProtocol = false;953/// A flag indicating if we've emitted at least one protocol reference.954/// If we haven't, then we need to emit an empty protocol, to ensure that the955/// __start__objc_protocol_refs and __stop__objc_protocol_refs sections956/// exist.957bool EmittedProtocolRef = false;958/// A flag indicating if we've emitted at least one class.959/// If we haven't, then we need to emit an empty protocol, to ensure that the960/// __start__objc_classes and __stop__objc_classes sections / exist.961bool EmittedClass = false;962/// Generate the name of a symbol for a reference to a class. Accesses to963/// classes should be indirected via this.964965typedef std::pair<std::string, std::pair<llvm::GlobalVariable*, int>>966EarlyInitPair;967std::vector<EarlyInitPair> EarlyInitList;968969std::string SymbolForClassRef(StringRef Name, bool isWeak) {970if (isWeak)971return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();972else973return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();974}975/// Generate the name of a class symbol.976std::string SymbolForClass(StringRef Name) {977return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();978}979void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,980ArrayRef<llvm::Value*> Args) {981SmallVector<llvm::Type *,8> Types;982for (auto *Arg : Args)983Types.push_back(Arg->getType());984llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,985false);986llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);987B.CreateCall(Fn, Args);988}989990ConstantAddress GenerateConstantString(const StringLiteral *SL) override {991992auto Str = SL->getString();993CharUnits Align = CGM.getPointerAlign();994995// Look for an existing one996llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);997if (old != ObjCStrings.end())998return ConstantAddress(old->getValue(), IdElemTy, Align);9991000bool isNonASCII = SL->containsNonAscii();10011002auto LiteralLength = SL->getLength();10031004if ((CGM.getTarget().getPointerWidth(LangAS::Default) == 64) &&1005(LiteralLength < 9) && !isNonASCII) {1006// Tiny strings are only used on 64-bit platforms. They store 8 7-bit1007// ASCII characters in the high 56 bits, followed by a 4-bit length and a1008// 3-bit tag (which is always 4).1009uint64_t str = 0;1010// Fill in the characters1011for (unsigned i=0 ; i<LiteralLength ; i++)1012str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));1013// Fill in the length1014str |= LiteralLength << 3;1015// Set the tag1016str |= 4;1017auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(1018llvm::ConstantInt::get(Int64Ty, str), IdTy);1019ObjCStrings[Str] = ObjCStr;1020return ConstantAddress(ObjCStr, IdElemTy, Align);1021}10221023StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;10241025if (StringClass.empty()) StringClass = "NSConstantString";10261027std::string Sym = SymbolForClass(StringClass);10281029llvm::Constant *isa = TheModule.getNamedGlobal(Sym);10301031if (!isa) {1032isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,1033llvm::GlobalValue::ExternalLinkage, nullptr, Sym);1034if (CGM.getTriple().isOSBinFormatCOFF()) {1035cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);1036}1037}10381039// struct1040// {1041// Class isa;1042// uint32_t flags;1043// uint32_t length; // Number of codepoints1044// uint32_t size; // Number of bytes1045// uint32_t hash;1046// const char *data;1047// };10481049ConstantInitBuilder Builder(CGM);1050auto Fields = Builder.beginStruct();1051if (!CGM.getTriple().isOSBinFormatCOFF()) {1052Fields.add(isa);1053} else {1054Fields.addNullPointer(PtrTy);1055}1056// For now, all non-ASCII strings are represented as UTF-16. As such, the1057// number of bytes is simply double the number of UTF-16 codepoints. In1058// ASCII strings, the number of bytes is equal to the number of non-ASCII1059// codepoints.1060if (isNonASCII) {1061unsigned NumU8CodeUnits = Str.size();1062// A UTF-16 representation of a unicode string contains at most the same1063// number of code units as a UTF-8 representation. Allocate that much1064// space, plus one for the final null character.1065SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);1066const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();1067llvm::UTF16 *ToPtr = &ToBuf[0];1068(void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,1069&ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);1070uint32_t StringLength = ToPtr - &ToBuf[0];1071// Add null terminator1072*ToPtr = 0;1073// Flags: 2 indicates UTF-16 encoding1074Fields.addInt(Int32Ty, 2);1075// Number of UTF-16 codepoints1076Fields.addInt(Int32Ty, StringLength);1077// Number of bytes1078Fields.addInt(Int32Ty, StringLength * 2);1079// Hash. Not currently initialised by the compiler.1080Fields.addInt(Int32Ty, 0);1081// pointer to the data string.1082auto Arr = llvm::ArrayRef(&ToBuf[0], ToPtr + 1);1083auto *C = llvm::ConstantDataArray::get(VMContext, Arr);1084auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),1085/*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");1086Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);1087Fields.add(Buffer);1088} else {1089// Flags: 0 indicates ASCII encoding1090Fields.addInt(Int32Ty, 0);1091// Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint1092Fields.addInt(Int32Ty, Str.size());1093// Number of bytes1094Fields.addInt(Int32Ty, Str.size());1095// Hash. Not currently initialised by the compiler.1096Fields.addInt(Int32Ty, 0);1097// Data pointer1098Fields.add(MakeConstantString(Str));1099}1100std::string StringName;1101bool isNamed = !isNonASCII;1102if (isNamed) {1103StringName = ".objc_str_";1104for (int i=0,e=Str.size() ; i<e ; ++i) {1105unsigned char c = Str[i];1106if (isalnum(c))1107StringName += c;1108else if (c == ' ')1109StringName += '_';1110else {1111isNamed = false;1112break;1113}1114}1115}1116llvm::GlobalVariable *ObjCStrGV =1117Fields.finishAndCreateGlobal(1118isNamed ? StringRef(StringName) : ".objc_string",1119Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage1120: llvm::GlobalValue::PrivateLinkage);1121ObjCStrGV->setSection(sectionName<ConstantStringSection>());1122if (isNamed) {1123ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));1124ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);1125}1126if (CGM.getTriple().isOSBinFormatCOFF()) {1127std::pair<llvm::GlobalVariable*, int> v{ObjCStrGV, 0};1128EarlyInitList.emplace_back(Sym, v);1129}1130ObjCStrings[Str] = ObjCStrGV;1131ConstantStrings.push_back(ObjCStrGV);1132return ConstantAddress(ObjCStrGV, IdElemTy, Align);1133}11341135void PushProperty(ConstantArrayBuilder &PropertiesArray,1136const ObjCPropertyDecl *property,1137const Decl *OCD,1138bool isSynthesized=true, bool1139isDynamic=true) override {1140// struct objc_property1141// {1142// const char *name;1143// const char *attributes;1144// const char *type;1145// SEL getter;1146// SEL setter;1147// };1148auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);1149ASTContext &Context = CGM.getContext();1150Fields.add(MakeConstantString(property->getNameAsString()));1151std::string TypeStr =1152CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);1153Fields.add(MakeConstantString(TypeStr));1154std::string typeStr;1155Context.getObjCEncodingForType(property->getType(), typeStr);1156Fields.add(MakeConstantString(typeStr));1157auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {1158if (accessor) {1159std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);1160Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));1161} else {1162Fields.add(NULLPtr);1163}1164};1165addPropertyMethod(property->getGetterMethodDecl());1166addPropertyMethod(property->getSetterMethodDecl());1167Fields.finishAndAddTo(PropertiesArray);1168}11691170llvm::Constant *1171GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {1172// struct objc_protocol_method_description1173// {1174// SEL selector;1175// const char *types;1176// };1177llvm::StructType *ObjCMethodDescTy =1178llvm::StructType::get(CGM.getLLVMContext(),1179{ PtrToInt8Ty, PtrToInt8Ty });1180ASTContext &Context = CGM.getContext();1181ConstantInitBuilder Builder(CGM);1182// struct objc_protocol_method_description_list1183// {1184// int count;1185// int size;1186// struct objc_protocol_method_description methods[];1187// };1188auto MethodList = Builder.beginStruct();1189// int count;1190MethodList.addInt(IntTy, Methods.size());1191// int size; // sizeof(struct objc_method_description)1192llvm::DataLayout td(&TheModule);1193MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /1194CGM.getContext().getCharWidth());1195// struct objc_method_description[]1196auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);1197for (auto *M : Methods) {1198auto Method = MethodArray.beginStruct(ObjCMethodDescTy);1199Method.add(CGObjCGNU::GetConstantSelector(M));1200Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));1201Method.finishAndAddTo(MethodArray);1202}1203MethodArray.finishAndAddTo(MethodList);1204return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",1205CGM.getPointerAlign());1206}1207llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)1208override {1209const auto &ReferencedProtocols = OCD->getReferencedProtocols();1210auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),1211ReferencedProtocols.end());1212SmallVector<llvm::Constant *, 16> Protocols;1213for (const auto *PI : RuntimeProtocols)1214Protocols.push_back(GenerateProtocolRef(PI));1215return GenerateProtocolList(Protocols);1216}12171218llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,1219llvm::Value *cmd, MessageSendInfo &MSI) override {1220// Don't access the slot unless we're trying to cache the result.1221CGBuilderTy &Builder = CGF.Builder;1222llvm::Value *lookupArgs[] = {1223CGObjCGNU::EnforceType(Builder, ObjCSuper.emitRawPointer(CGF),1224PtrToObjCSuperTy),1225cmd};1226return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);1227}12281229llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {1230std::string SymbolName = SymbolForClassRef(Name, isWeak);1231auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);1232if (ClassSymbol)1233return ClassSymbol;1234ClassSymbol = new llvm::GlobalVariable(TheModule,1235IdTy, false, llvm::GlobalValue::ExternalLinkage,1236nullptr, SymbolName);1237// If this is a weak symbol, then we are creating a valid definition for1238// the symbol, pointing to a weak definition of the real class pointer. If1239// this is not a weak reference, then we are expecting another compilation1240// unit to provide the real indirection symbol.1241if (isWeak)1242ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,1243Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,1244nullptr, SymbolForClass(Name)));1245else {1246if (CGM.getTriple().isOSBinFormatCOFF()) {1247IdentifierInfo &II = CGM.getContext().Idents.get(Name);1248TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();1249DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);12501251const ObjCInterfaceDecl *OID = nullptr;1252for (const auto *Result : DC->lookup(&II))1253if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))1254break;12551256// The first Interface we find may be a @class,1257// which should only be treated as the source of1258// truth in the absence of a true declaration.1259assert(OID && "Failed to find ObjCInterfaceDecl");1260const ObjCInterfaceDecl *OIDDef = OID->getDefinition();1261if (OIDDef != nullptr)1262OID = OIDDef;12631264auto Storage = llvm::GlobalValue::DefaultStorageClass;1265if (OID->hasAttr<DLLImportAttr>())1266Storage = llvm::GlobalValue::DLLImportStorageClass;1267else if (OID->hasAttr<DLLExportAttr>())1268Storage = llvm::GlobalValue::DLLExportStorageClass;12691270cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);1271}1272}1273assert(ClassSymbol->getName() == SymbolName);1274return ClassSymbol;1275}1276llvm::Value *GetClassNamed(CodeGenFunction &CGF,1277const std::string &Name,1278bool isWeak) override {1279return CGF.Builder.CreateLoad(1280Address(GetClassVar(Name, isWeak), IdTy, CGM.getPointerAlign()));1281}1282int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {1283// typedef enum {1284// ownership_invalid = 0,1285// ownership_strong = 1,1286// ownership_weak = 2,1287// ownership_unsafe = 31288// } ivar_ownership;1289int Flag;1290switch (Ownership) {1291case Qualifiers::OCL_Strong:1292Flag = 1;1293break;1294case Qualifiers::OCL_Weak:1295Flag = 2;1296break;1297case Qualifiers::OCL_ExplicitNone:1298Flag = 3;1299break;1300case Qualifiers::OCL_None:1301case Qualifiers::OCL_Autoreleasing:1302assert(Ownership != Qualifiers::OCL_Autoreleasing);1303Flag = 0;1304}1305return Flag;1306}1307llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,1308ArrayRef<llvm::Constant *> IvarTypes,1309ArrayRef<llvm::Constant *> IvarOffsets,1310ArrayRef<llvm::Constant *> IvarAlign,1311ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {1312llvm_unreachable("Method should not be called!");1313}13141315llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {1316std::string Name = SymbolForProtocol(ProtocolName);1317auto *GV = TheModule.getGlobalVariable(Name);1318if (!GV) {1319// Emit a placeholder symbol.1320GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,1321llvm::GlobalValue::ExternalLinkage, nullptr, Name);1322GV->setAlignment(CGM.getPointerAlign().getAsAlign());1323}1324return GV;1325}13261327/// Existing protocol references.1328llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;13291330llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,1331const ObjCProtocolDecl *PD) override {1332auto Name = PD->getNameAsString();1333auto *&Ref = ExistingProtocolRefs[Name];1334if (!Ref) {1335auto *&Protocol = ExistingProtocols[Name];1336if (!Protocol)1337Protocol = GenerateProtocolRef(PD);1338std::string RefName = SymbolForProtocolRef(Name);1339assert(!TheModule.getGlobalVariable(RefName));1340// Emit a reference symbol.1341auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy, false,1342llvm::GlobalValue::LinkOnceODRLinkage,1343Protocol, RefName);1344GV->setComdat(TheModule.getOrInsertComdat(RefName));1345GV->setSection(sectionName<ProtocolReferenceSection>());1346GV->setAlignment(CGM.getPointerAlign().getAsAlign());1347Ref = GV;1348}1349EmittedProtocolRef = true;1350return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,1351CGM.getPointerAlign());1352}13531354llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {1355llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,1356Protocols.size());1357llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,1358Protocols);1359ConstantInitBuilder builder(CGM);1360auto ProtocolBuilder = builder.beginStruct();1361ProtocolBuilder.addNullPointer(PtrTy);1362ProtocolBuilder.addInt(SizeTy, Protocols.size());1363ProtocolBuilder.add(ProtocolArray);1364return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",1365CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);1366}13671368void GenerateProtocol(const ObjCProtocolDecl *PD) override {1369// Do nothing - we only emit referenced protocols.1370}1371llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {1372std::string ProtocolName = PD->getNameAsString();1373auto *&Protocol = ExistingProtocols[ProtocolName];1374if (Protocol)1375return Protocol;13761377EmittedProtocol = true;13781379auto SymName = SymbolForProtocol(ProtocolName);1380auto *OldGV = TheModule.getGlobalVariable(SymName);13811382// Use the protocol definition, if there is one.1383if (const ObjCProtocolDecl *Def = PD->getDefinition())1384PD = Def;1385else {1386// If there is no definition, then create an external linkage symbol and1387// hope that someone else fills it in for us (and fail to link if they1388// don't).1389assert(!OldGV);1390Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,1391/*isConstant*/false,1392llvm::GlobalValue::ExternalLinkage, nullptr, SymName);1393return Protocol;1394}13951396SmallVector<llvm::Constant*, 16> Protocols;1397auto RuntimeProtocols =1398GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());1399for (const auto *PI : RuntimeProtocols)1400Protocols.push_back(GenerateProtocolRef(PI));1401llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);14021403// Collect information about methods1404llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;1405llvm::Constant *ClassMethodList, *OptionalClassMethodList;1406EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,1407OptionalInstanceMethodList);1408EmitProtocolMethodList(PD->class_methods(), ClassMethodList,1409OptionalClassMethodList);14101411// The isa pointer must be set to a magic number so the runtime knows it's1412// the correct layout.1413ConstantInitBuilder builder(CGM);1414auto ProtocolBuilder = builder.beginStruct();1415ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(1416llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));1417ProtocolBuilder.add(MakeConstantString(ProtocolName));1418ProtocolBuilder.add(ProtocolList);1419ProtocolBuilder.add(InstanceMethodList);1420ProtocolBuilder.add(ClassMethodList);1421ProtocolBuilder.add(OptionalInstanceMethodList);1422ProtocolBuilder.add(OptionalClassMethodList);1423// Required instance properties1424ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));1425// Optional instance properties1426ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));1427// Required class properties1428ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));1429// Optional class properties1430ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));14311432auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,1433CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);1434GV->setSection(sectionName<ProtocolSection>());1435GV->setComdat(TheModule.getOrInsertComdat(SymName));1436if (OldGV) {1437OldGV->replaceAllUsesWith(GV);1438OldGV->removeFromParent();1439GV->setName(SymName);1440}1441Protocol = GV;1442return GV;1443}1444llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,1445const std::string &TypeEncoding) override {1446return GetConstantSelector(Sel, TypeEncoding);1447}1448std::string GetSymbolNameForTypeEncoding(const std::string &TypeEncoding) {1449std::string MangledTypes = std::string(TypeEncoding);1450// @ is used as a special character in ELF symbol names (used for symbol1451// versioning), so mangle the name to not include it. Replace it with a1452// character that is not a valid type encoding character (and, being1453// non-printable, never will be!)1454if (CGM.getTriple().isOSBinFormatELF())1455std::replace(MangledTypes.begin(), MangledTypes.end(), '@', '\1');1456// = in dll exported names causes lld to fail when linking on Windows.1457if (CGM.getTriple().isOSWindows())1458std::replace(MangledTypes.begin(), MangledTypes.end(), '=', '\2');1459return MangledTypes;1460}1461llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {1462if (TypeEncoding.empty())1463return NULLPtr;1464std::string MangledTypes =1465GetSymbolNameForTypeEncoding(std::string(TypeEncoding));1466std::string TypesVarName = ".objc_sel_types_" + MangledTypes;1467auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);1468if (!TypesGlobal) {1469llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,1470TypeEncoding);1471auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),1472true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);1473GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));1474GV->setVisibility(llvm::GlobalValue::HiddenVisibility);1475TypesGlobal = GV;1476}1477return TypesGlobal;1478}1479llvm::Constant *GetConstantSelector(Selector Sel,1480const std::string &TypeEncoding) override {1481std::string MangledTypes = GetSymbolNameForTypeEncoding(TypeEncoding);1482auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +1483MangledTypes).str();1484if (auto *GV = TheModule.getNamedGlobal(SelVarName))1485return GV;1486ConstantInitBuilder builder(CGM);1487auto SelBuilder = builder.beginStruct();1488SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",1489true));1490SelBuilder.add(GetTypeString(TypeEncoding));1491auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,1492CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);1493GV->setComdat(TheModule.getOrInsertComdat(SelVarName));1494GV->setVisibility(llvm::GlobalValue::HiddenVisibility);1495GV->setSection(sectionName<SelectorSection>());1496return GV;1497}1498llvm::StructType *emptyStruct = nullptr;14991500/// Return pointers to the start and end of a section. On ELF platforms, we1501/// use the __start_ and __stop_ symbols that GNU-compatible linkers will set1502/// to the start and end of section names, as long as those section names are1503/// valid identifiers and the symbols are referenced but not defined. On1504/// Windows, we use the fact that MSVC-compatible linkers will lexically sort1505/// by subsections and place everything that we want to reference in a middle1506/// subsection and then insert zero-sized symbols in subsections a and z.1507std::pair<llvm::Constant*,llvm::Constant*>1508GetSectionBounds(StringRef Section) {1509if (CGM.getTriple().isOSBinFormatCOFF()) {1510if (emptyStruct == nullptr) {1511emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");1512emptyStruct->setBody({}, /*isPacked*/true);1513}1514auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);1515auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {1516auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,1517/*isConstant*/false,1518llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +1519Section);1520Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);1521Sym->setSection((Section + SecSuffix).str());1522Sym->setComdat(TheModule.getOrInsertComdat((Prefix +1523Section).str()));1524Sym->setAlignment(CGM.getPointerAlign().getAsAlign());1525return Sym;1526};1527return { Sym("__start_", "$a"), Sym("__stop", "$z") };1528}1529auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,1530/*isConstant*/false,1531llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +1532Section);1533Start->setVisibility(llvm::GlobalValue::HiddenVisibility);1534auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,1535/*isConstant*/false,1536llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +1537Section);1538Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);1539return { Start, Stop };1540}1541CatchTypeInfo getCatchAllTypeInfo() override {1542return CGM.getCXXABI().getCatchAllTypeInfo();1543}1544llvm::Function *ModuleInitFunction() override {1545llvm::Function *LoadFunction = llvm::Function::Create(1546llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),1547llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",1548&TheModule);1549LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);1550LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));15511552llvm::BasicBlock *EntryBB =1553llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);1554CGBuilderTy B(CGM, VMContext);1555B.SetInsertPoint(EntryBB);1556ConstantInitBuilder builder(CGM);1557auto InitStructBuilder = builder.beginStruct();1558InitStructBuilder.addInt(Int64Ty, 0);1559auto §ionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;1560for (auto *s : sectionVec) {1561auto bounds = GetSectionBounds(s);1562InitStructBuilder.add(bounds.first);1563InitStructBuilder.add(bounds.second);1564}1565auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",1566CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);1567InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);1568InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));15691570CallRuntimeFunction(B, "__objc_load", {InitStruct});;1571B.CreateRetVoid();1572// Make sure that the optimisers don't delete this function.1573CGM.addCompilerUsedGlobal(LoadFunction);1574// FIXME: Currently ELF only!1575// We have to do this by hand, rather than with @llvm.ctors, so that the1576// linker can remove the duplicate invocations.1577auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),1578/*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,1579LoadFunction, ".objc_ctor");1580// Check that this hasn't been renamed. This shouldn't happen, because1581// this function should be called precisely once.1582assert(InitVar->getName() == ".objc_ctor");1583// In Windows, initialisers are sorted by the suffix. XCL is for library1584// initialisers, which run before user initialisers. We are running1585// Objective-C loads at the end of library load. This means +load methods1586// will run before any other static constructors, but that static1587// constructors can see a fully initialised Objective-C state.1588if (CGM.getTriple().isOSBinFormatCOFF())1589InitVar->setSection(".CRT$XCLz");1590else1591{1592if (CGM.getCodeGenOpts().UseInitArray)1593InitVar->setSection(".init_array");1594else1595InitVar->setSection(".ctors");1596}1597InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);1598InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));1599CGM.addUsedGlobal(InitVar);1600for (auto *C : Categories) {1601auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());1602Cat->setSection(sectionName<CategorySection>());1603CGM.addUsedGlobal(Cat);1604}1605auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,1606StringRef Section) {1607auto nullBuilder = builder.beginStruct();1608for (auto *F : Init)1609nullBuilder.add(F);1610auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),1611false, llvm::GlobalValue::LinkOnceODRLinkage);1612GV->setSection(Section);1613GV->setComdat(TheModule.getOrInsertComdat(Name));1614GV->setVisibility(llvm::GlobalValue::HiddenVisibility);1615CGM.addUsedGlobal(GV);1616return GV;1617};1618for (auto clsAlias : ClassAliases)1619createNullGlobal(std::string(".objc_class_alias") +1620clsAlias.second, { MakeConstantString(clsAlias.second),1621GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());1622// On ELF platforms, add a null value for each special section so that we1623// can always guarantee that the _start and _stop symbols will exist and be1624// meaningful. This is not required on COFF platforms, where our start and1625// stop symbols will create the section.1626if (!CGM.getTriple().isOSBinFormatCOFF()) {1627createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},1628sectionName<SelectorSection>());1629if (Categories.empty())1630createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,1631NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},1632sectionName<CategorySection>());1633if (!EmittedClass) {1634createNullGlobal(".objc_null_cls_init_ref", NULLPtr,1635sectionName<ClassSection>());1636createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },1637sectionName<ClassReferenceSection>());1638}1639if (!EmittedProtocol)1640createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,1641NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,1642NULLPtr}, sectionName<ProtocolSection>());1643if (!EmittedProtocolRef)1644createNullGlobal(".objc_null_protocol_ref", {NULLPtr},1645sectionName<ProtocolReferenceSection>());1646if (ClassAliases.empty())1647createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },1648sectionName<ClassAliasSection>());1649if (ConstantStrings.empty()) {1650auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);1651createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,1652i32Zero, i32Zero, i32Zero, NULLPtr },1653sectionName<ConstantStringSection>());1654}1655}1656ConstantStrings.clear();1657Categories.clear();1658Classes.clear();16591660if (EarlyInitList.size() > 0) {1661auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,1662{}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",1663&CGM.getModule());1664llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",1665Init));1666for (const auto &lateInit : EarlyInitList) {1667auto *global = TheModule.getGlobalVariable(lateInit.first);1668if (global) {1669llvm::GlobalVariable *GV = lateInit.second.first;1670b.CreateAlignedStore(1671global,1672b.CreateStructGEP(GV->getValueType(), GV, lateInit.second.second),1673CGM.getPointerAlign().getAsAlign());1674}1675}1676b.CreateRetVoid();1677// We can't use the normal LLVM global initialisation array, because we1678// need to specify that this runs early in library initialisation.1679auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),1680/*isConstant*/true, llvm::GlobalValue::InternalLinkage,1681Init, ".objc_early_init_ptr");1682InitVar->setSection(".CRT$XCLb");1683CGM.addUsedGlobal(InitVar);1684}1685return nullptr;1686}1687/// In the v2 ABI, ivar offset variables use the type encoding in their name1688/// to trigger linker failures if the types don't match.1689std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,1690const ObjCIvarDecl *Ivar) override {1691std::string TypeEncoding;1692CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);1693TypeEncoding = GetSymbolNameForTypeEncoding(TypeEncoding);1694const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()1695+ '.' + Ivar->getNameAsString() + '.' + TypeEncoding;1696return Name;1697}1698llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,1699const ObjCInterfaceDecl *Interface,1700const ObjCIvarDecl *Ivar) override {1701const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);1702llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);1703if (!IvarOffsetPointer)1704IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,1705llvm::GlobalValue::ExternalLinkage, nullptr, Name);1706CharUnits Align = CGM.getIntAlign();1707llvm::Value *Offset =1708CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);1709if (Offset->getType() != PtrDiffTy)1710Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);1711return Offset;1712}1713void GenerateClass(const ObjCImplementationDecl *OID) override {1714ASTContext &Context = CGM.getContext();1715bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();17161717// Get the class name1718ObjCInterfaceDecl *classDecl =1719const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());1720std::string className = classDecl->getNameAsString();1721auto *classNameConstant = MakeConstantString(className);17221723ConstantInitBuilder builder(CGM);1724auto metaclassFields = builder.beginStruct();1725// struct objc_class *isa;1726metaclassFields.addNullPointer(PtrTy);1727// struct objc_class *super_class;1728metaclassFields.addNullPointer(PtrTy);1729// const char *name;1730metaclassFields.add(classNameConstant);1731// long version;1732metaclassFields.addInt(LongTy, 0);1733// unsigned long info;1734// objc_class_flag_meta1735metaclassFields.addInt(LongTy, ClassFlags::ClassFlagMeta);1736// long instance_size;1737// Setting this to zero is consistent with the older ABI, but it might be1738// more sensible to set this to sizeof(struct objc_class)1739metaclassFields.addInt(LongTy, 0);1740// struct objc_ivar_list *ivars;1741metaclassFields.addNullPointer(PtrTy);1742// struct objc_method_list *methods1743// FIXME: Almost identical code is copied and pasted below for the1744// class, but refactoring it cleanly requires C++14 generic lambdas.1745if (OID->classmeth_begin() == OID->classmeth_end())1746metaclassFields.addNullPointer(PtrTy);1747else {1748SmallVector<ObjCMethodDecl*, 16> ClassMethods;1749ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),1750OID->classmeth_end());1751metaclassFields.add(1752GenerateMethodList(className, "", ClassMethods, true));1753}1754// void *dtable;1755metaclassFields.addNullPointer(PtrTy);1756// IMP cxx_construct;1757metaclassFields.addNullPointer(PtrTy);1758// IMP cxx_destruct;1759metaclassFields.addNullPointer(PtrTy);1760// struct objc_class *subclass_list1761metaclassFields.addNullPointer(PtrTy);1762// struct objc_class *sibling_class1763metaclassFields.addNullPointer(PtrTy);1764// struct objc_protocol_list *protocols;1765metaclassFields.addNullPointer(PtrTy);1766// struct reference_list *extra_data;1767metaclassFields.addNullPointer(PtrTy);1768// long abi_version;1769metaclassFields.addInt(LongTy, 0);1770// struct objc_property_list *properties1771metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));17721773auto *metaclass = metaclassFields.finishAndCreateGlobal(1774ManglePublicSymbol("OBJC_METACLASS_") + className,1775CGM.getPointerAlign());17761777auto classFields = builder.beginStruct();1778// struct objc_class *isa;1779classFields.add(metaclass);1780// struct objc_class *super_class;1781// Get the superclass name.1782const ObjCInterfaceDecl * SuperClassDecl =1783OID->getClassInterface()->getSuperClass();1784llvm::Constant *SuperClass = nullptr;1785if (SuperClassDecl) {1786auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());1787SuperClass = TheModule.getNamedGlobal(SuperClassName);1788if (!SuperClass)1789{1790SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,1791llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);1792if (IsCOFF) {1793auto Storage = llvm::GlobalValue::DefaultStorageClass;1794if (SuperClassDecl->hasAttr<DLLImportAttr>())1795Storage = llvm::GlobalValue::DLLImportStorageClass;1796else if (SuperClassDecl->hasAttr<DLLExportAttr>())1797Storage = llvm::GlobalValue::DLLExportStorageClass;17981799cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);1800}1801}1802if (!IsCOFF)1803classFields.add(SuperClass);1804else1805classFields.addNullPointer(PtrTy);1806} else1807classFields.addNullPointer(PtrTy);1808// const char *name;1809classFields.add(classNameConstant);1810// long version;1811classFields.addInt(LongTy, 0);1812// unsigned long info;1813// !objc_class_flag_meta1814classFields.addInt(LongTy, 0);1815// long instance_size;1816int superInstanceSize = !SuperClassDecl ? 0 :1817Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();1818// Instance size is negative for classes that have not yet had their ivar1819// layout calculated.1820classFields.addInt(LongTy,18210 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -1822superInstanceSize));18231824if (classDecl->all_declared_ivar_begin() == nullptr)1825classFields.addNullPointer(PtrTy);1826else {1827int ivar_count = 0;1828for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;1829IVD = IVD->getNextIvar()) ivar_count++;1830llvm::DataLayout td(&TheModule);1831// struct objc_ivar_list *ivars;1832ConstantInitBuilder b(CGM);1833auto ivarListBuilder = b.beginStruct();1834// int count;1835ivarListBuilder.addInt(IntTy, ivar_count);1836// size_t size;1837llvm::StructType *ObjCIvarTy = llvm::StructType::get(1838PtrToInt8Ty,1839PtrToInt8Ty,1840PtrToInt8Ty,1841Int32Ty,1842Int32Ty);1843ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /1844CGM.getContext().getCharWidth());1845// struct objc_ivar ivars[]1846auto ivarArrayBuilder = ivarListBuilder.beginArray();1847for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;1848IVD = IVD->getNextIvar()) {1849auto ivarTy = IVD->getType();1850auto ivarBuilder = ivarArrayBuilder.beginStruct();1851// const char *name;1852ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));1853// const char *type;1854std::string TypeStr;1855//Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);1856Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);1857ivarBuilder.add(MakeConstantString(TypeStr));1858// int *offset;1859uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);1860uint64_t Offset = BaseOffset - superInstanceSize;1861llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);1862std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);1863llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);1864if (OffsetVar)1865OffsetVar->setInitializer(OffsetValue);1866else1867OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,1868false, llvm::GlobalValue::ExternalLinkage,1869OffsetValue, OffsetName);1870auto ivarVisibility =1871(IVD->getAccessControl() == ObjCIvarDecl::Private ||1872IVD->getAccessControl() == ObjCIvarDecl::Package ||1873classDecl->getVisibility() == HiddenVisibility) ?1874llvm::GlobalValue::HiddenVisibility :1875llvm::GlobalValue::DefaultVisibility;1876OffsetVar->setVisibility(ivarVisibility);1877if (ivarVisibility != llvm::GlobalValue::HiddenVisibility)1878CGM.setGVProperties(OffsetVar, OID->getClassInterface());1879ivarBuilder.add(OffsetVar);1880// Ivar size1881ivarBuilder.addInt(Int32Ty,1882CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());1883// Alignment will be stored as a base-2 log of the alignment.1884unsigned align =1885llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());1886// Objects that require more than 2^64-byte alignment should be impossible!1887assert(align < 64);1888// uint32_t flags;1889// Bits 0-1 are ownership.1890// Bit 2 indicates an extended type encoding1891// Bits 3-8 contain log2(aligment)1892ivarBuilder.addInt(Int32Ty,1893(align << 3) | (1<<2) |1894FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));1895ivarBuilder.finishAndAddTo(ivarArrayBuilder);1896}1897ivarArrayBuilder.finishAndAddTo(ivarListBuilder);1898auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",1899CGM.getPointerAlign(), /*constant*/ false,1900llvm::GlobalValue::PrivateLinkage);1901classFields.add(ivarList);1902}1903// struct objc_method_list *methods1904SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;1905InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),1906OID->instmeth_end());1907for (auto *propImpl : OID->property_impls())1908if (propImpl->getPropertyImplementation() ==1909ObjCPropertyImplDecl::Synthesize) {1910auto addIfExists = [&](const ObjCMethodDecl *OMD) {1911if (OMD && OMD->hasBody())1912InstanceMethods.push_back(OMD);1913};1914addIfExists(propImpl->getGetterMethodDecl());1915addIfExists(propImpl->getSetterMethodDecl());1916}19171918if (InstanceMethods.size() == 0)1919classFields.addNullPointer(PtrTy);1920else1921classFields.add(1922GenerateMethodList(className, "", InstanceMethods, false));19231924// void *dtable;1925classFields.addNullPointer(PtrTy);1926// IMP cxx_construct;1927classFields.addNullPointer(PtrTy);1928// IMP cxx_destruct;1929classFields.addNullPointer(PtrTy);1930// struct objc_class *subclass_list1931classFields.addNullPointer(PtrTy);1932// struct objc_class *sibling_class1933classFields.addNullPointer(PtrTy);1934// struct objc_protocol_list *protocols;1935auto RuntimeProtocols = GetRuntimeProtocolList(classDecl->protocol_begin(),1936classDecl->protocol_end());1937SmallVector<llvm::Constant *, 16> Protocols;1938for (const auto *I : RuntimeProtocols)1939Protocols.push_back(GenerateProtocolRef(I));19401941if (Protocols.empty())1942classFields.addNullPointer(PtrTy);1943else1944classFields.add(GenerateProtocolList(Protocols));1945// struct reference_list *extra_data;1946classFields.addNullPointer(PtrTy);1947// long abi_version;1948classFields.addInt(LongTy, 0);1949// struct objc_property_list *properties1950classFields.add(GeneratePropertyList(OID, classDecl));19511952llvm::GlobalVariable *classStruct =1953classFields.finishAndCreateGlobal(SymbolForClass(className),1954CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);19551956auto *classRefSymbol = GetClassVar(className);1957classRefSymbol->setSection(sectionName<ClassReferenceSection>());1958classRefSymbol->setInitializer(classStruct);19591960if (IsCOFF) {1961// we can't import a class struct.1962if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {1963classStruct->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);1964cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);1965}19661967if (SuperClass) {1968std::pair<llvm::GlobalVariable*, int> v{classStruct, 1};1969EarlyInitList.emplace_back(std::string(SuperClass->getName()),1970std::move(v));1971}19721973}197419751976// Resolve the class aliases, if they exist.1977// FIXME: Class pointer aliases shouldn't exist!1978if (ClassPtrAlias) {1979ClassPtrAlias->replaceAllUsesWith(classStruct);1980ClassPtrAlias->eraseFromParent();1981ClassPtrAlias = nullptr;1982}1983if (auto Placeholder =1984TheModule.getNamedGlobal(SymbolForClass(className)))1985if (Placeholder != classStruct) {1986Placeholder->replaceAllUsesWith(classStruct);1987Placeholder->eraseFromParent();1988classStruct->setName(SymbolForClass(className));1989}1990if (MetaClassPtrAlias) {1991MetaClassPtrAlias->replaceAllUsesWith(metaclass);1992MetaClassPtrAlias->eraseFromParent();1993MetaClassPtrAlias = nullptr;1994}1995assert(classStruct->getName() == SymbolForClass(className));19961997auto classInitRef = new llvm::GlobalVariable(TheModule,1998classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,1999classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);2000classInitRef->setSection(sectionName<ClassSection>());2001CGM.addUsedGlobal(classInitRef);20022003EmittedClass = true;2004}2005public:2006CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {2007MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,2008PtrToObjCSuperTy, SelectorTy);2009SentInitializeFn.init(&CGM, "objc_send_initialize",2010llvm::Type::getVoidTy(VMContext), IdTy);2011// struct objc_property2012// {2013// const char *name;2014// const char *attributes;2015// const char *type;2016// SEL getter;2017// SEL setter;2018// }2019PropertyMetadataTy =2020llvm::StructType::get(CGM.getLLVMContext(),2021{ PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });2022}20232024void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,2025const ObjCMethodDecl *OMD,2026const ObjCContainerDecl *CD) override {2027auto &Builder = CGF.Builder;2028bool ReceiverCanBeNull = true;2029auto selfAddr = CGF.GetAddrOfLocalVar(OMD->getSelfDecl());2030auto selfValue = Builder.CreateLoad(selfAddr);20312032// Generate:2033//2034// /* unless the receiver is never NULL */2035// if (self == nil) {2036// return (ReturnType){ };2037// }2038//2039// /* for class methods only to force class lazy initialization */2040// if (!__objc_{class}_initialized)2041// {2042// objc_send_initialize(class);2043// __objc_{class}_initialized = 1;2044// }2045//2046// _cmd = @selector(...)2047// ...20482049if (OMD->isClassMethod()) {2050const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(CD);20512052// Nullable `Class` expressions cannot be messaged with a direct method2053// so the only reason why the receive can be null would be because2054// of weak linking.2055ReceiverCanBeNull = isWeakLinkedClass(OID);2056}20572058llvm::MDBuilder MDHelper(CGM.getLLVMContext());2059if (ReceiverCanBeNull) {2060llvm::BasicBlock *SelfIsNilBlock =2061CGF.createBasicBlock("objc_direct_method.self_is_nil");2062llvm::BasicBlock *ContBlock =2063CGF.createBasicBlock("objc_direct_method.cont");20642065// if (self == nil) {2066auto selfTy = cast<llvm::PointerType>(selfValue->getType());2067auto Zero = llvm::ConstantPointerNull::get(selfTy);20682069Builder.CreateCondBr(Builder.CreateICmpEQ(selfValue, Zero),2070SelfIsNilBlock, ContBlock,2071MDHelper.createUnlikelyBranchWeights());20722073CGF.EmitBlock(SelfIsNilBlock);20742075// return (ReturnType){ };2076auto retTy = OMD->getReturnType();2077Builder.SetInsertPoint(SelfIsNilBlock);2078if (!retTy->isVoidType()) {2079CGF.EmitNullInitialization(CGF.ReturnValue, retTy);2080}2081CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);2082// }20832084// rest of the body2085CGF.EmitBlock(ContBlock);2086Builder.SetInsertPoint(ContBlock);2087}20882089if (OMD->isClassMethod()) {2090// Prefix of the class type.2091auto *classStart =2092llvm::StructType::get(PtrTy, PtrTy, PtrTy, LongTy, LongTy);2093auto &astContext = CGM.getContext();2094auto flags = Builder.CreateLoad(2095Address{Builder.CreateStructGEP(classStart, selfValue, 4), LongTy,2096CharUnits::fromQuantity(2097astContext.getTypeAlign(astContext.UnsignedLongTy))});2098auto isInitialized =2099Builder.CreateAnd(flags, ClassFlags::ClassFlagInitialized);2100llvm::BasicBlock *notInitializedBlock =2101CGF.createBasicBlock("objc_direct_method.class_uninitialized");2102llvm::BasicBlock *initializedBlock =2103CGF.createBasicBlock("objc_direct_method.class_initialized");2104Builder.CreateCondBr(Builder.CreateICmpEQ(isInitialized, Zeros[0]),2105notInitializedBlock, initializedBlock,2106MDHelper.createUnlikelyBranchWeights());2107CGF.EmitBlock(notInitializedBlock);2108Builder.SetInsertPoint(notInitializedBlock);2109CGF.EmitRuntimeCall(SentInitializeFn, selfValue);2110Builder.CreateBr(initializedBlock);2111CGF.EmitBlock(initializedBlock);2112Builder.SetInsertPoint(initializedBlock);2113}21142115// only synthesize _cmd if it's referenced2116if (OMD->getCmdDecl()->isUsed()) {2117// `_cmd` is not a parameter to direct methods, so storage must be2118// explicitly declared for it.2119CGF.EmitVarDecl(*OMD->getCmdDecl());2120Builder.CreateStore(GetSelector(CGF, OMD),2121CGF.GetAddrOfLocalVar(OMD->getCmdDecl()));2122}2123}2124};21252126const char *const CGObjCGNUstep2::SectionsBaseNames[8] =2127{2128"__objc_selectors",2129"__objc_classes",2130"__objc_class_refs",2131"__objc_cats",2132"__objc_protocols",2133"__objc_protocol_refs",2134"__objc_class_aliases",2135"__objc_constant_string"2136};21372138const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =2139{2140".objcrt$SEL",2141".objcrt$CLS",2142".objcrt$CLR",2143".objcrt$CAT",2144".objcrt$PCL",2145".objcrt$PCR",2146".objcrt$CAL",2147".objcrt$STR"2148};21492150/// Support for the ObjFW runtime.2151class CGObjCObjFW: public CGObjCGNU {2152protected:2153/// The GCC ABI message lookup function. Returns an IMP pointing to the2154/// method implementation for this message.2155LazyRuntimeFunction MsgLookupFn;2156/// stret lookup function. While this does not seem to make sense at the2157/// first look, this is required to call the correct forwarding function.2158LazyRuntimeFunction MsgLookupFnSRet;2159/// The GCC ABI superclass message lookup function. Takes a pointer to a2160/// structure describing the receiver and the class, and a selector as2161/// arguments. Returns the IMP for the corresponding method.2162LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;21632164llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,2165llvm::Value *cmd, llvm::MDNode *node,2166MessageSendInfo &MSI) override {2167CGBuilderTy &Builder = CGF.Builder;2168llvm::Value *args[] = {2169EnforceType(Builder, Receiver, IdTy),2170EnforceType(Builder, cmd, SelectorTy) };21712172llvm::CallBase *imp;2173if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))2174imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);2175else2176imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);21772178imp->setMetadata(msgSendMDKind, node);2179return imp;2180}21812182llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,2183llvm::Value *cmd, MessageSendInfo &MSI) override {2184CGBuilderTy &Builder = CGF.Builder;2185llvm::Value *lookupArgs[] = {2186EnforceType(Builder, ObjCSuper.emitRawPointer(CGF), PtrToObjCSuperTy),2187cmd,2188};21892190if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))2191return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);2192else2193return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);2194}21952196llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,2197bool isWeak) override {2198if (isWeak)2199return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);22002201EmitClassRef(Name);2202std::string SymbolName = "_OBJC_CLASS_" + Name;2203llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);2204if (!ClassSymbol)2205ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,2206llvm::GlobalValue::ExternalLinkage,2207nullptr, SymbolName);2208return ClassSymbol;2209}22102211public:2212CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {2213// IMP objc_msg_lookup(id, SEL);2214MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);2215MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,2216SelectorTy);2217// IMP objc_msg_lookup_super(struct objc_super*, SEL);2218MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,2219PtrToObjCSuperTy, SelectorTy);2220MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,2221PtrToObjCSuperTy, SelectorTy);2222}2223};2224} // end anonymous namespace22252226/// Emits a reference to a dummy variable which is emitted with each class.2227/// This ensures that a linker error will be generated when trying to link2228/// together modules where a referenced class is not defined.2229void CGObjCGNU::EmitClassRef(const std::string &className) {2230std::string symbolRef = "__objc_class_ref_" + className;2231// Don't emit two copies of the same symbol2232if (TheModule.getGlobalVariable(symbolRef))2233return;2234std::string symbolName = "__objc_class_name_" + className;2235llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);2236if (!ClassSymbol) {2237ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,2238llvm::GlobalValue::ExternalLinkage,2239nullptr, symbolName);2240}2241new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,2242llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);2243}22442245CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,2246unsigned protocolClassVersion, unsigned classABI)2247: CGObjCRuntime(cgm), TheModule(CGM.getModule()),2248VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),2249MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),2250ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {22512252msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");2253usesSEHExceptions =2254cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();2255usesCxxExceptions =2256cgm.getContext().getTargetInfo().getTriple().isOSCygMing() &&2257isRuntime(ObjCRuntime::GNUstep, 2);22582259CodeGenTypes &Types = CGM.getTypes();2260IntTy = cast<llvm::IntegerType>(2261Types.ConvertType(CGM.getContext().IntTy));2262LongTy = cast<llvm::IntegerType>(2263Types.ConvertType(CGM.getContext().LongTy));2264SizeTy = cast<llvm::IntegerType>(2265Types.ConvertType(CGM.getContext().getSizeType()));2266PtrDiffTy = cast<llvm::IntegerType>(2267Types.ConvertType(CGM.getContext().getPointerDiffType()));2268BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);22692270Int8Ty = llvm::Type::getInt8Ty(VMContext);2271// C string type. Used in lots of places.2272PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);2273ProtocolPtrTy = llvm::PointerType::getUnqual(2274Types.ConvertType(CGM.getContext().getObjCProtoType()));22752276Zeros[0] = llvm::ConstantInt::get(LongTy, 0);2277Zeros[1] = Zeros[0];2278NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);2279// Get the selector Type.2280QualType selTy = CGM.getContext().getObjCSelType();2281if (QualType() == selTy) {2282SelectorTy = PtrToInt8Ty;2283SelectorElemTy = Int8Ty;2284} else {2285SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));2286SelectorElemTy = CGM.getTypes().ConvertTypeForMem(selTy->getPointeeType());2287}22882289PtrToIntTy = llvm::PointerType::getUnqual(IntTy);2290PtrTy = PtrToInt8Ty;22912292Int32Ty = llvm::Type::getInt32Ty(VMContext);2293Int64Ty = llvm::Type::getInt64Ty(VMContext);22942295IntPtrTy =2296CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;22972298// Object type2299QualType UnqualIdTy = CGM.getContext().getObjCIdType();2300ASTIdTy = CanQualType();2301if (UnqualIdTy != QualType()) {2302ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);2303IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));2304IdElemTy = CGM.getTypes().ConvertTypeForMem(2305ASTIdTy.getTypePtr()->getPointeeType());2306} else {2307IdTy = PtrToInt8Ty;2308IdElemTy = Int8Ty;2309}2310PtrToIdTy = llvm::PointerType::getUnqual(IdTy);2311ProtocolTy = llvm::StructType::get(IdTy,2312PtrToInt8Ty, // name2313PtrToInt8Ty, // protocols2314PtrToInt8Ty, // instance methods2315PtrToInt8Ty, // class methods2316PtrToInt8Ty, // optional instance methods2317PtrToInt8Ty, // optional class methods2318PtrToInt8Ty, // properties2319PtrToInt8Ty);// optional properties23202321// struct objc_property_gsv12322// {2323// const char *name;2324// char attributes;2325// char attributes2;2326// char unused1;2327// char unused2;2328// const char *getter_name;2329// const char *getter_types;2330// const char *setter_name;2331// const char *setter_types;2332// }2333PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {2334PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,2335PtrToInt8Ty, PtrToInt8Ty });23362337ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);2338PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);23392340llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);23412342// void objc_exception_throw(id);2343ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);2344ExceptionReThrowFn.init(&CGM,2345usesCxxExceptions ? "objc_exception_rethrow"2346: "objc_exception_throw",2347VoidTy, IdTy);2348// int objc_sync_enter(id);2349SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);2350// int objc_sync_exit(id);2351SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);23522353// void objc_enumerationMutation (id)2354EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);23552356// id objc_getProperty(id, SEL, ptrdiff_t, BOOL)2357GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,2358PtrDiffTy, BoolTy);2359// void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)2360SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,2361PtrDiffTy, IdTy, BoolTy, BoolTy);2362// void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)2363GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,2364PtrDiffTy, BoolTy, BoolTy);2365// void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)2366SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,2367PtrDiffTy, BoolTy, BoolTy);23682369// IMP type2370llvm::Type *IMPArgs[] = { IdTy, SelectorTy };2371IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,2372true));23732374const LangOptions &Opts = CGM.getLangOpts();2375if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)2376RuntimeVersion = 10;23772378// Don't bother initialising the GC stuff unless we're compiling in GC mode2379if (Opts.getGC() != LangOptions::NonGC) {2380// This is a bit of an hack. We should sort this out by having a proper2381// CGObjCGNUstep subclass for GC, but we may want to really support the old2382// ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now2383// Get selectors needed in GC mode2384RetainSel = GetNullarySelector("retain", CGM.getContext());2385ReleaseSel = GetNullarySelector("release", CGM.getContext());2386AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());23872388// Get functions needed in GC mode23892390// id objc_assign_ivar(id, id, ptrdiff_t);2391IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);2392// id objc_assign_strongCast (id, id*)2393StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,2394PtrToIdTy);2395// id objc_assign_global(id, id*);2396GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);2397// id objc_assign_weak(id, id*);2398WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);2399// id objc_read_weak(id*);2400WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);2401// void *objc_memmove_collectable(void*, void *, size_t);2402MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,2403SizeTy);2404}2405}24062407llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,2408const std::string &Name, bool isWeak) {2409llvm::Constant *ClassName = MakeConstantString(Name);2410// With the incompatible ABI, this will need to be replaced with a direct2411// reference to the class symbol. For the compatible nonfragile ABI we are2412// still performing this lookup at run time but emitting the symbol for the2413// class externally so that we can make the switch later.2414//2415// Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class2416// with memoized versions or with static references if it's safe to do so.2417if (!isWeak)2418EmitClassRef(Name);24192420llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(2421llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");2422return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);2423}24242425// This has to perform the lookup every time, since posing and related2426// techniques can modify the name -> class mapping.2427llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,2428const ObjCInterfaceDecl *OID) {2429auto *Value =2430GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());2431if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))2432CGM.setGVProperties(ClassSymbol, OID);2433return Value;2434}24352436llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {2437auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);2438if (CGM.getTriple().isOSBinFormatCOFF()) {2439if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {2440IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");2441TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();2442DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);24432444const VarDecl *VD = nullptr;2445for (const auto *Result : DC->lookup(&II))2446if ((VD = dyn_cast<VarDecl>(Result)))2447break;24482449CGM.setGVProperties(ClassSymbol, VD);2450}2451}2452return Value;2453}24542455llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,2456const std::string &TypeEncoding) {2457SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];2458llvm::GlobalAlias *SelValue = nullptr;24592460for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),2461e = Types.end() ; i!=e ; i++) {2462if (i->first == TypeEncoding) {2463SelValue = i->second;2464break;2465}2466}2467if (!SelValue) {2468SelValue = llvm::GlobalAlias::create(SelectorElemTy, 0,2469llvm::GlobalValue::PrivateLinkage,2470".objc_selector_" + Sel.getAsString(),2471&TheModule);2472Types.emplace_back(TypeEncoding, SelValue);2473}24742475return SelValue;2476}24772478Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {2479llvm::Value *SelValue = GetSelector(CGF, Sel);24802481// Store it to a temporary. Does this satisfy the semantics of2482// GetAddrOfSelector? Hopefully.2483Address tmp = CGF.CreateTempAlloca(SelValue->getType(),2484CGF.getPointerAlign());2485CGF.Builder.CreateStore(SelValue, tmp);2486return tmp;2487}24882489llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {2490return GetTypedSelector(CGF, Sel, std::string());2491}24922493llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,2494const ObjCMethodDecl *Method) {2495std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);2496return GetTypedSelector(CGF, Method->getSelector(), SelTypes);2497}24982499llvm::Constant *CGObjCGNU::GetEHType(QualType T) {2500if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {2501// With the old ABI, there was only one kind of catchall, which broke2502// foreign exceptions. With the new ABI, we use __objc_id_typeinfo as2503// a pointer indicating object catchalls, and NULL to indicate real2504// catchalls2505if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {2506return MakeConstantString("@id");2507} else {2508return nullptr;2509}2510}25112512// All other types should be Objective-C interface pointer types.2513const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();2514assert(OPT && "Invalid @catch type.");2515const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();2516assert(IDecl && "Invalid @catch type.");2517return MakeConstantString(IDecl->getIdentifier()->getName());2518}25192520llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {2521if (usesSEHExceptions)2522return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);25232524if (!CGM.getLangOpts().CPlusPlus && !usesCxxExceptions)2525return CGObjCGNU::GetEHType(T);25262527// For Objective-C++, we want to provide the ability to catch both C++ and2528// Objective-C objects in the same function.25292530// There's a particular fixed type info for 'id'.2531if (T->isObjCIdType() ||2532T->isObjCQualifiedIdType()) {2533llvm::Constant *IDEHType =2534CGM.getModule().getGlobalVariable("__objc_id_type_info");2535if (!IDEHType)2536IDEHType =2537new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,2538false,2539llvm::GlobalValue::ExternalLinkage,2540nullptr, "__objc_id_type_info");2541return IDEHType;2542}25432544const ObjCObjectPointerType *PT =2545T->getAs<ObjCObjectPointerType>();2546assert(PT && "Invalid @catch type.");2547const ObjCInterfaceType *IT = PT->getInterfaceType();2548assert(IT && "Invalid @catch type.");2549std::string className =2550std::string(IT->getDecl()->getIdentifier()->getName());25512552std::string typeinfoName = "__objc_eh_typeinfo_" + className;25532554// Return the existing typeinfo if it exists2555if (llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName))2556return typeinfo;25572558// Otherwise create it.25592560// vtable for gnustep::libobjc::__objc_class_type_info2561// It's quite ugly hard-coding this. Ideally we'd generate it using the host2562// platform's name mangling.2563const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";2564auto *Vtable = TheModule.getGlobalVariable(vtableName);2565if (!Vtable) {2566Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,2567llvm::GlobalValue::ExternalLinkage,2568nullptr, vtableName);2569}2570llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);2571auto *BVtable =2572llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two);25732574llvm::Constant *typeName =2575ExportUniqueString(className, "__objc_eh_typename_");25762577ConstantInitBuilder builder(CGM);2578auto fields = builder.beginStruct();2579fields.add(BVtable);2580fields.add(typeName);2581llvm::Constant *TI =2582fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,2583CGM.getPointerAlign(),2584/*constant*/ false,2585llvm::GlobalValue::LinkOnceODRLinkage);2586return TI;2587}25882589/// Generate an NSConstantString object.2590ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {25912592std::string Str = SL->getString().str();2593CharUnits Align = CGM.getPointerAlign();25942595// Look for an existing one2596llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);2597if (old != ObjCStrings.end())2598return ConstantAddress(old->getValue(), Int8Ty, Align);25992600StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;26012602if (StringClass.empty()) StringClass = "NSConstantString";26032604std::string Sym = "_OBJC_CLASS_";2605Sym += StringClass;26062607llvm::Constant *isa = TheModule.getNamedGlobal(Sym);26082609if (!isa)2610isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */ false,2611llvm::GlobalValue::ExternalWeakLinkage,2612nullptr, Sym);26132614ConstantInitBuilder Builder(CGM);2615auto Fields = Builder.beginStruct();2616Fields.add(isa);2617Fields.add(MakeConstantString(Str));2618Fields.addInt(IntTy, Str.size());2619llvm::Constant *ObjCStr = Fields.finishAndCreateGlobal(".objc_str", Align);2620ObjCStrings[Str] = ObjCStr;2621ConstantStrings.push_back(ObjCStr);2622return ConstantAddress(ObjCStr, Int8Ty, Align);2623}26242625///Generates a message send where the super is the receiver. This is a message2626///send to self with special delivery semantics indicating which class's method2627///should be called.2628RValue2629CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,2630ReturnValueSlot Return,2631QualType ResultType,2632Selector Sel,2633const ObjCInterfaceDecl *Class,2634bool isCategoryImpl,2635llvm::Value *Receiver,2636bool IsClassMessage,2637const CallArgList &CallArgs,2638const ObjCMethodDecl *Method) {2639CGBuilderTy &Builder = CGF.Builder;2640if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {2641if (Sel == RetainSel || Sel == AutoreleaseSel) {2642return RValue::get(EnforceType(Builder, Receiver,2643CGM.getTypes().ConvertType(ResultType)));2644}2645if (Sel == ReleaseSel) {2646return RValue::get(nullptr);2647}2648}26492650llvm::Value *cmd = GetSelector(CGF, Sel);2651CallArgList ActualArgs;26522653ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);2654ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());2655ActualArgs.addFrom(CallArgs);26562657MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);26582659llvm::Value *ReceiverClass = nullptr;2660bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);2661if (isV2ABI) {2662ReceiverClass = GetClassNamed(CGF,2663Class->getSuperClass()->getNameAsString(), /*isWeak*/false);2664if (IsClassMessage) {2665// Load the isa pointer of the superclass is this is a class method.2666ReceiverClass = Builder.CreateBitCast(ReceiverClass,2667llvm::PointerType::getUnqual(IdTy));2668ReceiverClass =2669Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());2670}2671ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);2672} else {2673if (isCategoryImpl) {2674llvm::FunctionCallee classLookupFunction = nullptr;2675if (IsClassMessage) {2676classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(2677IdTy, PtrTy, true), "objc_get_meta_class");2678} else {2679classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(2680IdTy, PtrTy, true), "objc_get_class");2681}2682ReceiverClass = Builder.CreateCall(classLookupFunction,2683MakeConstantString(Class->getNameAsString()));2684} else {2685// Set up global aliases for the metaclass or class pointer if they do not2686// already exist. These will are forward-references which will be set to2687// pointers to the class and metaclass structure created for the runtime2688// load function. To send a message to super, we look up the value of the2689// super_class pointer from either the class or metaclass structure.2690if (IsClassMessage) {2691if (!MetaClassPtrAlias) {2692MetaClassPtrAlias = llvm::GlobalAlias::create(2693IdElemTy, 0, llvm::GlobalValue::InternalLinkage,2694".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);2695}2696ReceiverClass = MetaClassPtrAlias;2697} else {2698if (!ClassPtrAlias) {2699ClassPtrAlias = llvm::GlobalAlias::create(2700IdElemTy, 0, llvm::GlobalValue::InternalLinkage,2701".objc_class_ref" + Class->getNameAsString(), &TheModule);2702}2703ReceiverClass = ClassPtrAlias;2704}2705}2706// Cast the pointer to a simplified version of the class structure2707llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);2708ReceiverClass = Builder.CreateBitCast(ReceiverClass,2709llvm::PointerType::getUnqual(CastTy));2710// Get the superclass pointer2711ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);2712// Load the superclass pointer2713ReceiverClass =2714Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());2715}2716// Construct the structure used to look up the IMP2717llvm::StructType *ObjCSuperTy =2718llvm::StructType::get(Receiver->getType(), IdTy);27192720Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,2721CGF.getPointerAlign());27222723Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));2724Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));27252726// Get the IMP2727llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);2728imp = EnforceType(Builder, imp, MSI.MessengerType);27292730llvm::Metadata *impMD[] = {2731llvm::MDString::get(VMContext, Sel.getAsString()),2732llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),2733llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(2734llvm::Type::getInt1Ty(VMContext), IsClassMessage))};2735llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);27362737CGCallee callee(CGCalleeInfo(), imp);27382739llvm::CallBase *call;2740RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);2741call->setMetadata(msgSendMDKind, node);2742return msgRet;2743}27442745/// Generate code for a message send expression.2746RValue2747CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,2748ReturnValueSlot Return,2749QualType ResultType,2750Selector Sel,2751llvm::Value *Receiver,2752const CallArgList &CallArgs,2753const ObjCInterfaceDecl *Class,2754const ObjCMethodDecl *Method) {2755CGBuilderTy &Builder = CGF.Builder;27562757// Strip out message sends to retain / release in GC mode2758if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {2759if (Sel == RetainSel || Sel == AutoreleaseSel) {2760return RValue::get(EnforceType(Builder, Receiver,2761CGM.getTypes().ConvertType(ResultType)));2762}2763if (Sel == ReleaseSel) {2764return RValue::get(nullptr);2765}2766}27672768bool isDirect = Method && Method->isDirectMethod();27692770IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));2771llvm::Value *cmd;2772if (!isDirect) {2773if (Method)2774cmd = GetSelector(CGF, Method);2775else2776cmd = GetSelector(CGF, Sel);2777cmd = EnforceType(Builder, cmd, SelectorTy);2778}27792780Receiver = EnforceType(Builder, Receiver, IdTy);27812782llvm::Metadata *impMD[] = {2783llvm::MDString::get(VMContext, Sel.getAsString()),2784llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),2785llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(2786llvm::Type::getInt1Ty(VMContext), Class != nullptr))};2787llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);27882789CallArgList ActualArgs;2790ActualArgs.add(RValue::get(Receiver), ASTIdTy);2791if (!isDirect)2792ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());2793ActualArgs.addFrom(CallArgs);27942795MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);27962797// Message sends are expected to return a zero value when the2798// receiver is nil. At one point, this was only guaranteed for2799// simple integer and pointer types, but expectations have grown2800// over time.2801//2802// Given a nil receiver, the GNU runtime's message lookup will2803// return a stub function that simply sets various return-value2804// registers to zero and then returns. That's good enough for us2805// if and only if (1) the calling conventions of that stub are2806// compatible with the signature we're using and (2) the registers2807// it sets are sufficient to produce a zero value of the return type.2808// Rather than doing a whole target-specific analysis, we assume it2809// only works for void, integer, and pointer types, and in all2810// other cases we do an explicit nil check is emitted code. In2811// addition to ensuring we produce a zero value for other types, this2812// sidesteps the few outright CC incompatibilities we know about that2813// could otherwise lead to crashes, like when a method is expected to2814// return on the x87 floating point stack or adjust the stack pointer2815// because of an indirect return.2816bool hasParamDestroyedInCallee = false;2817bool requiresExplicitZeroResult = false;2818bool requiresNilReceiverCheck = [&] {2819// We never need a check if we statically know the receiver isn't nil.2820if (!canMessageReceiverBeNull(CGF, Method, /*IsSuper*/ false,2821Class, Receiver))2822return false;28232824// If there's a consumed argument, we need a nil check.2825if (Method && Method->hasParamDestroyedInCallee()) {2826hasParamDestroyedInCallee = true;2827}28282829// If the return value isn't flagged as unused, and the result2830// type isn't in our narrow set where we assume compatibility,2831// we need a nil check to ensure a nil value.2832if (!Return.isUnused()) {2833if (ResultType->isVoidType()) {2834// void results are definitely okay.2835} else if (ResultType->hasPointerRepresentation() &&2836CGM.getTypes().isZeroInitializable(ResultType)) {2837// Pointer types should be fine as long as they have2838// bitwise-zero null pointers. But do we need to worry2839// about unusual address spaces?2840} else if (ResultType->isIntegralOrEnumerationType()) {2841// Bitwise zero should always be zero for integral types.2842// FIXME: we probably need a size limit here, but we've2843// never imposed one before2844} else {2845// Otherwise, use an explicit check just to be sure, unless we're2846// calling a direct method, where the implementation does this for us.2847requiresExplicitZeroResult = !isDirect;2848}2849}28502851return hasParamDestroyedInCallee || requiresExplicitZeroResult;2852}();28532854// We will need to explicitly zero-initialize an aggregate result slot2855// if we generally require explicit zeroing and we have an aggregate2856// result.2857bool requiresExplicitAggZeroing =2858requiresExplicitZeroResult && CGF.hasAggregateEvaluationKind(ResultType);28592860// The block we're going to end up in after any message send or nil path.2861llvm::BasicBlock *continueBB = nullptr;2862// The block that eventually branched to continueBB along the nil path.2863llvm::BasicBlock *nilPathBB = nullptr;2864// The block to do explicit work in along the nil path, if necessary.2865llvm::BasicBlock *nilCleanupBB = nullptr;28662867// Emit the nil-receiver check.2868if (requiresNilReceiverCheck) {2869llvm::BasicBlock *messageBB = CGF.createBasicBlock("msgSend");2870continueBB = CGF.createBasicBlock("continue");28712872// If we need to zero-initialize an aggregate result or destroy2873// consumed arguments, we'll need a separate cleanup block.2874// Otherwise we can just branch directly to the continuation block.2875if (requiresExplicitAggZeroing || hasParamDestroyedInCallee) {2876nilCleanupBB = CGF.createBasicBlock("nilReceiverCleanup");2877} else {2878nilPathBB = Builder.GetInsertBlock();2879}28802881llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,2882llvm::Constant::getNullValue(Receiver->getType()));2883Builder.CreateCondBr(isNil, nilCleanupBB ? nilCleanupBB : continueBB,2884messageBB);2885CGF.EmitBlock(messageBB);2886}28872888// Get the IMP to call2889llvm::Value *imp;28902891// If this is a direct method, just emit it here.2892if (isDirect)2893imp = GenerateMethod(Method, Method->getClassInterface());2894else2895// If we have non-legacy dispatch specified, we try using the2896// objc_msgSend() functions. These are not supported on all platforms2897// (or all runtimes on a given platform), so we2898switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {2899case CodeGenOptions::Legacy:2900imp = LookupIMP(CGF, Receiver, cmd, node, MSI);2901break;2902case CodeGenOptions::Mixed:2903case CodeGenOptions::NonLegacy:2904StringRef name = "objc_msgSend";2905if (CGM.ReturnTypeUsesFPRet(ResultType)) {2906name = "objc_msgSend_fpret";2907} else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {2908name = "objc_msgSend_stret";29092910// The address of the memory block is be passed in x8 for POD type,2911// or in x0 for non-POD type (marked as inreg).2912bool shouldCheckForInReg =2913CGM.getContext()2914.getTargetInfo()2915.getTriple()2916.isWindowsMSVCEnvironment() &&2917CGM.getContext().getTargetInfo().getTriple().isAArch64();2918if (shouldCheckForInReg && CGM.ReturnTypeHasInReg(MSI.CallInfo)) {2919name = "objc_msgSend_stret2";2920}2921}2922// The actual types here don't matter - we're going to bitcast the2923// function anyway2924imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),2925name)2926.getCallee();2927}29282929// Reset the receiver in case the lookup modified it2930ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);29312932imp = EnforceType(Builder, imp, MSI.MessengerType);29332934llvm::CallBase *call;2935CGCallee callee(CGCalleeInfo(), imp);2936RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);2937if (!isDirect)2938call->setMetadata(msgSendMDKind, node);29392940if (requiresNilReceiverCheck) {2941llvm::BasicBlock *nonNilPathBB = CGF.Builder.GetInsertBlock();2942CGF.Builder.CreateBr(continueBB);29432944// Emit the nil path if we decided it was necessary above.2945if (nilCleanupBB) {2946CGF.EmitBlock(nilCleanupBB);29472948if (hasParamDestroyedInCallee) {2949destroyCalleeDestroyedArguments(CGF, Method, CallArgs);2950}29512952if (requiresExplicitAggZeroing) {2953assert(msgRet.isAggregate());2954Address addr = msgRet.getAggregateAddress();2955CGF.EmitNullInitialization(addr, ResultType);2956}29572958nilPathBB = CGF.Builder.GetInsertBlock();2959CGF.Builder.CreateBr(continueBB);2960}29612962// Enter the continuation block and emit a phi if required.2963CGF.EmitBlock(continueBB);2964if (msgRet.isScalar()) {2965// If the return type is void, do nothing2966if (llvm::Value *v = msgRet.getScalarVal()) {2967llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);2968phi->addIncoming(v, nonNilPathBB);2969phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB);2970msgRet = RValue::get(phi);2971}2972} else if (msgRet.isAggregate()) {2973// Aggregate zeroing is handled in nilCleanupBB when it's required.2974} else /* isComplex() */ {2975std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();2976llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);2977phi->addIncoming(v.first, nonNilPathBB);2978phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),2979nilPathBB);2980llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);2981phi2->addIncoming(v.second, nonNilPathBB);2982phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),2983nilPathBB);2984msgRet = RValue::getComplex(phi, phi2);2985}2986}2987return msgRet;2988}29892990/// Generates a MethodList. Used in construction of a objc_class and2991/// objc_category structures.2992llvm::Constant *CGObjCGNU::2993GenerateMethodList(StringRef ClassName,2994StringRef CategoryName,2995ArrayRef<const ObjCMethodDecl*> Methods,2996bool isClassMethodList) {2997if (Methods.empty())2998return NULLPtr;29993000ConstantInitBuilder Builder(CGM);30013002auto MethodList = Builder.beginStruct();3003MethodList.addNullPointer(CGM.Int8PtrTy);3004MethodList.addInt(Int32Ty, Methods.size());30053006// Get the method structure type.3007llvm::StructType *ObjCMethodTy =3008llvm::StructType::get(CGM.getLLVMContext(), {3009PtrToInt8Ty, // Really a selector, but the runtime creates it us.3010PtrToInt8Ty, // Method types3011IMPTy // Method pointer3012});3013bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);3014if (isV2ABI) {3015// size_t size;3016llvm::DataLayout td(&TheModule);3017MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /3018CGM.getContext().getCharWidth());3019ObjCMethodTy =3020llvm::StructType::get(CGM.getLLVMContext(), {3021IMPTy, // Method pointer3022PtrToInt8Ty, // Selector3023PtrToInt8Ty // Extended type encoding3024});3025} else {3026ObjCMethodTy =3027llvm::StructType::get(CGM.getLLVMContext(), {3028PtrToInt8Ty, // Really a selector, but the runtime creates it us.3029PtrToInt8Ty, // Method types3030IMPTy // Method pointer3031});3032}3033auto MethodArray = MethodList.beginArray();3034ASTContext &Context = CGM.getContext();3035for (const auto *OMD : Methods) {3036llvm::Constant *FnPtr =3037TheModule.getFunction(getSymbolNameForMethod(OMD));3038assert(FnPtr && "Can't generate metadata for method that doesn't exist");3039auto Method = MethodArray.beginStruct(ObjCMethodTy);3040if (isV2ABI) {3041Method.add(FnPtr);3042Method.add(GetConstantSelector(OMD->getSelector(),3043Context.getObjCEncodingForMethodDecl(OMD)));3044Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));3045} else {3046Method.add(MakeConstantString(OMD->getSelector().getAsString()));3047Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));3048Method.add(FnPtr);3049}3050Method.finishAndAddTo(MethodArray);3051}3052MethodArray.finishAndAddTo(MethodList);30533054// Create an instance of the structure3055return MethodList.finishAndCreateGlobal(".objc_method_list",3056CGM.getPointerAlign());3057}30583059/// Generates an IvarList. Used in construction of a objc_class.3060llvm::Constant *CGObjCGNU::3061GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,3062ArrayRef<llvm::Constant *> IvarTypes,3063ArrayRef<llvm::Constant *> IvarOffsets,3064ArrayRef<llvm::Constant *> IvarAlign,3065ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {3066if (IvarNames.empty())3067return NULLPtr;30683069ConstantInitBuilder Builder(CGM);30703071// Structure containing array count followed by array.3072auto IvarList = Builder.beginStruct();3073IvarList.addInt(IntTy, (int)IvarNames.size());30743075// Get the ivar structure type.3076llvm::StructType *ObjCIvarTy =3077llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);30783079// Array of ivar structures.3080auto Ivars = IvarList.beginArray(ObjCIvarTy);3081for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {3082auto Ivar = Ivars.beginStruct(ObjCIvarTy);3083Ivar.add(IvarNames[i]);3084Ivar.add(IvarTypes[i]);3085Ivar.add(IvarOffsets[i]);3086Ivar.finishAndAddTo(Ivars);3087}3088Ivars.finishAndAddTo(IvarList);30893090// Create an instance of the structure3091return IvarList.finishAndCreateGlobal(".objc_ivar_list",3092CGM.getPointerAlign());3093}30943095/// Generate a class structure3096llvm::Constant *CGObjCGNU::GenerateClassStructure(3097llvm::Constant *MetaClass,3098llvm::Constant *SuperClass,3099unsigned info,3100const char *Name,3101llvm::Constant *Version,3102llvm::Constant *InstanceSize,3103llvm::Constant *IVars,3104llvm::Constant *Methods,3105llvm::Constant *Protocols,3106llvm::Constant *IvarOffsets,3107llvm::Constant *Properties,3108llvm::Constant *StrongIvarBitmap,3109llvm::Constant *WeakIvarBitmap,3110bool isMeta) {3111// Set up the class structure3112// Note: Several of these are char*s when they should be ids. This is3113// because the runtime performs this translation on load.3114//3115// Fields marked New ABI are part of the GNUstep runtime. We emit them3116// anyway; the classes will still work with the GNU runtime, they will just3117// be ignored.3118llvm::StructType *ClassTy = llvm::StructType::get(3119PtrToInt8Ty, // isa3120PtrToInt8Ty, // super_class3121PtrToInt8Ty, // name3122LongTy, // version3123LongTy, // info3124LongTy, // instance_size3125IVars->getType(), // ivars3126Methods->getType(), // methods3127// These are all filled in by the runtime, so we pretend3128PtrTy, // dtable3129PtrTy, // subclass_list3130PtrTy, // sibling_class3131PtrTy, // protocols3132PtrTy, // gc_object_type3133// New ABI:3134LongTy, // abi_version3135IvarOffsets->getType(), // ivar_offsets3136Properties->getType(), // properties3137IntPtrTy, // strong_pointers3138IntPtrTy // weak_pointers3139);31403141ConstantInitBuilder Builder(CGM);3142auto Elements = Builder.beginStruct(ClassTy);31433144// Fill in the structure31453146// isa3147Elements.add(MetaClass);3148// super_class3149Elements.add(SuperClass);3150// name3151Elements.add(MakeConstantString(Name, ".class_name"));3152// version3153Elements.addInt(LongTy, 0);3154// info3155Elements.addInt(LongTy, info);3156// instance_size3157if (isMeta) {3158llvm::DataLayout td(&TheModule);3159Elements.addInt(LongTy,3160td.getTypeSizeInBits(ClassTy) /3161CGM.getContext().getCharWidth());3162} else3163Elements.add(InstanceSize);3164// ivars3165Elements.add(IVars);3166// methods3167Elements.add(Methods);3168// These are all filled in by the runtime, so we pretend3169// dtable3170Elements.add(NULLPtr);3171// subclass_list3172Elements.add(NULLPtr);3173// sibling_class3174Elements.add(NULLPtr);3175// protocols3176Elements.add(Protocols);3177// gc_object_type3178Elements.add(NULLPtr);3179// abi_version3180Elements.addInt(LongTy, ClassABIVersion);3181// ivar_offsets3182Elements.add(IvarOffsets);3183// properties3184Elements.add(Properties);3185// strong_pointers3186Elements.add(StrongIvarBitmap);3187// weak_pointers3188Elements.add(WeakIvarBitmap);3189// Create an instance of the structure3190// This is now an externally visible symbol, so that we can speed up class3191// messages in the next ABI. We may already have some weak references to3192// this, so check and fix them properly.3193std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +3194std::string(Name));3195llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);3196llvm::Constant *Class =3197Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,3198llvm::GlobalValue::ExternalLinkage);3199if (ClassRef) {3200ClassRef->replaceAllUsesWith(Class);3201ClassRef->removeFromParent();3202Class->setName(ClassSym);3203}3204return Class;3205}32063207llvm::Constant *CGObjCGNU::3208GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {3209// Get the method structure type.3210llvm::StructType *ObjCMethodDescTy =3211llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });3212ASTContext &Context = CGM.getContext();3213ConstantInitBuilder Builder(CGM);3214auto MethodList = Builder.beginStruct();3215MethodList.addInt(IntTy, Methods.size());3216auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);3217for (auto *M : Methods) {3218auto Method = MethodArray.beginStruct(ObjCMethodDescTy);3219Method.add(MakeConstantString(M->getSelector().getAsString()));3220Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));3221Method.finishAndAddTo(MethodArray);3222}3223MethodArray.finishAndAddTo(MethodList);3224return MethodList.finishAndCreateGlobal(".objc_method_list",3225CGM.getPointerAlign());3226}32273228// Create the protocol list structure used in classes, categories and so on3229llvm::Constant *3230CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {32313232ConstantInitBuilder Builder(CGM);3233auto ProtocolList = Builder.beginStruct();3234ProtocolList.add(NULLPtr);3235ProtocolList.addInt(LongTy, Protocols.size());32363237auto Elements = ProtocolList.beginArray(PtrToInt8Ty);3238for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();3239iter != endIter ; iter++) {3240llvm::Constant *protocol = nullptr;3241llvm::StringMap<llvm::Constant*>::iterator value =3242ExistingProtocols.find(*iter);3243if (value == ExistingProtocols.end()) {3244protocol = GenerateEmptyProtocol(*iter);3245} else {3246protocol = value->getValue();3247}3248Elements.add(protocol);3249}3250Elements.finishAndAddTo(ProtocolList);3251return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",3252CGM.getPointerAlign());3253}32543255llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,3256const ObjCProtocolDecl *PD) {3257auto protocol = GenerateProtocolRef(PD);3258llvm::Type *T =3259CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());3260return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));3261}32623263llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {3264llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];3265if (!protocol)3266GenerateProtocol(PD);3267assert(protocol && "Unknown protocol");3268return protocol;3269}32703271llvm::Constant *3272CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {3273llvm::Constant *ProtocolList = GenerateProtocolList({});3274llvm::Constant *MethodList = GenerateProtocolMethodList({});3275// Protocols are objects containing lists of the methods implemented and3276// protocols adopted.3277ConstantInitBuilder Builder(CGM);3278auto Elements = Builder.beginStruct();32793280// The isa pointer must be set to a magic number so the runtime knows it's3281// the correct layout.3282Elements.add(llvm::ConstantExpr::getIntToPtr(3283llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));32843285Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));3286Elements.add(ProtocolList); /* .protocol_list */3287Elements.add(MethodList); /* .instance_methods */3288Elements.add(MethodList); /* .class_methods */3289Elements.add(MethodList); /* .optional_instance_methods */3290Elements.add(MethodList); /* .optional_class_methods */3291Elements.add(NULLPtr); /* .properties */3292Elements.add(NULLPtr); /* .optional_properties */3293return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),3294CGM.getPointerAlign());3295}32963297void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {3298if (PD->isNonRuntimeProtocol())3299return;33003301std::string ProtocolName = PD->getNameAsString();33023303// Use the protocol definition, if there is one.3304if (const ObjCProtocolDecl *Def = PD->getDefinition())3305PD = Def;33063307SmallVector<std::string, 16> Protocols;3308for (const auto *PI : PD->protocols())3309Protocols.push_back(PI->getNameAsString());3310SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;3311SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;3312for (const auto *I : PD->instance_methods())3313if (I->isOptional())3314OptionalInstanceMethods.push_back(I);3315else3316InstanceMethods.push_back(I);3317// Collect information about class methods:3318SmallVector<const ObjCMethodDecl*, 16> ClassMethods;3319SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;3320for (const auto *I : PD->class_methods())3321if (I->isOptional())3322OptionalClassMethods.push_back(I);3323else3324ClassMethods.push_back(I);33253326llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);3327llvm::Constant *InstanceMethodList =3328GenerateProtocolMethodList(InstanceMethods);3329llvm::Constant *ClassMethodList =3330GenerateProtocolMethodList(ClassMethods);3331llvm::Constant *OptionalInstanceMethodList =3332GenerateProtocolMethodList(OptionalInstanceMethods);3333llvm::Constant *OptionalClassMethodList =3334GenerateProtocolMethodList(OptionalClassMethods);33353336// Property metadata: name, attributes, isSynthesized, setter name, setter3337// types, getter name, getter types.3338// The isSynthesized value is always set to 0 in a protocol. It exists to3339// simplify the runtime library by allowing it to use the same data3340// structures for protocol metadata everywhere.33413342llvm::Constant *PropertyList =3343GeneratePropertyList(nullptr, PD, false, false);3344llvm::Constant *OptionalPropertyList =3345GeneratePropertyList(nullptr, PD, false, true);33463347// Protocols are objects containing lists of the methods implemented and3348// protocols adopted.3349// The isa pointer must be set to a magic number so the runtime knows it's3350// the correct layout.3351ConstantInitBuilder Builder(CGM);3352auto Elements = Builder.beginStruct();3353Elements.add(3354llvm::ConstantExpr::getIntToPtr(3355llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));3356Elements.add(MakeConstantString(ProtocolName));3357Elements.add(ProtocolList);3358Elements.add(InstanceMethodList);3359Elements.add(ClassMethodList);3360Elements.add(OptionalInstanceMethodList);3361Elements.add(OptionalClassMethodList);3362Elements.add(PropertyList);3363Elements.add(OptionalPropertyList);3364ExistingProtocols[ProtocolName] =3365Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign());3366}3367void CGObjCGNU::GenerateProtocolHolderCategory() {3368// Collect information about instance methods33693370ConstantInitBuilder Builder(CGM);3371auto Elements = Builder.beginStruct();33723373const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";3374const std::string CategoryName = "AnotherHack";3375Elements.add(MakeConstantString(CategoryName));3376Elements.add(MakeConstantString(ClassName));3377// Instance method list3378Elements.add(GenerateMethodList(ClassName, CategoryName, {}, false));3379// Class method list3380Elements.add(GenerateMethodList(ClassName, CategoryName, {}, true));33813382// Protocol list3383ConstantInitBuilder ProtocolListBuilder(CGM);3384auto ProtocolList = ProtocolListBuilder.beginStruct();3385ProtocolList.add(NULLPtr);3386ProtocolList.addInt(LongTy, ExistingProtocols.size());3387auto ProtocolElements = ProtocolList.beginArray(PtrTy);3388for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();3389iter != endIter ; iter++) {3390ProtocolElements.add(iter->getValue());3391}3392ProtocolElements.finishAndAddTo(ProtocolList);3393Elements.add(ProtocolList.finishAndCreateGlobal(".objc_protocol_list",3394CGM.getPointerAlign()));3395Categories.push_back(3396Elements.finishAndCreateGlobal("", CGM.getPointerAlign()));3397}33983399/// Libobjc2 uses a bitfield representation where small(ish) bitfields are3400/// stored in a 64-bit value with the low bit set to 1 and the remaining 633401/// bits set to their values, LSB first, while larger ones are stored in a3402/// structure of this / form:3403///3404/// struct { int32_t length; int32_t values[length]; };3405///3406/// The values in the array are stored in host-endian format, with the least3407/// significant bit being assumed to come first in the bitfield. Therefore, a3408/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a3409/// bitfield / with the 63rd bit set will be 1<<64.3410llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {3411int bitCount = bits.size();3412int ptrBits = CGM.getDataLayout().getPointerSizeInBits();3413if (bitCount < ptrBits) {3414uint64_t val = 1;3415for (int i=0 ; i<bitCount ; ++i) {3416if (bits[i]) val |= 1ULL<<(i+1);3417}3418return llvm::ConstantInt::get(IntPtrTy, val);3419}3420SmallVector<llvm::Constant *, 8> values;3421int v=0;3422while (v < bitCount) {3423int32_t word = 0;3424for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {3425if (bits[v]) word |= 1<<i;3426v++;3427}3428values.push_back(llvm::ConstantInt::get(Int32Ty, word));3429}34303431ConstantInitBuilder builder(CGM);3432auto fields = builder.beginStruct();3433fields.addInt(Int32Ty, values.size());3434auto array = fields.beginArray();3435for (auto *v : values) array.add(v);3436array.finishAndAddTo(fields);34373438llvm::Constant *GS =3439fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));3440llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);3441return ptr;3442}34433444llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const3445ObjCCategoryDecl *OCD) {3446const auto &RefPro = OCD->getReferencedProtocols();3447const auto RuntimeProtos =3448GetRuntimeProtocolList(RefPro.begin(), RefPro.end());3449SmallVector<std::string, 16> Protocols;3450for (const auto *PD : RuntimeProtos)3451Protocols.push_back(PD->getNameAsString());3452return GenerateProtocolList(Protocols);3453}34543455void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {3456const ObjCInterfaceDecl *Class = OCD->getClassInterface();3457std::string ClassName = Class->getNameAsString();3458std::string CategoryName = OCD->getNameAsString();34593460// Collect the names of referenced protocols3461const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();34623463ConstantInitBuilder Builder(CGM);3464auto Elements = Builder.beginStruct();3465Elements.add(MakeConstantString(CategoryName));3466Elements.add(MakeConstantString(ClassName));3467// Instance method list3468SmallVector<ObjCMethodDecl*, 16> InstanceMethods;3469InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),3470OCD->instmeth_end());3471Elements.add(3472GenerateMethodList(ClassName, CategoryName, InstanceMethods, false));34733474// Class method list34753476SmallVector<ObjCMethodDecl*, 16> ClassMethods;3477ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),3478OCD->classmeth_end());3479Elements.add(GenerateMethodList(ClassName, CategoryName, ClassMethods, true));34803481// Protocol list3482Elements.add(GenerateCategoryProtocolList(CatDecl));3483if (isRuntime(ObjCRuntime::GNUstep, 2)) {3484const ObjCCategoryDecl *Category =3485Class->FindCategoryDeclaration(OCD->getIdentifier());3486if (Category) {3487// Instance properties3488Elements.add(GeneratePropertyList(OCD, Category, false));3489// Class properties3490Elements.add(GeneratePropertyList(OCD, Category, true));3491} else {3492Elements.addNullPointer(PtrTy);3493Elements.addNullPointer(PtrTy);3494}3495}34963497Categories.push_back(Elements.finishAndCreateGlobal(3498std::string(".objc_category_") + ClassName + CategoryName,3499CGM.getPointerAlign()));3500}35013502llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,3503const ObjCContainerDecl *OCD,3504bool isClassProperty,3505bool protocolOptionalProperties) {35063507SmallVector<const ObjCPropertyDecl *, 16> Properties;3508llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;3509bool isProtocol = isa<ObjCProtocolDecl>(OCD);3510ASTContext &Context = CGM.getContext();35113512std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties3513= [&](const ObjCProtocolDecl *Proto) {3514for (const auto *P : Proto->protocols())3515collectProtocolProperties(P);3516for (const auto *PD : Proto->properties()) {3517if (isClassProperty != PD->isClassProperty())3518continue;3519// Skip any properties that are declared in protocols that this class3520// conforms to but are not actually implemented by this class.3521if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))3522continue;3523if (!PropertySet.insert(PD->getIdentifier()).second)3524continue;3525Properties.push_back(PD);3526}3527};35283529if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))3530for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())3531for (auto *PD : ClassExt->properties()) {3532if (isClassProperty != PD->isClassProperty())3533continue;3534PropertySet.insert(PD->getIdentifier());3535Properties.push_back(PD);3536}35373538for (const auto *PD : OCD->properties()) {3539if (isClassProperty != PD->isClassProperty())3540continue;3541// If we're generating a list for a protocol, skip optional / required ones3542// when generating the other list.3543if (isProtocol && (protocolOptionalProperties != PD->isOptional()))3544continue;3545// Don't emit duplicate metadata for properties that were already in a3546// class extension.3547if (!PropertySet.insert(PD->getIdentifier()).second)3548continue;35493550Properties.push_back(PD);3551}35523553if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))3554for (const auto *P : OID->all_referenced_protocols())3555collectProtocolProperties(P);3556else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))3557for (const auto *P : CD->protocols())3558collectProtocolProperties(P);35593560auto numProperties = Properties.size();35613562if (numProperties == 0)3563return NULLPtr;35643565ConstantInitBuilder builder(CGM);3566auto propertyList = builder.beginStruct();3567auto properties = PushPropertyListHeader(propertyList, numProperties);35683569// Add all of the property methods need adding to the method list and to the3570// property metadata list.3571for (auto *property : Properties) {3572bool isSynthesized = false;3573bool isDynamic = false;3574if (!isProtocol) {3575auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);3576if (propertyImpl) {3577isSynthesized = (propertyImpl->getPropertyImplementation() ==3578ObjCPropertyImplDecl::Synthesize);3579isDynamic = (propertyImpl->getPropertyImplementation() ==3580ObjCPropertyImplDecl::Dynamic);3581}3582}3583PushProperty(properties, property, Container, isSynthesized, isDynamic);3584}3585properties.finishAndAddTo(propertyList);35863587return propertyList.finishAndCreateGlobal(".objc_property_list",3588CGM.getPointerAlign());3589}35903591void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {3592// Get the class declaration for which the alias is specified.3593ObjCInterfaceDecl *ClassDecl =3594const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());3595ClassAliases.emplace_back(ClassDecl->getNameAsString(),3596OAD->getNameAsString());3597}35983599void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {3600ASTContext &Context = CGM.getContext();36013602// Get the superclass name.3603const ObjCInterfaceDecl * SuperClassDecl =3604OID->getClassInterface()->getSuperClass();3605std::string SuperClassName;3606if (SuperClassDecl) {3607SuperClassName = SuperClassDecl->getNameAsString();3608EmitClassRef(SuperClassName);3609}36103611// Get the class name3612ObjCInterfaceDecl *ClassDecl =3613const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());3614std::string ClassName = ClassDecl->getNameAsString();36153616// Emit the symbol that is used to generate linker errors if this class is3617// referenced in other modules but not declared.3618std::string classSymbolName = "__objc_class_name_" + ClassName;3619if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {3620symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));3621} else {3622new llvm::GlobalVariable(TheModule, LongTy, false,3623llvm::GlobalValue::ExternalLinkage,3624llvm::ConstantInt::get(LongTy, 0),3625classSymbolName);3626}36273628// Get the size of instances.3629int instanceSize =3630Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();36313632// Collect information about instance variables.3633SmallVector<llvm::Constant*, 16> IvarNames;3634SmallVector<llvm::Constant*, 16> IvarTypes;3635SmallVector<llvm::Constant*, 16> IvarOffsets;3636SmallVector<llvm::Constant*, 16> IvarAligns;3637SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;36383639ConstantInitBuilder IvarOffsetBuilder(CGM);3640auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);3641SmallVector<bool, 16> WeakIvars;3642SmallVector<bool, 16> StrongIvars;36433644int superInstanceSize = !SuperClassDecl ? 0 :3645Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();3646// For non-fragile ivars, set the instance size to 0 - {the size of just this3647// class}. The runtime will then set this to the correct value on load.3648if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {3649instanceSize = 0 - (instanceSize - superInstanceSize);3650}36513652for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;3653IVD = IVD->getNextIvar()) {3654// Store the name3655IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));3656// Get the type encoding for this ivar3657std::string TypeStr;3658Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);3659IvarTypes.push_back(MakeConstantString(TypeStr));3660IvarAligns.push_back(llvm::ConstantInt::get(IntTy,3661Context.getTypeSize(IVD->getType())));3662// Get the offset3663uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);3664uint64_t Offset = BaseOffset;3665if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {3666Offset = BaseOffset - superInstanceSize;3667}3668llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);3669// Create the direct offset value3670std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +3671IVD->getNameAsString();36723673llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);3674if (OffsetVar) {3675OffsetVar->setInitializer(OffsetValue);3676// If this is the real definition, change its linkage type so that3677// different modules will use this one, rather than their private3678// copy.3679OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);3680} else3681OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,3682false, llvm::GlobalValue::ExternalLinkage,3683OffsetValue, OffsetName);3684IvarOffsets.push_back(OffsetValue);3685IvarOffsetValues.add(OffsetVar);3686Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();3687IvarOwnership.push_back(lt);3688switch (lt) {3689case Qualifiers::OCL_Strong:3690StrongIvars.push_back(true);3691WeakIvars.push_back(false);3692break;3693case Qualifiers::OCL_Weak:3694StrongIvars.push_back(false);3695WeakIvars.push_back(true);3696break;3697default:3698StrongIvars.push_back(false);3699WeakIvars.push_back(false);3700}3701}3702llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);3703llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);3704llvm::GlobalVariable *IvarOffsetArray =3705IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",3706CGM.getPointerAlign());37073708// Collect information about instance methods3709SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;3710InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),3711OID->instmeth_end());37123713SmallVector<const ObjCMethodDecl*, 16> ClassMethods;3714ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),3715OID->classmeth_end());37163717llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);37183719// Collect the names of referenced protocols3720auto RefProtocols = ClassDecl->protocols();3721auto RuntimeProtocols =3722GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());3723SmallVector<std::string, 16> Protocols;3724for (const auto *I : RuntimeProtocols)3725Protocols.push_back(I->getNameAsString());37263727// Get the superclass pointer.3728llvm::Constant *SuperClass;3729if (!SuperClassName.empty()) {3730SuperClass = MakeConstantString(SuperClassName, ".super_class_name");3731} else {3732SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);3733}3734// Empty vector used to construct empty method lists3735SmallVector<llvm::Constant*, 1> empty;3736// Generate the method and instance variable lists3737llvm::Constant *MethodList = GenerateMethodList(ClassName, "",3738InstanceMethods, false);3739llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",3740ClassMethods, true);3741llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,3742IvarOffsets, IvarAligns, IvarOwnership);3743// Irrespective of whether we are compiling for a fragile or non-fragile ABI,3744// we emit a symbol containing the offset for each ivar in the class. This3745// allows code compiled for the non-Fragile ABI to inherit from code compiled3746// for the legacy ABI, without causing problems. The converse is also3747// possible, but causes all ivar accesses to be fragile.37483749// Offset pointer for getting at the correct field in the ivar list when3750// setting up the alias. These are: The base address for the global, the3751// ivar array (second field), the ivar in this list (set for each ivar), and3752// the offset (third field in ivar structure)3753llvm::Type *IndexTy = Int32Ty;3754llvm::Constant *offsetPointerIndexes[] = {Zeros[0],3755llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,3756llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };37573758unsigned ivarIndex = 0;3759for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;3760IVD = IVD->getNextIvar()) {3761const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);3762offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);3763// Get the correct ivar field3764llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(3765cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,3766offsetPointerIndexes);3767// Get the existing variable, if one exists.3768llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);3769if (offset) {3770offset->setInitializer(offsetValue);3771// If this is the real definition, change its linkage type so that3772// different modules will use this one, rather than their private3773// copy.3774offset->setLinkage(llvm::GlobalValue::ExternalLinkage);3775} else3776// Add a new alias if there isn't one already.3777new llvm::GlobalVariable(TheModule, offsetValue->getType(),3778false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);3779++ivarIndex;3780}3781llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);37823783//Generate metaclass for class methods3784llvm::Constant *MetaClassStruct = GenerateClassStructure(3785NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],3786NULLPtr, ClassMethodList, NULLPtr, NULLPtr,3787GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);3788CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),3789OID->getClassInterface());37903791// Generate the class structure3792llvm::Constant *ClassStruct = GenerateClassStructure(3793MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,3794llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,3795GenerateProtocolList(Protocols), IvarOffsetArray, Properties,3796StrongIvarBitmap, WeakIvarBitmap);3797CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),3798OID->getClassInterface());37993800// Resolve the class aliases, if they exist.3801if (ClassPtrAlias) {3802ClassPtrAlias->replaceAllUsesWith(ClassStruct);3803ClassPtrAlias->eraseFromParent();3804ClassPtrAlias = nullptr;3805}3806if (MetaClassPtrAlias) {3807MetaClassPtrAlias->replaceAllUsesWith(MetaClassStruct);3808MetaClassPtrAlias->eraseFromParent();3809MetaClassPtrAlias = nullptr;3810}38113812// Add class structure to list to be added to the symtab later3813Classes.push_back(ClassStruct);3814}38153816llvm::Function *CGObjCGNU::ModuleInitFunction() {3817// Only emit an ObjC load function if no Objective-C stuff has been called3818if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&3819ExistingProtocols.empty() && SelectorTable.empty())3820return nullptr;38213822// Add all referenced protocols to a category.3823GenerateProtocolHolderCategory();38243825llvm::StructType *selStructTy = dyn_cast<llvm::StructType>(SelectorElemTy);3826if (!selStructTy) {3827selStructTy = llvm::StructType::get(CGM.getLLVMContext(),3828{ PtrToInt8Ty, PtrToInt8Ty });3829}38303831// Generate statics list:3832llvm::Constant *statics = NULLPtr;3833if (!ConstantStrings.empty()) {3834llvm::GlobalVariable *fileStatics = [&] {3835ConstantInitBuilder builder(CGM);3836auto staticsStruct = builder.beginStruct();38373838StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;3839if (stringClass.empty()) stringClass = "NXConstantString";3840staticsStruct.add(MakeConstantString(stringClass,3841".objc_static_class_name"));38423843auto array = staticsStruct.beginArray();3844array.addAll(ConstantStrings);3845array.add(NULLPtr);3846array.finishAndAddTo(staticsStruct);38473848return staticsStruct.finishAndCreateGlobal(".objc_statics",3849CGM.getPointerAlign());3850}();38513852ConstantInitBuilder builder(CGM);3853auto allStaticsArray = builder.beginArray(fileStatics->getType());3854allStaticsArray.add(fileStatics);3855allStaticsArray.addNullPointer(fileStatics->getType());38563857statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",3858CGM.getPointerAlign());3859}38603861// Array of classes, categories, and constant objects.38623863SmallVector<llvm::GlobalAlias*, 16> selectorAliases;3864unsigned selectorCount;38653866// Pointer to an array of selectors used in this module.3867llvm::GlobalVariable *selectorList = [&] {3868ConstantInitBuilder builder(CGM);3869auto selectors = builder.beginArray(selStructTy);3870auto &table = SelectorTable; // MSVC workaround3871std::vector<Selector> allSelectors;3872for (auto &entry : table)3873allSelectors.push_back(entry.first);3874llvm::sort(allSelectors);38753876for (auto &untypedSel : allSelectors) {3877std::string selNameStr = untypedSel.getAsString();3878llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");38793880for (TypedSelector &sel : table[untypedSel]) {3881llvm::Constant *selectorTypeEncoding = NULLPtr;3882if (!sel.first.empty())3883selectorTypeEncoding =3884MakeConstantString(sel.first, ".objc_sel_types");38853886auto selStruct = selectors.beginStruct(selStructTy);3887selStruct.add(selName);3888selStruct.add(selectorTypeEncoding);3889selStruct.finishAndAddTo(selectors);38903891// Store the selector alias for later replacement3892selectorAliases.push_back(sel.second);3893}3894}38953896// Remember the number of entries in the selector table.3897selectorCount = selectors.size();38983899// NULL-terminate the selector list. This should not actually be required,3900// because the selector list has a length field. Unfortunately, the GCC3901// runtime decides to ignore the length field and expects a NULL terminator,3902// and GCC cooperates with this by always setting the length to 0.3903auto selStruct = selectors.beginStruct(selStructTy);3904selStruct.add(NULLPtr);3905selStruct.add(NULLPtr);3906selStruct.finishAndAddTo(selectors);39073908return selectors.finishAndCreateGlobal(".objc_selector_list",3909CGM.getPointerAlign());3910}();39113912// Now that all of the static selectors exist, create pointers to them.3913for (unsigned i = 0; i < selectorCount; ++i) {3914llvm::Constant *idxs[] = {3915Zeros[0],3916llvm::ConstantInt::get(Int32Ty, i)3917};3918// FIXME: We're generating redundant loads and stores here!3919llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(3920selectorList->getValueType(), selectorList, idxs);3921selectorAliases[i]->replaceAllUsesWith(selPtr);3922selectorAliases[i]->eraseFromParent();3923}39243925llvm::GlobalVariable *symtab = [&] {3926ConstantInitBuilder builder(CGM);3927auto symtab = builder.beginStruct();39283929// Number of static selectors3930symtab.addInt(LongTy, selectorCount);39313932symtab.add(selectorList);39333934// Number of classes defined.3935symtab.addInt(CGM.Int16Ty, Classes.size());3936// Number of categories defined3937symtab.addInt(CGM.Int16Ty, Categories.size());39383939// Create an array of classes, then categories, then static object instances3940auto classList = symtab.beginArray(PtrToInt8Ty);3941classList.addAll(Classes);3942classList.addAll(Categories);3943// NULL-terminated list of static object instances (mainly constant strings)3944classList.add(statics);3945classList.add(NULLPtr);3946classList.finishAndAddTo(symtab);39473948// Construct the symbol table.3949return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());3950}();39513952// The symbol table is contained in a module which has some version-checking3953// constants3954llvm::Constant *module = [&] {3955llvm::Type *moduleEltTys[] = {3956LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy3957};3958llvm::StructType *moduleTy = llvm::StructType::get(3959CGM.getLLVMContext(),3960ArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));39613962ConstantInitBuilder builder(CGM);3963auto module = builder.beginStruct(moduleTy);3964// Runtime version, used for ABI compatibility checking.3965module.addInt(LongTy, RuntimeVersion);3966// sizeof(ModuleTy)3967module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));39683969// The path to the source file where this module was declared3970SourceManager &SM = CGM.getContext().getSourceManager();3971OptionalFileEntryRef mainFile = SM.getFileEntryRefForID(SM.getMainFileID());3972std::string path =3973(mainFile->getDir().getName() + "/" + mainFile->getName()).str();3974module.add(MakeConstantString(path, ".objc_source_file_name"));3975module.add(symtab);39763977if (RuntimeVersion >= 10) {3978switch (CGM.getLangOpts().getGC()) {3979case LangOptions::GCOnly:3980module.addInt(IntTy, 2);3981break;3982case LangOptions::NonGC:3983if (CGM.getLangOpts().ObjCAutoRefCount)3984module.addInt(IntTy, 1);3985else3986module.addInt(IntTy, 0);3987break;3988case LangOptions::HybridGC:3989module.addInt(IntTy, 1);3990break;3991}3992}39933994return module.finishAndCreateGlobal("", CGM.getPointerAlign());3995}();39963997// Create the load function calling the runtime entry point with the module3998// structure3999llvm::Function * LoadFunction = llvm::Function::Create(4000llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),4001llvm::GlobalValue::InternalLinkage, ".objc_load_function",4002&TheModule);4003llvm::BasicBlock *EntryBB =4004llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);4005CGBuilderTy Builder(CGM, VMContext);4006Builder.SetInsertPoint(EntryBB);40074008llvm::FunctionType *FT =4009llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);4010llvm::FunctionCallee Register =4011CGM.CreateRuntimeFunction(FT, "__objc_exec_class");4012Builder.CreateCall(Register, module);40134014if (!ClassAliases.empty()) {4015llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};4016llvm::FunctionType *RegisterAliasTy =4017llvm::FunctionType::get(Builder.getVoidTy(),4018ArgTypes, false);4019llvm::Function *RegisterAlias = llvm::Function::Create(4020RegisterAliasTy,4021llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",4022&TheModule);4023llvm::BasicBlock *AliasBB =4024llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);4025llvm::BasicBlock *NoAliasBB =4026llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);40274028// Branch based on whether the runtime provided class_registerAlias_np()4029llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,4030llvm::Constant::getNullValue(RegisterAlias->getType()));4031Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);40324033// The true branch (has alias registration function):4034Builder.SetInsertPoint(AliasBB);4035// Emit alias registration calls:4036for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();4037iter != ClassAliases.end(); ++iter) {4038llvm::Constant *TheClass =4039TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);4040if (TheClass) {4041Builder.CreateCall(RegisterAlias,4042{TheClass, MakeConstantString(iter->second)});4043}4044}4045// Jump to end:4046Builder.CreateBr(NoAliasBB);40474048// Missing alias registration function, just return from the function:4049Builder.SetInsertPoint(NoAliasBB);4050}4051Builder.CreateRetVoid();40524053return LoadFunction;4054}40554056llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,4057const ObjCContainerDecl *CD) {4058CodeGenTypes &Types = CGM.getTypes();4059llvm::FunctionType *MethodTy =4060Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));40614062bool isDirect = OMD->isDirectMethod();4063std::string FunctionName =4064getSymbolNameForMethod(OMD, /*include category*/ !isDirect);40654066if (!isDirect)4067return llvm::Function::Create(MethodTy,4068llvm::GlobalVariable::InternalLinkage,4069FunctionName, &TheModule);40704071auto *COMD = OMD->getCanonicalDecl();4072auto I = DirectMethodDefinitions.find(COMD);4073llvm::Function *OldFn = nullptr, *Fn = nullptr;40744075if (I == DirectMethodDefinitions.end()) {4076auto *F =4077llvm::Function::Create(MethodTy, llvm::GlobalVariable::ExternalLinkage,4078FunctionName, &TheModule);4079DirectMethodDefinitions.insert(std::make_pair(COMD, F));4080return F;4081}40824083// Objective-C allows for the declaration and implementation types4084// to differ slightly.4085//4086// If we're being asked for the Function associated for a method4087// implementation, a previous value might have been cached4088// based on the type of the canonical declaration.4089//4090// If these do not match, then we'll replace this function with4091// a new one that has the proper type below.4092if (!OMD->getBody() || COMD->getReturnType() == OMD->getReturnType())4093return I->second;40944095OldFn = I->second;4096Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage, "",4097&CGM.getModule());4098Fn->takeName(OldFn);4099OldFn->replaceAllUsesWith(Fn);4100OldFn->eraseFromParent();41014102// Replace the cached function in the map.4103I->second = Fn;4104return Fn;4105}41064107void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,4108llvm::Function *Fn,4109const ObjCMethodDecl *OMD,4110const ObjCContainerDecl *CD) {4111// GNU runtime doesn't support direct calls at this time4112}41134114llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {4115return GetPropertyFn;4116}41174118llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {4119return SetPropertyFn;4120}41214122llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,4123bool copy) {4124return nullptr;4125}41264127llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {4128return GetStructPropertyFn;4129}41304131llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {4132return SetStructPropertyFn;4133}41344135llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {4136return nullptr;4137}41384139llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {4140return nullptr;4141}41424143llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {4144return EnumerationMutationFn;4145}41464147void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,4148const ObjCAtSynchronizedStmt &S) {4149EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);4150}415141524153void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,4154const ObjCAtTryStmt &S) {4155// Unlike the Apple non-fragile runtimes, which also uses4156// unwind-based zero cost exceptions, the GNU Objective C runtime's4157// EH support isn't a veneer over C++ EH. Instead, exception4158// objects are created by objc_exception_throw and destroyed by4159// the personality function; this avoids the need for bracketing4160// catch handlers with calls to __blah_begin_catch/__blah_end_catch4161// (or even _Unwind_DeleteException), but probably doesn't4162// interoperate very well with foreign exceptions.4163//4164// In Objective-C++ mode, we actually emit something equivalent to the C++4165// exception handler.4166EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);4167}41684169void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,4170const ObjCAtThrowStmt &S,4171bool ClearInsertionPoint) {4172llvm::Value *ExceptionAsObject;4173bool isRethrow = false;41744175if (const Expr *ThrowExpr = S.getThrowExpr()) {4176llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);4177ExceptionAsObject = Exception;4178} else {4179assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&4180"Unexpected rethrow outside @catch block.");4181ExceptionAsObject = CGF.ObjCEHValueStack.back();4182isRethrow = true;4183}4184if (isRethrow && (usesSEHExceptions || usesCxxExceptions)) {4185// For SEH, ExceptionAsObject may be undef, because the catch handler is4186// not passed it for catchalls and so it is not visible to the catch4187// funclet. The real thrown object will still be live on the stack at this4188// point and will be rethrown. If we are explicitly rethrowing the object4189// that was passed into the `@catch` block, then this code path is not4190// reached and we will instead call `objc_exception_throw` with an explicit4191// argument.4192llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);4193Throw->setDoesNotReturn();4194} else {4195ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);4196llvm::CallBase *Throw =4197CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);4198Throw->setDoesNotReturn();4199}4200CGF.Builder.CreateUnreachable();4201if (ClearInsertionPoint)4202CGF.Builder.ClearInsertionPoint();4203}42044205llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,4206Address AddrWeakObj) {4207CGBuilderTy &B = CGF.Builder;4208return B.CreateCall(4209WeakReadFn, EnforceType(B, AddrWeakObj.emitRawPointer(CGF), PtrToIdTy));4210}42114212void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,4213llvm::Value *src, Address dst) {4214CGBuilderTy &B = CGF.Builder;4215src = EnforceType(B, src, IdTy);4216llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);4217B.CreateCall(WeakAssignFn, {src, dstVal});4218}42194220void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,4221llvm::Value *src, Address dst,4222bool threadlocal) {4223CGBuilderTy &B = CGF.Builder;4224src = EnforceType(B, src, IdTy);4225llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);4226// FIXME. Add threadloca assign API4227assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");4228B.CreateCall(GlobalAssignFn, {src, dstVal});4229}42304231void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,4232llvm::Value *src, Address dst,4233llvm::Value *ivarOffset) {4234CGBuilderTy &B = CGF.Builder;4235src = EnforceType(B, src, IdTy);4236llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), IdTy);4237B.CreateCall(IvarAssignFn, {src, dstVal, ivarOffset});4238}42394240void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,4241llvm::Value *src, Address dst) {4242CGBuilderTy &B = CGF.Builder;4243src = EnforceType(B, src, IdTy);4244llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);4245B.CreateCall(StrongCastAssignFn, {src, dstVal});4246}42474248void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,4249Address DestPtr,4250Address SrcPtr,4251llvm::Value *Size) {4252CGBuilderTy &B = CGF.Builder;4253llvm::Value *DestPtrVal = EnforceType(B, DestPtr.emitRawPointer(CGF), PtrTy);4254llvm::Value *SrcPtrVal = EnforceType(B, SrcPtr.emitRawPointer(CGF), PtrTy);42554256B.CreateCall(MemMoveFn, {DestPtrVal, SrcPtrVal, Size});4257}42584259llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(4260const ObjCInterfaceDecl *ID,4261const ObjCIvarDecl *Ivar) {4262const std::string Name = GetIVarOffsetVariableName(ID, Ivar);4263// Emit the variable and initialize it with what we think the correct value4264// is. This allows code compiled with non-fragile ivars to work correctly4265// when linked against code which isn't (most of the time).4266llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);4267if (!IvarOffsetPointer)4268IvarOffsetPointer = new llvm::GlobalVariable(4269TheModule, llvm::PointerType::getUnqual(VMContext), false,4270llvm::GlobalValue::ExternalLinkage, nullptr, Name);4271return IvarOffsetPointer;4272}42734274LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,4275QualType ObjectTy,4276llvm::Value *BaseValue,4277const ObjCIvarDecl *Ivar,4278unsigned CVRQualifiers) {4279const ObjCInterfaceDecl *ID =4280ObjectTy->castAs<ObjCObjectType>()->getInterface();4281return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,4282EmitIvarOffset(CGF, ID, Ivar));4283}42844285static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,4286const ObjCInterfaceDecl *OID,4287const ObjCIvarDecl *OIVD) {4288for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;4289next = next->getNextIvar()) {4290if (OIVD == next)4291return OID;4292}42934294// Otherwise check in the super class.4295if (const ObjCInterfaceDecl *Super = OID->getSuperClass())4296return FindIvarInterface(Context, Super, OIVD);42974298return nullptr;4299}43004301llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,4302const ObjCInterfaceDecl *Interface,4303const ObjCIvarDecl *Ivar) {4304if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {4305Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);43064307// The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage4308// and ExternalLinkage, so create a reference to the ivar global and rely on4309// the definition being created as part of GenerateClass.4310if (RuntimeVersion < 10 ||4311CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())4312return CGF.Builder.CreateZExtOrBitCast(4313CGF.Builder.CreateAlignedLoad(4314Int32Ty,4315CGF.Builder.CreateAlignedLoad(4316llvm::PointerType::getUnqual(VMContext),4317ObjCIvarOffsetVariable(Interface, Ivar),4318CGF.getPointerAlign(), "ivar"),4319CharUnits::fromQuantity(4)),4320PtrDiffTy);4321std::string name = "__objc_ivar_offset_value_" +4322Interface->getNameAsString() +"." + Ivar->getNameAsString();4323CharUnits Align = CGM.getIntAlign();4324llvm::Value *Offset = TheModule.getGlobalVariable(name);4325if (!Offset) {4326auto GV = new llvm::GlobalVariable(TheModule, IntTy,4327false, llvm::GlobalValue::LinkOnceAnyLinkage,4328llvm::Constant::getNullValue(IntTy), name);4329GV->setAlignment(Align.getAsAlign());4330Offset = GV;4331}4332Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);4333if (Offset->getType() != PtrDiffTy)4334Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);4335return Offset;4336}4337uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);4338return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);4339}43404341CGObjCRuntime *4342clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {4343auto Runtime = CGM.getLangOpts().ObjCRuntime;4344switch (Runtime.getKind()) {4345case ObjCRuntime::GNUstep:4346if (Runtime.getVersion() >= VersionTuple(2, 0))4347return new CGObjCGNUstep2(CGM);4348return new CGObjCGNUstep(CGM);43494350case ObjCRuntime::GCC:4351return new CGObjCGCC(CGM);43524353case ObjCRuntime::ObjFW:4354return new CGObjCObjFW(CGM);43554356case ObjCRuntime::FragileMacOSX:4357case ObjCRuntime::MacOSX:4358case ObjCRuntime::iOS:4359case ObjCRuntime::WatchOS:4360llvm_unreachable("these runtimes are not GNU runtimes");4361}4362llvm_unreachable("bad runtime");4363}436443654366