blob: 37b7f45b1ade7f51c88772ae7c00b0527c5e02a5 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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#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"
Chris Lattner1b989192007-12-31 04:13:23 +000021#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Target/TargetInstrInfo.h"
23#include "llvm/Target/TargetMachine.h"
Evan Cheng7b66cd12008-04-03 16:38:20 +000024#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Compiler.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include <algorithm>
Evan Cheng0d34ac92008-04-02 17:23:50 +000029#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030using namespace llvm;
31
32STATISTIC(NumAtomic, "Number of atomic phis lowered");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033
34namespace {
Evan Cheng7b66cd12008-04-03 16:38:20 +000035 class VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
36 MachineRegisterInfo *MRI; // Machine register information
37
38 public:
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039 static char ID; // Pass identification, replacement for typeid
40 PNE() : MachineFunctionPass((intptr_t)&ID) {}
41
Evan Cheng7b66cd12008-04-03 16:38:20 +000042 virtual bool runOnMachineFunction(MachineFunction &Fn);
43
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.addPreserved<LiveVariables>();
Bill Wendling62264362008-01-04 20:54:55 +000046 AU.addPreservedID(MachineLoopInfoID);
47 AU.addPreservedID(MachineDominatorsID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048 MachineFunctionPass::getAnalysisUsage(AU);
49 }
50
51 private:
52 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
53 /// in predecessor basic blocks.
54 ///
55 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
56 void LowerAtomicPHINode(MachineBasicBlock &MBB,
57 MachineBasicBlock::iterator AfterPHIsIt);
58
59 /// analyzePHINodes - Gather information about the PHI nodes in
60 /// here. In particular, we want to map the number of uses of a virtual
61 /// register which is used in a PHI node. We map that to the BB the
62 /// vreg is coming from. This is used later to determine when the vreg
63 /// is killed in the BB.
64 ///
65 void analyzePHINodes(const MachineFunction& Fn);
66
67 typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair;
68 typedef std::map<BBVRegPair, unsigned> VRegPHIUse;
69
70 VRegPHIUse VRegPHIUseCount;
Evan Cheng7b66cd12008-04-03 16:38:20 +000071
72 // Defs of PHI sources which are implicit_def.
73 SmallPtrSet<MachineInstr*, 4> ImpDefs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074 };
75
76 char PNE::ID = 0;
77 RegisterPass<PNE> X("phi-node-elimination",
78 "Eliminate PHI nodes for register allocation");
79}
80
81const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
82
Evan Cheng7b66cd12008-04-03 16:38:20 +000083bool PNE::runOnMachineFunction(MachineFunction &Fn) {
84 MRI = &Fn.getRegInfo();
85
86 analyzePHINodes(Fn);
87
88 bool Changed = false;
89
90 // Eliminate PHI instructions by inserting copies into predecessor blocks.
91 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
92 Changed |= EliminatePHINodes(Fn, *I);
93
94 // Remove dead IMPLICIT_DEF instructions.
95 for (SmallPtrSet<MachineInstr*,4>::iterator I = ImpDefs.begin(),
96 E = ImpDefs.end(); I != E; ++I) {
97 MachineInstr *DefMI = *I;
98 unsigned DefReg = DefMI->getOperand(0).getReg();
99 if (MRI->use_begin(DefReg) == MRI->use_end())
100 DefMI->eraseFromParent();
101 }
102
103 ImpDefs.clear();
104 VRegPHIUseCount.clear();
105 return Changed;
106}
107
108
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000109/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
110/// predecessor basic blocks.
111///
112bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
113 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
114 return false; // Quick exit for basic blocks without PHIs.
115
116 // Get an iterator to the first instruction after the last PHI node (this may
117 // also be the end of the basic block).
118 MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
119 while (AfterPHIsIt != MBB.end() &&
120 AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
121 ++AfterPHIsIt; // Skip over all of the PHI nodes...
122
123 while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
124 LowerAtomicPHINode(MBB, AfterPHIsIt);
125
126 return true;
127}
128
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129/// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
130/// under the assuption that it needs to be lowered in a way that supports
131/// atomic execution of PHIs. This lowering method is always correct all of the
132/// time.
133void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
134 MachineBasicBlock::iterator AfterPHIsIt) {
135 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
136 MachineInstr *MPhi = MBB.remove(MBB.begin());
137
138 unsigned DestReg = MPhi->getOperand(0).getReg();
139
140 // Create a new register for the incoming PHI arguments.
141 MachineFunction &MF = *MBB.getParent();
Chris Lattner1b989192007-12-31 04:13:23 +0000142 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
143 unsigned IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144
145 // Insert a register to register copy in the top of the current block (but
146 // after any remaining phi nodes) which copies the new incoming register
147 // into the phi node destination.
148 //
Owen Anderson8f2c8932007-12-31 06:32:00 +0000149 const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
150 TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151
152 // Update live variable information if there is any...
153 LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
154 if (LV) {
155 MachineInstr *PHICopy = prior(AfterPHIsIt);
156
157 // Increment use count of the newly created virtual register.
158 LV->getVarInfo(IncomingReg).NumUses++;
159
160 // Add information to LiveVariables to know that the incoming value is
161 // killed. Note that because the value is defined in several places (once
162 // each for each incoming block), the "def" block and instruction fields
163 // for the VarInfo is not filled in.
164 //
165 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
166
167 // Since we are going to be deleting the PHI node, if it is the last use
168 // of any registers, or if the value itself is dead, we need to move this
169 // information over to the new copy we just inserted.
170 //
171 LV->removeVirtualRegistersKilled(MPhi);
172
173 // If the result is dead, update LV.
Evan Chengc7daf1f2008-03-05 00:59:57 +0000174 if (MPhi->registerDefIsDead(DestReg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 LV->addVirtualRegisterDead(DestReg, PHICopy);
176 LV->removeVirtualRegistersDead(MPhi);
177 }
Owen Anderson721b2cc2007-11-08 01:20:48 +0000178
179 LV->getVarInfo(IncomingReg).UsedBlocks[MBB.getNumber()] = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 }
181
182 // Adjust the VRegPHIUseCount map to account for the removal of this PHI
183 // node.
184 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
Chris Lattner6017d482007-12-30 23:10:15 +0000185 --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
186 MPhi->getOperand(i).getReg())];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187
188 // Now loop over all of the incoming arguments, changing them to copy into
189 // the IncomingReg register in the corresponding predecessor basic block.
190 //
Evan Cheng7b66cd12008-04-03 16:38:20 +0000191 SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
193 unsigned SrcReg = MPhi->getOperand(i-1).getReg();
Dan Gohman1e57df32008-02-10 18:45:23 +0000194 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 "Machine PHI Operands must all be virtual registers!");
196
Evan Cheng7b66cd12008-04-03 16:38:20 +0000197 // If source is defined by an implicit def, there is no need to insert
198 // a copy.
199 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
200 if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
201 ImpDefs.insert(DefMI);
202 continue;
203 }
204
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
206 // source path the PHI.
Chris Lattner6017d482007-12-30 23:10:15 +0000207 MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208
209 // Check to make sure we haven't already emitted the copy for this block.
210 // This can happen because PHI nodes may have multiple entries for the
211 // same basic block.
Evan Cheng7b66cd12008-04-03 16:38:20 +0000212 if (!MBBsInsertedInto.insert(&opBlock))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 continue; // If the copy has already been emitted, we're done.
214
Evan Cheng7b66cd12008-04-03 16:38:20 +0000215 // Find a safe location to insert the copy, this may be the first
216 // terminator in the block (or end()).
Evan Cheng3bca6ca2008-04-04 01:20:05 +0000217 MachineBasicBlock::iterator InsertPos = opBlock.getFirstTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218
219 // Insert the copy.
Evan Cheng7b66cd12008-04-03 16:38:20 +0000220 TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221
222 // Now update live variable information if we have it. Otherwise we're done
223 if (!LV) continue;
224
225 // We want to be able to insert a kill of the register if this PHI
226 // (aka, the copy we just inserted) is the last use of the source
227 // value. Live variable analysis conservatively handles this by
228 // saying that the value is live until the end of the block the PHI
229 // entry lives in. If the value really is dead at the PHI copy, there
230 // will be no successor blocks which have the value live-in.
231 //
232 // Check to see if the copy is the last use, and if so, update the
233 // live variables information so that it knows the copy source
234 // instruction kills the incoming value.
235 //
236 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
Owen Anderson721b2cc2007-11-08 01:20:48 +0000237 InRegVI.UsedBlocks[opBlock.getNumber()] = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238
239 // Loop over all of the successors of the basic block, checking to see
240 // if the value is either live in the block, or if it is killed in the
241 // block. Also check to see if this register is in use by another PHI
242 // node which has not yet been eliminated. If so, it will be killed
243 // at an appropriate point later.
244 //
245
246 // Is it used by any PHI instructions in this block?
247 bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
248
249 std::vector<MachineBasicBlock*> OpSuccBlocks;
250
251 // Otherwise, scan successors, including the BB the PHI node lives in.
252 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
253 E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
254 MachineBasicBlock *SuccMBB = *SI;
255
256 // Is it alive in this successor?
257 unsigned SuccIdx = SuccMBB->getNumber();
258 if (SuccIdx < InRegVI.AliveBlocks.size() &&
259 InRegVI.AliveBlocks[SuccIdx]) {
260 ValueIsLive = true;
261 break;
262 }
263
264 OpSuccBlocks.push_back(SuccMBB);
265 }
266
267 // Check to see if this value is live because there is a use in a successor
268 // that kills it.
269 if (!ValueIsLive) {
270 switch (OpSuccBlocks.size()) {
271 case 1: {
272 MachineBasicBlock *MBB = OpSuccBlocks[0];
273 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
274 if (InRegVI.Kills[i]->getParent() == MBB) {
275 ValueIsLive = true;
276 break;
277 }
278 break;
279 }
280 case 2: {
281 MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
282 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
283 if (InRegVI.Kills[i]->getParent() == MBB1 ||
284 InRegVI.Kills[i]->getParent() == MBB2) {
285 ValueIsLive = true;
286 break;
287 }
288 break;
289 }
290 default:
291 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
292 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
293 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
294 InRegVI.Kills[i]->getParent())) {
295 ValueIsLive = true;
296 break;
297 }
298 }
299 }
300
301 // Okay, if we now know that the value is not live out of the block,
302 // we can add a kill marker in this block saying that it kills the incoming
303 // value!
304 if (!ValueIsLive) {
305 // In our final twist, we have to decide which instruction kills the
306 // register. In most cases this is the copy, however, the first
307 // terminator instruction at the end of the block may also use the value.
308 // In this case, we should mark *it* as being the killing block, not the
309 // copy.
Evan Cheng7b66cd12008-04-03 16:38:20 +0000310 MachineBasicBlock::iterator KillInst = prior(InsertPos);
311 MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
312 if (Term != opBlock.end()) {
313 if (Term->readsRegister(SrcReg))
314 KillInst = Term;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315
316 // Check that no other terminators use values.
317#ifndef NDEBUG
Evan Cheng7b66cd12008-04-03 16:38:20 +0000318 for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 ++TI) {
Evan Cheng7b66cd12008-04-03 16:38:20 +0000320 assert(!TI->readsRegister(SrcReg) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321 "Terminator instructions cannot use virtual registers unless"
322 "they are the first terminator in a block!");
323 }
324#endif
325 }
326
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327 // Finally, mark it killed.
328 LV->addVirtualRegisterKilled(SrcReg, KillInst);
329
330 // This vreg no longer lives all of the way through opBlock.
331 unsigned opBlockNum = opBlock.getNumber();
332 if (opBlockNum < InRegVI.AliveBlocks.size())
333 InRegVI.AliveBlocks[opBlockNum] = false;
334 }
335 }
336
337 // Really delete the PHI instruction now!
338 delete MPhi;
339 ++NumAtomic;
340}
341
342/// analyzePHINodes - Gather information about the PHI nodes in here. In
343/// particular, we want to map the number of uses of a virtual register which is
344/// used in a PHI node. We map that to the BB the vreg is coming from. This is
345/// used later to determine when the vreg is killed in the BB.
346///
347void PNE::analyzePHINodes(const MachineFunction& Fn) {
348 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
349 I != E; ++I)
350 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
351 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
352 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
Chris Lattner6017d482007-12-30 23:10:15 +0000353 ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
354 BBI->getOperand(i).getReg())];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355}