#include "CGCXXABI.h"
#include "CGCleanup.h"
#include "CGObjCRuntime.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtObjC.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ConvertUTF.h"
#include <cctype>
using namespace clang;
using namespace CodeGen;
namespace {
class LazyRuntimeFunction {
CodeGenModule *CGM;
llvm::FunctionType *FTy;
const char *FunctionName;
llvm::FunctionCallee Function;
public:
LazyRuntimeFunction()
: CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
template <typename... Tys>
void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
Tys *... Types) {
CGM = Mod;
FunctionName = name;
Function = nullptr;
if(sizeof...(Tys)) {
SmallVector<llvm::Type *, 8> ArgTys({Types...});
FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
}
else {
FTy = llvm::FunctionType::get(RetTy, None, false);
}
}
llvm::FunctionType *getType() { return FTy; }
operator llvm::FunctionCallee() {
if (!Function) {
if (!FunctionName)
return nullptr;
Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
}
return Function;
}
};
class CGObjCGNU : public CGObjCRuntime {
protected:
llvm::Module &TheModule;
llvm::StructType *ObjCSuperTy;
llvm::PointerType *PtrToObjCSuperTy;
llvm::PointerType *SelectorTy;
llvm::Type *SelectorElemTy;
llvm::IntegerType *Int8Ty;
llvm::PointerType *PtrToInt8Ty;
llvm::StructType *ProtocolTy;
llvm::PointerType *ProtocolPtrTy;
llvm::PointerType *IMPTy;
llvm::PointerType *IdTy;
llvm::Type *IdElemTy;
llvm::PointerType *PtrToIdTy;
CanQualType ASTIdTy;
llvm::IntegerType *IntTy;
llvm::PointerType *PtrTy;
llvm::IntegerType *LongTy;
llvm::IntegerType *SizeTy;
llvm::IntegerType *IntPtrTy;
llvm::IntegerType *PtrDiffTy;
llvm::PointerType *PtrToIntTy;
llvm::Type *BoolTy;
llvm::IntegerType *Int32Ty;
llvm::IntegerType *Int64Ty;
llvm::StructType *PropertyMetadataTy;
unsigned msgSendMDKind;
bool usesSEHExceptions;
bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
return (R.getKind() == kind) &&
(R.getVersion() >= VersionTuple(major, minor));
}
std::string ManglePublicSymbol(StringRef Name) {
return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
}
std::string SymbolForProtocol(Twine Name) {
return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
}
std::string SymbolForProtocolRef(StringRef Name) {
return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
}
llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
ConstantAddress Array =
CGM.GetAddrOfConstantCString(std::string(Str), Name);
return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
Array.getPointer(), Zeros);
}
llvm::Constant *ExportUniqueString(const std::string &Str,
const std::string &prefix,
bool Private=false) {
std::string name = prefix + Str;
auto *ConstStr = TheModule.getGlobalVariable(name);
if (!ConstStr) {
llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
llvm::GlobalValue::LinkOnceODRLinkage, value, name);
GV->setComdat(TheModule.getOrInsertComdat(name));
if (Private)
GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
ConstStr = GV;
}
return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
ConstStr, Zeros);
}
llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
const Decl *Container) {
assert(!isRuntime(ObjCRuntime::GNUstep, 2));
if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
std::string NameAndAttributes;
std::string TypeStr =
CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
NameAndAttributes += '\0';
NameAndAttributes += TypeStr.length() + 3;
NameAndAttributes += TypeStr;
NameAndAttributes += '\0';
NameAndAttributes += PD->getNameAsString();
return MakeConstantString(NameAndAttributes);
}
return MakeConstantString(PD->getNameAsString());
}
void PushPropertyAttributes(ConstantStructBuilder &Fields,
const ObjCPropertyDecl *property, bool isSynthesized=true, bool
isDynamic=true) {
int attrs = property->getPropertyAttributes();
if (attrs & ObjCPropertyAttribute::kind_readonly) {
attrs &= ~ObjCPropertyAttribute::kind_copy;
attrs &= ~ObjCPropertyAttribute::kind_retain;
attrs &= ~ObjCPropertyAttribute::kind_weak;
attrs &= ~ObjCPropertyAttribute::kind_strong;
}
Fields.addInt(Int8Ty, attrs & 0xff);
attrs >>= 8;
attrs <<= 2;
attrs |= isSynthesized ? (1<<0) : 0;
attrs |= isDynamic ? (1<<1) : 0;
Fields.addInt(Int8Ty, attrs & 0xff);
Fields.addInt(Int8Ty, 0);
Fields.addInt(Int8Ty, 0);
}
virtual llvm::Constant *GenerateCategoryProtocolList(const
ObjCCategoryDecl *OCD);
virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
int count) {
Fields.addInt(IntTy, count);
if (isRuntime(ObjCRuntime::GNUstep, 2)) {
llvm::DataLayout td(&TheModule);
Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
CGM.getContext().getCharWidth());
}
Fields.add(NULLPtr);
return Fields.beginArray(PropertyMetadataTy);
}
virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
const ObjCPropertyDecl *property,
const Decl *OCD,
bool isSynthesized=true, bool
isDynamic=true) {
auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
ASTContext &Context = CGM.getContext();
Fields.add(MakePropertyEncodingString(property, OCD));
PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
if (accessor) {
std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
Fields.add(TypeEncoding);
} else {
Fields.add(NULLPtr);
Fields.add(NULLPtr);
}
};
addPropertyMethod(property->getGetterMethodDecl());
addPropertyMethod(property->getSetterMethodDecl());
Fields.finishAndAddTo(PropertiesArray);
}
llvm::Value *EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
if (V->getType() == Ty)
return V;
return B.CreateBitCast(V, Ty);
}
llvm::Constant *Zeros[2];
llvm::Constant *NULLPtr;
llvm::LLVMContext &VMContext;
protected:
llvm::GlobalAlias *ClassPtrAlias;
llvm::GlobalAlias *MetaClassPtrAlias;
std::vector<llvm::Constant*> Classes;
std::vector<llvm::Constant*> Categories;
std::vector<llvm::Constant*> ConstantStrings;
llvm::StringMap<llvm::Constant*> ObjCStrings;
llvm::StringMap<llvm::Constant*> ExistingProtocols;
typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
SelectorMap;
SelectorMap SelectorTable;
Selector RetainSel, ReleaseSel, AutoreleaseSel;
LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
WeakAssignFn, GlobalAssignFn;
typedef std::pair<std::string, std::string> ClassAliasPair;
std::vector<ClassAliasPair> ClassAliases;
protected:
LazyRuntimeFunction ExceptionThrowFn;
LazyRuntimeFunction ExceptionReThrowFn;
LazyRuntimeFunction EnterCatchFn;
LazyRuntimeFunction ExitCatchFn;
LazyRuntimeFunction SyncEnterFn;
LazyRuntimeFunction SyncExitFn;
private:
LazyRuntimeFunction EnumerationMutationFn;
LazyRuntimeFunction GetPropertyFn;
LazyRuntimeFunction SetPropertyFn;
LazyRuntimeFunction GetStructPropertyFn;
LazyRuntimeFunction SetStructPropertyFn;
protected:
int RuntimeVersion;
const int ProtocolVersion;
const int ClassABIVersion;
virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
ArrayRef<llvm::Constant *> IvarTypes,
ArrayRef<llvm::Constant *> IvarOffsets,
ArrayRef<llvm::Constant *> IvarAlign,
ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
llvm::Constant *GenerateMethodList(StringRef ClassName,
StringRef CategoryName,
ArrayRef<const ObjCMethodDecl*> Methods,
bool isClassMethodList);
virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
llvm::Constant *GeneratePropertyList(const Decl *Container,
const ObjCContainerDecl *OCD,
bool isClassProperty=false,
bool protocolOptionalProperties=false);
llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
void GenerateProtocolHolderCategory();
llvm::Constant *GenerateClassStructure(
llvm::Constant *MetaClass,
llvm::Constant *SuperClass,
unsigned info,
const char *Name,
llvm::Constant *Version,
llvm::Constant *InstanceSize,
llvm::Constant *IVars,
llvm::Constant *Methods,
llvm::Constant *Protocols,
llvm::Constant *IvarOffsets,
llvm::Constant *Properties,
llvm::Constant *StrongIvarBitmap,
llvm::Constant *WeakIvarBitmap,
bool isMeta=false);
virtual llvm::Constant *GenerateProtocolMethodList(
ArrayRef<const ObjCMethodDecl*> Methods);
template<class T>
void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
llvm::Constant *&Optional) {
SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
for (const auto *I : Methods)
if (I->isOptional())
OptionalMethods.push_back(I);
else
RequiredMethods.push_back(I);
Required = GenerateProtocolMethodList(RequiredMethods);
Optional = GenerateProtocolMethodList(OptionalMethods);
}
virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
const std::string &TypeEncoding);
virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
const ObjCIvarDecl *Ivar) {
const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
+ '.' + Ivar->getNameAsString();
return Name;
}
llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
const ObjCIvarDecl *Ivar);
void EmitClassRef(const std::string &className);
virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
const std::string &Name, bool isWeak);
virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
llvm::Value *&Receiver,
llvm::Value *cmd,
llvm::MDNode *node,
MessageSendInfo &MSI) = 0;
virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
Address ObjCSuper,
llvm::Value *cmd,
MessageSendInfo &MSI) = 0;
llvm::Constant *MakeBitField(ArrayRef<bool> bits);
public:
CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
unsigned protocolClassVersion, unsigned classABI=1);
ConstantAddress GenerateConstantString(const StringLiteral *) override;
RValue
GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
QualType ResultType, Selector Sel,
llvm::Value *Receiver, const CallArgList &CallArgs,
const ObjCInterfaceDecl *Class,
const ObjCMethodDecl *Method) override;
RValue
GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
QualType ResultType, Selector Sel,
const ObjCInterfaceDecl *Class,
bool isCategoryImpl, llvm::Value *Receiver,
bool IsClassMessage, const CallArgList &CallArgs,
const ObjCMethodDecl *Method) override;
llvm::Value *GetClass(CodeGenFunction &CGF,
const ObjCInterfaceDecl *OID) override;
llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
llvm::Value *GetSelector(CodeGenFunction &CGF,
const ObjCMethodDecl *Method) override;
virtual llvm::Constant *GetConstantSelector(Selector Sel,
const std::string &TypeEncoding) {
llvm_unreachable("Runtime unable to generate constant selector");
}
llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
return GetConstantSelector(M->getSelector(),
CGM.getContext().getObjCEncodingForMethodDecl(M));
}
llvm::Constant *GetEHType(QualType T) override;
llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
const ObjCContainerDecl *CD) override;
void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
const ObjCMethodDecl *OMD,
const ObjCContainerDecl *CD) override;
void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
const ObjCProtocolDecl *PD) override;
void GenerateProtocol(const ObjCProtocolDecl *PD) override;
virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD);
llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override {
return GenerateProtocolRef(PD);
}
llvm::Function *ModuleInitFunction() override;
llvm::FunctionCallee GetPropertyGetFunction() override;
llvm::FunctionCallee GetPropertySetFunction() override;
llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
bool copy) override;
llvm::FunctionCallee GetSetStructFunction() override;
llvm::FunctionCallee GetGetStructFunction() override;
llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
llvm::FunctionCallee EnumerationMutationFunction() override;
void EmitTryStmt(CodeGenFunction &CGF,
const ObjCAtTryStmt &S) override;
void EmitSynchronizedStmt(CodeGenFunction &CGF,
const ObjCAtSynchronizedStmt &S) override;
void EmitThrowStmt(CodeGenFunction &CGF,
const ObjCAtThrowStmt &S,
bool ClearInsertionPoint=true) override;
llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Address AddrWeakObj) override;
void EmitObjCWeakAssign(CodeGenFunction &CGF,
llvm::Value *src, Address dst) override;
void EmitObjCGlobalAssign(CodeGenFunction &CGF,
llvm::Value *src, Address dest,
bool threadlocal=false) override;
void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
Address dest, llvm::Value *ivarOffset) override;
void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
llvm::Value *src, Address dest) override;
void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
Address SrcPtr,
llvm::Value *Size) override;
LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
unsigned CVRQualifiers) override;
llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
const ObjCInterfaceDecl *Interface,
const ObjCIvarDecl *Ivar) override;
llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
const CGBlockInfo &blockInfo) override {
return NULLPtr;
}
llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
const CGBlockInfo &blockInfo) override {
return NULLPtr;
}
llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
return NULLPtr;
}
};
class CGObjCGCC : public CGObjCGNU {
LazyRuntimeFunction MsgLookupFn;
LazyRuntimeFunction MsgLookupSuperFn;
protected:
llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
llvm::Value *cmd, llvm::MDNode *node,
MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *args[] = {
EnforceType(Builder, Receiver, IdTy),
EnforceType(Builder, cmd, SelectorTy) };
llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
imp->setMetadata(msgSendMDKind, node);
return imp;
}
llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
llvm::Value *cmd, MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *lookupArgs[] = {
EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd};
return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
}
public:
CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
PtrToObjCSuperTy, SelectorTy);
}
};
class CGObjCGNUstep : public CGObjCGNU {
LazyRuntimeFunction SlotLookupFn;
LazyRuntimeFunction SlotLookupSuperFn;
LazyRuntimeFunction SetPropertyAtomic;
LazyRuntimeFunction SetPropertyAtomicCopy;
LazyRuntimeFunction SetPropertyNonAtomic;
LazyRuntimeFunction SetPropertyNonAtomicCopy;
LazyRuntimeFunction CxxAtomicObjectGetFn;
LazyRuntimeFunction CxxAtomicObjectSetFn;
llvm::Type *SlotTy;
llvm::Type *SlotStructTy;
public:
llvm::Constant *GetEHType(QualType T) override;
protected:
llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
llvm::Value *cmd, llvm::MDNode *node,
MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::FunctionCallee LookupFn = SlotLookupFn;
Address ReceiverPtr =
CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
Builder.CreateStore(Receiver, ReceiverPtr);
llvm::Value *self;
if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
self = CGF.LoadObjCSelf();
} else {
self = llvm::ConstantPointerNull::get(IdTy);
}
if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
llvm::Value *args[] = {
EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
EnforceType(Builder, cmd, SelectorTy),
EnforceType(Builder, self, IdTy) };
llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
slot->setOnlyReadsMemory();
slot->setMetadata(msgSendMDKind, node);
llvm::Value *imp = Builder.CreateAlignedLoad(
IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
CGF.getPointerAlign());
Receiver = Builder.CreateLoad(ReceiverPtr, true);
return imp;
}
llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
llvm::Value *cmd,
MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
llvm::CallInst *slot =
CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
slot->setOnlyReadsMemory();
return Builder.CreateAlignedLoad(
IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
CGF.getPointerAlign());
}
public:
CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
unsigned ClassABI) :
CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
SelectorTy, IdTy);
SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
PtrToObjCSuperTy, SelectorTy);
if (usesSEHExceptions) {
llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
} else if (CGM.getLangOpts().CPlusPlus) {
llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
PtrTy);
} else if (R.getVersion() >= VersionTuple(1, 7)) {
llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
}
llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
SelectorTy, IdTy, PtrDiffTy);
SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
IdTy, SelectorTy, IdTy, PtrDiffTy);
SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
IdTy, SelectorTy, IdTy, PtrDiffTy);
SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
PtrTy, PtrTy);
CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
PtrTy, PtrTy);
}
llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
VersionTuple(1, 7));
return CxxAtomicObjectGetFn;
}
llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
VersionTuple(1, 7));
return CxxAtomicObjectSetFn;
}
llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
bool copy) override {
assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
VersionTuple(1, 7));
if (atomic) {
if (copy) return SetPropertyAtomicCopy;
return SetPropertyAtomic;
}
return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
}
};
class CGObjCGNUstep2 : public CGObjCGNUstep {
enum SectionKind
{
SelectorSection = 0,
ClassSection,
ClassReferenceSection,
CategorySection,
ProtocolSection,
ProtocolReferenceSection,
ClassAliasSection,
ConstantStringSection
};
static const char *const SectionsBaseNames[8];
static const char *const PECOFFSectionsBaseNames[8];
template<SectionKind K>
std::string sectionName() {
if (CGM.getTriple().isOSBinFormatCOFF()) {
std::string name(PECOFFSectionsBaseNames[K]);
name += "$m";
return name;
}
return SectionsBaseNames[K];
}
LazyRuntimeFunction MsgLookupSuperFn;
bool EmittedProtocol = false;
bool EmittedProtocolRef = false;
bool EmittedClass = false;
typedef std::pair<std::string, std::pair<llvm::GlobalVariable*, int>>
EarlyInitPair;
std::vector<EarlyInitPair> EarlyInitList;
std::string SymbolForClassRef(StringRef Name, bool isWeak) {
if (isWeak)
return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
else
return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
}
std::string SymbolForClass(StringRef Name) {
return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
}
void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
ArrayRef<llvm::Value*> Args) {
SmallVector<llvm::Type *,8> Types;
for (auto *Arg : Args)
Types.push_back(Arg->getType());
llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
false);
llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
B.CreateCall(Fn, Args);
}
ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
auto Str = SL->getString();
CharUnits Align = CGM.getPointerAlign();
llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
if (old != ObjCStrings.end())
return ConstantAddress(old->getValue(), IdElemTy, Align);
bool isNonASCII = SL->containsNonAscii();
auto LiteralLength = SL->getLength();
if ((CGM.getTarget().getPointerWidth(0) == 64) &&
(LiteralLength < 9) && !isNonASCII) {
uint64_t str = 0;
for (unsigned i=0 ; i<LiteralLength ; i++)
str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
str |= LiteralLength << 3;
str |= 4;
auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
llvm::ConstantInt::get(Int64Ty, str), IdTy);
ObjCStrings[Str] = ObjCStr;
return ConstantAddress(ObjCStr, IdElemTy, Align);
}
StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
if (StringClass.empty()) StringClass = "NSConstantString";
std::string Sym = SymbolForClass(StringClass);
llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
if (!isa) {
isa = new llvm::GlobalVariable(TheModule, IdTy, false,
llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
if (CGM.getTriple().isOSBinFormatCOFF()) {
cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
}
} else if (isa->getType() != PtrToIdTy)
isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
ConstantInitBuilder Builder(CGM);
auto Fields = Builder.beginStruct();
if (!CGM.getTriple().isOSBinFormatCOFF()) {
Fields.add(isa);
} else {
Fields.addNullPointer(PtrTy);
}
if (isNonASCII) {
unsigned NumU8CodeUnits = Str.size();
SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
llvm::UTF16 *ToPtr = &ToBuf[0];
(void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
&ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
uint32_t StringLength = ToPtr - &ToBuf[0];
*ToPtr = 0;
Fields.addInt(Int32Ty, 2);
Fields.addInt(Int32Ty, StringLength);
Fields.addInt(Int32Ty, StringLength * 2);
Fields.addInt(Int32Ty, 0);
auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
true, llvm::GlobalValue::PrivateLinkage, C, ".str");
Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Fields.add(Buffer);
} else {
Fields.addInt(Int32Ty, 0);
Fields.addInt(Int32Ty, Str.size());
Fields.addInt(Int32Ty, Str.size());
Fields.addInt(Int32Ty, 0);
Fields.add(MakeConstantString(Str));
}
std::string StringName;
bool isNamed = !isNonASCII;
if (isNamed) {
StringName = ".objc_str_";
for (int i=0,e=Str.size() ; i<e ; ++i) {
unsigned char c = Str[i];
if (isalnum(c))
StringName += c;
else if (c == ' ')
StringName += '_';
else {
isNamed = false;
break;
}
}
}
llvm::GlobalVariable *ObjCStrGV =
Fields.finishAndCreateGlobal(
isNamed ? StringRef(StringName) : ".objc_string",
Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
: llvm::GlobalValue::PrivateLinkage);
ObjCStrGV->setSection(sectionName<ConstantStringSection>());
if (isNamed) {
ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
}
if (CGM.getTriple().isOSBinFormatCOFF()) {
std::pair<llvm::GlobalVariable*, int> v{ObjCStrGV, 0};
EarlyInitList.emplace_back(Sym, v);
}
llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
ObjCStrings[Str] = ObjCStr;
ConstantStrings.push_back(ObjCStr);
return ConstantAddress(ObjCStr, IdElemTy, Align);
}
void PushProperty(ConstantArrayBuilder &PropertiesArray,
const ObjCPropertyDecl *property,
const Decl *OCD,
bool isSynthesized=true, bool
isDynamic=true) override {
auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
ASTContext &Context = CGM.getContext();
Fields.add(MakeConstantString(property->getNameAsString()));
std::string TypeStr =
CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
Fields.add(MakeConstantString(TypeStr));
std::string typeStr;
Context.getObjCEncodingForType(property->getType(), typeStr);
Fields.add(MakeConstantString(typeStr));
auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
if (accessor) {
std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
} else {
Fields.add(NULLPtr);
}
};
addPropertyMethod(property->getGetterMethodDecl());
addPropertyMethod(property->getSetterMethodDecl());
Fields.finishAndAddTo(PropertiesArray);
}
llvm::Constant *
GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
llvm::StructType *ObjCMethodDescTy =
llvm::StructType::get(CGM.getLLVMContext(),
{ PtrToInt8Ty, PtrToInt8Ty });
ASTContext &Context = CGM.getContext();
ConstantInitBuilder Builder(CGM);
auto MethodList = Builder.beginStruct();
MethodList.addInt(IntTy, Methods.size());
llvm::DataLayout td(&TheModule);
MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
CGM.getContext().getCharWidth());
auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
for (auto *M : Methods) {
auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
Method.add(CGObjCGNU::GetConstantSelector(M));
Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
Method.finishAndAddTo(MethodArray);
}
MethodArray.finishAndAddTo(MethodList);
return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
CGM.getPointerAlign());
}
llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
override {
const auto &ReferencedProtocols = OCD->getReferencedProtocols();
auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),
ReferencedProtocols.end());
SmallVector<llvm::Constant *, 16> Protocols;
for (const auto *PI : RuntimeProtocols)
Protocols.push_back(
llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
ProtocolPtrTy));
return GenerateProtocolList(Protocols);
}
llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
llvm::Value *cmd, MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder,
ObjCSuper.getPointer(),
PtrToObjCSuperTy),
cmd};
return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
}
llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
std::string SymbolName = SymbolForClassRef(Name, isWeak);
auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
if (ClassSymbol)
return ClassSymbol;
ClassSymbol = new llvm::GlobalVariable(TheModule,
IdTy, false, llvm::GlobalValue::ExternalLinkage,
nullptr, SymbolName);
if (isWeak)
ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
nullptr, SymbolForClass(Name)));
else {
if (CGM.getTriple().isOSBinFormatCOFF()) {
IdentifierInfo &II = CGM.getContext().Idents.get(Name);
TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
const ObjCInterfaceDecl *OID = nullptr;
for (const auto *Result : DC->lookup(&II))
if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
break;
assert(OID && "Failed to find ObjCInterfaceDecl");
const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
if (OIDDef != nullptr)
OID = OIDDef;
auto Storage = llvm::GlobalValue::DefaultStorageClass;
if (OID->hasAttr<DLLImportAttr>())
Storage = llvm::GlobalValue::DLLImportStorageClass;
else if (OID->hasAttr<DLLExportAttr>())
Storage = llvm::GlobalValue::DLLExportStorageClass;
cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
}
}
assert(ClassSymbol->getName() == SymbolName);
return ClassSymbol;
}
llvm::Value *GetClassNamed(CodeGenFunction &CGF,
const std::string &Name,
bool isWeak) override {
return CGF.Builder.CreateLoad(
Address(GetClassVar(Name, isWeak), IdTy, CGM.getPointerAlign()));
}
int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
int Flag;
switch (Ownership) {
case Qualifiers::OCL_Strong:
Flag = 1;
break;
case Qualifiers::OCL_Weak:
Flag = 2;
break;
case Qualifiers::OCL_ExplicitNone:
Flag = 3;
break;
case Qualifiers::OCL_None:
case Qualifiers::OCL_Autoreleasing:
assert(Ownership != Qualifiers::OCL_Autoreleasing);
Flag = 0;
}
return Flag;
}
llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
ArrayRef<llvm::Constant *> IvarTypes,
ArrayRef<llvm::Constant *> IvarOffsets,
ArrayRef<llvm::Constant *> IvarAlign,
ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
llvm_unreachable("Method should not be called!");
}
llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
std::string Name = SymbolForProtocol(ProtocolName);
auto *GV = TheModule.getGlobalVariable(Name);
if (!GV) {
GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
llvm::GlobalValue::ExternalLinkage, nullptr, Name);
GV->setAlignment(CGM.getPointerAlign().getAsAlign());
}
return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
}
llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
const ObjCProtocolDecl *PD) override {
auto Name = PD->getNameAsString();
auto *&Ref = ExistingProtocolRefs[Name];
if (!Ref) {
auto *&Protocol = ExistingProtocols[Name];
if (!Protocol)
Protocol = GenerateProtocolRef(PD);
std::string RefName = SymbolForProtocolRef(Name);
assert(!TheModule.getGlobalVariable(RefName));
auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
false, llvm::GlobalValue::LinkOnceODRLinkage,
llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
GV->setComdat(TheModule.getOrInsertComdat(RefName));
GV->setSection(sectionName<ProtocolReferenceSection>());
GV->setAlignment(CGM.getPointerAlign().getAsAlign());
Ref = GV;
}
EmittedProtocolRef = true;
return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,
CGM.getPointerAlign());
}
llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
Protocols.size());
llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Protocols);
ConstantInitBuilder builder(CGM);
auto ProtocolBuilder = builder.beginStruct();
ProtocolBuilder.addNullPointer(PtrTy);
ProtocolBuilder.addInt(SizeTy, Protocols.size());
ProtocolBuilder.add(ProtocolArray);
return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
}
void GenerateProtocol(const ObjCProtocolDecl *PD) override {
}
llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {
std::string ProtocolName = PD->getNameAsString();
auto *&Protocol = ExistingProtocols[ProtocolName];
if (Protocol)
return Protocol;
EmittedProtocol = true;
auto SymName = SymbolForProtocol(ProtocolName);
auto *OldGV = TheModule.getGlobalVariable(SymName);
if (const ObjCProtocolDecl *Def = PD->getDefinition())
PD = Def;
else {
assert(!OldGV);
Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
false,
llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
return Protocol;
}
SmallVector<llvm::Constant*, 16> Protocols;
auto RuntimeProtocols =
GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());
for (const auto *PI : RuntimeProtocols)
Protocols.push_back(
llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
ProtocolPtrTy));
llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
llvm::Constant *ClassMethodList, *OptionalClassMethodList;
EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
OptionalInstanceMethodList);
EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
OptionalClassMethodList);
ConstantInitBuilder builder(CGM);
auto ProtocolBuilder = builder.beginStruct();
ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
ProtocolBuilder.add(MakeConstantString(ProtocolName));
ProtocolBuilder.add(ProtocolList);
ProtocolBuilder.add(InstanceMethodList);
ProtocolBuilder.add(ClassMethodList);
ProtocolBuilder.add(OptionalInstanceMethodList);
ProtocolBuilder.add(OptionalClassMethodList);
ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
GV->setSection(sectionName<ProtocolSection>());
GV->setComdat(TheModule.getOrInsertComdat(SymName));
if (OldGV) {
OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
OldGV->getType()));
OldGV->removeFromParent();
GV->setName(SymName);
}
Protocol = GV;
return GV;
}
llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
if (Val->getType() == Ty)
return Val;
return llvm::ConstantExpr::getBitCast(Val, Ty);
}
llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
const std::string &TypeEncoding) override {
return GetConstantSelector(Sel, TypeEncoding);
}
llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
if (TypeEncoding.empty())
return NULLPtr;
std::string MangledTypes = std::string(TypeEncoding);
std::replace(MangledTypes.begin(), MangledTypes.end(),
'@', '\1');
std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
if (!TypesGlobal) {
llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
TypeEncoding);
auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
TypesGlobal = GV;
}
return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
TypesGlobal, Zeros);
}
llvm::Constant *GetConstantSelector(Selector Sel,
const std::string &TypeEncoding) override {
std::string MangledTypes = TypeEncoding;
std::replace(MangledTypes.begin(), MangledTypes.end(),
'@', '\1');
auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
MangledTypes).str();
if (auto *GV = TheModule.getNamedGlobal(SelVarName))
return EnforceType(GV, SelectorTy);
ConstantInitBuilder builder(CGM);
auto SelBuilder = builder.beginStruct();
SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
true));
SelBuilder.add(GetTypeString(TypeEncoding));
auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
GV->setSection(sectionName<SelectorSection>());
auto *SelVal = EnforceType(GV, SelectorTy);
return SelVal;
}
llvm::StructType *emptyStruct = nullptr;
std::pair<llvm::Constant*,llvm::Constant*>
GetSectionBounds(StringRef Section) {
if (CGM.getTriple().isOSBinFormatCOFF()) {
if (emptyStruct == nullptr) {
emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
emptyStruct->setBody({}, true);
}
auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
false,
llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
Section);
Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
Sym->setSection((Section + SecSuffix).str());
Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
Section).str()));
Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
return Sym;
};
return { Sym("__start_", "$a"), Sym("__stop", "$z") };
}
auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
false,
llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
Section);
Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
false,
llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
Section);
Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
return { Start, Stop };
}
CatchTypeInfo getCatchAllTypeInfo() override {
return CGM.getCXXABI().getCatchAllTypeInfo();
}
llvm::Function *ModuleInitFunction() override {
llvm::Function *LoadFunction = llvm::Function::Create(
llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
&TheModule);
LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
llvm::BasicBlock *EntryBB =
llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
CGBuilderTy B(CGM, VMContext);
B.SetInsertPoint(EntryBB);
ConstantInitBuilder builder(CGM);
auto InitStructBuilder = builder.beginStruct();
InitStructBuilder.addInt(Int64Ty, 0);
auto §ionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
for (auto *s : sectionVec) {
auto bounds = GetSectionBounds(s);
InitStructBuilder.add(bounds.first);
InitStructBuilder.add(bounds.second);
}
auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
CallRuntimeFunction(B, "__objc_load", {InitStruct});;
B.CreateRetVoid();
CGM.addCompilerUsedGlobal(LoadFunction);
auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
false, llvm::GlobalValue::LinkOnceAnyLinkage,
LoadFunction, ".objc_ctor");
assert(InitVar->getName() == ".objc_ctor");
if (CGM.getTriple().isOSBinFormatCOFF())
InitVar->setSection(".CRT$XCLz");
else
{
if (CGM.getCodeGenOpts().UseInitArray)
InitVar->setSection(".init_array");
else
InitVar->setSection(".ctors");
}
InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
CGM.addUsedGlobal(InitVar);
for (auto *C : Categories) {
auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
Cat->setSection(sectionName<CategorySection>());
CGM.addUsedGlobal(Cat);
}
auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
StringRef Section) {
auto nullBuilder = builder.beginStruct();
for (auto *F : Init)
nullBuilder.add(F);
auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
false, llvm::GlobalValue::LinkOnceODRLinkage);
GV->setSection(Section);
GV->setComdat(TheModule.getOrInsertComdat(Name));
GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
CGM.addUsedGlobal(GV);
return GV;
};
for (auto clsAlias : ClassAliases)
createNullGlobal(std::string(".objc_class_alias") +
clsAlias.second, { MakeConstantString(clsAlias.second),
GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
if (!CGM.getTriple().isOSBinFormatCOFF()) {
createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
sectionName<SelectorSection>());
if (Categories.empty())
createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
sectionName<CategorySection>());
if (!EmittedClass) {
createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
sectionName<ClassSection>());
createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
sectionName<ClassReferenceSection>());
}
if (!EmittedProtocol)
createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
NULLPtr}, sectionName<ProtocolSection>());
if (!EmittedProtocolRef)
createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
sectionName<ProtocolReferenceSection>());
if (ClassAliases.empty())
createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
sectionName<ClassAliasSection>());
if (ConstantStrings.empty()) {
auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
i32Zero, i32Zero, i32Zero, NULLPtr },
sectionName<ConstantStringSection>());
}
}
ConstantStrings.clear();
Categories.clear();
Classes.clear();
if (EarlyInitList.size() > 0) {
auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
{}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
&CGM.getModule());
llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
Init));
for (const auto &lateInit : EarlyInitList) {
auto *global = TheModule.getGlobalVariable(lateInit.first);
if (global) {
llvm::GlobalVariable *GV = lateInit.second.first;
b.CreateAlignedStore(
global,
b.CreateStructGEP(GV->getValueType(), GV, lateInit.second.second),
CGM.getPointerAlign().getAsAlign());
}
}
b.CreateRetVoid();
auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
true, llvm::GlobalValue::InternalLinkage,
Init, ".objc_early_init_ptr");
InitVar->setSection(".CRT$XCLb");
CGM.addUsedGlobal(InitVar);
}
return nullptr;
}
std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
const ObjCIvarDecl *Ivar) override {
std::string TypeEncoding;
CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
std::replace(TypeEncoding.begin(), TypeEncoding.end(),
'@', '\1');
const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
+ '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
return Name;
}
llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
const ObjCInterfaceDecl *Interface,
const ObjCIvarDecl *Ivar) override {
const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
if (!IvarOffsetPointer)
IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
llvm::GlobalValue::ExternalLinkage, nullptr, Name);
CharUnits Align = CGM.getIntAlign();
llvm::Value *Offset =
CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
if (Offset->getType() != PtrDiffTy)
Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
return Offset;
}
void GenerateClass(const ObjCImplementationDecl *OID) override {
ASTContext &Context = CGM.getContext();
bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
ObjCInterfaceDecl *classDecl =
const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
std::string className = classDecl->getNameAsString();
auto *classNameConstant = MakeConstantString(className);
ConstantInitBuilder builder(CGM);
auto metaclassFields = builder.beginStruct();
metaclassFields.addNullPointer(PtrTy);
metaclassFields.addNullPointer(PtrTy);
metaclassFields.add(classNameConstant);
metaclassFields.addInt(LongTy, 0);
metaclassFields.addInt(LongTy, 1);
metaclassFields.addInt(LongTy, 0);
metaclassFields.addNullPointer(PtrTy);
if (OID->classmeth_begin() == OID->classmeth_end())
metaclassFields.addNullPointer(PtrTy);
else {
SmallVector<ObjCMethodDecl*, 16> ClassMethods;
ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
OID->classmeth_end());
metaclassFields.addBitCast(
GenerateMethodList(className, "", ClassMethods, true),
PtrTy);
}
metaclassFields.addNullPointer(PtrTy);
metaclassFields.addNullPointer(PtrTy);
metaclassFields.addNullPointer(PtrTy);
metaclassFields.addNullPointer(PtrTy);
metaclassFields.addNullPointer(PtrTy);
metaclassFields.addNullPointer(PtrTy);
metaclassFields.addNullPointer(PtrTy);
metaclassFields.addInt(LongTy, 0);
metaclassFields.add(GeneratePropertyList(OID, classDecl, true));
auto *metaclass = metaclassFields.finishAndCreateGlobal(
ManglePublicSymbol("OBJC_METACLASS_") + className,
CGM.getPointerAlign());
auto classFields = builder.beginStruct();
classFields.add(metaclass);
const ObjCInterfaceDecl * SuperClassDecl =
OID->getClassInterface()->getSuperClass();
llvm::Constant *SuperClass = nullptr;
if (SuperClassDecl) {
auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
SuperClass = TheModule.getNamedGlobal(SuperClassName);
if (!SuperClass)
{
SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
if (IsCOFF) {
auto Storage = llvm::GlobalValue::DefaultStorageClass;
if (SuperClassDecl->hasAttr<DLLImportAttr>())
Storage = llvm::GlobalValue::DLLImportStorageClass;
else if (SuperClassDecl->hasAttr<DLLExportAttr>())
Storage = llvm::GlobalValue::DLLExportStorageClass;
cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
}
}
if (!IsCOFF)
classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
else
classFields.addNullPointer(PtrTy);
} else
classFields.addNullPointer(PtrTy);
classFields.add(classNameConstant);
classFields.addInt(LongTy, 0);
classFields.addInt(LongTy, 0);
int superInstanceSize = !SuperClassDecl ? 0 :
Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
classFields.addInt(LongTy,
0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
superInstanceSize));
if (classDecl->all_declared_ivar_begin() == nullptr)
classFields.addNullPointer(PtrTy);
else {
int ivar_count = 0;
for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
IVD = IVD->getNextIvar()) ivar_count++;
llvm::DataLayout td(&TheModule);
ConstantInitBuilder b(CGM);
auto ivarListBuilder = b.beginStruct();
ivarListBuilder.addInt(IntTy, ivar_count);
llvm::StructType *ObjCIvarTy = llvm::StructType::get(
PtrToInt8Ty,
PtrToInt8Ty,
PtrToInt8Ty,
Int32Ty,
Int32Ty);
ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
CGM.getContext().getCharWidth());
auto ivarArrayBuilder = ivarListBuilder.beginArray();
for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
IVD = IVD->getNextIvar()) {
auto ivarTy = IVD->getType();
auto ivarBuilder = ivarArrayBuilder.beginStruct();
ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
std::string TypeStr;
Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
ivarBuilder.add(MakeConstantString(TypeStr));
uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
uint64_t Offset = BaseOffset - superInstanceSize;
llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
if (OffsetVar)
OffsetVar->setInitializer(OffsetValue);
else
OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
false, llvm::GlobalValue::ExternalLinkage,
OffsetValue, OffsetName);
auto ivarVisibility =
(IVD->getAccessControl() == ObjCIvarDecl::Private ||
IVD->getAccessControl() == ObjCIvarDecl::Package ||
classDecl->getVisibility() == HiddenVisibility) ?
llvm::GlobalValue::HiddenVisibility :
llvm::GlobalValue::DefaultVisibility;
OffsetVar->setVisibility(ivarVisibility);
ivarBuilder.add(OffsetVar);
ivarBuilder.addInt(Int32Ty,
CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
unsigned align =
llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
assert(align < 64);
ivarBuilder.addInt(Int32Ty,
(align << 3) | (1<<2) |
FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
ivarBuilder.finishAndAddTo(ivarArrayBuilder);
}
ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
CGM.getPointerAlign(), false,
llvm::GlobalValue::PrivateLinkage);
classFields.add(ivarList);
}
SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
OID->instmeth_end());
for (auto *propImpl : OID->property_impls())
if (propImpl->getPropertyImplementation() ==
ObjCPropertyImplDecl::Synthesize) {
auto addIfExists = [&](const ObjCMethodDecl *OMD) {
if (OMD && OMD->hasBody())
InstanceMethods.push_back(OMD);
};
addIfExists(propImpl->getGetterMethodDecl());
addIfExists(propImpl->getSetterMethodDecl());
}
if (InstanceMethods.size() == 0)
classFields.addNullPointer(PtrTy);
else
classFields.addBitCast(
GenerateMethodList(className, "", InstanceMethods, false),
PtrTy);
classFields.addNullPointer(PtrTy);
classFields.addNullPointer(PtrTy);
classFields.addNullPointer(PtrTy);
classFields.addNullPointer(PtrTy);
classFields.addNullPointer(PtrTy);
auto RuntimeProtocols = GetRuntimeProtocolList(classDecl->protocol_begin(),
classDecl->protocol_end());
SmallVector<llvm::Constant *, 16> Protocols;
for (const auto *I : RuntimeProtocols)
Protocols.push_back(
llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
ProtocolPtrTy));
if (Protocols.empty())
classFields.addNullPointer(PtrTy);
else
classFields.add(GenerateProtocolList(Protocols));
classFields.addNullPointer(PtrTy);
classFields.addInt(LongTy, 0);
classFields.add(GeneratePropertyList(OID, classDecl));
llvm::GlobalVariable *classStruct =
classFields.finishAndCreateGlobal(SymbolForClass(className),
CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
auto *classRefSymbol = GetClassVar(className);
classRefSymbol->setSection(sectionName<ClassReferenceSection>());
classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
if (IsCOFF) {
if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
classStruct->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
}
if (SuperClass) {
std::pair<llvm::GlobalVariable*, int> v{classStruct, 1};
EarlyInitList.emplace_back(std::string(SuperClass->getName()),
std::move(v));
}
}
if (ClassPtrAlias) {
ClassPtrAlias->replaceAllUsesWith(
llvm::ConstantExpr::getBitCast(classStruct, IdTy));
ClassPtrAlias->eraseFromParent();
ClassPtrAlias = nullptr;
}
if (auto Placeholder =
TheModule.getNamedGlobal(SymbolForClass(className)))
if (Placeholder != classStruct) {
Placeholder->replaceAllUsesWith(
llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
Placeholder->eraseFromParent();
classStruct->setName(SymbolForClass(className));
}
if (MetaClassPtrAlias) {
MetaClassPtrAlias->replaceAllUsesWith(
llvm::ConstantExpr::getBitCast(metaclass, IdTy));
MetaClassPtrAlias->eraseFromParent();
MetaClassPtrAlias = nullptr;
}
assert(classStruct->getName() == SymbolForClass(className));
auto classInitRef = new llvm::GlobalVariable(TheModule,
classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
classInitRef->setSection(sectionName<ClassSection>());
CGM.addUsedGlobal(classInitRef);
EmittedClass = true;
}
public:
CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
PtrToObjCSuperTy, SelectorTy);
PropertyMetadataTy =
llvm::StructType::get(CGM.getLLVMContext(),
{ PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
}
};
const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
{
"__objc_selectors",
"__objc_classes",
"__objc_class_refs",
"__objc_cats",
"__objc_protocols",
"__objc_protocol_refs",
"__objc_class_aliases",
"__objc_constant_string"
};
const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
{
".objcrt$SEL",
".objcrt$CLS",
".objcrt$CLR",
".objcrt$CAT",
".objcrt$PCL",
".objcrt$PCR",
".objcrt$CAL",
".objcrt$STR"
};
class CGObjCObjFW: public CGObjCGNU {
protected:
LazyRuntimeFunction MsgLookupFn;
LazyRuntimeFunction MsgLookupFnSRet;
LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
llvm::Value *cmd, llvm::MDNode *node,
MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *args[] = {
EnforceType(Builder, Receiver, IdTy),
EnforceType(Builder, cmd, SelectorTy) };
llvm::CallBase *imp;
if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
else
imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
imp->setMetadata(msgSendMDKind, node);
return imp;
}
llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
llvm::Value *cmd, MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *lookupArgs[] = {
EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
};
if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
else
return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
}
llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
bool isWeak) override {
if (isWeak)
return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
EmitClassRef(Name);
std::string SymbolName = "_OBJC_CLASS_" + Name;
llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
if (!ClassSymbol)
ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
llvm::GlobalValue::ExternalLinkage,
nullptr, SymbolName);
return ClassSymbol;
}
public:
CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
SelectorTy);
MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
PtrToObjCSuperTy, SelectorTy);
MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
PtrToObjCSuperTy, SelectorTy);
}
};
}
void CGObjCGNU::EmitClassRef(const std::string &className) {
std::string symbolRef = "__objc_class_ref_" + className;
if (TheModule.getGlobalVariable(symbolRef))
return;
std::string symbolName = "__objc_class_name_" + className;
llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
if (!ClassSymbol) {
ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
llvm::GlobalValue::ExternalLinkage,
nullptr, symbolName);
}
new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
}
CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
unsigned protocolClassVersion, unsigned classABI)
: CGObjCRuntime(cgm), TheModule(CGM.getModule()),
VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
usesSEHExceptions =
cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
CodeGenTypes &Types = CGM.getTypes();
IntTy = cast<llvm::IntegerType>(
Types.ConvertType(CGM.getContext().IntTy));
LongTy = cast<llvm::IntegerType>(
Types.ConvertType(CGM.getContext().LongTy));
SizeTy = cast<llvm::IntegerType>(
Types.ConvertType(CGM.getContext().getSizeType()));
PtrDiffTy = cast<llvm::IntegerType>(
Types.ConvertType(CGM.getContext().getPointerDiffType()));
BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Int8Ty = llvm::Type::getInt8Ty(VMContext);
PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
ProtocolPtrTy = llvm::PointerType::getUnqual(
Types.ConvertType(CGM.getContext().getObjCProtoType()));
Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Zeros[1] = Zeros[0];
NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
QualType selTy = CGM.getContext().getObjCSelType();
if (QualType() == selTy) {
SelectorTy = PtrToInt8Ty;
SelectorElemTy = Int8Ty;
} else {
SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
SelectorElemTy = CGM.getTypes().ConvertTypeForMem(selTy->getPointeeType());
}
PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
PtrTy = PtrToInt8Ty;
Int32Ty = llvm::Type::getInt32Ty(VMContext);
Int64Ty = llvm::Type::getInt64Ty(VMContext);
IntPtrTy =
CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
QualType UnqualIdTy = CGM.getContext().getObjCIdType();
ASTIdTy = CanQualType();
if (UnqualIdTy != QualType()) {
ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
IdElemTy = CGM.getTypes().ConvertTypeForMem(
ASTIdTy.getTypePtr()->getPointeeType());
} else {
IdTy = PtrToInt8Ty;
IdElemTy = Int8Ty;
}
PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
ProtocolTy = llvm::StructType::get(IdTy,
PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty);
PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
PtrToInt8Ty, PtrToInt8Ty });
ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
PtrDiffTy, BoolTy);
SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
PtrDiffTy, IdTy, BoolTy, BoolTy);
GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
PtrDiffTy, BoolTy, BoolTy);
SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
PtrDiffTy, BoolTy, BoolTy);
llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
true));
const LangOptions &Opts = CGM.getLangOpts();
if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
RuntimeVersion = 10;
if (Opts.getGC() != LangOptions::NonGC) {
RetainSel = GetNullarySelector("retain", CGM.getContext());
ReleaseSel = GetNullarySelector("release", CGM.getContext());
AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
PtrToIdTy);
GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
SizeTy);
}
}
llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
const std::string &Name, bool isWeak) {
llvm::Constant *ClassName = MakeConstantString(Name);
if (!isWeak)
EmitClassRef(Name);
llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
}
llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
const ObjCInterfaceDecl *OID) {
auto *Value =
GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
CGM.setGVProperties(ClassSymbol, OID);
return Value;
}
llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
if (CGM.getTriple().isOSBinFormatCOFF()) {
if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
const VarDecl *VD = nullptr;
for (const auto *Result : DC->lookup(&II))
if ((VD = dyn_cast<VarDecl>(Result)))
break;
CGM.setGVProperties(ClassSymbol, VD);
}
}
return Value;
}
llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
const std::string &TypeEncoding) {
SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
llvm::GlobalAlias *SelValue = nullptr;
for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
e = Types.end() ; i!=e ; i++) {
if (i->first == TypeEncoding) {
SelValue = i->second;
break;
}
}
if (!SelValue) {
SelValue = llvm::GlobalAlias::create(SelectorElemTy, 0,
llvm::GlobalValue::PrivateLinkage,
".objc_selector_" + Sel.getAsString(),
&TheModule);
Types.emplace_back(TypeEncoding, SelValue);
}
return SelValue;
}
Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
llvm::Value *SelValue = GetSelector(CGF, Sel);
Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
CGF.getPointerAlign());
CGF.Builder.CreateStore(SelValue, tmp);
return tmp;
}
llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
return GetTypedSelector(CGF, Sel, std::string());
}
llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
const ObjCMethodDecl *Method) {
std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
}
llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
return MakeConstantString("@id");
} else {
return nullptr;
}
}
const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
assert(OPT && "Invalid @catch type.");
const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
assert(IDecl && "Invalid @catch type.");
return MakeConstantString(IDecl->getIdentifier()->getName());
}
llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
if (usesSEHExceptions)
return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
if (!CGM.getLangOpts().CPlusPlus)
return CGObjCGNU::GetEHType(T);
if (T->isObjCIdType() ||
T->isObjCQualifiedIdType()) {
llvm::Constant *IDEHType =
CGM.getModule().getGlobalVariable("__objc_id_type_info");
if (!IDEHType)
IDEHType =
new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
false,
llvm::GlobalValue::ExternalLinkage,
nullptr, "__objc_id_type_info");
return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
}
const ObjCObjectPointerType *PT =
T->getAs<ObjCObjectPointerType>();
assert(PT && "Invalid @catch type.");
const ObjCInterfaceType *IT = PT->getInterfaceType();
assert(IT && "Invalid @catch type.");
std::string className =
std::string(IT->getDecl()->getIdentifier()->getName());
std::string typeinfoName = "__objc_eh_typeinfo_" + className;
llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
if (typeinfo)
return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
auto *Vtable = TheModule.getGlobalVariable(vtableName);
if (!Vtable) {
Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
llvm::GlobalValue::ExternalLinkage,
nullptr, vtableName);
}
llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
auto *BVtable = llvm::ConstantExpr::getBitCast(
llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
PtrToInt8Ty);
llvm::Constant *typeName =
ExportUniqueString(className, "__objc_eh_typename_");
ConstantInitBuilder builder(CGM);
auto fields = builder.beginStruct();
fields.add(BVtable);
fields.add(typeName);
llvm::Constant *TI =
fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
CGM.getPointerAlign(),
false,
llvm::GlobalValue::LinkOnceODRLinkage);
return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
}
ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
std::string Str = SL->getString().str();
CharUnits Align = CGM.getPointerAlign();
llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
if (old != ObjCStrings.end())
return ConstantAddress(old->getValue(), Int8Ty, Align);
StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
if (StringClass.empty()) StringClass = "NSConstantString";
std::string Sym = "_OBJC_CLASS_";
Sym += StringClass;
llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
if (!isa)
isa = new llvm::GlobalVariable(TheModule, IdTy, false,
llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
else if (isa->getType() != PtrToIdTy)
isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
ConstantInitBuilder Builder(CGM);
auto Fields = Builder.beginStruct();
Fields.add(isa);
Fields.add(MakeConstantString(Str));
Fields.addInt(IntTy, Str.size());
llvm::Constant *ObjCStr =
Fields.finishAndCreateGlobal(".objc_str", Align);
ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
ObjCStrings[Str] = ObjCStr;
ConstantStrings.push_back(ObjCStr);
return ConstantAddress(ObjCStr, Int8Ty, Align);
}
RValue
CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
ReturnValueSlot Return,
QualType ResultType,
Selector Sel,
const ObjCInterfaceDecl *Class,
bool isCategoryImpl,
llvm::Value *Receiver,
bool IsClassMessage,
const CallArgList &CallArgs,
const ObjCMethodDecl *Method) {
CGBuilderTy &Builder = CGF.Builder;
if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
if (Sel == RetainSel || Sel == AutoreleaseSel) {
return RValue::get(EnforceType(Builder, Receiver,
CGM.getTypes().ConvertType(ResultType)));
}
if (Sel == ReleaseSel) {
return RValue::get(nullptr);
}
}
llvm::Value *cmd = GetSelector(CGF, Sel);
CallArgList ActualArgs;
ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
ActualArgs.addFrom(CallArgs);
MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
llvm::Value *ReceiverClass = nullptr;
bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
if (isV2ABI) {
ReceiverClass = GetClassNamed(CGF,
Class->getSuperClass()->getNameAsString(), false);
if (IsClassMessage) {
ReceiverClass = Builder.CreateBitCast(ReceiverClass,
llvm::PointerType::getUnqual(IdTy));
ReceiverClass =
Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
}
ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
} else {
if (isCategoryImpl) {
llvm::FunctionCallee classLookupFunction = nullptr;
if (IsClassMessage) {
classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
IdTy, PtrTy, true), "objc_get_meta_class");
} else {
classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
IdTy, PtrTy, true), "objc_get_class");
}
ReceiverClass = Builder.CreateCall(classLookupFunction,
MakeConstantString(Class->getNameAsString()));
} else {
if (IsClassMessage) {
if (!MetaClassPtrAlias) {
MetaClassPtrAlias = llvm::GlobalAlias::create(
IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
}
ReceiverClass = MetaClassPtrAlias;
} else {
if (!ClassPtrAlias) {
ClassPtrAlias = llvm::GlobalAlias::create(
IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
".objc_class_ref" + Class->getNameAsString(), &TheModule);
}
ReceiverClass = ClassPtrAlias;
}
}
llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
ReceiverClass = Builder.CreateBitCast(ReceiverClass,
llvm::PointerType::getUnqual(CastTy));
ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
ReceiverClass =
Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
}
llvm::StructType *ObjCSuperTy =
llvm::StructType::get(Receiver->getType(), IdTy);
Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
CGF.getPointerAlign());
Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
imp = EnforceType(Builder, imp, MSI.MessengerType);
llvm::Metadata *impMD[] = {
llvm::MDString::get(VMContext, Sel.getAsString()),
llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
CGCallee callee(CGCalleeInfo(), imp);
llvm::CallBase *call;
RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
call->setMetadata(msgSendMDKind, node);
return msgRet;
}
RValue
CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
ReturnValueSlot Return,
QualType ResultType,
Selector Sel,
llvm::Value *Receiver,
const CallArgList &CallArgs,
const ObjCInterfaceDecl *Class,
const ObjCMethodDecl *Method) {
CGBuilderTy &Builder = CGF.Builder;
if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
if (Sel == RetainSel || Sel == AutoreleaseSel) {
return RValue::get(EnforceType(Builder, Receiver,
CGM.getTypes().ConvertType(ResultType)));
}
if (Sel == ReleaseSel) {
return RValue::get(nullptr);
}
}
IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
llvm::Value *cmd;
if (Method)
cmd = GetSelector(CGF, Method);
else
cmd = GetSelector(CGF, Sel);
cmd = EnforceType(Builder, cmd, SelectorTy);
Receiver = EnforceType(Builder, Receiver, IdTy);
llvm::Metadata *impMD[] = {
llvm::MDString::get(VMContext, Sel.getAsString()),
llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
CallArgList ActualArgs;
ActualArgs.add(RValue::get(Receiver), ASTIdTy);
ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
ActualArgs.addFrom(CallArgs);
MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
bool hasParamDestroyedInCallee = false;
bool requiresExplicitZeroResult = false;
bool requiresNilReceiverCheck = [&] {
if (!canMessageReceiverBeNull(CGF, Method, false,
Class, Receiver))
return false;
if (Method && Method->hasParamDestroyedInCallee()) {
hasParamDestroyedInCallee = true;
}
if (!Return.isUnused()) {
if (ResultType->isVoidType()) {
} else if (ResultType->hasPointerRepresentation() &&
CGM.getTypes().isZeroInitializable(ResultType)) {
} else if (ResultType->isIntegralOrEnumerationType()) {
} else {
requiresExplicitZeroResult = true;
}
}
return hasParamDestroyedInCallee || requiresExplicitZeroResult;
}();
bool requiresExplicitAggZeroing =
requiresExplicitZeroResult && CGF.hasAggregateEvaluationKind(ResultType);
llvm::BasicBlock *continueBB = nullptr;
llvm::BasicBlock *nilPathBB = nullptr;
llvm::BasicBlock *nilCleanupBB = nullptr;
if (requiresNilReceiverCheck) {
llvm::BasicBlock *messageBB = CGF.createBasicBlock("msgSend");
continueBB = CGF.createBasicBlock("continue");
if (requiresExplicitAggZeroing || hasParamDestroyedInCallee) {
nilCleanupBB = CGF.createBasicBlock("nilReceiverCleanup");
} else {
nilPathBB = Builder.GetInsertBlock();
}
llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
llvm::Constant::getNullValue(Receiver->getType()));
Builder.CreateCondBr(isNil, nilCleanupBB ? nilCleanupBB : continueBB,
messageBB);
CGF.EmitBlock(messageBB);
}
llvm::Value *imp;
switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
case CodeGenOptions::Legacy:
imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
break;
case CodeGenOptions::Mixed:
case CodeGenOptions::NonLegacy:
if (CGM.ReturnTypeUsesFPRet(ResultType)) {
imp =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
"objc_msgSend_fpret")
.getCallee();
} else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
imp =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
"objc_msgSend_stret")
.getCallee();
} else {
imp = CGM.CreateRuntimeFunction(
llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
.getCallee();
}
}
ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
imp = EnforceType(Builder, imp, MSI.MessengerType);
llvm::CallBase *call;
CGCallee callee(CGCalleeInfo(), imp);
RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
call->setMetadata(msgSendMDKind, node);
if (requiresNilReceiverCheck) {
llvm::BasicBlock *nonNilPathBB = CGF.Builder.GetInsertBlock();
CGF.Builder.CreateBr(continueBB);
if (nilCleanupBB) {
CGF.EmitBlock(nilCleanupBB);
if (hasParamDestroyedInCallee) {
destroyCalleeDestroyedArguments(CGF, Method, CallArgs);
}
if (requiresExplicitAggZeroing) {
assert(msgRet.isAggregate());
Address addr = msgRet.getAggregateAddress();
CGF.EmitNullInitialization(addr, ResultType);
}
nilPathBB = CGF.Builder.GetInsertBlock();
CGF.Builder.CreateBr(continueBB);
}
CGF.EmitBlock(continueBB);
if (msgRet.isScalar()) {
if (llvm::Value *v = msgRet.getScalarVal()) {
llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
phi->addIncoming(v, nonNilPathBB);
phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB);
msgRet = RValue::get(phi);
}
} else if (msgRet.isAggregate()) {
} else {
std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
phi->addIncoming(v.first, nonNilPathBB);
phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
nilPathBB);
llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
phi2->addIncoming(v.second, nonNilPathBB);
phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
nilPathBB);
msgRet = RValue::getComplex(phi, phi2);
}
}
return msgRet;
}
llvm::Constant *CGObjCGNU::
GenerateMethodList(StringRef ClassName,
StringRef CategoryName,
ArrayRef<const ObjCMethodDecl*> Methods,
bool isClassMethodList) {
if (Methods.empty())
return NULLPtr;
ConstantInitBuilder Builder(CGM);
auto MethodList = Builder.beginStruct();
MethodList.addNullPointer(CGM.Int8PtrTy);
MethodList.addInt(Int32Ty, Methods.size());
llvm::StructType *ObjCMethodTy =
llvm::StructType::get(CGM.getLLVMContext(), {
PtrToInt8Ty, PtrToInt8Ty, IMPTy });
bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
if (isV2ABI) {
llvm::DataLayout td(&TheModule);
MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
CGM.getContext().getCharWidth());
ObjCMethodTy =
llvm::StructType::get(CGM.getLLVMContext(), {
IMPTy, PtrToInt8Ty, PtrToInt8Ty });
} else {
ObjCMethodTy =
llvm::StructType::get(CGM.getLLVMContext(), {
PtrToInt8Ty, PtrToInt8Ty, IMPTy });
}
auto MethodArray = MethodList.beginArray();
ASTContext &Context = CGM.getContext();
for (const auto *OMD : Methods) {
llvm::Constant *FnPtr =
TheModule.getFunction(getSymbolNameForMethod(OMD));
assert(FnPtr && "Can't generate metadata for method that doesn't exist");
auto Method = MethodArray.beginStruct(ObjCMethodTy);
if (isV2ABI) {
Method.addBitCast(FnPtr, IMPTy);
Method.add(GetConstantSelector(OMD->getSelector(),
Context.getObjCEncodingForMethodDecl(OMD)));
Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
} else {
Method.add(MakeConstantString(OMD->getSelector().getAsString()));
Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
Method.addBitCast(FnPtr, IMPTy);
}
Method.finishAndAddTo(MethodArray);
}
MethodArray.finishAndAddTo(MethodList);
return MethodList.finishAndCreateGlobal(".objc_method_list",
CGM.getPointerAlign());
}
llvm::Constant *CGObjCGNU::
GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
ArrayRef<llvm::Constant *> IvarTypes,
ArrayRef<llvm::Constant *> IvarOffsets,
ArrayRef<llvm::Constant *> IvarAlign,
ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
if (IvarNames.empty())
return NULLPtr;
ConstantInitBuilder Builder(CGM);
auto IvarList = Builder.beginStruct();
IvarList.addInt(IntTy, (int)IvarNames.size());
llvm::StructType *ObjCIvarTy =
llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
auto Ivars = IvarList.beginArray(ObjCIvarTy);
for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
auto Ivar = Ivars.beginStruct(ObjCIvarTy);
Ivar.add(IvarNames[i]);
Ivar.add(IvarTypes[i]);
Ivar.add(IvarOffsets[i]);
Ivar.finishAndAddTo(Ivars);
}
Ivars.finishAndAddTo(IvarList);
return IvarList.finishAndCreateGlobal(".objc_ivar_list",
CGM.getPointerAlign());
}
llvm::Constant *CGObjCGNU::GenerateClassStructure(
llvm::Constant *MetaClass,
llvm::Constant *SuperClass,
unsigned info,
const char *Name,
llvm::Constant *Version,
llvm::Constant *InstanceSize,
llvm::Constant *IVars,
llvm::Constant *Methods,
llvm::Constant *Protocols,
llvm::Constant *IvarOffsets,
llvm::Constant *Properties,
llvm::Constant *StrongIvarBitmap,
llvm::Constant *WeakIvarBitmap,
bool isMeta) {
llvm::StructType *ClassTy = llvm::StructType::get(
PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, LongTy, LongTy, LongTy, IVars->getType(), Methods->getType(), PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, LongTy, IvarOffsets->getType(), Properties->getType(), IntPtrTy, IntPtrTy );
ConstantInitBuilder Builder(CGM);
auto Elements = Builder.beginStruct(ClassTy);
Elements.addBitCast(MetaClass, PtrToInt8Ty);
Elements.add(SuperClass);
Elements.add(MakeConstantString(Name, ".class_name"));
Elements.addInt(LongTy, 0);
Elements.addInt(LongTy, info);
if (isMeta) {
llvm::DataLayout td(&TheModule);
Elements.addInt(LongTy,
td.getTypeSizeInBits(ClassTy) /
CGM.getContext().getCharWidth());
} else
Elements.add(InstanceSize);
Elements.add(IVars);
Elements.add(Methods);
Elements.add(NULLPtr);
Elements.add(NULLPtr);
Elements.add(NULLPtr);
Elements.addBitCast(Protocols, PtrTy);
Elements.add(NULLPtr);
Elements.addInt(LongTy, ClassABIVersion);
Elements.add(IvarOffsets);
Elements.add(Properties);
Elements.add(StrongIvarBitmap);
Elements.add(WeakIvarBitmap);
std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
std::string(Name));
llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
llvm::Constant *Class =
Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
llvm::GlobalValue::ExternalLinkage);
if (ClassRef) {
ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
ClassRef->getType()));
ClassRef->removeFromParent();
Class->setName(ClassSym);
}
return Class;
}
llvm::Constant *CGObjCGNU::
GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
llvm::StructType *ObjCMethodDescTy =
llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
ASTContext &Context = CGM.getContext();
ConstantInitBuilder Builder(CGM);
auto MethodList = Builder.beginStruct();
MethodList.addInt(IntTy, Methods.size());
auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
for (auto *M : Methods) {
auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
Method.add(MakeConstantString(M->getSelector().getAsString()));
Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
Method.finishAndAddTo(MethodArray);
}
MethodArray.finishAndAddTo(MethodList);
return MethodList.finishAndCreateGlobal(".objc_method_list",
CGM.getPointerAlign());
}
llvm::Constant *
CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
ConstantInitBuilder Builder(CGM);
auto ProtocolList = Builder.beginStruct();
ProtocolList.add(NULLPtr);
ProtocolList.addInt(LongTy, Protocols.size());
auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
iter != endIter ; iter++) {
llvm::Constant *protocol = nullptr;
llvm::StringMap<llvm::Constant*>::iterator value =
ExistingProtocols.find(*iter);
if (value == ExistingProtocols.end()) {
protocol = GenerateEmptyProtocol(*iter);
} else {
protocol = value->getValue();
}
Elements.addBitCast(protocol, PtrToInt8Ty);
}
Elements.finishAndAddTo(ProtocolList);
return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
CGM.getPointerAlign());
}
llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
const ObjCProtocolDecl *PD) {
auto protocol = GenerateProtocolRef(PD);
llvm::Type *T =
CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
}
llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
if (!protocol)
GenerateProtocol(PD);
assert(protocol && "Unknown protocol");
return protocol;
}
llvm::Constant *
CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
llvm::Constant *ProtocolList = GenerateProtocolList({});
llvm::Constant *MethodList = GenerateProtocolMethodList({});
MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
ConstantInitBuilder Builder(CGM);
auto Elements = Builder.beginStruct();
Elements.add(llvm::ConstantExpr::getIntToPtr(
llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
Elements.add(ProtocolList);
Elements.add(MethodList);
Elements.add(MethodList);
Elements.add(MethodList);
Elements.add(MethodList);
Elements.add(NULLPtr);
Elements.add(NULLPtr);
return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
CGM.getPointerAlign());
}
void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
if (PD->isNonRuntimeProtocol())
return;
std::string ProtocolName = PD->getNameAsString();
if (const ObjCProtocolDecl *Def = PD->getDefinition())
PD = Def;
SmallVector<std::string, 16> Protocols;
for (const auto *PI : PD->protocols())
Protocols.push_back(PI->getNameAsString());
SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
for (const auto *I : PD->instance_methods())
if (I->isOptional())
OptionalInstanceMethods.push_back(I);
else
InstanceMethods.push_back(I);
SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
for (const auto *I : PD->class_methods())
if (I->isOptional())
OptionalClassMethods.push_back(I);
else
ClassMethods.push_back(I);
llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
llvm::Constant *InstanceMethodList =
GenerateProtocolMethodList(InstanceMethods);
llvm::Constant *ClassMethodList =
GenerateProtocolMethodList(ClassMethods);
llvm::Constant *OptionalInstanceMethodList =
GenerateProtocolMethodList(OptionalInstanceMethods);
llvm::Constant *OptionalClassMethodList =
GenerateProtocolMethodList(OptionalClassMethods);
llvm::Constant *PropertyList =
GeneratePropertyList(nullptr, PD, false, false);
llvm::Constant *OptionalPropertyList =
GeneratePropertyList(nullptr, PD, false, true);
ConstantInitBuilder Builder(CGM);
auto Elements = Builder.beginStruct();
Elements.add(
llvm::ConstantExpr::getIntToPtr(
llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Elements.add(MakeConstantString(ProtocolName));
Elements.add(ProtocolList);
Elements.add(InstanceMethodList);
Elements.add(ClassMethodList);
Elements.add(OptionalInstanceMethodList);
Elements.add(OptionalClassMethodList);
Elements.add(PropertyList);
Elements.add(OptionalPropertyList);
ExistingProtocols[ProtocolName] =
llvm::ConstantExpr::getBitCast(
Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
IdTy);
}
void CGObjCGNU::GenerateProtocolHolderCategory() {
ConstantInitBuilder Builder(CGM);
auto Elements = Builder.beginStruct();
const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
const std::string CategoryName = "AnotherHack";
Elements.add(MakeConstantString(CategoryName));
Elements.add(MakeConstantString(ClassName));
Elements.addBitCast(GenerateMethodList(
ClassName, CategoryName, {}, false), PtrTy);
Elements.addBitCast(GenerateMethodList(
ClassName, CategoryName, {}, true), PtrTy);
ConstantInitBuilder ProtocolListBuilder(CGM);
auto ProtocolList = ProtocolListBuilder.beginStruct();
ProtocolList.add(NULLPtr);
ProtocolList.addInt(LongTy, ExistingProtocols.size());
auto ProtocolElements = ProtocolList.beginArray(PtrTy);
for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
iter != endIter ; iter++) {
ProtocolElements.addBitCast(iter->getValue(), PtrTy);
}
ProtocolElements.finishAndAddTo(ProtocolList);
Elements.addBitCast(
ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
CGM.getPointerAlign()),
PtrTy);
Categories.push_back(llvm::ConstantExpr::getBitCast(
Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
PtrTy));
}
llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
int bitCount = bits.size();
int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
if (bitCount < ptrBits) {
uint64_t val = 1;
for (int i=0 ; i<bitCount ; ++i) {
if (bits[i]) val |= 1ULL<<(i+1);
}
return llvm::ConstantInt::get(IntPtrTy, val);
}
SmallVector<llvm::Constant *, 8> values;
int v=0;
while (v < bitCount) {
int32_t word = 0;
for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
if (bits[v]) word |= 1<<i;
v++;
}
values.push_back(llvm::ConstantInt::get(Int32Ty, word));
}
ConstantInitBuilder builder(CGM);
auto fields = builder.beginStruct();
fields.addInt(Int32Ty, values.size());
auto array = fields.beginArray();
for (auto v : values) array.add(v);
array.finishAndAddTo(fields);
llvm::Constant *GS =
fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
return ptr;
}
llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
ObjCCategoryDecl *OCD) {
const auto &RefPro = OCD->getReferencedProtocols();
const auto RuntimeProtos =
GetRuntimeProtocolList(RefPro.begin(), RefPro.end());
SmallVector<std::string, 16> Protocols;
for (const auto *PD : RuntimeProtos)
Protocols.push_back(PD->getNameAsString());
return GenerateProtocolList(Protocols);
}
void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
const ObjCInterfaceDecl *Class = OCD->getClassInterface();
std::string ClassName = Class->getNameAsString();
std::string CategoryName = OCD->getNameAsString();
const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
ConstantInitBuilder Builder(CGM);
auto Elements = Builder.beginStruct();
Elements.add(MakeConstantString(CategoryName));
Elements.add(MakeConstantString(ClassName));
SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
OCD->instmeth_end());
Elements.addBitCast(
GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
PtrTy);
SmallVector<ObjCMethodDecl*, 16> ClassMethods;
ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
OCD->classmeth_end());
Elements.addBitCast(
GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
PtrTy);
Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
if (isRuntime(ObjCRuntime::GNUstep, 2)) {
const ObjCCategoryDecl *Category =
Class->FindCategoryDeclaration(OCD->getIdentifier());
if (Category) {
Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
} else {
Elements.addNullPointer(PtrTy);
Elements.addNullPointer(PtrTy);
}
}
Categories.push_back(llvm::ConstantExpr::getBitCast(
Elements.finishAndCreateGlobal(
std::string(".objc_category_")+ClassName+CategoryName,
CGM.getPointerAlign()),
PtrTy));
}
llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
const ObjCContainerDecl *OCD,
bool isClassProperty,
bool protocolOptionalProperties) {
SmallVector<const ObjCPropertyDecl *, 16> Properties;
llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
bool isProtocol = isa<ObjCProtocolDecl>(OCD);
ASTContext &Context = CGM.getContext();
std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
= [&](const ObjCProtocolDecl *Proto) {
for (const auto *P : Proto->protocols())
collectProtocolProperties(P);
for (const auto *PD : Proto->properties()) {
if (isClassProperty != PD->isClassProperty())
continue;
if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
continue;
if (!PropertySet.insert(PD->getIdentifier()).second)
continue;
Properties.push_back(PD);
}
};
if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
for (auto *PD : ClassExt->properties()) {
if (isClassProperty != PD->isClassProperty())
continue;
PropertySet.insert(PD->getIdentifier());
Properties.push_back(PD);
}
for (const auto *PD : OCD->properties()) {
if (isClassProperty != PD->isClassProperty())
continue;
if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
continue;
if (!PropertySet.insert(PD->getIdentifier()).second)
continue;
Properties.push_back(PD);
}
if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
for (const auto *P : OID->all_referenced_protocols())
collectProtocolProperties(P);
else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
for (const auto *P : CD->protocols())
collectProtocolProperties(P);
auto numProperties = Properties.size();
if (numProperties == 0)
return NULLPtr;
ConstantInitBuilder builder(CGM);
auto propertyList = builder.beginStruct();
auto properties = PushPropertyListHeader(propertyList, numProperties);
for (auto *property : Properties) {
bool isSynthesized = false;
bool isDynamic = false;
if (!isProtocol) {
auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
if (propertyImpl) {
isSynthesized = (propertyImpl->getPropertyImplementation() ==
ObjCPropertyImplDecl::Synthesize);
isDynamic = (propertyImpl->getPropertyImplementation() ==
ObjCPropertyImplDecl::Dynamic);
}
}
PushProperty(properties, property, Container, isSynthesized, isDynamic);
}
properties.finishAndAddTo(propertyList);
return propertyList.finishAndCreateGlobal(".objc_property_list",
CGM.getPointerAlign());
}
void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
ObjCInterfaceDecl *ClassDecl =
const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
ClassAliases.emplace_back(ClassDecl->getNameAsString(),
OAD->getNameAsString());
}
void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
ASTContext &Context = CGM.getContext();
const ObjCInterfaceDecl * SuperClassDecl =
OID->getClassInterface()->getSuperClass();
std::string SuperClassName;
if (SuperClassDecl) {
SuperClassName = SuperClassDecl->getNameAsString();
EmitClassRef(SuperClassName);
}
ObjCInterfaceDecl *ClassDecl =
const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
std::string ClassName = ClassDecl->getNameAsString();
std::string classSymbolName = "__objc_class_name_" + ClassName;
if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
} else {
new llvm::GlobalVariable(TheModule, LongTy, false,
llvm::GlobalValue::ExternalLinkage,
llvm::ConstantInt::get(LongTy, 0),
classSymbolName);
}
int instanceSize =
Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
SmallVector<llvm::Constant*, 16> IvarNames;
SmallVector<llvm::Constant*, 16> IvarTypes;
SmallVector<llvm::Constant*, 16> IvarOffsets;
SmallVector<llvm::Constant*, 16> IvarAligns;
SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
ConstantInitBuilder IvarOffsetBuilder(CGM);
auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
SmallVector<bool, 16> WeakIvars;
SmallVector<bool, 16> StrongIvars;
int superInstanceSize = !SuperClassDecl ? 0 :
Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
instanceSize = 0 - (instanceSize - superInstanceSize);
}
for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
IVD = IVD->getNextIvar()) {
IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
std::string TypeStr;
Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
IvarTypes.push_back(MakeConstantString(TypeStr));
IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
Context.getTypeSize(IVD->getType())));
uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
uint64_t Offset = BaseOffset;
if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Offset = BaseOffset - superInstanceSize;
}
llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
IVD->getNameAsString();
llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
if (OffsetVar) {
OffsetVar->setInitializer(OffsetValue);
OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
} else
OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
false, llvm::GlobalValue::ExternalLinkage,
OffsetValue, OffsetName);
IvarOffsets.push_back(OffsetValue);
IvarOffsetValues.add(OffsetVar);
Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
IvarOwnership.push_back(lt);
switch (lt) {
case Qualifiers::OCL_Strong:
StrongIvars.push_back(true);
WeakIvars.push_back(false);
break;
case Qualifiers::OCL_Weak:
StrongIvars.push_back(false);
WeakIvars.push_back(true);
break;
default:
StrongIvars.push_back(false);
WeakIvars.push_back(false);
}
}
llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
llvm::GlobalVariable *IvarOffsetArray =
IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
CGM.getPointerAlign());
SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
OID->instmeth_end());
SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
OID->classmeth_end());
llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
auto RefProtocols = ClassDecl->protocols();
auto RuntimeProtocols =
GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());
SmallVector<std::string, 16> Protocols;
for (const auto *I : RuntimeProtocols)
Protocols.push_back(I->getNameAsString());
llvm::Constant *SuperClass;
if (!SuperClassName.empty()) {
SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
} else {
SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
}
SmallVector<llvm::Constant*, 1> empty;
llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
InstanceMethods, false);
llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
ClassMethods, true);
llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
IvarOffsets, IvarAligns, IvarOwnership);
llvm::Type *IndexTy = Int32Ty;
llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
unsigned ivarIndex = 0;
for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
IVD = IVD->getNextIvar()) {
const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
offsetPointerIndexes);
llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
if (offset) {
offset->setInitializer(offsetValue);
offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
} else
new llvm::GlobalVariable(TheModule, offsetValue->getType(),
false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
++ivarIndex;
}
llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
llvm::Constant *MetaClassStruct = GenerateClassStructure(
NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
OID->getClassInterface());
llvm::Constant *ClassStruct = GenerateClassStructure(
MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
StrongIvarBitmap, WeakIvarBitmap);
CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
OID->getClassInterface());
if (ClassPtrAlias) {
ClassPtrAlias->replaceAllUsesWith(
llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
ClassPtrAlias->eraseFromParent();
ClassPtrAlias = nullptr;
}
if (MetaClassPtrAlias) {
MetaClassPtrAlias->replaceAllUsesWith(
llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
MetaClassPtrAlias->eraseFromParent();
MetaClassPtrAlias = nullptr;
}
ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Classes.push_back(ClassStruct);
}
llvm::Function *CGObjCGNU::ModuleInitFunction() {
if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
ExistingProtocols.empty() && SelectorTable.empty())
return nullptr;
GenerateProtocolHolderCategory();
llvm::StructType *selStructTy = dyn_cast<llvm::StructType>(SelectorElemTy);
llvm::Type *selStructPtrTy = SelectorTy;
if (!selStructTy) {
selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
{ PtrToInt8Ty, PtrToInt8Ty });
selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
}
llvm::Constant *statics = NULLPtr;
if (!ConstantStrings.empty()) {
llvm::GlobalVariable *fileStatics = [&] {
ConstantInitBuilder builder(CGM);
auto staticsStruct = builder.beginStruct();
StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
if (stringClass.empty()) stringClass = "NXConstantString";
staticsStruct.add(MakeConstantString(stringClass,
".objc_static_class_name"));
auto array = staticsStruct.beginArray();
array.addAll(ConstantStrings);
array.add(NULLPtr);
array.finishAndAddTo(staticsStruct);
return staticsStruct.finishAndCreateGlobal(".objc_statics",
CGM.getPointerAlign());
}();
ConstantInitBuilder builder(CGM);
auto allStaticsArray = builder.beginArray(fileStatics->getType());
allStaticsArray.add(fileStatics);
allStaticsArray.addNullPointer(fileStatics->getType());
statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
CGM.getPointerAlign());
statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
}
SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
unsigned selectorCount;
llvm::GlobalVariable *selectorList = [&] {
ConstantInitBuilder builder(CGM);
auto selectors = builder.beginArray(selStructTy);
auto &table = SelectorTable; std::vector<Selector> allSelectors;
for (auto &entry : table)
allSelectors.push_back(entry.first);
llvm::sort(allSelectors);
for (auto &untypedSel : allSelectors) {
std::string selNameStr = untypedSel.getAsString();
llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
for (TypedSelector &sel : table[untypedSel]) {
llvm::Constant *selectorTypeEncoding = NULLPtr;
if (!sel.first.empty())
selectorTypeEncoding =
MakeConstantString(sel.first, ".objc_sel_types");
auto selStruct = selectors.beginStruct(selStructTy);
selStruct.add(selName);
selStruct.add(selectorTypeEncoding);
selStruct.finishAndAddTo(selectors);
selectorAliases.push_back(sel.second);
}
}
selectorCount = selectors.size();
auto selStruct = selectors.beginStruct(selStructTy);
selStruct.add(NULLPtr);
selStruct.add(NULLPtr);
selStruct.finishAndAddTo(selectors);
return selectors.finishAndCreateGlobal(".objc_selector_list",
CGM.getPointerAlign());
}();
for (unsigned i = 0; i < selectorCount; ++i) {
llvm::Constant *idxs[] = {
Zeros[0],
llvm::ConstantInt::get(Int32Ty, i)
};
llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
selectorList->getValueType(), selectorList, idxs);
selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
selectorAliases[i]->replaceAllUsesWith(selPtr);
selectorAliases[i]->eraseFromParent();
}
llvm::GlobalVariable *symtab = [&] {
ConstantInitBuilder builder(CGM);
auto symtab = builder.beginStruct();
symtab.addInt(LongTy, selectorCount);
symtab.addBitCast(selectorList, selStructPtrTy);
symtab.addInt(CGM.Int16Ty, Classes.size());
symtab.addInt(CGM.Int16Ty, Categories.size());
auto classList = symtab.beginArray(PtrToInt8Ty);
classList.addAll(Classes);
classList.addAll(Categories);
classList.add(statics);
classList.add(NULLPtr);
classList.finishAndAddTo(symtab);
return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
}();
llvm::Constant *module = [&] {
llvm::Type *moduleEltTys[] = {
LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
};
llvm::StructType *moduleTy =
llvm::StructType::get(CGM.getLLVMContext(),
makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
ConstantInitBuilder builder(CGM);
auto module = builder.beginStruct(moduleTy);
module.addInt(LongTy, RuntimeVersion);
module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
SourceManager &SM = CGM.getContext().getSourceManager();
Optional<FileEntryRef> mainFile =
SM.getFileEntryRefForID(SM.getMainFileID());
std::string path =
(mainFile->getDir().getName() + "/" + mainFile->getName()).str();
module.add(MakeConstantString(path, ".objc_source_file_name"));
module.add(symtab);
if (RuntimeVersion >= 10) {
switch (CGM.getLangOpts().getGC()) {
case LangOptions::GCOnly:
module.addInt(IntTy, 2);
break;
case LangOptions::NonGC:
if (CGM.getLangOpts().ObjCAutoRefCount)
module.addInt(IntTy, 1);
else
module.addInt(IntTy, 0);
break;
case LangOptions::HybridGC:
module.addInt(IntTy, 1);
break;
}
}
return module.finishAndCreateGlobal("", CGM.getPointerAlign());
}();
llvm::Function * LoadFunction = llvm::Function::Create(
llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
llvm::GlobalValue::InternalLinkage, ".objc_load_function",
&TheModule);
llvm::BasicBlock *EntryBB =
llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
CGBuilderTy Builder(CGM, VMContext);
Builder.SetInsertPoint(EntryBB);
llvm::FunctionType *FT =
llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
llvm::FunctionCallee Register =
CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Builder.CreateCall(Register, module);
if (!ClassAliases.empty()) {
llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
llvm::FunctionType *RegisterAliasTy =
llvm::FunctionType::get(Builder.getVoidTy(),
ArgTypes, false);
llvm::Function *RegisterAlias = llvm::Function::Create(
RegisterAliasTy,
llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
&TheModule);
llvm::BasicBlock *AliasBB =
llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
llvm::BasicBlock *NoAliasBB =
llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
llvm::Constant::getNullValue(RegisterAlias->getType()));
Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
Builder.SetInsertPoint(AliasBB);
for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
iter != ClassAliases.end(); ++iter) {
llvm::Constant *TheClass =
TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
if (TheClass) {
TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
Builder.CreateCall(RegisterAlias,
{TheClass, MakeConstantString(iter->second)});
}
}
Builder.CreateBr(NoAliasBB);
Builder.SetInsertPoint(NoAliasBB);
}
Builder.CreateRetVoid();
return LoadFunction;
}
llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
const ObjCContainerDecl *CD) {
CodeGenTypes &Types = CGM.getTypes();
llvm::FunctionType *MethodTy =
Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
std::string FunctionName = getSymbolNameForMethod(OMD);
llvm::Function *Method
= llvm::Function::Create(MethodTy,
llvm::GlobalValue::InternalLinkage,
FunctionName,
&TheModule);
return Method;
}
void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
llvm::Function *Fn,
const ObjCMethodDecl *OMD,
const ObjCContainerDecl *CD) {
}
llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
return GetPropertyFn;
}
llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
return SetPropertyFn;
}
llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
bool copy) {
return nullptr;
}
llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
return GetStructPropertyFn;
}
llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
return SetStructPropertyFn;
}
llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
return nullptr;
}
llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
return nullptr;
}
llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
return EnumerationMutationFn;
}
void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
const ObjCAtSynchronizedStmt &S) {
EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
}
void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
const ObjCAtTryStmt &S) {
EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
}
void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
const ObjCAtThrowStmt &S,
bool ClearInsertionPoint) {
llvm::Value *ExceptionAsObject;
bool isRethrow = false;
if (const Expr *ThrowExpr = S.getThrowExpr()) {
llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
ExceptionAsObject = Exception;
} else {
assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
"Unexpected rethrow outside @catch block.");
ExceptionAsObject = CGF.ObjCEHValueStack.back();
isRethrow = true;
}
if (isRethrow && usesSEHExceptions) {
llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
Throw->setDoesNotReturn();
}
else {
ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
llvm::CallBase *Throw =
CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
Throw->setDoesNotReturn();
}
CGF.Builder.CreateUnreachable();
if (ClearInsertionPoint)
CGF.Builder.ClearInsertionPoint();
}
llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Address AddrWeakObj) {
CGBuilderTy &B = CGF.Builder;
return B.CreateCall(WeakReadFn,
EnforceType(B, AddrWeakObj.getPointer(), PtrToIdTy));
}
void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
llvm::Value *src, Address dst) {
CGBuilderTy &B = CGF.Builder;
src = EnforceType(B, src, IdTy);
llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
B.CreateCall(WeakAssignFn, {src, dstVal});
}
void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
llvm::Value *src, Address dst,
bool threadlocal) {
CGBuilderTy &B = CGF.Builder;
src = EnforceType(B, src, IdTy);
llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
B.CreateCall(GlobalAssignFn, {src, dstVal});
}
void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
llvm::Value *src, Address dst,
llvm::Value *ivarOffset) {
CGBuilderTy &B = CGF.Builder;
src = EnforceType(B, src, IdTy);
llvm::Value *dstVal = EnforceType(B, dst.getPointer(), IdTy);
B.CreateCall(IvarAssignFn, {src, dstVal, ivarOffset});
}
void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
llvm::Value *src, Address dst) {
CGBuilderTy &B = CGF.Builder;
src = EnforceType(B, src, IdTy);
llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
B.CreateCall(StrongCastAssignFn, {src, dstVal});
}
void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Address DestPtr,
Address SrcPtr,
llvm::Value *Size) {
CGBuilderTy &B = CGF.Builder;
llvm::Value *DestPtrVal = EnforceType(B, DestPtr.getPointer(), PtrTy);
llvm::Value *SrcPtrVal = EnforceType(B, SrcPtr.getPointer(), PtrTy);
B.CreateCall(MemMoveFn, {DestPtrVal, SrcPtrVal, Size});
}
llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
const ObjCInterfaceDecl *ID,
const ObjCIvarDecl *Ivar) {
const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
if (!IvarOffsetPointer)
IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
llvm::Type::getInt32PtrTy(VMContext), false,
llvm::GlobalValue::ExternalLinkage, nullptr, Name);
return IvarOffsetPointer;
}
LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
QualType ObjectTy,
llvm::Value *BaseValue,
const ObjCIvarDecl *Ivar,
unsigned CVRQualifiers) {
const ObjCInterfaceDecl *ID =
ObjectTy->castAs<ObjCObjectType>()->getInterface();
return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
EmitIvarOffset(CGF, ID, Ivar));
}
static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
const ObjCInterfaceDecl *OID,
const ObjCIvarDecl *OIVD) {
for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
next = next->getNextIvar()) {
if (OIVD == next)
return OID;
}
if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
return FindIvarInterface(Context, Super, OIVD);
return nullptr;
}
llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
const ObjCInterfaceDecl *Interface,
const ObjCIvarDecl *Ivar) {
if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
if (RuntimeVersion < 10 ||
CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
return CGF.Builder.CreateZExtOrBitCast(
CGF.Builder.CreateAlignedLoad(
Int32Ty, CGF.Builder.CreateAlignedLoad(
llvm::Type::getInt32PtrTy(VMContext),
ObjCIvarOffsetVariable(Interface, Ivar),
CGF.getPointerAlign(), "ivar"),
CharUnits::fromQuantity(4)),
PtrDiffTy);
std::string name = "__objc_ivar_offset_value_" +
Interface->getNameAsString() +"." + Ivar->getNameAsString();
CharUnits Align = CGM.getIntAlign();
llvm::Value *Offset = TheModule.getGlobalVariable(name);
if (!Offset) {
auto GV = new llvm::GlobalVariable(TheModule, IntTy,
false, llvm::GlobalValue::LinkOnceAnyLinkage,
llvm::Constant::getNullValue(IntTy), name);
GV->setAlignment(Align.getAsAlign());
Offset = GV;
}
Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);
if (Offset->getType() != PtrDiffTy)
Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
return Offset;
}
uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
return llvm::ConstantInt::get(PtrDiffTy, Offset, true);
}
CGObjCRuntime *
clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
auto Runtime = CGM.getLangOpts().ObjCRuntime;
switch (Runtime.getKind()) {
case ObjCRuntime::GNUstep:
if (Runtime.getVersion() >= VersionTuple(2, 0))
return new CGObjCGNUstep2(CGM);
return new CGObjCGNUstep(CGM);
case ObjCRuntime::GCC:
return new CGObjCGCC(CGM);
case ObjCRuntime::ObjFW:
return new CGObjCObjFW(CGM);
case ObjCRuntime::FragileMacOSX:
case ObjCRuntime::MacOSX:
case ObjCRuntime::iOS:
case ObjCRuntime::WatchOS:
llvm_unreachable("these runtimes are not GNU runtimes");
}
llvm_unreachable("bad runtime");
}