Eliminate repeated allocation of a per-BB DenseMap for a 4.6% reduction of time
[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 PHI instructions by aggressively coalescing the copies
11 // that would be inserted by a naive algorithm and only inserting the copies
12 // that are necessary. The coalescing technique initially assumes that all
13 // registers appearing in a PHI instruction do not interfere. It then eliminates
14 // proven interferences, using dominators to only perform a linear number of
15 // interference tests instead of the quadratic number of interference tests
16 // that this would naively require. This is a technique derived from:
17 // 
18 //    Budimlic, et al. Fast copy coalescing and live-range identification.
19 //    In Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language
20 //    Design and Implementation (Berlin, Germany, June 17 - 19, 2002).
21 //    PLDI '02. ACM, New York, NY, 25-32.
22 //
23 // The original implementation constructs a data structure they call a dominance
24 // forest for this purpose. The dominance forest was shown to be unnecessary,
25 // as it is possible to emulate the creation and traversal of a dominance forest
26 // by directly using the dominator tree, rather than actually constructing the
27 // dominance forest.  This technique is explained in:
28 //
29 //   Boissinot, et al. Revisiting Out-of-SSA Translation for Correctness, Code
30 //     Quality and Efficiency,
31 //   In Proceedings of the 7th annual IEEE/ACM International Symposium on Code
32 //   Generation and Optimization (Seattle, Washington, March 22 - 25, 2009).
33 //   CGO '09. IEEE, Washington, DC, 114-125.
34 //
35 // Careful implementation allows for all of the dominator forest interference
36 // checks to be performed at once in a single depth-first traversal of the
37 // dominator tree, which is what is implemented here.
38 //
39 //===----------------------------------------------------------------------===//
40
41 #define DEBUG_TYPE "strongphielim"
42 #include "PHIEliminationUtils.h"
43 #include "llvm/CodeGen/Passes.h"
44 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
45 #include "llvm/CodeGen/MachineDominators.h"
46 #include "llvm/CodeGen/MachineFunctionPass.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineRegisterInfo.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Support/Debug.h"
51 using namespace llvm;
52
53 namespace {
54   class StrongPHIElimination : public MachineFunctionPass {
55   public:
56     static char ID; // Pass identification, replacement for typeid
57     StrongPHIElimination() : MachineFunctionPass(ID) {
58       initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
59     }
60
61     virtual void getAnalysisUsage(AnalysisUsage&) const;
62     bool runOnMachineFunction(MachineFunction&);
63
64   private:
65     /// This struct represents a single node in the union-find data structure
66     /// representing the variable congruence classes. There is one difference
67     /// from a normal union-find data structure. We steal two bits from the parent
68     /// pointer . One of these bits is used to represent whether the register
69     /// itself has been isolated, and the other is used to represent whether the
70     /// PHI with that register as its destination has been isolated.
71     ///
72     /// Note that this leads to the strange situation where the leader of a
73     /// congruence class may no longer logically be a member, due to being
74     /// isolated.
75     struct Node {
76       enum Flags {
77         kRegisterIsolatedFlag = 1,
78         kPHIIsolatedFlag = 2
79       };
80       Node(unsigned v) : value(v), rank(0) { parent.setPointer(this); }
81
82       Node* getLeader();
83
84       PointerIntPair<Node*, 2> parent;
85       unsigned value;
86       unsigned rank;
87     };
88
89     /// Add a register in a new congruence class containing only itself.
90     void addReg(unsigned);
91
92     /// Join the congruence classes of two registers.
93     void unionRegs(unsigned, unsigned);
94
95     /// Get the color of a register. The color is 0 if the register has been
96     /// isolated.
97     unsigned getRegColor(unsigned);
98
99     // Isolate a register.
100     void isolateReg(unsigned);
101
102     /// Get the color of a PHI. The color of a PHI is 0 if the PHI has been
103     /// isolated. Otherwise, it is the original color of its destination and
104     /// all of its operands (before they were isolated, if they were).
105     unsigned getPHIColor(MachineInstr*);
106
107     /// Isolate a PHI.
108     void isolatePHI(MachineInstr*);
109
110     /// Traverses a basic block, splitting any interferences found between
111     /// registers in the same congruence class. It takes two DenseMaps as
112     /// arguments that it also updates: CurrentDominatingParent, which maps
113     /// a color to the register in that congruence class whose definition was
114     /// most recently seen, and ImmediateDominatingParent, which maps a register
115     /// to the register in the same congruence class that most immediately
116     /// dominates it.
117     ///
118     /// This function assumes that it is being called in a depth-first traversal
119     /// of the dominator tree.
120     void SplitInterferencesForBasicBlock(
121       MachineBasicBlock&,
122       DenseMap<unsigned, unsigned>& CurrentDominatingParent,
123       DenseMap<unsigned, unsigned>& ImmediateDominatingParent);
124
125     // Lowers a PHI instruction, inserting copies of the source and destination
126     // registers as necessary.
127     void InsertCopiesForPHI(MachineInstr*, MachineBasicBlock*);
128
129     // Merges the live interval of Reg into NewReg and renames Reg to NewReg
130     // everywhere that Reg appears. Requires Reg and NewReg to have non-
131     // overlapping lifetimes.
132     void MergeLIsAndRename(unsigned Reg, unsigned NewReg);
133
134     MachineRegisterInfo* MRI;
135     const TargetInstrInfo* TII;
136     MachineDominatorTree* DT;
137     LiveIntervals* LI;
138
139     BumpPtrAllocator Allocator;
140
141     DenseMap<unsigned, Node*> RegNodeMap;
142
143     // Maps a basic block to a list of its defs of registers that appear as PHI
144     // sources.
145     DenseMap<MachineBasicBlock*, std::vector<MachineInstr*> > PHISrcDefs;
146
147     // Maps a color to a pair of a MachineInstr* and a virtual register, which
148     // is the operand of that PHI corresponding to the current basic block.
149     DenseMap<unsigned, std::pair<MachineInstr*, unsigned> > CurrentPHIForColor;
150
151     // FIXME: Can these two data structures be combined? Would a std::multimap
152     // be any better?
153
154     // Stores pairs of predecessor basic blocks and the source registers of
155     // inserted copy instructions.
156     typedef DenseSet<std::pair<MachineBasicBlock*, unsigned> > SrcCopySet;
157     SrcCopySet InsertedSrcCopySet;
158
159     // Maps pairs of predecessor basic blocks and colors to their defining copy
160     // instructions.
161     typedef DenseMap<std::pair<MachineBasicBlock*, unsigned>, MachineInstr*>
162       SrcCopyMap;
163     SrcCopyMap InsertedSrcCopyMap;
164
165     // Maps inserted destination copy registers to their defining copy
166     // instructions.
167     typedef DenseMap<unsigned, MachineInstr*> DestCopyMap;
168     DestCopyMap InsertedDestCopies;
169   };
170
171   struct MIIndexCompare {
172     MIIndexCompare(LiveIntervals* LiveIntervals) : LI(LiveIntervals) { }
173
174     bool operator()(const MachineInstr* LHS, const MachineInstr* RHS) const {
175       return LI->getInstructionIndex(LHS) < LI->getInstructionIndex(RHS);
176     }
177
178     LiveIntervals* LI;
179   };
180 } // namespace
181
182 char StrongPHIElimination::ID = 0;
183 INITIALIZE_PASS_BEGIN(StrongPHIElimination, "strong-phi-node-elimination",
184   "Eliminate PHI nodes for register allocation, intelligently", false, false)
185 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
186 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
187 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
188 INITIALIZE_PASS_END(StrongPHIElimination, "strong-phi-node-elimination",
189   "Eliminate PHI nodes for register allocation, intelligently", false, false)
190
191 char &llvm::StrongPHIEliminationID = StrongPHIElimination::ID;
192
193 void StrongPHIElimination::getAnalysisUsage(AnalysisUsage& AU) const {
194   AU.setPreservesCFG();
195   AU.addRequired<MachineDominatorTree>();
196   AU.addRequired<SlotIndexes>();
197   AU.addPreserved<SlotIndexes>();
198   AU.addRequired<LiveIntervals>();
199   AU.addPreserved<LiveIntervals>();
200   MachineFunctionPass::getAnalysisUsage(AU);
201 }
202
203 static MachineOperand* findLastUse(MachineBasicBlock* MBB, unsigned Reg) {
204   // FIXME: This only needs to check from the first terminator, as only the
205   // first terminator can use a virtual register.
206   for (MachineBasicBlock::reverse_iterator RI = MBB->rbegin(); ; ++RI) {
207     assert (RI != MBB->rend());
208     MachineInstr* MI = &*RI;
209
210     for (MachineInstr::mop_iterator OI = MI->operands_begin(),
211          OE = MI->operands_end(); OI != OE; ++OI) {
212       MachineOperand& MO = *OI;
213       if (MO.isReg() && MO.isUse() && MO.getReg() == Reg)
214         return &MO;
215     }
216   }
217   return NULL;
218 }
219
220 bool StrongPHIElimination::runOnMachineFunction(MachineFunction& MF) {
221   MRI = &MF.getRegInfo();
222   TII = MF.getTarget().getInstrInfo();
223   DT = &getAnalysis<MachineDominatorTree>();
224   LI = &getAnalysis<LiveIntervals>();
225
226   for (MachineFunction::iterator I = MF.begin(), E = MF.end();
227        I != E; ++I) {
228     for (MachineBasicBlock::iterator BBI = I->begin(), BBE = I->end();
229          BBI != BBE && BBI->isPHI(); ++BBI) {
230       unsigned DestReg = BBI->getOperand(0).getReg();
231       addReg(DestReg);
232       PHISrcDefs[I].push_back(BBI);
233
234       for (unsigned i = 1; i < BBI->getNumOperands(); i += 2) {
235         MachineOperand& SrcMO = BBI->getOperand(i);
236         unsigned SrcReg = SrcMO.getReg();
237         addReg(SrcReg);
238         unionRegs(DestReg, SrcReg);
239
240         MachineInstr* DefMI = MRI->getVRegDef(SrcReg);
241         if (DefMI)
242           PHISrcDefs[DefMI->getParent()].push_back(DefMI);
243       }
244     }
245   }
246
247   // Perform a depth-first traversal of the dominator tree, splitting
248   // interferences amongst PHI-congruence classes.
249   DenseMap<unsigned, unsigned> CurrentDominatingParent;
250   DenseMap<unsigned, unsigned> ImmediateDominatingParent;
251   for (df_iterator<MachineDomTreeNode*> DI = df_begin(DT->getRootNode()),
252        DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
253     SplitInterferencesForBasicBlock(*DI->getBlock(),
254                                     CurrentDominatingParent,
255                                     ImmediateDominatingParent);
256   }
257
258   // Insert copies for all PHI source and destination registers.
259   for (MachineFunction::iterator I = MF.begin(), E = MF.end();
260        I != E; ++I) {
261     for (MachineBasicBlock::iterator BBI = I->begin(), BBE = I->end();
262          BBI != BBE && BBI->isPHI(); ++BBI) {
263       InsertCopiesForPHI(BBI, I);
264     }
265   }
266
267   // FIXME: Preserve the equivalence classes during copy insertion and use
268   // the preversed equivalence classes instead of recomputing them.
269   RegNodeMap.clear();
270   for (MachineFunction::iterator I = MF.begin(), E = MF.end();
271        I != E; ++I) {
272     for (MachineBasicBlock::iterator BBI = I->begin(), BBE = I->end();
273          BBI != BBE && BBI->isPHI(); ++BBI) {
274       unsigned DestReg = BBI->getOperand(0).getReg();
275       addReg(DestReg);
276
277       for (unsigned i = 1; i < BBI->getNumOperands(); i += 2) {
278         unsigned SrcReg = BBI->getOperand(i).getReg();
279         addReg(SrcReg);
280         unionRegs(DestReg, SrcReg);
281       }
282     }
283   }
284
285   DenseMap<unsigned, unsigned> RegRenamingMap;
286   bool Changed = false;
287   for (MachineFunction::iterator I = MF.begin(), E = MF.end();
288        I != E; ++I) {
289     MachineBasicBlock::iterator BBI = I->begin(), BBE = I->end();
290     while (BBI != BBE && BBI->isPHI()) {
291       MachineInstr* PHI = BBI;
292
293       assert(PHI->getNumOperands() > 0);
294
295       unsigned SrcReg = PHI->getOperand(1).getReg();
296       unsigned SrcColor = getRegColor(SrcReg);
297       unsigned NewReg = RegRenamingMap[SrcColor];
298       if (!NewReg) {
299         NewReg = SrcReg;
300         RegRenamingMap[SrcColor] = SrcReg;
301       }
302       MergeLIsAndRename(SrcReg, NewReg);
303
304       unsigned DestReg = PHI->getOperand(0).getReg();
305       if (!InsertedDestCopies.count(DestReg))
306         MergeLIsAndRename(DestReg, NewReg);
307
308       for (unsigned i = 3; i < PHI->getNumOperands(); i += 2) {
309         unsigned SrcReg = PHI->getOperand(i).getReg();
310         MergeLIsAndRename(SrcReg, NewReg);
311       }
312
313       ++BBI;
314       LI->RemoveMachineInstrFromMaps(PHI);
315       PHI->eraseFromParent();
316       Changed = true;
317     }
318   }
319
320   // Due to the insertion of copies to split live ranges, the live intervals are
321   // guaranteed to not overlap, except in one case: an original PHI source and a
322   // PHI destination copy. In this case, they have the same value and thus don't
323   // truly intersect, so we merge them into the value live at that point.
324   // FIXME: Is there some better way we can handle this?
325   for (DestCopyMap::iterator I = InsertedDestCopies.begin(),
326        E = InsertedDestCopies.end(); I != E; ++I) {
327     unsigned DestReg = I->first;
328     unsigned DestColor = getRegColor(DestReg);
329     unsigned NewReg = RegRenamingMap[DestColor];
330
331     LiveInterval& DestLI = LI->getInterval(DestReg);
332     LiveInterval& NewLI = LI->getInterval(NewReg);
333
334     assert(DestLI.ranges.size() == 1
335            && "PHI destination copy's live interval should be a single live "
336                "range from the beginning of the BB to the copy instruction.");
337     LiveRange* DestLR = DestLI.begin();
338     VNInfo* NewVNI = NewLI.getVNInfoAt(DestLR->start);
339     if (!NewVNI) {
340       NewVNI = NewLI.createValueCopy(DestLR->valno, LI->getVNInfoAllocator());
341       MachineInstr* CopyInstr = I->second;
342       CopyInstr->getOperand(1).setIsKill(true);
343     }
344
345     LiveRange NewLR(DestLR->start, DestLR->end, NewVNI);
346     NewLI.addRange(NewLR);
347
348     LI->removeInterval(DestReg);
349     MRI->replaceRegWith(DestReg, NewReg);
350   }
351
352   // Adjust the live intervals of all PHI source registers to handle the case
353   // where the PHIs in successor blocks were the only later uses of the source
354   // register.
355   for (SrcCopySet::iterator I = InsertedSrcCopySet.begin(),
356        E = InsertedSrcCopySet.end(); I != E; ++I) {
357     MachineBasicBlock* MBB = I->first;
358     unsigned SrcReg = I->second;
359     if (unsigned RenamedRegister = RegRenamingMap[getRegColor(SrcReg)])
360       SrcReg = RenamedRegister;
361
362     LiveInterval& SrcLI = LI->getInterval(SrcReg);
363
364     bool isLiveOut = false;
365     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
366          SE = MBB->succ_end(); SI != SE; ++SI) {
367       if (SrcLI.liveAt(LI->getMBBStartIdx(*SI))) {
368         isLiveOut = true;
369         break;
370       }
371     }
372
373     if (isLiveOut)
374       continue;
375
376     MachineOperand* LastUse = findLastUse(MBB, SrcReg);
377     assert(LastUse);
378     SlotIndex LastUseIndex = LI->getInstructionIndex(LastUse->getParent());
379     SrcLI.removeRange(LastUseIndex.getDefIndex(), LI->getMBBEndIdx(MBB));
380     LastUse->setIsKill(true);
381   }
382
383   LI->renumber();
384
385   Allocator.Reset();
386   RegNodeMap.clear();
387   PHISrcDefs.clear();
388   InsertedSrcCopySet.clear();
389   InsertedSrcCopyMap.clear();
390   InsertedDestCopies.clear();
391
392   return Changed;
393 }
394
395 void StrongPHIElimination::addReg(unsigned Reg) {
396   if (RegNodeMap.count(Reg))
397     return;
398   RegNodeMap[Reg] = new (Allocator) Node(Reg);
399 }
400
401 StrongPHIElimination::Node*
402 StrongPHIElimination::Node::getLeader() {
403   Node* parentPointer = parent.getPointer();
404   if (parentPointer == this)
405     return this;
406   Node* newParent = parentPointer->getLeader();
407   parent.setPointer(newParent);
408   return newParent;
409 }
410
411 unsigned StrongPHIElimination::getRegColor(unsigned Reg) {
412   DenseMap<unsigned, Node*>::iterator RI = RegNodeMap.find(Reg);
413   if (RI == RegNodeMap.end())
414     return 0;
415   Node* Node = RI->second;
416   if (Node->parent.getInt() & Node::kRegisterIsolatedFlag)
417     return 0;
418   return Node->getLeader()->value;
419 }
420
421 void StrongPHIElimination::unionRegs(unsigned Reg1, unsigned Reg2) {
422   Node* Node1 = RegNodeMap[Reg1]->getLeader();
423   Node* Node2 = RegNodeMap[Reg2]->getLeader();
424
425   if (Node1->rank > Node2->rank) {
426     Node2->parent.setPointer(Node1->getLeader());
427   } else if (Node1->rank < Node2->rank) {
428     Node1->parent.setPointer(Node2->getLeader());
429   } else if (Node1 != Node2) {
430     Node2->parent.setPointer(Node1->getLeader());
431     Node1->rank++;
432   }
433 }
434
435 void StrongPHIElimination::isolateReg(unsigned Reg) {
436   Node* Node = RegNodeMap[Reg];
437   Node->parent.setInt(Node->parent.getInt() | Node::kRegisterIsolatedFlag);
438 }
439
440 unsigned StrongPHIElimination::getPHIColor(MachineInstr* PHI) {
441   assert(PHI->isPHI());
442
443   unsigned DestReg = PHI->getOperand(0).getReg();
444   Node* DestNode = RegNodeMap[DestReg];
445   if (DestNode->parent.getInt() & Node::kPHIIsolatedFlag)
446     return 0;
447
448   for (unsigned i = 1; i < PHI->getNumOperands(); i += 2) {
449     unsigned SrcColor = getRegColor(PHI->getOperand(i).getReg());
450     if (SrcColor)
451       return SrcColor;
452   }
453   return 0;
454 }
455
456 void StrongPHIElimination::isolatePHI(MachineInstr* PHI) {
457   assert(PHI->isPHI());
458   Node* Node = RegNodeMap[PHI->getOperand(0).getReg()];
459   Node->parent.setInt(Node->parent.getInt() | Node::kPHIIsolatedFlag);
460 }
461
462 /// SplitInterferencesForBasicBlock - traverses a basic block, splitting any
463 /// interferences found between registers in the same congruence class. It
464 /// takes two DenseMaps as arguments that it also updates:
465 ///
466 /// 1) CurrentDominatingParent, which maps a color to the register in that
467 ///    congruence class whose definition was most recently seen.
468 ///
469 /// 2) ImmediateDominatingParent, which maps a register to the register in the
470 ///    same congruence class that most immediately dominates it.
471 ///
472 /// This function assumes that it is being called in a depth-first traversal
473 /// of the dominator tree.
474 ///
475 /// The algorithm used here is a generalization of the dominance-based SSA test
476 /// for two variables. If there are variables a_1, ..., a_n such that
477 ///
478 ///   def(a_1) dom ... dom def(a_n),
479 ///
480 /// then we can test for an interference between any two a_i by only using O(n)
481 /// interference tests between pairs of variables. If i < j and a_i and a_j
482 /// interfere, then a_i is alive at def(a_j), so it is also alive at def(a_i+1).
483 /// Thus, in order to test for an interference involving a_i, we need only check
484 /// for a potential interference with a_i+1.
485 ///
486 /// This method can be generalized to arbitrary sets of variables by performing
487 /// a depth-first traversal of the dominator tree. As we traverse down a branch
488 /// of the dominator tree, we keep track of the current dominating variable and
489 /// only perform an interference test with that variable. However, when we go to
490 /// another branch of the dominator tree, the definition of the current dominating
491 /// variable may no longer dominate the current block. In order to correct this,
492 /// we need to use a stack of past choices of the current dominating variable
493 /// and pop from this stack until we find a variable whose definition actually
494 /// dominates the current block.
495 /// 
496 /// There will be one push on this stack for each variable that has become the
497 /// current dominating variable, so instead of using an explicit stack we can
498 /// simply associate the previous choice for a current dominating variable with
499 /// the new choice. This works better in our implementation, where we test for
500 /// interference in multiple distinct sets at once.
501 void
502 StrongPHIElimination::SplitInterferencesForBasicBlock(
503     MachineBasicBlock& MBB,
504     DenseMap<unsigned, unsigned>& CurrentDominatingParent,
505     DenseMap<unsigned, unsigned>& ImmediateDominatingParent) {
506   // Sort defs by their order in the original basic block, as the code below
507   // assumes that it is processing definitions in dominance order.
508   std::vector<MachineInstr*>& DefInstrs = PHISrcDefs[&MBB];
509   std::sort(DefInstrs.begin(), DefInstrs.end(), MIIndexCompare(LI));
510
511   for (std::vector<MachineInstr*>::const_iterator BBI = DefInstrs.begin(),
512        BBE = DefInstrs.end(); BBI != BBE; ++BBI) {
513     for (MachineInstr::const_mop_iterator I = (*BBI)->operands_begin(),
514          E = (*BBI)->operands_end(); I != E; ++I) {
515       const MachineOperand& MO = *I;
516
517       // FIXME: This would be faster if it were possible to bail out of checking
518       // an instruction's operands after the explicit defs, but this is incorrect
519       // for variadic instructions, which may appear before register allocation
520       // in the future.
521       if (!MO.isReg() || !MO.isDef())
522         continue;
523
524       unsigned DestReg = MO.getReg();
525       if (!DestReg || !TargetRegisterInfo::isVirtualRegister(DestReg))
526         continue;
527
528       // If the virtual register being defined is not used in any PHI or has
529       // already been isolated, then there are no more interferences to check.
530       unsigned DestColor = getRegColor(DestReg);
531       if (!DestColor)
532         continue;
533
534       // The input to this pass sometimes is not in SSA form in every basic
535       // block, as some virtual registers have redefinitions. We could eliminate
536       // this by fixing the passes that generate the non-SSA code, or we could
537       // handle it here by tracking defining machine instructions rather than
538       // virtual registers. For now, we just handle the situation conservatively
539       // in a way that will possibly lead to false interferences.
540       unsigned NewParent = CurrentDominatingParent[DestColor];
541       if (NewParent == DestReg)
542         continue;
543
544       // Pop registers from the stack represented by ImmediateDominatingParent
545       // until we find a parent that dominates the current instruction.
546       while (NewParent && (!DT->dominates(MRI->getVRegDef(NewParent), *BBI)
547                            || !getRegColor(NewParent)))
548         NewParent = ImmediateDominatingParent[NewParent];
549
550       // If NewParent is nonzero, then its definition dominates the current
551       // instruction, so it is only necessary to check for the liveness of
552       // NewParent in order to check for an interference.
553       if (NewParent
554           && LI->getInterval(NewParent).liveAt(LI->getInstructionIndex(*BBI))) {
555         // If there is an interference, always isolate the new register. This
556         // could be improved by using a heuristic that decides which of the two
557         // registers to isolate.
558         isolateReg(DestReg);
559         CurrentDominatingParent[DestColor] = NewParent;
560       } else {
561         // If there is no interference, update ImmediateDominatingParent and set
562         // the CurrentDominatingParent for this color to the current register.
563         ImmediateDominatingParent[DestReg] = NewParent;
564         CurrentDominatingParent[DestColor] = DestReg;
565       }
566     }
567   }
568
569   // We now walk the PHIs in successor blocks and check for interferences. This
570   // is necesary because the use of a PHI's operands are logically contained in
571   // the predecessor block. The def of a PHI's destination register is processed
572   // along with the other defs in a basic block.
573
574   CurrentPHIForColor.clear();
575
576   for (MachineBasicBlock::succ_iterator SI = MBB.succ_begin(),
577        SE = MBB.succ_end(); SI != SE; ++SI) {
578     for (MachineBasicBlock::iterator BBI = (*SI)->begin(), BBE = (*SI)->end();
579          BBI != BBE && BBI->isPHI(); ++BBI) {
580       MachineInstr* PHI = BBI;
581
582       // If a PHI is already isolated, either by being isolated directly or
583       // having all of its operands isolated, ignore it.
584       unsigned Color = getPHIColor(PHI);
585       if (!Color)
586         continue;
587
588       // Find the index of the PHI operand that corresponds to this basic block.
589       unsigned PredIndex;
590       for (PredIndex = 1; PredIndex < PHI->getNumOperands(); PredIndex += 2) {
591         if (PHI->getOperand(PredIndex + 1).getMBB() == &MBB)
592           break;
593       }
594       assert(PredIndex < PHI->getNumOperands());
595       unsigned PredOperandReg = PHI->getOperand(PredIndex).getReg();
596
597       // Pop registers from the stack represented by ImmediateDominatingParent
598       // until we find a parent that dominates the current instruction.
599       unsigned NewParent = CurrentDominatingParent[Color];
600       while (NewParent
601              && (!DT->dominates(MRI->getVRegDef(NewParent)->getParent(), &MBB)
602                  || !getRegColor(NewParent)))
603         NewParent = ImmediateDominatingParent[NewParent];
604       CurrentDominatingParent[Color] = NewParent;
605
606       // If there is an interference with a register, always isolate the
607       // register rather than the PHI. It is also possible to isolate the
608       // PHI, but that introduces copies for all of the registers involved
609       // in that PHI.
610       if (NewParent && LI->isLiveOutOfMBB(LI->getInterval(NewParent), &MBB)
611                     && NewParent != PredOperandReg)
612         isolateReg(NewParent);
613
614       std::pair<MachineInstr*, unsigned> CurrentPHI = CurrentPHIForColor[Color];
615
616       // If two PHIs have the same operand from every shared predecessor, then
617       // they don't actually interfere. Otherwise, isolate the current PHI. This
618       // could possibly be improved, e.g. we could isolate the PHI with the
619       // fewest operands.
620       if (CurrentPHI.first && CurrentPHI.second != PredOperandReg)
621         isolatePHI(PHI);
622       else
623         CurrentPHIForColor[Color] = std::make_pair(PHI, PredOperandReg);
624     }
625   }
626 }
627
628 void StrongPHIElimination::InsertCopiesForPHI(MachineInstr* PHI,
629                                               MachineBasicBlock* MBB) {
630   assert(PHI->isPHI());
631   unsigned PHIColor = getPHIColor(PHI);
632
633   for (unsigned i = 1; i < PHI->getNumOperands(); i += 2) {
634     MachineOperand& SrcMO = PHI->getOperand(i);
635
636     // If a source is defined by an implicit def, there is no need to insert a
637     // copy in the predecessor.
638     if (SrcMO.isUndef())
639       continue;
640
641     unsigned SrcReg = SrcMO.getReg();
642     assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
643            "Machine PHI Operands must all be virtual registers!");
644
645     MachineBasicBlock* PredBB = PHI->getOperand(i + 1).getMBB();
646     unsigned SrcColor = getRegColor(SrcReg);
647
648     // If neither the PHI nor the operand were isolated, then we only need to
649     // set the phi-kill flag on the VNInfo at this PHI.
650     if (PHIColor && SrcColor == PHIColor) {
651       LiveInterval& SrcInterval = LI->getInterval(SrcReg);
652       SlotIndex PredIndex = LI->getMBBEndIdx(PredBB);
653       VNInfo* SrcVNI = SrcInterval.getVNInfoAt(PredIndex.getPrevIndex());
654       assert(SrcVNI);
655       SrcVNI->setHasPHIKill(true);
656       continue;
657     }
658
659     unsigned CopyReg = 0;
660     if (PHIColor) {
661       SrcCopyMap::const_iterator I
662         = InsertedSrcCopyMap.find(std::make_pair(PredBB, PHIColor));
663       CopyReg
664         = I != InsertedSrcCopyMap.end() ? I->second->getOperand(0).getReg() : 0;
665     }
666
667     if (!CopyReg) {
668       const TargetRegisterClass* RC = MRI->getRegClass(SrcReg);
669       CopyReg = MRI->createVirtualRegister(RC);
670
671       MachineBasicBlock::iterator
672         CopyInsertPoint = findPHICopyInsertPoint(PredBB, MBB, SrcReg);
673       unsigned SrcSubReg = SrcMO.getSubReg();
674       MachineInstr* CopyInstr = BuildMI(*PredBB,
675                                         CopyInsertPoint,
676                                         PHI->getDebugLoc(),
677                                         TII->get(TargetOpcode::COPY),
678                                         CopyReg).addReg(SrcReg, 0, SrcSubReg);
679       LI->InsertMachineInstrInMaps(CopyInstr);
680
681       // addLiveRangeToEndOfBlock() also adds the phikill flag to the VNInfo for
682       // the newly added range.
683       LI->addLiveRangeToEndOfBlock(CopyReg, CopyInstr);
684       InsertedSrcCopySet.insert(std::make_pair(PredBB, SrcReg));
685
686       addReg(CopyReg);
687       if (PHIColor) {
688         unionRegs(PHIColor, CopyReg);
689         assert(getRegColor(CopyReg) != CopyReg);
690       } else {
691         PHIColor = CopyReg;
692         assert(getRegColor(CopyReg) == CopyReg);
693       }
694
695       if (!InsertedSrcCopyMap.count(std::make_pair(PredBB, PHIColor)))
696         InsertedSrcCopyMap[std::make_pair(PredBB, PHIColor)] = CopyInstr;
697     }
698
699     SrcMO.setReg(CopyReg);
700
701     // If SrcReg is not live beyond the PHI, trim its interval so that it is no
702     // longer live-in to MBB. Note that SrcReg may appear in other PHIs that are
703     // processed later, but this is still correct to do at this point because we
704     // never rely on LiveIntervals being correct while inserting copies.
705     // FIXME: Should this just count uses at PHIs like the normal PHIElimination
706     // pass does?
707     LiveInterval& SrcLI = LI->getInterval(SrcReg);
708     SlotIndex MBBStartIndex = LI->getMBBStartIdx(MBB);
709     SlotIndex PHIIndex = LI->getInstructionIndex(PHI);
710     SlotIndex NextInstrIndex = PHIIndex.getNextIndex();
711     if (SrcLI.liveAt(MBBStartIndex) && SrcLI.expiredAt(NextInstrIndex))
712       SrcLI.removeRange(MBBStartIndex, PHIIndex, true);
713   }
714
715   unsigned DestReg = PHI->getOperand(0).getReg();
716   unsigned DestColor = getRegColor(DestReg);
717
718   if (PHIColor && DestColor == PHIColor) {
719     LiveInterval& DestLI = LI->getInterval(DestReg);
720
721     // Set the phi-def flag for the VN at this PHI.
722     SlotIndex PHIIndex = LI->getInstructionIndex(PHI);
723     VNInfo* DestVNI = DestLI.getVNInfoAt(PHIIndex.getDefIndex());
724     assert(DestVNI);
725     DestVNI->setIsPHIDef(true);
726   
727     // Prior to PHI elimination, the live ranges of PHIs begin at their defining
728     // instruction. After PHI elimination, PHI instructions are replaced by VNs
729     // with the phi-def flag set, and the live ranges of these VNs start at the
730     // beginning of the basic block.
731     SlotIndex MBBStartIndex = LI->getMBBStartIdx(MBB);
732     DestVNI->def = MBBStartIndex;
733     DestLI.addRange(LiveRange(MBBStartIndex,
734                               PHIIndex.getDefIndex(),
735                               DestVNI));
736     return;
737   }
738
739   const TargetRegisterClass* RC = MRI->getRegClass(DestReg);
740   unsigned CopyReg = MRI->createVirtualRegister(RC);
741
742   MachineInstr* CopyInstr = BuildMI(*MBB,
743                                     MBB->SkipPHIsAndLabels(MBB->begin()),
744                                     PHI->getDebugLoc(),
745                                     TII->get(TargetOpcode::COPY),
746                                     DestReg).addReg(CopyReg);
747   LI->InsertMachineInstrInMaps(CopyInstr);
748   PHI->getOperand(0).setReg(CopyReg);
749
750   // Add the region from the beginning of MBB to the copy instruction to
751   // CopyReg's live interval, and give the VNInfo the phidef flag.
752   LiveInterval& CopyLI = LI->getOrCreateInterval(CopyReg);
753   SlotIndex MBBStartIndex = LI->getMBBStartIdx(MBB);
754   SlotIndex DestCopyIndex = LI->getInstructionIndex(CopyInstr);
755   VNInfo* CopyVNI = CopyLI.getNextValue(MBBStartIndex,
756                                         CopyInstr,
757                                         LI->getVNInfoAllocator());
758   CopyVNI->setIsPHIDef(true);
759   CopyLI.addRange(LiveRange(MBBStartIndex,
760                             DestCopyIndex.getDefIndex(),
761                             CopyVNI));
762
763   // Adjust DestReg's live interval to adjust for its new definition at
764   // CopyInstr.
765   LiveInterval& DestLI = LI->getOrCreateInterval(DestReg);
766   SlotIndex PHIIndex = LI->getInstructionIndex(PHI);
767   DestLI.removeRange(PHIIndex.getDefIndex(), DestCopyIndex.getDefIndex());
768
769   VNInfo* DestVNI = DestLI.getVNInfoAt(DestCopyIndex.getDefIndex());
770   assert(DestVNI);
771   DestVNI->def = DestCopyIndex.getDefIndex();
772
773   InsertedDestCopies[CopyReg] = CopyInstr;
774 }
775
776 void StrongPHIElimination::MergeLIsAndRename(unsigned Reg, unsigned NewReg) {
777   if (Reg == NewReg)
778     return;
779
780   LiveInterval& OldLI = LI->getInterval(Reg);
781   LiveInterval& NewLI = LI->getInterval(NewReg);
782
783   // Merge the live ranges of the two registers.
784   DenseMap<VNInfo*, VNInfo*> VNMap;
785   for (LiveInterval::iterator LRI = OldLI.begin(), LRE = OldLI.end();
786        LRI != LRE; ++LRI) {
787     LiveRange OldLR = *LRI;
788     VNInfo* OldVN = OldLR.valno;
789
790     VNInfo*& NewVN = VNMap[OldVN];
791     if (!NewVN) {
792       NewVN = NewLI.createValueCopy(OldVN, LI->getVNInfoAllocator());
793       VNMap[OldVN] = NewVN;
794     }
795
796     LiveRange LR(OldLR.start, OldLR.end, NewVN);
797     NewLI.addRange(LR);
798   }
799
800   // Remove the LiveInterval for the register being renamed and replace all
801   // of its defs and uses with the new register.
802   LI->removeInterval(Reg);
803   MRI->replaceRegWith(Reg, NewReg);
804 }