#define DEBUG_TYPE "sjljehprepare"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/IRBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(NumInvokes, "Number of invokes replaced");
STATISTIC(NumSpilled, "Number of registers live across unwind edges");
namespace {
class SjLjEHPass : public FunctionPass {
const TargetLowering *TLI;
Type *FunctionContextTy;
Constant *RegisterFn;
Constant *UnregisterFn;
Constant *BuiltinSetjmpFn;
Constant *FrameAddrFn;
Constant *StackAddrFn;
Constant *StackRestoreFn;
Constant *LSDAAddrFn;
Value *PersonalityFn;
Constant *CallSiteFn;
Constant *FuncCtxFn;
AllocaInst *FuncCtx;
public:
static char ID; explicit SjLjEHPass(const TargetLowering *tli = NULL)
: FunctionPass(ID), TLI(tli) { }
bool doInitialization(Module &M);
bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
const char *getPassName() const {
return "SJLJ Exception Handling preparation";
}
private:
bool setupEntryBlockAndCallSites(Function &F);
void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
Value *SelVal);
Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
void lowerIncomingArguments(Function &F);
void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
void insertCallSiteStore(Instruction *I, int Number);
};
}
char SjLjEHPass::ID = 0;
FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
return new SjLjEHPass(TLI);
}
bool SjLjEHPass::doInitialization(Module &M) {
Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
Type *Int32Ty = Type::getInt32Ty(M.getContext());
FunctionContextTy =
StructType::get(VoidPtrTy, Int32Ty, ArrayType::get(Int32Ty, 4), VoidPtrTy, VoidPtrTy, ArrayType::get(VoidPtrTy, 5), NULL);
RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
Type::getVoidTy(M.getContext()),
PointerType::getUnqual(FunctionContextTy),
(Type *)0);
UnregisterFn =
M.getOrInsertFunction("_Unwind_SjLj_Unregister",
Type::getVoidTy(M.getContext()),
PointerType::getUnqual(FunctionContextTy),
(Type *)0);
FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
PersonalityFn = 0;
return true;
}
void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number) {
IRBuilder<> Builder(I);
Type *Int32Ty = Type::getInt32Ty(I->getContext());
Value *Zero = ConstantInt::get(Int32Ty, 0);
Value *One = ConstantInt::get(Int32Ty, 1);
Value *Idxs[2] = { Zero, One };
Value *CallSite = Builder.CreateGEP(FuncCtx, Idxs, "call_site");
ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
Number);
Builder.CreateStore(CallSiteNoC, CallSite, true);
}
static void MarkBlocksLiveIn(BasicBlock *BB,
SmallPtrSet<BasicBlock*, 64> &LiveBBs) {
if (!LiveBBs.insert(BB)) return;
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
MarkBlocksLiveIn(*PI, LiveBBs);
}
void SjLjEHPass::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
Value *SelVal) {
SmallVector<Value*, 8> UseWorkList(LPI->use_begin(), LPI->use_end());
while (!UseWorkList.empty()) {
Value *Val = UseWorkList.pop_back_val();
ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
if (!EVI) continue;
if (EVI->getNumIndices() != 1) continue;
if (*EVI->idx_begin() == 0)
EVI->replaceAllUsesWith(ExnVal);
else if (*EVI->idx_begin() == 1)
EVI->replaceAllUsesWith(SelVal);
if (EVI->getNumUses() == 0)
EVI->eraseFromParent();
}
if (LPI->getNumUses() == 0) return;
Type *LPadType = LPI->getType();
Value *LPadVal = UndefValue::get(LPadType);
IRBuilder<>
Builder(llvm::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
LPI->replaceAllUsesWith(LPadVal);
}
Value *SjLjEHPass::
setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
BasicBlock *EntryBB = F.begin();
unsigned Align =
TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
FuncCtx =
new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
Type *Int32Ty = Type::getInt32Ty(F.getContext());
Value *Zero = ConstantInt::get(Int32Ty, 0);
Value *One = ConstantInt::get(Int32Ty, 1);
Value *Two = ConstantInt::get(Int32Ty, 2);
Value *Three = ConstantInt::get(Int32Ty, 3);
Value *Four = ConstantInt::get(Int32Ty, 4);
Value *Idxs[2] = { Zero, 0 };
for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
LandingPadInst *LPI = LPads[I];
IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
Idxs[1] = Two;
Value *FCData = Builder.CreateGEP(FuncCtx, Idxs, "__data");
Idxs[1] = Zero;
Value *ExceptionAddr = Builder.CreateGEP(FCData, Idxs, "exception_gep");
Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
Idxs[1] = One;
Value *SelectorAddr = Builder.CreateGEP(FCData, Idxs, "exn_selector_gep");
Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
substituteLPadValues(LPI, ExnVal, SelVal);
}
Idxs[1] = Three;
if (!PersonalityFn)
PersonalityFn = LPads[0]->getPersonalityFn();
Value *PersonalityFieldPtr =
GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
EntryBB->getTerminator());
new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
EntryBB->getTerminator());
Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
EntryBB->getTerminator());
Idxs[1] = Four;
Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
EntryBB->getTerminator());
new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
return FuncCtx;
}
void SjLjEHPass::lowerIncomingArguments(Function &F) {
BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
while (isa<AllocaInst>(AfterAllocaInsPt) &&
isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
++AfterAllocaInsPt;
for (Function::arg_iterator
AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
Type *Ty = AI->getType();
if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
Instruction *NI = InsertValueInst::Create(AI, EI, 0);
NI->insertAfter(EI);
AI->replaceAllUsesWith(NI);
EI->setOperand(0, AI);
NI->setOperand(0, AI);
} else {
CastInst *NC =
new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
AfterAllocaInsPt);
AI->replaceAllUsesWith(NC);
NC->setOperand(0, AI);
}
}
}
void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
ArrayRef<InvokeInst*> Invokes) {
for (Function::iterator
BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
for (BasicBlock::iterator
II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
Instruction *Inst = II;
if (Inst->use_empty()) continue;
if (Inst->hasOneUse() &&
cast<Instruction>(Inst->use_back())->getParent() == BB &&
!isa<PHINode>(Inst->use_back())) continue;
if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
continue;
SmallVector<Instruction*, 16> Users;
for (Value::use_iterator
UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
Instruction *User = cast<Instruction>(*UI);
if (User->getParent() != BB || isa<PHINode>(User))
Users.push_back(User);
}
SmallPtrSet<BasicBlock*, 64> LiveBBs;
LiveBBs.insert(Inst->getParent());
while (!Users.empty()) {
Instruction *U = Users.back();
Users.pop_back();
if (!isa<PHINode>(U)) {
MarkBlocksLiveIn(U->getParent(), LiveBBs);
} else {
PHINode *PN = cast<PHINode>(U);
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) == Inst)
MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
}
}
bool NeedsSpill = false;
for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
<< UnwindBlock->getName() << "\n");
NeedsSpill = true;
break;
}
}
if (NeedsSpill) {
DemoteRegToStack(*Inst, true);
++NumSpilled;
}
}
}
for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
SmallPtrSet<PHINode*, 8> PHIsToDemote;
for (BasicBlock::iterator
PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
PHIsToDemote.insert(cast<PHINode>(PN));
if (PHIsToDemote.empty()) continue;
for (SmallPtrSet<PHINode*, 8>::iterator
I = PHIsToDemote.begin(), E = PHIsToDemote.end(); I != E; ++I)
DemotePHIToStack(*I);
LPI->moveBefore(UnwindBlock->begin());
}
}
bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
SmallVector<ReturnInst*, 16> Returns;
SmallVector<InvokeInst*, 16> Invokes;
SmallSetVector<LandingPadInst*, 16> LPads;
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Invokes.push_back(II);
LPads.insert(II->getUnwindDest()->getLandingPadInst());
} else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Returns.push_back(RI);
}
if (Invokes.empty()) return false;
NumInvokes += Invokes.size();
lowerIncomingArguments(F);
lowerAcrossUnwindEdges(F, Invokes);
Value *FuncCtx =
setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
BasicBlock *EntryBB = F.begin();
Type *Int32Ty = Type::getInt32Ty(F.getContext());
Value *Idxs[2] = {
ConstantInt::get(Int32Ty, 0), 0
};
Idxs[1] = ConstantInt::get(Int32Ty, 5);
Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
EntryBB->getTerminator());
Idxs[1] = ConstantInt::get(Int32Ty, 0);
Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
EntryBB->getTerminator());
Value *Val = CallInst::Create(FrameAddrFn,
ConstantInt::get(Int32Ty, 0),
"fp",
EntryBB->getTerminator());
new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
Idxs[1] = ConstantInt::get(Int32Ty, 2);
Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
EntryBB->getTerminator());
Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
Type::getInt8PtrTy(F.getContext()), "",
EntryBB->getTerminator());
CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
Type::getInt8PtrTy(F.getContext()), "",
EntryBB->getTerminator());
CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
insertCallSiteStore(Invokes[I], I + 1);
ConstantInt *CallSiteNum =
ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
}
for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
if (CallInst *CI = dyn_cast<CallInst>(I)) {
if (!CI->doesNotThrow())
insertCallSiteStore(CI, -1);
} else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
insertCallSiteStore(RI, -1);
}
CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
EntryBB->getTerminator());
Register->setDoesNotThrow();
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
if (BB == F.begin())
continue;
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
if (CallInst *CI = dyn_cast<CallInst>(I)) {
if (CI->getCalledFunction() != StackRestoreFn)
continue;
} else if (!isa<AllocaInst>(I)) {
continue;
}
Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
StackAddr->insertAfter(I);
Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
StoreStackAddr->insertAfter(StackAddr);
}
}
for (unsigned I = 0, E = Returns.size(); I != E; ++I)
CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
return true;
}
bool SjLjEHPass::runOnFunction(Function &F) {
bool Res = setupEntryBlockAndCallSites(F);
return Res;
}