In some situations, we need to check for local interferences between the PHI
[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/LiveIntervalAnalysis.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/ADT/DepthFirstIterator.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/Compiler.h"
35 using namespace llvm;
36
37
38 namespace {
39   struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
40     static char ID; // Pass identification, replacement for typeid
41     StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
42
43     // Waiting stores, for each MBB, the set of copies that need to
44     // be inserted into that MBB
45     DenseMap<MachineBasicBlock*,
46              std::map<unsigned, unsigned> > Waiting;
47     
48     // Stacks holds the renaming stack for each register
49     std::map<unsigned, std::vector<unsigned> > Stacks;
50     
51     // Registers in UsedByAnother are PHI nodes that are themselves
52     // used as operands to another another PHI node
53     std::set<unsigned> UsedByAnother;
54     
55     // RenameSets are the sets of operands (and their VNInfo IDs) to a PHI
56     // (the defining instruction of the key) that can be renamed without copies.
57     std::map<unsigned, std::map<unsigned, unsigned> > RenameSets;
58     
59     // PhiValueNumber holds the ID numbers of the VNs for each phi that we're
60     // eliminating, indexed by the register defined by that phi.
61     std::map<unsigned, unsigned> PhiValueNumber;
62
63     // Store the DFS-in number of each block
64     DenseMap<MachineBasicBlock*, unsigned> preorder;
65     
66     // Store the DFS-out number of each block
67     DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
68
69     bool runOnMachineFunction(MachineFunction &Fn);
70     
71     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72       AU.addRequired<MachineDominatorTree>();
73       AU.addRequired<LiveIntervals>();
74       
75       // TODO: Actually make this true.
76       AU.addPreserved<LiveIntervals>();
77       MachineFunctionPass::getAnalysisUsage(AU);
78     }
79     
80     virtual void releaseMemory() {
81       preorder.clear();
82       maxpreorder.clear();
83       
84       Waiting.clear();
85       Stacks.clear();
86       UsedByAnother.clear();
87       RenameSets.clear();
88     }
89
90   private:
91     
92     /// DomForestNode - Represents a node in the "dominator forest".  This is
93     /// a forest in which the nodes represent registers and the edges
94     /// represent a dominance relation in the block defining those registers.
95     struct DomForestNode {
96     private:
97       // Store references to our children
98       std::vector<DomForestNode*> children;
99       // The register we represent
100       unsigned reg;
101       
102       // Add another node as our child
103       void addChild(DomForestNode* DFN) { children.push_back(DFN); }
104       
105     public:
106       typedef std::vector<DomForestNode*>::iterator iterator;
107       
108       // Create a DomForestNode by providing the register it represents, and
109       // the node to be its parent.  The virtual root node has register 0
110       // and a null parent.
111       DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
112         if (parent)
113           parent->addChild(this);
114       }
115       
116       ~DomForestNode() {
117         for (iterator I = begin(), E = end(); I != E; ++I)
118           delete *I;
119       }
120       
121       /// getReg - Return the regiser that this node represents
122       inline unsigned getReg() { return reg; }
123       
124       // Provide iterator access to our children
125       inline DomForestNode::iterator begin() { return children.begin(); }
126       inline DomForestNode::iterator end() { return children.end(); }
127     };
128     
129     void computeDFS(MachineFunction& MF);
130     void processBlock(MachineBasicBlock* MBB);
131     
132     std::vector<DomForestNode*> computeDomForest(std::map<unsigned, unsigned>& instrs,
133                                                  MachineRegisterInfo& MRI);
134     void processPHIUnion(MachineInstr* Inst,
135                          std::map<unsigned, unsigned>& PHIUnion,
136                          std::vector<StrongPHIElimination::DomForestNode*>& DF,
137                          std::vector<std::pair<unsigned, unsigned> >& locals);
138     void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
139     void InsertCopies(MachineBasicBlock* MBB,
140                       SmallPtrSet<MachineBasicBlock*, 16>& v);
141     void mergeLiveIntervals(unsigned primary, unsigned secondary, unsigned VN);
142   };
143
144   char StrongPHIElimination::ID = 0;
145   RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
146                   "Eliminate PHI nodes for register allocation, intelligently");
147 }
148
149 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
150
151 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
152 /// of the given MachineFunction.  These numbers are then used in other parts
153 /// of the PHI elimination process.
154 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
155   SmallPtrSet<MachineDomTreeNode*, 8> frontier;
156   SmallPtrSet<MachineDomTreeNode*, 8> visited;
157   
158   unsigned time = 0;
159   
160   MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
161   
162   MachineDomTreeNode* node = DT.getRootNode();
163   
164   std::vector<MachineDomTreeNode*> worklist;
165   worklist.push_back(node);
166   
167   while (!worklist.empty()) {
168     MachineDomTreeNode* currNode = worklist.back();
169     
170     if (!frontier.count(currNode)) {
171       frontier.insert(currNode);
172       ++time;
173       preorder.insert(std::make_pair(currNode->getBlock(), time));
174     }
175     
176     bool inserted = false;
177     for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
178          I != E; ++I)
179       if (!frontier.count(*I) && !visited.count(*I)) {
180         worklist.push_back(*I);
181         inserted = true;
182         break;
183       }
184     
185     if (!inserted) {
186       frontier.erase(currNode);
187       visited.insert(currNode);
188       maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
189       
190       worklist.pop_back();
191     }
192   }
193 }
194
195 /// PreorderSorter - a helper class that is used to sort registers
196 /// according to the preorder number of their defining blocks
197 class PreorderSorter {
198 private:
199   DenseMap<MachineBasicBlock*, unsigned>& preorder;
200   MachineRegisterInfo& MRI;
201   
202 public:
203   PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
204                 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
205   
206   bool operator()(unsigned A, unsigned B) {
207     if (A == B)
208       return false;
209     
210     MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
211     MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
212     
213     if (preorder[ABlock] < preorder[BBlock])
214       return true;
215     else if (preorder[ABlock] > preorder[BBlock])
216       return false;
217     
218     return false;
219   }
220 };
221
222 /// computeDomForest - compute the subforest of the DomTree corresponding
223 /// to the defining blocks of the registers in question
224 std::vector<StrongPHIElimination::DomForestNode*>
225 StrongPHIElimination::computeDomForest(std::map<unsigned, unsigned>& regs, 
226                                        MachineRegisterInfo& MRI) {
227   // Begin by creating a virtual root node, since the actual results
228   // may well be a forest.  Assume this node has maximum DFS-out number.
229   DomForestNode* VirtualRoot = new DomForestNode(0, 0);
230   maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
231   
232   // Populate a worklist with the registers
233   std::vector<unsigned> worklist;
234   worklist.reserve(regs.size());
235   for (std::map<unsigned, unsigned>::iterator I = regs.begin(), E = regs.end();
236        I != E; ++I)
237     worklist.push_back(I->first);
238   
239   // Sort the registers by the DFS-in number of their defining block
240   PreorderSorter PS(preorder, MRI);
241   std::sort(worklist.begin(), worklist.end(), PS);
242   
243   // Create a "current parent" stack, and put the virtual root on top of it
244   DomForestNode* CurrentParent = VirtualRoot;
245   std::vector<DomForestNode*> stack;
246   stack.push_back(VirtualRoot);
247   
248   // Iterate over all the registers in the previously computed order
249   for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
250        I != E; ++I) {
251     unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
252     MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
253                  MRI.getVRegDef(CurrentParent->getReg())->getParent() :
254                  0;
255     
256     // If the DFS-in number of the register is greater than the DFS-out number
257     // of the current parent, repeatedly pop the parent stack until it isn't.
258     while (pre > maxpreorder[parentBlock]) {
259       stack.pop_back();
260       CurrentParent = stack.back();
261       
262       parentBlock = CurrentParent->getReg() ?
263                    MRI.getVRegDef(CurrentParent->getReg())->getParent() :
264                    0;
265     }
266     
267     // Now that we've found the appropriate parent, create a DomForestNode for
268     // this register and attach it to the forest
269     DomForestNode* child = new DomForestNode(*I, CurrentParent);
270     
271     // Push this new node on the "current parent" stack
272     stack.push_back(child);
273     CurrentParent = child;
274   }
275   
276   // Return a vector containing the children of the virtual root node
277   std::vector<DomForestNode*> ret;
278   ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
279   return ret;
280 }
281
282 /// isLiveIn - helper method that determines, from a regno, if a register
283 /// is live into a block
284 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
285                      LiveIntervals& LI) {
286   LiveInterval& I = LI.getOrCreateInterval(r);
287   unsigned idx = LI.getMBBStartIdx(MBB);
288   return I.liveBeforeAndAt(idx);
289 }
290
291 /// isLiveOut - help method that determines, from a regno, if a register is
292 /// live out of a block.
293 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
294                       LiveIntervals& LI) {
295   for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
296        E = MBB->succ_end(); PI != E; ++PI) {
297     if (isLiveIn(r, *PI, LI))
298       return true;
299   }
300   
301   return false;
302 }
303
304 /// interferes - checks for local interferences by scanning a block.  The only
305 /// trick parameter is 'mode' which tells it the relationship of the two
306 /// registers. 0 - defined in the same block, 1 - first properly dominates
307 /// second, 2 - second properly dominates first 
308 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
309                        LiveIntervals& LV, unsigned mode) {
310   MachineInstr* def = 0;
311   MachineInstr* kill = 0;
312   
313   // The code is still in SSA form at this point, so there is only one
314   // definition per VReg.  Thus we can safely use MRI->getVRegDef().
315   const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
316   
317   bool interference = false;
318   
319   // Wallk the block, checking for interferences
320   for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
321        MBI != MBE; ++MBI) {
322     MachineInstr* curr = MBI;
323     
324     // Same defining block...
325     if (mode == 0) {
326       if (curr == MRI->getVRegDef(a)) {
327         // If we find our first definition, save it
328         if (!def) {
329           def = curr;
330         // If there's already an unkilled definition, then 
331         // this is an interference
332         } else if (!kill) {
333           interference = true;
334           break;
335         // If there's a definition followed by a KillInst, then
336         // they can't interfere
337         } else {
338           interference = false;
339           break;
340         }
341       // Symmetric with the above
342       } else if (curr == MRI->getVRegDef(b)) {
343         if (!def) {
344           def = curr;
345         } else if (!kill) {
346           interference = true;
347           break;
348         } else {
349           interference = false;
350           break;
351         }
352       // Store KillInsts if they match up with the definition
353       } else if (curr->killsRegister(a)) {
354         if (def == MRI->getVRegDef(a)) {
355           kill = curr;
356         } else if (curr->killsRegister(b)) {
357           if (def == MRI->getVRegDef(b)) {
358             kill = curr;
359           }
360         }
361       }
362     // First properly dominates second...
363     } else if (mode == 1) {
364       if (curr == MRI->getVRegDef(b)) {
365         // Definition of second without kill of first is an interference
366         if (!kill) {
367           interference = true;
368           break;
369         // Definition after a kill is a non-interference
370         } else {
371           interference = false;
372           break;
373         }
374       // Save KillInsts of First
375       } else if (curr->killsRegister(a)) {
376         kill = curr;
377       }
378     // Symmetric with the above
379     } else if (mode == 2) {
380       if (curr == MRI->getVRegDef(a)) {
381         if (!kill) {
382           interference = true;
383           break;
384         } else {
385           interference = false;
386           break;
387         }
388       } else if (curr->killsRegister(b)) {
389         kill = curr;
390       }
391     }
392   }
393   
394   return interference;
395 }
396
397 /// processBlock - Determine how to break up PHIs in the current block.  Each
398 /// PHI is broken up by some combination of renaming its operands and inserting
399 /// copies.  This method is responsible for determining which operands receive
400 /// which treatment.
401 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
402   LiveIntervals& LI = getAnalysis<LiveIntervals>();
403   MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
404   
405   // Holds names that have been added to a set in any PHI within this block
406   // before the current one.
407   std::set<unsigned> ProcessedNames;
408   
409   // Iterate over all the PHI nodes in this block
410   MachineBasicBlock::iterator P = MBB->begin();
411   while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
412     unsigned DestReg = P->getOperand(0).getReg();
413
414     // Don't both doing PHI elimination for dead PHI's.
415     if (P->registerDefIsDead(DestReg)) {
416       ++P;
417       continue;
418     }
419
420     LiveInterval& PI = LI.getOrCreateInterval(DestReg);
421     unsigned pIdx = LI.getDefIndex(LI.getInstructionIndex(P));
422     VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
423     PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
424
425     // PHIUnion is the set of incoming registers to the PHI node that
426     // are going to be renames rather than having copies inserted.  This set
427     // is refinded over the course of this function.  UnionedBlocks is the set
428     // of corresponding MBBs.
429     std::map<unsigned, unsigned> PHIUnion;
430     SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
431   
432     // Iterate over the operands of the PHI node
433     for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
434       unsigned SrcReg = P->getOperand(i-1).getReg();
435     
436       // Check for trivial interferences via liveness information, allowing us
437       // to avoid extra work later.  Any registers that interfere cannot both
438       // be in the renaming set, so choose one and add copies for it instead.
439       // The conditions are:
440       //   1) if the operand is live into the PHI node's block OR
441       //   2) if the PHI node is live out of the operand's defining block OR
442       //   3) if the operand is itself a PHI node and the original PHI is
443       //      live into the operand's defining block OR
444       //   4) if the operand is already being renamed for another PHI node
445       //      in this block OR
446       //   5) if any two operands are defined in the same block, insert copies
447       //      for one of them
448       if (isLiveIn(SrcReg, P->getParent(), LI) ||
449           isLiveOut(P->getOperand(0).getReg(),
450                     MRI.getVRegDef(SrcReg)->getParent(), LI) ||
451           ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
452             isLiveIn(P->getOperand(0).getReg(),
453                      MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
454           ProcessedNames.count(SrcReg) ||
455           UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
456         
457         // Add a copy for the selected register
458         MachineBasicBlock* From = P->getOperand(i).getMBB();
459         Waiting[From].insert(std::make_pair(SrcReg, DestReg));
460         UsedByAnother.insert(SrcReg);
461       } else {
462         // Otherwise, add it to the renaming set
463         LiveInterval& I = LI.getOrCreateInterval(SrcReg);
464         unsigned idx = LI.getMBBEndIdx(P->getOperand(i).getMBB());
465         VNInfo* VN = I.getLiveRangeContaining(idx)->valno;
466         
467         assert(VN && "No VNInfo for register?");
468         
469         PHIUnion.insert(std::make_pair(SrcReg, VN->id));
470         UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
471       }
472     }
473     
474     // Compute the dominator forest for the renaming set.  This is a forest
475     // where the nodes are the registers and the edges represent dominance 
476     // relations between the defining blocks of the registers
477     std::vector<StrongPHIElimination::DomForestNode*> DF = 
478                                                 computeDomForest(PHIUnion, MRI);
479     
480     // Walk DomForest to resolve interferences at an inter-block level.  This
481     // will remove registers from the renaming set (and insert copies for them)
482     // if interferences are found.
483     std::vector<std::pair<unsigned, unsigned> > localInterferences;
484     processPHIUnion(P, PHIUnion, DF, localInterferences);
485     
486     // If one of the inputs is defined in the same block as the current PHI
487     // then we need to check for a local interference between that input and
488     // the PHI.
489     for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
490          E = PHIUnion.end(); I != E; ++I)
491       if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
492         localInterferences.push_back(std::make_pair(I->first,
493                                                     P->getOperand(0).getReg()));
494     
495     // The dominator forest walk may have returned some register pairs whose
496     // interference cannot be determined from dominator analysis.  We now 
497     // examine these pairs for local interferences.
498     for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
499         localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
500       std::pair<unsigned, unsigned> p = *I;
501       
502       MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
503       
504       // Determine the block we need to scan and the relationship between
505       // the two registers
506       MachineBasicBlock* scan = 0;
507       unsigned mode = 0;
508       if (MRI.getVRegDef(p.first)->getParent() ==
509           MRI.getVRegDef(p.second)->getParent()) {
510         scan = MRI.getVRegDef(p.first)->getParent();
511         mode = 0; // Same block
512       } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
513                                MRI.getVRegDef(p.second)->getParent())) {
514         scan = MRI.getVRegDef(p.second)->getParent();
515         mode = 1; // First dominates second
516       } else {
517         scan = MRI.getVRegDef(p.first)->getParent();
518         mode = 2; // Second dominates first
519       }
520       
521       // If there's an interference, we need to insert  copies
522       if (interferes(p.first, p.second, scan, LI, mode)) {
523         // Insert copies for First
524         for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
525           if (P->getOperand(i-1).getReg() == p.first) {
526             unsigned SrcReg = p.first;
527             MachineBasicBlock* From = P->getOperand(i).getMBB();
528             
529             Waiting[From].insert(std::make_pair(SrcReg,
530                                                 P->getOperand(0).getReg()));
531             UsedByAnother.insert(SrcReg);
532             
533             PHIUnion.erase(SrcReg);
534           }
535         }
536       }
537     }
538     
539     // Add the renaming set for this PHI node to our overall renaming information
540     RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
541     
542     // Remember which registers are already renamed, so that we don't try to 
543     // rename them for another PHI node in this block
544     for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
545          E = PHIUnion.end(); I != E; ++I)
546       ProcessedNames.insert(I->first);
547     
548     ++P;
549   }
550 }
551
552 /// processPHIUnion - Take a set of candidate registers to be coalesced when
553 /// decomposing the PHI instruction.  Use the DominanceForest to remove the ones
554 /// that are known to interfere, and flag others that need to be checked for
555 /// local interferences.
556 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
557                                         std::map<unsigned, unsigned>& PHIUnion,
558                         std::vector<StrongPHIElimination::DomForestNode*>& DF,
559                         std::vector<std::pair<unsigned, unsigned> >& locals) {
560   
561   std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
562   SmallPtrSet<DomForestNode*, 4> visited;
563   
564   // Code is still in SSA form, so we can use MRI::getVRegDef()
565   MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
566   
567   LiveIntervals& LI = getAnalysis<LiveIntervals>();
568   unsigned DestReg = Inst->getOperand(0).getReg();
569   
570   // DF walk on the DomForest
571   while (!worklist.empty()) {
572     DomForestNode* DFNode = worklist.back();
573     
574     visited.insert(DFNode);
575     
576     bool inserted = false;
577     for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
578          CI != CE; ++CI) {
579       DomForestNode* child = *CI;   
580       
581       // If the current node is live-out of the defining block of one of its
582       // children, insert a copy for it.  NOTE: The paper actually calls for
583       // a more elaborate heuristic for determining whether to insert copies
584       // for the child or the parent.  In the interest of simplicity, we're
585       // just always choosing the parent.
586       if (isLiveOut(DFNode->getReg(),
587           MRI.getVRegDef(child->getReg())->getParent(), LI)) {
588         // Insert copies for parent
589         for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
590           if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
591             unsigned SrcReg = DFNode->getReg();
592             MachineBasicBlock* From = Inst->getOperand(i).getMBB();
593             
594             Waiting[From].insert(std::make_pair(SrcReg, DestReg));
595             UsedByAnother.insert(SrcReg);
596             
597             PHIUnion.erase(SrcReg);
598           }
599         }
600       
601       // If a node is live-in to the defining block of one of its children, but
602       // not live-out, then we need to scan that block for local interferences.
603       } else if (isLiveIn(DFNode->getReg(),
604                           MRI.getVRegDef(child->getReg())->getParent(), LI) ||
605                  MRI.getVRegDef(DFNode->getReg())->getParent() ==
606                                  MRI.getVRegDef(child->getReg())->getParent()) {
607         // Add (p, c) to possible local interferences
608         locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
609       }
610       
611       if (!visited.count(child)) {
612         worklist.push_back(child);
613         inserted = true;
614       }
615     }
616     
617     if (!inserted) worklist.pop_back();
618   }
619 }
620
621 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
622 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
623 /// problems.
624 ///
625 /// Based on "Practical Improvements to the Construction and Destruction
626 /// of Static Single Assignment Form" by Briggs, et al.
627 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
628                                           std::set<unsigned>& pushed) {
629   // FIXME: This function needs to update LiveVariables
630   std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
631   
632   std::map<unsigned, unsigned> worklist;
633   std::map<unsigned, unsigned> map;
634   
635   // Setup worklist of initial copies
636   for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
637        E = copy_set.end(); I != E; ) {
638     map.insert(std::make_pair(I->first, I->first));
639     map.insert(std::make_pair(I->second, I->second));
640          
641     if (!UsedByAnother.count(I->second)) {
642       worklist.insert(*I);
643       
644       // Avoid iterator invalidation
645       unsigned first = I->first;
646       ++I;
647       copy_set.erase(first);
648     } else {
649       ++I;
650     }
651   }
652   
653   LiveIntervals& LI = getAnalysis<LiveIntervals>();
654   MachineFunction* MF = MBB->getParent();
655   MachineRegisterInfo& MRI = MF->getRegInfo();
656   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
657   
658   // Iterate over the worklist, inserting copies
659   while (!worklist.empty() || !copy_set.empty()) {
660     while (!worklist.empty()) {
661       std::pair<unsigned, unsigned> curr = *worklist.begin();
662       worklist.erase(curr.first);
663       
664       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
665       
666       if (isLiveOut(curr.second, MBB, LI)) {
667         // Create a temporary
668         unsigned t = MF->getRegInfo().createVirtualRegister(RC);
669         
670         // Insert copy from curr.second to a temporary at
671         // the Phi defining curr.second
672         MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
673         TII->copyRegToReg(*PI->getParent(), PI, t,
674                           curr.second, RC, RC);
675         
676         // Push temporary on Stacks
677         Stacks[curr.second].push_back(t);
678         
679         // Insert curr.second in pushed
680         pushed.insert(curr.second);
681       }
682       
683       // Insert copy from map[curr.first] to curr.second
684       TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
685                         map[curr.first], RC, RC);
686       map[curr.first] = curr.second;
687       
688       // If curr.first is a destination in copy_set...
689       for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
690            E = copy_set.end(); I != E; )
691         if (curr.first == I->second) {
692           std::pair<unsigned, unsigned> temp = *I;
693           
694           // Avoid iterator invalidation
695           ++I;
696           copy_set.erase(temp.first);
697           worklist.insert(temp);
698           
699           break;
700         } else {
701           ++I;
702         }
703     }
704     
705     if (!copy_set.empty()) {
706       std::pair<unsigned, unsigned> curr = *copy_set.begin();
707       copy_set.erase(curr.first);
708       
709       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
710       
711       // Insert a copy from dest to a new temporary t at the end of b
712       unsigned t = MF->getRegInfo().createVirtualRegister(RC);
713       TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
714                         curr.second, RC, RC);
715       map[curr.second] = t;
716       
717       worklist.insert(curr);
718     }
719   }
720 }
721
722 /// InsertCopies - insert copies into MBB and all of its successors
723 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
724                                  SmallPtrSet<MachineBasicBlock*, 16>& visited) {
725   visited.insert(MBB);
726   
727   std::set<unsigned> pushed;
728   
729   // Rewrite register uses from Stacks
730   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
731       I != E; ++I)
732     for (unsigned i = 0; i < I->getNumOperands(); ++i)
733       if (I->getOperand(i).isRegister() &&
734           Stacks[I->getOperand(i).getReg()].size()) {
735         I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
736       }
737   
738   // Schedule the copies for this block
739   ScheduleCopies(MBB, pushed);
740   
741   // Recur to our successors
742   for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I = 
743        GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
744        GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
745     if (!visited.count(*I))
746       InsertCopies(*I, visited);
747   
748   // As we exit this block, pop the names we pushed while processing it
749   for (std::set<unsigned>::iterator I = pushed.begin(), 
750        E = pushed.end(); I != E; ++I)
751     Stacks[*I].pop_back();
752 }
753
754 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
755 /// compute what the resultant value numbers for each value in the input two
756 /// ranges will be.  This is complicated by copies between the two which can
757 /// and will commonly cause multiple value numbers to be merged into one.
758 ///
759 /// VN is the value number that we're trying to resolve.  InstDefiningValue
760 /// keeps track of the new InstDefiningValue assignment for the result
761 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
762 /// whether a value in this or other is a copy from the opposite set.
763 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
764 /// already been assigned.
765 ///
766 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
767 /// contains the value number the copy is from.
768 ///
769 static unsigned ComputeUltimateVN(VNInfo *VNI,
770                                   SmallVector<VNInfo*, 16> &NewVNInfo,
771                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
772                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
773                                   SmallVector<int, 16> &ThisValNoAssignments,
774                                   SmallVector<int, 16> &OtherValNoAssignments) {
775   unsigned VN = VNI->id;
776
777   // If the VN has already been computed, just return it.
778   if (ThisValNoAssignments[VN] >= 0)
779     return ThisValNoAssignments[VN];
780 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
781
782   // If this val is not a copy from the other val, then it must be a new value
783   // number in the destination.
784   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
785   if (I == ThisFromOther.end()) {
786     NewVNInfo.push_back(VNI);
787     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
788   }
789   VNInfo *OtherValNo = I->second;
790
791   // Otherwise, this *is* a copy from the RHS.  If the other side has already
792   // been computed, return it.
793   if (OtherValNoAssignments[OtherValNo->id] >= 0)
794     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
795   
796   // Mark this value number as currently being computed, then ask what the
797   // ultimate value # of the other value is.
798   ThisValNoAssignments[VN] = -2;
799   unsigned UltimateVN =
800     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
801                       OtherValNoAssignments, ThisValNoAssignments);
802   return ThisValNoAssignments[VN] = UltimateVN;
803 }
804
805 void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
806                                               unsigned secondary,
807                                               unsigned secondaryVN) {
808   
809   LiveIntervals& LI = getAnalysis<LiveIntervals>();
810   LiveInterval& LHS = LI.getOrCreateInterval(primary);
811   LiveInterval& RHS = LI.getOrCreateInterval(secondary);
812   
813   // Compute the final value assignment, assuming that the live ranges can be
814   // coalesced.
815   SmallVector<int, 16> LHSValNoAssignments;
816   SmallVector<int, 16> RHSValNoAssignments;
817   SmallVector<VNInfo*, 16> NewVNInfo;
818   
819   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
820   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
821   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
822   
823   for (LiveInterval::vni_iterator I = LHS.vni_begin(), E = LHS.vni_end();
824        I != E; ++I) {
825     VNInfo *VNI = *I;
826     unsigned VN = VNI->id;
827     if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
828       continue;
829     
830     NewVNInfo.push_back(VNI);
831     LHSValNoAssignments[VN] = NewVNInfo.size()-1;
832   }
833   
834   for (LiveInterval::vni_iterator I = RHS.vni_begin(), E = RHS.vni_end();
835        I != E; ++I) {
836     VNInfo *VNI = *I;
837     unsigned VN = VNI->id;
838     if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
839       continue;
840       
841     NewVNInfo.push_back(VNI);
842     RHSValNoAssignments[VN] = NewVNInfo.size()-1;
843   }
844
845   // If we get here, we know that we can coalesce the live ranges.  Ask the
846   // intervals to coalesce themselves now.
847
848   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
849   LI.removeInterval(secondary);
850   
851   // The valno that was previously the input to the PHI node
852   // now has a PHIKill.
853   LHS.getValNumInfo(RHSValNoAssignments[secondaryVN])->hasPHIKill = true;
854 }
855
856 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
857   LiveIntervals& LI = getAnalysis<LiveIntervals>();
858   
859   // Compute DFS numbers of each block
860   computeDFS(Fn);
861   
862   // Determine which phi node operands need copies
863   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
864     if (!I->empty() &&
865         I->begin()->getOpcode() == TargetInstrInfo::PHI)
866       processBlock(I);
867   
868   // Insert copies
869   // FIXME: This process should probably preserve LiveVariables
870   SmallPtrSet<MachineBasicBlock*, 16> visited;
871   InsertCopies(Fn.begin(), visited);
872   
873   // Perform renaming
874   typedef std::map<unsigned, std::map<unsigned, unsigned> > RenameSetType;
875   for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
876        I != E; ++I)
877     for (std::map<unsigned, unsigned>::iterator SI = I->second.begin(),
878          SE = I->second.end(); SI != SE; ++SI) {
879       mergeLiveIntervals(I->first, SI->first, SI->second);
880       Fn.getRegInfo().replaceRegWith(SI->first, I->first);
881     }
882   
883   // FIXME: Insert last-minute copies
884   
885   // Remove PHIs
886   std::vector<MachineInstr*> phis;
887   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
888     for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
889          BI != BE; ++BI)
890       if (BI->getOpcode() == TargetInstrInfo::PHI)
891         phis.push_back(BI);
892   }
893   
894   for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
895        I != E; ) {
896     MachineInstr* PInstr = *(I++);
897     
898     // If this is a dead PHI node, then remove it from LiveIntervals.
899     unsigned DestReg = PInstr->getOperand(0).getReg();
900     LiveInterval& PI = LI.getInterval(DestReg);
901     if (PInstr->registerDefIsDead(DestReg)) {
902       if (PI.containsOneValue()) {
903         LI.removeInterval(DestReg);
904       } else {
905         unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
906         PI.removeRange(*PI.getLiveRangeContaining(idx), true);
907       }
908     } else {
909       // If the PHI is not dead, then the valno defined by the PHI
910       // now has an unknown def.
911       unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
912       PI.getLiveRangeContaining(idx)->valno->def = ~0U;
913     }
914     
915     LI.RemoveMachineInstrFromMaps(PInstr);
916     PInstr->eraseFromParent();
917   }
918   
919   return true;
920 }