1 //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/MachineRegisterInfo.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/ADT/SmallPtrSet.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");
35 class VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
36 MachineRegisterInfo *MRI; // Machine register information
39 static char ID; // Pass identification, replacement for typeid
40 PNE() : MachineFunctionPass((intptr_t)&ID) {}
42 virtual bool runOnMachineFunction(MachineFunction &Fn);
44 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.addPreserved<LiveVariables>();
46 AU.addPreservedID(MachineLoopInfoID);
47 AU.addPreservedID(MachineDominatorsID);
48 MachineFunctionPass::getAnalysisUsage(AU);
52 /// findInsertionPoint - Find a safe location to insert a move to copy
53 /// source of a PHI instruction.
54 MachineBasicBlock::iterator
55 findInsertionPoint(MachineBasicBlock &MBB, MachineInstr *DefMI,
56 unsigned DstReg, unsigned SrcReg) const;
58 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
59 /// in predecessor basic blocks.
61 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
62 void LowerAtomicPHINode(MachineBasicBlock &MBB,
63 MachineBasicBlock::iterator AfterPHIsIt);
65 /// analyzePHINodes - Gather information about the PHI nodes in
66 /// here. In particular, we want to map the number of uses of a virtual
67 /// register which is used in a PHI node. We map that to the BB the
68 /// vreg is coming from. This is used later to determine when the vreg
69 /// is killed in the BB.
71 void analyzePHINodes(const MachineFunction& Fn);
73 typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair;
74 typedef std::map<BBVRegPair, unsigned> VRegPHIUse;
76 VRegPHIUse VRegPHIUseCount;
78 // Defs of PHI sources which are implicit_def.
79 SmallPtrSet<MachineInstr*, 4> ImpDefs;
83 RegisterPass<PNE> X("phi-node-elimination",
84 "Eliminate PHI nodes for register allocation");
87 const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
89 bool PNE::runOnMachineFunction(MachineFunction &Fn) {
90 MRI = &Fn.getRegInfo();
96 // Eliminate PHI instructions by inserting copies into predecessor blocks.
97 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
98 Changed |= EliminatePHINodes(Fn, *I);
100 // Remove dead IMPLICIT_DEF instructions.
101 for (SmallPtrSet<MachineInstr*,4>::iterator I = ImpDefs.begin(),
102 E = ImpDefs.end(); I != E; ++I) {
103 MachineInstr *DefMI = *I;
104 unsigned DefReg = DefMI->getOperand(0).getReg();
105 if (MRI->use_begin(DefReg) == MRI->use_end())
106 DefMI->eraseFromParent();
110 VRegPHIUseCount.clear();
115 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
116 /// predecessor basic blocks.
118 bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
119 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
120 return false; // Quick exit for basic blocks without PHIs.
122 // Get an iterator to the first instruction after the last PHI node (this may
123 // also be the end of the basic block).
124 MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
125 while (AfterPHIsIt != MBB.end() &&
126 AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
127 ++AfterPHIsIt; // Skip over all of the PHI nodes...
129 while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
130 LowerAtomicPHINode(MBB, AfterPHIsIt);
135 /// findInsertionPoint - Find a safe location to insert a move to copy
136 /// source of a PHI instruction.
137 MachineBasicBlock::iterator
138 PNE::findInsertionPoint(MachineBasicBlock &MBB, MachineInstr *DefMI,
139 unsigned DstReg, unsigned SrcReg) const {
140 if (DefMI->getOpcode() == TargetInstrInfo::PHI ||
141 DefMI->getParent() != &MBB)
142 return MBB.getFirstTerminator();
144 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(SrcReg),
145 E = MRI->use_end(); I != E; ++I)
146 if (I->getParent() == &MBB)
147 return MBB.getFirstTerminator();
148 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(DstReg),
149 E = MRI->use_end(); I != E; ++I)
150 if (I->getParent() == &MBB)
151 return MBB.getFirstTerminator();
153 MachineBasicBlock::iterator I = DefMI;
157 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
158 /// under the assuption that it needs to be lowered in a way that supports
159 /// atomic execution of PHIs. This lowering method is always correct all of the
161 void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
162 MachineBasicBlock::iterator AfterPHIsIt) {
163 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
164 MachineInstr *MPhi = MBB.remove(MBB.begin());
166 unsigned DestReg = MPhi->getOperand(0).getReg();
168 // Create a new register for the incoming PHI arguments.
169 MachineFunction &MF = *MBB.getParent();
170 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
171 unsigned IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
173 // Insert a register to register copy in the top of the current block (but
174 // after any remaining phi nodes) which copies the new incoming register
175 // into the phi node destination.
177 const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
178 TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
180 // Update live variable information if there is any...
181 LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
183 MachineInstr *PHICopy = prior(AfterPHIsIt);
185 // Increment use count of the newly created virtual register.
186 LV->getVarInfo(IncomingReg).NumUses++;
188 // Add information to LiveVariables to know that the incoming value is
189 // killed. Note that because the value is defined in several places (once
190 // each for each incoming block), the "def" block and instruction fields
191 // for the VarInfo is not filled in.
193 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
195 // Since we are going to be deleting the PHI node, if it is the last use
196 // of any registers, or if the value itself is dead, we need to move this
197 // information over to the new copy we just inserted.
199 LV->removeVirtualRegistersKilled(MPhi);
201 // If the result is dead, update LV.
202 if (MPhi->registerDefIsDead(DestReg)) {
203 LV->addVirtualRegisterDead(DestReg, PHICopy);
204 LV->removeVirtualRegistersDead(MPhi);
207 LV->getVarInfo(IncomingReg).UsedBlocks[MBB.getNumber()] = true;
210 // Adjust the VRegPHIUseCount map to account for the removal of this PHI
212 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
213 --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
214 MPhi->getOperand(i).getReg())];
216 // Now loop over all of the incoming arguments, changing them to copy into
217 // the IncomingReg register in the corresponding predecessor basic block.
219 SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
220 for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
221 unsigned SrcReg = MPhi->getOperand(i-1).getReg();
222 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
223 "Machine PHI Operands must all be virtual registers!");
225 // If source is defined by an implicit def, there is no need to insert
227 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
228 if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
229 ImpDefs.insert(DefMI);
233 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
234 // source path the PHI.
235 MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMBB();
237 // Check to make sure we haven't already emitted the copy for this block.
238 // This can happen because PHI nodes may have multiple entries for the
240 if (!MBBsInsertedInto.insert(&opBlock))
241 continue; // If the copy has already been emitted, we're done.
243 // Find a safe location to insert the copy, this may be the first
244 // terminator in the block (or end()).
245 MachineBasicBlock::iterator InsertPos =
246 findInsertionPoint(opBlock, DefMI, IncomingReg, SrcReg);
249 TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC);
251 // Now update live variable information if we have it. Otherwise we're done
254 // We want to be able to insert a kill of the register if this PHI
255 // (aka, the copy we just inserted) is the last use of the source
256 // value. Live variable analysis conservatively handles this by
257 // saying that the value is live until the end of the block the PHI
258 // entry lives in. If the value really is dead at the PHI copy, there
259 // will be no successor blocks which have the value live-in.
261 // Check to see if the copy is the last use, and if so, update the
262 // live variables information so that it knows the copy source
263 // instruction kills the incoming value.
265 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
266 InRegVI.UsedBlocks[opBlock.getNumber()] = true;
268 // Loop over all of the successors of the basic block, checking to see
269 // if the value is either live in the block, or if it is killed in the
270 // block. Also check to see if this register is in use by another PHI
271 // node which has not yet been eliminated. If so, it will be killed
272 // at an appropriate point later.
275 // Is it used by any PHI instructions in this block?
276 bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
278 std::vector<MachineBasicBlock*> OpSuccBlocks;
280 // Otherwise, scan successors, including the BB the PHI node lives in.
281 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
282 E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
283 MachineBasicBlock *SuccMBB = *SI;
285 // Is it alive in this successor?
286 unsigned SuccIdx = SuccMBB->getNumber();
287 if (SuccIdx < InRegVI.AliveBlocks.size() &&
288 InRegVI.AliveBlocks[SuccIdx]) {
293 OpSuccBlocks.push_back(SuccMBB);
296 // Check to see if this value is live because there is a use in a successor
299 switch (OpSuccBlocks.size()) {
301 MachineBasicBlock *MBB = OpSuccBlocks[0];
302 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
303 if (InRegVI.Kills[i]->getParent() == MBB) {
310 MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
311 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
312 if (InRegVI.Kills[i]->getParent() == MBB1 ||
313 InRegVI.Kills[i]->getParent() == MBB2) {
320 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
321 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
322 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
323 InRegVI.Kills[i]->getParent())) {
330 // Okay, if we now know that the value is not live out of the block,
331 // we can add a kill marker in this block saying that it kills the incoming
334 // In our final twist, we have to decide which instruction kills the
335 // register. In most cases this is the copy, however, the first
336 // terminator instruction at the end of the block may also use the value.
337 // In this case, we should mark *it* as being the killing block, not the
339 MachineBasicBlock::iterator KillInst = prior(InsertPos);
340 MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
341 if (Term != opBlock.end()) {
342 if (Term->readsRegister(SrcReg))
345 // Check that no other terminators use values.
347 for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end();
349 assert(!TI->readsRegister(SrcReg) &&
350 "Terminator instructions cannot use virtual registers unless"
351 "they are the first terminator in a block!");
356 // Finally, mark it killed.
357 LV->addVirtualRegisterKilled(SrcReg, KillInst);
359 // This vreg no longer lives all of the way through opBlock.
360 unsigned opBlockNum = opBlock.getNumber();
361 if (opBlockNum < InRegVI.AliveBlocks.size())
362 InRegVI.AliveBlocks[opBlockNum] = false;
366 // Really delete the PHI instruction now!
371 /// analyzePHINodes - Gather information about the PHI nodes in here. In
372 /// particular, we want to map the number of uses of a virtual register which is
373 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
374 /// used later to determine when the vreg is killed in the BB.
376 void PNE::analyzePHINodes(const MachineFunction& Fn) {
377 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
379 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
380 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
381 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
382 ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
383 BBI->getOperand(i).getReg())];