Home | History | Annotate | Download | only in Utils
      1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
      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 // BreakCriticalEdges pass - Break all of the critical edges in the CFG by
     11 // inserting a dummy basic block.  This pass may be "required" by passes that
     12 // cannot deal with critical edges.  For this usage, the structure type is
     13 // forward declared.  This pass obviously invalidates the CFG, but can update
     14 // dominator trees.
     15 //
     16 //===----------------------------------------------------------------------===//
     17 
     18 #include "llvm/Transforms/Scalar.h"
     19 #include "llvm/ADT/SmallVector.h"
     20 #include "llvm/ADT/Statistic.h"
     21 #include "llvm/Analysis/AliasAnalysis.h"
     22 #include "llvm/Analysis/CFG.h"
     23 #include "llvm/Analysis/LoopInfo.h"
     24 #include "llvm/IR/CFG.h"
     25 #include "llvm/IR/Dominators.h"
     26 #include "llvm/IR/Function.h"
     27 #include "llvm/IR/Instructions.h"
     28 #include "llvm/IR/Type.h"
     29 #include "llvm/Support/ErrorHandling.h"
     30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
     31 using namespace llvm;
     32 
     33 #define DEBUG_TYPE "break-crit-edges"
     34 
     35 STATISTIC(NumBroken, "Number of blocks inserted");
     36 
     37 namespace {
     38   struct BreakCriticalEdges : public FunctionPass {
     39     static char ID; // Pass identification, replacement for typeid
     40     BreakCriticalEdges() : FunctionPass(ID) {
     41       initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
     42     }
     43 
     44     bool runOnFunction(Function &F) override {
     45       auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
     46       auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
     47       auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
     48       auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
     49       unsigned N =
     50           SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
     51       NumBroken += N;
     52       return N > 0;
     53     }
     54 
     55     void getAnalysisUsage(AnalysisUsage &AU) const override {
     56       AU.addPreserved<DominatorTreeWrapperPass>();
     57       AU.addPreserved<LoopInfoWrapperPass>();
     58 
     59       // No loop canonicalization guarantees are broken by this pass.
     60       AU.addPreservedID(LoopSimplifyID);
     61     }
     62   };
     63 }
     64 
     65 char BreakCriticalEdges::ID = 0;
     66 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
     67                 "Break critical edges in CFG", false, false)
     68 
     69 // Publicly exposed interface to pass...
     70 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
     71 FunctionPass *llvm::createBreakCriticalEdgesPass() {
     72   return new BreakCriticalEdges();
     73 }
     74 
     75 //===----------------------------------------------------------------------===//
     76 //    Implementation of the external critical edge manipulation functions
     77 //===----------------------------------------------------------------------===//
     78 
     79 /// createPHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form
     80 /// may require new PHIs in the new exit block. This function inserts the
     81 /// new PHIs, as needed. Preds is a list of preds inside the loop, SplitBB
     82 /// is the new loop exit block, and DestBB is the old loop exit, now the
     83 /// successor of SplitBB.
     84 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
     85                                        BasicBlock *SplitBB,
     86                                        BasicBlock *DestBB) {
     87   // SplitBB shouldn't have anything non-trivial in it yet.
     88   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
     89           SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
     90 
     91   // For each PHI in the destination block.
     92   for (BasicBlock::iterator I = DestBB->begin();
     93        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
     94     unsigned Idx = PN->getBasicBlockIndex(SplitBB);
     95     Value *V = PN->getIncomingValue(Idx);
     96 
     97     // If the input is a PHI which already satisfies LCSSA, don't create
     98     // a new one.
     99     if (const PHINode *VP = dyn_cast<PHINode>(V))
    100       if (VP->getParent() == SplitBB)
    101         continue;
    102 
    103     // Otherwise a new PHI is needed. Create one and populate it.
    104     PHINode *NewPN = PHINode::Create(
    105         PN->getType(), Preds.size(), "split",
    106         SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
    107     for (unsigned i = 0, e = Preds.size(); i != e; ++i)
    108       NewPN->addIncoming(V, Preds[i]);
    109 
    110     // Update the original PHI.
    111     PN->setIncomingValue(Idx, NewPN);
    112   }
    113 }
    114 
    115 /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
    116 /// split the critical edge.  This will update DominatorTree information if it
    117 /// is available, thus calling this pass will not invalidate either of them.
    118 /// This returns the new block if the edge was split, null otherwise.
    119 ///
    120 /// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
    121 /// specified successor will be merged into the same critical edge block.
    122 /// This is most commonly interesting with switch instructions, which may
    123 /// have many edges to any one destination.  This ensures that all edges to that
    124 /// dest go to one block instead of each going to a different block, but isn't
    125 /// the standard definition of a "critical edge".
    126 ///
    127 /// It is invalid to call this function on a critical edge that starts at an
    128 /// IndirectBrInst.  Splitting these edges will almost always create an invalid
    129 /// program because the address of the new block won't be the one that is jumped
    130 /// to.
    131 ///
    132 BasicBlock *llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
    133                                     const CriticalEdgeSplittingOptions &Options) {
    134   if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
    135     return nullptr;
    136 
    137   assert(!isa<IndirectBrInst>(TI) &&
    138          "Cannot split critical edge from IndirectBrInst");
    139 
    140   BasicBlock *TIBB = TI->getParent();
    141   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
    142 
    143   // Splitting the critical edge to a pad block is non-trivial. Don't do
    144   // it in this generic function.
    145   if (DestBB->isEHPad()) return nullptr;
    146 
    147   // Create a new basic block, linking it into the CFG.
    148   BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
    149                       TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
    150   // Create our unconditional branch.
    151   BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
    152   NewBI->setDebugLoc(TI->getDebugLoc());
    153 
    154   // Branch to the new block, breaking the edge.
    155   TI->setSuccessor(SuccNum, NewBB);
    156 
    157   // Insert the block into the function... right after the block TI lives in.
    158   Function &F = *TIBB->getParent();
    159   Function::iterator FBBI = TIBB->getIterator();
    160   F.getBasicBlockList().insert(++FBBI, NewBB);
    161 
    162   // If there are any PHI nodes in DestBB, we need to update them so that they
    163   // merge incoming values from NewBB instead of from TIBB.
    164   {
    165     unsigned BBIdx = 0;
    166     for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
    167       // We no longer enter through TIBB, now we come in through NewBB.
    168       // Revector exactly one entry in the PHI node that used to come from
    169       // TIBB to come from NewBB.
    170       PHINode *PN = cast<PHINode>(I);
    171 
    172       // Reuse the previous value of BBIdx if it lines up.  In cases where we
    173       // have multiple phi nodes with *lots* of predecessors, this is a speed
    174       // win because we don't have to scan the PHI looking for TIBB.  This
    175       // happens because the BB list of PHI nodes are usually in the same
    176       // order.
    177       if (PN->getIncomingBlock(BBIdx) != TIBB)
    178         BBIdx = PN->getBasicBlockIndex(TIBB);
    179       PN->setIncomingBlock(BBIdx, NewBB);
    180     }
    181   }
    182 
    183   // If there are any other edges from TIBB to DestBB, update those to go
    184   // through the split block, making those edges non-critical as well (and
    185   // reducing the number of phi entries in the DestBB if relevant).
    186   if (Options.MergeIdenticalEdges) {
    187     for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
    188       if (TI->getSuccessor(i) != DestBB) continue;
    189 
    190       // Remove an entry for TIBB from DestBB phi nodes.
    191       DestBB->removePredecessor(TIBB, Options.DontDeleteUselessPHIs);
    192 
    193       // We found another edge to DestBB, go to NewBB instead.
    194       TI->setSuccessor(i, NewBB);
    195     }
    196   }
    197 
    198   // If we have nothing to update, just return.
    199   auto *DT = Options.DT;
    200   auto *LI = Options.LI;
    201   if (!DT && !LI)
    202     return NewBB;
    203 
    204   // Now update analysis information.  Since the only predecessor of NewBB is
    205   // the TIBB, TIBB clearly dominates NewBB.  TIBB usually doesn't dominate
    206   // anything, as there are other successors of DestBB.  However, if all other
    207   // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
    208   // loop header) then NewBB dominates DestBB.
    209   SmallVector<BasicBlock*, 8> OtherPreds;
    210 
    211   // If there is a PHI in the block, loop over predecessors with it, which is
    212   // faster than iterating pred_begin/end.
    213   if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
    214     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
    215       if (PN->getIncomingBlock(i) != NewBB)
    216         OtherPreds.push_back(PN->getIncomingBlock(i));
    217   } else {
    218     for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
    219          I != E; ++I) {
    220       BasicBlock *P = *I;
    221       if (P != NewBB)
    222         OtherPreds.push_back(P);
    223     }
    224   }
    225 
    226   bool NewBBDominatesDestBB = true;
    227 
    228   // Should we update DominatorTree information?
    229   if (DT) {
    230     DomTreeNode *TINode = DT->getNode(TIBB);
    231 
    232     // The new block is not the immediate dominator for any other nodes, but
    233     // TINode is the immediate dominator for the new node.
    234     //
    235     if (TINode) {       // Don't break unreachable code!
    236       DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
    237       DomTreeNode *DestBBNode = nullptr;
    238 
    239       // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
    240       if (!OtherPreds.empty()) {
    241         DestBBNode = DT->getNode(DestBB);
    242         while (!OtherPreds.empty() && NewBBDominatesDestBB) {
    243           if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
    244             NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
    245           OtherPreds.pop_back();
    246         }
    247         OtherPreds.clear();
    248       }
    249 
    250       // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
    251       // doesn't dominate anything.
    252       if (NewBBDominatesDestBB) {
    253         if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
    254         DT->changeImmediateDominator(DestBBNode, NewBBNode);
    255       }
    256     }
    257   }
    258 
    259   // Update LoopInfo if it is around.
    260   if (LI) {
    261     if (Loop *TIL = LI->getLoopFor(TIBB)) {
    262       // If one or the other blocks were not in a loop, the new block is not
    263       // either, and thus LI doesn't need to be updated.
    264       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
    265         if (TIL == DestLoop) {
    266           // Both in the same loop, the NewBB joins loop.
    267           DestLoop->addBasicBlockToLoop(NewBB, *LI);
    268         } else if (TIL->contains(DestLoop)) {
    269           // Edge from an outer loop to an inner loop.  Add to the outer loop.
    270           TIL->addBasicBlockToLoop(NewBB, *LI);
    271         } else if (DestLoop->contains(TIL)) {
    272           // Edge from an inner loop to an outer loop.  Add to the outer loop.
    273           DestLoop->addBasicBlockToLoop(NewBB, *LI);
    274         } else {
    275           // Edge from two loops with no containment relation.  Because these
    276           // are natural loops, we know that the destination block must be the
    277           // header of its loop (adding a branch into a loop elsewhere would
    278           // create an irreducible loop).
    279           assert(DestLoop->getHeader() == DestBB &&
    280                  "Should not create irreducible loops!");
    281           if (Loop *P = DestLoop->getParentLoop())
    282             P->addBasicBlockToLoop(NewBB, *LI);
    283         }
    284       }
    285 
    286       // If TIBB is in a loop and DestBB is outside of that loop, we may need
    287       // to update LoopSimplify form and LCSSA form.
    288       if (!TIL->contains(DestBB)) {
    289         assert(!TIL->contains(NewBB) &&
    290                "Split point for loop exit is contained in loop!");
    291 
    292         // Update LCSSA form in the newly created exit block.
    293         if (Options.PreserveLCSSA) {
    294           createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
    295         }
    296 
    297         // The only that we can break LoopSimplify form by splitting a critical
    298         // edge is if after the split there exists some edge from TIL to DestBB
    299         // *and* the only edge into DestBB from outside of TIL is that of
    300         // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
    301         // is the new exit block and it has no non-loop predecessors. If the
    302         // second isn't true, then DestBB was not in LoopSimplify form prior to
    303         // the split as it had a non-loop predecessor. In both of these cases,
    304         // the predecessor must be directly in TIL, not in a subloop, or again
    305         // LoopSimplify doesn't hold.
    306         SmallVector<BasicBlock *, 4> LoopPreds;
    307         for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
    308              ++I) {
    309           BasicBlock *P = *I;
    310           if (P == NewBB)
    311             continue; // The new block is known.
    312           if (LI->getLoopFor(P) != TIL) {
    313             // No need to re-simplify, it wasn't to start with.
    314             LoopPreds.clear();
    315             break;
    316           }
    317           LoopPreds.push_back(P);
    318         }
    319         if (!LoopPreds.empty()) {
    320           assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
    321           BasicBlock *NewExitBB = SplitBlockPredecessors(
    322               DestBB, LoopPreds, "split", DT, LI, Options.PreserveLCSSA);
    323           if (Options.PreserveLCSSA)
    324             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
    325         }
    326       }
    327     }
    328   }
    329 
    330   return NewBB;
    331 }
    332