Reorganize code for locality, improve comments
[oota-llvm.git] / lib / Transforms / Utils / BreakCriticalEdges.cpp
1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 // forward dominator (set, immediate dominators, tree, and frontier)
15 // information.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Function.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/iPHINode.h"
25 #include "llvm/Support/CFG.h"
26 #include "Support/Statistic.h"
27
28 namespace {
29   Statistic<> NumBroken("break-crit-edges", "Number of blocks inserted");
30
31   struct BreakCriticalEdges : public FunctionPass {
32     virtual bool runOnFunction(Function &F);
33     
34     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
35       AU.addPreserved<DominatorSet>();
36       AU.addPreserved<ImmediateDominators>();
37       AU.addPreserved<DominatorTree>();
38       AU.addPreserved<DominanceFrontier>();
39
40       // No loop canonicalization guarantees are broken by this pass.
41       AU.addPreservedID(LoopSimplifyID);
42     }
43   };
44
45   RegisterOpt<BreakCriticalEdges> X("break-crit-edges",
46                                     "Break critical edges in CFG");
47 }
48
49 // Publically exposed interface to pass...
50 const PassInfo *BreakCriticalEdgesID = X.getPassInfo();
51 Pass *createBreakCriticalEdgesPass() { return new BreakCriticalEdges(); }
52
53 // runOnFunction - Loop over all of the edges in the CFG, breaking critical
54 // edges as they are found.
55 //
56 bool BreakCriticalEdges::runOnFunction(Function &F) {
57   bool Changed = false;
58   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
59     TerminatorInst *TI = I->getTerminator();
60     if (TI->getNumSuccessors() > 1)
61       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
62         if (SplitCriticalEdge(TI, i, this)) {
63           ++NumBroken;
64           Changed = true;
65         }
66   }
67
68   return Changed;
69 }
70
71 //===----------------------------------------------------------------------===//
72 //    Implementation of the external critical edge manipulation functions
73 //===----------------------------------------------------------------------===//
74
75 // isCriticalEdge - Return true if the specified edge is a critical edge.
76 // Critical edges are edges from a block with multiple successors to a block
77 // with multiple predecessors.
78 //
79 bool isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum) {
80   assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
81   if (TI->getNumSuccessors() == 1) return false;
82
83   const BasicBlock *Dest = TI->getSuccessor(SuccNum);
84   pred_const_iterator I = pred_begin(Dest), E = pred_end(Dest);
85
86   // If there is more than one predecessor, this is a critical edge...
87   assert(I != E && "No preds, but we have an edge to the block?");
88   ++I;        // Skip one edge due to the incoming arc from TI.
89   return I != E;
90 }
91
92 // SplitCriticalEdge - If this edge is a critical edge, insert a new node to
93 // split the critical edge.  This will update DominatorSet, ImmediateDominator,
94 // DominatorTree, and DominatorFrontier information if it is available, thus
95 // calling this pass will not invalidate either of them.  This returns true if
96 // the edge was split, false otherwise.
97 //
98 bool SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
99   if (!isCriticalEdge(TI, SuccNum)) return false;
100   BasicBlock *TIBB = TI->getParent();
101   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
102
103   // Create a new basic block, linking it into the CFG.
104   BasicBlock *NewBB = new BasicBlock(TIBB->getName() + "." +
105                                      DestBB->getName() + "_crit_edge");
106   // Create our unconditional branch...
107   BranchInst *BI = new BranchInst(DestBB);
108   NewBB->getInstList().push_back(BI);
109   
110   // Branch to the new block, breaking the edge...
111   TI->setSuccessor(SuccNum, NewBB);
112
113   // Insert the block into the function... right after the block TI lives in.
114   Function &F = *TIBB->getParent();
115   F.getBasicBlockList().insert(TIBB->getNext(), NewBB);
116
117   // If there are any PHI nodes in DestBB, we need to update them so that they
118   // merge incoming values from NewBB instead of from TIBB.
119   //
120   for (BasicBlock::iterator I = DestBB->begin();
121        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
122     // We no longer enter through TIBB, now we come in through NewBB.
123     PN->replaceUsesOfWith(TIBB, NewBB);
124   }
125
126   // If we don't have a pass object, we can't update anything...
127   if (P == 0) return true;
128
129   // Now update analysis information.  These are the analyses that we are
130   // currently capable of updating...
131   //
132
133   // Should we update DominatorSet information?
134   if (DominatorSet *DS = P->getAnalysisToUpdate<DominatorSet>()) {
135     // The blocks that dominate the new one are the blocks that dominate TIBB
136     // plus the new block itself.
137     DominatorSet::DomSetType DomSet = DS->getDominators(TIBB);
138     DomSet.insert(NewBB);  // A block always dominates itself.
139     DS->addBasicBlock(NewBB, DomSet);
140   }
141
142   // Should we update ImmediateDominator information?
143   if (ImmediateDominators *ID = P->getAnalysisToUpdate<ImmediateDominators>()) {
144     // TIBB is the new immediate dominator for NewBB.  NewBB doesn't dominate
145     // anything.
146     ID->addNewBlock(NewBB, TIBB);
147   }
148   
149   // Should we update DominatorTree information?
150   if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>()) {
151     DominatorTree::Node *TINode = DT->getNode(TIBB);
152     
153     // The new block is not the immediate dominator for any other nodes, but
154     // TINode is the immediate dominator for the new node.
155     //
156     if (TINode)        // Don't break unreachable code!
157       DT->createNewNode(NewBB, TINode);
158   }
159
160   // Should we update DominanceFrontier information?
161   if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>()) {
162     // Since the new block is dominated by its only predecessor TIBB,
163     // it cannot be in any block's dominance frontier.  Its dominance
164     // frontier is {DestBB}.
165     DominanceFrontier::DomSetType NewDFSet;
166     NewDFSet.insert(DestBB);
167     DF->addBasicBlock(NewBB, NewDFSet);
168   }
169   return true;
170 }