f6d00f702ac4f5d3d74b6aeb2c9b731008954f26
[oota-llvm.git] / lib / CodeGen / LiveVariables.cpp
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 "Support/DepthFirstIterator.h"
35 #include "Support/STLExtras.h"
36 using namespace llvm;
37
38 static RegisterAnalysis<LiveVariables> X("livevars", "Live Variable Analysis");
39
40 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
41   assert(MRegisterInfo::isVirtualRegister(RegIdx) &&
42          "getVarInfo: not a virtual register!");
43   RegIdx -= MRegisterInfo::FirstVirtualRegister;
44   if (RegIdx >= VirtRegInfo.size()) {
45     if (RegIdx >= 2*VirtRegInfo.size())
46       VirtRegInfo.resize(RegIdx*2);
47     else
48       VirtRegInfo.resize(2*VirtRegInfo.size());
49   }
50   return VirtRegInfo[RegIdx];
51 }
52
53
54
55 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
56                                             MachineBasicBlock *MBB) {
57   unsigned BBNum = MBB->getNumber();
58
59   // Check to see if this basic block is one of the killing blocks.  If so,
60   // remove it...
61   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
62     if (VRInfo.Kills[i]->getParent() == MBB) {
63       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
64       break;
65     }
66
67   if (MBB == VRInfo.DefInst->getParent()) return;  // Terminate recursion
68
69   if (VRInfo.AliveBlocks.size() <= BBNum)
70     VRInfo.AliveBlocks.resize(BBNum+1);  // Make space...
71
72   if (VRInfo.AliveBlocks[BBNum])
73     return;  // We already know the block is live
74
75   // Mark the variable known alive in this bb
76   VRInfo.AliveBlocks[BBNum] = true;
77
78   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
79          E = MBB->pred_end(); PI != E; ++PI)
80     MarkVirtRegAliveInBlock(VRInfo, *PI);
81 }
82
83 void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
84                                      MachineInstr *MI) {
85   // Check to see if this basic block is already a kill block...
86   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
87     // Yes, this register is killed in this basic block already.  Increase the
88     // live range by updating the kill instruction.
89     VRInfo.Kills.back() = MI;
90     return;
91   }
92
93 #ifndef NDEBUG
94   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
95     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
96 #endif
97
98   assert(MBB != VRInfo.DefInst->getParent() && 
99          "Should have kill for defblock!");
100
101   // Add a new kill entry for this basic block.
102   VRInfo.Kills.push_back(MI);
103
104   // Update all dominating blocks to mark them known live.
105   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
106          E = MBB->pred_end(); PI != E; ++PI)
107     MarkVirtRegAliveInBlock(VRInfo, *PI);
108 }
109
110 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
111   PhysRegInfo[Reg] = MI;
112   PhysRegUsed[Reg] = true;
113
114   for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
115        unsigned Alias = *AliasSet; ++AliasSet) {
116     PhysRegInfo[Alias] = MI;
117     PhysRegUsed[Alias] = true;
118   }
119 }
120
121 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
122   // Does this kill a previous version of this register?
123   if (MachineInstr *LastUse = PhysRegInfo[Reg]) {
124     if (PhysRegUsed[Reg])
125       RegistersKilled.insert(std::make_pair(LastUse, Reg));
126     else
127       RegistersDead.insert(std::make_pair(LastUse, Reg));
128   }
129   PhysRegInfo[Reg] = MI;
130   PhysRegUsed[Reg] = false;
131
132   for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
133        unsigned Alias = *AliasSet; ++AliasSet) {
134     if (MachineInstr *LastUse = PhysRegInfo[Alias]) {
135       if (PhysRegUsed[Alias])
136         RegistersKilled.insert(std::make_pair(LastUse, Alias));
137       else
138         RegistersDead.insert(std::make_pair(LastUse, Alias));
139     }
140     PhysRegInfo[Alias] = MI;
141     PhysRegUsed[Alias] = false;
142   }
143 }
144
145 bool LiveVariables::runOnMachineFunction(MachineFunction &MF) {
146   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
147   RegInfo = MF.getTarget().getRegisterInfo();
148   assert(RegInfo && "Target doesn't have register information?");
149
150   AllocatablePhysicalRegisters = RegInfo->getAllocatableSet(MF);
151
152   // PhysRegInfo - Keep track of which instruction was the last use of a
153   // physical register.  This is a purely local property, because all physical
154   // register references as presumed dead across basic blocks.
155   //
156   MachineInstr *PhysRegInfoA[RegInfo->getNumRegs()];
157   bool          PhysRegUsedA[RegInfo->getNumRegs()];
158   std::fill(PhysRegInfoA, PhysRegInfoA+RegInfo->getNumRegs(), (MachineInstr*)0);
159   PhysRegInfo = PhysRegInfoA;
160   PhysRegUsed = PhysRegUsedA;
161
162   /// Get some space for a respectable number of registers...
163   VirtRegInfo.resize(64);
164   
165   // Calculate live variable information in depth first order on the CFG of the
166   // function.  This guarantees that we will see the definition of a virtual
167   // register before its uses due to dominance properties of SSA (except for PHI
168   // nodes, which are treated as a special case).
169   //
170   MachineBasicBlock *Entry = MF.begin();
171   std::set<MachineBasicBlock*> Visited;
172   for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
173          E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
174     MachineBasicBlock *MBB = *DFI;
175     unsigned BBNum = MBB->getNumber();
176
177     // Loop over all of the instructions, processing them.
178     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
179          I != E; ++I) {
180       MachineInstr *MI = I;
181       const TargetInstrDescriptor &MID = TII.get(MI->getOpcode());
182
183       // Process all of the operands of the instruction...
184       unsigned NumOperandsToProcess = MI->getNumOperands();
185
186       // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
187       // of the uses.  They will be handled in other basic blocks.
188       if (MI->getOpcode() == TargetInstrInfo::PHI)      
189         NumOperandsToProcess = 1;
190
191       // Loop over implicit uses, using them.
192       for (const unsigned *ImplicitUses = MID.ImplicitUses;
193            *ImplicitUses; ++ImplicitUses)
194         HandlePhysRegUse(*ImplicitUses, MI);
195
196       // Process all explicit uses...
197       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
198         MachineOperand &MO = MI->getOperand(i);
199         if (MO.isUse() && MO.isRegister() && MO.getReg()) {
200           if (MRegisterInfo::isVirtualRegister(MO.getReg())){
201             HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
202           } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
203                      AllocatablePhysicalRegisters[MO.getReg()]) {
204             HandlePhysRegUse(MO.getReg(), MI);
205           }
206         }
207       }
208
209       // Loop over implicit defs, defining them.
210       for (const unsigned *ImplicitDefs = MID.ImplicitDefs;
211            *ImplicitDefs; ++ImplicitDefs)
212         HandlePhysRegDef(*ImplicitDefs, MI);
213
214       // Process all explicit defs...
215       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
216         MachineOperand &MO = MI->getOperand(i);
217         if (MO.isDef() && MO.isRegister() && MO.getReg()) {
218           if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
219             VarInfo &VRInfo = getVarInfo(MO.getReg());
220
221             assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
222             VRInfo.DefInst = MI;
223             // Defaults to dead
224             VRInfo.Kills.push_back(MI);
225           } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
226                      AllocatablePhysicalRegisters[MO.getReg()]) {
227             HandlePhysRegDef(MO.getReg(), MI);
228           }
229         }
230       }
231     }
232
233     // Handle any virtual assignments from PHI nodes which might be at the
234     // bottom of this basic block.  We check all of our successor blocks to see
235     // if they have PHI nodes, and if so, we simulate an assignment at the end
236     // of the current block.
237     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
238            E = MBB->succ_end(); SI != E; ++SI) {
239       MachineBasicBlock *Succ = *SI;
240       
241       // PHI nodes are guaranteed to be at the top of the block...
242       for (MachineBasicBlock::iterator MI = Succ->begin(), ME = Succ->end();
243            MI != ME && MI->getOpcode() == TargetInstrInfo::PHI; ++MI) {
244         for (unsigned i = 1; ; i += 2) {
245           assert(MI->getNumOperands() > i+1 &&
246                  "Didn't find an entry for our predecessor??");
247           if (MI->getOperand(i+1).getMachineBasicBlock() == MBB) {
248             MachineOperand &MO = MI->getOperand(i);
249             if (!MO.getVRegValueOrNull()) {
250               VarInfo &VRInfo = getVarInfo(MO.getReg());
251
252               // Only mark it alive only in the block we are representing...
253               MarkVirtRegAliveInBlock(VRInfo, MBB);
254               break;   // Found the PHI entry for this block...
255             }
256           }
257         }
258       }
259     }
260     
261     // Loop over PhysRegInfo, killing any registers that are available at the
262     // end of the basic block.  This also resets the PhysRegInfo map.
263     for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
264       if (PhysRegInfo[i])
265         HandlePhysRegDef(i, 0);
266   }
267
268   // Convert the information we have gathered into VirtRegInfo and transform it
269   // into a form usable by RegistersKilled.
270   //
271   for (unsigned i = 0, e = VirtRegInfo.size(); i != e; ++i)
272     for (unsigned j = 0, e = VirtRegInfo[i].Kills.size(); j != e; ++j) {
273       if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
274         RegistersDead.insert(std::make_pair(VirtRegInfo[i].Kills[j],
275                              i + MRegisterInfo::FirstVirtualRegister));
276
277       else
278         RegistersKilled.insert(std::make_pair(VirtRegInfo[i].Kills[j],
279                                i + MRegisterInfo::FirstVirtualRegister));
280     }
281
282   // Check to make sure there are no unreachable blocks in the MC CFG for the
283   // function.  If so, it is due to a bug in the instruction selector or some
284   // other part of the code generator if this happens.
285 #ifndef NDEBUG
286   for(MachineFunction::iterator i = MF.begin(), e = MF.end(); i != e; ++i) 
287     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
288 #endif
289
290   return false;
291 }
292
293 /// instructionChanged - When the address of an instruction changes, this
294 /// method should be called so that live variables can update its internal
295 /// data structures.  This removes the records for OldMI, transfering them to
296 /// the records for NewMI.
297 void LiveVariables::instructionChanged(MachineInstr *OldMI,
298                                        MachineInstr *NewMI) {
299   // If the instruction defines any virtual registers, update the VarInfo for
300   // the instruction.
301   for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
302     MachineOperand &MO = OldMI->getOperand(i);
303     if (MO.isRegister() && MO.isDef() && MO.getReg() &&
304         MRegisterInfo::isVirtualRegister(MO.getReg())) {
305       unsigned Reg = MO.getReg();
306       VarInfo &VI = getVarInfo(Reg);
307       if (VI.DefInst == OldMI)
308         VI.DefInst = NewMI;
309     }
310   }
311
312   // Move the killed information over...
313   killed_iterator I, E;
314   tie(I, E) = killed_range(OldMI);
315   std::vector<unsigned> Regs;
316   for (killed_iterator A = I; A != E; ++A)
317     Regs.push_back(A->second);
318   RegistersKilled.erase(I, E);
319
320   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
321     RegistersKilled.insert(std::make_pair(NewMI, Regs[i]));
322   Regs.clear();
323
324   // Move the dead information over...
325   tie(I, E) = dead_range(OldMI);
326   for (killed_iterator A = I; A != E; ++A)
327     Regs.push_back(A->second);
328   RegistersDead.erase(I, E);
329
330   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
331     RegistersDead.insert(std::make_pair(NewMI, Regs[i]));
332 }