Break critical edges coming into blocks with PHI nodes.
[oota-llvm.git] / lib / CodeGen / StrongPHIElimination.cpp
1 //===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Owen Anderson and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass eliminates machine instruction PHI nodes by inserting copy
11 // instructions, using an intelligent copy-folding technique based on
12 // dominator information.  This is technique is derived from:
13 // 
14 //    Budimlic, et al. Fast copy coalescing and live-range identification.
15 //    In Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language
16 //    Design and Implementation (Berlin, Germany, June 17 - 19, 2002).
17 //    PLDI '02. ACM, New York, NY, 25-32.
18 //    DOI= http://doi.acm.org/10.1145/512529.512534
19 //
20 //===----------------------------------------------------------------------===//
21
22 #define DEBUG_TYPE "strongphielim"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/BreakCriticalMachineEdge.h"
25 #include "llvm/CodeGen/LiveVariables.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/Compiler.h"
33 using namespace llvm;
34
35
36 namespace {
37   struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
38     static char ID; // Pass identification, replacement for typeid
39     StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
40
41     bool runOnMachineFunction(MachineFunction &Fn);
42     
43     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
44       AU.addPreserved<LiveVariables>();
45       AU.addPreservedID(PHIEliminationID);
46       AU.addRequired<MachineDominatorTree>();
47       AU.addRequired<LiveVariables>();
48       AU.setPreservesAll();
49       MachineFunctionPass::getAnalysisUsage(AU);
50     }
51     
52     virtual void releaseMemory() {
53       preorder.clear();
54       maxpreorder.clear();
55       
56       waiting.clear();
57     }
58
59   private:
60     struct DomForestNode {
61     private:
62       std::vector<DomForestNode*> children;
63       unsigned reg;
64       
65       void addChild(DomForestNode* DFN) { children.push_back(DFN); }
66       
67     public:
68       typedef std::vector<DomForestNode*>::iterator iterator;
69       
70       DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
71         if (parent)
72           parent->addChild(this);
73       }
74       
75       ~DomForestNode() {
76         for (iterator I = begin(), E = end(); I != E; ++I)
77           delete *I;
78       }
79       
80       inline unsigned getReg() { return reg; }
81       
82       inline DomForestNode::iterator begin() { return children.begin(); }
83       inline DomForestNode::iterator end() { return children.end(); }
84     };
85     
86     DenseMap<MachineBasicBlock*, unsigned> preorder;
87     DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
88     
89     DenseMap<MachineBasicBlock*, std::vector<MachineInstr*> > waiting;
90     
91     
92     void computeDFS(MachineFunction& MF);
93     void processBlock(MachineBasicBlock* MBB);
94     
95     std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs);
96     void breakCriticalEdges(MachineFunction &Fn);
97     
98   };
99
100   char StrongPHIElimination::ID = 0;
101   RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
102                   "Eliminate PHI nodes for register allocation, intelligently");
103 }
104
105 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
106
107 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
108 /// of the given MachineFunction.  These numbers are then used in other parts
109 /// of the PHI elimination process.
110 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
111   SmallPtrSet<MachineDomTreeNode*, 8> frontier;
112   SmallPtrSet<MachineDomTreeNode*, 8> visited;
113   
114   unsigned time = 0;
115   
116   MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
117   
118   MachineDomTreeNode* node = DT.getRootNode();
119   
120   std::vector<MachineDomTreeNode*> worklist;
121   worklist.push_back(node);
122   
123   while (!worklist.empty()) {
124     MachineDomTreeNode* currNode = worklist.back();
125     
126     if (!frontier.count(currNode)) {
127       frontier.insert(currNode);
128       ++time;
129       preorder.insert(std::make_pair(currNode->getBlock(), time));
130     }
131     
132     bool inserted = false;
133     for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
134          I != E; ++I)
135       if (!frontier.count(*I) && !visited.count(*I)) {
136         worklist.push_back(*I);
137         inserted = true;
138         break;
139       }
140     
141     if (!inserted) {
142       frontier.erase(currNode);
143       visited.insert(currNode);
144       maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
145       
146       worklist.pop_back();
147     }
148   }
149 }
150
151 /// PreorderSorter - a helper class that is used to sort registers
152 /// according to the preorder number of their defining blocks
153 class PreorderSorter {
154 private:
155   DenseMap<MachineBasicBlock*, unsigned>& preorder;
156   LiveVariables& LV;
157   
158 public:
159   PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
160                 LiveVariables& L) : preorder(p), LV(L) { }
161   
162   bool operator()(unsigned A, unsigned B) {
163     if (A == B)
164       return false;
165     
166     MachineBasicBlock* ABlock = LV.getVarInfo(A).DefInst->getParent();
167     MachineBasicBlock* BBlock = LV.getVarInfo(A).DefInst->getParent();
168     
169     if (preorder[ABlock] < preorder[BBlock])
170       return true;
171     else if (preorder[ABlock] > preorder[BBlock])
172       return false;
173     
174     assert(0 && "Error sorting by dominance!");
175     return false;
176   }
177 };
178
179 /// computeDomForest - compute the subforest of the DomTree corresponding
180 /// to the defining blocks of the registers in question
181 std::vector<StrongPHIElimination::DomForestNode*>
182 StrongPHIElimination::computeDomForest(std::set<unsigned>& regs) {
183   LiveVariables& LV = getAnalysis<LiveVariables>();
184   
185   DomForestNode* VirtualRoot = new DomForestNode(0, 0);
186   maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
187   
188   std::vector<unsigned> worklist;
189   worklist.reserve(regs.size());
190   for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
191        I != E; ++I)
192     worklist.push_back(*I);
193   
194   PreorderSorter PS(preorder, LV);
195   std::sort(worklist.begin(), worklist.end(), PS);
196   
197   DomForestNode* CurrentParent = VirtualRoot;
198   std::vector<DomForestNode*> stack;
199   stack.push_back(VirtualRoot);
200   
201   for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
202        I != E; ++I) {
203     unsigned pre = preorder[LV.getVarInfo(*I).DefInst->getParent()];
204     MachineBasicBlock* parentBlock =
205       LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
206     
207     while (pre > maxpreorder[parentBlock]) {
208       stack.pop_back();
209       CurrentParent = stack.back();
210       
211       parentBlock = LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
212     }
213     
214     DomForestNode* child = new DomForestNode(*I, CurrentParent);
215     stack.push_back(child);
216     CurrentParent = child;
217   }
218   
219   std::vector<DomForestNode*> ret;
220   ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
221   return ret;
222 }
223
224 /// isLiveIn - helper method that determines, from a VarInfo, if a register
225 /// is live into a block
226 bool isLiveIn(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
227   if (V.AliveBlocks.test(MBB->getNumber()))
228     return true;
229   
230   if (V.DefInst->getParent() != MBB &&
231       V.UsedBlocks.test(MBB->getNumber()))
232     return true;
233   
234   return false;
235 }
236
237 /// isLiveOut - help method that determines, from a VarInfo, if a register is
238 /// live out of a block.
239 bool isLiveOut(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
240   if (MBB == V.DefInst->getParent() ||
241       V.UsedBlocks.test(MBB->getNumber())) {
242     for (std::vector<MachineInstr*>::iterator I = V.Kills.begin(), 
243          E = V.Kills.end(); I != E; ++I)
244       if ((*I)->getParent() == MBB)
245         return false;
246     
247     return true;
248   }
249   
250   return false;
251 }
252
253 /// processBlock - Eliminate PHIs in the given block
254 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
255   LiveVariables& LV = getAnalysis<LiveVariables>();
256   
257   // Holds names that have been added to a set in any PHI within this block
258   // before the current one.
259   std::set<unsigned> ProcessedNames;
260   
261   MachineBasicBlock::iterator P = MBB->begin();
262   while (P->getOpcode() == TargetInstrInfo::PHI) {
263     LiveVariables::VarInfo& PHIInfo = LV.getVarInfo(P->getOperand(0).getReg());
264
265     // Hold the names that are currently in the candidate set.
266     std::set<unsigned> PHIUnion;
267     std::set<MachineBasicBlock*> UnionedBlocks;
268   
269     for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
270       unsigned SrcReg = P->getOperand(i-1).getReg();
271       LiveVariables::VarInfo& SrcInfo = LV.getVarInfo(SrcReg);
272     
273       if (isLiveIn(SrcInfo, P->getParent())) {
274         // add a copy from a_i to p in Waiting[From[a_i]]
275       } else if (isLiveOut(PHIInfo, SrcInfo.DefInst->getParent())) {
276         // add a copy to Waiting[From[a_i]]
277       } else if (PHIInfo.DefInst->getOpcode() == TargetInstrInfo::PHI &&
278                  isLiveIn(PHIInfo, SrcInfo.DefInst->getParent())) {
279         // add a copy to Waiting[From[a_i]]
280       } else if (ProcessedNames.count(SrcReg)) {
281         // add a copy to Waiting[From[a_i]]
282       } else if (UnionedBlocks.count(SrcInfo.DefInst->getParent())) {
283         // add a copy to Waiting[From[a_i]]
284       } else {
285         PHIUnion.insert(SrcReg);
286         UnionedBlocks.insert(SrcInfo.DefInst->getParent());
287         
288         // DO STUFF HERE
289         
290       }
291       
292       ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
293     }
294     
295     ++P;
296   }
297 }
298
299 void StrongPHIElimination::breakCriticalEdges(MachineFunction &Fn) {
300   typedef std::pair<MachineBasicBlock*, MachineBasicBlock*> MBB_pair;
301   
302   MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
303   //LiveVariables& LV = getAnalysis<LiveVariables>();
304   
305   std::vector<MBB_pair> criticals;
306   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
307     if (!I->empty() &&
308         I->begin()->getOpcode() == TargetInstrInfo::PHI &&
309         I->pred_size() > 1)
310       for (MachineBasicBlock::pred_iterator PI = I->pred_begin(),
311            PE = I->pred_end(); PI != PE; ++PI)
312         if ((*PI)->succ_size() > 1)
313           criticals.push_back(std::make_pair(*PI, I));
314   
315   for (std::vector<MBB_pair>::iterator I = criticals.begin(),
316        E = criticals.end(); I != E; ++I) {
317     SplitCriticalMachineEdge(I->first, I->second);
318     
319     MDT.splitBlock(I->first);
320   }
321 }
322
323 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
324   breakCriticalEdges(Fn);
325   computeDFS(Fn);
326   
327   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
328     if (!I->empty() &&
329         I->begin()->getOpcode() == TargetInstrInfo::PHI)
330       processBlock(I);
331   
332   return false;
333 }