9519e7c9d7ed545efa1d9f03869158539036a75a
[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/CodeGen/SSARegMap.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Compiler.h"
34 using namespace llvm;
35
36
37 namespace {
38   struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
39     static char ID; // Pass identification, replacement for typeid
40     StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
41
42     DenseMap<MachineBasicBlock*,
43              SmallVector<std::pair<unsigned, unsigned>, 2> > Waiting;
44
45     bool runOnMachineFunction(MachineFunction &Fn);
46     
47     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48       AU.addPreserved<LiveVariables>();
49       AU.addPreservedID(PHIEliminationID);
50       AU.addRequired<MachineDominatorTree>();
51       AU.addRequired<LiveVariables>();
52       AU.setPreservesAll();
53       MachineFunctionPass::getAnalysisUsage(AU);
54     }
55     
56     virtual void releaseMemory() {
57       preorder.clear();
58       maxpreorder.clear();
59       
60       waiting.clear();
61     }
62
63   private:
64     struct DomForestNode {
65     private:
66       std::vector<DomForestNode*> children;
67       unsigned reg;
68       
69       void addChild(DomForestNode* DFN) { children.push_back(DFN); }
70       
71     public:
72       typedef std::vector<DomForestNode*>::iterator iterator;
73       
74       DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
75         if (parent)
76           parent->addChild(this);
77       }
78       
79       ~DomForestNode() {
80         for (iterator I = begin(), E = end(); I != E; ++I)
81           delete *I;
82       }
83       
84       inline unsigned getReg() { return reg; }
85       
86       inline DomForestNode::iterator begin() { return children.begin(); }
87       inline DomForestNode::iterator end() { return children.end(); }
88     };
89     
90     DenseMap<MachineBasicBlock*, unsigned> preorder;
91     DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
92     
93     DenseMap<MachineBasicBlock*, std::vector<MachineInstr*> > waiting;
94     
95     
96     void computeDFS(MachineFunction& MF);
97     void processBlock(MachineBasicBlock* MBB);
98     
99     std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs);
100     void processPHIUnion(MachineInstr* Inst,
101                          std::set<unsigned>& PHIUnion,
102                          std::vector<StrongPHIElimination::DomForestNode*>& DF);
103     void breakCriticalEdges(MachineFunction &Fn);
104     
105   };
106
107   char StrongPHIElimination::ID = 0;
108   RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
109                   "Eliminate PHI nodes for register allocation, intelligently");
110 }
111
112 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
113
114 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
115 /// of the given MachineFunction.  These numbers are then used in other parts
116 /// of the PHI elimination process.
117 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
118   SmallPtrSet<MachineDomTreeNode*, 8> frontier;
119   SmallPtrSet<MachineDomTreeNode*, 8> visited;
120   
121   unsigned time = 0;
122   
123   MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
124   
125   MachineDomTreeNode* node = DT.getRootNode();
126   
127   std::vector<MachineDomTreeNode*> worklist;
128   worklist.push_back(node);
129   
130   while (!worklist.empty()) {
131     MachineDomTreeNode* currNode = worklist.back();
132     
133     if (!frontier.count(currNode)) {
134       frontier.insert(currNode);
135       ++time;
136       preorder.insert(std::make_pair(currNode->getBlock(), time));
137     }
138     
139     bool inserted = false;
140     for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
141          I != E; ++I)
142       if (!frontier.count(*I) && !visited.count(*I)) {
143         worklist.push_back(*I);
144         inserted = true;
145         break;
146       }
147     
148     if (!inserted) {
149       frontier.erase(currNode);
150       visited.insert(currNode);
151       maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
152       
153       worklist.pop_back();
154     }
155   }
156 }
157
158 /// PreorderSorter - a helper class that is used to sort registers
159 /// according to the preorder number of their defining blocks
160 class PreorderSorter {
161 private:
162   DenseMap<MachineBasicBlock*, unsigned>& preorder;
163   LiveVariables& LV;
164   
165 public:
166   PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
167                 LiveVariables& L) : preorder(p), LV(L) { }
168   
169   bool operator()(unsigned A, unsigned B) {
170     if (A == B)
171       return false;
172     
173     MachineBasicBlock* ABlock = LV.getVarInfo(A).DefInst->getParent();
174     MachineBasicBlock* BBlock = LV.getVarInfo(A).DefInst->getParent();
175     
176     if (preorder[ABlock] < preorder[BBlock])
177       return true;
178     else if (preorder[ABlock] > preorder[BBlock])
179       return false;
180     
181     assert(0 && "Error sorting by dominance!");
182     return false;
183   }
184 };
185
186 /// computeDomForest - compute the subforest of the DomTree corresponding
187 /// to the defining blocks of the registers in question
188 std::vector<StrongPHIElimination::DomForestNode*>
189 StrongPHIElimination::computeDomForest(std::set<unsigned>& regs) {
190   LiveVariables& LV = getAnalysis<LiveVariables>();
191   
192   DomForestNode* VirtualRoot = new DomForestNode(0, 0);
193   maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
194   
195   std::vector<unsigned> worklist;
196   worklist.reserve(regs.size());
197   for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
198        I != E; ++I)
199     worklist.push_back(*I);
200   
201   PreorderSorter PS(preorder, LV);
202   std::sort(worklist.begin(), worklist.end(), PS);
203   
204   DomForestNode* CurrentParent = VirtualRoot;
205   std::vector<DomForestNode*> stack;
206   stack.push_back(VirtualRoot);
207   
208   for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
209        I != E; ++I) {
210     unsigned pre = preorder[LV.getVarInfo(*I).DefInst->getParent()];
211     MachineBasicBlock* parentBlock =
212       LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
213     
214     while (pre > maxpreorder[parentBlock]) {
215       stack.pop_back();
216       CurrentParent = stack.back();
217       
218       parentBlock = LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
219     }
220     
221     DomForestNode* child = new DomForestNode(*I, CurrentParent);
222     stack.push_back(child);
223     CurrentParent = child;
224   }
225   
226   std::vector<DomForestNode*> ret;
227   ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
228   return ret;
229 }
230
231 /// isLiveIn - helper method that determines, from a VarInfo, if a register
232 /// is live into a block
233 bool isLiveIn(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
234   if (V.AliveBlocks.test(MBB->getNumber()))
235     return true;
236   
237   if (V.DefInst->getParent() != MBB &&
238       V.UsedBlocks.test(MBB->getNumber()))
239     return true;
240   
241   return false;
242 }
243
244 /// isLiveOut - help method that determines, from a VarInfo, if a register is
245 /// live out of a block.
246 bool isLiveOut(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
247   if (MBB == V.DefInst->getParent() ||
248       V.UsedBlocks.test(MBB->getNumber())) {
249     for (std::vector<MachineInstr*>::iterator I = V.Kills.begin(), 
250          E = V.Kills.end(); I != E; ++I)
251       if ((*I)->getParent() == MBB)
252         return false;
253     
254     return true;
255   }
256   
257   return false;
258 }
259
260 /// processBlock - Eliminate PHIs in the given block
261 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
262   LiveVariables& LV = getAnalysis<LiveVariables>();
263   
264   // Holds names that have been added to a set in any PHI within this block
265   // before the current one.
266   std::set<unsigned> ProcessedNames;
267   
268   MachineBasicBlock::iterator P = MBB->begin();
269   while (P->getOpcode() == TargetInstrInfo::PHI) {
270     LiveVariables::VarInfo& PHIInfo = LV.getVarInfo(P->getOperand(0).getReg());
271
272     unsigned DestReg = P->getOperand(0).getReg();
273
274     // Hold the names that are currently in the candidate set.
275     std::set<unsigned> PHIUnion;
276     std::set<MachineBasicBlock*> UnionedBlocks;
277   
278     for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
279       unsigned SrcReg = P->getOperand(i-1).getReg();
280       LiveVariables::VarInfo& SrcInfo = LV.getVarInfo(SrcReg);
281     
282       // Check for trivial interferences
283       if (isLiveIn(SrcInfo, P->getParent()) ||
284           isLiveOut(PHIInfo, SrcInfo.DefInst->getParent()) ||
285           ( PHIInfo.DefInst->getOpcode() == TargetInstrInfo::PHI &&
286             isLiveIn(PHIInfo, SrcInfo.DefInst->getParent()) ) ||
287           ProcessedNames.count(SrcReg) ||
288           UnionedBlocks.count(SrcInfo.DefInst->getParent())) {
289         
290         // add a copy from a_i to p in Waiting[From[a_i]]
291         MachineBasicBlock* From = P->getOperand(i).getMachineBasicBlock();
292         Waiting[From].push_back(std::make_pair(SrcReg, DestReg));
293       } else {
294         PHIUnion.insert(SrcReg);
295         UnionedBlocks.insert(SrcInfo.DefInst->getParent());
296       }
297     }
298     
299     std::vector<StrongPHIElimination::DomForestNode*> DF = 
300                                                      computeDomForest(PHIUnion);
301     
302     // Walk DomForest to resolve interferences
303     
304     ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
305     ++P;
306   }
307 }
308
309 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
310                                            std::set<unsigned>& PHIUnion,
311                         std::vector<StrongPHIElimination::DomForestNode*>& DF) {
312   
313   std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
314   SmallPtrSet<DomForestNode*, 4> visited;
315   
316   LiveVariables& LV = getAnalysis<LiveVariables>();
317   unsigned DestReg = Inst->getOperand(0).getReg();
318   
319   while (!worklist.empty()) {
320     DomForestNode* DFNode = worklist.back();
321     
322     LiveVariables::VarInfo& Info = LV.getVarInfo(DFNode->getReg());
323     visited.insert(DFNode);
324     
325     bool inserted = false;
326     SmallPtrSet<DomForestNode*, 4> interferences;
327     for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
328          CI != CE; ++CI) {
329       DomForestNode* child = *CI;   
330       LiveVariables::VarInfo& CInfo = LV.getVarInfo(child->getReg());
331         
332       if (isLiveOut(Info, CInfo.DefInst->getParent())) {
333         interferences.insert(child);
334       } else if (isLiveIn(Info, CInfo.DefInst->getParent()) ||
335                  Info.DefInst->getParent() == CInfo.DefInst->getParent()) {
336         // FIXME: Add (p, c) to possible local interferences
337       }
338         
339       if (!visited.count(child)) {
340         worklist.push_back(child);
341         inserted = true;
342       }
343     }
344     
345     if (interferences.size() == 1) {
346       DomForestNode* child = *interferences.begin();
347       
348       unsigned numParentCopies = 0;
349       unsigned numChildCopies = 0;
350       for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
351         unsigned SrcReg = Inst->getOperand(i-1).getReg();
352         if (SrcReg == DFNode->getReg()) numParentCopies++;
353         else if (SrcReg == child->getReg()) numChildCopies++;
354       }
355       
356       if (numParentCopies < numChildCopies) {
357         // Insert copies for child
358         for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
359           if (Inst->getOperand(i-1).getReg() == child->getReg()) {
360             unsigned SrcReg = child->getReg();
361             MachineBasicBlock* From = Inst->getOperand(i).getMBB();
362             
363             Waiting[From].push_back(std::make_pair(SrcReg, DestReg));
364             PHIUnion.erase(SrcReg);
365           }
366         }
367         
368         // FIXME: Make child's children parent's children
369       } else {
370         // Insert copies for parent
371         for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
372           if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
373             unsigned SrcReg = DFNode->getReg();
374             MachineBasicBlock* From = Inst->getOperand(i).getMBB();
375             
376             Waiting[From].push_back(std::make_pair(SrcReg, DestReg));
377             PHIUnion.erase(SrcReg);
378           }
379         }
380       }
381     } else if (interferences.size() > 1) {
382       // Insert copies for parent
383       for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
384         if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
385           unsigned SrcReg = DFNode->getReg();
386           MachineBasicBlock* From = Inst->getOperand(i).getMBB();
387           
388           Waiting[From].push_back(std::make_pair(SrcReg, DestReg));
389           PHIUnion.erase(SrcReg);
390         }
391       }
392     }
393     
394     if (!inserted) worklist.pop_back();
395   }
396 }
397
398 /// breakCriticalEdges - Break critical edges coming into blocks with PHI
399 /// nodes, preserving dominator and livevariable info.
400 void StrongPHIElimination::breakCriticalEdges(MachineFunction &Fn) {
401   typedef std::pair<MachineBasicBlock*, MachineBasicBlock*> MBB_pair;
402   
403   MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
404   LiveVariables& LV = getAnalysis<LiveVariables>();
405   
406   // Find critical edges
407   std::vector<MBB_pair> criticals;
408   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
409     if (!I->empty() &&
410         I->begin()->getOpcode() == TargetInstrInfo::PHI &&
411         I->pred_size() > 1)
412       for (MachineBasicBlock::pred_iterator PI = I->pred_begin(),
413            PE = I->pred_end(); PI != PE; ++PI)
414         if ((*PI)->succ_size() > 1)
415           criticals.push_back(std::make_pair(*PI, I));
416   
417   for (std::vector<MBB_pair>::iterator I = criticals.begin(),
418        E = criticals.end(); I != E; ++I) {
419     // Split the edge
420     MachineBasicBlock* new_bb = SplitCriticalMachineEdge(I->first, I->second);
421     
422     // Update dominators
423     MDT.splitBlock(I->first);
424     
425     // Update livevariables
426     for (unsigned var = 1024; var < Fn.getSSARegMap()->getLastVirtReg(); ++var)
427       if (isLiveOut(LV.getVarInfo(var), I->first))
428         LV.getVarInfo(var).AliveBlocks.set(new_bb->getNumber());
429   }
430 }
431
432 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
433   breakCriticalEdges(Fn);
434   computeDFS(Fn);
435   
436   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
437     if (!I->empty() &&
438         I->begin()->getOpcode() == TargetInstrInfo::PHI)
439       processBlock(I);
440   
441   return false;
442 }