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