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