LCOV - code coverage report
Current view: top level - lib/CodeGen - DwarfEHPrepare.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 93 94 98.9 %
Date: 2018-06-17 00:07:59 Functions: 11 12 91.7 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- DwarfEHPrepare - Prepare exception handling for code generation ----===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This pass mulches exception handling code into a form adapted to code
      11             : // generation. Required if using dwarf exception handling.
      12             : //
      13             : //===----------------------------------------------------------------------===//
      14             : 
      15             : #include "llvm/ADT/BitVector.h"
      16             : #include "llvm/ADT/SmallVector.h"
      17             : #include "llvm/ADT/Statistic.h"
      18             : #include "llvm/Analysis/CFG.h"
      19             : #include "llvm/Analysis/EHPersonalities.h"
      20             : #include "llvm/Analysis/TargetTransformInfo.h"
      21             : #include "llvm/Transforms/Utils/Local.h"
      22             : #include "llvm/CodeGen/RuntimeLibcalls.h"
      23             : #include "llvm/CodeGen/TargetLowering.h"
      24             : #include "llvm/CodeGen/TargetPassConfig.h"
      25             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      26             : #include "llvm/IR/BasicBlock.h"
      27             : #include "llvm/IR/Constants.h"
      28             : #include "llvm/IR/DerivedTypes.h"
      29             : #include "llvm/IR/Dominators.h"
      30             : #include "llvm/IR/Function.h"
      31             : #include "llvm/IR/Instructions.h"
      32             : #include "llvm/IR/Module.h"
      33             : #include "llvm/IR/Type.h"
      34             : #include "llvm/Pass.h"
      35             : #include "llvm/Support/Casting.h"
      36             : #include "llvm/Target/TargetMachine.h"
      37             : #include <cstddef>
      38             : 
      39             : using namespace llvm;
      40             : 
      41             : #define DEBUG_TYPE "dwarfehprepare"
      42             : 
      43             : STATISTIC(NumResumesLowered, "Number of resume calls lowered");
      44             : 
      45             : namespace {
      46             : 
      47       39984 :   class DwarfEHPrepare : public FunctionPass {
      48             :     // RewindFunction - _Unwind_Resume or the target equivalent.
      49             :     Constant *RewindFunction = nullptr;
      50             : 
      51             :     DominatorTree *DT = nullptr;
      52             :     const TargetLowering *TLI = nullptr;
      53             : 
      54             :     bool InsertUnwindResumeCalls(Function &Fn);
      55             :     Value *GetExceptionObject(ResumeInst *RI);
      56             :     size_t
      57             :     pruneUnreachableResumes(Function &Fn,
      58             :                             SmallVectorImpl<ResumeInst *> &Resumes,
      59             :                             SmallVectorImpl<LandingPadInst *> &CleanupLPads);
      60             : 
      61             :   public:
      62             :     static char ID; // Pass identification, replacement for typeid.
      63             : 
      64       40166 :     DwarfEHPrepare() : FunctionPass(ID) {}
      65             : 
      66             :     bool runOnFunction(Function &Fn) override;
      67             : 
      68       19890 :     bool doFinalization(Module &M) override {
      69       19890 :       RewindFunction = nullptr;
      70       19890 :       return false;
      71             :     }
      72             : 
      73             :     void getAnalysisUsage(AnalysisUsage &AU) const override;
      74             : 
      75          19 :     StringRef getPassName() const override {
      76          19 :       return "Exception handling preparation";
      77             :     }
      78             :   };
      79             : 
      80             : } // end anonymous namespace
      81             : 
      82             : char DwarfEHPrepare::ID = 0;
      83             : 
      84       33750 : INITIALIZE_PASS_BEGIN(DwarfEHPrepare, DEBUG_TYPE,
      85             :                       "Prepare DWARF exceptions", false, false)
      86       33750 : INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
      87       33750 : INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
      88       33750 : INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
      89      182566 : INITIALIZE_PASS_END(DwarfEHPrepare, DEBUG_TYPE,
      90             :                     "Prepare DWARF exceptions", false, false)
      91             : 
      92       40162 : FunctionPass *llvm::createDwarfEHPass() { return new DwarfEHPrepare(); }
      93             : 
      94       19977 : void DwarfEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
      95             :   AU.addRequired<TargetPassConfig>();
      96             :   AU.addRequired<TargetTransformInfoWrapperPass>();
      97             :   AU.addRequired<DominatorTreeWrapperPass>();
      98       19977 : }
      99             : 
     100             : /// GetExceptionObject - Return the exception object from the value passed into
     101             : /// the 'resume' instruction (typically an aggregate). Clean up any dead
     102             : /// instructions, including the 'resume' instruction.
     103        3996 : Value *DwarfEHPrepare::GetExceptionObject(ResumeInst *RI) {
     104             :   Value *V = RI->getOperand(0);
     105             :   Value *ExnObj = nullptr;
     106             :   InsertValueInst *SelIVI = dyn_cast<InsertValueInst>(V);
     107             :   LoadInst *SelLoad = nullptr;
     108             :   InsertValueInst *ExcIVI = nullptr;
     109             :   bool EraseIVIs = false;
     110             : 
     111             :   if (SelIVI) {
     112        2780 :     if (SelIVI->getNumIndices() == 1 && *SelIVI->idx_begin() == 1) {
     113             :       ExcIVI = dyn_cast<InsertValueInst>(SelIVI->getOperand(0));
     114        5560 :       if (ExcIVI && isa<UndefValue>(ExcIVI->getOperand(0)) &&
     115        2780 :           ExcIVI->getNumIndices() == 1 && *ExcIVI->idx_begin() == 0) {
     116             :         ExnObj = ExcIVI->getOperand(1);
     117             :         SelLoad = dyn_cast<LoadInst>(SelIVI->getOperand(1));
     118             :         EraseIVIs = true;
     119             :       }
     120             :     }
     121             :   }
     122             : 
     123        3996 :   if (!ExnObj)
     124        2432 :     ExnObj = ExtractValueInst::Create(RI->getOperand(0), 0, "exn.obj", RI);
     125             : 
     126        3996 :   RI->eraseFromParent();
     127             : 
     128        3996 :   if (EraseIVIs) {
     129        2780 :     if (SelIVI->use_empty())
     130        2780 :       SelIVI->eraseFromParent();
     131        2780 :     if (ExcIVI->use_empty())
     132        2780 :       ExcIVI->eraseFromParent();
     133        2780 :     if (SelLoad && SelLoad->use_empty())
     134        1414 :       SelLoad->eraseFromParent();
     135             :   }
     136             : 
     137        3996 :   return ExnObj;
     138             : }
     139             : 
     140             : /// Replace resumes that are not reachable from a cleanup landing pad with
     141             : /// unreachable and then simplify those blocks.
     142        3735 : size_t DwarfEHPrepare::pruneUnreachableResumes(
     143             :     Function &Fn, SmallVectorImpl<ResumeInst *> &Resumes,
     144             :     SmallVectorImpl<LandingPadInst *> &CleanupLPads) {
     145        3735 :   BitVector ResumeReachable(Resumes.size());
     146             :   size_t ResumeIndex = 0;
     147       11799 :   for (auto *RI : Resumes) {
     148       18842 :     for (auto *LP : CleanupLPads) {
     149       11401 :       if (isPotentiallyReachable(LP, RI, DT)) {
     150        3996 :         ResumeReachable.set(ResumeIndex);
     151             :         break;
     152             :       }
     153             :     }
     154        4032 :     ++ResumeIndex;
     155             :   }
     156             : 
     157             :   // If everything is reachable, there is no change.
     158        3735 :   if (ResumeReachable.all())
     159        3699 :     return Resumes.size();
     160             : 
     161             :   const TargetTransformInfo &TTI =
     162          36 :       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn);
     163          36 :   LLVMContext &Ctx = Fn.getContext();
     164             : 
     165             :   // Otherwise, insert unreachable instructions and call simplifycfg.
     166             :   size_t ResumesLeft = 0;
     167         108 :   for (size_t I = 0, E = Resumes.size(); I < E; ++I) {
     168          36 :     ResumeInst *RI = Resumes[I];
     169          72 :     if (ResumeReachable[I]) {
     170           0 :       Resumes[ResumesLeft++] = RI;
     171             :     } else {
     172          36 :       BasicBlock *BB = RI->getParent();
     173          36 :       new UnreachableInst(Ctx, RI);
     174          36 :       RI->eraseFromParent();
     175          36 :       simplifyCFG(BB, TTI);
     176             :     }
     177             :   }
     178          36 :   Resumes.resize(ResumesLeft);
     179          36 :   return ResumesLeft;
     180             : }
     181             : 
     182             : /// InsertUnwindResumeCalls - Convert the ResumeInsts that are still present
     183             : /// into calls to the appropriate _Unwind_Resume function.
     184      204021 : bool DwarfEHPrepare::InsertUnwindResumeCalls(Function &Fn) {
     185             :   SmallVector<ResumeInst*, 16> Resumes;
     186             :   SmallVector<LandingPadInst*, 16> CleanupLPads;
     187      604127 :   for (BasicBlock &BB : Fn) {
     188      400106 :     if (auto *RI = dyn_cast<ResumeInst>(BB.getTerminator()))
     189        4032 :       Resumes.push_back(RI);
     190      400106 :     if (auto *LP = BB.getLandingPadInst())
     191       28430 :       if (LP->isCleanup())
     192       18834 :         CleanupLPads.push_back(LP);
     193             :   }
     194             : 
     195      204021 :   if (Resumes.empty())
     196             :     return false;
     197             : 
     198             :   // Check the personality, don't do anything if it's scope-based.
     199        3735 :   EHPersonality Pers = classifyEHPersonality(Fn.getPersonalityFn());
     200             :   if (isScopedEHPersonality(Pers))
     201             :     return false;
     202             : 
     203        3735 :   LLVMContext &Ctx = Fn.getContext();
     204             : 
     205        3735 :   size_t ResumesLeft = pruneUnreachableResumes(Fn, Resumes, CleanupLPads);
     206        3735 :   if (ResumesLeft == 0)
     207             :     return true; // We pruned them all.
     208             : 
     209             :   // Find the rewind function if we didn't already.
     210        3699 :   if (!RewindFunction) {
     211        1236 :     FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
     212        1854 :                                           Type::getInt8PtrTy(Ctx), false);
     213         618 :     const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
     214        1236 :     RewindFunction = Fn.getParent()->getOrInsertFunction(RewindName, FTy);
     215             :   }
     216             : 
     217             :   // Create the basic block where the _Unwind_Resume call will live.
     218        3699 :   if (ResumesLeft == 1) {
     219             :     // Instead of creating a new BB and PHI node, just append the call to
     220             :     // _Unwind_Resume to the end of the single resume block.
     221        3628 :     ResumeInst *RI = Resumes.front();
     222        3628 :     BasicBlock *UnwindBB = RI->getParent();
     223        3628 :     Value *ExnObj = GetExceptionObject(RI);
     224             : 
     225             :     // Call the _Unwind_Resume function.
     226        3628 :     CallInst *CI = CallInst::Create(RewindFunction, ExnObj, "", UnwindBB);
     227        3628 :     CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
     228             : 
     229             :     // We never expect _Unwind_Resume to return.
     230        3628 :     new UnreachableInst(Ctx, UnwindBB);
     231             :     return true;
     232             :   }
     233             : 
     234          71 :   BasicBlock *UnwindBB = BasicBlock::Create(Ctx, "unwind_resume", &Fn);
     235         142 :   PHINode *PN = PHINode::Create(Type::getInt8PtrTy(Ctx), ResumesLeft,
     236             :                                 "exn.obj", UnwindBB);
     237             : 
     238             :   // Extract the exception object from the ResumeInst and add it to the PHI node
     239             :   // that feeds the _Unwind_Resume call.
     240         807 :   for (ResumeInst *RI : Resumes) {
     241         368 :     BasicBlock *Parent = RI->getParent();
     242         368 :     BranchInst::Create(UnwindBB, Parent);
     243             : 
     244         368 :     Value *ExnObj = GetExceptionObject(RI);
     245         368 :     PN->addIncoming(ExnObj, Parent);
     246             : 
     247             :     ++NumResumesLowered;
     248             :   }
     249             : 
     250             :   // Call the function.
     251         142 :   CallInst *CI = CallInst::Create(RewindFunction, PN, "", UnwindBB);
     252          71 :   CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
     253             : 
     254             :   // We never expect _Unwind_Resume to return.
     255          71 :   new UnreachableInst(Ctx, UnwindBB);
     256          71 :   return true;
     257             : }
     258             : 
     259      204021 : bool DwarfEHPrepare::runOnFunction(Function &Fn) {
     260             :   const TargetMachine &TM =
     261      204021 :       getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
     262      408042 :   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
     263      204021 :   TLI = TM.getSubtargetImpl(Fn)->getTargetLowering();
     264      204021 :   bool Changed = InsertUnwindResumeCalls(Fn);
     265      204021 :   DT = nullptr;
     266      204021 :   TLI = nullptr;
     267      204021 :   return Changed;
     268             : }

Generated by: LCOV version 1.13