Constant fold SIGN_EXTEND_INREG with ashr not lshr.
[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     // Waiting stores, for each MBB, the set of copies that need to
43     // be inserted into that MBB
44     DenseMap<MachineBasicBlock*,
45              std::map<unsigned, unsigned> > Waiting;
46     
47     // Stacks holds the renaming stack for each register
48     std::map<unsigned, std::vector<unsigned> > Stacks;
49     
50     // Registers in UsedByAnother are PHI nodes that are themselves
51     // used as operands to another another PHI node
52     std::set<unsigned> UsedByAnother;
53     
54     // RenameSets are the sets of operands to a PHI (the defining instruction
55     // of the key) that can be renamed without copies
56     std::map<unsigned, std::set<unsigned> > RenameSets;
57
58     // Store the DFS-in number of each block
59     DenseMap<MachineBasicBlock*, unsigned> preorder;
60     
61     // Store the DFS-out number of each block
62     DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
63
64     bool runOnMachineFunction(MachineFunction &Fn);
65     
66     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67       AU.addRequired<MachineDominatorTree>();
68       AU.addRequired<LiveVariables>();
69       MachineFunctionPass::getAnalysisUsage(AU);
70     }
71     
72     virtual void releaseMemory() {
73       preorder.clear();
74       maxpreorder.clear();
75       
76       Waiting.clear();
77       Stacks.clear();
78       UsedByAnother.clear();
79       RenameSets.clear();
80     }
81
82   private:
83     
84     /// DomForestNode - Represents a node in the "dominator forest".  This is
85     /// a forest in which the nodes represent registers and the edges
86     /// represent a dominance relation in the block defining those registers.
87     struct DomForestNode {
88     private:
89       // Store references to our children
90       std::vector<DomForestNode*> children;
91       // The register we represent
92       unsigned reg;
93       
94       // Add another node as our child
95       void addChild(DomForestNode* DFN) { children.push_back(DFN); }
96       
97     public:
98       typedef std::vector<DomForestNode*>::iterator iterator;
99       
100       // Create a DomForestNode by providing the register it represents, and
101       // the node to be its parent.  The virtual root node has register 0
102       // and a null parent.
103       DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
104         if (parent)
105           parent->addChild(this);
106       }
107       
108       ~DomForestNode() {
109         for (iterator I = begin(), E = end(); I != E; ++I)
110           delete *I;
111       }
112       
113       /// getReg - Return the regiser that this node represents
114       inline unsigned getReg() { return reg; }
115       
116       // Provide iterator access to our children
117       inline DomForestNode::iterator begin() { return children.begin(); }
118       inline DomForestNode::iterator end() { return children.end(); }
119     };
120     
121     void computeDFS(MachineFunction& MF);
122     void processBlock(MachineBasicBlock* MBB);
123     
124     std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs,
125                                                  MachineRegisterInfo& MRI);
126     void processPHIUnion(MachineInstr* Inst,
127                          std::set<unsigned>& PHIUnion,
128                          std::vector<StrongPHIElimination::DomForestNode*>& DF,
129                          std::vector<std::pair<unsigned, unsigned> >& locals);
130     void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
131     void InsertCopies(MachineBasicBlock* MBB, std::set<MachineBasicBlock*>& v);
132   };
133
134   char StrongPHIElimination::ID = 0;
135   RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
136                   "Eliminate PHI nodes for register allocation, intelligently");
137 }
138
139 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
140
141 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
142 /// of the given MachineFunction.  These numbers are then used in other parts
143 /// of the PHI elimination process.
144 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
145   SmallPtrSet<MachineDomTreeNode*, 8> frontier;
146   SmallPtrSet<MachineDomTreeNode*, 8> visited;
147   
148   unsigned time = 0;
149   
150   MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
151   
152   MachineDomTreeNode* node = DT.getRootNode();
153   
154   std::vector<MachineDomTreeNode*> worklist;
155   worklist.push_back(node);
156   
157   while (!worklist.empty()) {
158     MachineDomTreeNode* currNode = worklist.back();
159     
160     if (!frontier.count(currNode)) {
161       frontier.insert(currNode);
162       ++time;
163       preorder.insert(std::make_pair(currNode->getBlock(), time));
164     }
165     
166     bool inserted = false;
167     for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
168          I != E; ++I)
169       if (!frontier.count(*I) && !visited.count(*I)) {
170         worklist.push_back(*I);
171         inserted = true;
172         break;
173       }
174     
175     if (!inserted) {
176       frontier.erase(currNode);
177       visited.insert(currNode);
178       maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
179       
180       worklist.pop_back();
181     }
182   }
183 }
184
185 /// PreorderSorter - a helper class that is used to sort registers
186 /// according to the preorder number of their defining blocks
187 class PreorderSorter {
188 private:
189   DenseMap<MachineBasicBlock*, unsigned>& preorder;
190   MachineRegisterInfo& MRI;
191   
192 public:
193   PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
194                 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
195   
196   bool operator()(unsigned A, unsigned B) {
197     if (A == B)
198       return false;
199     
200     MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
201     MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
202     
203     if (preorder[ABlock] < preorder[BBlock])
204       return true;
205     else if (preorder[ABlock] > preorder[BBlock])
206       return false;
207     
208     return false;
209   }
210 };
211
212 /// computeDomForest - compute the subforest of the DomTree corresponding
213 /// to the defining blocks of the registers in question
214 std::vector<StrongPHIElimination::DomForestNode*>
215 StrongPHIElimination::computeDomForest(std::set<unsigned>& regs, 
216                                        MachineRegisterInfo& MRI) {
217   // Begin by creating a virtual root node, since the actual results
218   // may well be a forest.  Assume this node has maximum DFS-out number.
219   DomForestNode* VirtualRoot = new DomForestNode(0, 0);
220   maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
221   
222   // Populate a worklist with the registers
223   std::vector<unsigned> worklist;
224   worklist.reserve(regs.size());
225   for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
226        I != E; ++I)
227     worklist.push_back(*I);
228   
229   // Sort the registers by the DFS-in number of their defining block
230   PreorderSorter PS(preorder, MRI);
231   std::sort(worklist.begin(), worklist.end(), PS);
232   
233   // Create a "current parent" stack, and put the virtual root on top of it
234   DomForestNode* CurrentParent = VirtualRoot;
235   std::vector<DomForestNode*> stack;
236   stack.push_back(VirtualRoot);
237   
238   // Iterate over all the registers in the previously computed order
239   for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
240        I != E; ++I) {
241     unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
242     MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
243                  MRI.getVRegDef(CurrentParent->getReg())->getParent() :
244                  0;
245     
246     // If the DFS-in number of the register is greater than the DFS-out number
247     // of the current parent, repeatedly pop the parent stack until it isn't.
248     while (pre > maxpreorder[parentBlock]) {
249       stack.pop_back();
250       CurrentParent = stack.back();
251       
252       parentBlock = CurrentParent->getReg() ?
253                    MRI.getVRegDef(CurrentParent->getReg())->getParent() :
254                    0;
255     }
256     
257     // Now that we've found the appropriate parent, create a DomForestNode for
258     // this register and attach it to the forest
259     DomForestNode* child = new DomForestNode(*I, CurrentParent);
260     
261     // Push this new node on the "current parent" stack
262     stack.push_back(child);
263     CurrentParent = child;
264   }
265   
266   // Return a vector containing the children of the virtual root node
267   std::vector<DomForestNode*> ret;
268   ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
269   return ret;
270 }
271
272 /// isLiveIn - helper method that determines, from a VarInfo, if a register
273 /// is live into a block
274 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
275                      MachineRegisterInfo& MRI, LiveVariables& LV) {
276   LiveVariables::VarInfo V = LV.getVarInfo(r);
277   if (V.AliveBlocks.test(MBB->getNumber()))
278     return true;
279   
280   if (MRI.getVRegDef(r)->getParent() != MBB &&
281       V.UsedBlocks.test(MBB->getNumber()))
282     return true;
283   
284   return false;
285 }
286
287 /// isLiveOut - help method that determines, from a VarInfo, if a register is
288 /// live out of a block.
289 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
290                       MachineRegisterInfo& MRI, LiveVariables& LV) {
291   LiveVariables::VarInfo& V = LV.getVarInfo(r);
292   if (MBB == MRI.getVRegDef(r)->getParent() ||
293       V.UsedBlocks.test(MBB->getNumber())) {
294     for (std::vector<MachineInstr*>::iterator I = V.Kills.begin(), 
295          E = V.Kills.end(); I != E; ++I)
296       if ((*I)->getParent() == MBB)
297         return false;
298     
299     return true;
300   }
301   
302   return false;
303 }
304
305 /// interferes - checks for local interferences by scanning a block.  The only
306 /// trick parameter is 'mode' which tells it the relationship of the two
307 /// registers. 0 - defined in the same block, 1 - first properly dominates
308 /// second, 2 - second properly dominates first 
309 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
310                        LiveVariables& LV, unsigned mode) {
311   MachineInstr* def = 0;
312   MachineInstr* kill = 0;
313   
314   // The code is still in SSA form at this point, so there is only one
315   // definition per VReg.  Thus we can safely use MRI->getVRegDef().
316   const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
317   
318   bool interference = false;
319   
320   // Wallk the block, checking for interferences
321   for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
322        MBI != MBE; ++MBI) {
323     MachineInstr* curr = MBI;
324     
325     // Same defining block...
326     if (mode == 0) {
327       if (curr == MRI->getVRegDef(a)) {
328         // If we find our first definition, save it
329         if (!def) {
330           def = curr;
331         // If there's already an unkilled definition, then 
332         // this is an interference
333         } else if (!kill) {
334           interference = true;
335           break;
336         // If there's a definition followed by a KillInst, then
337         // they can't interfere
338         } else {
339           interference = false;
340           break;
341         }
342       // Symmetric with the above
343       } else if (curr == MRI->getVRegDef(b)) {
344         if (!def) {
345           def = curr;
346         } else if (!kill) {
347           interference = true;
348           break;
349         } else {
350           interference = false;
351           break;
352         }
353       // Store KillInsts if they match up with the definition
354       } else if (curr->killsRegister(a)) {
355         if (def == MRI->getVRegDef(a)) {
356           kill = curr;
357         } else if (curr->killsRegister(b)) {
358           if (def == MRI->getVRegDef(b)) {
359             kill = curr;
360           }
361         }
362       }
363     // First properly dominates second...
364     } else if (mode == 1) {
365       if (curr == MRI->getVRegDef(b)) {
366         // Definition of second without kill of first is an interference
367         if (!kill) {
368           interference = true;
369           break;
370         // Definition after a kill is a non-interference
371         } else {
372           interference = false;
373           break;
374         }
375       // Save KillInsts of First
376       } else if (curr->killsRegister(a)) {
377         kill = curr;
378       }
379     // Symmetric with the above
380     } else if (mode == 2) {
381       if (curr == MRI->getVRegDef(a)) {
382         if (!kill) {
383           interference = true;
384           break;
385         } else {
386           interference = false;
387           break;
388         }
389       } else if (curr->killsRegister(b)) {
390         kill = curr;
391       }
392     }
393   }
394   
395   return interference;
396 }
397
398 /// processBlock - Determine how to break up PHIs in the current block.  Each
399 /// PHI is broken up by some combination of renaming its operands and inserting
400 /// copies.  This method is responsible for determining which operands receive
401 /// which treatment.
402 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
403   LiveVariables& LV = getAnalysis<LiveVariables>();
404   MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
405   
406   // Holds names that have been added to a set in any PHI within this block
407   // before the current one.
408   std::set<unsigned> ProcessedNames;
409   
410   // Iterate over all the PHI nodes in this block
411   MachineBasicBlock::iterator P = MBB->begin();
412   while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
413     unsigned DestReg = P->getOperand(0).getReg();
414
415     // PHIUnion is the set of incoming registers to the PHI node that
416     // are going to be renames rather than having copies inserted.  This set
417     // is refinded over the course of this function.  UnionedBlocks is the set
418     // of corresponding MBBs.
419     std::set<unsigned> PHIUnion;
420     std::set<MachineBasicBlock*> UnionedBlocks;
421   
422     // Iterate over the operands of the PHI node
423     for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
424       unsigned SrcReg = P->getOperand(i-1).getReg();
425     
426       // Check for trivial interferences via liveness information, allowing us
427       // to avoid extra work later.  Any registers that interfere cannot both
428       // be in the renaming set, so choose one and add copies for it instead.
429       // The conditions are:
430       //   1) if the operand is live into the PHI node's block OR
431       //   2) if the PHI node is live out of the operand's defining block OR
432       //   3) if the operand is itself a PHI node and the original PHI is
433       //      live into the operand's defining block OR
434       //   4) if the operand is already being renamed for another PHI node
435       //      in this block OR
436       //   5) if any two operands are defined in the same block, insert copies
437       //      for one of them
438       if (isLiveIn(SrcReg, P->getParent(), MRI, LV) ||
439           isLiveOut(P->getOperand(0).getReg(),
440                     MRI.getVRegDef(SrcReg)->getParent(), MRI, LV) ||
441           ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
442             isLiveIn(P->getOperand(0).getReg(),
443                      MRI.getVRegDef(SrcReg)->getParent(), MRI, LV) ) ||
444           ProcessedNames.count(SrcReg) ||
445           UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
446         
447         // Add a copy for the selected register
448         MachineBasicBlock* From = P->getOperand(i).getMBB();
449         Waiting[From].insert(std::make_pair(SrcReg, DestReg));
450         UsedByAnother.insert(SrcReg);
451       } else {
452         // Otherwise, add it to the renaming set
453         PHIUnion.insert(SrcReg);
454         UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
455       }
456     }
457     
458     // Compute the dominator forest for the renaming set.  This is a forest
459     // where the nodes are the registers and the edges represent dominance 
460     // relations between the defining blocks of the registers
461     std::vector<StrongPHIElimination::DomForestNode*> DF = 
462                                                 computeDomForest(PHIUnion, MRI);
463     
464     // Walk DomForest to resolve interferences at an inter-block level.  This
465     // will remove registers from the renaming set (and insert copies for them)
466     // if interferences are found.
467     std::vector<std::pair<unsigned, unsigned> > localInterferences;
468     processPHIUnion(P, PHIUnion, DF, localInterferences);
469     
470     // The dominator forest walk may have returned some register pairs whose
471     // interference cannot be determines from dominator analysis.  We now 
472     // examine these pairs for local interferences.
473     for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
474         localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
475       std::pair<unsigned, unsigned> p = *I;
476       
477       MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
478       
479       // Determine the block we need to scan and the relationship between
480       // the two registers
481       MachineBasicBlock* scan = 0;
482       unsigned mode = 0;
483       if (MRI.getVRegDef(p.first)->getParent() ==
484           MRI.getVRegDef(p.second)->getParent()) {
485         scan = MRI.getVRegDef(p.first)->getParent();
486         mode = 0; // Same block
487       } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
488                                MRI.getVRegDef(p.second)->getParent())) {
489         scan = MRI.getVRegDef(p.second)->getParent();
490         mode = 1; // First dominates second
491       } else {
492         scan = MRI.getVRegDef(p.first)->getParent();
493         mode = 2; // Second dominates first
494       }
495       
496       // If there's an interference, we need to insert  copies
497       if (interferes(p.first, p.second, scan, LV, mode)) {
498         // Insert copies for First
499         for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
500           if (P->getOperand(i-1).getReg() == p.first) {
501             unsigned SrcReg = p.first;
502             MachineBasicBlock* From = P->getOperand(i).getMBB();
503             
504             Waiting[From].insert(std::make_pair(SrcReg,
505                                                 P->getOperand(0).getReg()));
506             UsedByAnother.insert(SrcReg);
507             
508             PHIUnion.erase(SrcReg);
509           }
510         }
511       }
512     }
513     
514     // Add the renaming set for this PHI node to our overal renaming information
515     RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
516     
517     // Remember which registers are already renamed, so that we don't try to 
518     // rename them for another PHI node in this block
519     ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
520     
521     ++P;
522   }
523 }
524
525 /// processPHIUnion - Take a set of candidate registers to be coallesced when
526 /// decomposing the PHI instruction.  Use the DominanceForest to remove the ones
527 /// that are known to interfere, and flag others that need to be checked for
528 /// local interferences.
529 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
530                                            std::set<unsigned>& PHIUnion,
531                         std::vector<StrongPHIElimination::DomForestNode*>& DF,
532                         std::vector<std::pair<unsigned, unsigned> >& locals) {
533   
534   std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
535   SmallPtrSet<DomForestNode*, 4> visited;
536   
537   // Code is still in SSA form, so we can use MRI::getVRegDef()
538   MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
539   
540   LiveVariables& LV = getAnalysis<LiveVariables>();
541   unsigned DestReg = Inst->getOperand(0).getReg();
542   
543   // DF walk on the DomForest
544   while (!worklist.empty()) {
545     DomForestNode* DFNode = worklist.back();
546     
547     visited.insert(DFNode);
548     
549     bool inserted = false;
550     for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
551          CI != CE; ++CI) {
552       DomForestNode* child = *CI;   
553       
554       // If the current node is live-out of the defining block of one of its
555       // children, insert a copy for it.  NOTE: The paper actually calls for
556       // a more elaborate heuristic for determining whether to insert copies
557       // for the child or the parent.  In the interest of simplicity, we're
558       // just always choosing the parent.
559       if (isLiveOut(DFNode->getReg(),
560           MRI.getVRegDef(child->getReg())->getParent(), MRI, LV)) {
561         // Insert copies for parent
562         for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
563           if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
564             unsigned SrcReg = DFNode->getReg();
565             MachineBasicBlock* From = Inst->getOperand(i).getMBB();
566             
567             Waiting[From].insert(std::make_pair(SrcReg, DestReg));
568             UsedByAnother.insert(SrcReg);
569             
570             PHIUnion.erase(SrcReg);
571           }
572         }
573       
574       // If a node is live-in to the defining block of one of its children, but
575       // not live-out, then we need to scan that block for local interferences.
576       } else if (isLiveIn(DFNode->getReg(),
577                           MRI.getVRegDef(child->getReg())->getParent(),
578                           MRI, LV) ||
579                  MRI.getVRegDef(DFNode->getReg())->getParent() ==
580                                  MRI.getVRegDef(child->getReg())->getParent()) {
581         // Add (p, c) to possible local interferences
582         locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
583       }
584       
585       if (!visited.count(child)) {
586         worklist.push_back(child);
587         inserted = true;
588       }
589     }
590     
591     if (!inserted) worklist.pop_back();
592   }
593 }
594
595 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
596 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
597 /// problems.
598 ///
599 /// Based on "Practical Improvements to the Construction and Destruction
600 /// of Static Single Assignment Form" by Briggs, et al.
601 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
602                                           std::set<unsigned>& pushed) {
603   // FIXME: This function needs to update LiveVariables
604   std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
605   
606   std::map<unsigned, unsigned> worklist;
607   std::map<unsigned, unsigned> map;
608   
609   // Setup worklist of initial copies
610   for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
611        E = copy_set.end(); I != E; ) {
612     map.insert(std::make_pair(I->first, I->first));
613     map.insert(std::make_pair(I->second, I->second));
614          
615     if (!UsedByAnother.count(I->first)) {
616       worklist.insert(*I);
617       
618       // Avoid iterator invalidation
619       unsigned first = I->first;
620       ++I;
621       copy_set.erase(first);
622     } else {
623       ++I;
624     }
625   }
626   
627   LiveVariables& LV = getAnalysis<LiveVariables>();
628   MachineFunction* MF = MBB->getParent();
629   MachineRegisterInfo& MRI = MF->getRegInfo();
630   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
631   
632   // Iterate over the worklist, inserting copies
633   while (!worklist.empty() || !copy_set.empty()) {
634     while (!worklist.empty()) {
635       std::pair<unsigned, unsigned> curr = *worklist.begin();
636       worklist.erase(curr.first);
637       
638       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
639       
640       if (isLiveOut(curr.second, MBB, MRI, LV)) {
641         // Create a temporary
642         unsigned t = MF->getRegInfo().createVirtualRegister(RC);
643         
644         // Insert copy from curr.second to a temporary at
645         // the Phi defining curr.second
646         MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
647         TII->copyRegToReg(*PI->getParent(), PI, t,
648                           curr.second, RC, RC);
649         
650         // Push temporary on Stacks
651         Stacks[curr.second].push_back(t);
652         
653         // Insert curr.second in pushed
654         pushed.insert(curr.second);
655       }
656       
657       // Insert copy from map[curr.first] to curr.second
658       TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
659                         map[curr.first], RC, RC);
660       map[curr.first] = curr.second;
661       
662       // If curr.first is a destination in copy_set...
663       for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
664            E = copy_set.end(); I != E; )
665         if (curr.first == I->second) {
666           std::pair<unsigned, unsigned> temp = *I;
667           
668           // Avoid iterator invalidation
669           ++I;
670           copy_set.erase(temp.first);
671           worklist.insert(temp);
672           
673           break;
674         } else {
675           ++I;
676         }
677     }
678     
679     if (!copy_set.empty()) {
680       std::pair<unsigned, unsigned> curr = *copy_set.begin();
681       copy_set.erase(curr.first);
682       
683       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
684       
685       // Insert a copy from dest to a new temporary t at the end of b
686       unsigned t = MF->getRegInfo().createVirtualRegister(RC);
687       TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
688                         curr.second, RC, RC);
689       map[curr.second] = t;
690       
691       worklist.insert(curr);
692     }
693   }
694 }
695
696 /// InsertCopies - insert copies into MBB and all of its successors
697 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
698                                         std::set<MachineBasicBlock*>& visited) {
699   visited.insert(MBB);
700   
701   std::set<unsigned> pushed;
702   
703   // Rewrite register uses from Stacks
704   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
705       I != E; ++I)
706     for (unsigned i = 0; i < I->getNumOperands(); ++i)
707       if (I->getOperand(i).isRegister() &&
708           Stacks[I->getOperand(i).getReg()].size()) {
709         I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
710       }
711   
712   // Schedule the copies for this block
713   ScheduleCopies(MBB, pushed);
714   
715   // Recur to our successors
716   for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I = 
717        GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
718        GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
719     if (!visited.count(*I))
720       InsertCopies(*I, visited);
721   
722   // As we exit this block, pop the names we pushed while processing it
723   for (std::set<unsigned>::iterator I = pushed.begin(), 
724        E = pushed.end(); I != E; ++I)
725     Stacks[*I].pop_back();
726 }
727
728 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
729   // Compute DFS numbers of each block
730   computeDFS(Fn);
731   
732   // Determine which phi node operands need copies
733   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
734     if (!I->empty() &&
735         I->begin()->getOpcode() == TargetInstrInfo::PHI)
736       processBlock(I);
737   
738   // Insert copies
739   // FIXME: This process should probably preserve LiveVariables
740   std::set<MachineBasicBlock*> visited;
741   InsertCopies(Fn.begin(), visited);
742   
743   // Perform renaming
744   typedef std::map<unsigned, std::set<unsigned> > RenameSetType;
745   for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
746        I != E; ++I)
747     for (std::set<unsigned>::iterator SI = I->second.begin(),
748          SE = I->second.end(); SI != SE; ++SI)
749       Fn.getRegInfo().replaceRegWith(*SI, I->first);
750   
751   // FIXME: Insert last-minute copies
752   
753   // Remove PHIs
754   std::vector<MachineInstr*> phis;
755   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
756     for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
757          BI != BE; ++BI)
758       if (BI->getOpcode() == TargetInstrInfo::PHI)
759         phis.push_back(BI);
760   }
761   
762   for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
763        I != E; ++I)
764     (*I)->eraseFromParent();
765   
766   return false;
767 }