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