For real this time: PHI Def & Kill tracking added to PHIElimination.
[oota-llvm.git] / lib / CodeGen / PHIElimination.cpp
1 //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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 "PHIElimination.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/Compiler.h"
31 #include <algorithm>
32 #include <map>
33 using namespace llvm;
34
35 STATISTIC(NumAtomic, "Number of atomic phis lowered");
36
37 char PHIElimination::ID = 0;
38 static RegisterPass<PHIElimination>
39 X("phi-node-elimination", "Eliminate PHI nodes for register allocation");
40
41 const PassInfo *const llvm::PHIEliminationID = &X;
42
43 void llvm::PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
44    AU.addPreserved<LiveVariables>();
45    AU.addPreservedID(MachineLoopInfoID);
46    AU.addPreservedID(MachineDominatorsID);
47    MachineFunctionPass::getAnalysisUsage(AU);
48  }
49
50 bool llvm::PHIElimination::runOnMachineFunction(MachineFunction &Fn) {
51   MRI = &Fn.getRegInfo();
52
53   PHIDefs.clear();
54   PHIKills.clear();
55   analyzePHINodes(Fn);
56
57   bool Changed = false;
58
59   // Eliminate PHI instructions by inserting copies into predecessor blocks.
60   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
61     Changed |= EliminatePHINodes(Fn, *I);
62
63   // Remove dead IMPLICIT_DEF instructions.
64   for (SmallPtrSet<MachineInstr*,4>::iterator I = ImpDefs.begin(),
65          E = ImpDefs.end(); I != E; ++I) {
66     MachineInstr *DefMI = *I;
67     unsigned DefReg = DefMI->getOperand(0).getReg();
68     if (MRI->use_empty(DefReg))
69       DefMI->eraseFromParent();
70   }
71
72   ImpDefs.clear();
73   VRegPHIUseCount.clear();
74   return Changed;
75 }
76
77
78 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
79 /// predecessor basic blocks.
80 ///
81 bool llvm::PHIElimination::EliminatePHINodes(MachineFunction &MF,
82                                              MachineBasicBlock &MBB) {
83   if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
84     return false;   // Quick exit for basic blocks without PHIs.
85
86   // Get an iterator to the first instruction after the last PHI node (this may
87   // also be the end of the basic block).
88   MachineBasicBlock::iterator AfterPHIsIt = SkipPHIsAndLabels(MBB, MBB.begin());
89
90   while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
91     LowerAtomicPHINode(MBB, AfterPHIsIt);
92
93   return true;
94 }
95
96 /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
97 /// are implicit_def's.
98 static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
99                                          const MachineRegisterInfo *MRI) {
100   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
101     unsigned SrcReg = MPhi->getOperand(i).getReg();
102     const MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
103     if (!DefMI || DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
104       return false;
105   }
106   return true;
107 }
108
109 // FindCopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg.
110 // This needs to be after any def or uses of SrcReg, but before any subsequent
111 // point where control flow might jump out of the basic block.
112 MachineBasicBlock::iterator
113 llvm::PHIElimination::FindCopyInsertPoint(MachineBasicBlock &MBB,
114                                           unsigned SrcReg) {
115   // Handle the trivial case trivially.
116   if (MBB.empty())
117     return MBB.begin();
118
119   // If this basic block does not contain an invoke, then control flow always
120   // reaches the end of it, so place the copy there.  The logic below works in
121   // this case too, but is more expensive.
122   if (!isa<InvokeInst>(MBB.getBasicBlock()->getTerminator()))
123     return MBB.getFirstTerminator();
124
125   // Discover any definition/uses in this basic block.
126   SmallPtrSet<MachineInstr*, 8> DefUsesInMBB;
127   for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
128        RE = MRI->reg_end(); RI != RE; ++RI) {
129     MachineInstr *DefUseMI = &*RI;
130     if (DefUseMI->getParent() == &MBB)
131       DefUsesInMBB.insert(DefUseMI);
132   }
133
134   MachineBasicBlock::iterator InsertPoint;
135   if (DefUsesInMBB.empty()) {
136     // No def/uses.  Insert the copy at the start of the basic block.
137     InsertPoint = MBB.begin();
138   } else if (DefUsesInMBB.size() == 1) {
139     // Insert the copy immediately after the definition/use.
140     InsertPoint = *DefUsesInMBB.begin();
141     ++InsertPoint;
142   } else {
143     // Insert the copy immediately after the last definition/use.
144     InsertPoint = MBB.end();
145     while (!DefUsesInMBB.count(&*--InsertPoint)) {}
146     ++InsertPoint;
147   }
148
149   // Make sure the copy goes after any phi nodes however.
150   return SkipPHIsAndLabels(MBB, InsertPoint);
151 }
152
153 /// LowerAtomicPHINode - Lower the PHI node at the top of the specified block,
154 /// under the assuption that it needs to be lowered in a way that supports
155 /// atomic execution of PHIs.  This lowering method is always correct all of the
156 /// time.
157 ///  
158 void llvm::PHIElimination::LowerAtomicPHINode(
159                                       MachineBasicBlock &MBB,
160                                       MachineBasicBlock::iterator AfterPHIsIt) {
161   // Unlink the PHI node from the basic block, but don't delete the PHI yet.
162   MachineInstr *MPhi = MBB.remove(MBB.begin());
163
164   unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
165   unsigned DestReg = MPhi->getOperand(0).getReg();
166   bool isDead = MPhi->getOperand(0).isDead();
167
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 = 0;
172
173   // Insert a register to register copy at 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.
176   const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
177   if (isSourceDefinedByImplicitDef(MPhi, MRI))
178     // If all sources of a PHI node are implicit_def, just emit an
179     // implicit_def instead of a copy.
180     BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
181             TII->get(TargetInstrInfo::IMPLICIT_DEF), DestReg);
182   else {
183     IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
184     TII->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC, RC);
185   }
186
187   // Record PHI def.
188   assert(!hasPHIDef(DestReg) && "Vreg has multiple phi-defs?"); 
189   PHIDefs[DestReg] = &MBB;
190
191   // Update live variable information if there is any.
192   LiveVariables *LV = getAnalysisIfAvailable<LiveVariables>();
193   if (LV) {
194     MachineInstr *PHICopy = prior(AfterPHIsIt);
195
196     if (IncomingReg) {
197       // Increment use count of the newly created virtual register.
198       LV->getVarInfo(IncomingReg).NumUses++;
199
200       // Add information to LiveVariables to know that the incoming value is
201       // killed.  Note that because the value is defined in several places (once
202       // each for each incoming block), the "def" block and instruction fields
203       // for the VarInfo is not filled in.
204       LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
205     }
206
207     // Since we are going to be deleting the PHI node, if it is the last use of
208     // any registers, or if the value itself is dead, we need to move this
209     // information over to the new copy we just inserted.
210     LV->removeVirtualRegistersKilled(MPhi);
211
212     // If the result is dead, update LV.
213     if (isDead) {
214       LV->addVirtualRegisterDead(DestReg, PHICopy);
215       LV->removeVirtualRegisterDead(DestReg, MPhi);
216     }
217   }
218
219   // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
220   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
221     --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i + 1).getMBB(),
222                                  MPhi->getOperand(i).getReg())];
223
224   // Now loop over all of the incoming arguments, changing them to copy into the
225   // IncomingReg register in the corresponding predecessor basic block.
226   SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
227   for (int i = NumSrcs - 1; i >= 0; --i) {
228     unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
229     assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
230            "Machine PHI Operands must all be virtual registers!");
231
232     // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
233     // path the PHI.
234     MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
235
236     // Record the kill.
237     PHIKills[SrcReg].insert(&opBlock);
238
239     // If source is defined by an implicit def, there is no need to insert a
240     // copy.
241     MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
242     if (DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
243       ImpDefs.insert(DefMI);
244       continue;
245     }
246
247     // Check to make sure we haven't already emitted the copy for this block.
248     // This can happen because PHI nodes may have multiple entries for the same
249     // basic block.
250     if (!MBBsInsertedInto.insert(&opBlock))
251       continue;  // If the copy has already been emitted, we're done.
252  
253     // Find a safe location to insert the copy, this may be the first terminator
254     // in the block (or end()).
255     MachineBasicBlock::iterator InsertPos = FindCopyInsertPoint(opBlock, SrcReg);
256
257     // Insert the copy.
258     TII->copyRegToReg(opBlock, InsertPos, IncomingReg, SrcReg, RC, RC);
259
260     // Now update live variable information if we have it.  Otherwise we're done
261     if (!LV) continue;
262     
263     // We want to be able to insert a kill of the register if this PHI (aka, the
264     // copy we just inserted) is the last use of the source value.  Live
265     // variable analysis conservatively handles this by saying that the value is
266     // live until the end of the block the PHI entry lives in.  If the value
267     // really is dead at the PHI copy, there will be no successor blocks which
268     // have the value live-in.
269     //
270     // Check to see if the copy is the last use, and if so, update the live
271     // variables information so that it knows the copy source instruction kills
272     // the incoming value.
273     LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
274
275     // Loop over all of the successors of the basic block, checking to see if
276     // the value is either live in the block, or if it is killed in the block.
277     // Also check to see if this register is in use by another PHI node which
278     // has not yet been eliminated.  If so, it will be killed at an appropriate
279     // point later.
280
281     // Is it used by any PHI instructions in this block?
282     bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
283
284     std::vector<MachineBasicBlock*> OpSuccBlocks;
285     
286     // Otherwise, scan successors, including the BB the PHI node lives in.
287     for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
288            E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
289       MachineBasicBlock *SuccMBB = *SI;
290
291       // Is it alive in this successor?
292       unsigned SuccIdx = SuccMBB->getNumber();
293       if (InRegVI.AliveBlocks.test(SuccIdx)) {
294         ValueIsLive = true;
295         break;
296       }
297
298       OpSuccBlocks.push_back(SuccMBB);
299     }
300
301     // Check to see if this value is live because there is a use in a successor
302     // that kills it.
303     if (!ValueIsLive) {
304       switch (OpSuccBlocks.size()) {
305       case 1: {
306         MachineBasicBlock *MBB = OpSuccBlocks[0];
307         for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
308           if (InRegVI.Kills[i]->getParent() == MBB) {
309             ValueIsLive = true;
310             break;
311           }
312         break;
313       }
314       case 2: {
315         MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];
316         for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
317           if (InRegVI.Kills[i]->getParent() == MBB1 || 
318               InRegVI.Kills[i]->getParent() == MBB2) {
319             ValueIsLive = true;
320             break;
321           }
322         break;        
323       }
324       default:
325         std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
326         for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
327           if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
328                                  InRegVI.Kills[i]->getParent())) {
329             ValueIsLive = true;
330             break;
331           }
332       }
333     }        
334
335     // Okay, if we now know that the value is not live out of the block, we can
336     // add a kill marker in this block saying that it kills the incoming value!
337     if (!ValueIsLive) {
338       // In our final twist, we have to decide which instruction kills the
339       // register.  In most cases this is the copy, however, the first
340       // terminator instruction at the end of the block may also use the value.
341       // In this case, we should mark *it* as being the killing block, not the
342       // copy.
343       MachineBasicBlock::iterator KillInst = prior(InsertPos);
344       MachineBasicBlock::iterator Term = opBlock.getFirstTerminator();
345       if (Term != opBlock.end()) {
346         if (Term->readsRegister(SrcReg))
347           KillInst = Term;
348       
349         // Check that no other terminators use values.
350 #ifndef NDEBUG
351         for (MachineBasicBlock::iterator TI = next(Term); TI != opBlock.end();
352              ++TI) {
353           assert(!TI->readsRegister(SrcReg) &&
354                  "Terminator instructions cannot use virtual registers unless"
355                  "they are the first terminator in a block!");
356         }
357 #endif
358       }
359       
360       // Finally, mark it killed.
361       LV->addVirtualRegisterKilled(SrcReg, KillInst);
362
363       // This vreg no longer lives all of the way through opBlock.
364       unsigned opBlockNum = opBlock.getNumber();
365       InRegVI.AliveBlocks.reset(opBlockNum);
366     }
367   }
368     
369   // Really delete the PHI instruction now!
370   MF.DeleteMachineInstr(MPhi);
371   ++NumAtomic;
372 }
373
374 /// analyzePHINodes - Gather information about the PHI nodes in here. In
375 /// particular, we want to map the number of uses of a virtual register which is
376 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
377 /// used later to determine when the vreg is killed in the BB.
378 ///
379 void llvm::PHIElimination::analyzePHINodes(const MachineFunction& Fn) {
380   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
381        I != E; ++I)
382     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
383          BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
384       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
385         ++VRegPHIUseCount[BBVRegPair(BBI->getOperand(i + 1).getMBB(),
386                                      BBI->getOperand(i).getReg())];
387 }