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