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