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