[WinEH] C++ EH state numbering fixes
[oota-llvm.git] / lib / CodeGen / WinEHPrepare.cpp
index e4e63fddebb883ae7fd4c407b156859b4e882d97..8f67d21a47d9141f0943d7655e581a31428b0aef 100644 (file)
@@ -91,6 +91,7 @@ public:
 private:
   bool prepareExceptionHandlers(Function &F,
                                 SmallVectorImpl<LandingPadInst *> &LPads);
+  void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
   void promoteLandingPadValues(LandingPadInst *LPad);
   void demoteValuesLiveAcrossHandlers(Function &F,
                                       SmallVectorImpl<LandingPadInst *> &LPads);
@@ -127,6 +128,9 @@ private:
   CatchHandlerMapTy CatchHandlerMap;
   CleanupHandlerMapTy CleanupHandlerMap;
   DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
+  SmallPtrSet<BasicBlock *, 4> NormalBlocks;
+  SmallPtrSet<BasicBlock *, 4> EHBlocks;
+  SetVector<BasicBlock *> EHReturnBlocks;
 
   // This maps landing pad instructions found in outlined handlers to
   // the landing pad instruction in the parent function from which they
@@ -214,6 +218,9 @@ public:
   virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
                                         const Instruction *Inst,
                                         BasicBlock *NewBB) = 0;
+  virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
+                                         const IndirectBrInst *IBr,
+                                         BasicBlock *NewBB) = 0;
   virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
                                      const InvokeInst *Invoke,
                                      BasicBlock *NewBB) = 0;
@@ -244,10 +251,12 @@ public:
   WinEHCatchDirector(
       Function *CatchFn, Value *ParentFP, Value *Selector,
       FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
-      DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
+      DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
+      DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
       : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
         CurrentSelector(Selector->stripPointerCasts()),
-        ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
+        ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
+        DT(DT), EHBlocks(EHBlocks) {}
 
   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
                                  const Instruction *Inst,
@@ -257,6 +266,9 @@ public:
   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
                                 const Instruction *Inst,
                                 BasicBlock *NewBB) override;
+  CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
+                                 const IndirectBrInst *IBr,
+                                 BasicBlock *NewBB) override;
   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
                              BasicBlock *NewBB) override;
   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
@@ -279,6 +291,8 @@ private:
   // This will be a reference to the field of the same name in the WinEHPrepare
   // object which instantiates this WinEHCatchDirector object.
   DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
+  DominatorTree *DT;
+  SmallPtrSetImpl<BasicBlock *> &EHBlocks;
 };
 
 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
@@ -296,6 +310,9 @@ public:
   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
                                 const Instruction *Inst,
                                 BasicBlock *NewBB) override;
+  CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
+                                 const IndirectBrInst *IBr,
+                                 BasicBlock *NewBB) override;
   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
                              BasicBlock *NewBB) override;
   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
@@ -525,13 +542,8 @@ void WinEHPrepare::findSEHEHReturnPoints(
   }
 }
 
