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