blob: 37b7f45b1ade7f51c88772ae7c00b0527c5e02a5 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Chris Lattner84bc5422007-12-31 04:13:23 +000021#include "llvm/CodeGen/MachineRegisterInfo.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"
Evan Cheng576a2702008-04-03 16:38:20 +000024#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000025#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 Lattner6db07562005-10-03 07:22:07 +000028#include <algorithm>
Evan Cheng10883172008-04-02 17:23:50 +000029#include <map>
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");
Chris Lattnercd3245a2006-12-19 22:41:21 +000033
Chris Lattnerbc40e892003-01-13 20:01:16 +000034namespace {
Evan Cheng576a2702008-04-03 16:38:20 +000035 class VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
36 MachineRegisterInfo *MRI; // Machine register information
37
38 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000039 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000040 PNE() : MachineFunctionPass((intptr_t)&ID) {}
41
Evan Cheng576a2702008-04-03 16:38:20 +000042 virtual bool runOnMachineFunction(MachineFunction &Fn);
43
Chris Lattnerbc40e892003-01-13 20:01:16 +000044 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.addPreserved<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000046 AU.addPreservedID(MachineLoopInfoID);
47 AU.addPreservedID(MachineDominatorsID);
Chris Lattnerbc40e892003-01-13 20:01:16 +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);
Chris Lattner53a79aa2005-10-03 04:47:08 +000056 void LowerAtomicPHINode(MachineBasicBlock &MBB,
Bill Wendlingca756d22006-09-28 07:10:24 +000057 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 Cheng576a2702008-04-03 16:38:20 +000071
72 // Defs of PHI sources which are implicit_def.
73 SmallPtrSet<MachineInstr*, 4> ImpDefs;
Chris Lattnerbc40e892003-01-13 20:01:16 +000074 };
75
Devang Patel19974732007-05-03 01:11:54 +000076 char PNE::ID = 0;
Chris Lattnerbc40e892003-01-13 20:01:16 +000077 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
Evan Cheng576a2702008-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
Chris Lattnerbc40e892003-01-13 20:01:16 +0000109/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
110/// predecessor basic blocks.
111///
112bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000113 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
Chris Lattner53a79aa2005-10-03 04:47:08 +0000114 return false; // Quick exit for basic blocks without PHIs.
Chris Lattnerbc40e892003-01-13 20:01:16 +0000115
Chris Lattner791f8962004-05-10 18:47:18 +0000116 // Get an iterator to the first instruction after the last PHI node (this may
Chris Lattner53a79aa2005-10-03 04:47:08 +0000117 // also be the end of the basic block).
Chris Lattner791f8962004-05-10 18:47:18 +0000118 MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
119 while (AfterPHIsIt != MBB.end() &&
Chris Lattnerbee88722004-05-12 21:47:57 +0000120 AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
Chris Lattner791f8962004-05-10 18:47:18 +0000121 ++AfterPHIsIt; // Skip over all of the PHI nodes...
122
Bill Wendlingca756d22006-09-28 07:10:24 +0000123 while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
124 LowerAtomicPHINode(MBB, AfterPHIsIt);
125
Chris Lattner53a79aa2005-10-03 04:47:08 +0000126 return true;
127}
Misha Brukmanedf128a2005-04-21 22:36:52 +0000128
Chris Lattner53a79aa2005-10-03 04:47:08 +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,
Bill Wendlingca756d22006-09-28 07:10:24 +0000134 MachineBasicBlock::iterator AfterPHIsIt) {
Chris Lattner53a79aa2005-10-03 04:47:08 +0000135 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
136 MachineInstr *MPhi = MBB.remove(MBB.begin());
Chris Lattnerbc40e892003-01-13 20:01:16 +0000137
Chris Lattner53a79aa2005-10-03 04:47:08 +0000138 unsigned DestReg = MPhi->getOperand(0).getReg();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000139
Bill Wendlingca756d22006-09-28 07:10:24 +0000140 // Create a new register for the incoming PHI arguments.
Chris Lattner53a79aa2005-10-03 04:47:08 +0000141 MachineFunction &MF = *MBB.getParent();
Chris Lattner84bc5422007-12-31 04:13:23 +0000142 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
143 unsigned IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
Chris Lattnerbc40e892003-01-13 20:01:16 +0000144
Chris Lattner53a79aa2005-10-03 04:47:08 +0000145 // 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 Andersond10fd972007-12-31 06:32:00 +0000149 const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
150 TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
Chris Lattner53a79aa2005-10-03 04:47:08 +0000151
152 // Update live variable information if there is any...
153 LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
154 if (LV) {
155 MachineInstr *PHICopy = prior(AfterPHIsIt);
156
Evan Cheng3fefc182007-04-18 00:36:11 +0000157 // Increment use count of the newly created virtual register.
158 LV->getVarInfo(IncomingReg).NumUses++;
159
Chris Lattner53a79aa2005-10-03 04:47:08 +0000160 // 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.
Chris Lattnerbc40e892003-01-13 20:01:16 +0000164 //
Chris Lattner53a79aa2005-10-03 04:47:08 +0000165 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000166
Chris Lattner53a79aa2005-10-03 04:47:08 +0000167 // 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);
Chris Lattnerbc40e892003-01-13 20:01:16 +0000172
Chris Lattner6db07562005-10-03 07:22:07 +0000173 // If the result is dead, update LV.
Evan Cheng6130f662008-03-05 00:59:57 +0000174 if (MPhi->registerDefIsDead(DestReg)) {
Chris Lattner6db07562005-10-03 07:22:07 +0000175 LV->addVirtualRegisterDead(DestReg, PHICopy);
Chris Lattner53a79aa2005-10-03 04:47:08 +0000176 LV->removeVirtualRegistersDead(MPhi);
177 }
Owen Andersona0185402007-11-08 01:20:48 +0000178
179 LV->getVarInfo(IncomingReg).UsedBlocks[MBB.getNumber()] = true;
Chris Lattner53a79aa2005-10-03 04:47:08 +0000180 }
Chris Lattnerbc40e892003-01-13 20:01:16 +0000181
Chris Lattner53a79aa2005-10-03 04:47:08 +0000182 // 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 Lattner8aa797a2007-12-30 23:10:15 +0000185 --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
186 MPhi->getOperand(i).getReg())];
Chris Lattner572c7702003-05-12 14:28:28 +0000187
Chris Lattner53a79aa2005-10-03 04:47:08 +0000188 // 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 Cheng576a2702008-04-03 16:38:20 +0000191 SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
Chris Lattner53a79aa2005-10-03 04:47:08 +0000192 for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
Chris Lattner6db07562005-10-03 07:22:07 +0000193 unsigned SrcReg = MPhi->getOperand(i-1).getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000194 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
Chris Lattner6db07562005-10-03 07:22:07 +0000195 "Machine PHI Operands must all be virtual registers!");
Chris Lattner53a79aa2005-10-03 04:47:08 +0000196
Evan Cheng576a2702008-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
Chris Lattner53a79aa2005-10-03 04:47:08 +0000205 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
206 // source path the PHI.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000207 MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMBB();
Chris Lattner53a79aa2005-10-03 04:47:08 +0000208
Chris Lattner53a79aa2005-10-03 04:47:08 +0000209 // 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
Chris Lattner6db07562005-10-03 07:22:07 +0000211 // same basic block.
Evan Cheng576a2702008-04-03 16:38:20 +0000212 if (!MBBsInsertedInto.insert(&opBlock))
Chris Lattner6db07562005-10-03 07:22:07 +0000213 continue; // If the copy has already been emitted, we're done.
214
Evan Cheng576a2702008-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 Chengfc5423d2008-04-04 01:20:05 +0000217 MachineBasicBlock::iterator InsertPos = opBlock.getFirstTerminator();
Chris Lattner6db07562005-10-03 07:22:07 +0000218
219 // Insert the copy.
Evan Cheng576a2702008-04-03 16:38:20 +0000220 TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC);
Chris Lattner53a79aa2005-10-03 04:47:08 +0000221
Chris Lattner6db07562005-10-03 07:22:07 +0000222 // 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 Andersona0185402007-11-08 01:20:48 +0000237 InRegVI.UsedBlocks[opBlock.getNumber()] = true;
Chris Lattner6db07562005-10-03 07:22:07 +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?
Bill Wendlingca756d22006-09-28 07:10:24 +0000247 bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
Chris Lattner6db07562005-10-03 07:22:07 +0000248
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;
Chris Lattner927ce5d2003-05-12 03:55:21 +0000262 }
Chris Lattner6db07562005-10-03 07:22:07 +0000263
264 OpSuccBlocks.push_back(SuccMBB);
Chris Lattner927ce5d2003-05-12 03:55:21 +0000265 }
266
Chris Lattner6db07562005-10-03 07:22:07 +0000267 // 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) {
Chris Lattner53a79aa2005-10-03 04:47:08 +0000275 ValueIsLive = true;
276 break;
277 }
Chris Lattner6db07562005-10-03 07:22:07 +0000278 break;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000279 }
Chris Lattner6db07562005-10-03 07:22:07 +0000280 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,
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000302 // we can add a kill marker in this block saying that it kills the incoming
303 // value!
Chris Lattner6db07562005-10-03 07:22:07 +0000304 if (!ValueIsLive) {
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000305 // 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 Cheng576a2702008-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;
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000315
316 // Check that no other terminators use values.
317#ifndef NDEBUG
Evan Cheng576a2702008-04-03 16:38:20 +0000318 for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end();
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000319 ++TI) {
Evan Cheng576a2702008-04-03 16:38:20 +0000320 assert(!TI->readsRegister(SrcReg) &&
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000321 "Terminator instructions cannot use virtual registers unless"
322 "they are the first terminator in a block!");
323 }
324#endif
325 }
326
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000327 // Finally, mark it killed.
328 LV->addVirtualRegisterKilled(SrcReg, KillInst);
Chris Lattner6db07562005-10-03 07:22:07 +0000329
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;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000334 }
Chris Lattnerbc40e892003-01-13 20:01:16 +0000335 }
Chris Lattner53a79aa2005-10-03 04:47:08 +0000336
337 // Really delete the PHI instruction now!
338 delete MPhi;
Chris Lattner6db07562005-10-03 07:22:07 +0000339 ++NumAtomic;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000340}
Bill Wendlingca756d22006-09-28 07:10:24 +0000341
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 Lattner8aa797a2007-12-30 23:10:15 +0000353 ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
354 BBI->getOperand(i).getReg())];
Bill Wendlingca756d22006-09-28 07:10:24 +0000355}