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/LiveVariables.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/Statistic.h"
31 Statistic<> NumAtomic("phielim", "Number of atomic phis lowered");
32 Statistic<> NumSimple("phielim", "Number of simple phis lowered");
34 struct PNE : public MachineFunctionPass {
35 bool runOnMachineFunction(MachineFunction &Fn) {
38 // Eliminate PHI instructions by inserting copies into predecessor blocks.
39 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
40 Changed |= EliminatePHINodes(Fn, *I);
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addPreserved<LiveVariables>();
47 MachineFunctionPass::getAnalysisUsage(AU);
51 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
52 /// in predecessor basic blocks.
54 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
55 void LowerAtomicPHINode(MachineBasicBlock &MBB,
56 MachineBasicBlock::iterator AfterPHIsIt,
57 DenseMap<unsigned, VirtReg2IndexFunctor> &VUC);
60 RegisterPass<PNE> X("phi-node-elimination",
61 "Eliminate PHI nodes for register allocation");
65 const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
67 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
68 /// predecessor basic blocks.
70 bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
71 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
72 return false; // Quick exit for basic blocks without PHIs.
74 // VRegPHIUseCount - Keep track of the number of times each virtual register
75 // is used by PHI nodes in successors of this block.
76 DenseMap<unsigned, VirtReg2IndexFunctor> VRegPHIUseCount;
77 VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg());
79 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(),
80 E = MBB.pred_end(); PI != E; ++PI)
81 for (MachineBasicBlock::succ_iterator SI = (*PI)->succ_begin(),
82 E = (*PI)->succ_end(); SI != E; ++SI)
83 for (MachineBasicBlock::iterator BBI = (*SI)->begin(), E = (*SI)->end();
84 BBI != E && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
85 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
86 VRegPHIUseCount[BBI->getOperand(i).getReg()]++;
88 // Get an iterator to the first instruction after the last PHI node (this may
89 // also be the end of the basic block).
90 MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
91 while (AfterPHIsIt != MBB.end() &&
92 AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
93 ++AfterPHIsIt; // Skip over all of the PHI nodes...
95 while (MBB.front().getOpcode() == TargetInstrInfo::PHI) {
96 LowerAtomicPHINode(MBB, AfterPHIsIt, VRegPHIUseCount);
101 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
102 /// under the assuption that it needs to be lowered in a way that supports
103 /// atomic execution of PHIs. This lowering method is always correct all of the
105 void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
106 MachineBasicBlock::iterator AfterPHIsIt,
107 DenseMap<unsigned, VirtReg2IndexFunctor> &VRegPHIUseCount) {
108 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
109 MachineInstr *MPhi = MBB.remove(MBB.begin());
111 unsigned DestReg = MPhi->getOperand(0).getReg();
113 // Create a new register for the incoming PHI arguments/
114 MachineFunction &MF = *MBB.getParent();
115 const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
116 unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
118 // Insert a register to register copy in the top of the current block (but
119 // after any remaining phi nodes) which copies the new incoming register
120 // into the phi node destination.
122 const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
123 RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
125 // Update live variable information if there is any...
126 LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
128 MachineInstr *PHICopy = prior(AfterPHIsIt);
130 // Add information to LiveVariables to know that the incoming value is
131 // killed. Note that because the value is defined in several places (once
132 // each for each incoming block), the "def" block and instruction fields
133 // for the VarInfo is not filled in.
135 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
137 // Since we are going to be deleting the PHI node, if it is the last use
138 // of any registers, or if the value itself is dead, we need to move this
139 // information over to the new copy we just inserted.
141 LV->removeVirtualRegistersKilled(MPhi);
143 // If the result is dead, update LV.
144 if (LV->RegisterDefIsDead(MPhi, DestReg)) {
145 LV->addVirtualRegisterDead(DestReg, PHICopy);
146 LV->removeVirtualRegistersDead(MPhi);
150 // Adjust the VRegPHIUseCount map to account for the removal of this PHI
152 unsigned NumPreds = (MPhi->getNumOperands()-1)/2;
153 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
154 VRegPHIUseCount[MPhi->getOperand(i).getReg()] -= NumPreds;
156 // Now loop over all of the incoming arguments, changing them to copy into
157 // the IncomingReg register in the corresponding predecessor basic block.
159 std::set<MachineBasicBlock*> MBBsInsertedInto;
160 for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
161 unsigned SrcReg = MPhi->getOperand(i-1).getReg();
162 assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
163 "Machine PHI Operands must all be virtual registers!");
165 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
166 // source path the PHI.
167 MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
169 // Check to make sure we haven't already emitted the copy for this block.
170 // This can happen because PHI nodes may have multiple entries for the
172 if (!MBBsInsertedInto.insert(&opBlock).second)
173 continue; // If the copy has already been emitted, we're done.
175 // Get an iterator pointing to the first terminator in the block (or end()).
176 // This is the point where we can insert a copy if we'd like to.
177 MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
180 RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
182 // Now update live variable information if we have it. Otherwise we're done
185 // We want to be able to insert a kill of the register if this PHI
186 // (aka, the copy we just inserted) is the last use of the source
187 // value. Live variable analysis conservatively handles this by
188 // saying that the value is live until the end of the block the PHI
189 // entry lives in. If the value really is dead at the PHI copy, there
190 // will be no successor blocks which have the value live-in.
192 // Check to see if the copy is the last use, and if so, update the
193 // live variables information so that it knows the copy source
194 // instruction kills the incoming value.
196 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
198 // Loop over all of the successors of the basic block, checking to see
199 // if the value is either live in the block, or if it is killed in the
200 // block. Also check to see if this register is in use by another PHI
201 // node which has not yet been eliminated. If so, it will be killed
202 // at an appropriate point later.
205 // Is it used by any PHI instructions in this block?
206 bool ValueIsLive = VRegPHIUseCount[SrcReg] != 0;
208 std::vector<MachineBasicBlock*> OpSuccBlocks;
210 // Otherwise, scan successors, including the BB the PHI node lives in.
211 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
212 E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
213 MachineBasicBlock *SuccMBB = *SI;
215 // Is it alive in this successor?
216 unsigned SuccIdx = SuccMBB->getNumber();
217 if (SuccIdx < InRegVI.AliveBlocks.size() &&
218 InRegVI.AliveBlocks[SuccIdx]) {
223 OpSuccBlocks.push_back(SuccMBB);
226 // Check to see if this value is live because there is a use in a successor
229 switch (OpSuccBlocks.size()) {
231 MachineBasicBlock *MBB = OpSuccBlocks[0];
232 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
233 if (InRegVI.Kills[i]->getParent() == MBB) {
240 MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
241 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
242 if (InRegVI.Kills[i]->getParent() == MBB1 ||
243 InRegVI.Kills[i]->getParent() == MBB2) {
250 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
251 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
252 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
253 InRegVI.Kills[i]->getParent())) {
260 // Okay, if we now know that the value is not live out of the block,
261 // we can add a kill marker to the copy we inserted saying that it
262 // kills the incoming value!
265 MachineBasicBlock::iterator Prev = prior(I);
266 LV->addVirtualRegisterKilled(SrcReg, Prev);
268 // This vreg no longer lives all of the way through opBlock.
269 unsigned opBlockNum = opBlock.getNumber();
270 if (opBlockNum < InRegVI.AliveBlocks.size())
271 InRegVI.AliveBlocks[opBlockNum] = false;
275 // Really delete the PHI instruction now!