Fix an infinite recursion bug in InsertCopies.
[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 is distributed under the University of Illinois Open Source
6 // 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/LiveVariables.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/ADT/DepthFirstIterator.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              std::map<unsigned, unsigned> > Waiting;
44     
45     std::map<unsigned, std::vector<unsigned> > Stacks;
46     std::set<unsigned> UsedByAnother;
47     std::map<unsigned, std::set<unsigned> > RenameSets;
48
49     bool runOnMachineFunction(MachineFunction &Fn);
50     
51     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52       AU.addRequired<MachineDominatorTree>();
53       AU.addRequired<LiveVariables>();
54       MachineFunctionPass::getAnalysisUsage(AU);
55     }
56     
57     virtual void releaseMemory() {
58       preorder.clear();
59       maxpreorder.clear();
60       
61       Waiting.clear();
62     }
63
64   private:
65     struct DomForestNode {
66     private:
67       std::vector<DomForestNode*> children;
68       unsigned reg;
69       
70       void addChild(DomForestNode* DFN) { children.push_back(DFN); }
71       
72     public:
73       typedef std::vector<DomForestNode*>::iterator iterator;
74       
75       DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
76         if (parent)
77           parent->addChild(this);
78       }
79       
80       ~DomForestNode() {
81         for (iterator I = begin(), E = end(); I != E; ++I)
82           delete *I;
83       }
84       
85       inline unsigned getReg() { return reg; }
86       
87       inline DomForestNode::iterator begin() { return children.begin(); }
88       inline DomForestNode::iterator end() { return children.end(); }
89     };
90     
91     DenseMap<MachineBasicBlock*, unsigned> preorder;
92     DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
93     
94     
95     void computeDFS(MachineFunction& MF);
96     void processBlock(MachineBasicBlock* MBB);
97     
98     std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs);
99     void processPHIUnion(MachineInstr* Inst,
100                          std::set<unsigned>& PHIUnion,
101                          std::vector<StrongPHIElimination::DomForestNode*>& DF,
102                          std::vector<std::pair<unsigned, unsigned> >& locals);
103     void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
104     void InsertCopies(MachineBasicBlock* MBB, std::set<MachineBasicBlock*>& v);
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     return false;
182   }
183 };
184
185 /// computeDomForest - compute the subforest of the DomTree corresponding
186 /// to the defining blocks of the registers in question
187 std::vector<StrongPHIElimination::DomForestNode*>
188 StrongPHIElimination::computeDomForest(std::set<unsigned>& regs) {
189   LiveVariables& LV = getAnalysis<LiveVariables>();
190   
191   DomForestNode* VirtualRoot = new DomForestNode(0, 0);
192   maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
193   
194   std::vector<unsigned> worklist;
195   worklist.reserve(regs.size());
196   for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
197        I != E; ++I)
198     worklist.push_back(*I);
199   
200   PreorderSorter PS(preorder, LV);
201   std::sort(worklist.begin(), worklist.end(), PS);
202   
203   DomForestNode* CurrentParent = VirtualRoot;
204   std::vector<DomForestNode*> stack;
205   stack.push_back(VirtualRoot);
206   
207   for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
208        I != E; ++I) {
209     unsigned pre = preorder[LV.getVarInfo(*I).DefInst->getParent()];
210     MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
211                  LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent() :
212                  0;
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 static 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 static 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 /// isKillInst - helper method that determines, from a VarInfo, if an 
261 /// instruction kills a given register
262 static bool isKillInst(LiveVariables::VarInfo& V, MachineInstr* MI) {
263   return std::find(V.Kills.begin(), V.Kills.end(), MI) != V.Kills.end();
264 }
265
266 /// interferes - checks for local interferences by scanning a block.  The only
267 /// trick parameter is 'mode' which tells it the relationship of the two
268 /// registers. 0 - defined in the same block, 1 - first properly dominates
269 /// second, 2 - second properly dominates first 
270 static bool interferes(LiveVariables::VarInfo& First, LiveVariables::VarInfo& Second,
271                 MachineBasicBlock* scan, unsigned mode) {
272   MachineInstr* def = 0;
273   MachineInstr* kill = 0;
274   
275   bool interference = false;
276   
277   // Wallk the block, checking for interferences
278   for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
279        MBI != MBE; ++MBI) {
280     MachineInstr* curr = MBI;
281     
282     // Same defining block...
283     if (mode == 0) {
284       if (curr == First.DefInst) {
285         // If we find our first DefInst, save it
286         if (!def) {
287           def = curr;
288         // If there's already an unkilled DefInst, then 
289         // this is an interference
290         } else if (!kill) {
291           interference = true;
292           break;
293         // If there's a DefInst followed by a KillInst, then
294         // they can't interfere
295         } else {
296           interference = false;
297           break;
298         }
299       // Symmetric with the above
300       } else if (curr == Second.DefInst ) {
301         if (!def) {
302           def = curr;
303         } else if (!kill) {
304           interference = true;
305           break;
306         } else {
307           interference = false;
308           break;
309         }
310       // Store KillInsts if they match up with the DefInst
311       } else if (isKillInst(First, curr)) {
312         if (def == First.DefInst) {
313           kill = curr;
314         } else if (isKillInst(Second, curr)) {
315           if (def == Second.DefInst) {
316             kill = curr;
317           }
318         }
319       }
320     // First properly dominates second...
321     } else if (mode == 1) {
322       if (curr == Second.DefInst) {
323         // DefInst of second without kill of first is an interference
324         if (!kill) {
325           interference = true;
326           break;
327         // DefInst after a kill is a non-interference
328         } else {
329           interference = false;
330           break;
331         }
332       // Save KillInsts of First
333       } else if (isKillInst(First, curr)) {
334         kill = curr;
335       }
336     // Symmetric with the above
337     } else if (mode == 2) {
338       if (curr == First.DefInst) {
339         if (!kill) {
340           interference = true;
341           break;
342         } else {
343           interference = false;
344           break;
345         }
346       } else if (isKillInst(Second, curr)) {
347         kill = curr;
348       }
349     }
350   }
351   
352   return interference;
353 }
354
355 /// processBlock - Eliminate PHIs in the given block
356 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
357   LiveVariables& LV = getAnalysis<LiveVariables>();
358   
359   // Holds names that have been added to a set in any PHI within this block
360   // before the current one.
361   std::set<unsigned> ProcessedNames;
362   
363   MachineBasicBlock::iterator P = MBB->begin();
364   while (P->getOpcode() == TargetInstrInfo::PHI) {
365     LiveVariables::VarInfo& PHIInfo = LV.getVarInfo(P->getOperand(0).getReg());
366
367     unsigned DestReg = P->getOperand(0).getReg();
368
369     // Hold the names that are currently in the candidate set.
370     std::set<unsigned> PHIUnion;
371     std::set<MachineBasicBlock*> UnionedBlocks;
372   
373     for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
374       unsigned SrcReg = P->getOperand(i-1).getReg();
375       LiveVariables::VarInfo& SrcInfo = LV.getVarInfo(SrcReg);
376     
377       // Check for trivial interferences
378       if (isLiveIn(SrcInfo, P->getParent()) ||
379           isLiveOut(PHIInfo, SrcInfo.DefInst->getParent()) ||
380           ( PHIInfo.DefInst->getOpcode() == TargetInstrInfo::PHI &&
381             isLiveIn(PHIInfo, SrcInfo.DefInst->getParent()) ) ||
382           ProcessedNames.count(SrcReg) ||
383           UnionedBlocks.count(SrcInfo.DefInst->getParent())) {
384         
385         // add a copy from a_i to p in Waiting[From[a_i]]
386         MachineBasicBlock* From = P->getOperand(i).getMBB();
387         Waiting[From].insert(std::make_pair(SrcReg, DestReg));
388         UsedByAnother.insert(SrcReg);
389       } else {
390         PHIUnion.insert(SrcReg);
391         UnionedBlocks.insert(SrcInfo.DefInst->getParent());
392       }
393     }
394     
395     std::vector<StrongPHIElimination::DomForestNode*> DF = 
396                                                      computeDomForest(PHIUnion);
397     
398     // Walk DomForest to resolve interferences
399     std::vector<std::pair<unsigned, unsigned> > localInterferences;
400     processPHIUnion(P, PHIUnion, DF, localInterferences);
401     
402     // Check for local interferences
403     for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
404         localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
405       std::pair<unsigned, unsigned> p = *I;
406       
407       LiveVariables::VarInfo& FirstInfo = LV.getVarInfo(p.first);
408       LiveVariables::VarInfo& SecondInfo = LV.getVarInfo(p.second);
409       
410       MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
411       
412       // Determine the block we need to scan and the relationship between
413       // the two registers
414       MachineBasicBlock* scan = 0;
415       unsigned mode = 0;
416       if (FirstInfo.DefInst->getParent() == SecondInfo.DefInst->getParent()) {
417         scan = FirstInfo.DefInst->getParent();
418         mode = 0; // Same block
419       } else if (MDT.dominates(FirstInfo.DefInst->getParent(),
420                              SecondInfo.DefInst->getParent())) {
421         scan = SecondInfo.DefInst->getParent();
422         mode = 1; // First dominates second
423       } else {
424         scan = FirstInfo.DefInst->getParent();
425         mode = 2; // Second dominates first
426       }
427       
428       // If there's an interference, we need to insert  copies
429       if (interferes(FirstInfo, SecondInfo, scan, mode)) {
430         // Insert copies for First
431         for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
432           if (P->getOperand(i-1).getReg() == p.first) {
433             unsigned SrcReg = p.first;
434             MachineBasicBlock* From = P->getOperand(i).getMBB();
435             
436             Waiting[From].insert(std::make_pair(SrcReg,
437                                                 P->getOperand(0).getReg()));
438             UsedByAnother.insert(SrcReg);
439             
440             PHIUnion.erase(SrcReg);
441           }
442         }
443       }
444     }
445     
446     // Cache renaming information
447     RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
448     
449     ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
450     ++P;
451   }
452 }
453
454 /// processPHIUnion - Take a set of candidate registers to be coallesced when
455 /// decomposing the PHI instruction.  Use the DominanceForest to remove the ones
456 /// that are known to interfere, and flag others that need to be checked for
457 /// local interferences.
458 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
459                                            std::set<unsigned>& PHIUnion,
460                         std::vector<StrongPHIElimination::DomForestNode*>& DF,
461                         std::vector<std::pair<unsigned, unsigned> >& locals) {
462   
463   std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
464   SmallPtrSet<DomForestNode*, 4> visited;
465   
466   LiveVariables& LV = getAnalysis<LiveVariables>();
467   unsigned DestReg = Inst->getOperand(0).getReg();
468   
469   // DF walk on the DomForest
470   while (!worklist.empty()) {
471     DomForestNode* DFNode = worklist.back();
472     
473     LiveVariables::VarInfo& Info = LV.getVarInfo(DFNode->getReg());
474     visited.insert(DFNode);
475     
476     bool inserted = false;
477     for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
478          CI != CE; ++CI) {
479       DomForestNode* child = *CI;   
480       LiveVariables::VarInfo& CInfo = LV.getVarInfo(child->getReg());
481         
482       if (isLiveOut(Info, CInfo.DefInst->getParent())) {
483         // Insert copies for parent
484         for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
485           if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
486             unsigned SrcReg = DFNode->getReg();
487             MachineBasicBlock* From = Inst->getOperand(i).getMBB();
488             
489             Waiting[From].insert(std::make_pair(SrcReg, DestReg));
490             UsedByAnother.insert(SrcReg);
491             
492             PHIUnion.erase(SrcReg);
493           }
494         }
495       } else if (isLiveIn(Info, CInfo.DefInst->getParent()) ||
496                  Info.DefInst->getParent() == CInfo.DefInst->getParent()) {
497         // Add (p, c) to possible local interferences
498         locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
499       }
500       
501       if (!visited.count(child)) {
502         worklist.push_back(child);
503         inserted = true;
504       }
505     }
506     
507     if (!inserted) worklist.pop_back();
508   }
509 }
510
511 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
512 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
513 /// problems.
514 ///
515 /// Based on "Practical Improvements to the Construction and Destruction
516 /// of Static Single Assignment Form" by Briggs, et al.
517 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
518                                           std::set<unsigned>& pushed) {
519   // FIXME: This function needs to update LiveVariables
520   std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
521   
522   std::map<unsigned, unsigned> worklist;
523   std::map<unsigned, unsigned> map;
524   
525   // Setup worklist of initial copies
526   for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
527        E = copy_set.end(); I != E; ) {
528     map.insert(std::make_pair(I->first, I->first));
529     map.insert(std::make_pair(I->second, I->second));
530          
531     if (!UsedByAnother.count(I->first)) {
532       worklist.insert(*I);
533       
534       // Avoid iterator invalidation
535       unsigned first = I->first;
536       ++I;
537       copy_set.erase(first);
538     } else {
539       ++I;
540     }
541   }
542   
543   LiveVariables& LV = getAnalysis<LiveVariables>();
544   MachineFunction* MF = MBB->getParent();
545   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
546   
547   // Iterate over the worklist, inserting copies
548   while (!worklist.empty() || !copy_set.empty()) {
549     while (!worklist.empty()) {
550       std::pair<unsigned, unsigned> curr = *worklist.begin();
551       worklist.erase(curr.first);
552       
553       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
554       
555       if (isLiveOut(LV.getVarInfo(curr.second), MBB)) {
556         // Create a temporary
557         unsigned t = MF->getRegInfo().createVirtualRegister(RC);
558         
559         // Insert copy from curr.second to a temporary at
560         // the Phi defining curr.second
561         LiveVariables::VarInfo VI = LV.getVarInfo(curr.second);
562         MachineBasicBlock::iterator PI = VI.DefInst;
563         TII->copyRegToReg(*VI.DefInst->getParent(), PI, t,
564                           curr.second, RC, RC);
565         
566         // Push temporary on Stacks
567         Stacks[curr.second].push_back(t);
568         
569         // Insert curr.second in pushed
570         pushed.insert(curr.second);
571       }
572       
573       // Insert copy from map[curr.first] to curr.second
574       TII->copyRegToReg(*MBB, MBB->end(), curr.second,
575                         map[curr.first], RC, RC);
576       map[curr.first] = curr.second;
577       
578       // If curr.first is a destination in copy_set...
579       for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
580            E = copy_set.end(); I != E; )
581         if (curr.first == I->second) {
582           std::pair<unsigned, unsigned> temp = *I;
583           
584           // Avoid iterator invalidation
585           ++I;
586           copy_set.erase(temp.first);
587           worklist.insert(temp);
588           
589           break;
590         } else {
591           ++I;
592         }
593     }
594     
595     if (!copy_set.empty()) {
596       std::pair<unsigned, unsigned> curr = *copy_set.begin();
597       copy_set.erase(curr.first);
598       
599       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
600       
601       // Insert a copy from dest to a new temporary t at the end of b
602       unsigned t = MF->getRegInfo().createVirtualRegister(RC);
603       TII->copyRegToReg(*MBB, MBB->end(), t,
604                         curr.second, RC, RC);
605       map[curr.second] = t;
606       
607       worklist.insert(curr);
608     }
609   }
610 }
611
612 /// InsertCopies - insert copies into MBB and all of its successors
613 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
614                                         std::set<MachineBasicBlock*>& visited) {
615   visited.insert(MBB);
616   
617   std::set<unsigned> pushed;
618   
619   // Rewrite register uses from Stacks
620   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
621       I != E; ++I)
622     for (unsigned i = 0; i < I->getNumOperands(); ++i)
623       if (I->getOperand(i).isRegister() &&
624           Stacks[I->getOperand(i).getReg()].size()) {
625         I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
626       }
627   
628   // Schedule the copies for this block
629   ScheduleCopies(MBB, pushed);
630   
631   // Recur to our successors
632   for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I = 
633        GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
634        GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
635     if (!visited.count(*I))
636       InsertCopies(*I, visited);
637   
638   // As we exit this block, pop the names we pushed while processing it
639   for (std::set<unsigned>::iterator I = pushed.begin(), 
640        E = pushed.end(); I != E; ++I)
641     Stacks[*I].pop_back();
642 }
643
644 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
645   // Compute DFS numbers of each block
646   computeDFS(Fn);
647   
648   // Determine which phi node operands need copies
649   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
650     if (!I->empty() &&
651         I->begin()->getOpcode() == TargetInstrInfo::PHI)
652       processBlock(I);
653   
654   // Insert copies
655   // FIXME: This process should probably preserve LiveVariables
656   std::set<MachineBasicBlock*> visited;
657   InsertCopies(Fn.begin(), visited);
658   
659   // Perform renaming
660   typedef std::map<unsigned, std::set<unsigned> > RenameSetType;
661   for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
662        I != E; ++I)
663     for (std::set<unsigned>::iterator SI = I->second.begin(),
664          SE = I->second.end(); SI != SE; ++SI)
665       Fn.getRegInfo().replaceRegWith(*SI, I->first);
666   
667   // FIXME: Insert last-minute copies
668   
669   // Remove PHIs
670   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
671     for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
672          BI != BE; ++BI)
673       if (BI->getOpcode() == TargetInstrInfo::PHI)
674         BI->eraseFromParent();
675   
676   return false;
677 }