#include "CGObjCRuntime.h"
#include "CGCXXABI.h"
#include "CGCleanup.h"
#include "CGRecordLayout.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtObjC.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace clang;
using namespace CodeGen;
uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
const ObjCInterfaceDecl *OID,
const ObjCIvarDecl *Ivar) {
return CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar) /
CGM.getContext().getCharWidth();
}
uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
const ObjCImplementationDecl *OID,
const ObjCIvarDecl *Ivar) {
return CGM.getContext().lookupFieldBitOffset(OID->getClassInterface(), OID,
Ivar) /
CGM.getContext().getCharWidth();
}
unsigned CGObjCRuntime::ComputeBitfieldBitOffset(
CodeGen::CodeGenModule &CGM,
const ObjCInterfaceDecl *ID,
const ObjCIvarDecl *Ivar) {
return CGM.getContext().lookupFieldBitOffset(ID, ID->getImplementation(),
Ivar);
}
LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
const ObjCInterfaceDecl *OID,
llvm::Value *BaseValue,
const ObjCIvarDecl *Ivar,
unsigned CVRQualifiers,
llvm::Value *Offset) {
QualType InterfaceTy{OID->getTypeForDecl(), 0};
QualType ObjectPtrTy =
CGF.CGM.getContext().getObjCObjectPointerType(InterfaceTy);
QualType IvarTy =
Ivar->getUsageType(ObjectPtrTy).withCVRQualifiers(CVRQualifiers);
llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy);
V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, V, Offset, "add.ptr");
if (!Ivar->isBitField()) {
V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
return LV;
}
uint64_t FieldBitOffset =
CGF.CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar);
uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign();
uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
CharUnits StorageSize = CGF.CGM.getContext().toCharUnitsFromBits(
llvm::alignTo(BitOffset + BitFieldSize, AlignmentBits));
CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits);
CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
CGF.CGM.getContext().toBits(StorageSize),
CharUnits::fromQuantity(0)));
Address Addr = Address(V, CGF.Int8Ty, Alignment);
Addr = CGF.Builder.CreateElementBitCast(Addr,
llvm::Type::getIntNTy(CGF.getLLVMContext(),
Info->StorageSize));
return LValue::MakeBitfield(Addr, *Info, IvarTy,
LValueBaseInfo(AlignmentSource::Decl),
TBAAAccessInfo());
}
namespace {
struct CatchHandler {
const VarDecl *Variable;
const Stmt *Body;
llvm::BasicBlock *Block;
llvm::Constant *TypeInfo;
unsigned Flags;
};
struct CallObjCEndCatch final : EHScopeStack::Cleanup {
CallObjCEndCatch(bool MightThrow, llvm::FunctionCallee Fn)
: MightThrow(MightThrow), Fn(Fn) {}
bool MightThrow;
llvm::FunctionCallee Fn;
void Emit(CodeGenFunction &CGF, Flags flags) override {
if (MightThrow)
CGF.EmitRuntimeCallOrInvoke(Fn);
else
CGF.EmitNounwindRuntimeCall(Fn);
}
};
}
void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
const ObjCAtTryStmt &S,
llvm::FunctionCallee beginCatchFn,
llvm::FunctionCallee endCatchFn,
llvm::FunctionCallee exceptionRethrowFn) {
CodeGenFunction::JumpDest Cont;
if (S.getNumCatchStmts())
Cont = CGF.getJumpDestInCurrentScope("eh.cont");
bool useFunclets = EHPersonality::get(CGF).usesFuncletPads();
CodeGenFunction::FinallyInfo FinallyInfo;
if (!useFunclets)
if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
FinallyInfo.enter(CGF, Finally->getFinallyBody(),
beginCatchFn, endCatchFn, exceptionRethrowFn);
SmallVector<CatchHandler, 8> Handlers;
if (S.getNumCatchStmts()) {
for (const ObjCAtCatchStmt *CatchStmt : S.catch_stmts()) {
const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Handlers.push_back(CatchHandler());
CatchHandler &Handler = Handlers.back();
Handler.Variable = CatchDecl;
Handler.Body = CatchStmt->getCatchBody();
Handler.Block = CGF.createBasicBlock("catch");
Handler.Flags = 0;
if (!CatchDecl) {
auto catchAll = getCatchAllTypeInfo();
Handler.TypeInfo = catchAll.RTTI;
Handler.Flags = catchAll.Flags;
break;
}
Handler.TypeInfo = GetEHType(CatchDecl->getType());
}
EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
Catch->setHandler(I, { Handlers[I].TypeInfo, Handlers[I].Flags }, Handlers[I].Block);
}
if (useFunclets)
if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
CodeGenFunction HelperCGF(CGM, true);
if (!CGF.CurSEHParent)
CGF.CurSEHParent = cast<NamedDecl>(CGF.CurFuncDecl);
const Stmt *FinallyBlock = Finally->getFinallyBody();
HelperCGF.startOutlinedSEHHelper(CGF, false, FinallyBlock);
HelperCGF.EmitStmt(FinallyBlock);
HelperCGF.FinishFunction(FinallyBlock->getEndLoc());
llvm::Function *FinallyFunc = HelperCGF.CurFn;
CGF.pushSEHCleanup(NormalAndEHCleanup, FinallyFunc);
}
CGF.EmitStmt(S.getTryBody());
if (S.getNumCatchStmts())
CGF.popCatchScope();
CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
CatchHandler &Handler = Handlers[I];
CGF.EmitBlock(Handler.Block);
llvm::CatchPadInst *CPI = nullptr;
SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(CGF.CurrentFuncletPad);
if (useFunclets)
if ((CPI = dyn_cast_or_null<llvm::CatchPadInst>(Handler.Block->getFirstNonPHI()))) {
CGF.CurrentFuncletPad = CPI;
CPI->setOperand(2, CGF.getExceptionSlot().getPointer());
}
llvm::Value *RawExn = CGF.getExceptionFromSlot();
llvm::Value *Exn = RawExn;
if (beginCatchFn)
Exn = CGF.EmitNounwindRuntimeCall(beginCatchFn, RawExn, "exn.adjusted");
CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());
if (endCatchFn) {
bool EndCatchMightThrow = (Handler.Variable == nullptr);
CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
EndCatchMightThrow,
endCatchFn);
}
if (const VarDecl *CatchParam = Handler.Variable) {
llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
CGF.EmitAutoVarDecl(*CatchParam);
EmitInitOfCatchParam(CGF, CastExn, CatchParam);
}
if (CPI)
CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
CGF.ObjCEHValueStack.push_back(Exn);
CGF.EmitStmt(Handler.Body);
CGF.ObjCEHValueStack.pop_back();
cleanups.ForceCleanup();
CGF.EmitBranchThroughCleanup(Cont);
}
CGF.Builder.restoreIP(SavedIP);
if (!useFunclets && S.getFinallyStmt())
FinallyInfo.exit(CGF);
if (Cont.isValid())
CGF.EmitBlock(Cont.getBlock());
}
void CGObjCRuntime::EmitInitOfCatchParam(CodeGenFunction &CGF,
llvm::Value *exn,
const VarDecl *paramDecl) {
Address paramAddr = CGF.GetAddrOfLocalVar(paramDecl);
switch (paramDecl->getType().getQualifiers().getObjCLifetime()) {
case Qualifiers::OCL_Strong:
exn = CGF.EmitARCRetainNonBlock(exn);
LLVM_FALLTHROUGH;
case Qualifiers::OCL_None:
case Qualifiers::OCL_ExplicitNone:
case Qualifiers::OCL_Autoreleasing:
CGF.Builder.CreateStore(exn, paramAddr);
return;
case Qualifiers::OCL_Weak:
CGF.EmitARCInitWeak(paramAddr, exn);
return;
}
llvm_unreachable("invalid ownership qualifier");
}
namespace {
struct CallSyncExit final : EHScopeStack::Cleanup {
llvm::FunctionCallee SyncExitFn;
llvm::Value *SyncArg;
CallSyncExit(llvm::FunctionCallee SyncExitFn, llvm::Value *SyncArg)
: SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
CGF.EmitNounwindRuntimeCall(SyncExitFn, SyncArg);
}
};
}
void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
const ObjCAtSynchronizedStmt &S,
llvm::FunctionCallee syncEnterFn,
llvm::FunctionCallee syncExitFn) {
CodeGenFunction::RunCleanupsScope cleanups(CGF);
const Expr *lockExpr = S.getSynchExpr();
llvm::Value *lock;
if (CGF.getLangOpts().ObjCAutoRefCount) {
lock = CGF.EmitARCRetainScalarExpr(lockExpr);
lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
} else {
lock = CGF.EmitScalarExpr(lockExpr);
}
lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
CGF.EmitStmt(S.getSynchBody());
}
CGObjCRuntime::MessageSendInfo
CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
QualType resultType,
CallArgList &callArgs) {
if (method) {
const CGFunctionInfo &signature =
CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
llvm::PointerType *signatureType =
CGM.getTypes().GetFunctionType(signature)->getPointerTo();
const CGFunctionInfo &signatureForCall =
CGM.getTypes().arrangeCall(signature, callArgs);
return MessageSendInfo(signatureForCall, signatureType);
}
const CGFunctionInfo &argsInfo =
CGM.getTypes().arrangeUnprototypedObjCMessageSend(resultType, callArgs);
llvm::PointerType *signatureType =
CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();
return MessageSendInfo(argsInfo, signatureType);
}
bool CGObjCRuntime::canMessageReceiverBeNull(CodeGenFunction &CGF,
const ObjCMethodDecl *method,
bool isSuper,
const ObjCInterfaceDecl *classReceiver,
llvm::Value *receiver) {
if (isSuper)
return false;
if (classReceiver && method && method->isClassMethod())
return isWeakLinkedClass(classReceiver);
if (auto curMethod =
dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) {
auto self = curMethod->getSelfDecl();
if (self->getType().isConstQualified()) {
if (auto LI = dyn_cast<llvm::LoadInst>(receiver->stripPointerCasts())) {
llvm::Value *selfAddr = CGF.GetAddrOfLocalVar(self).getPointer();
if (selfAddr == LI->getPointerOperand()) {
return false;
}
}
}
}
return true;
}
bool CGObjCRuntime::isWeakLinkedClass(const ObjCInterfaceDecl *ID) {
do {
if (ID->isWeakImported())
return true;
} while ((ID = ID->getSuperClass()));
return false;
}
void CGObjCRuntime::destroyCalleeDestroyedArguments(CodeGenFunction &CGF,
const ObjCMethodDecl *method,
const CallArgList &callArgs) {
CallArgList::const_iterator I = callArgs.begin();
for (auto i = method->param_begin(), e = method->param_end();
i != e; ++i, ++I) {
const ParmVarDecl *param = (*i);
if (param->hasAttr<NSConsumedAttr>()) {
RValue RV = I->getRValue(CGF);
assert(RV.isScalar() &&
"NullReturnState::complete - arg not on object");
CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
} else {
QualType QT = param->getType();
auto *RT = QT->getAs<RecordType>();
if (RT && RT->getDecl()->isParamDestroyedInCallee()) {
RValue RV = I->getRValue(CGF);
QualType::DestructionKind DtorKind = QT.isDestructedType();
switch (DtorKind) {
case QualType::DK_cxx_destructor:
CGF.destroyCXXObject(CGF, RV.getAggregateAddress(), QT);
break;
case QualType::DK_nontrivial_c_struct:
CGF.destroyNonTrivialCStruct(CGF, RV.getAggregateAddress(), QT);
break;
default:
llvm_unreachable("unexpected dtor kind");
break;
}
}
}
}
}
llvm::Constant *
clang::CodeGen::emitObjCProtocolObject(CodeGenModule &CGM,
const ObjCProtocolDecl *protocol) {
return CGM.getObjCRuntime().GetOrEmitProtocol(protocol);
}
std::string CGObjCRuntime::getSymbolNameForMethod(const ObjCMethodDecl *OMD,
bool includeCategoryName) {
std::string buffer;
llvm::raw_string_ostream out(buffer);
CGM.getCXXABI().getMangleContext().mangleObjCMethodName(OMD, out,
true,
includeCategoryName);
return buffer;
}