-/// Ensure that all values live into and out of exception handlers are stored
-/// in memory.
-/// FIXME: This falls down when values are defined in one handler and live into
-/// another handler. For example, a cleanup defines a value used only by a
-/// catch handler.
-void WinEHPrepare::demoteValuesLiveAcrossHandlers(
-    Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
+void WinEHPrepare::identifyEHBlocks(Function &F, 
+                                    SmallVectorImpl<LandingPadInst *> &LPads) {
   DEBUG(dbgs() << "Demoting values live across exception handlers in function "
                << F.getName() << '\n');
 
@@ -541,10 +553,6 @@ void WinEHPrepare::demoteValuesLiveAcrossHandlers(
   // - Exceptional blocks are blocks reachable from landingpads. Analysis does
   //   not follow llvm.eh.endcatch blocks, which mark a transition from
   //   exceptional to normal control.
-  SmallPtrSet<BasicBlock *, 4> NormalBlocks;
-  SmallPtrSet<BasicBlock *, 4> EHBlocks;
-  SetVector<BasicBlock *> EHReturnBlocks;
-  SetVector<BasicBlock *> Worklist;
 
   if (Personality == EHPersonality::MSVC_CXX)
     findCXXEHReturnPoints(F, EHReturnBlocks);
@@ -567,6 +575,7 @@ void WinEHPrepare::demoteValuesLiveAcrossHandlers(
 
   // Normal blocks are the blocks reachable from the entry block and all EH
   // return points.
+  SetVector<BasicBlock *> Worklist;
   Worklist = EHReturnBlocks;
   Worklist.insert(&F.getEntryBlock());
   findReachableBlocks(NormalBlocks, Worklist, nullptr);
@@ -588,6 +597,21 @@ void WinEHPrepare::demoteValuesLiveAcrossHandlers(
       dbgs() << "  " << BB->getName() << '\n';
   });
 
+}
+
+/// Ensure that all values live into and out of exception handlers are stored
+/// in memory.
+/// FIXME: This falls down when values are defined in one handler and live into
+/// another handler. For example, a cleanup defines a value used only by a
+/// catch handler.
+void WinEHPrepare::demoteValuesLiveAcrossHandlers(
+    Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
+  DEBUG(dbgs() << "Demoting values live across exception handlers in function "
+               << F.getName() << '\n');
+
+  // identifyEHBlocks() should have been called before this function.
+  assert(!NormalBlocks.empty());
+
   SetVector<Argument *> ArgsToDemote;
   SetVector<Instruction *> InstrsToDemote;
   for (BasicBlock &BB : F) {
@@ -678,6 +702,7 @@ bool WinEHPrepare::prepareExceptionHandlers(
         return false;
   }
 
+  identifyEHBlocks(F, LPads);
   demoteValuesLiveAcrossHandlers(F, LPads);
 
   // These containers are used to re-map frame variables that are used in
@@ -702,6 +727,16 @@ bool WinEHPrepare::prepareExceptionHandlers(
                        F.getEntryBlock().getFirstInsertionPt());
   }
 
+  // In order to handle the case where one outlined catch handler returns
+  // to a block within another outlined catch handler that would otherwise
+  // be unreachable, we need to outline the nested landing pad before we
+  // outline the landing pad which encloses it.
+  if (!isAsynchronousEHPersonality(Personality)) 
+    std::sort(LPads.begin(), LPads.end(), 
+              [this](LandingPadInst* &L, LandingPadInst* &R) {
+                return DT->dominates(R->getParent(), L->getParent());
+              });
+
   // This container stores the llvm.eh.recover and IndirectBr instructions
   // that make up the body of each landing pad after it has been outlined.
   // We need to defer the population of the target list for the indirectbr
@@ -829,28 +864,24 @@ bool WinEHPrepare::prepareExceptionHandlers(
     CallInst *Recover =
         CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
 
-    if (isAsynchronousEHPersonality(Personality)) {
-      // SEH can create the target list directly, since catch handlers
-      // are not outlined.
-      SetVector<BasicBlock *> ReturnTargets;
-      for (ActionHandler *Action : Actions) {
-        if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
-          const auto &CatchTargets = CatchAction->getReturnTargets();
-          ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
-        }
+    SetVector<BasicBlock *> ReturnTargets;
+    for (ActionHandler *Action : Actions) {
+      if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
+        const auto &CatchTargets = CatchAction->getReturnTargets();
+        ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
       }
-      IndirectBrInst *Branch =
-          IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
-      for (BasicBlock *Target : ReturnTargets)
-        Branch->addDestination(Target);
-    } else {
-      // C++ EH must defer populating the targets to handle the case of
-      // targets that are reached indirectly through nested landing pads.
-      IndirectBrInst *Branch =
-          IndirectBrInst::Create(Recover, 0, LPadBB);
+    }
+    IndirectBrInst *Branch =
+        IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
+    for (BasicBlock *Target : ReturnTargets)
+      Branch->addDestination(Target);
 
+    if (!isAsynchronousEHPersonality(Personality)) {
+      // C++ EH must repopulate the targets later to handle the case of
+      // targets that are reached indirectly through nested landing pads.
       LPadImpls.push_back(std::make_pair(Recover, Branch));
     }
+
   } // End for each landingpad
 
   // If nothing got outlined, there is no more processing to be done.
@@ -864,8 +895,7 @@ bool WinEHPrepare::prepareExceptionHandlers(
     completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
   NestedLPtoOriginalLP.clear();
 
-  // Populate the indirectbr instructions' target lists if we deferred
-  // doing so above.
+  // Update the indirectbr instructions' target lists if necessary.
   SetVector<BasicBlock*> CheckedTargets;
   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
   for (auto &LPadImplPair : LPadImpls) {
@@ -884,6 +914,12 @@ bool WinEHPrepare::prepareExceptionHandlers(
       }
     }
     ActionList.clear();
+    // Clear any targets we already knew about.
+    for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
+      BasicBlock *KnownTarget = Branch->getDestination(I);
+      if (ReturnTargets.count(KnownTarget))
+        ReturnTargets.remove(KnownTarget);
+    }
     for (BasicBlock *Target : ReturnTargets) {
       Branch->addDestination(Target);
       // The target may be a block that we excepted to get pruned.
@@ -994,6 +1030,9 @@ bool WinEHPrepare::prepareExceptionHandlers(
   HandlerToParentFP.clear();
   DT = nullptr;
   SEHExceptionCodeSlot = nullptr;
+  EHBlocks.clear();
+  NormalBlocks.clear();
+  EHReturnBlocks.clear();
 
   return HandlersOutlined;
 }
@@ -1079,10 +1118,19 @@ void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
   // temporarily inserted as its terminator.
   LLVMContext &Context = ParentFn->getContext();
   BasicBlock *OutlinedBB = OutlinedLPad->getParent();
-  assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
-  OutlinedBB->getTerminator()->eraseFromParent();
-  // That should leave OutlinedLPad as the last instruction in its block.
-  assert(&OutlinedBB->back() == OutlinedLPad);
+  // If the nested landing pad was outlined before the landing pad that enclosed
+  // it, it will already be in outlined form.  In that case, we just need to see
+  // if the returns and the enclosing branch instruction need to be updated.
+  IndirectBrInst *Branch =
+      dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
+  if (!Branch) {
+    // If the landing pad wasn't in outlined form, it should be a stub with
+    // an unreachable terminator.
+    assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
+    OutlinedBB->getTerminator()->eraseFromParent();
+    // That should leave OutlinedLPad as the last instruction in its block.
+    assert(&OutlinedBB->back() == OutlinedLPad);
+  }
 
   // The original landing pad will have already had its action intrinsic
   // built by the outlining loop.  We need to clone that into the outlined
@@ -1096,9 +1144,9 @@ void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
   // The instruction after the landing pad should now be a call to eh.actions.
   const Instruction *Recover = II;
   assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
-  IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
+  const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
 
-  // Remap the exception variables into the outlined function.
+  // Remap the return target in the nested handler.
   SmallVector<BlockAddress *, 4> ActionTargets;
   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
   parseEHActions(EHActions, ActionList);
@@ -1125,7 +1173,7 @@ void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
       // should be a block that was outlined into OutlinedHandlerFn.
       assert(BA->getFunction() == ParentFn);
 
-      // Ignore targets that aren't part of OutlinedHandlerFn.
+      // Ignore targets that aren't part of an outlined handler function.
       if (!LPadTargetBlocks.count(BA->getBasicBlock()))
         continue;
 
@@ -1142,13 +1190,25 @@ void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
     }
   }
   ActionList.clear();
-  OutlinedBB->getInstList().push_back(EHActions);
 
-  // Insert an indirect branch into the outlined landing pad BB.
-  IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
-  // Add the previously collected action targets.
-  for (auto *Target : ActionTargets)
-    IBr->addDestination(Target->getBasicBlock());
+  if (Branch) {
+    // If the landing pad was already in outlined form, just update its targets.
+    for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
+      Branch->removeDestination(I);
+    // Add the previously collected action targets.
+    for (auto *Target : ActionTargets)
+      Branch->addDestination(Target->getBasicBlock());
+  } else {
+    // If the landing pad was previously stubbed out, fill in its outlined form.
+    IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
+    OutlinedBB->getInstList().push_back(NewEHActions);
+
+    // Insert an indirect branch into the outlined landing pad BB.
+    IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
+    // Add the previously collected action targets.
+    for (auto *Target : ActionTargets)
+      IBr->addDestination(Target->getBasicBlock());
+  }
 }
 
 // This function examines a block to determine whether the block ends with a
@@ -1326,9 +1386,9 @@ bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
     LPadMap.mapLandingPad(LPad);
   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
     Constant *Sel = CatchAction->getSelector();
-    Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel,
-                                          VarInfo, LPadMap,
-                                          NestedLPtoOriginalLP));
+    Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
+                                          LPadMap, NestedLPtoOriginalLP, DT,
+                                          EHBlocks));
     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
                           ConstantInt::get(Type::getInt32Ty(Context), 1));
   } else {
@@ -1532,15 +1592,22 @@ CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
   if (LPadMap.isLandingPadSpecificInst(Inst))
     return CloningDirector::SkipInstruction;
 
-  // Nested landing pads will be cloned as stubs, with just the
-  // landingpad instruction and an unreachable instruction. When
-  // all landingpads have been outlined, we'll replace this with the
-  // llvm.eh.actions call and indirect branch created when the
-  // landing pad was outlined.
+  // Nested landing pads that have not already been outlined will be cloned as
+  // stubs, with just the landingpad instruction and an unreachable instruction.
+  // When all landingpads have been outlined, we'll replace this with the
+  // llvm.eh.actions call and indirect branch created when the landing pad was
+  // outlined.
   if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
     return handleLandingPad(VMap, LPad, NewBB);
   }
 
