-//===-- WinEHPrepare - Prepare exception handling for code generation ---===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// This pass lowers LLVM IR exception handling into something closer to what the
-// backend wants. It snifs the personality function to see which kind of
-// preparation is necessary. If the personality function uses the Itanium LSDA,
-// this pass delegates to the DWARF EH preparation pass.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/CodeGen/Passes.h"
-#include "llvm/Analysis/LibCallSemantics.h"
-#include "llvm/IR/Function.h"
-#include "llvm/IR/IRBuilder.h"
-#include "llvm/IR/Instructions.h"
-#include "llvm/Pass.h"
-#include <memory>
-
-using namespace llvm;
-
-#define DEBUG_TYPE "winehprepare"
-
-namespace {
-class WinEHPrepare : public FunctionPass {
- std::unique_ptr<FunctionPass> DwarfPrepare;
-
-public:
- static char ID; // Pass identification, replacement for typeid.
- WinEHPrepare(const TargetMachine *TM = nullptr)
- : FunctionPass(ID), DwarfPrepare(createDwarfEHPass(TM)) {}
-
- bool runOnFunction(Function &Fn) override;
-
- bool doFinalization(Module &M) override;
-
- void getAnalysisUsage(AnalysisUsage &AU) const override;
-
- const char *getPassName() const override {
- return "Windows exception handling preparation";
- }
-};
-} // end anonymous namespace
-
-char WinEHPrepare::ID = 0;
-INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare",
- "Prepare Windows exceptions", false, false)
-
-FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
- return new WinEHPrepare(TM);
-}
-
-static bool isMSVCPersonality(EHPersonality Pers) {
- return Pers == EHPersonality::MSVC_Win64SEH ||
- Pers == EHPersonality::MSVC_CXX;
-}
-
-bool WinEHPrepare::runOnFunction(Function &Fn) {
- SmallVector<LandingPadInst *, 4> LPads;
- SmallVector<ResumeInst *, 4> Resumes;
- for (BasicBlock &BB : Fn) {
- if (auto *LP = BB.getLandingPadInst())
- LPads.push_back(LP);
- if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
- Resumes.push_back(Resume);
- }
-
- // No need to prepare functions that lack landing pads.
- if (LPads.empty())
- return false;
-
- // Classify the personality to see what kind of preparation we need.
- EHPersonality Pers = classifyEHPersonality(LPads.back()->getPersonalityFn());
-
- // Delegate through to the DWARF pass if this is unrecognized.
- if (!isMSVCPersonality(Pers))
- return DwarfPrepare->runOnFunction(Fn);
-
- // FIXME: Cleanups are unimplemented. Replace them with unreachable.
- if (Resumes.empty())
- return false;
-
- for (ResumeInst *Resume : Resumes) {
- IRBuilder<>(Resume).CreateUnreachable();
- Resume->eraseFromParent();
- }
-
- return true;
-}
-
-bool WinEHPrepare::doFinalization(Module &M) {
- return DwarfPrepare->doFinalization(M);
-}
-
-void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
- DwarfPrepare->getAnalysisUsage(AU);
-}
+//===-- WinEHPrepare - Prepare exception handling for code generation ---===//\r
+//\r
+// The LLVM Compiler Infrastructure\r
+//\r
+// This file is distributed under the University of Illinois Open Source\r
+// License. See LICENSE.TXT for details.\r
+//\r
+//===----------------------------------------------------------------------===//\r
+//\r
+// This pass lowers LLVM IR exception handling into something closer to what the\r
+// backend wants. It snifs the personality function to see which kind of\r
+// preparation is necessary. If the personality function uses the Itanium LSDA,\r
+// this pass delegates to the DWARF EH preparation pass.\r
+//\r
+//===----------------------------------------------------------------------===//\r
+\r
+#include "llvm/CodeGen/Passes.h"\r
+#include "llvm/Analysis/LibCallSemantics.h"\r
+#include "llvm/IR/Function.h"\r
+#include "llvm/IR/IRBuilder.h"\r
+#include "llvm/IR/Instructions.h"\r
+#include "llvm/IR/IntrinsicInst.h"\r
+#include "llvm/IR/Module.h"\r
+#include "llvm/IR/PatternMatch.h"\r
+#include "llvm/Pass.h"\r
+#include "llvm/Transforms/Utils/Cloning.h"\r
+#include "llvm/Transforms/Utils/Local.h"\r
+#include <memory>\r
+\r
+using namespace llvm;\r
+using namespace llvm::PatternMatch;\r
+\r
+#define DEBUG_TYPE "winehprepare"\r
+\r
+namespace {\r
+class WinEHPrepare : public FunctionPass {\r
+ std::unique_ptr<FunctionPass> DwarfPrepare;\r
+\r
+public:\r
+ static char ID; // Pass identification, replacement for typeid.\r
+ WinEHPrepare(const TargetMachine *TM = nullptr)\r
+ : FunctionPass(ID), DwarfPrepare(createDwarfEHPass(TM)) {}\r
+\r
+ bool runOnFunction(Function &Fn) override;\r
+\r
+ bool doFinalization(Module &M) override;\r
+\r
+ void getAnalysisUsage(AnalysisUsage &AU) const override;\r
+\r
+ const char *getPassName() const override {\r
+ return "Windows exception handling preparation";\r
+ }\r
+\r
+private:\r
+ bool prepareCPPEHHandlers(Function &F,\r
+ SmallVectorImpl<LandingPadInst *> &LPads);\r
+ bool outlineCatchHandler(Function *SrcFn, Constant *SelectorType,\r
+ LandingPadInst *LPad, StructType *EHDataStructTy);\r
+};\r
+\r
+class WinEHCatchDirector : public CloningDirector {\r
+public:\r
+ WinEHCatchDirector(LandingPadInst *LPI, Function *CatchFn, Value *Selector,\r
+ Value *EHObj)\r
+ : LPI(LPI), CatchFn(CatchFn),\r
+ CurrentSelector(Selector->stripPointerCasts()), EHObj(EHObj),\r
+ SelectorIDType(Type::getInt32Ty(LPI->getContext())),\r
+ Int8PtrType(Type::getInt8PtrTy(LPI->getContext())) {}\r
+ virtual ~WinEHCatchDirector() {}\r
+\r
+ CloningAction handleInstruction(ValueToValueMapTy &VMap,\r
+ const Instruction *Inst,\r
+ BasicBlock *NewBB) override;\r
+\r
+private:\r
+ LandingPadInst *LPI;\r
+ Function *CatchFn;\r
+ Value *CurrentSelector;\r
+ Value *EHObj;\r
+ Type *SelectorIDType;\r
+ Type *Int8PtrType;\r
+\r
+ const Value *ExtractedEHPtr;\r
+ const Value *ExtractedSelector;\r
+ const Value *EHPtrStoreAddr;\r
+ const Value *SelectorStoreAddr;\r
+ const Value *EHObjStoreAddr;\r
+};\r
+} // end anonymous namespace\r
+\r
+char WinEHPrepare::ID = 0;\r
+INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",\r
+ false, false)\r
+\r
+FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {\r
+ return new WinEHPrepare(TM);\r
+}\r
+\r
+static bool isMSVCPersonality(EHPersonality Pers) {\r
+ return Pers == EHPersonality::MSVC_Win64SEH ||\r
+ Pers == EHPersonality::MSVC_CXX;\r
+}\r
+\r
+bool WinEHPrepare::runOnFunction(Function &Fn) {\r
+ SmallVector<LandingPadInst *, 4> LPads;\r
+ SmallVector<ResumeInst *, 4> Resumes;\r
+ for (BasicBlock &BB : Fn) {\r
+ if (auto *LP = BB.getLandingPadInst())\r
+ LPads.push_back(LP);\r
+ if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))\r
+ Resumes.push_back(Resume);\r
+ }\r
+\r
+ // No need to prepare functions that lack landing pads.\r
+ if (LPads.empty())\r
+ return false;\r
+\r
+ // Classify the personality to see what kind of preparation we need.\r
+ EHPersonality Pers = classifyEHPersonality(LPads.back()->getPersonalityFn());\r
+\r
+ // Delegate through to the DWARF pass if this is unrecognized.\r
+ if (!isMSVCPersonality(Pers))\r
+ return DwarfPrepare->runOnFunction(Fn);\r
+\r
+ // FIXME: This only returns true if the C++ EH handlers were outlined.\r
+ // When that code is complete, it should always return whatever\r
+ // prepareCPPEHHandlers returns.\r
+ if (Pers == EHPersonality::MSVC_CXX && prepareCPPEHHandlers(Fn, LPads))\r
+ return true;\r
+\r
+ // FIXME: SEH Cleanups are unimplemented. Replace them with unreachable.\r
+ if (Resumes.empty())\r
+ return false;\r
+\r
+ for (ResumeInst *Resume : Resumes) {\r
+ IRBuilder<>(Resume).CreateUnreachable();\r
+ Resume->eraseFromParent();\r
+ }\r
+\r
+ return true;\r
+}\r
+\r
+bool WinEHPrepare::doFinalization(Module &M) {\r
+ return DwarfPrepare->doFinalization(M);\r
+}\r
+\r
+void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {\r
+ DwarfPrepare->getAnalysisUsage(AU);\r
+}\r
+\r
+bool WinEHPrepare::prepareCPPEHHandlers(\r
+ Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {\r
+ // FIXME: Find all frame variable references in the handlers\r
+ // to populate the structure elements.\r
+ SmallVector<Type *, 2> AllocStructTys;\r
+ AllocStructTys.push_back(Type::getInt32Ty(F.getContext())); // EH state\r
+ AllocStructTys.push_back(Type::getInt8PtrTy(F.getContext())); // EH object\r
+ StructType *EHDataStructTy =\r
+ StructType::create(F.getContext(), AllocStructTys, \r
+ "struct." + F.getName().str() + ".ehdata");\r
+ bool HandlersOutlined = false;\r
+\r
+ for (LandingPadInst *LPad : LPads) {\r
+ // Look for evidence that this landingpad has already been processed.\r
+ bool LPadHasActionList = false;\r
+ BasicBlock *LPadBB = LPad->getParent();\r
+ for (Instruction &Inst : LPadBB->getInstList()) {\r
+ // FIXME: Make this an intrinsic.\r
+ if (auto *Call = dyn_cast<CallInst>(&Inst))\r
+ if (Call->getCalledFunction()->getName() == "llvm.eh.actions") {\r
+ LPadHasActionList = true;\r
+ break;\r
+ }\r
+ }\r
+\r
+ // If we've already outlined the handlers for this landingpad,\r
+ // there's nothing more to do here.\r
+ if (LPadHasActionList)\r
+ continue;\r
+\r
+ for (unsigned Idx = 0, NumClauses = LPad->getNumClauses(); Idx < NumClauses;\r
+ ++Idx) {\r
+ if (LPad->isCatch(Idx))\r
+ HandlersOutlined =\r
+ outlineCatchHandler(&F, LPad->getClause(Idx), LPad, EHDataStructTy);\r
+ } // End for each clause\r
+ } // End for each landingpad\r
+\r
+ return HandlersOutlined;\r
+}\r
+\r
+bool WinEHPrepare::outlineCatchHandler(Function *SrcFn, Constant *SelectorType,\r
+ LandingPadInst *LPad,\r
+ StructType *EHDataStructTy) {\r
+ Module *M = SrcFn->getParent();\r
+ LLVMContext &Context = M->getContext();\r
+\r
+ // Create a new function to receive the handler contents.\r
+ Type *Int8PtrType = Type::getInt8PtrTy(Context);\r
+ std::vector<Type *> ArgTys;\r
+ ArgTys.push_back(Int8PtrType);\r
+ ArgTys.push_back(Int8PtrType);\r
+ FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);\r
+ Function *CatchHandler = Function::Create(\r
+ FnType, GlobalVariable::ExternalLinkage, SrcFn->getName() + ".catch", M);\r
+\r
+ // Generate a standard prolog to setup the frame recovery structure.\r
+ IRBuilder<> Builder(Context);\r
+ BasicBlock *Entry = BasicBlock::Create(Context, "catch.entry");\r
+ CatchHandler->getBasicBlockList().push_front(Entry);\r
+ Builder.SetInsertPoint(Entry);\r
+ Builder.SetCurrentDebugLocation(LPad->getDebugLoc());\r
+\r
+ // The outlined handler will be called with the parent's frame pointer as\r
+ // its second argument. To enable the handler to access variables from\r
+ // the parent frame, we use that pointer to get locate a special block\r
+ // of memory that was allocated using llvm.eh.allocateframe for this\r
+ // purpose. During the outlining process we will determine which frame\r
+ // variables are used in handlers and create a structure that maps these\r
+ // variables into the frame allocation block.\r
+ //\r
+ // The frame allocation block also contains an exception state variable\r
+ // used by the runtime and a pointer to the exception object pointer\r
+ // which will be filled in by the runtime for use in the handler.\r
+ Function *RecoverFrameFn =\r
+ Intrinsic::getDeclaration(M, Intrinsic::framerecover);\r
+ Value *RecoverArgs[] = {Builder.CreateBitCast(SrcFn, Int8PtrType, ""),\r
+ &(CatchHandler->getArgumentList().back())};\r
+ CallInst *EHAlloc =\r
+ Builder.CreateCall(RecoverFrameFn, RecoverArgs, "eh.alloc");\r
+ Value *EHData =\r
+ Builder.CreateBitCast(EHAlloc, EHDataStructTy->getPointerTo(), "ehdata");\r
+ Value *EHObjPtr =\r
+ Builder.CreateConstInBoundsGEP2_32(EHData, 0, 1, "eh.obj.ptr");\r
+\r
+ // This will give us a raw pointer to the exception object, which\r
+ // corresponds to the formal parameter of the catch statement. If the\r
+ // handler uses this object, we will generate code during the outlining\r
+ // process to cast the pointer to the appropriate type and deference it\r
+ // as necessary. The un-outlined landing pad code represents the\r
+ // exception object as the result of the llvm.eh.begincatch call.\r
+ Value *EHObj = Builder.CreateLoad(EHObjPtr, false, "eh.obj");\r
+\r
+ ValueToValueMapTy VMap;\r
+\r
+ // FIXME: Map other values referenced in the filter handler.\r
+\r
+ WinEHCatchDirector Director(LPad, CatchHandler, SelectorType, EHObj);\r
+\r
+ SmallVector<ReturnInst *, 8> Returns;\r
+ ClonedCodeInfo InlinedFunctionInfo;\r
+\r
+ BasicBlock::iterator II = LPad;\r
+\r
+ CloneAndPruneIntoFromInst(CatchHandler, SrcFn, ++II, VMap,\r
+ /*ModuleLevelChanges=*/false, Returns, "",\r
+ &InlinedFunctionInfo,\r
+ SrcFn->getParent()->getDataLayout(), &Director);\r
+\r
+ // Move all the instructions in the first cloned block into our entry block.\r
+ BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));\r
+ Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());\r
+ FirstClonedBB->eraseFromParent();\r
+\r
+ return true;\r
+}\r
+\r
+CloningDirector::CloningAction WinEHCatchDirector::handleInstruction(\r
+ ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {\r
+ // Intercept instructions which extract values from the landing pad aggregate.\r
+ if (auto *Extract = dyn_cast<ExtractValueInst>(Inst)) {\r
+ if (Extract->getAggregateOperand() == LPI) {\r
+ assert(Extract->getNumIndices() == 1 &&\r
+ "Unexpected operation: extracting both landing pad values");\r
+ assert((*(Extract->idx_begin()) == 0 || *(Extract->idx_begin()) == 1) &&\r
+ "Unexpected operation: extracting an unknown landing pad element");\r
+\r
+ if (*(Extract->idx_begin()) == 0) {\r
+ // Element 0 doesn't directly corresponds to anything in the WinEH scheme.\r
+ // It will be stored to a memory location, then later loaded and finally\r
+ // the loaded value will be used as the argument to an llvm.eh.begincatch\r
+ // call. We're tracking it here so that we can skip the store and load.\r
+ ExtractedEHPtr = Inst;\r
+ } else {\r
+ // Element 1 corresponds to the filter selector. We'll map it to 1 for\r
+ // matching purposes, but it will also probably be stored to memory and\r
+ // reloaded, so we need to track the instuction so that we can map the\r
+ // loaded value too.\r
+ VMap[Inst] = ConstantInt::get(SelectorIDType, 1);\r
+ ExtractedSelector = Inst;\r
+ }\r
+\r
+ // Tell the caller not to clone this instruction.\r
+ return CloningDirector::SkipInstruction;\r
+ }\r
+ // Other extract value instructions just get cloned.\r
+ return CloningDirector::CloneInstruction;\r
+ }\r
+\r
+ if (auto *Store = dyn_cast<StoreInst>(Inst)) {\r
+ // Look for and suppress stores of the extracted landingpad values.\r
+ const Value *StoredValue = Store->getValueOperand();\r
+ if (StoredValue == ExtractedEHPtr) {\r
+ EHPtrStoreAddr = Store->getPointerOperand();\r
+ return CloningDirector::SkipInstruction;\r
+ }\r
+ if (StoredValue == ExtractedSelector) {\r
+ SelectorStoreAddr = Store->getPointerOperand();\r
+ return CloningDirector::SkipInstruction;\r
+ }\r
+\r
+ // Any other store just gets cloned.\r
+ return CloningDirector::CloneInstruction;\r
+ }\r
+\r
+ if (auto *Load = dyn_cast<LoadInst>(Inst)) {\r
+ // Look for loads of (previously suppressed) landingpad values.\r
+ // The EHPtr load can be ignored (it should only be used as\r
+ // an argument to llvm.eh.begincatch), but the selector value\r
+ // needs to be mapped to a constant value of 1 to be used to\r
+ // simplify the branching to always flow to the current handler.\r
+ const Value *LoadAddr = Load->getPointerOperand();\r
+ if (LoadAddr == EHPtrStoreAddr) {\r
+ VMap[Inst] = UndefValue::get(Int8PtrType);\r
+ return CloningDirector::SkipInstruction;\r
+ }\r
+ if (LoadAddr == SelectorStoreAddr) {\r
+ VMap[Inst] = ConstantInt::get(SelectorIDType, 1);\r
+ return CloningDirector::SkipInstruction;\r
+ }\r
+\r
+ // Any other loads just get cloned.\r
+ return CloningDirector::CloneInstruction;\r
+ }\r
+\r
+ if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) {\r
+ // The argument to the call is some form of the first element of the\r
+ // landingpad aggregate value, but that doesn't matter. It isn't used\r
+ // here.\r
+ // The return value of this instruction, however, is used to access the\r
+ // EH object pointer. We have generated an instruction to get that value\r
+ // from the EH alloc block, so we can just map to that here.\r
+ VMap[Inst] = EHObj;\r
+ return CloningDirector::SkipInstruction;\r
+ }\r
+ if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) {\r
+ auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);\r
+ // It might be interesting to track whether or not we are inside a catch\r
+ // function, but that might make the algorithm more brittle than it needs\r
+ // to be.\r
+\r
+ // The end catch call can occur in one of two places: either in a\r
+ // landingpad\r
+ // block that is part of the catch handlers exception mechanism, or at the\r
+ // end of the catch block. If it occurs in a landing pad, we must skip it\r
+ // and continue so that the landing pad gets cloned.\r
+ // FIXME: This case isn't fully supported yet and shouldn't turn up in any\r
+ // of the test cases until it is.\r
+ if (IntrinCall->getParent()->isLandingPad())\r
+ return CloningDirector::SkipInstruction;\r
+\r
+ // If an end catch occurs anywhere else the next instruction should be an\r
+ // unconditional branch instruction that we want to replace with a return\r
+ // to the the address of the branch target.\r
+ const BasicBlock *EndCatchBB = IntrinCall->getParent();\r
+ const TerminatorInst *Terminator = EndCatchBB->getTerminator();\r
+ const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);\r
+ assert(Branch && Branch->isUnconditional());\r
+ assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==\r
+ BasicBlock::const_iterator(Branch));\r
+\r
+ ReturnInst::Create(NewBB->getContext(),\r
+ BlockAddress::get(Branch->getSuccessor(0)), NewBB);\r
+\r
+ // We just added a terminator to the cloned block.\r
+ // Tell the caller to stop processing the current basic block so that\r
+ // the branch instruction will be skipped.\r
+ return CloningDirector::StopCloningBB;\r
+ }\r
+ if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) {\r
+ auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);\r
+ Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();\r
+ // This causes a replacement that will collapse the landing pad CFG based\r
+ // on the filter function we intend to match.\r
+ if (Selector == CurrentSelector)\r
+ VMap[Inst] = ConstantInt::get(SelectorIDType, 1);\r
+ else\r
+ VMap[Inst] = ConstantInt::get(SelectorIDType, 0);\r
+ // Tell the caller not to clone this instruction.\r
+ return CloningDirector::SkipInstruction;\r
+ }\r
+\r
+ // Continue with the default cloning behavior.\r
+ return CloningDirector::CloneInstruction;\r
+}\r
const char *NameSuffix;
ClonedCodeInfo *CodeInfo;
const DataLayout *DL;
+ CloningDirector *Director;
+
public:
PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
ValueToValueMapTy &valueMap,
bool moduleLevelChanges,
const char *nameSuffix,
ClonedCodeInfo *codeInfo,
- const DataLayout *DL)
+ const DataLayout *DL,
+ CloningDirector *Director)
: NewFunc(newFunc), OldFunc(oldFunc),
VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
- NameSuffix(nameSuffix), CodeInfo(codeInfo), DL(DL) {
+ NameSuffix(nameSuffix), CodeInfo(codeInfo), DL(DL),
+ Director(Director) {
}
/// CloneBlock - The specified block is found to be reachable, clone it and
/// anything that it can reach.
- void CloneBlock(const BasicBlock *BB,
+ void CloneBlock(const BasicBlock *BB,
+ BasicBlock::const_iterator StartingInst,
std::vector<const BasicBlock*> &ToClone);
};
}
/// CloneBlock - The specified block is found to be reachable, clone it and
/// anything that it can reach.
void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
+ BasicBlock::const_iterator StartingInst,
std::vector<const BasicBlock*> &ToClone){
WeakVH &BBEntry = VMap[BB];
const_cast<BasicBlock*>(BB));
VMap[OldBBAddr] = BlockAddress::get(NewFunc, NewBB);
}
-
bool hasCalls = false, hasDynamicAllocas = false, hasStaticAllocas = false;
-
+
// Loop over all instructions, and copy them over, DCE'ing as we go. This
// loop doesn't include the terminator.
- for (BasicBlock::const_iterator II = BB->begin(), IE = --BB->end();
+ for (BasicBlock::const_iterator II = StartingInst, IE = --BB->end();
II != IE; ++II) {
+ // If the "Director" remaps the instruction, don't clone it.
+ if (Director) {
+ CloningDirector::CloningAction Action
+ = Director->handleInstruction(VMap, II, NewBB);
+ // If the cloning director says stop, we want to stop everything, not
+ // just break out of the loop (which would cause the terminator to be
+ // cloned). The cloning director is responsible for inserting a proper
+ // terminator into the new basic block in this case.
+ if (Action == CloningDirector::StopCloningBB)
+ return;
+ // If the cloning director says skip, continue to the next instruction.
+ // In this case, the cloning director is responsible for mapping the
+ // skipped instruction to some value that is defined in the new
+ // basic block.
+ if (Action == CloningDirector::SkipInstruction)
+ continue;
+ }
+
Instruction *NewInst = II->clone();
// Eagerly remap operands to the newly cloned instruction, except for PHI
// Finally, clone over the terminator.
const TerminatorInst *OldTI = BB->getTerminator();
bool TerminatorDone = false;
+ if (Director) {
+ CloningDirector::CloningAction Action
+ = Director->handleInstruction(VMap, OldTI, NewBB);
+ // If the cloning director says stop, we want to stop everything, not
+ // just break out of the loop (which would cause the terminator to be
+ // cloned). The cloning director is responsible for inserting a proper
+ // terminator into the new basic block in this case.
+ if (Action == CloningDirector::StopCloningBB)
+ return;
+ assert(Action != CloningDirector::SkipInstruction &&
+ "SkipInstruction is not valid for terminators.");
+ }
if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
if (BI->isConditional()) {
// If the condition was a known constant in the callee...
}
}
-/// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
-/// except that it does some simple constant prop and DCE on the fly. The
-/// effect of this is to copy significantly less code in cases where (for
-/// example) a function call with constant arguments is inlined, and those
-/// constant arguments cause a significant amount of code in the callee to be
-/// dead. Since this doesn't produce an exact copy of the input, it can't be
-/// used for things like CloneFunction or CloneModule.
-void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
+/// CloneAndPruneIntoFromInst - This works like CloneAndPruneFunctionInto, except
+/// that it does not clone the entire function. Instead it starts at an
+/// instruction provided by the caller and copies (and prunes) only the code
+/// reachable from that instruction.
+void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
+ const Instruction *StartingInst,
ValueToValueMapTy &VMap,
bool ModuleLevelChanges,
- SmallVectorImpl<ReturnInst*> &Returns,
+ SmallVectorImpl<ReturnInst *> &Returns,
const char *NameSuffix,
ClonedCodeInfo *CodeInfo,
const DataLayout *DL,
- Instruction *TheCall) {
+ CloningDirector *Director) {
assert(NameSuffix && "NameSuffix cannot be null!");
-
+
#ifndef NDEBUG
- for (Function::const_arg_iterator II = OldFunc->arg_begin(),
- E = OldFunc->arg_end(); II != E; ++II)
- assert(VMap.count(II) && "No mapping from source argument specified!");
+ // If the cloning starts at the begining of the function, verify that
+ // the function arguments are mapped.
+ if (!StartingInst)
+ for (Function::const_arg_iterator II = OldFunc->arg_begin(),
+ E = OldFunc->arg_end(); II != E; ++II)
+ assert(VMap.count(II) && "No mapping from source argument specified!");
#endif
PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
- NameSuffix, CodeInfo, DL);
+ NameSuffix, CodeInfo, DL, Director);
+ const BasicBlock *StartingBB;
+ if (StartingInst)
+ StartingBB = StartingInst->getParent();
+ else {
+ StartingBB = &OldFunc->getEntryBlock();
+ StartingInst = StartingBB->begin();
+ }
// Clone the entry block, and anything recursively reachable from it.
std::vector<const BasicBlock*> CloneWorklist;
- CloneWorklist.push_back(&OldFunc->getEntryBlock());
+ PFC.CloneBlock(StartingBB, StartingInst, CloneWorklist);
while (!CloneWorklist.empty()) {
const BasicBlock *BB = CloneWorklist.back();
CloneWorklist.pop_back();
- PFC.CloneBlock(BB, CloneWorklist);
+ PFC.CloneBlock(BB, BB->begin(), CloneWorklist);
}
// Loop over all of the basic blocks in the old function. If the block was
// and zap unconditional fall-through branches. This happen all the time when
// specializing code: code specialization turns conditional branches into
// uncond branches, and this code folds them.
- Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
+ Function::iterator Begin = cast<BasicBlock>(VMap[StartingBB]);
Function::iterator I = Begin;
while (I != NewFunc->end()) {
// Check if this block has become dead during inlining or other
// Make a final pass over the basic blocks from theh old function to gather
// any return instructions which survived folding. We have to do this here
// because we can iteratively remove and merge returns above.
- for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
+ for (Function::iterator I = cast<BasicBlock>(VMap[StartingBB]),
E = NewFunc->end();
I != E; ++I)
if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
Returns.push_back(RI);
}
+
+
+/// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
+/// except that it does some simple constant prop and DCE on the fly. The
+/// effect of this is to copy significantly less code in cases where (for
+/// example) a function call with constant arguments is inlined, and those
+/// constant arguments cause a significant amount of code in the callee to be
+/// dead. Since this doesn't produce an exact copy of the input, it can't be
+/// used for things like CloneFunction or CloneModule.
+void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
+ ValueToValueMapTy &VMap,
+ bool ModuleLevelChanges,
+ SmallVectorImpl<ReturnInst*> &Returns,
+ const char *NameSuffix,
+ ClonedCodeInfo *CodeInfo,
+ const DataLayout *DL,
+ Instruction *TheCall) {
+ CloneAndPruneIntoFromInst(NewFunc, OldFunc, OldFunc->front().begin(),
+ VMap, ModuleLevelChanges, Returns, NameSuffix,
+ CodeInfo, DL, nullptr);
+}