LiveVariables.cpp revision a8db01ac8353f00b519211e6e9e7d53feb1b2923
1//===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
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 file implements the LiveVariable analysis pass.  For each machine
11// instruction in the function, this pass calculates the set of registers that
12// are immediately dead after the instruction (i.e., the instruction calculates
13// the value, but it is never used) and the set of registers that are used by
14// the instruction, but are never used after the instruction (i.e., they are
15// killed).
16//
17// This class computes live variables using are sparse implementation based on
18// the machine code SSA form.  This class computes live variable information for
19// each virtual and _register allocatable_ physical register in a function.  It
20// uses the dominance properties of SSA form to efficiently compute live
21// variables for virtual registers, and assumes that physical registers are only
22// live within a single basic block (allowing it to do a single local analysis
23// to resolve physical register lifetimes in each basic block).  If a physical
24// register is not register allocatable, it is not tracked.  This is useful for
25// things like the stack pointer and condition codes.
26//
27//===----------------------------------------------------------------------===//
28
29#include "llvm/CodeGen/LiveVariables.h"
30#include "llvm/CodeGen/MachineInstr.h"
31#include "llvm/Target/MRegisterInfo.h"
32#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Support/CFG.h"
35#include "Support/DepthFirstIterator.h"
36#include "Support/STLExtras.h"
37using namespace llvm;
38
39static RegisterAnalysis<LiveVariables> X("livevars", "Live Variable Analysis");
40
41const std::pair<MachineBasicBlock*, unsigned> &
42LiveVariables::getMachineBasicBlockInfo(MachineBasicBlock *MBB) const{
43  return BBMap.find(MBB->getBasicBlock())->second;
44}
45
46/// getIndexMachineBasicBlock() - Given a block index, return the
47/// MachineBasicBlock corresponding to it.
48MachineBasicBlock *LiveVariables::getIndexMachineBasicBlock(unsigned Idx) {
49  if (BBIdxMap.empty()) {
50    BBIdxMap.resize(BBMap.size());
51    for (std::map<const BasicBlock*, std::pair<MachineBasicBlock*, unsigned> >
52           ::iterator I = BBMap.begin(), E = BBMap.end(); I != E; ++I) {
53      assert(BBIdxMap.size() > I->second.second &&"Indices are not sequential");
54      assert(BBIdxMap[I->second.second] == 0 && "Multiple idx collision!");
55      BBIdxMap[I->second.second] = I->second.first;
56    }
57  }
58  assert(Idx < BBIdxMap.size() && "BB Index out of range!");
59  return BBIdxMap[Idx];
60}
61
62LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
63  assert(MRegisterInfo::isVirtualRegister(RegIdx) &&
64         "getVarInfo: not a virtual register!");
65  RegIdx -= MRegisterInfo::FirstVirtualRegister;
66  if (RegIdx >= VirtRegInfo.size()) {
67    if (RegIdx >= 2*VirtRegInfo.size())
68      VirtRegInfo.resize(RegIdx*2);
69    else
70      VirtRegInfo.resize(2*VirtRegInfo.size());
71  }
72  return VirtRegInfo[RegIdx];
73}
74
75
76
77void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
78					    const BasicBlock *BB) {
79  const std::pair<MachineBasicBlock*,unsigned> &Info = BBMap.find(BB)->second;
80  MachineBasicBlock *MBB = Info.first;
81  unsigned BBNum = Info.second;
82
83  // Check to see if this basic block is one of the killing blocks.  If so,
84  // remove it...
85  for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
86    if (VRInfo.Kills[i].first == MBB) {
87      VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
88      break;
89    }
90
91  if (MBB == VRInfo.DefBlock) return;  // Terminate recursion
92
93  if (VRInfo.AliveBlocks.size() <= BBNum)
94    VRInfo.AliveBlocks.resize(BBNum+1);  // Make space...
95
96  if (VRInfo.AliveBlocks[BBNum])
97    return;  // We already know the block is live
98
99  // Mark the variable known alive in this bb
100  VRInfo.AliveBlocks[BBNum] = true;
101
102  for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
103    MarkVirtRegAliveInBlock(VRInfo, *PI);
104}
105
106void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
107				     MachineInstr *MI) {
108  // Check to see if this basic block is already a kill block...
109  if (!VRInfo.Kills.empty() && VRInfo.Kills.back().first == MBB) {
110    // Yes, this register is killed in this basic block already.  Increase the
111    // live range by updating the kill instruction.
112    VRInfo.Kills.back().second = MI;
113    return;
114  }
115
116#ifndef NDEBUG
117  for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
118    assert(VRInfo.Kills[i].first != MBB && "entry should be at end!");
119#endif
120
121  assert(MBB != VRInfo.DefBlock && "Should have kill for defblock!");
122
123  // Add a new kill entry for this basic block.
124  VRInfo.Kills.push_back(std::make_pair(MBB, MI));
125
126  // Update all dominating blocks to mark them known live.
127  const BasicBlock *BB = MBB->getBasicBlock();
128  for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB);
129       PI != E; ++PI)
130    MarkVirtRegAliveInBlock(VRInfo, *PI);
131}
132
133void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
134  PhysRegInfo[Reg] = MI;
135  PhysRegUsed[Reg] = true;
136}
137
138void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
139  // Does this kill a previous version of this register?
140  if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
141    if (PhysRegUsed[Reg])
142      RegistersKilled.insert(std::make_pair(LastUse, Reg));
143    else
144      RegistersDead.insert(std::make_pair(LastUse, Reg));
145  }
146  PhysRegInfo[Reg] = MI;
147  PhysRegUsed[Reg] = false;
148
149  for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
150       *AliasSet; ++AliasSet) {
151    unsigned Alias = *AliasSet;
152    if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
153      if (PhysRegUsed[Alias])
154	RegistersKilled.insert(std::make_pair(LastUse, Alias));
155      else
156	RegistersDead.insert(std::make_pair(LastUse, Alias));
157    }
158    PhysRegInfo[Alias] = MI;
159    PhysRegUsed[Alias] = false;
160  }
161}
162
163bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
164  const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
165  RegInfo = MF.getTarget().getRegisterInfo();
166  assert(RegInfo && "Target doesn't have register information?");
167
168  // First time though, initialize AllocatablePhysicalRegisters for the target
169  if (AllocatablePhysicalRegisters.empty()) {
170    // Make space, initializing to false...
171    AllocatablePhysicalRegisters.resize(RegInfo->getNumRegs());
172
173    // Loop over all of the register classes...
174    for (MRegisterInfo::regclass_iterator RCI = RegInfo->regclass_begin(),
175           E = RegInfo->regclass_end(); RCI != E; ++RCI)
176      // Loop over all of the allocatable registers in the function...
177      for (TargetRegisterClass::iterator I = (*RCI)->allocation_order_begin(MF),
178             E = (*RCI)->allocation_order_end(MF); I != E; ++I)
179        AllocatablePhysicalRegisters[*I] = true;  // The reg is allocatable!
180  }
181
182  // Build BBMap...
183  unsigned BBNum = 0;
184  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
185    BBMap[I->getBasicBlock()] = std::make_pair(I, BBNum++);
186
187  // PhysRegInfo - Keep track of which instruction was the last use of a
188  // physical register.  This is a purely local property, because all physical
189  // register references as presumed dead across basic blocks.
190  //
191  MachineInstr *PhysRegInfoA[RegInfo->getNumRegs()];
192  bool          PhysRegUsedA[RegInfo->getNumRegs()];
193  std::fill(PhysRegInfoA, PhysRegInfoA+RegInfo->getNumRegs(), (MachineInstr*)0);
194  PhysRegInfo = PhysRegInfoA;
195  PhysRegUsed = PhysRegUsedA;
196
197  /// Get some space for a respectable number of registers...
198  VirtRegInfo.resize(64);
199
200  // Calculate live variable information in depth first order on the CFG of the
201  // function.  This guarantees that we will see the definition of a virtual
202  // register before its uses due to dominance properties of SSA (except for PHI
203  // nodes, which are treated as a special case).
204  //
205  const BasicBlock *Entry = MF.getFunction()->begin();
206  for (df_iterator<const BasicBlock*> DFI = df_begin(Entry), E = df_end(Entry);
207       DFI != E; ++DFI) {
208    const BasicBlock *BB = *DFI;
209    std::pair<MachineBasicBlock*, unsigned> &BBRec = BBMap.find(BB)->second;
210    MachineBasicBlock *MBB = BBRec.first;
211    unsigned BBNum = BBRec.second;
212
213    // Loop over all of the instructions, processing them.
214    for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
215	 I != E; ++I) {
216      MachineInstr *MI = I;
217      const TargetInstrDescriptor &MID = TII.get(MI->getOpcode());
218
219      // Process all of the operands of the instruction...
220      unsigned NumOperandsToProcess = MI->getNumOperands();
221
222      // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
223      // of the uses.  They will be handled in other basic blocks.
224      if (MI->getOpcode() == TargetInstrInfo::PHI)
225	NumOperandsToProcess = 1;
226
227      // Loop over implicit uses, using them.
228      for (const unsigned *ImplicitUses = MID.ImplicitUses;
229           *ImplicitUses; ++ImplicitUses)
230	HandlePhysRegUse(*ImplicitUses, MI);
231
232      // Process all explicit uses...
233      for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
234	MachineOperand &MO = MI->getOperand(i);
235	if (MO.isUse() && MO.isRegister() && MO.getReg()) {
236	  if (MRegisterInfo::isVirtualRegister(MO.getReg())){
237	    HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
238	  } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
239                     AllocatablePhysicalRegisters[MO.getReg()]) {
240	    HandlePhysRegUse(MO.getReg(), MI);
241	  }
242	}
243      }
244
245      // Loop over implicit defs, defining them.
246      for (const unsigned *ImplicitDefs = MID.ImplicitDefs;
247           *ImplicitDefs; ++ImplicitDefs)
248        HandlePhysRegDef(*ImplicitDefs, MI);
249
250      // Process all explicit defs...
251      for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
252	MachineOperand &MO = MI->getOperand(i);
253	if (MO.isDef() && MO.isRegister() && MO.getReg()) {
254	  if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
255	    VarInfo &VRInfo = getVarInfo(MO.getReg());
256
257	    assert(VRInfo.DefBlock == 0 && "Variable multiply defined!");
258	    VRInfo.DefBlock = MBB;                           // Created here...
259	    VRInfo.DefInst = MI;
260	    VRInfo.Kills.push_back(std::make_pair(MBB, MI)); // Defaults to dead
261	  } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
262                     AllocatablePhysicalRegisters[MO.getReg()]) {
263	    HandlePhysRegDef(MO.getReg(), MI);
264	  }
265	}
266      }
267    }
268
269    // Handle any virtual assignments from PHI nodes which might be at the
270    // bottom of this basic block.  We check all of our successor blocks to see
271    // if they have PHI nodes, and if so, we simulate an assignment at the end
272    // of the current block.
273    for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB);
274         SI != E; ++SI) {
275      MachineBasicBlock *Succ = BBMap.find(*SI)->second.first;
276
277      // PHI nodes are guaranteed to be at the top of the block...
278      for (MachineBasicBlock::iterator MI = Succ->begin(), ME = Succ->end();
279	   MI != ME && MI->getOpcode() == TargetInstrInfo::PHI; ++MI) {
280	for (unsigned i = 1; ; i += 2) {
281          assert(MI->getNumOperands() > i+1 &&
282                 "Didn't find an entry for our predecessor??");
283	  if (MI->getOperand(i+1).getMachineBasicBlock() == MBB) {
284	    MachineOperand &MO = MI->getOperand(i);
285	    if (!MO.getVRegValueOrNull()) {
286	      VarInfo &VRInfo = getVarInfo(MO.getReg());
287
288	      // Only mark it alive only in the block we are representing...
289	      MarkVirtRegAliveInBlock(VRInfo, BB);
290	      break;   // Found the PHI entry for this block...
291	    }
292	  }
293        }
294      }
295    }
296
297    // Loop over PhysRegInfo, killing any registers that are available at the
298    // end of the basic block.  This also resets the PhysRegInfo map.
299    for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
300      if (PhysRegInfo[i])
301	HandlePhysRegDef(i, 0);
302  }
303
304  // Convert the information we have gathered into VirtRegInfo and transform it
305  // into a form usable by RegistersKilled.
306  //
307  for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
308    for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
309      if (VirtRegInfo[i].Kills[j].second == VirtRegInfo[i].DefInst)
310	RegistersDead.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
311		    i + MRegisterInfo::FirstVirtualRegister));
312
313      else
314	RegistersKilled.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
315		    i + MRegisterInfo::FirstVirtualRegister));
316    }
317
318  return false;
319}
320
321/// instructionChanged - When the address of an instruction changes, this
322/// method should be called so that live variables can update its internal
323/// data structures.  This removes the records for OldMI, transfering them to
324/// the records for NewMI.
325void LiveVariables::instructionChanged(MachineInstr *OldMI,
326                                       MachineInstr *NewMI) {
327  // If the instruction defines any virtual registers, update the VarInfo for
328  // the instruction.
329  for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
330    MachineOperand &MO = OldMI->getOperand(i);
331    if (MO.isRegister() && MO.isDef() && MO.getReg() &&
332        MRegisterInfo::isVirtualRegister(MO.getReg())) {
333      unsigned Reg = MO.getReg();
334      VarInfo &VI = getVarInfo(Reg);
335      if (VI.DefInst == OldMI)
336        VI.DefInst = NewMI;
337    }
338  }
339
340  // Move the killed information over...
341  killed_iterator I, E;
342  tie(I, E) = killed_range(OldMI);
343  std::vector<unsigned> Regs;
344  for (killed_iterator A = I; A != E; ++A)
345    Regs.push_back(A->second);
346  RegistersKilled.erase(I, E);
347
348  for (unsigned i = 0, e = Regs.size(); i != e; ++i)
349    RegistersKilled.insert(std::make_pair(NewMI, Regs[i]));
350  Regs.clear();
351
352
353  // Move the dead information over...
354  tie(I, E) = dead_range(OldMI);
355  for (killed_iterator A = I; A != E; ++A)
356    Regs.push_back(A->second);
357  RegistersDead.erase(I, E);
358
359  for (unsigned i = 0, e = Regs.size(); i != e; ++i)
360    RegistersDead.insert(std::make_pair(NewMI, Regs[i]));
361}
362