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