PHIElimination.cpp revision cd3245ac45c595da96bb768a55cddc356dff55fe
1//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
2//
3//                     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.
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 "llvm/CodeGen/LiveVariables.h"
18#include "llvm/CodeGen/Passes.h"
19#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/CodeGen/MachineInstr.h"
21#include "llvm/CodeGen/SSARegMap.h"
22#include "llvm/Target/TargetInstrInfo.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Compiler.h"
28#include <set>
29#include <algorithm>
30using namespace llvm;
31
32STATISTIC(NumAtomic, "Number of atomic phis lowered");
33//STATISTIC(NumSimple, "Number of simple phis lowered");
34
35namespace {
36  struct VISIBILITY_HIDDEN PNE : public MachineFunctionPass {
37    bool runOnMachineFunction(MachineFunction &Fn) {
38      analyzePHINodes(Fn);
39
40      bool Changed = false;
41
42      // Eliminate PHI instructions by inserting copies into predecessor blocks.
43      for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
44        Changed |= EliminatePHINodes(Fn, *I);
45
46      VRegPHIUseCount.clear();
47      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);
60    void LowerAtomicPHINode(MachineBasicBlock &MBB,
61                            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;
75  };
76
77  RegisterPass<PNE> X("phi-node-elimination",
78                      "Eliminate PHI nodes for register allocation");
79}
80
81const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
82
83/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
84/// predecessor basic blocks.
85///
86bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
87  if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
88    return false;   // Quick exit for basic blocks without PHIs.
89
90  // Get an iterator to the first instruction after the last PHI node (this may
91  // also be the end of the basic block).
92  MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
93  while (AfterPHIsIt != MBB.end() &&
94         AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)
95    ++AfterPHIsIt;    // Skip over all of the PHI nodes...
96
97  while (MBB.front().getOpcode() == TargetInstrInfo::PHI)
98    LowerAtomicPHINode(MBB, AfterPHIsIt);
99
100  return true;
101}
102
103/// 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)
107    if (MI->getOperand(i).isRegister() &&
108        MI->getOperand(i).getReg() == SrcReg &&
109        MI->getOperand(i).isUse())
110      return true;
111  return false;
112}
113
114/// 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,
119                             MachineBasicBlock::iterator AfterPHIsIt) {
120  // Unlink the PHI node from the basic block, but don't delete the PHI yet.
121  MachineInstr *MPhi = MBB.remove(MBB.begin());
122
123  unsigned DestReg = MPhi->getOperand(0).getReg();
124
125  // 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);
129
130  // 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.
146    //
147    LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
148
149    // 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);
154
155    // If the result is dead, update LV.
156    if (LV->RegisterDefIsDead(MPhi, DestReg)) {
157      LV->addVirtualRegisterDead(DestReg, PHICopy);
158      LV->removeVirtualRegistersDead(MPhi);
159    }
160
161    // Realize that the destination register is defined by the PHI copy now, not
162    // the PHI itself.
163    LV->getVarInfo(DestReg).DefInst = PHICopy;
164  }
165
166  // Adjust the VRegPHIUseCount map to account for the removal of this PHI
167  // node.
168  for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
169    --VRegPHIUseCount[BBVRegPair(
170                        MPhi->getOperand(i + 1).getMachineBasicBlock(),
171                        MPhi->getOperand(i).getReg())];
172
173  // Now loop over all of the incoming arguments, changing them to copy into
174  // the IncomingReg register in the corresponding predecessor basic block.
175  //
176  std::set<MachineBasicBlock*> MBBsInsertedInto;
177  for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {
178    unsigned SrcReg = MPhi->getOperand(i-1).getReg();
179    assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
180           "Machine PHI Operands must all be virtual registers!");
181
182    // Get the MachineBasicBlock equivalent of the BasicBlock that is the
183    // source path the PHI.
184    MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();
185
186    // 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
188    // 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);
198
199    // 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?
223    bool ValueIsLive = VRegPHIUseCount[BBVRegPair(&opBlock, SrcReg)] != 0;
224
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;
238      }
239
240      OpSuccBlocks.push_back(SuccMBB);
241    }
242
243    // 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) {
251            ValueIsLive = true;
252            break;
253          }
254        break;
255      }
256      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,
278    // we can add a kill marker in this block saying that it kills the incoming
279    // value!
280    if (!ValueIsLive) {
281      // 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);
309
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;
314    }
315  }
316
317  // Really delete the PHI instruction now!
318  delete MPhi;
319  ++NumAtomic;
320}
321
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}
337