Use a new VRegPHIUseCount to compute uses of PHI values by other phi values
[oota-llvm.git] / lib / CodeGen / PHIElimination.cpp
1 //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass eliminates machine instruction PHI nodes by inserting copy
11 // instructions.  This destroys SSA information, but is the desired input for
12 // some register allocators.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/SSARegMap.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "Support/STLExtras.h"
24 using namespace llvm;
25
26 namespace {
27   struct PNE : public MachineFunctionPass {
28     bool runOnMachineFunction(MachineFunction &Fn) {
29       bool Changed = false;
30
31       // Eliminate PHI instructions by inserting copies into predecessor blocks.
32       //
33       for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
34         Changed |= EliminatePHINodes(Fn, *I);
35
36       //std::cerr << "AFTER PHI NODE ELIM:\n";
37       //Fn.dump();
38       return Changed;
39     }
40
41     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42       AU.addPreserved<LiveVariables>();
43       MachineFunctionPass::getAnalysisUsage(AU);
44     }
45
46   private:
47     /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
48     /// in predecessor basic blocks.
49     ///
50     bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
51   };
52
53   RegisterPass<PNE> X("phi-node-elimination",
54                       "Eliminate PHI nodes for register allocation");
55 }
56
57
58 const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
59
60 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
61 /// predecessor basic blocks.
62 ///
63 bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
64   if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
65     return false;   // Quick exit for normal case...
66
67   LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
68   const TargetInstrInfo &MII = MF.getTarget().getInstrInfo();
69   const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
70
71   // VRegPHIUseCount - Keep track of the number of times each virtual register
72   // is used by PHI nodes in this block.
73   std::map<unsigned, unsigned> VRegPHIUseCount;
74
75   // Get an iterator to the first instruction after the last PHI node (this may
76   // allso be the end of the basic block).  While we are scanning the PHIs,
77   // populate the VRegPHIUseCount map.
78   MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
79   while (AfterPHIsIt != MBB.end() &&
80          AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI) {
81     MachineInstr *PHI = AfterPHIsIt;
82     for (unsigned i = 1, e = PHI->getNumOperands(); i < e; i += 2)
83       VRegPHIUseCount[PHI->getOperand(i).getReg()]++;
84     ++AfterPHIsIt;    // Skip over all of the PHI nodes...
85   }
86
87   while (MBB.front().getOpcode() == TargetInstrInfo::PHI) {
88     // Unlink the PHI node from the basic block... but don't delete the PHI yet
89     MachineInstr *MI = MBB.remove(MBB.begin());
90     
91     assert(MRegisterInfo::isVirtualRegister(MI->getOperand(0).getReg()) &&
92            "PHI node doesn't write virt reg?");
93
94     unsigned DestReg = MI->getOperand(0).getReg();
95     
96     // Create a new register for the incoming PHI arguments
97     const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
98     unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
99
100     // Insert a register to register copy in the top of the current block (but
101     // after any remaining phi nodes) which copies the new incoming register
102     // into the phi node destination.
103     //
104     RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
105     
106     // Update live variable information if there is any...
107     if (LV) {
108       MachineInstr *PHICopy = prior(AfterPHIsIt);
109
110       // Add information to LiveVariables to know that the incoming value is
111       // killed.  Note that because the value is defined in several places (once
112       // each for each incoming block), the "def" block and instruction fields
113       // for the VarInfo is not filled in.
114       //
115       LV->addVirtualRegisterKilled(IncomingReg, &MBB, PHICopy);
116
117       // Since we are going to be deleting the PHI node, if it is the last use
118       // of any registers, or if the value itself is dead, we need to move this
119       // information over to the new copy we just inserted...
120       //
121       std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator> 
122         RKs = LV->killed_range(MI);
123       std::vector<std::pair<MachineInstr*, unsigned> > Range;
124       if (RKs.first != RKs.second) {
125         // Copy the range into a vector...
126         Range.assign(RKs.first, RKs.second);
127
128         // Delete the range...
129         LV->removeVirtualRegistersKilled(RKs.first, RKs.second);
130
131         // Add all of the kills back, which will update the appropriate info...
132         for (unsigned i = 0, e = Range.size(); i != e; ++i)
133           LV->addVirtualRegisterKilled(Range[i].second, &MBB, PHICopy);
134       }
135
136       RKs = LV->dead_range(MI);
137       if (RKs.first != RKs.second) {
138         // Works as above...
139         Range.assign(RKs.first, RKs.second);
140         LV->removeVirtualRegistersDead(RKs.first, RKs.second);
141         for (unsigned i = 0, e = Range.size(); i != e; ++i)
142           LV->addVirtualRegisterDead(Range[i].second, &MBB, PHICopy);
143       }
144     }
145
146     // Adjust the VRegPHIUseCount map to account for the removal of this PHI
147     // node.
148     for (unsigned i = 1; i != MI->getNumOperands(); i += 2)
149       VRegPHIUseCount[MI->getOperand(i).getReg()]--;
150
151     // Now loop over all of the incoming arguments, changing them to copy into
152     // the IncomingReg register in the corresponding predecessor basic block.
153     //
154     for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
155       MachineOperand &opVal = MI->getOperand(i-1);
156       
157       // Get the MachineBasicBlock equivalent of the BasicBlock that is the
158       // source path the PHI.
159       MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
160
161       MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
162       
163       // Check to make sure we haven't already emitted the copy for this block.
164       // This can happen because PHI nodes may have multiple entries for the
165       // same basic block.  It doesn't matter which entry we use though, because
166       // all incoming values are guaranteed to be the same for a particular bb.
167       //
168       // If we emitted a copy for this basic block already, it will be right
169       // where we want to insert one now.  Just check for a definition of the
170       // register we are interested in!
171       //
172       bool HaveNotEmitted = true;
173       
174       if (I != opBlock.begin()) {
175         MachineBasicBlock::iterator PrevInst = prior(I);
176         for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) {
177           MachineOperand &MO = PrevInst->getOperand(i);
178           if (MO.isRegister() && MO.getReg() == IncomingReg)
179             if (MO.isDef()) {
180               HaveNotEmitted = false;
181               break;
182             }             
183         }
184       }
185
186       if (HaveNotEmitted) { // If the copy has not already been emitted, do it.
187         assert(MRegisterInfo::isVirtualRegister(opVal.getReg()) &&
188                "Machine PHI Operands must all be virtual registers!");
189         unsigned SrcReg = opVal.getReg();
190         RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
191
192         // Now update live variable information if we have it.
193         if (LV) {
194           // We want to be able to insert a kill of the register if this PHI
195           // (aka, the copy we just inserted) is the last use of the source
196           // value.  Live variable analysis conservatively handles this by
197           // saying that the value is live until the end of the block the PHI
198           // entry lives in.  If the value really is dead at the PHI copy, there
199           // will be no successor blocks which have the value live-in.
200           //
201           // Check to see if the copy is the last use, and if so, update the
202           // live variables information so that it knows the copy source
203           // instruction kills the incoming value.
204           //
205           LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
206
207           // Loop over all of the successors of the basic block, checking to see
208           // if the value is either live in the block, or if it is killed in the
209           // block.  Also check to see if this register is in use by another PHI
210           // node which has not yet been eliminated.  If so, it will be killed
211           // at an appropriate point later.
212           //
213           bool ValueIsLive = false;
214           for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
215                  E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
216             MachineBasicBlock *MBB = *SI;
217             
218             // Is it alive in this successor?
219             unsigned SuccIdx = LV->getMachineBasicBlockIndex(MBB);
220             if (SuccIdx < InRegVI.AliveBlocks.size() &&
221                 InRegVI.AliveBlocks[SuccIdx]) {
222               ValueIsLive = true;
223               break;
224             }
225             
226             // Is it killed in this successor?
227             for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
228               if (InRegVI.Kills[i].first == MBB) {
229                 ValueIsLive = true;
230                 break;
231               }
232
233             // Is it used by any PHI instructions in this block?
234             if (!ValueIsLive) {
235               std::map<unsigned,unsigned>::iterator I =
236                 VRegPHIUseCount.find(SrcReg);
237               ValueIsLive = I != VRegPHIUseCount.end() && I->second;
238             }
239           }
240           
241           // Okay, if we now know that the value is not live out of the block,
242           // we can add a kill marker to the copy we inserted saying that it
243           // kills the incoming value!
244           //
245           if (!ValueIsLive) {
246             MachineBasicBlock::iterator Prev = prior(I);
247             LV->addVirtualRegisterKilled(SrcReg, &opBlock, Prev);
248           }
249         }
250       }
251     }
252     
253     // really delete the PHI instruction now!
254     delete MI;
255   }
256   return true;
257 }