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