blob: a5d17c2e4b075f13cc9cb072db488d6877eed86f [file] [log] [blame]
Chris Lattnerbc40e892003-01-13 20:01:16 +00001//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
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.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbc40e892003-01-13 20:01:16 +00009//
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
Chris Lattnercd3245a2006-12-19 22:41:21 +000016#define DEBUG_TYPE "phielim"
Misha Brukmand7a10c82005-05-05 23:45:17 +000017#include "llvm/CodeGen/LiveVariables.h"
Chris Lattner0742b592004-02-23 18:38:20 +000018#include "llvm/CodeGen/Passes.h"
Chris Lattnerbc40e892003-01-13 20:01:16 +000019#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/CodeGen/MachineInstr.h"
21#include "llvm/CodeGen/SSARegMap.h"
Chris Lattner3501fea2003-01-14 22:00:31 +000022#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerbc40e892003-01-13 20:01:16 +000023#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/STLExtras.h"
Chris Lattner6db07562005-10-03 07:22:07 +000026#include "llvm/ADT/Statistic.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000027#include "llvm/Support/Compiler.h"
Chris Lattner53a79aa2005-10-03 04:47:08 +000028#include <set>
Chris Lattner6db07562005-10-03 07:22:07 +000029#include <algorithm>
Chris Lattner0742b592004-02-23 18:38:20 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattnercd3245a2006-12-19 22:41:21 +000032STATISTIC(NumAtomic, "Number of atomic phis lowered");
33//STATISTIC(NumSimple, "Number of simple phis lowered");
34
Chris Lattnerbc40e892003-01-13 20:01:16 +000035namespace {
Chris Lattner95255282006-06-28 23:17:24 +000036 struct VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
Chris Lattnerbc40e892003-01-13 20:01:16 +000037 bool runOnMachineFunction(MachineFunction &Fn) {
Bill Wendlingca756d22006-09-28 07:10:24 +000038 analyzePHINodes(Fn);
39
Chris Lattnerbc40e892003-01-13 20:01:16 +000040 bool Changed = false;
41
42 // Eliminate PHI instructions by inserting copies into predecessor blocks.
Chris Lattnerbc40e892003-01-13 20:01:16 +000043 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Misha Brukmandedf2bd2005-04-22 04:01:18 +000044 Changed |= EliminatePHINodes(Fn, *I);
Chris Lattnerbc40e892003-01-13 20:01:16 +000045
Bill Wendlingca756d22006-09-28 07:10:24 +000046 VRegPHIUseCount.clear();
Chris Lattnerbc40e892003-01-13 20:01:16 +000047 return Changed;
48 }
49
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addPreserved<LiveVariables>();
52 MachineFunctionPass::getAnalysisUsage(AU);
53 }
54
55 private:
56 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
57 /// in predecessor basic blocks.
58 ///
59 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
Chris Lattner53a79aa2005-10-03 04:47:08 +000060 void LowerAtomicPHINode(MachineBasicBlock &MBB,
Bill Wendlingca756d22006-09-28 07:10:24 +000061 MachineBasicBlock::iterator AfterPHIsIt);
62
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.
68 ///
69 void analyzePHINodes(const MachineFunction& Fn);
70
71 typedef std::pair<const MachineBasicBlock*, unsigned> BBVRegPair;
72 typedef std::map<BBVRegPair, unsigned> VRegPHIUse;
73
74 VRegPHIUse VRegPHIUseCount;
Chris Lattnerbc40e892003-01-13 20:01:16 +000075 };
76
77 RegisterPass<PNE> X("phi-node-elimination",
Misha Brukmandedf2bd2005-04-22 04:01:18 +000078 "Eliminate PHI nodes for register allocation");
Chris Lattnerbc40e892003-01-13 20:01:16 +000079}
80
Chris Lattner0742b592004-02-23 18:38:20 +000081const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
Chris Lattnerbc40e892003-01-13 20:01:16 +000082
83/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
84/// predecessor basic blocks.
85///
86bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +000087 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
Chris Lattner53a79aa2005-10-03 04:47:08 +000088 return false; // Quick exit for basic blocks without PHIs.
Chris Lattnerbc40e892003-01-13 20:01:16 +000089
Chris Lattner791f8962004-05-10 18:47:18 +000090 // Get an iterator to the first instruction after the last PHI node (this may
Chris Lattner53a79aa2005-10-03 04:47:08 +000091 // also be the end of the basic block).
Chris Lattner791f8962004-05-10 18:47:18 +000092 MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
93 while (AfterPHIsIt != MBB.end() &&
Chris Lattnerbee88722004-05-12 21:47:57 +000094 AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
Chris Lattner791f8962004-05-10 18:47:18 +000095 ++AfterPHIsIt; // Skip over all of the PHI nodes...
96
Bill Wendlingca756d22006-09-28 07:10:24 +000097 while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
98 LowerAtomicPHINode(MBB, AfterPHIsIt);
99
Chris Lattner53a79aa2005-10-03 04:47:08 +0000100 return true;
101}
Misha Brukmanedf128a2005-04-21 22:36:52 +0000102
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000103/// InstructionUsesRegister - Return true if the specified machine instr has a
104/// use of the specified register.
105static bool InstructionUsesRegister(MachineInstr *MI, unsigned SrcReg) {
106 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
Chris Lattner103de772006-08-12 05:41:39 +0000107 if (MI->getOperand(i).isRegister() &&
108 MI->getOperand(i).getReg() == SrcReg &&
109 MI->getOperand(i).isUse())
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000110 return true;
111 return false;
112}
113
Chris Lattner53a79aa2005-10-03 04:47:08 +0000114/// 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
117/// time.
118void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
Bill Wendlingca756d22006-09-28 07:10:24 +0000119 MachineBasicBlock::iterator AfterPHIsIt) {
Chris Lattner53a79aa2005-10-03 04:47:08 +0000120 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
121 MachineInstr *MPhi = MBB.remove(MBB.begin());
Chris Lattnerbc40e892003-01-13 20:01:16 +0000122
Chris Lattner53a79aa2005-10-03 04:47:08 +0000123 unsigned DestReg = MPhi->getOperand(0).getReg();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000124
Bill Wendlingca756d22006-09-28 07:10:24 +0000125 // Create a new register for the incoming PHI arguments.
Chris Lattner53a79aa2005-10-03 04:47:08 +0000126 MachineFunction &MF = *MBB.getParent();
127 const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
128 unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
Chris Lattnerbc40e892003-01-13 20:01:16 +0000129
Chris Lattner53a79aa2005-10-03 04:47:08 +0000130 // 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.
133 //
134 const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
135 RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
136
137 // Update live variable information if there is any...
138 LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
139 if (LV) {
140 MachineInstr *PHICopy = prior(AfterPHIsIt);
141
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.
Chris Lattnerbc40e892003-01-13 20:01:16 +0000146 //
Chris Lattner53a79aa2005-10-03 04:47:08 +0000147 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000148
Chris Lattner53a79aa2005-10-03 04:47:08 +0000149 // 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.
152 //
153 LV->removeVirtualRegistersKilled(MPhi);
Chris Lattnerbc40e892003-01-13 20:01:16 +0000154
Chris Lattner6db07562005-10-03 07:22:07 +0000155 // If the result is dead, update LV.
156 if (LV->RegisterDefIsDead(MPhi, DestReg)) {
157 LV->addVirtualRegisterDead(DestReg, PHICopy);
Chris Lattner53a79aa2005-10-03 04:47:08 +0000158 LV->removeVirtualRegistersDead(MPhi);
159 }
Chris Lattner172c3622006-01-04 06:47:48 +0000160
161 // Realize that the destination register is defined by the PHI copy now, not
162 // the PHI itself.
163 LV->getVarInfo(DestReg).DefInst = PHICopy;
Chris Lattner53a79aa2005-10-03 04:47:08 +0000164 }
Chris Lattnerbc40e892003-01-13 20:01:16 +0000165
Chris Lattner53a79aa2005-10-03 04:47:08 +0000166 // Adjust the VRegPHIUseCount map to account for the removal of this PHI
167 // node.
168 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
Bill Wendlingca756d22006-09-28 07:10:24 +0000169 --VRegPHIUseCount[BBVRegPair(
170 MPhi->getOperand(i + 1).getMachineBasicBlock(),
171 MPhi->getOperand(i).getReg())];
Chris Lattner572c7702003-05-12 14:28:28 +0000172
Chris Lattner53a79aa2005-10-03 04:47:08 +0000173 // Now loop over all of the incoming arguments, changing them to copy into
174 // the IncomingReg register in the corresponding predecessor basic block.
175 //
Chris Lattner6db07562005-10-03 07:22:07 +0000176 std::set<MachineBasicBlock*> MBBsInsertedInto;
Chris Lattner53a79aa2005-10-03 04:47:08 +0000177 for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
Chris Lattner6db07562005-10-03 07:22:07 +0000178 unsigned SrcReg = MPhi->getOperand(i-1).getReg();
179 assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
180 "Machine PHI Operands must all be virtual registers!");
Chris Lattner53a79aa2005-10-03 04:47:08 +0000181
182 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
183 // source path the PHI.
184 MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
185
Chris Lattner53a79aa2005-10-03 04:47:08 +0000186 // 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
Chris Lattner6db07562005-10-03 07:22:07 +0000188 // same basic block.
189 if (!MBBsInsertedInto.insert(&opBlock).second)
190 continue; // If the copy has already been emitted, we're done.
191
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();
195
196 // Insert the copy.
197 RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
Chris Lattner53a79aa2005-10-03 04:47:08 +0000198
Chris Lattner6db07562005-10-03 07:22:07 +0000199 // Now update live variable information if we have it. Otherwise we're done
200 if (!LV) continue;
201
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.
208 //
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.
212 //
213 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
214
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.
220 //
221
222 // Is it used by any PHI instructions in this block?
Bill Wendlingca756d22006-09-28 07:10:24 +0000223 bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
Chris Lattner6db07562005-10-03 07:22:07 +0000224
225 std::vector<MachineBasicBlock*> OpSuccBlocks;
226
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;
231
232 // Is it alive in this successor?
233 unsigned SuccIdx = SuccMBB->getNumber();
234 if (SuccIdx < InRegVI.AliveBlocks.size() &&
235 InRegVI.AliveBlocks[SuccIdx]) {
236 ValueIsLive = true;
237 break;
Chris Lattner927ce5d2003-05-12 03:55:21 +0000238 }
Chris Lattner6db07562005-10-03 07:22:07 +0000239
240 OpSuccBlocks.push_back(SuccMBB);
Chris Lattner927ce5d2003-05-12 03:55:21 +0000241 }
242
Chris Lattner6db07562005-10-03 07:22:07 +0000243 // Check to see if this value is live because there is a use in a successor
244 // that kills it.
245 if (!ValueIsLive) {
246 switch (OpSuccBlocks.size()) {
247 case 1: {
248 MachineBasicBlock *MBB = OpSuccBlocks[0];
249 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
250 if (InRegVI.Kills[i]->getParent() == MBB) {
Chris Lattner53a79aa2005-10-03 04:47:08 +0000251 ValueIsLive = true;
252 break;
253 }
Chris Lattner6db07562005-10-03 07:22:07 +0000254 break;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000255 }
Chris Lattner6db07562005-10-03 07:22:07 +0000256 case 2: {
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) {
261 ValueIsLive = true;
262 break;
263 }
264 break;
265 }
266 default:
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())) {
271 ValueIsLive = true;
272 break;
273 }
274 }
275 }
276
277 // Okay, if we now know that the value is not live out of the block,
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000278 // we can add a kill marker in this block saying that it kills the incoming
279 // value!
Chris Lattner6db07562005-10-03 07:22:07 +0000280 if (!ValueIsLive) {
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000281 // 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
285 // copy.
286 bool FirstTerminatorUsesValue = false;
287 if (I != opBlock.end()) {
288 FirstTerminatorUsesValue = InstructionUsesRegister(I, SrcReg);
289
290 // Check that no other terminators use values.
291#ifndef NDEBUG
292 for (MachineBasicBlock::iterator TI = next(I); TI != opBlock.end();
293 ++TI) {
294 assert(!InstructionUsesRegister(TI, SrcReg) &&
295 "Terminator instructions cannot use virtual registers unless"
296 "they are the first terminator in a block!");
297 }
298#endif
299 }
300
301 MachineBasicBlock::iterator KillInst;
302 if (!FirstTerminatorUsesValue)
303 KillInst = prior(I);
304 else
305 KillInst = I;
306
307 // Finally, mark it killed.
308 LV->addVirtualRegisterKilled(SrcReg, KillInst);
Chris Lattner6db07562005-10-03 07:22:07 +0000309
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;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000314 }
Chris Lattnerbc40e892003-01-13 20:01:16 +0000315 }
Chris Lattner53a79aa2005-10-03 04:47:08 +0000316
317 // Really delete the PHI instruction now!
318 delete MPhi;
Chris Lattner6db07562005-10-03 07:22:07 +0000319 ++NumAtomic;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000320}
Bill Wendlingca756d22006-09-28 07:10:24 +0000321
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.
326///
327void PNE::analyzePHINodes(const MachineFunction& Fn) {
328 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
329 I != E; ++I)
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())];
336}