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