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 #define DEBUG_TYPE "phielim"
17 #include "llvm/CodeGen/LiveVariables.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Compiler.h"
32 STATISTIC(NumAtomic, "Number of atomic phis lowered");
33 //STATISTIC(NumSimple, "Number of simple phis lowered");
36 struct VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
37 bool runOnMachineFunction(MachineFunction &Fn) {
42 // Eliminate PHI instructions by inserting copies into predecessor blocks.
43 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
44 Changed |= EliminatePHINodes(Fn, *I);
46 VRegPHIUseCount.clear();
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addPreserved<LiveVariables>();
52 MachineFunctionPass::getAnalysisUsage(AU);
56 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
57 /// in predecessor basic blocks.
59 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
60 void LowerAtomicPHINode(MachineBasicBlock &MBB,
61 MachineBasicBlock::iterator AfterPHIsIt);
63 /// analyzePHINodes - Gather information about the PHI nodes in
64 /// here. In particular, we want to map the number of uses of a virtual
65 /// register which is used in a PHI node. We map that to the BB the
66 /// vreg is coming from. This is used later to determine when the vreg
67 /// is killed in the BB.
69 void analyzePHINodes(const MachineFunction& Fn);
71 typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair;
72 typedef std::map<BBVRegPair, unsigned> VRegPHIUse;
74 VRegPHIUse VRegPHIUseCount;
77 RegisterPass<PNE> X("phi-node-elimination",
78 "Eliminate PHI nodes for register allocation");
81 const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
83 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
84 /// predecessor basic blocks.
86 bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
87 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
88 return false; // Quick exit for basic blocks without PHIs.
90 // Get an iterator to the first instruction after the last PHI node (this may
91 // also be the end of the basic block).
92 MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
93 while (AfterPHIsIt != MBB.end() &&
94 AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
95 ++AfterPHIsIt; // Skip over all of the PHI nodes...
97 while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
98 LowerAtomicPHINode(MBB, AfterPHIsIt);
103 /// InstructionUsesRegister - Return true if the specified machine instr has a
104 /// use of the specified register.
105 static bool InstructionUsesRegister(MachineInstr *MI, unsigned SrcReg) {
106 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
107 if (MI->getOperand(i).isRegister() &&
108 MI->getOperand(i).getReg() == SrcReg &&
109 MI->getOperand(i).isUse())
114 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
115 /// under the assuption that it needs to be lowered in a way that supports
116 /// atomic execution of PHIs. This lowering method is always correct all of the
118 void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
119 MachineBasicBlock::iterator AfterPHIsIt) {
120 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
121 MachineInstr *MPhi = MBB.remove(MBB.begin());
123 unsigned DestReg = MPhi->getOperand(0).getReg();
125 // Create a new register for the incoming PHI arguments.
126 MachineFunction &MF = *MBB.getParent();
127 const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
128 unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
130 // Insert a register to register copy in the top of the current block (but
131 // after any remaining phi nodes) which copies the new incoming register
132 // into the phi node destination.
134 const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
135 RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
137 // Update live variable information if there is any...
138 LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
140 MachineInstr *PHICopy = prior(AfterPHIsIt);
142 // Add information to LiveVariables to know that the incoming value is
143 // killed. Note that because the value is defined in several places (once
144 // each for each incoming block), the "def" block and instruction fields
145 // for the VarInfo is not filled in.
147 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
149 // Since we are going to be deleting the PHI node, if it is the last use
150 // of any registers, or if the value itself is dead, we need to move this
151 // information over to the new copy we just inserted.
153 LV->removeVirtualRegistersKilled(MPhi);
155 // If the result is dead, update LV.
156 if (LV->RegisterDefIsDead(MPhi, DestReg)) {
157 LV->addVirtualRegisterDead(DestReg, PHICopy);
158 LV->removeVirtualRegistersDead(MPhi);
161 // Realize that the destination register is defined by the PHI copy now, not
163 LV->getVarInfo(DestReg).DefInst = PHICopy;
166 // Adjust the VRegPHIUseCount map to account for the removal of this PHI
168 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
169 --VRegPHIUseCount[BBVRegPair(
170 MPhi->getOperand(i + 1).getMachineBasicBlock(),
171 MPhi->getOperand(i).getReg())];
173 // Now loop over all of the incoming arguments, changing them to copy into
174 // the IncomingReg register in the corresponding predecessor basic block.
176 std::set<MachineBasicBlock*> MBBsInsertedInto;
177 for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
178 unsigned SrcReg = MPhi->getOperand(i-1).getReg();
179 assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
180 "Machine PHI Operands must all be virtual registers!");
182 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
183 // source path the PHI.
184 MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
186 // Check to make sure we haven't already emitted the copy for this block.
187 // This can happen because PHI nodes may have multiple entries for the
189 if (!MBBsInsertedInto.insert(&opBlock).second)
190 continue; // If the copy has already been emitted, we're done.
192 // Get an iterator pointing to the first terminator in the block (or end()).
193 // This is the point where we can insert a copy if we'd like to.
194 MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
197 RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
199 // Now update live variable information if we have it. Otherwise we're done
202 // We want to be able to insert a kill of the register if this PHI
203 // (aka, the copy we just inserted) is the last use of the source
204 // value. Live variable analysis conservatively handles this by
205 // saying that the value is live until the end of the block the PHI
206 // entry lives in. If the value really is dead at the PHI copy, there
207 // will be no successor blocks which have the value live-in.
209 // Check to see if the copy is the last use, and if so, update the
210 // live variables information so that it knows the copy source
211 // instruction kills the incoming value.
213 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
215 // Loop over all of the successors of the basic block, checking to see
216 // if the value is either live in the block, or if it is killed in the
217 // block. Also check to see if this register is in use by another PHI
218 // node which has not yet been eliminated. If so, it will be killed
219 // at an appropriate point later.
222 // Is it used by any PHI instructions in this block?
223 bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
225 std::vector<MachineBasicBlock*> OpSuccBlocks;
227 // Otherwise, scan successors, including the BB the PHI node lives in.
228 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
229 E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
230 MachineBasicBlock *SuccMBB = *SI;
232 // Is it alive in this successor?
233 unsigned SuccIdx = SuccMBB->getNumber();
234 if (SuccIdx < InRegVI.AliveBlocks.size() &&
235 InRegVI.AliveBlocks[SuccIdx]) {
240 OpSuccBlocks.push_back(SuccMBB);
243 // Check to see if this value is live because there is a use in a successor
246 switch (OpSuccBlocks.size()) {
248 MachineBasicBlock *MBB = OpSuccBlocks[0];
249 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
250 if (InRegVI.Kills[i]->getParent() == MBB) {
257 MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
258 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
259 if (InRegVI.Kills[i]->getParent() == MBB1 ||
260 InRegVI.Kills[i]->getParent() == MBB2) {
267 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
268 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
269 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
270 InRegVI.Kills[i]->getParent())) {
277 // Okay, if we now know that the value is not live out of the block,
278 // we can add a kill marker in this block saying that it kills the incoming
281 // In our final twist, we have to decide which instruction kills the
282 // register. In most cases this is the copy, however, the first
283 // terminator instruction at the end of the block may also use the value.
284 // In this case, we should mark *it* as being the killing block, not the
286 bool FirstTerminatorUsesValue = false;
287 if (I != opBlock.end()) {
288 FirstTerminatorUsesValue = InstructionUsesRegister(I, SrcReg);
290 // Check that no other terminators use values.
292 for (MachineBasicBlock::iterator TI = next(I); TI != opBlock.end();
294 assert(!InstructionUsesRegister(TI, SrcReg) &&
295 "Terminator instructions cannot use virtual registers unless"
296 "they are the first terminator in a block!");
301 MachineBasicBlock::iterator KillInst;
302 if (!FirstTerminatorUsesValue)
307 // Finally, mark it killed.
308 LV->addVirtualRegisterKilled(SrcReg, KillInst);
310 // This vreg no longer lives all of the way through opBlock.
311 unsigned opBlockNum = opBlock.getNumber();
312 if (opBlockNum < InRegVI.AliveBlocks.size())
313 InRegVI.AliveBlocks[opBlockNum] = false;
317 // Really delete the PHI instruction now!
322 /// analyzePHINodes - Gather information about the PHI nodes in here. In
323 /// particular, we want to map the number of uses of a virtual register which is
324 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
325 /// used later to determine when the vreg is killed in the BB.
327 void PNE::analyzePHINodes(const MachineFunction& Fn) {
328 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
330 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
331 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
332 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
333 ++VRegPHIUseCount[BBVRegPair(
334 BBI->getOperand(i + 1).getMachineBasicBlock(),
335 BBI->getOperand(i).getReg())];