+  // Nested landing pads that have already been outlined will be cloned in their
+  // outlined form, but we need to intercept the ibr instruction to filter out
+  // targets that do not return to the handler we are outlining.
+  if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
+    return handleIndirectBr(VMap, IBr, NewBB);
+  }
+
   if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
     return handleInvoke(VMap, Invoke, NewBB);
 
@@ -1570,6 +1637,20 @@ CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
 
 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
+  // If the instruction after the landing pad is a call to llvm.eh.actions
+  // the landing pad has already been outlined.  In this case, we should
+  // clone it because it may return to a block in the handler we are
+  // outlining now that would otherwise be unreachable.  The landing pads
+  // are sorted before outlining begins to enable this case to work
+  // properly.
+  const Instruction *NextI = LPad->getNextNode();
+  if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
+    return CloningDirector::CloneInstruction;
+
+  // If the landing pad hasn't been outlined yet, the landing pad we are
+  // outlining now does not dominate it and so it cannot return to a block
+  // in this handler.  In that case, we can just insert a stub landing
+  // pad now and patch it up later.
   Instruction *NewInst = LPad->clone();
   if (LPad->hasName())
     NewInst->setName(LPad->getName());
@@ -1661,6 +1742,48 @@ CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
   return CloningDirector::SkipInstruction;
 }
 
+CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
+    ValueToValueMapTy &VMap,
+    const IndirectBrInst *IBr,
+    BasicBlock *NewBB) {
+  // If this indirect branch is not part of a landing pad block, just clone it.
+  const BasicBlock *ParentBB = IBr->getParent();
+  if (!ParentBB->isLandingPad())
+    return CloningDirector::CloneInstruction;
+
+  // If it is part of a landing pad, we want to filter out target blocks
+  // that are not part of the handler we are outlining.
+  const LandingPadInst *LPad = ParentBB->getLandingPadInst();
+
+  // Save this correlation for later processing.
+  NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
+
+  // We should only get here for landing pads that have already been outlined.
+  assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
+
+  // Copy the indirectbr, but only include targets that were previously
+  // identified as EH blocks and are dominated by the nested landing pad.
+  SetVector<const BasicBlock *> ReturnTargets;
+  for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
+    auto *TargetBB = IBr->getDestination(I);
+    if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
+        DT->dominates(ParentBB, TargetBB)) {
+      DEBUG(dbgs() << "  Adding destination " << TargetBB->getName() << "\n");
+      ReturnTargets.insert(TargetBB);
+    }
+  }
+  IndirectBrInst *NewBranch = 
+        IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
+                               ReturnTargets.size(), NewBB);
+  for (auto *Target : ReturnTargets)
+    NewBranch->addDestination(const_cast<BasicBlock*>(Target));
+
+  // The operands and targets of the branch instruction are remapped later
+  // because it is a terminator.  Tell the cloning code to clone the
+  // blocks we just added to the target list.
+  return CloningDirector::CloneSuccessors;
+}
+
 CloningDirector::CloningAction
 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
                                  const InvokeInst *Invoke, BasicBlock *NewBB) {
@@ -1750,6 +1873,14 @@ CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
   return CloningDirector::SkipInstruction;
 }
 
+CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
+    ValueToValueMapTy &VMap,
+    const IndirectBrInst *IBr,
+    BasicBlock *NewBB) {
+  // No special handling is required for cleanup cloning.
+  return CloningDirector::CloneInstruction;
+}
+
 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
     ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
   // All invokes in cleanup handlers can be replaced with calls.