Preserve and update ETForest. Patch by Daniel Berlin
[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/Analysis/LoopInfo.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Type.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/ADT/Statistic.h"
28 using namespace llvm;
29
30 namespace {
31   Statistic<> NumBroken("break-crit-edges", "Number of blocks inserted");
32
33   struct BreakCriticalEdges : public FunctionPass {
34     virtual bool runOnFunction(Function &F);
35
36     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
37       AU.addPreserved<ETForest>();
38       AU.addPreserved<DominatorSet>();
39       AU.addPreserved<ImmediateDominators>();
40       AU.addPreserved<DominatorTree>();
41       AU.addPreserved<DominanceFrontier>();
42       AU.addPreserved<LoopInfo>();
43
44       // No loop canonicalization guarantees are broken by this pass.
45       AU.addPreservedID(LoopSimplifyID);
46     }
47   };
48
49   RegisterOpt<BreakCriticalEdges> X("break-crit-edges",
50                                     "Break critical edges in CFG");
51 }
52
53 // Publically exposed interface to pass...
54 const PassInfo *llvm::BreakCriticalEdgesID = X.getPassInfo();
55 FunctionPass *llvm::createBreakCriticalEdgesPass() {
56   return new BreakCriticalEdges();
57 }
58
59 // runOnFunction - Loop over all of the edges in the CFG, breaking critical
60 // edges as they are found.
61 //
62 bool BreakCriticalEdges::runOnFunction(Function &F) {
63   bool Changed = false;
64   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
65     TerminatorInst *TI = I->getTerminator();
66     if (TI->getNumSuccessors() > 1)
67       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
68         if (SplitCriticalEdge(TI, i, this)) {
69           ++NumBroken;
70           Changed = true;
71         }
72   }
73
74   return Changed;
75 }
76
77 //===----------------------------------------------------------------------===//
78 //    Implementation of the external critical edge manipulation functions
79 //===----------------------------------------------------------------------===//
80
81 // isCriticalEdge - Return true if the specified edge is a critical edge.
82 // Critical edges are edges from a block with multiple successors to a block
83 // with multiple predecessors.
84 //
85 bool llvm::isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum) {
86   assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
87   if (TI->getNumSuccessors() == 1) return false;
88
89   const BasicBlock *Dest = TI->getSuccessor(SuccNum);
90   pred_const_iterator I = pred_begin(Dest), E = pred_end(Dest);
91
92   // If there is more than one predecessor, this is a critical edge...
93   assert(I != E && "No preds, but we have an edge to the block?");
94   ++I;        // Skip one edge due to the incoming arc from TI.
95   return I != E;
96 }
97
98 // SplitCriticalEdge - If this edge is a critical edge, insert a new node to
99 // split the critical edge.  This will update DominatorSet, ImmediateDominator,
100 // DominatorTree, and DominatorFrontier information if it is available, thus
101 // calling this pass will not invalidate either of them.  This returns true if
102 // the edge was split, false otherwise.
103 //
104 bool llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
105   if (!isCriticalEdge(TI, SuccNum)) return false;
106   BasicBlock *TIBB = TI->getParent();
107   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
108
109   // Create a new basic block, linking it into the CFG.
110   BasicBlock *NewBB = new BasicBlock(TIBB->getName() + "." +
111                                      DestBB->getName() + "_crit_edge");
112   // Create our unconditional branch...
113   new BranchInst(DestBB, NewBB);
114
115   // Branch to the new block, breaking the edge...
116   TI->setSuccessor(SuccNum, NewBB);
117
118   // Insert the block into the function... right after the block TI lives in.
119   Function &F = *TIBB->getParent();
120   F.getBasicBlockList().insert(TIBB->getNext(), NewBB);
121
122   // If there are any PHI nodes in DestBB, we need to update them so that they
123   // merge incoming values from NewBB instead of from TIBB.
124   //
125   for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
126     PHINode *PN = cast<PHINode>(I);
127     // We no longer enter through TIBB, now we come in through NewBB.  Revector
128     // exactly one entry in the PHI node that used to come from TIBB to come
129     // from NewBB.
130     int BBIdx = PN->getBasicBlockIndex(TIBB);
131     PN->setIncomingBlock(BBIdx, NewBB);
132   }
133
134   // If we don't have a pass object, we can't update anything...
135   if (P == 0) return true;
136
137   // Now update analysis information.  These are the analyses that we are
138   // currently capable of updating...
139   //
140
141   // Should we update DominatorSet information?
142   if (DominatorSet *DS = P->getAnalysisToUpdate<DominatorSet>()) {
143     // The blocks that dominate the new one are the blocks that dominate TIBB
144     // plus the new block itself.
145     DominatorSet::DomSetType DomSet = DS->getDominators(TIBB);
146     DomSet.insert(NewBB);  // A block always dominates itself.
147     DS->addBasicBlock(NewBB, DomSet);
148   }
149
150   // Should we update ImmediateDominator information?
151   if (ImmediateDominators *ID = P->getAnalysisToUpdate<ImmediateDominators>()) {
152     // TIBB is the new immediate dominator for NewBB.  NewBB doesn't dominate
153     // anything.
154     ID->addNewBlock(NewBB, TIBB);
155   }
156
157   // Update the forest?
158   if (ETForest *EF = P->getAnalysisToUpdate<ETForest>())
159     EF->addNewBlock(NewBB, TIBB);
160
161   // Should we update DominatorTree information?
162   if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>()) {
163     DominatorTree::Node *TINode = DT->getNode(TIBB);
164
165     // The new block is not the immediate dominator for any other nodes, but
166     // TINode is the immediate dominator for the new node.
167     //
168     if (TINode)        // Don't break unreachable code!
169       DT->createNewNode(NewBB, TINode);
170   }
171
172   // Should we update DominanceFrontier information?
173   if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>()) {
174     // Since the new block is dominated by its only predecessor TIBB,
175     // it cannot be in any block's dominance frontier.  Its dominance
176     // frontier is {DestBB}.
177     DominanceFrontier::DomSetType NewDFSet;
178     NewDFSet.insert(DestBB);
179     DF->addBasicBlock(NewBB, NewDFSet);
180   }
181   
182   // Update LoopInfo if it is around.
183   if (LoopInfo *LI = P->getAnalysisToUpdate<LoopInfo>()) {
184     // If one or the other blocks were not in a loop, the new block is not
185     // either, and thus LI doesn't need to be updated.
186     if (Loop *TIL = LI->getLoopFor(TIBB))
187       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
188         if (TIL == DestLoop) {
189           // Both in the same loop, the NewBB joins loop.
190           DestLoop->addBasicBlockToLoop(NewBB, *LI);
191         } else if (TIL->contains(DestLoop->getHeader())) {
192           // Edge from an outer loop to an inner loop.  Add to the outer lopo.
193           TIL->addBasicBlockToLoop(NewBB, *LI);
194         } else if (DestLoop->contains(TIL->getHeader())) {
195           // Edge from an inner loop to an outer loop.  Add to the outer lopo.
196           DestLoop->addBasicBlockToLoop(NewBB, *LI);
197         } else {
198           // Edge from two loops with no containment relation.  Because these
199           // are natural loops, we know that the destination block must be the
200           // header of its loop (adding a branch into a loop elsewhere would
201           // create an irreducible loop).
202           assert(DestLoop->getHeader() == DestBB &&
203                  "Should not create irreducible loops!");
204           if (Loop *P = DestLoop->getParentLoop())
205             P->addBasicBlockToLoop(NewBB, *LI);
206         }
207       }
208     
209   }
210   return true;
211 }