1 //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
25 struct PNE : public MachineFunctionPass {
26 bool runOnMachineFunction(MachineFunction &Fn) {
29 // Eliminate PHI instructions by inserting copies into predecessor blocks.
31 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
32 Changed |= EliminatePHINodes(Fn, *I);
34 //std::cerr << "AFTER PHI NODE ELIM:\n";
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addPreserved<LiveVariables>();
41 MachineFunctionPass::getAnalysisUsage(AU);
45 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
46 /// in predecessor basic blocks.
48 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
51 RegisterPass<PNE> X("phi-node-elimination",
52 "Eliminate PHI nodes for register allocation");
55 const PassInfo *PHIEliminationID = X.getPassInfo();
57 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
58 /// predecessor basic blocks.
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...
64 LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
65 const TargetInstrInfo &MII = MF.getTarget().getInstrInfo();
66 const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
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());
73 assert(MI->getOperand(0).isVirtualRegister() &&
74 "PHI node doesn't write virt reg?");
76 unsigned DestReg = MI->getOperand(0).getAllocatedRegNum();
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);
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.
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);
92 // Update live variable information if there is any...
94 MachineInstr *PHICopy = *(AfterPHIsIt-1);
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.
101 LV->addVirtualRegisterKilled(IncomingReg, &MBB, PHICopy);
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...
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);
114 // Delete the range...
115 LV->removeVirtualRegistersKilled(RKs.first, RKs.second);
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);
122 RKs = LV->dead_range(MI);
123 if (RKs.first != RKs.second) {
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);
132 // Now loop over all of the incoming arguments, changing them to copy into
133 // the IncomingReg register in the corresponding predecessor basic block.
135 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
136 MachineOperand &opVal = MI->getOperand(i-1);
138 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
139 // source path the PHI.
140 MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
142 // Figure out where to insert the copy, which is at the end of the
143 // predecessor basic block, but before any terminator/branch
145 MachineBasicBlock::iterator I = opBlock.end();
146 if (I != opBlock.begin()) { // Handle empty blocks
148 // must backtrack over ALL the branches in the previous block
149 while (MII.isTerminatorInstr((*I)->getOpcode()) &&
150 I != opBlock.begin())
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()))
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.
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!
168 bool HaveNotEmitted = true;
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;
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);
188 // Now update live variable information if we have it.
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.
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.
201 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
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.
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);
216 // Is it alive in this successor?
217 unsigned SuccIdx = SuccInfo.second;
218 if (SuccIdx < InRegVI.AliveBlocks.size() &&
219 InRegVI.AliveBlocks[SuccIdx]) {
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) {
232 // Is it used by any PHI instructions in this block?
233 if (ValueIsLive) break;
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;
240 for (unsigned i = 1, e = (*BBI)->getNumOperands(); i < e; i += 2)
241 if ((*BBI)->getOperand(i).getReg() == SrcReg) {
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!
252 LV->addVirtualRegisterKilled(SrcReg, &opBlock, *(I-1));
257 // really delete the PHI instruction now!