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