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