LiveVariables.cpp revision bc40e898e153c9b81f246a7971eaac7b14446c49
1//===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
2//
3// This file implements the LiveVariable analysis pass.
4//
5//===----------------------------------------------------------------------===//
6
7#include "llvm/CodeGen/LiveVariables.h"
8#include "llvm/CodeGen/MachineInstr.h"
9#include "llvm/Target/MachineInstrInfo.h"
10#include "llvm/Target/TargetMachine.h"
11#include "llvm/Support/CFG.h"
12#include "Support/DepthFirstIterator.h"
13
14static RegisterAnalysis<LiveVariables> X("livevars", "Live Variable Analysis");
15
16void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
17					    const BasicBlock *BB) {
18  const std::pair<MachineBasicBlock*,unsigned> &Info = BBMap.find(BB)->second;
19  MachineBasicBlock *MBB = Info.first;
20  unsigned BBNum = Info.second;
21
22  // Check to see if this basic block is one of the killing blocks.  If so,
23  // remove it...
24  for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
25    if (VRInfo.Kills[i].first == MBB) {
26      VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
27      break;
28    }
29
30  if (MBB == VRInfo.DefBlock) return;  // Terminate recursion
31
32  if (VRInfo.AliveBlocks.size() <= BBNum)
33    VRInfo.AliveBlocks.resize(BBNum+1);  // Make space...
34
35  if (VRInfo.AliveBlocks[BBNum])
36    return;  // We already know the block is live
37
38  // Mark the variable known alive in this bb
39  VRInfo.AliveBlocks[BBNum] = true;
40
41  for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
42    MarkVirtRegAliveInBlock(VRInfo, *PI);
43}
44
45void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
46				     MachineInstr *MI) {
47  // Check to see if this basic block is already a kill block...
48  if (!VRInfo.Kills.empty() && VRInfo.Kills.back().first == MBB) {
49    // Yes, this register is killed in this basic block already.  Increase the
50    // live range by updating the kill instruction.
51    VRInfo.Kills.back().second = MI;
52    return;
53  }
54
55#ifndef NDEBUG
56  for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
57    assert(VRInfo.Kills[i].first != MBB && "entry should be at end!");
58#endif
59
60  assert(MBB != VRInfo.DefBlock && "Should have kill for defblock!");
61
62  // Add a new kill entry for this basic block.
63  VRInfo.Kills.push_back(std::make_pair(MBB, MI));
64
65  // Update all dominating blocks to mark them known live.
66  const BasicBlock *BB = MBB->getBasicBlock();
67  for (pred_const_iterator PI = pred_begin(BB), E = pred_end(BB);
68       PI != E; ++PI)
69    MarkVirtRegAliveInBlock(VRInfo, *PI);
70}
71
72void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
73  if (PhysRegInfo[Reg]) {
74    PhysRegInfo[Reg] = MI;
75    PhysRegUsed[Reg] = true;
76  } else if (const unsigned *AliasSet = RegInfo->getAliasSet(Reg)) {
77    for (; unsigned NReg = AliasSet[0]; ++AliasSet)
78      if (MachineInstr *LastUse = PhysRegInfo[NReg]) {
79	PhysRegInfo[NReg] = MI;
80	PhysRegUsed[NReg] = true;
81      }
82  }
83}
84
85void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
86  // Does this kill a previous version of this register?
87  if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
88    if (PhysRegUsed[Reg])
89      RegistersKilled.insert(std::make_pair(LastUse, Reg));
90    else
91      RegistersDead.insert(std::make_pair(LastUse, Reg));
92  } else if (const unsigned *AliasSet = RegInfo->getAliasSet(Reg)) {
93    for (; unsigned NReg = AliasSet[0]; ++AliasSet)
94      if (MachineInstr *LastUse = PhysRegInfo[NReg]) {
95	if (PhysRegUsed[NReg])
96	  RegistersKilled.insert(std::make_pair(LastUse, NReg));
97	else
98	  RegistersDead.insert(std::make_pair(LastUse, NReg));
99	PhysRegInfo[NReg] = 0;  // Kill the aliased register
100      }
101  }
102  PhysRegInfo[Reg] = MI;
103  PhysRegUsed[Reg] = false;
104}
105
106bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
107  // Build BBMap...
108  unsigned BBNum = 0;
109  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
110    BBMap[I->getBasicBlock()] = std::make_pair(I, BBNum++);
111
112  // PhysRegInfo - Keep track of which instruction was the last use of a
113  // physical register.  This is a purely local property, because all physical
114  // register references as presumed dead across basic blocks.
115  //
116  MachineInstr *PhysRegInfoA[MRegisterInfo::FirstVirtualRegister];
117  bool          PhysRegUsedA[MRegisterInfo::FirstVirtualRegister];
118  std::fill(PhysRegInfoA, PhysRegInfoA+MRegisterInfo::FirstVirtualRegister,
119	    (MachineInstr*)0);
120  PhysRegInfo = PhysRegInfoA;
121  PhysRegUsed = PhysRegUsedA;
122
123  const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
124  RegInfo = MF.getTarget().getRegisterInfo();
125
126  /// Get some space for a respectable number of registers...
127  VirtRegInfo.resize(64);
128
129  // Calculate live variable information in depth first order on the CFG of the
130  // function.  This guarantees that we will see the definition of a virtual
131  // register before its uses due to dominance properties of SSA (except for PHI
132  // nodes, which are treated as a special case).
133  //
134  const BasicBlock *Entry = MF.getFunction()->begin();
135  for (df_iterator<const BasicBlock*> DFI = df_begin(Entry), E = df_end(Entry);
136       DFI != E; ++DFI) {
137    const BasicBlock *BB = *DFI;
138    std::pair<MachineBasicBlock*, unsigned> &BBRec = BBMap.find(BB)->second;
139    MachineBasicBlock *MBB = BBRec.first;
140    unsigned BBNum = BBRec.second;
141
142    // Loop over all of the instructions, processing them.
143    for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
144	 I != E; ++I) {
145      MachineInstr *MI = *I;
146      const TargetInstrDescriptor &MID = TII.get(MI->getOpcode());
147
148      // Process all of the operands of the instruction...
149      unsigned NumOperandsToProcess = MI->getNumOperands();
150
151      // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
152      // of the uses.  They will be handled in other basic blocks.
153      if (MI->getOpcode() == TargetInstrInfo::PHI)
154	NumOperandsToProcess = 1;
155
156      // Loop over implicit uses, using them.
157      if (const unsigned *ImplicitUses = MID.ImplicitUses)
158	for (unsigned i = 0; ImplicitUses[i]; ++i)
159	  HandlePhysRegUse(ImplicitUses[i], MI);
160
161      // Process all explicit uses...
162      for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
163	MachineOperand &MO = MI->getOperand(i);
164	if (MO.opIsUse() || MO.opIsDefAndUse()) {
165	  if (MO.isVirtualRegister() && !MO.getVRegValueOrNull()) {
166	    unsigned RegIdx = MO.getReg()-MRegisterInfo::FirstVirtualRegister;
167	    HandleVirtRegUse(getVarInfo(RegIdx), MBB, MI);
168	  } else if (MO.isPhysicalRegister() && MO.getReg() != 0
169		   /// FIXME: This is a gross hack, due to us not being able to
170		   /// say that some registers are defined on entry to the
171		   /// function.  5 = ESP
172&& MO.getReg() != 5
173) {
174	    HandlePhysRegUse(MO.getReg(), MI);
175	  }
176	}
177      }
178
179      // Loop over implicit defs, defining them.
180      if (const unsigned *ImplicitDefs = MID.ImplicitDefs)
181	for (unsigned i = 0; ImplicitDefs[i]; ++i)
182	  HandlePhysRegDef(ImplicitDefs[i], MI);
183
184      // Process all explicit defs...
185      for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
186	MachineOperand &MO = MI->getOperand(i);
187	if (MO.opIsDef() || MO.opIsDefAndUse()) {
188	  if (MO.isVirtualRegister()) {
189	    unsigned RegIdx = MO.getReg()-MRegisterInfo::FirstVirtualRegister;
190	    VarInfo &VRInfo = getVarInfo(RegIdx);
191
192	    assert(VRInfo.DefBlock == 0 && "Variable multiply defined!");
193	    VRInfo.DefBlock = MBB;                           // Created here...
194	    VRInfo.DefInst = MI;
195	    VRInfo.Kills.push_back(std::make_pair(MBB, MI)); // Defaults to dead
196	  } else if (MO.isPhysicalRegister() && MO.getReg() != 0
197		   /// FIXME: This is a gross hack, due to us not being able to
198		   /// say that some registers are defined on entry to the
199		   /// function.  5 = ESP
200&& MO.getReg() != 5
201) {
202	    HandlePhysRegDef(MO.getReg(), MI);
203	  }
204	}
205      }
206    }
207
208    // Handle any virtual assignments from PHI nodes which might be at the
209    // bottom of this basic block.  We check all of our successor blocks to see
210    // if they have PHI nodes, and if so, we simulate an assignment at the end
211    // of the current block.
212    for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I){
213      MachineBasicBlock *Succ = BBMap.find(*I)->second.first;
214
215      // PHI nodes are guaranteed to be at the top of the block...
216      for (MachineBasicBlock::iterator I = Succ->begin(), E = Succ->end();
217	   I != E && (*I)->getOpcode() == TargetInstrInfo::PHI; ++I) {
218	for (unsigned i = 1; ; i += 2)
219	  if ((*I)->getOperand(i+1).getMachineBasicBlock() == MBB) {
220	    MachineOperand &MO = (*I)->getOperand(i);
221	    if (!MO.getVRegValueOrNull()) {
222	      unsigned RegIdx = MO.getReg()-MRegisterInfo::FirstVirtualRegister;
223	      VarInfo &VRInfo = getVarInfo(RegIdx);
224
225	      // Only mark it alive only in the block we are representing...
226	      MarkVirtRegAliveInBlock(VRInfo, BB);
227	      break;   // Found the PHI entry for this block...
228	    }
229	  }
230      }
231    }
232
233    // Loop over PhysRegInfo, killing any registers that are available at the
234    // end of the basic block.  This also resets the PhysRegInfo map.
235    for (unsigned i = 0, e = MRegisterInfo::FirstVirtualRegister; i != e; ++i)
236      if (PhysRegInfo[i])
237	HandlePhysRegDef(i, 0);
238  }
239
240  BBMap.clear();
241
242  // Convert the information we have gathered into VirtRegInfo and transform it
243  // into a form usable by RegistersKilled.
244  //
245  for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
246    for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
247      if (VirtRegInfo[i].Kills[j].second == VirtRegInfo[i].DefInst)
248	RegistersDead.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
249		    i + MRegisterInfo::FirstVirtualRegister));
250
251      else
252	RegistersKilled.insert(std::make_pair(VirtRegInfo[i].Kills[j].second,
253		    i + MRegisterInfo::FirstVirtualRegister));
254    }
255
256  return false;
257}
258