LiveVariables.cpp revision a284cbf667e11660840dc7bae3ee9eeaa3c7cbd2
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/ADT/DepthFirstIterator.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/Config/alloca.h"
37#include <algorithm>
38using namespace llvm;
39
40static RegisterPass<LiveVariables> X("livevars", "Live Variable Analysis");
41
42void LiveVariables::VarInfo::dump() const {
43  cerr << "Register Defined by: ";
44  if (DefInst)
45    cerr << *DefInst;
46  else
47    cerr << "<null>\n";
48  cerr << "  Alive in blocks: ";
49  for (unsigned i = 0, e = AliveBlocks.size(); i != e; ++i)
50    if (AliveBlocks[i]) cerr << i << ", ";
51  cerr << "\n  Killed by:";
52  if (Kills.empty())
53    cerr << " No instructions.\n";
54  else {
55    for (unsigned i = 0, e = Kills.size(); i != e; ++i)
56      cerr << "\n    #" << i << ": " << *Kills[i];
57    cerr << "\n";
58  }
59}
60
61LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
62  assert(MRegisterInfo::isVirtualRegister(RegIdx) &&
63         "getVarInfo: not a virtual register!");
64  RegIdx -= MRegisterInfo::FirstVirtualRegister;
65  if (RegIdx >= VirtRegInfo.size()) {
66    if (RegIdx >= 2*VirtRegInfo.size())
67      VirtRegInfo.resize(RegIdx*2);
68    else
69      VirtRegInfo.resize(2*VirtRegInfo.size());
70  }
71  return VirtRegInfo[RegIdx];
72}
73
74/// registerOverlap - Returns true if register 1 is equal to register 2
75/// or if register 1 is equal to any of alias of register 2.
76static bool registerOverlap(unsigned Reg1, unsigned Reg2,
77                             const MRegisterInfo *RegInfo) {
78  bool isVirt1 = MRegisterInfo::isVirtualRegister(Reg1);
79  bool isVirt2 = MRegisterInfo::isVirtualRegister(Reg2);
80  if (isVirt1 != isVirt2)
81    return false;
82  if (Reg1 == Reg2)
83    return true;
84  else if (isVirt1)
85    return false;
86  for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg2);
87       unsigned Alias = *AliasSet; ++AliasSet) {
88    if (Reg1 == Alias)
89      return true;
90  }
91  return false;
92}
93
94bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
95  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
96    MachineOperand &MO = MI->getOperand(i);
97    if (MO.isReg() && MO.isKill()) {
98      if (registerOverlap(Reg, MO.getReg(), RegInfo))
99        return true;
100    }
101  }
102  return false;
103}
104
105bool LiveVariables::RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const {
106  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
107    MachineOperand &MO = MI->getOperand(i);
108    if (MO.isReg() && MO.isDead())
109      if (registerOverlap(Reg, MO.getReg(), RegInfo))
110        return true;
111  }
112  return false;
113}
114
115bool LiveVariables::ModifiesRegister(MachineInstr *MI, unsigned Reg) const {
116  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
117    MachineOperand &MO = MI->getOperand(i);
118    if (MO.isReg() && MO.isDef()) {
119      if (registerOverlap(Reg, MO.getReg(), RegInfo))
120        return true;
121    }
122  }
123  return false;
124}
125
126void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
127                                            MachineBasicBlock *MBB) {
128  unsigned BBNum = MBB->getNumber();
129
130  // Check to see if this basic block is one of the killing blocks.  If so,
131  // remove it...
132  for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
133    if (VRInfo.Kills[i]->getParent() == MBB) {
134      VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
135      break;
136    }
137
138  if (MBB == VRInfo.DefInst->getParent()) return;  // Terminate recursion
139
140  if (VRInfo.AliveBlocks.size() <= BBNum)
141    VRInfo.AliveBlocks.resize(BBNum+1);  // Make space...
142
143  if (VRInfo.AliveBlocks[BBNum])
144    return;  // We already know the block is live
145
146  // Mark the variable known alive in this bb
147  VRInfo.AliveBlocks[BBNum] = true;
148
149  for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
150         E = MBB->pred_end(); PI != E; ++PI)
151    MarkVirtRegAliveInBlock(VRInfo, *PI);
152}
153
154void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
155                                     MachineInstr *MI) {
156  assert(VRInfo.DefInst && "Register use before def!");
157
158  // Check to see if this basic block is already a kill block...
159  if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
160    // Yes, this register is killed in this basic block already.  Increase the
161    // live range by updating the kill instruction.
162    VRInfo.Kills.back() = MI;
163    return;
164  }
165
166#ifndef NDEBUG
167  for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
168    assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
169#endif
170
171  assert(MBB != VRInfo.DefInst->getParent() &&
172         "Should have kill for defblock!");
173
174  // Add a new kill entry for this basic block.
175  VRInfo.Kills.push_back(MI);
176
177  // Update all dominating blocks to mark them known live.
178  for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
179         E = MBB->pred_end(); PI != E; ++PI)
180    MarkVirtRegAliveInBlock(VRInfo, *PI);
181}
182
183void LiveVariables::addRegisterKilled(unsigned IncomingReg, MachineInstr *MI) {
184  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
185    MachineOperand &MO = MI->getOperand(i);
186    if (MO.isReg() && MO.isUse() && MO.getReg() == IncomingReg) {
187      MO.setIsKill();
188      break;
189    }
190  }
191}
192
193void LiveVariables::addRegisterDead(unsigned IncomingReg, MachineInstr *MI) {
194  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
195    MachineOperand &MO = MI->getOperand(i);
196    if (MO.isReg() && MO.isDef() && MO.getReg() == IncomingReg) {
197      MO.setIsDead();
198      break;
199    }
200  }
201}
202
203void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
204  PhysRegInfo[Reg] = MI;
205  PhysRegUsed[Reg] = true;
206
207  for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
208       unsigned Alias = *AliasSet; ++AliasSet) {
209    PhysRegInfo[Alias] = MI;
210    PhysRegUsed[Alias] = true;
211  }
212}
213
214void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
215  // Does this kill a previous version of this register?
216  if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
217    if (PhysRegUsed[Reg])
218      addRegisterKilled(Reg, LastUse);
219    else
220      addRegisterDead(Reg, LastUse);
221  }
222  PhysRegInfo[Reg] = MI;
223  PhysRegUsed[Reg] = false;
224
225  for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
226       unsigned Alias = *AliasSet; ++AliasSet) {
227    if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
228      if (PhysRegUsed[Alias])
229        addRegisterKilled(Alias, LastUse);
230      else
231        addRegisterDead(Alias, LastUse);
232    }
233    PhysRegInfo[Alias] = MI;
234    PhysRegUsed[Alias] = false;
235  }
236}
237
238bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
239  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
240  RegInfo = MF.getTarget().getRegisterInfo();
241  assert(RegInfo && "Target doesn't have register information?");
242
243  AllocatablePhysicalRegisters = RegInfo->getAllocatableSet(MF);
244
245  // PhysRegInfo - Keep track of which instruction was the last use of a
246  // physical register.  This is a purely local property, because all physical
247  // register references as presumed dead across basic blocks.
248  //
249  PhysRegInfo = (MachineInstr**)alloca(sizeof(MachineInstr*) *
250                                       RegInfo->getNumRegs());
251  PhysRegUsed = (bool*)alloca(sizeof(bool)*RegInfo->getNumRegs());
252  std::fill(PhysRegInfo, PhysRegInfo+RegInfo->getNumRegs(), (MachineInstr*)0);
253
254  /// Get some space for a respectable number of registers...
255  VirtRegInfo.resize(64);
256
257  analyzePHINodes(MF);
258
259  // Calculate live variable information in depth first order on the CFG of the
260  // function.  This guarantees that we will see the definition of a virtual
261  // register before its uses due to dominance properties of SSA (except for PHI
262  // nodes, which are treated as a special case).
263  //
264  MachineBasicBlock *Entry = MF.begin();
265  std::set<MachineBasicBlock*> Visited;
266  for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
267         E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
268    MachineBasicBlock *MBB = *DFI;
269
270  // Mark live-in registers as live-in.
271    for (MachineBasicBlock::livein_iterator II = MBB->livein_begin(),
272           EE = MBB->livein_end(); II != EE; ++II) {
273      assert(MRegisterInfo::isPhysicalRegister(*II) &&
274             "Cannot have a live-in virtual register!");
275      HandlePhysRegDef(*II, 0);
276    }
277
278    // Loop over all of the instructions, processing them.
279    for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
280         I != E; ++I) {
281      MachineInstr *MI = I;
282
283      // Process all of the operands of the instruction...
284      unsigned NumOperandsToProcess = MI->getNumOperands();
285
286      // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
287      // of the uses.  They will be handled in other basic blocks.
288      if (MI->getOpcode() == TargetInstrInfo::PHI)
289        NumOperandsToProcess = 1;
290
291      // Process all uses...
292      for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
293        MachineOperand &MO = MI->getOperand(i);
294        if (MO.isRegister() && MO.isUse() && MO.getReg()) {
295          if (MRegisterInfo::isVirtualRegister(MO.getReg())){
296            HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
297          } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
298                     AllocatablePhysicalRegisters[MO.getReg()]) {
299            HandlePhysRegUse(MO.getReg(), MI);
300          }
301        }
302      }
303
304      // Process all defs...
305      for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
306        MachineOperand &MO = MI->getOperand(i);
307        if (MO.isRegister() && MO.isDef() && MO.getReg()) {
308          if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
309            VarInfo &VRInfo = getVarInfo(MO.getReg());
310
311            assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
312            VRInfo.DefInst = MI;
313            // Defaults to dead
314            VRInfo.Kills.push_back(MI);
315          } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
316                     AllocatablePhysicalRegisters[MO.getReg()]) {
317            HandlePhysRegDef(MO.getReg(), MI);
318          }
319        }
320      }
321    }
322
323    // Handle any virtual assignments from PHI nodes which might be at the
324    // bottom of this basic block.  We check all of our successor blocks to see
325    // if they have PHI nodes, and if so, we simulate an assignment at the end
326    // of the current block.
327    if (!PHIVarInfo[MBB].empty()) {
328      std::vector<unsigned>& VarInfoVec = PHIVarInfo[MBB];
329
330      for (std::vector<unsigned>::iterator I = VarInfoVec.begin(),
331             E = VarInfoVec.end(); I != E; ++I) {
332        VarInfo& VRInfo = getVarInfo(*I);
333        assert(VRInfo.DefInst && "Register use before def (or no def)!");
334
335        // Only mark it alive only in the block we are representing.
336        MarkVirtRegAliveInBlock(VRInfo, MBB);
337      }
338    }
339
340    // Finally, if the last instruction in the block is a return, make sure to mark
341    // it as using all of the live-out values in the function.
342    if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
343      MachineInstr *Ret = &MBB->back();
344      for (MachineFunction::liveout_iterator I = MF.liveout_begin(),
345             E = MF.liveout_end(); I != E; ++I) {
346        assert(MRegisterInfo::isPhysicalRegister(*I) &&
347               "Cannot have a live-in virtual register!");
348        HandlePhysRegUse(*I, Ret);
349        // Add live-out registers as implicit uses.
350        Ret->addRegOperand(*I, false, true);
351      }
352    }
353
354    // Loop over PhysRegInfo, killing any registers that are available at the
355    // end of the basic block.  This also resets the PhysRegInfo map.
356    for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
357      if (PhysRegInfo[i])
358        HandlePhysRegDef(i, 0);
359  }
360
361  // Convert and transfer the dead / killed information we have gathered into
362  // VirtRegInfo onto MI's.
363  //
364  for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
365    for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
366      if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
367        addRegisterDead(i + MRegisterInfo::FirstVirtualRegister,
368                        VirtRegInfo[i].Kills[j]);
369      else
370        addRegisterKilled(i + MRegisterInfo::FirstVirtualRegister,
371                          VirtRegInfo[i].Kills[j]);
372    }
373
374  // Check to make sure there are no unreachable blocks in the MC CFG for the
375  // function.  If so, it is due to a bug in the instruction selector or some
376  // other part of the code generator if this happens.
377#ifndef NDEBUG
378  for(MachineFunction::iterator i = MF.begin(), e = MF.end(); i != e; ++i)
379    assert(Visited.count(&*i) != 0 && "unreachable basic block found");
380#endif
381
382  PHIVarInfo.clear();
383  return false;
384}
385
386/// instructionChanged - When the address of an instruction changes, this
387/// method should be called so that live variables can update its internal
388/// data structures.  This removes the records for OldMI, transfering them to
389/// the records for NewMI.
390void LiveVariables::instructionChanged(MachineInstr *OldMI,
391                                       MachineInstr *NewMI) {
392  // If the instruction defines any virtual registers, update the VarInfo,
393  // kill and dead information for the instruction.
394  for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
395    MachineOperand &MO = OldMI->getOperand(i);
396    if (MO.isRegister() && MO.getReg() &&
397        MRegisterInfo::isVirtualRegister(MO.getReg())) {
398      unsigned Reg = MO.getReg();
399      VarInfo &VI = getVarInfo(Reg);
400      if (MO.isDef()) {
401        if (MO.isDead()) {
402          MO.unsetIsDead();
403          addVirtualRegisterDead(Reg, NewMI);
404        }
405        // Update the defining instruction.
406        if (VI.DefInst == OldMI)
407          VI.DefInst = NewMI;
408      }
409      if (MO.isUse()) {
410        if (MO.isKill()) {
411          MO.unsetIsKill();
412          addVirtualRegisterKilled(Reg, NewMI);
413        }
414        // If this is a kill of the value, update the VI kills list.
415        if (VI.removeKill(OldMI))
416          VI.Kills.push_back(NewMI);   // Yes, there was a kill of it
417      }
418    }
419  }
420}
421
422/// removeVirtualRegistersKilled - Remove all killed info for the specified
423/// instruction.
424void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
425  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
426    MachineOperand &MO = MI->getOperand(i);
427    if (MO.isReg() && MO.isKill()) {
428      MO.unsetIsKill();
429      unsigned Reg = MO.getReg();
430      if (MRegisterInfo::isVirtualRegister(Reg)) {
431        bool removed = getVarInfo(Reg).removeKill(MI);
432        assert(removed && "kill not in register's VarInfo?");
433      }
434    }
435  }
436}
437
438/// removeVirtualRegistersDead - Remove all of the dead registers for the
439/// specified instruction from the live variable information.
440void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
441  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
442    MachineOperand &MO = MI->getOperand(i);
443    if (MO.isReg() && MO.isDead()) {
444      MO.unsetIsDead();
445      unsigned Reg = MO.getReg();
446      if (MRegisterInfo::isVirtualRegister(Reg)) {
447        bool removed = getVarInfo(Reg).removeKill(MI);
448        assert(removed && "kill not in register's VarInfo?");
449      }
450    }
451  }
452}
453
454/// analyzePHINodes - Gather information about the PHI nodes in here. In
455/// particular, we want to map the variable information of a virtual
456/// register which is used in a PHI node. We map that to the BB the vreg is
457/// coming from.
458///
459void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
460  for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
461       I != E; ++I)
462    for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
463         BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
464      for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
465        PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()].
466          push_back(BBI->getOperand(i).getReg());
467}
468