PHIElimination.cpp revision bee887211b603a7e19bf72a4c04e120b47ad82e9
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#include "llvm/CodeGen/Passes.h"
17#include "llvm/CodeGen/MachineFunctionPass.h"
18#include "llvm/CodeGen/MachineInstr.h"
19#include "llvm/CodeGen/SSARegMap.h"
20#include "llvm/CodeGen/LiveVariables.h"
21#include "llvm/Target/TargetInstrInfo.h"
22#include "llvm/Target/TargetMachine.h"
23#include "Support/DenseMap.h"
24#include "Support/STLExtras.h"
25using namespace llvm;
26
27namespace {
28  struct PNE : public MachineFunctionPass {
29    bool runOnMachineFunction(MachineFunction &Fn) {
30      bool Changed = false;
31
32      // Eliminate PHI instructions by inserting copies into predecessor blocks.
33      //
34      for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
35	Changed |= EliminatePHINodes(Fn, *I);
36
37      //std::cerr << "AFTER PHI NODE ELIM:\n";
38      //Fn.dump();
39      return Changed;
40    }
41
42    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
43      AU.addPreserved<LiveVariables>();
44      MachineFunctionPass::getAnalysisUsage(AU);
45    }
46
47  private:
48    /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
49    /// in predecessor basic blocks.
50    ///
51    bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
52  };
53
54  RegisterPass<PNE> X("phi-node-elimination",
55		      "Eliminate PHI nodes for register allocation");
56}
57
58
59const PassInfo *llvm::PHIEliminationID = X.getPassInfo();
60
61/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
62/// predecessor basic blocks.
63///
64bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
65  if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)
66    return false;   // Quick exit for normal case...
67
68  LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
69  const TargetInstrInfo &MII = MF.getTarget().getInstrInfo();
70  const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
71
72  // VRegPHIUseCount - Keep track of the number of times each virtual register
73  // is used by PHI nodes in successors of this block.
74  DenseMap<unsigned, VirtReg2IndexFunctor> VRegPHIUseCount;
75  VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg());
76
77  unsigned BBIsSuccOfPreds = 0;  // Number of times MBB is a succ of preds
78  for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(),
79         E = MBB.pred_end(); PI != E; ++PI)
80    for (MachineBasicBlock::succ_iterator SI = (*PI)->succ_begin(),
81           E = (*PI)->succ_end(); SI != E; ++SI) {
82    BBIsSuccOfPreds += *SI == &MBB;
83    for (MachineBasicBlock::iterator BBI = (*SI)->begin(); BBI !=(*SI)->end() &&
84           BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
85      for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
86        VRegPHIUseCount[BBI->getOperand(i).getReg()]++;
87  }
88
89  // Get an iterator to the first instruction after the last PHI node (this may
90  // also be the end of the basic block).  While we are scanning the PHIs,
91  // populate the VRegPHIUseCount map.
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    // Unlink the PHI node from the basic block... but don't delete the PHI yet
99    MachineInstr *MI = MBB.remove(MBB.begin());
100
101    assert(MRegisterInfo::isVirtualRegister(MI->getOperand(0).getReg()) &&
102           "PHI node doesn't write virt reg?");
103
104    unsigned DestReg = MI->getOperand(0).getReg();
105
106    // Create a new register for the incoming PHI arguments
107    const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
108    unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
109
110    // Insert a register to register copy in the top of the current block (but
111    // after any remaining phi nodes) which copies the new incoming register
112    // into the phi node destination.
113    //
114    RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
115
116    // Update live variable information if there is any...
117    if (LV) {
118      MachineInstr *PHICopy = prior(AfterPHIsIt);
119
120      // Add information to LiveVariables to know that the incoming value is
121      // killed.  Note that because the value is defined in several places (once
122      // each for each incoming block), the "def" block and instruction fields
123      // for the VarInfo is not filled in.
124      //
125      LV->addVirtualRegisterKilled(IncomingReg, &MBB, PHICopy);
126
127      // Since we are going to be deleting the PHI node, if it is the last use
128      // of any registers, or if the value itself is dead, we need to move this
129      // information over to the new copy we just inserted...
130      //
131      std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator>
132        RKs = LV->killed_range(MI);
133      std::vector<std::pair<MachineInstr*, unsigned> > Range;
134      if (RKs.first != RKs.second) {
135        // Copy the range into a vector...
136        Range.assign(RKs.first, RKs.second);
137
138        // Delete the range...
139        LV->removeVirtualRegistersKilled(RKs.first, RKs.second);
140
141        // Add all of the kills back, which will update the appropriate info...
142        for (unsigned i = 0, e = Range.size(); i != e; ++i)
143          LV->addVirtualRegisterKilled(Range[i].second, &MBB, PHICopy);
144      }
145
146      RKs = LV->dead_range(MI);
147      if (RKs.first != RKs.second) {
148        // Works as above...
149        Range.assign(RKs.first, RKs.second);
150        LV->removeVirtualRegistersDead(RKs.first, RKs.second);
151        for (unsigned i = 0, e = Range.size(); i != e; ++i)
152          LV->addVirtualRegisterDead(Range[i].second, &MBB, PHICopy);
153      }
154    }
155
156    // Adjust the VRegPHIUseCount map to account for the removal of this PHI
157    // node.
158    for (unsigned i = 1; i != MI->getNumOperands(); i += 2)
159      VRegPHIUseCount[MI->getOperand(i).getReg()] -= BBIsSuccOfPreds;
160
161    // Now loop over all of the incoming arguments, changing them to copy into
162    // the IncomingReg register in the corresponding predecessor basic block.
163    //
164    for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
165      MachineOperand &opVal = MI->getOperand(i-1);
166
167      // Get the MachineBasicBlock equivalent of the BasicBlock that is the
168      // source path the PHI.
169      MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
170
171      MachineBasicBlock::iterator I = opBlock.getFirstTerminator();
172
173      // Check to make sure we haven't already emitted the copy for this block.
174      // This can happen because PHI nodes may have multiple entries for the
175      // same basic block.  It doesn't matter which entry we use though, because
176      // all incoming values are guaranteed to be the same for a particular bb.
177      //
178      // If we emitted a copy for this basic block already, it will be right
179      // where we want to insert one now.  Just check for a definition of the
180      // register we are interested in!
181      //
182      bool HaveNotEmitted = true;
183
184      if (I != opBlock.begin()) {
185        MachineBasicBlock::iterator PrevInst = prior(I);
186        for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) {
187          MachineOperand &MO = PrevInst->getOperand(i);
188          if (MO.isRegister() && MO.getReg() == IncomingReg)
189            if (MO.isDef()) {
190              HaveNotEmitted = false;
191              break;
192            }
193        }
194      }
195
196      if (HaveNotEmitted) { // If the copy has not already been emitted, do it.
197        assert(MRegisterInfo::isVirtualRegister(opVal.getReg()) &&
198               "Machine PHI Operands must all be virtual registers!");
199        unsigned SrcReg = opVal.getReg();
200        RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
201
202        // Now update live variable information if we have it.
203        if (LV) {
204          // We want to be able to insert a kill of the register if this PHI
205          // (aka, the copy we just inserted) is the last use of the source
206          // value.  Live variable analysis conservatively handles this by
207          // saying that the value is live until the end of the block the PHI
208          // entry lives in.  If the value really is dead at the PHI copy, there
209          // will be no successor blocks which have the value live-in.
210          //
211          // Check to see if the copy is the last use, and if so, update the
212          // live variables information so that it knows the copy source
213          // instruction kills the incoming value.
214          //
215          LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
216
217          // Loop over all of the successors of the basic block, checking to see
218          // if the value is either live in the block, or if it is killed in the
219          // block.  Also check to see if this register is in use by another PHI
220          // node which has not yet been eliminated.  If so, it will be killed
221          // at an appropriate point later.
222          //
223          bool ValueIsLive = false;
224          for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
225                 E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {
226            MachineBasicBlock *SuccMBB = *SI;
227
228            // Is it alive in this successor?
229            unsigned SuccIdx = LV->getMachineBasicBlockIndex(SuccMBB);
230            if (SuccIdx < InRegVI.AliveBlocks.size() &&
231                InRegVI.AliveBlocks[SuccIdx]) {
232              ValueIsLive = true;
233              break;
234            }
235
236            // Is it killed in this successor?
237            for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
238              if (InRegVI.Kills[i].first == SuccMBB) {
239                ValueIsLive = true;
240                break;
241              }
242
243            // Is it used by any PHI instructions in this block?
244            if (!ValueIsLive)
245              ValueIsLive = VRegPHIUseCount[SrcReg] != 0;
246          }
247
248          // Okay, if we now know that the value is not live out of the block,
249          // we can add a kill marker to the copy we inserted saying that it
250          // kills the incoming value!
251          //
252          if (!ValueIsLive) {
253            MachineBasicBlock::iterator Prev = prior(I);
254            LV->addVirtualRegisterKilled(SrcReg, &opBlock, Prev);
255          }
256        }
257      }
258    }
259
260    // really delete the PHI instruction now!
261    delete MI;
262  }
263  return true;
264}
265