Remap frame variables for native Windows exception handling.
authorAndrew Kaylor <andrew.kaylor@intel.com>
Mon, 23 Feb 2015 20:01:56 +0000 (20:01 +0000)
committerAndrew Kaylor <andrew.kaylor@intel.com>
Mon, 23 Feb 2015 20:01:56 +0000 (20:01 +0000)
Differential Revision: http://reviews.llvm.org/D7770

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@230249 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/Transforms/Utils/Cloning.h
lib/CodeGen/WinEHPrepare.cpp
lib/Transforms/Utils/CloneFunction.cpp
test/CodeGen/X86/cppeh-catch-all.ll
test/CodeGen/X86/cppeh-catch-scalar.ll

index 6c4427652a478c525b44e4d8c2b13a67950dd992..0aca1ab96d3faf745475eb7d4f295a30b01baa39 100644 (file)
@@ -153,6 +153,9 @@ public:
   virtual CloningAction handleInstruction(ValueToValueMapTy &VMap,
                                           const Instruction *Inst,
                                           BasicBlock *NewBB) = 0;
+
+  virtual ValueMapTypeRemapper *getTypeRemapper() { return nullptr; }
+  virtual ValueMaterializer *getValueMaterializer() { return nullptr; }
 };
 
 void CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
index 4a8569cf0265149b0726cbf9b14c27c8a378877d..422ef5adc1de1f30b6cd198f81aa3ed8408fd798 100644 (file)
-//===-- 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/IR/IntrinsicInst.h"
-#include "llvm/IR/Module.h"
-#include "llvm/IR/PatternMatch.h"
-#include "llvm/Pass.h"
-#include "llvm/Transforms/Utils/Cloning.h"
-#include "llvm/Transforms/Utils/Local.h"
-#include <memory>
-
-using namespace llvm;
-using namespace llvm::PatternMatch;
-
-#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";
-  }
-
-private:
-  bool prepareCPPEHHandlers(Function &F,
-                            SmallVectorImpl<LandingPadInst *> &LPads);
-  bool outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
-                           LandingPadInst *LPad, StructType *EHDataStructTy);
-};
-
-class WinEHCatchDirector : public CloningDirector {
-public:
-  WinEHCatchDirector(LandingPadInst *LPI, Value *Selector, Value *EHObj)
-      : LPI(LPI), CurrentSelector(Selector->stripPointerCasts()), EHObj(EHObj),
-        SelectorIDType(Type::getInt32Ty(LPI->getContext())),
-        Int8PtrType(Type::getInt8PtrTy(LPI->getContext())) {}
-
-  CloningAction handleInstruction(ValueToValueMapTy &VMap,
-                                  const Instruction *Inst,
-                                  BasicBlock *NewBB) override;
-
-private:
-  LandingPadInst *LPI;
-  Value *CurrentSelector;
-  Value *EHObj;
-  Type *SelectorIDType;
-  Type *Int8PtrType;
-
-  const Value *ExtractedEHPtr;
-  const Value *ExtractedSelector;
-  const Value *EHPtrStoreAddr;
-  const Value *SelectorStoreAddr;
-};
-} // 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: This only returns true if the C++ EH handlers were outlined.
-  //        When that code is complete, it should always return whatever
-  //        prepareCPPEHHandlers returns.
-  if (Pers == EHPersonality::MSVC_CXX && prepareCPPEHHandlers(Fn, LPads))
-    return true;
-
-  // FIXME: SEH 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);
-}
-
-bool WinEHPrepare::prepareCPPEHHandlers(
-    Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
-  // FIXME: Find all frame variable references in the handlers
-  //        to populate the structure elements.
-  SmallVector<Type *, 2> AllocStructTys;
-  AllocStructTys.push_back(Type::getInt32Ty(F.getContext()));   // EH state
-  AllocStructTys.push_back(Type::getInt8PtrTy(F.getContext())); // EH object
-  StructType *EHDataStructTy =
-      StructType::create(F.getContext(), AllocStructTys, 
-                         "struct." + F.getName().str() + ".ehdata");
-  bool HandlersOutlined = false;
-
-  for (LandingPadInst *LPad : LPads) {
-    // Look for evidence that this landingpad has already been processed.
-    bool LPadHasActionList = false;
-    BasicBlock *LPadBB = LPad->getParent();
-    for (Instruction &Inst : LPadBB->getInstList()) {
-      // FIXME: Make this an intrinsic.
-      if (auto *Call = dyn_cast<CallInst>(&Inst))
-        if (Call->getCalledFunction()->getName() == "llvm.eh.actions") {
-          LPadHasActionList = true;
-          break;
-        }
-    }
-
-    // If we've already outlined the handlers for this landingpad,
-    // there's nothing more to do here.
-    if (LPadHasActionList)
-      continue;
-
-    for (unsigned Idx = 0, NumClauses = LPad->getNumClauses(); Idx < NumClauses;
-         ++Idx) {
-      if (LPad->isCatch(Idx))
-        HandlersOutlined =
-            outlineCatchHandler(&F, LPad->getClause(Idx), LPad, EHDataStructTy);
-    } // End for each clause
-  }   // End for each landingpad
-
-  return HandlersOutlined;
-}
-
-bool WinEHPrepare::outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
-                                       LandingPadInst *LPad,
-                                       StructType *EHDataStructTy) {
-  Module *M = SrcFn->getParent();
-  LLVMContext &Context = M->getContext();
-
-  // Create a new function to receive the handler contents.
-  Type *Int8PtrType = Type::getInt8PtrTy(Context);
-  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);
-
-  // 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);
-  Builder.SetInsertPoint(Entry);
-  Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
-
-  // The outlined handler will be called with the parent's frame pointer as
-  // its second argument. To enable the handler to access variables from
-  // the parent frame, we use that pointer to get locate a special block
-  // of memory that was allocated using llvm.eh.allocateframe for this
-  // purpose.  During the outlining process we will determine which frame
-  // variables are used in handlers and create a structure that maps these
-  // variables into the frame allocation block.
-  //
-  // The frame allocation block also contains an exception state variable
-  // used by the runtime and a pointer to the exception object pointer
-  // which will be filled in by the runtime for use in the handler.
-  Function *RecoverFrameFn =
-      Intrinsic::getDeclaration(M, Intrinsic::framerecover);
-  Value *RecoverArgs[] = {Builder.CreateBitCast(SrcFn, Int8PtrType, ""),
-                          &(CatchHandler->getArgumentList().back())};
-  CallInst *EHAlloc =
-      Builder.CreateCall(RecoverFrameFn, RecoverArgs, "eh.alloc");
-  Value *EHData =
-      Builder.CreateBitCast(EHAlloc, EHDataStructTy->getPointerTo(), "ehdata");
-  Value *EHObjPtr =
-      Builder.CreateConstInBoundsGEP2_32(EHData, 0, 1, "eh.obj.ptr");
-
-  // 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");
-
-  ValueToValueMapTy VMap;
-
-  // FIXME: Map other values referenced in the filter handler.
-
-  WinEHCatchDirector Director(LPad, SelectorType, EHObj);
-
-  SmallVector<ReturnInst *, 8> Returns;
-  ClonedCodeInfo InlinedFunctionInfo;
-
-  BasicBlock::iterator II = LPad;
-
-  CloneAndPruneIntoFromInst(CatchHandler, SrcFn, ++II, VMap,
-                            /*ModuleLevelChanges=*/false, Returns, "",
-                            &InlinedFunctionInfo,
-                            SrcFn->getParent()->getDataLayout(), &Director);
-
-  // Move all the instructions in the first cloned block into our entry block.
-  BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
-  Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
-  FirstClonedBB->eraseFromParent();
-
-  return true;
-}
-
-CloningDirector::CloningAction WinEHCatchDirector::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)) {
-    if (Extract->getAggregateOperand() == LPI) {
-      assert(Extract->getNumIndices() == 1 &&
-             "Unexpected operation: extracting both landing pad values");
-      assert((*(Extract->idx_begin()) == 0 || *(Extract->idx_begin()) == 1) &&
-             "Unexpected operation: extracting an unknown landing pad element");
-
-      if (*(Extract->idx_begin()) == 0) {
-        // Element 0 doesn't directly corresponds to anything in the WinEH scheme.
-        // It will be stored to a memory location, then later loaded and finally
-        // the loaded value will be used as the argument to an llvm.eh.begincatch
-        // call.  We're tracking it here so that we can skip the store and load.
-        ExtractedEHPtr = Inst;
-      } else {
-        // Element 1 corresponds to the filter selector.  We'll map it to 1 for
-        // matching purposes, but it will also probably be stored to memory and
-        // reloaded, so we need to track the instuction so that we can map the
-        // loaded value too.
-        VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
-        ExtractedSelector = Inst;
-      }
-
-      // Tell the caller not to clone this instruction.
-      return CloningDirector::SkipInstruction;
-    }
-    // Other extract value instructions just get cloned.
-    return CloningDirector::CloneInstruction;
-  }
-
-  if (auto *Store = dyn_cast<StoreInst>(Inst)) {
-    // Look for and suppress stores of the extracted landingpad values.
-    const Value *StoredValue = Store->getValueOperand();
-    if (StoredValue == ExtractedEHPtr) {
-      EHPtrStoreAddr = Store->getPointerOperand();
-      return CloningDirector::SkipInstruction;
-    }
-    if (StoredValue == ExtractedSelector) {
-      SelectorStoreAddr = Store->getPointerOperand();
-      return CloningDirector::SkipInstruction;
-    }
-
-    // Any other store just gets cloned.
-    return CloningDirector::CloneInstruction;
-  }
-
-  if (auto *Load = dyn_cast<LoadInst>(Inst)) {
-    // Look for loads of (previously suppressed) landingpad values.
-    // The EHPtr load can be ignored (it should only be used as
-    // an argument to llvm.eh.begincatch), but the selector value
-    // needs to be mapped to a constant value of 1 to be used to
-    // simplify the branching to always flow to the current handler.
-    const Value *LoadAddr = Load->getPointerOperand();
-    if (LoadAddr == EHPtrStoreAddr) {
-      VMap[Inst] = UndefValue::get(Int8PtrType);
-      return CloningDirector::SkipInstruction;
-    }
-    if (LoadAddr == SelectorStoreAddr) {
-      VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
-      return CloningDirector::SkipInstruction;
-    }
-
-    // Any other loads just get cloned.
-    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 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;
-  }
-
-  // Continue with the default cloning behavior.
-  return CloningDirector::CloneInstruction;
-}
+//===-- 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/ADT/MapVector.h"\r
+#include "llvm/ADT/TinyPtrVector.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
+\r
+struct HandlerAllocas {\r
+  TinyPtrVector<AllocaInst *> Allocas;\r
+  int ParentFrameAllocationIndex;\r
+};\r
+\r
+// This map is used to model frame variable usage during outlining, to\r
+// construct a structure type to hold the frame variables in a frame\r
+// allocation block, and to remap the frame variable allocas (including\r
+// spill locations as needed) to GEPs that get the variable from the\r
+// frame allocation structure.\r
+typedef MapVector<AllocaInst *, HandlerAllocas> FrameVarInfoMap;\r
+\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, CallInst *&EHAlloc,\r
+                           AllocaInst *&EHObjPtr, FrameVarInfoMap &VarInfo);\r
+};\r
+\r
+class WinEHFrameVariableMaterializer : public ValueMaterializer {\r
+public:\r
+  WinEHFrameVariableMaterializer(Function *OutlinedFn,\r
+                                 FrameVarInfoMap &FrameVarInfo);\r
+  ~WinEHFrameVariableMaterializer() {}\r
+\r
+  virtual Value *materializeValueFor(Value *V) override;\r
+\r
+private:\r
+  Function *OutlinedFn;\r
+  FrameVarInfoMap &FrameVarInfo;\r
+  IRBuilder<> Builder;\r
+};\r
+\r
+class WinEHCatchDirector : public CloningDirector {\r
+public:\r
+  WinEHCatchDirector(LandingPadInst *LPI, Function *CatchFn, Value *Selector,\r
+                     Value *EHObj, FrameVarInfoMap &VarInfo)\r
+      : LPI(LPI), CurrentSelector(Selector->stripPointerCasts()), EHObj(EHObj),\r
+        Materializer(CatchFn, VarInfo),\r
+        SelectorIDType(Type::getInt32Ty(LPI->getContext())),\r
+        Int8PtrType(Type::getInt8PtrTy(LPI->getContext())) {}\r
+\r
+  CloningAction handleInstruction(ValueToValueMapTy &VMap,\r
+                                  const Instruction *Inst,\r
+                                  BasicBlock *NewBB) override;\r
+\r
+  ValueMaterializer *getValueMaterializer() override { return &Materializer; }\r
+\r
+private:\r
+  LandingPadInst *LPI;\r
+  Value *CurrentSelector;\r
+  Value *EHObj;\r
+  WinEHFrameVariableMaterializer Materializer;\r
+  Type *SelectorIDType;\r
+  Type *Int8PtrType;\r
+\r
+  const Value *ExtractedEHPtr;\r
+  const Value *ExtractedSelector;\r
+  const Value *EHPtrStoreAddr;\r
+  const Value *SelectorStoreAddr;\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
+  // These containers are used to re-map frame variables that are used in\r
+  // outlined catch and cleanup handlers.  They will be populated as the\r
+  // handlers are outlined.\r
+  FrameVarInfoMap FrameVarInfo;\r
+  SmallVector<CallInst *, 4> HandlerAllocs;\r
+  SmallVector<AllocaInst *, 4> HandlerEHObjPtrs;\r
+\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
+        // Create a new instance of the handler data structure in the\r
+        // HandlerData vector.\r
+        CallInst *EHAlloc = nullptr;\r
+        AllocaInst *EHObjPtr = nullptr;\r
+        bool Outlined = outlineCatchHandler(&F, LPad->getClause(Idx), LPad,\r
+                                            EHAlloc, EHObjPtr, FrameVarInfo);\r
+        if (Outlined) {\r
+          HandlersOutlined = true;\r
+          // These values must be resolved after all handlers have been\r
+          // outlined.\r
+          if (EHAlloc)\r
+            HandlerAllocs.push_back(EHAlloc);\r
+          if (EHObjPtr)\r
+            HandlerEHObjPtrs.push_back(EHObjPtr);\r
+        }\r
+      } // End if (isCatch)\r
+    }   // End for each clause\r
+  }     // End for each landingpad\r
+\r
+  // If nothing got outlined, there is no more processing to be done.\r
+  if (!HandlersOutlined)\r
+    return false;\r
+\r
+  // FIXME: We will replace the landingpad bodies with llvm.eh.actions\r
+  //        calls and indirect branches here and then delete blocks\r
+  //        which are no longer reachable.  That will get rid of the\r
+  //        handlers that we have outlined.  There is code below\r
+  //        that looks for allocas with no uses in the parent function.\r
+  //        That will only happen after the pruning is implemented.\r
+\r
+  // Remap the frame variables.\r
+  SmallVector<Type *, 2> StructTys;\r
+  StructTys.push_back(Type::getInt32Ty(F.getContext()));   // EH state\r
+  StructTys.push_back(Type::getInt8PtrTy(F.getContext())); // EH object\r
+\r
+  // Start the index at two since we always have the above fields at 0 and 1.\r
+  int Idx = 2;\r
+\r
+  // FIXME: Sort the FrameVarInfo vector by the ParentAlloca size and alignment\r
+  //        and add padding as necessary to provide the proper alignment.\r
+\r
+  // Map the alloca instructions to the corresponding index in the\r
+  // frame allocation structure.  If any alloca is used only in a single\r
+  // handler and is not used in the parent frame after outlining, it will\r
+  // be assigned an index of -1, meaning the handler can keep its\r
+  // "temporary" alloca and the original alloca can be erased from the\r
+  // parent function.  If we later encounter this alloca in a second\r
+  // handler, we will assign it a place in the frame allocation structure\r
+  // at that time.  Since the instruction replacement doesn't happen until\r
+  // all the entries in the HandlerData have been processed this isn't a\r
+  // problem.\r
+  for (auto &VarInfoEntry : FrameVarInfo) {\r
+    AllocaInst *ParentAlloca = VarInfoEntry.first;\r
+    HandlerAllocas &AllocaInfo = VarInfoEntry.second;\r
+\r
+    // If the instruction still has uses in the parent function or if it is\r
+    // referenced by more than one handler, add it to the frame allocation\r
+    // structure.\r
+    if (ParentAlloca->getNumUses() != 0 || AllocaInfo.Allocas.size() > 1) {\r
+      Type *VarTy = ParentAlloca->getAllocatedType();\r
+      StructTys.push_back(VarTy);\r
+      AllocaInfo.ParentFrameAllocationIndex = Idx++;\r
+    } else {\r
+      // If the variable is not used in the parent frame and it is only used\r
+      // in one handler, the alloca can be removed from the parent frame\r
+      // and the handler will keep its "temporary" alloca to define the value.\r
+      // An element index of -1 is used to indicate this condition.\r
+      AllocaInfo.ParentFrameAllocationIndex = -1;\r
+    }\r
+  }\r
+\r
+  // Having filled the StructTys vector and assigned an index to each element,\r
+  // we can now create the structure.\r
+  StructType *EHDataStructTy = StructType::create(\r
+      F.getContext(), StructTys, "struct." + F.getName().str() + ".ehdata");\r
+  IRBuilder<> Builder(F.getParent()->getContext());\r
+\r
+  // Create a frame allocation.\r
+  Module *M = F.getParent();\r
+  LLVMContext &Context = M->getContext();\r
+  BasicBlock *Entry = &F.getEntryBlock();\r
+  Builder.SetInsertPoint(Entry->getFirstInsertionPt());\r
+  Function *FrameAllocFn =\r
+      Intrinsic::getDeclaration(M, Intrinsic::frameallocate);\r
+  uint64_t EHAllocSize = M->getDataLayout()->getTypeAllocSize(EHDataStructTy);\r
+  Value *FrameAllocArgs[] = {\r
+      ConstantInt::get(Type::getInt32Ty(Context), EHAllocSize)};\r
+  CallInst *FrameAlloc =\r
+      Builder.CreateCall(FrameAllocFn, FrameAllocArgs, "frame.alloc");\r
+\r
+  Value *FrameEHData = Builder.CreateBitCast(\r
+      FrameAlloc, EHDataStructTy->getPointerTo(), "eh.data");\r
+\r
+  // Now visit each handler that is using the structure and bitcast its EHAlloc\r
+  // value to be a pointer to the frame alloc structure.\r
+  DenseMap<Function *, Value *> EHDataMap;\r
+  for (CallInst *EHAlloc : HandlerAllocs) {\r
+    // The EHAlloc has no uses at this time, so we need to just insert the\r
+    // cast before the next instruction. There is always a next instruction.\r
+    BasicBlock::iterator II = EHAlloc;\r
+    ++II;\r
+    Builder.SetInsertPoint(cast<Instruction>(II));\r
+    Value *EHData = Builder.CreateBitCast(\r
+        EHAlloc, EHDataStructTy->getPointerTo(), "eh.data");\r
+    EHDataMap[EHAlloc->getParent()->getParent()] = EHData;\r
+  }\r
+\r
+  // Next, replace the place-holder EHObjPtr allocas with GEP instructions\r
+  // that pull the EHObjPtr from the frame alloc structure\r
+  for (AllocaInst *EHObjPtr : HandlerEHObjPtrs) {\r
+    Value *EHData = EHDataMap[EHObjPtr->getParent()->getParent()];\r
+    Value *ElementPtr = Builder.CreateConstInBoundsGEP2_32(EHData, 0, 1);\r
+    EHObjPtr->replaceAllUsesWith(ElementPtr);\r
+    EHObjPtr->removeFromParent();\r
+    ElementPtr->takeName(EHObjPtr);\r
+    delete EHObjPtr;\r
+  }\r
+\r
+  // Finally, replace all of the temporary allocas for frame variables used in\r
+  // the outlined handlers and the original frame allocas with GEP instructions\r
+  // that get the equivalent pointer from the frame allocation struct.\r
+  for (auto &VarInfoEntry : FrameVarInfo) {\r
+    AllocaInst *ParentAlloca = VarInfoEntry.first;\r
+    HandlerAllocas &AllocaInfo = VarInfoEntry.second;\r
+    int Idx = AllocaInfo.ParentFrameAllocationIndex;\r
+\r
+    // If we have an index of -1 for this instruction, it means it isn't used\r
+    // outside of this handler.  In that case, we just keep the "temporary"\r
+    // alloca in the handler and erase the original alloca from the parent.\r
+    if (Idx == -1) {\r
+      ParentAlloca->eraseFromParent();\r
+    } else {\r
+      // Otherwise, we replace the parent alloca and all outlined allocas\r
+      // which map to it with GEP instructions.\r
+\r
+      // First replace the original alloca.\r
+      Builder.SetInsertPoint(ParentAlloca);\r
+      Builder.SetCurrentDebugLocation(ParentAlloca->getDebugLoc());\r
+      Value *ElementPtr =\r
+          Builder.CreateConstInBoundsGEP2_32(FrameEHData, 0, Idx);\r
+      ParentAlloca->replaceAllUsesWith(ElementPtr);\r
+      ParentAlloca->removeFromParent();\r
+      ElementPtr->takeName(ParentAlloca);\r
+      delete ParentAlloca;\r
+\r
+      // Next replace all outlined allocas that are mapped to it.\r
+      for (AllocaInst *TempAlloca : AllocaInfo.Allocas) {\r
+        Value *EHData = EHDataMap[TempAlloca->getParent()->getParent()];\r
+        // FIXME: Sink this GEP into the blocks where it is used.\r
+        Builder.SetInsertPoint(TempAlloca);\r
+        Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());\r
+        ElementPtr = Builder.CreateConstInBoundsGEP2_32(EHData, 0, Idx);\r
+        TempAlloca->replaceAllUsesWith(ElementPtr);\r
+        TempAlloca->removeFromParent();\r
+        ElementPtr->takeName(TempAlloca);\r
+        delete TempAlloca;\r
+      }\r
+    } // end else of if (Idx == -1)\r
+  }   // End for each FrameVarInfo entry.\r
+\r
+  return HandlersOutlined;\r
+}\r
+\r
+bool WinEHPrepare::outlineCatchHandler(Function *SrcFn, Constant *SelectorType,\r
+                                       LandingPadInst *LPad, CallInst *&EHAlloc,\r
+                                       AllocaInst *&EHObjPtr,\r
+                                       FrameVarInfoMap &VarInfo) {\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
+  EHAlloc = Builder.CreateCall(RecoverFrameFn, RecoverArgs, "eh.alloc");\r
+\r
+  // This alloca is only temporary.  We'll be replacing it once we know all the\r
+  // frame variables that need to go in the frame allocation structure.\r
+  EHObjPtr = Builder.CreateAlloca(Int8PtrType, 0, "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, VarInfo);\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\r
+        // 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\r
+        // 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
+\r
+WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(\r
+    Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)\r
+    : OutlinedFn(OutlinedFn), FrameVarInfo(FrameVarInfo),\r
+      Builder(OutlinedFn->getContext()) {\r
+  Builder.SetInsertPoint(&OutlinedFn->getEntryBlock());\r
+  // FIXME: Do something with the FrameVarMapped so that it is shared across the\r
+  // function.\r
+}\r
+\r
+Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {\r
+  // If we're asked to materialize an alloca variable, we temporarily\r
+  // create a matching alloca in the outlined function.  When all the\r
+  // outlining is complete, we'll collect these into a structure and\r
+  // replace these temporary allocas with GEPs referencing the frame\r
+  // allocation block.\r
+  if (auto *AV = dyn_cast<AllocaInst>(V)) {\r
+    AllocaInst *NewAlloca = Builder.CreateAlloca(\r
+        AV->getAllocatedType(), AV->getArraySize(), AV->getName());\r
+    FrameVarInfo[AV].Allocas.push_back(NewAlloca);\r
+    return NewAlloca;\r
+  }\r
+\r
+// FIXME: Do PHI nodes need special handling?\r
+\r
+// FIXME: Are there other cases we can handle better?  GEP, ExtractValue, etc.\r
+\r
+// FIXME: This doesn't work during cloning because it finds an instruction\r
+//        in the use list that isn't yet part of a basic block.\r
+#if 0\r
+  // If we're asked to remap some other instruction, we'll need to\r
+  // spill it to an alloca variable in the parent function and add a\r
+  // temporary alloca in the outlined function to be processed as\r
+  // described above.\r
+  Instruction *Inst = dyn_cast<Instruction>(V);\r
+  if (Inst) {\r
+    AllocaInst *Spill = DemoteRegToStack(*Inst, true);\r
+    AllocaInst *NewAlloca = Builder.CreateAlloca(Spill->getAllocatedType(),\r
+                                                 Spill->getArraySize());\r
+    FrameVarMap[AV] = NewAlloca;\r
+    return NewAlloca;\r
+  }\r
+#endif\r
+\r
+  return nullptr;\r
+}\r
index 40061abba8528406f084f6cc88700316545e345d..09279b6d5066f4fc3e22c4a848df24cd12631cd5 100644 (file)
@@ -261,6 +261,8 @@ namespace {
     ClonedCodeInfo *CodeInfo;
     const DataLayout *DL;
     CloningDirector *Director;
+    ValueMapTypeRemapper *TypeMapper;
+    ValueMaterializer *Materializer;
 
   public:
     PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
@@ -274,6 +276,14 @@ namespace {
       VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
       NameSuffix(nameSuffix), CodeInfo(codeInfo), DL(DL),
       Director(Director) {
+      // These are optional components.  The Director may return null.
+      if (Director) {
+        TypeMapper = Director->getTypeRemapper();
+        Materializer = Director->getValueMaterializer();
+      } else {
+        TypeMapper = nullptr;
+        Materializer = nullptr;
+      }
     }
 
     /// CloneBlock - The specified block is found to be reachable, clone it and
@@ -344,7 +354,8 @@ void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
     // nodes for which we defer processing until we update the CFG.
     if (!isa<PHINode>(NewInst)) {
       RemapInstruction(NewInst, VMap,
-                       ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
+                       ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
+                       TypeMapper, Materializer);
 
       // If we can simplify this instruction to some other value, simply add
       // a mapping to that value rather than inserting a new instruction into
@@ -459,6 +470,14 @@ void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
                                      CloningDirector *Director) {
   assert(NameSuffix && "NameSuffix cannot be null!");
 
+  ValueMapTypeRemapper *TypeMapper = nullptr;
+  ValueMaterializer *Materializer = nullptr;
+
+  if (Director) {
+    TypeMapper = Director->getTypeRemapper();
+    Materializer = Director->getValueMaterializer();
+  }
+
 #ifndef NDEBUG
   // If the cloning starts at the begining of the function, verify that
   // the function arguments are mapped.
@@ -513,7 +532,8 @@ void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
     // Finally, remap the terminator instructions, as those can't be remapped
     // until all BBs are mapped.
     RemapInstruction(NewBB->getTerminator(), VMap,
-                     ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges);
+                     ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
+                     TypeMapper, Materializer);
   }
   
   // Defer PHI resolution until rest of function is resolved, PHI resolution
index fd8c2f85885e26e8de055dc49f20541165e4faa8..9d3373cebf5830b11d350f6b65ade83203086d80 100644 (file)
@@ -1,83 +1,83 @@
-; RUN: opt -mtriple=x86_64-pc-windows-msvc -winehprepare -S -o - < %s | FileCheck %s
-
-; This test is based on the following code:
-;
-; void test()
-; {
-;   try {
-;     may_throw();
-;   } catch (...) {
-;     handle_exception();
-;   }
-; }
-;
-; Parts of the IR have been hand-edited to simplify the test case.
-; The full IR will be restored when Windows C++ EH support is complete.
-
-; ModuleID = 'catch-all.cpp'
-target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
-target triple = "x86_64-pc-windows-msvc"
-
-; Function Attrs: uwtable
-define void @_Z4testv() #0 {
-entry:
-  %exn.slot = alloca i8*
-  %ehselector.slot = alloca i32
-  invoke void @_Z9may_throwv()
-          to label %invoke.cont unwind label %lpad
-
-invoke.cont:                                      ; preds = %entry
-  br label %try.cont
-
-lpad:                                             ; preds = %entry
-  %0 = landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*)
-          catch i8* null
-  %1 = extractvalue { i8*, i32 } %0, 0
-  store i8* %1, i8** %exn.slot
-  %2 = extractvalue { i8*, i32 } %0, 1
-  store i32 %2, i32* %ehselector.slot
-  br label %catch
-
-catch:                                            ; preds = %lpad
-  %exn = load i8** %exn.slot
-  %3 = call i8* @llvm.eh.begincatch(i8* %exn) #3
-  call void @_Z16handle_exceptionv()
-  br label %invoke.cont2
-
-invoke.cont2:                                     ; preds = %catch
-  call void @llvm.eh.endcatch()
-  br label %try.cont
-
-try.cont:                                         ; preds = %invoke.cont2, %invoke.cont
-  ret void
-}
-
-; CHECK: define i8* @_Z4testv.catch(i8*, i8*) {
-; CHECK: catch.entry:
-; CHECK:   %eh.alloc = call i8* @llvm.framerecover(i8* bitcast (void ()* @_Z4testv to i8*), i8* %1)
-; CHECK:   %ehdata = bitcast i8* %eh.alloc to %struct._Z4testv.ehdata*
-; CHECK:   %eh.obj.ptr = getelementptr inbounds %struct._Z4testv.ehdata* %ehdata, i32 0, i32 1
-; CHECK:   %eh.obj = load i8** %eh.obj.ptr
-; CHECK:   call void @_Z16handle_exceptionv()
-; CHECK:   ret i8* blockaddress(@_Z4testv, %try.cont)
-; CHECK: }
-
-declare void @_Z9may_throwv() #1
-
-declare i32 @__CxxFrameHandler3(...)
-
-declare i8* @llvm.eh.begincatch(i8*)
-
-declare void @_Z16handle_exceptionv() #1
-
-declare void @llvm.eh.endcatch()
-
-attributes #0 = { uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }
-attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }
-attributes #2 = { noinline noreturn nounwind }
-attributes #3 = { nounwind }
-attributes #4 = { noreturn nounwind }
-
-!llvm.ident = !{!0}
-
-!0 = !{!"clang version 3.7.0 (trunk 226027)"}
+; RUN: opt -mtriple=x86_64-pc-windows-msvc -winehprepare -S -o - < %s | FileCheck %s\r
+\r
+; This test is based on the following code:\r
+;\r
+; void test()\r
+; {\r
+;   try {\r
+;     may_throw();\r
+;   } catch (...) {\r
+;     handle_exception();\r
+;   }\r
+; }\r
+;\r
+; Parts of the IR have been hand-edited to simplify the test case.\r
+; The full IR will be restored when Windows C++ EH support is complete.\r
+\r
+; ModuleID = 'catch-all.cpp'\r
+target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"\r
+target triple = "x86_64-pc-windows-msvc"\r
+\r
+; Function Attrs: uwtable\r
+define void @_Z4testv() #0 {\r
+entry:\r
+  %exn.slot = alloca i8*\r
+  %ehselector.slot = alloca i32\r
+  invoke void @_Z9may_throwv()\r
+          to label %invoke.cont unwind label %lpad\r
+\r
+invoke.cont:                                      ; preds = %entry\r
+  br label %try.cont\r
+\r
+lpad:                                             ; preds = %entry\r
+  %0 = landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*)\r
+          catch i8* null\r
+  %1 = extractvalue { i8*, i32 } %0, 0\r
+  store i8* %1, i8** %exn.slot\r
+  %2 = extractvalue { i8*, i32 } %0, 1\r
+  store i32 %2, i32* %ehselector.slot\r
+  br label %catch\r
+\r
+catch:                                            ; preds = %lpad\r
+  %exn = load i8** %exn.slot\r
+  %3 = call i8* @llvm.eh.begincatch(i8* %exn) #3\r
+  call void @_Z16handle_exceptionv()\r
+  br label %invoke.cont2\r
+\r
+invoke.cont2:                                     ; preds = %catch\r
+  call void @llvm.eh.endcatch()\r
+  br label %try.cont\r
+\r
+try.cont:                                         ; preds = %invoke.cont2, %invoke.cont\r
+  ret void\r
+}\r
+\r
+; CHECK: define i8* @_Z4testv.catch(i8*, i8*) {\r
+; CHECK: catch.entry:\r
+; CHECK:   %eh.alloc = call i8* @llvm.framerecover(i8* bitcast (void ()* @_Z4testv to i8*), i8* %1)\r
+; CHECK:   %eh.data = bitcast i8* %eh.alloc to %struct._Z4testv.ehdata*\r
+; CHECK:   %eh.obj.ptr = getelementptr inbounds %struct._Z4testv.ehdata* %eh.data, i32 0, i32 1\r
+; CHECK:   %eh.obj = load i8** %eh.obj.ptr\r
+; CHECK:   call void @_Z16handle_exceptionv()\r
+; CHECK:   ret i8* blockaddress(@_Z4testv, %try.cont)\r
+; CHECK: }\r
+\r
+declare void @_Z9may_throwv() #1\r
+\r
+declare i32 @__CxxFrameHandler3(...)\r
+\r
+declare i8* @llvm.eh.begincatch(i8*)\r
+\r
+declare void @_Z16handle_exceptionv() #1\r
+\r
+declare void @llvm.eh.endcatch()\r
+\r
+attributes #0 = { uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }\r
+attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }\r
+attributes #2 = { noinline noreturn nounwind }\r
+attributes #3 = { nounwind }\r
+attributes #4 = { noreturn nounwind }\r
+\r
+!llvm.ident = !{!0}\r
+\r
+!0 = !{!"clang version 3.7.0 (trunk 226027)"}\r
index 6685a5dd6f7ec4bb7a8c4294616d5edadd819391..a35e3faebadd7e36f150ba4b9b1318a927d592c4 100644 (file)
-; RUN: opt -mtriple=x86_64-pc-windows-msvc -winehprepare -S -o - < %s | FileCheck %s
-
-; This test is based on the following code:
-;
-; void test()
-; {
-;   try {
-;     may_throw();
-;   } catch (int) {
-;     handle_int();
-;   }
-; }
-;
-; Parts of the IR have been hand-edited to simplify the test case.
-; The full IR will be restored when Windows C++ EH support is complete.
-
-;ModuleID = 'cppeh-catch-scalar.cpp'
-target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
-target triple = "x86_64-pc-windows-msvc"
-
-@_ZTIi = external constant i8*
-
-; Function Attrs: uwtable
-define void @_Z4testv() #0 {
-entry:
-  %exn.slot = alloca i8*
-  %ehselector.slot = alloca i32
-  invoke void @_Z9may_throwv()
-          to label %invoke.cont unwind label %lpad
-
-invoke.cont:                                      ; preds = %entry
-  br label %try.cont
-
-lpad:                                             ; preds = %entry
-  %0 = landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*)
-          catch i8* bitcast (i8** @_ZTIi to i8*)
-  %1 = extractvalue { i8*, i32 } %0, 0
-  store i8* %1, i8** %exn.slot
-  %2 = extractvalue { i8*, i32 } %0, 1
-  store i32 %2, i32* %ehselector.slot
-  br label %catch.dispatch
-
-catch.dispatch:                                   ; preds = %lpad
-  %sel = load i32* %ehselector.slot
-  %3 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIi to i8*)) #3
-  %matches = icmp eq i32 %sel, %3
-  br i1 %matches, label %catch, label %eh.resume
-
-catch:                                            ; preds = %catch.dispatch
-  %exn11 = load i8** %exn.slot
-  %4 = call i8* @llvm.eh.begincatch(i8* %exn11) #3
-  %5 = bitcast i8* %4 to i32*
-  call void @_Z10handle_intv()
-  br label %invoke.cont2
-
-invoke.cont2:                                     ; preds = %catch
-  call void @llvm.eh.endcatch() #3
-  br label %try.cont
-
-try.cont:                                         ; preds = %invoke.cont2, %invoke.cont
-  ret void
-
-eh.resume:                                        ; preds = %catch.dispatch
-  %exn3 = load i8** %exn.slot
-  %sel4 = load i32* %ehselector.slot
-  %lpad.val = insertvalue { i8*, i32 } undef, i8* %exn3, 0
-  %lpad.val5 = insertvalue { i8*, i32 } %lpad.val, i32 %sel4, 1
-  resume { i8*, i32 } %lpad.val5
-}
-
-; CHECK: define i8* @_Z4testv.catch(i8*, i8*) {
-; CHECK: catch.entry:
-; CHECK:   %eh.alloc = call i8* @llvm.framerecover(i8* bitcast (void ()* @_Z4testv to i8*), i8* %1)
-; CHECK:   %ehdata = bitcast i8* %eh.alloc to %struct._Z4testv.ehdata*
-; CHECK:   %eh.obj.ptr = getelementptr inbounds %struct._Z4testv.ehdata* %ehdata, i32 0, i32 1
-; CHECK:   %eh.obj = load i8** %eh.obj.ptr
-; CHECK:   %2 = bitcast i8* %eh.obj to i32*
-; CHECK:   call void @_Z10handle_intv()
-; CHECK:   ret i8* blockaddress(@_Z4testv, %try.cont)
-; CHECK: }
-
-declare void @_Z9may_throwv() #1
-
-declare i32 @__CxxFrameHandler3(...)
-
-; Function Attrs: nounwind readnone
-declare i32 @llvm.eh.typeid.for(i8*) #2
-
-declare i8* @llvm.eh.begincatch(i8*)
-
-declare void @llvm.eh.endcatch()
-
-declare void @_Z10handle_intv() #1
-
-attributes #0 = { uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }
-attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }
-attributes #2 = { nounwind readnone }
-attributes #3 = { nounwind }
-
-!llvm.ident = !{!0}
-
-!0 = !{!"clang version 3.7.0 (trunk 227474) (llvm/trunk 227508)"}
+; RUN: opt -mtriple=x86_64-pc-windows-msvc -winehprepare -S -o - < %s | FileCheck %s\r
+\r
+; This test is based on the following code:\r
+;\r
+; void test()\r
+; {\r
+;   try {\r
+;     may_throw();\r
+;   } catch (int i) {\r
+;     handle_int(i);\r
+;   }\r
+; }\r
+;\r
+; Parts of the IR have been hand-edited to simplify the test case.\r
+; The full IR will be restored when Windows C++ EH support is complete.\r
+\r
+;ModuleID = 'cppeh-catch-scalar.cpp'\r
+target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"\r
+target triple = "x86_64-pc-windows-msvc"\r
+\r
+; This is the structure that will get created for the frame allocation.\r
+; CHECK: %struct._Z4testv.ehdata = type { i32, i8*, i32 }\r
+\r
+@_ZTIi = external constant i8*\r
+\r
+; The function entry will be rewritten like this.\r
+; CHECK: define void @_Z4testv() #0 {\r
+; CHECK: entry:\r
+; CHECK:   %frame.alloc = call i8* @llvm.frameallocate(i32 24)\r
+; CHECK:   %eh.data = bitcast i8* %frame.alloc to %struct._Z4testv.ehdata*\r
+; CHECK:   %exn.slot = alloca i8*\r
+; CHECK:   %ehselector.slot = alloca i32\r
+; CHECK-NOT:  %i = alloca i32, align 4\r
+; CHECK:  %i = getelementptr inbounds %struct._Z4testv.ehdata* %eh.data, i32 0, i32 2\r
+\r
+; Function Attrs: uwtable\r
+define void @_Z4testv() #0 {\r
+entry:\r
+  %exn.slot = alloca i8*\r
+  %ehselector.slot = alloca i32\r
+  %i = alloca i32, align 4\r
+  invoke void @_Z9may_throwv()\r
+          to label %invoke.cont unwind label %lpad\r
+\r
+invoke.cont:                                      ; preds = %entry\r
+  br label %try.cont\r
+\r
+lpad:                                             ; preds = %entry\r
+  %0 = landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*)\r
+          catch i8* bitcast (i8** @_ZTIi to i8*)\r
+  %1 = extractvalue { i8*, i32 } %0, 0\r
+  store i8* %1, i8** %exn.slot\r
+  %2 = extractvalue { i8*, i32 } %0, 1\r
+  store i32 %2, i32* %ehselector.slot\r
+  br label %catch.dispatch\r
+\r
+catch.dispatch:                                   ; preds = %lpad\r
+  %sel = load i32* %ehselector.slot\r
+  %3 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIi to i8*)) #3\r
+  %matches = icmp eq i32 %sel, %3\r
+  br i1 %matches, label %catch, label %eh.resume\r
+\r
+catch:                                            ; preds = %catch.dispatch\r
+  %exn11 = load i8** %exn.slot\r
+  %4 = call i8* @llvm.eh.begincatch(i8* %exn11) #3\r
+  %5 = bitcast i8* %4 to i32*\r
+  %6 = load i32* %5, align 4\r
+  store i32 %6, i32* %i, align 4\r
+  %7 = load i32* %i, align 4\r
+  call void @_Z10handle_inti(i32 %7)\r
+  br label %invoke.cont2\r
+\r
+invoke.cont2:                                     ; preds = %catch\r
+  call void @llvm.eh.endcatch() #3\r
+  br label %try.cont\r
+\r
+try.cont:                                         ; preds = %invoke.cont2, %invoke.cont\r
+  ret void\r
+\r
+eh.resume:                                        ; preds = %catch.dispatch\r
+  %exn3 = load i8** %exn.slot\r
+  %sel4 = load i32* %ehselector.slot\r
+  %lpad.val = insertvalue { i8*, i32 } undef, i8* %exn3, 0\r
+  %lpad.val5 = insertvalue { i8*, i32 } %lpad.val, i32 %sel4, 1\r
+  resume { i8*, i32 } %lpad.val5\r
+}\r
+\r
+; CHECK: define i8* @_Z4testv.catch(i8*, i8*) {\r
+; CHECK: catch.entry:\r
+; CHECK:   %eh.alloc = call i8* @llvm.framerecover(i8* bitcast (void ()* @_Z4testv to i8*), i8* %1)\r
+; CHECK:   %eh.data = bitcast i8* %eh.alloc to %struct._Z4testv.ehdata*\r
+; CHECK:   %eh.obj.ptr = getelementptr inbounds %struct._Z4testv.ehdata* %eh.data, i32 0, i32 1\r
+; CHECK:   %eh.obj = load i8** %eh.obj.ptr\r
+; CHECK:   %i = getelementptr inbounds %struct._Z4testv.ehdata* %eh.data, i32 0, i32 2\r
+; CHECK:   %2 = bitcast i8* %eh.obj to i32*\r
+; CHECK:   %3 = load i32* %2, align 4\r
+; CHECK:   store i32 %3, i32* %i, align 4\r
+; CHECK:   %4 = load i32* %i, align 4\r
+; CHECK:   call void @_Z10handle_inti(i32 %4)\r
+; CHECK:   ret i8* blockaddress(@_Z4testv, %try.cont)\r
+; CHECK: }\r
+\r
+declare void @_Z9may_throwv() #1\r
+\r
+declare i32 @__CxxFrameHandler3(...)\r
+\r
+; Function Attrs: nounwind readnone\r
+declare i32 @llvm.eh.typeid.for(i8*) #2\r
+\r
+declare i8* @llvm.eh.begincatch(i8*)\r
+\r
+declare void @llvm.eh.endcatch()\r
+\r
+declare void @_Z10handle_inti(i32) #1\r
+\r
+attributes #0 = { uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }\r
+attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }\r
+attributes #2 = { nounwind readnone }\r
+attributes #3 = { nounwind }\r
+\r
+!llvm.ident = !{!0}\r
+\r
+!0 = !{!"clang version 3.7.0 (trunk 227474) (llvm/trunk 227508)"}\r