blob: fef833cc19fa87acbd9dc1f7a0cc972e49df9d59 [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
Misha Brukmand7a10c82005-05-05 23:45:17 +000016#include "llvm/CodeGen/LiveVariables.h"
Chris Lattner0742b592004-02-23 18:38:20 +000017#include "llvm/CodeGen/Passes.h"
Chris Lattnerbc40e892003-01-13 20:01:16 +000018#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/CodeGen/MachineInstr.h"
20#include "llvm/CodeGen/SSARegMap.h"
Chris Lattner3501fea2003-01-14 22:00:31 +000021#include "llvm/Target/TargetInstrInfo.h"
Chris Lattnerbc40e892003-01-13 20:01:16 +000022#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
Chris Lattner6db07562005-10-03 07:22:07 +000025#include "llvm/ADT/Statistic.h"
Chris Lattner95255282006-06-28 23:17:24 +000026#include "llvm/Support/Visibility.h"
Chris Lattner53a79aa2005-10-03 04:47:08 +000027#include <set>
Chris Lattner6db07562005-10-03 07:22:07 +000028#include <algorithm>
Chris Lattner0742b592004-02-23 18:38:20 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattnerbc40e892003-01-13 20:01:16 +000031namespace {
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000032 static Statistic<> NumAtomic("phielim", "Number of atomic phis lowered");
33 static Statistic<> NumSimple("phielim", "Number of simple phis lowered");
Chris Lattner6db07562005-10-03 07:22:07 +000034
Chris Lattner95255282006-06-28 23:17:24 +000035 struct VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
Chris Lattnerbc40e892003-01-13 20:01:16 +000036 bool runOnMachineFunction(MachineFunction &Fn) {
37 bool Changed = false;
38
39 // Eliminate PHI instructions by inserting copies into predecessor blocks.
Chris Lattnerbc40e892003-01-13 20:01:16 +000040 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Misha Brukmandedf2bd2005-04-22 04:01:18 +000041 Changed |= EliminatePHINodes(Fn, *I);
Chris Lattnerbc40e892003-01-13 20:01:16 +000042
Chris Lattnerbc40e892003-01-13 20:01:16 +000043 return Changed;
44 }
45
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addPreserved<LiveVariables>();
48 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,
57 MachineBasicBlock::iterator AfterPHIsIt,
Chris Lattner6db07562005-10-03 07:22:07 +000058 DenseMap<unsigned, VirtReg2IndexFunctor> &VUC);
Chris Lattnerbc40e892003-01-13 20:01:16 +000059 };
60
61 RegisterPass<PNE> X("phi-node-elimination",
Misha Brukmandedf2bd2005-04-22 04:01:18 +000062 "Eliminate PHI nodes for register allocation");
Chris Lattnerbc40e892003-01-13 20:01:16 +000063}
64
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0742b592004-02-23 18:38:20 +000066const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
Chris Lattnerbc40e892003-01-13 20:01:16 +000067
68/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
69/// predecessor basic blocks.
70///
71bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +000072 if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
Chris Lattner53a79aa2005-10-03 04:47:08 +000073 return false; // Quick exit for basic blocks without PHIs.
Chris Lattnerbc40e892003-01-13 20:01:16 +000074
Chris Lattner80e20eb2004-05-10 19:06:37 +000075 // VRegPHIUseCount - Keep track of the number of times each virtual register
Chris Lattnerbee88722004-05-12 21:47:57 +000076 // is used by PHI nodes in successors of this block.
Chris Lattner8abf6932004-05-10 19:17:36 +000077 DenseMap<unsigned, VirtReg2IndexFunctor> VRegPHIUseCount;
78 VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg());
Chris Lattner80e20eb2004-05-10 19:06:37 +000079
Chris Lattnerbee88722004-05-12 21:47:57 +000080 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(),
81 E = MBB.pred_end(); PI != E; ++PI)
82 for (MachineBasicBlock::succ_iterator SI = (*PI)->succ_begin(),
Chris Lattner6db07562005-10-03 07:22:07 +000083 E = (*PI)->succ_end(); SI != E; ++SI)
84 for (MachineBasicBlock::iterator BBI = (*SI)->begin(), E = (*SI)->end();
85 BBI != E && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
86 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
87 VRegPHIUseCount[BBI->getOperand(i).getReg()]++;
88
Chris Lattner791f8962004-05-10 18:47:18 +000089 // Get an iterator to the first instruction after the last PHI node (this may
Chris Lattner53a79aa2005-10-03 04:47:08 +000090 // also be the end of the basic block).
Chris Lattner791f8962004-05-10 18:47:18 +000091 MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
92 while (AfterPHIsIt != MBB.end() &&
Chris Lattnerbee88722004-05-12 21:47:57 +000093 AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
Chris Lattner791f8962004-05-10 18:47:18 +000094 ++AfterPHIsIt; // Skip over all of the PHI nodes...
95
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +000096 while (MBB.front().getOpcode() == TargetInstrInfo::PHI) {
Chris Lattner6db07562005-10-03 07:22:07 +000097 LowerAtomicPHINode(MBB, AfterPHIsIt, VRegPHIUseCount);
Chris Lattner53a79aa2005-10-03 04:47:08 +000098 }
99 return true;
100}
Misha Brukmanedf128a2005-04-21 22:36:52 +0000101
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000102/// InstructionUsesRegister - Return true if the specified machine instr has a
103/// use of the specified register.
104static bool InstructionUsesRegister(MachineInstr *MI, unsigned SrcReg) {
105 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
Chris Lattner103de772006-08-12 05:41:39 +0000106 if (MI->getOperand(i).isRegister() &&
107 MI->getOperand(i).getReg() == SrcReg &&
108 MI->getOperand(i).isUse())
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000109 return true;
110 return false;
111}
112
Chris Lattner53a79aa2005-10-03 04:47:08 +0000113/// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
114/// under the assuption that it needs to be lowered in a way that supports
115/// atomic execution of PHIs. This lowering method is always correct all of the
116/// time.
117void PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,
118 MachineBasicBlock::iterator AfterPHIsIt,
Chris Lattner6db07562005-10-03 07:22:07 +0000119 DenseMap<unsigned, VirtReg2IndexFunctor> &VRegPHIUseCount) {
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
Chris Lattner53a79aa2005-10-03 04:47:08 +0000125 // Create a new register for the incoming PHI arguments/
126 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.
Chris Lattner6db07562005-10-03 07:22:07 +0000168 unsigned NumPreds = (MPhi->getNumOperands()-1)/2;
Chris Lattner53a79aa2005-10-03 04:47:08 +0000169 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
Chris Lattner6db07562005-10-03 07:22:07 +0000170 VRegPHIUseCount[MPhi->getOperand(i).getReg()] -= NumPreds;
Chris Lattner572c7702003-05-12 14:28:28 +0000171
Chris Lattner53a79aa2005-10-03 04:47:08 +0000172 // Now loop over all of the incoming arguments, changing them to copy into
173 // the IncomingReg register in the corresponding predecessor basic block.
174 //
Chris Lattner6db07562005-10-03 07:22:07 +0000175 std::set<MachineBasicBlock*> MBBsInsertedInto;
Chris Lattner53a79aa2005-10-03 04:47:08 +0000176 for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
Chris Lattner6db07562005-10-03 07:22:07 +0000177 unsigned SrcReg = MPhi->getOperand(i-1).getReg();
178 assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
179 "Machine PHI Operands must all be virtual registers!");
Chris Lattner53a79aa2005-10-03 04:47:08 +0000180
181 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
182 // source path the PHI.
183 MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
184
Chris Lattner53a79aa2005-10-03 04:47:08 +0000185 // Check to make sure we haven't already emitted the copy for this block.
186 // This can happen because PHI nodes may have multiple entries for the
Chris Lattner6db07562005-10-03 07:22:07 +0000187 // same basic block.
188 if (!MBBsInsertedInto.insert(&opBlock).second)
189 continue; // If the copy has already been emitted, we're done.
190
191 // Get an iterator pointing to the first terminator in the block (or end()).
192 // This is the point where we can insert a copy if we'd like to.
193 MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
194
195 // Insert the copy.
196 RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
Chris Lattner53a79aa2005-10-03 04:47:08 +0000197
Chris Lattner6db07562005-10-03 07:22:07 +0000198 // Now update live variable information if we have it. Otherwise we're done
199 if (!LV) continue;
200
201 // We want to be able to insert a kill of the register if this PHI
202 // (aka, the copy we just inserted) is the last use of the source
203 // value. Live variable analysis conservatively handles this by
204 // saying that the value is live until the end of the block the PHI
205 // entry lives in. If the value really is dead at the PHI copy, there
206 // will be no successor blocks which have the value live-in.
207 //
208 // Check to see if the copy is the last use, and if so, update the
209 // live variables information so that it knows the copy source
210 // instruction kills the incoming value.
211 //
212 LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
213
214 // Loop over all of the successors of the basic block, checking to see
215 // if the value is either live in the block, or if it is killed in the
216 // block. Also check to see if this register is in use by another PHI
217 // node which has not yet been eliminated. If so, it will be killed
218 // at an appropriate point later.
219 //
220
221 // Is it used by any PHI instructions in this block?
222 bool ValueIsLive = VRegPHIUseCount[SrcReg] != 0;
223
224 std::vector<MachineBasicBlock*> OpSuccBlocks;
225
226 // Otherwise, scan successors, including the BB the PHI node lives in.
227 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
228 E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
229 MachineBasicBlock *SuccMBB = *SI;
230
231 // Is it alive in this successor?
232 unsigned SuccIdx = SuccMBB->getNumber();
233 if (SuccIdx < InRegVI.AliveBlocks.size() &&
234 InRegVI.AliveBlocks[SuccIdx]) {
235 ValueIsLive = true;
236 break;
Chris Lattner927ce5d2003-05-12 03:55:21 +0000237 }
Chris Lattner6db07562005-10-03 07:22:07 +0000238
239 OpSuccBlocks.push_back(SuccMBB);
Chris Lattner927ce5d2003-05-12 03:55:21 +0000240 }
241
Chris Lattner6db07562005-10-03 07:22:07 +0000242 // Check to see if this value is live because there is a use in a successor
243 // that kills it.
244 if (!ValueIsLive) {
245 switch (OpSuccBlocks.size()) {
246 case 1: {
247 MachineBasicBlock *MBB = OpSuccBlocks[0];
248 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
249 if (InRegVI.Kills[i]->getParent() == MBB) {
Chris Lattner53a79aa2005-10-03 04:47:08 +0000250 ValueIsLive = true;
251 break;
252 }
Chris Lattner6db07562005-10-03 07:22:07 +0000253 break;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000254 }
Chris Lattner6db07562005-10-03 07:22:07 +0000255 case 2: {
256 MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
257 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
258 if (InRegVI.Kills[i]->getParent() == MBB1 ||
259 InRegVI.Kills[i]->getParent() == MBB2) {
260 ValueIsLive = true;
261 break;
262 }
263 break;
264 }
265 default:
266 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
267 for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
268 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
269 InRegVI.Kills[i]->getParent())) {
270 ValueIsLive = true;
271 break;
272 }
273 }
274 }
275
276 // Okay, if we now know that the value is not live out of the block,
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000277 // we can add a kill marker in this block saying that it kills the incoming
278 // value!
Chris Lattner6db07562005-10-03 07:22:07 +0000279 if (!ValueIsLive) {
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000280 // In our final twist, we have to decide which instruction kills the
281 // register. In most cases this is the copy, however, the first
282 // terminator instruction at the end of the block may also use the value.
283 // In this case, we should mark *it* as being the killing block, not the
284 // copy.
285 bool FirstTerminatorUsesValue = false;
286 if (I != opBlock.end()) {
287 FirstTerminatorUsesValue = InstructionUsesRegister(I, SrcReg);
288
289 // Check that no other terminators use values.
290#ifndef NDEBUG
291 for (MachineBasicBlock::iterator TI = next(I); TI != opBlock.end();
292 ++TI) {
293 assert(!InstructionUsesRegister(TI, SrcReg) &&
294 "Terminator instructions cannot use virtual registers unless"
295 "they are the first terminator in a block!");
296 }
297#endif
298 }
299
300 MachineBasicBlock::iterator KillInst;
301 if (!FirstTerminatorUsesValue)
302 KillInst = prior(I);
303 else
304 KillInst = I;
305
306 // Finally, mark it killed.
307 LV->addVirtualRegisterKilled(SrcReg, KillInst);
Chris Lattner6db07562005-10-03 07:22:07 +0000308
309 // This vreg no longer lives all of the way through opBlock.
310 unsigned opBlockNum = opBlock.getNumber();
311 if (opBlockNum < InRegVI.AliveBlocks.size())
312 InRegVI.AliveBlocks[opBlockNum] = false;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000313 }
Chris Lattnerbc40e892003-01-13 20:01:16 +0000314 }
Chris Lattner53a79aa2005-10-03 04:47:08 +0000315
316 // Really delete the PHI instruction now!
317 delete MPhi;
Chris Lattner6db07562005-10-03 07:22:07 +0000318 ++NumAtomic;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000319}