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 /// When a loop exit edge is split, LCSSA form may require new PHIs in the new
     80 /// exit block. This function inserts the new PHIs, as needed. Preds is a list
     81 /// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
     82 /// the old loop exit, now the successor of SplitBB.
     83 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
     84                                        BasicBlock *SplitBB,
     85                                        BasicBlock *DestBB) {
     86   // SplitBB shouldn't have anything non-trivial in it yet.
     87   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
     88           SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
     89 
     90   // For each PHI in the destination block.
     91   for (BasicBlock::iterator I = DestBB->begin();
     92        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
     93     unsigned Idx = PN->getBasicBlockIndex(SplitBB);
     94     Value *V = PN->getIncomingValue(Idx);
     95 
     96     // If the input is a PHI which already satisfies LCSSA, don't create
     97     // a new one.
     98     if (const PHINode *VP = dyn_cast<PHINode>(V))
     99       if (VP->getParent() == SplitBB)
    100         continue;
    101 
    102     // Otherwise a new PHI is needed. Create one and populate it.
    103     PHINode *NewPN = PHINode::Create(
    104         PN->getType(), Preds.size(), "split",
    105         SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
    106     for (unsigned i = 0, e = Preds.size(); i != e; ++i)
    107       NewPN->addIncoming(V, Preds[i]);
    108 
    109     // Update the original PHI.
    110     PN->setIncomingValue(Idx, NewPN);
    111   }
    112 }
    113 
    114 BasicBlock *
    115 llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
    116                         const CriticalEdgeSplittingOptions &Options) {
    117   if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
    118     return nullptr;
    119 
    120   assert(!isa<IndirectBrInst>(TI) &&
    121          "Cannot split critical edge from IndirectBrInst");
    122 
    123   BasicBlock *TIBB = TI->getParent();
    124   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
    125 
    126   // Splitting the critical edge to a pad block is non-trivial. Don't do
    127   // it in this generic function.
    128   if (DestBB->isEHPad()) return nullptr;
    129 
    130   // Create a new basic block, linking it into the CFG.
    131   BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
    132                       TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
    133   // Create our unconditional branch.
    134   BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
    135   NewBI->setDebugLoc(TI->getDebugLoc());
    136 
    137   // Branch to the new block, breaking the edge.
    138   TI->setSuccessor(SuccNum, NewBB);
    139 
    140   // Insert the block into the function... right after the block TI lives in.
    141   Function &F = *TIBB->getParent();
    142   Function::iterator FBBI = TIBB->getIterator();
    143   F.getBasicBlockList().insert(++FBBI, NewBB);
    144 
    145   // If there are any PHI nodes in DestBB, we need to update them so that they
    146   // merge incoming values from NewBB instead of from TIBB.
    147   {
    148     unsigned BBIdx = 0;
    149     for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
    150       // We no longer enter through TIBB, now we come in through NewBB.
    151       // Revector exactly one entry in the PHI node that used to come from
    152       // TIBB to come from NewBB.
    153       PHINode *PN = cast<PHINode>(I);
    154 
    155       // Reuse the previous value of BBIdx if it lines up.  In cases where we
    156       // have multiple phi nodes with *lots* of predecessors, this is a speed
    157       // win because we don't have to scan the PHI looking for TIBB.  This
    158       // happens because the BB list of PHI nodes are usually in the same
    159       // order.
    160       if (PN->getIncomingBlock(BBIdx) != TIBB)
    161         BBIdx = PN->getBasicBlockIndex(TIBB);
    162       PN->setIncomingBlock(BBIdx, NewBB);
    163     }
    164   }
    165 
    166   // If there are any other edges from TIBB to DestBB, update those to go
    167   // through the split block, making those edges non-critical as well (and
    168   // reducing the number of phi entries in the DestBB if relevant).
    169   if (Options.MergeIdenticalEdges) {
    170     for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
    171       if (TI->getSuccessor(i) != DestBB) continue;
    172 
    173       // Remove an entry for TIBB from DestBB phi nodes.
    174       DestBB->removePredecessor(TIBB, Options.DontDeleteUselessPHIs);
    175 
    176       // We found another edge to DestBB, go to NewBB instead.
    177       TI->setSuccessor(i, NewBB);
    178     }
    179   }
    180 
    181   // If we have nothing to update, just return.
    182   auto *DT = Options.DT;
    183   auto *LI = Options.LI;
    184   if (!DT && !LI)
    185     return NewBB;
    186 
    187   // Now update analysis information.  Since the only predecessor of NewBB is
    188   // the TIBB, TIBB clearly dominates NewBB.  TIBB usually doesn't dominate
    189   // anything, as there are other successors of DestBB.  However, if all other
    190   // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
    191   // loop header) then NewBB dominates DestBB.
    192   SmallVector<BasicBlock*, 8> OtherPreds;
    193 
    194   // If there is a PHI in the block, loop over predecessors with it, which is
    195   // faster than iterating pred_begin/end.
    196   if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
    197     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
    198       if (PN->getIncomingBlock(i) != NewBB)
    199         OtherPreds.push_back(PN->getIncomingBlock(i));
    200   } else {
    201     for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
    202          I != E; ++I) {
    203       BasicBlock *P = *I;
    204       if (P != NewBB)
    205         OtherPreds.push_back(P);
    206     }
    207   }
    208 
    209   bool NewBBDominatesDestBB = true;
    210 
    211   // Should we update DominatorTree information?
    212   if (DT) {
    213     DomTreeNode *TINode = DT->getNode(TIBB);
    214 
    215     // The new block is not the immediate dominator for any other nodes, but
    216     // TINode is the immediate dominator for the new node.
    217     //
    218     if (TINode) {       // Don't break unreachable code!
    219       DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
    220       DomTreeNode *DestBBNode = nullptr;
    221 
    222       // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
    223       if (!OtherPreds.empty()) {
    224         DestBBNode = DT->getNode(DestBB);
    225         while (!OtherPreds.empty() && NewBBDominatesDestBB) {
    226           if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
    227             NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
    228           OtherPreds.pop_back();
    229         }
    230         OtherPreds.clear();
    231       }
    232 
    233       // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
    234       // doesn't dominate anything.
    235       if (NewBBDominatesDestBB) {
    236         if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
    237         DT->changeImmediateDominator(DestBBNode, NewBBNode);
    238       }
    239     }
    240   }
    241 
    242   // Update LoopInfo if it is around.
    243   if (LI) {
    244     if (Loop *TIL = LI->getLoopFor(TIBB)) {
    245       // If one or the other blocks were not in a loop, the new block is not
    246       // either, and thus LI doesn't need to be updated.
    247       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
    248         if (TIL == DestLoop) {
    249           // Both in the same loop, the NewBB joins loop.
    250           DestLoop->addBasicBlockToLoop(NewBB, *LI);
    251         } else if (TIL->contains(DestLoop)) {
    252           // Edge from an outer loop to an inner loop.  Add to the outer loop.
    253           TIL->addBasicBlockToLoop(NewBB, *LI);
    254         } else if (DestLoop->contains(TIL)) {
    255           // Edge from an inner loop to an outer loop.  Add to the outer loop.
    256           DestLoop->addBasicBlockToLoop(NewBB, *LI);
    257         } else {
    258           // Edge from two loops with no containment relation.  Because these
    259           // are natural loops, we know that the destination block must be the
    260           // header of its loop (adding a branch into a loop elsewhere would
    261           // create an irreducible loop).
    262           assert(DestLoop->getHeader() == DestBB &&
    263                  "Should not create irreducible loops!");
    264           if (Loop *P = DestLoop->getParentLoop())
    265             P->addBasicBlockToLoop(NewBB, *LI);
    266         }
    267       }
    268 
    269       // If TIBB is in a loop and DestBB is outside of that loop, we may need
    270       // to update LoopSimplify form and LCSSA form.
    271       if (!TIL->contains(DestBB)) {
    272         assert(!TIL->contains(NewBB) &&
    273                "Split point for loop exit is contained in loop!");
    274 
    275         // Update LCSSA form in the newly created exit block.
    276         if (Options.PreserveLCSSA) {
    277           createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
    278         }
    279 
    280         // The only that we can break LoopSimplify form by splitting a critical
    281         // edge is if after the split there exists some edge from TIL to DestBB
    282         // *and* the only edge into DestBB from outside of TIL is that of
    283         // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
    284         // is the new exit block and it has no non-loop predecessors. If the
    285         // second isn't true, then DestBB was not in LoopSimplify form prior to
    286         // the split as it had a non-loop predecessor. In both of these cases,
    287         // the predecessor must be directly in TIL, not in a subloop, or again
    288         // LoopSimplify doesn't hold.
    289         SmallVector<BasicBlock *, 4> LoopPreds;
    290         for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
    291              ++I) {
    292           BasicBlock *P = *I;
    293           if (P == NewBB)
    294             continue; // The new block is known.
    295           if (LI->getLoopFor(P) != TIL) {
    296             // No need to re-simplify, it wasn't to start with.
    297             LoopPreds.clear();
    298             break;
    299           }
    300           LoopPreds.push_back(P);
    301         }
    302         if (!LoopPreds.empty()) {
    303           assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
    304           BasicBlock *NewExitBB = SplitBlockPredecessors(
    305               DestBB, LoopPreds, "split", DT, LI, Options.PreserveLCSSA);
    306           if (Options.PreserveLCSSA)
    307             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
    308         }
    309       }
    310     }
    311   }
    312 
    313   return NewBB;
    314 }
    315