// allocation block, and to remap the frame variable allocas (including
// spill locations as needed) to GEPs that get the variable from the
// frame allocation structure.
-typedef MapVector<AllocaInst *, HandlerAllocas> FrameVarInfoMap;
+typedef MapVector<Value *, HandlerAllocas> FrameVarInfoMap;
class WinEHPrepare : public FunctionPass {
std::unique_ptr<FunctionPass> DwarfPrepare;
+ enum HandlerType { Catch, Cleanup };
+
public:
static char ID; // Pass identification, replacement for typeid.
WinEHPrepare(const TargetMachine *TM = nullptr)
private:
bool prepareCPPEHHandlers(Function &F,
SmallVectorImpl<LandingPadInst *> &LPads);
- bool outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
- LandingPadInst *LPad, CallInst *&EHAlloc,
- AllocaInst *&EHObjPtr, FrameVarInfoMap &VarInfo);
+ bool outlineHandler(HandlerType CatchOrCleanup, Function *SrcFn,
+ Constant *SelectorType, LandingPadInst *LPad,
+ CallInst *&EHAlloc, FrameVarInfoMap &VarInfo);
};
class WinEHFrameVariableMaterializer : public ValueMaterializer {
IRBuilder<> Builder;
};
-class WinEHCatchDirector : public CloningDirector {
+class WinEHCloningDirectorBase : public CloningDirector {
public:
- WinEHCatchDirector(LandingPadInst *LPI, Function *CatchFn, Value *Selector,
- Value *EHObj, FrameVarInfoMap &VarInfo)
- : LPI(LPI), CurrentSelector(Selector->stripPointerCasts()), EHObj(EHObj),
- Materializer(CatchFn, VarInfo),
+ WinEHCloningDirectorBase(LandingPadInst *LPI, Function *HandlerFn,
+ FrameVarInfoMap &VarInfo)
+ : LPI(LPI), Materializer(HandlerFn, VarInfo),
SelectorIDType(Type::getInt32Ty(LPI->getContext())),
Int8PtrType(Type::getInt8PtrTy(LPI->getContext())) {}
const Instruction *Inst,
BasicBlock *NewBB) override;
+ virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
+ const Instruction *Inst,
+ BasicBlock *NewBB) = 0;
+ virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
+ const Instruction *Inst,
+ BasicBlock *NewBB) = 0;
+ virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
+ const Instruction *Inst,
+ BasicBlock *NewBB) = 0;
+ virtual CloningAction handleResume(ValueToValueMapTy &VMap,
+ const ResumeInst *Resume,
+ BasicBlock *NewBB) = 0;
+
ValueMaterializer *getValueMaterializer() override { return &Materializer; }
-private:
+protected:
LandingPadInst *LPI;
- Value *CurrentSelector;
- Value *EHObj;
WinEHFrameVariableMaterializer Materializer;
Type *SelectorIDType;
Type *Int8PtrType;
const Value *EHPtrStoreAddr;
const Value *SelectorStoreAddr;
};
+
+class WinEHCatchDirector : public WinEHCloningDirectorBase {
+public:
+ WinEHCatchDirector(LandingPadInst *LPI, Function *CatchFn, Value *Selector,
+ FrameVarInfoMap &VarInfo)
+ : WinEHCloningDirectorBase(LPI, CatchFn, VarInfo),
+ CurrentSelector(Selector->stripPointerCasts()) {}
+
+ CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
+ const Instruction *Inst,
+ BasicBlock *NewBB) override;
+ CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
+ BasicBlock *NewBB) override;
+ CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
+ const Instruction *Inst,
+ BasicBlock *NewBB) override;
+ CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
+ BasicBlock *NewBB) override;
+
+private:
+ Value *CurrentSelector;
+};
+
+class WinEHCleanupDirector : public WinEHCloningDirectorBase {
+public:
+ WinEHCleanupDirector(LandingPadInst *LPI, Function *CleanupFn,
+ FrameVarInfoMap &VarInfo)
+ : WinEHCloningDirectorBase(LPI, CleanupFn, VarInfo) {}
+
+ CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
+ const Instruction *Inst,
+ BasicBlock *NewBB) override;
+ CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
+ BasicBlock *NewBB) override;
+ CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
+ const Instruction *Inst,
+ BasicBlock *NewBB) override;
+ CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
+ BasicBlock *NewBB) override;
+};
+
} // end anonymous namespace
char WinEHPrepare::ID = 0;
// handlers are outlined.
FrameVarInfoMap FrameVarInfo;
SmallVector<CallInst *, 4> HandlerAllocs;
- SmallVector<AllocaInst *, 4> HandlerEHObjPtrs;
bool HandlersOutlined = false;
// Create a new instance of the handler data structure in the
// HandlerData vector.
CallInst *EHAlloc = nullptr;
- AllocaInst *EHObjPtr = nullptr;
- bool Outlined = outlineCatchHandler(&F, LPad->getClause(Idx), LPad,
- EHAlloc, EHObjPtr, FrameVarInfo);
+ bool Outlined = outlineHandler(Catch, &F, LPad->getClause(Idx), LPad,
+ EHAlloc, FrameVarInfo);
if (Outlined) {
HandlersOutlined = true;
// These values must be resolved after all handlers have been
// outlined.
if (EHAlloc)
HandlerAllocs.push_back(EHAlloc);
- if (EHObjPtr)
- HandlerEHObjPtrs.push_back(EHObjPtr);
}
} // End if (isCatch)
} // End for each clause
- } // End for each landingpad
+
+ // FIXME: This only handles the simple case where there is a 1:1
+ // correspondence between landing pad and cleanup blocks.
+ // It does not handle cases where there are catch blocks between
+ // cleanup blocks or the case where a cleanup block is shared by
+ // multiple landing pads. Those cases will be supported later
+ // when landing pad block analysis is added.
+ if (LPad->isCleanup()) {
+ CallInst *EHAlloc = nullptr;
+ bool Outlined =
+ outlineHandler(Cleanup, &F, nullptr, LPad, EHAlloc, FrameVarInfo);
+ if (Outlined) {
+ HandlersOutlined = true;
+ // This value must be resolved after all handlers have been outlined.
+ if (EHAlloc)
+ HandlerAllocs.push_back(EHAlloc);
+ }
+ }
+ } // End for each landingpad
// If nothing got outlined, there is no more processing to be done.
if (!HandlersOutlined)
// all the entries in the HandlerData have been processed this isn't a
// problem.
for (auto &VarInfoEntry : FrameVarInfo) {
- AllocaInst *ParentAlloca = VarInfoEntry.first;
+ Value *ParentVal = VarInfoEntry.first;
HandlerAllocas &AllocaInfo = VarInfoEntry.second;
- // If the instruction still has uses in the parent function or if it is
- // referenced by more than one handler, add it to the frame allocation
- // structure.
- if (ParentAlloca->getNumUses() != 0 || AllocaInfo.Allocas.size() > 1) {
- Type *VarTy = ParentAlloca->getAllocatedType();
+ if (auto *ParentAlloca = dyn_cast<AllocaInst>(ParentVal)) {
+ // If the instruction still has uses in the parent function or if it is
+ // referenced by more than one handler, add it to the frame allocation
+ // structure.
+ if (ParentAlloca->getNumUses() != 0 || AllocaInfo.Allocas.size() > 1) {
+ Type *VarTy = ParentAlloca->getAllocatedType();
+ StructTys.push_back(VarTy);
+ AllocaInfo.ParentFrameAllocationIndex = Idx++;
+ } else {
+ // If the variable is not used in the parent frame and it is only used
+ // in one handler, the alloca can be removed from the parent frame
+ // and the handler will keep its "temporary" alloca to define the value.
+ // An element index of -1 is used to indicate this condition.
+ AllocaInfo.ParentFrameAllocationIndex = -1;
+ }
+ } else {
+ // FIXME: Sink non-alloca values into the handler if they have no other
+ // uses in the parent function after outlining and are only used in
+ // one handler.
+ Type *VarTy = ParentVal->getType();
StructTys.push_back(VarTy);
AllocaInfo.ParentFrameAllocationIndex = Idx++;
- } else {
- // If the variable is not used in the parent frame and it is only used
- // in one handler, the alloca can be removed from the parent frame
- // and the handler will keep its "temporary" alloca to define the value.
- // An element index of -1 is used to indicate this condition.
- AllocaInfo.ParentFrameAllocationIndex = -1;
}
}
Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Function *FrameAllocFn =
Intrinsic::getDeclaration(M, Intrinsic::frameallocate);
- uint64_t EHAllocSize = M->getDataLayout()->getTypeAllocSize(EHDataStructTy);
+ uint64_t EHAllocSize = M->getDataLayout().getTypeAllocSize(EHDataStructTy);
Value *FrameAllocArgs[] = {
ConstantInt::get(Type::getInt32Ty(Context), EHAllocSize)};
CallInst *FrameAlloc =
EHDataMap[EHAlloc->getParent()->getParent()] = EHData;
}
- // Next, replace the place-holder EHObjPtr allocas with GEP instructions
- // that pull the EHObjPtr from the frame alloc structure
- for (AllocaInst *EHObjPtr : HandlerEHObjPtrs) {
- Value *EHData = EHDataMap[EHObjPtr->getParent()->getParent()];
- Builder.SetInsertPoint(EHObjPtr);
- Value *ElementPtr = Builder.CreateConstInBoundsGEP2_32(EHData, 0, 1);
- EHObjPtr->replaceAllUsesWith(ElementPtr);
- EHObjPtr->removeFromParent();
- ElementPtr->takeName(EHObjPtr);
- delete EHObjPtr;
- }
-
// Finally, replace all of the temporary allocas for frame variables used in
// the outlined handlers and the original frame allocas with GEP instructions
// that get the equivalent pointer from the frame allocation struct.
+ Instruction *FrameEHDataInst = cast<Instruction>(FrameEHData);
+ BasicBlock::iterator II = FrameEHDataInst;
+ ++II;
+ Instruction *AllocaInsertPt = II;
for (auto &VarInfoEntry : FrameVarInfo) {
- AllocaInst *ParentAlloca = VarInfoEntry.first;
+ Value *ParentVal = VarInfoEntry.first;
HandlerAllocas &AllocaInfo = VarInfoEntry.second;
int Idx = AllocaInfo.ParentFrameAllocationIndex;
+ // If the mapped value isn't already an alloca, we need to spill it if it
+ // is a computed value or copy it if it is an argument.
+ AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal);
+ if (!ParentAlloca) {
+ if (auto *Arg = dyn_cast<Argument>(ParentVal)) {
+ // Lower this argument to a copy and then demote that to the stack.
+ // We can't just use the argument location because the handler needs
+ // it to be in the frame allocation block.
+ // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
+ Value *TrueValue = ConstantInt::getTrue(Context);
+ Value *UndefValue = UndefValue::get(Arg->getType());
+ Instruction *SI =
+ SelectInst::Create(TrueValue, Arg, UndefValue,
+ Arg->getName() + ".tmp", AllocaInsertPt);
+ Arg->replaceAllUsesWith(SI);
+ // Reset the select operand, because it was clobbered by the RAUW above.
+ SI->setOperand(1, Arg);
+ ParentAlloca = DemoteRegToStack(*SI, true, SI);
+ } else if (auto *PN = dyn_cast<PHINode>(ParentVal)) {
+ ParentAlloca = DemotePHIToStack(PN, AllocaInsertPt);
+ } else {
+ Instruction *ParentInst = cast<Instruction>(ParentVal);
+ ParentAlloca = DemoteRegToStack(*ParentInst, true, ParentInst);
+ }
+ }
+
// If we have an index of -1 for this instruction, it means it isn't used
// outside of this handler. In that case, we just keep the "temporary"
// alloca in the handler and erase the original alloca from the parent.
ParentAlloca->replaceAllUsesWith(ElementPtr);
ParentAlloca->removeFromParent();
ElementPtr->takeName(ParentAlloca);
+ if (ParentAlloca == AllocaInsertPt)
+ AllocaInsertPt = dyn_cast<Instruction>(ElementPtr);
delete ParentAlloca;
// Next replace all outlined allocas that are mapped to it.
return HandlersOutlined;
}
-bool WinEHPrepare::outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
- LandingPadInst *LPad, CallInst *&EHAlloc,
- AllocaInst *&EHObjPtr,
- FrameVarInfoMap &VarInfo) {
+bool WinEHPrepare::outlineHandler(HandlerType CatchOrCleanup, Function *SrcFn,
+ Constant *SelectorType, LandingPadInst *LPad,
+ CallInst *&EHAlloc,
+ FrameVarInfoMap &VarInfo) {
Module *M = SrcFn->getParent();
LLVMContext &Context = M->getContext();
std::vector<Type *> ArgTys;
ArgTys.push_back(Int8PtrType);
ArgTys.push_back(Int8PtrType);
- FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
- Function *CatchHandler = Function::Create(
- FnType, GlobalVariable::ExternalLinkage, SrcFn->getName() + ".catch", M);
+ Function *Handler;
+ if (CatchOrCleanup == Catch) {
+ FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
+ Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
+ SrcFn->getName() + ".catch", M);
+ } else {
+ FunctionType *FnType =
+ FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
+ Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
+ SrcFn->getName() + ".cleanup", M);
+ }
// Generate a standard prolog to setup the frame recovery structure.
IRBuilder<> Builder(Context);
- BasicBlock *Entry = BasicBlock::Create(Context, "catch.entry");
- CatchHandler->getBasicBlockList().push_front(Entry);
+ BasicBlock *Entry = BasicBlock::Create(Context, "entry");
+ Handler->getBasicBlockList().push_front(Entry);
Builder.SetInsertPoint(Entry);
Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
Function *RecoverFrameFn =
Intrinsic::getDeclaration(M, Intrinsic::framerecover);
Value *RecoverArgs[] = {Builder.CreateBitCast(SrcFn, Int8PtrType, ""),
- &(CatchHandler->getArgumentList().back())};
+ &(Handler->getArgumentList().back())};
EHAlloc = Builder.CreateCall(RecoverFrameFn, RecoverArgs, "eh.alloc");
- // This alloca is only temporary. We'll be replacing it once we know all the
- // frame variables that need to go in the frame allocation structure.
- EHObjPtr = Builder.CreateAlloca(Int8PtrType, 0, "eh.obj.ptr");
+ std::unique_ptr<WinEHCloningDirectorBase> Director;
- // This will give us a raw pointer to the exception object, which
- // corresponds to the formal parameter of the catch statement. If the
- // handler uses this object, we will generate code during the outlining
- // process to cast the pointer to the appropriate type and deference it
- // as necessary. The un-outlined landing pad code represents the
- // exception object as the result of the llvm.eh.begincatch call.
- Value *EHObj = Builder.CreateLoad(EHObjPtr, false, "eh.obj");
+ if (CatchOrCleanup == Catch) {
+ Director.reset(
+ new WinEHCatchDirector(LPad, Handler, SelectorType, VarInfo));
+ } else {
+ Director.reset(new WinEHCleanupDirector(LPad, Handler, VarInfo));
+ }
ValueToValueMapTy VMap;
// FIXME: Map other values referenced in the filter handler.
- WinEHCatchDirector Director(LPad, CatchHandler, SelectorType, EHObj, VarInfo);
-
SmallVector<ReturnInst *, 8> Returns;
ClonedCodeInfo InlinedFunctionInfo;
BasicBlock::iterator II = LPad;
- CloneAndPruneIntoFromInst(CatchHandler, SrcFn, ++II, VMap,
- /*ModuleLevelChanges=*/false, Returns, "",
- &InlinedFunctionInfo,
- SrcFn->getParent()->getDataLayout(), &Director);
+ CloneAndPruneIntoFromInst(
+ Handler, SrcFn, ++II, VMap,
+ /*ModuleLevelChanges=*/false, Returns, "", &InlinedFunctionInfo,
+ &SrcFn->getParent()->getDataLayout(), Director.get());
// Move all the instructions in the first cloned block into our entry block.
BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
return true;
}
-CloningDirector::CloningAction WinEHCatchDirector::handleInstruction(
+CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
// Intercept instructions which extract values from the landing pad aggregate.
if (auto *Extract = dyn_cast<ExtractValueInst>(Inst)) {
return CloningDirector::CloneInstruction;
}
- if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) {
- // The argument to the call is some form of the first element of the
- // landingpad aggregate value, but that doesn't matter. It isn't used
- // here.
- // The return value of this instruction, however, is used to access the
- // EH object pointer. We have generated an instruction to get that value
- // from the EH alloc block, so we can just map to that here.
- VMap[Inst] = EHObj;
- return CloningDirector::SkipInstruction;
- }
- if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) {
- auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
- // It might be interesting to track whether or not we are inside a catch
- // function, but that might make the algorithm more brittle than it needs
- // to be.
-
- // The end catch call can occur in one of two places: either in a
- // landingpad
- // block that is part of the catch handlers exception mechanism, or at the
- // end of the catch block. If it occurs in a landing pad, we must skip it
- // and continue so that the landing pad gets cloned.
- // FIXME: This case isn't fully supported yet and shouldn't turn up in any
- // of the test cases until it is.
- if (IntrinCall->getParent()->isLandingPad())
- return CloningDirector::SkipInstruction;
+ if (auto *Resume = dyn_cast<ResumeInst>(Inst))
+ return handleResume(VMap, Resume, NewBB);
- // If an end catch occurs anywhere else the next instruction should be an
- // unconditional branch instruction that we want to replace with a return
- // to the the address of the branch target.
- const BasicBlock *EndCatchBB = IntrinCall->getParent();
- const TerminatorInst *Terminator = EndCatchBB->getTerminator();
- const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
- assert(Branch && Branch->isUnconditional());
- assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==
- BasicBlock::const_iterator(Branch));
-
- ReturnInst::Create(NewBB->getContext(),
- BlockAddress::get(Branch->getSuccessor(0)), NewBB);
-
- // We just added a terminator to the cloned block.
- // Tell the caller to stop processing the current basic block so that
- // the branch instruction will be skipped.
- return CloningDirector::StopCloningBB;
- }
- if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) {
- auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
- Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
- // This causes a replacement that will collapse the landing pad CFG based
- // on the filter function we intend to match.
- if (Selector == CurrentSelector)
- VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
- else
- VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
- // Tell the caller not to clone this instruction.
- return CloningDirector::SkipInstruction;
- }
+ if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
+ return handleBeginCatch(VMap, Inst, NewBB);
+ if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
+ return handleEndCatch(VMap, Inst, NewBB);
+ if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
+ return handleTypeIdFor(VMap, Inst, NewBB);
// Continue with the default cloning behavior.
return CloningDirector::CloneInstruction;
}
+CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
+ ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
+ // The argument to the call is some form of the first element of the
+ // landingpad aggregate value, but that doesn't matter. It isn't used
+ // here.
+ // The second argument is an outparameter where the exception object will be
+ // stored. Typically the exception object is a scalar, but it can be an
+ // aggregate when catching by value.
+ // FIXME: Leave something behind to indicate where the exception object lives
+ // for this handler. Should it be part of llvm.eh.actions?
+ return CloningDirector::SkipInstruction;
+}
+
+CloningDirector::CloningAction
+WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
+ const Instruction *Inst, BasicBlock *NewBB) {
+ auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
+ // It might be interesting to track whether or not we are inside a catch
+ // function, but that might make the algorithm more brittle than it needs
+ // to be.
+
+ // The end catch call can occur in one of two places: either in a
+ // landingpad
+ // block that is part of the catch handlers exception mechanism, or at the
+ // end of the catch block. If it occurs in a landing pad, we must skip it
+ // and continue so that the landing pad gets cloned.
+ // FIXME: This case isn't fully supported yet and shouldn't turn up in any
+ // of the test cases until it is.
+ if (IntrinCall->getParent()->isLandingPad())
+ return CloningDirector::SkipInstruction;
+
+ // If an end catch occurs anywhere else the next instruction should be an
+ // unconditional branch instruction that we want to replace with a return
+ // to the the address of the branch target.
+ const BasicBlock *EndCatchBB = IntrinCall->getParent();
+ const TerminatorInst *Terminator = EndCatchBB->getTerminator();
+ const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
+ assert(Branch && Branch->isUnconditional());
+ assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==
+ BasicBlock::const_iterator(Branch));
+
+ ReturnInst::Create(NewBB->getContext(),
+ BlockAddress::get(Branch->getSuccessor(0)), NewBB);
+
+ // We just added a terminator to the cloned block.
+ // Tell the caller to stop processing the current basic block so that
+ // the branch instruction will be skipped.
+ return CloningDirector::StopCloningBB;
+}
+
+CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
+ ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
+ auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
+ Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
+ // This causes a replacement that will collapse the landing pad CFG based
+ // on the filter function we intend to match.
+ if (Selector == CurrentSelector)
+ VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
+ else
+ VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
+ // Tell the caller not to clone this instruction.
+ return CloningDirector::SkipInstruction;
+}
+
+CloningDirector::CloningAction
+WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
+ const ResumeInst *Resume, BasicBlock *NewBB) {
+ // Resume instructions shouldn't be reachable from catch handlers.
+ // We still need to handle it, but it will be pruned.
+ BasicBlock::InstListType &InstList = NewBB->getInstList();
+ InstList.push_back(new UnreachableInst(NewBB->getContext()));
+ return CloningDirector::StopCloningBB;
+}
+
+CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
+ ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
+ // Catch blocks within cleanup handlers will always be unreachable.
+ // We'll insert an unreachable instruction now, but it will be pruned
+ // before the cloning process is complete.
+ BasicBlock::InstListType &InstList = NewBB->getInstList();
+ InstList.push_back(new UnreachableInst(NewBB->getContext()));
+ return CloningDirector::StopCloningBB;
+}
+
+CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
+ ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
+ // Catch blocks within cleanup handlers will always be unreachable.
+ // We'll insert an unreachable instruction now, but it will be pruned
+ // before the cloning process is complete.
+ BasicBlock::InstListType &InstList = NewBB->getInstList();
+ InstList.push_back(new UnreachableInst(NewBB->getContext()));
+ return CloningDirector::StopCloningBB;
+}
+
+CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
+ ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
+ // This causes a replacement that will collapse the landing pad CFG
+ // to just the cleanup code.
+ VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
+ // Tell the caller not to clone this instruction.
+ return CloningDirector::SkipInstruction;
+}
+
+CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
+ ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
+ ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
+
+ // We just added a terminator to the cloned block.
+ // Tell the caller to stop processing the current basic block so that
+ // the branch instruction will be skipped.
+ return CloningDirector::StopCloningBB;
+}
+
WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
: FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
}
Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
- // If we're asked to materialize an alloca variable, we temporarily
- // create a matching alloca in the outlined function. When all the
- // outlining is complete, we'll collect these into a structure and
- // replace these temporary allocas with GEPs referencing the frame
- // allocation block.
+ // If we're asked to materialize a value that is an instruction, we
+ // temporarily create an alloca in the outlined function and add this
+ // to the FrameVarInfo map. When all the outlining is complete, we'll
+ // collect these into a structure, spilling non-alloca values in the
+ // parent frame as necessary, and replace these temporary allocas with
+ // GEPs referencing the frame allocation block.
+
+ // If the value is an alloca, the mapping is direct.
if (auto *AV = dyn_cast<AllocaInst>(V)) {
- AllocaInst *NewAlloca = Builder.CreateAlloca(
- AV->getAllocatedType(), AV->getArraySize(), AV->getName());
+ AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
+ Builder.Insert(NewAlloca, AV->getName());
FrameVarInfo[AV].Allocas.push_back(NewAlloca);
return NewAlloca;
}
-// FIXME: Do PHI nodes need special handling?
-
-// FIXME: Are there other cases we can handle better? GEP, ExtractValue, etc.
-
-// FIXME: This doesn't work during cloning because it finds an instruction
-// in the use list that isn't yet part of a basic block.
-#if 0
- // If we're asked to remap some other instruction, we'll need to
- // spill it to an alloca variable in the parent function and add a
- // temporary alloca in the outlined function to be processed as
- // described above.
- Instruction *Inst = dyn_cast<Instruction>(V);
- if (Inst) {
- AllocaInst *Spill = DemoteRegToStack(*Inst, true);
- AllocaInst *NewAlloca = Builder.CreateAlloca(Spill->getAllocatedType(),
- Spill->getArraySize());
- FrameVarMap[AV] = NewAlloca;
- return NewAlloca;
+ // For other types of instructions or arguments, we need an alloca based on
+ // the value's type and a load of the alloca. The alloca will be replaced
+ // by a GEP, but the load will stay. In the parent function, the value will
+ // be spilled to a location in the frame allocation block.
+ if (isa<Instruction>(V) || isa<Argument>(V)) {
+ AllocaInst *NewAlloca =
+ Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
+ FrameVarInfo[V].Allocas.push_back(NewAlloca);
+ LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
+ return NewLoad;
}
-#endif
+ // Don't materialize other values.
return nullptr;
}