Delete an unused member variable.
[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 is distributed under the University of Illinois Open Source
6 // 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/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/ADT/DepthFirstIterator.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 char LiveVariables::ID = 0;
44 INITIALIZE_PASS_BEGIN(LiveVariables, "livevars",
45                 "Live Variable Analysis", false, false)
46 INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
47 INITIALIZE_PASS_END(LiveVariables, "livevars",
48                 "Live Variable Analysis", false, false)
49
50
51 void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const {
52   AU.addRequiredID(UnreachableMachineBlockElimID);
53   AU.setPreservesAll();
54   MachineFunctionPass::getAnalysisUsage(AU);
55 }
56
57 MachineInstr *
58 LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const {
59   for (unsigned i = 0, e = Kills.size(); i != e; ++i)
60     if (Kills[i]->getParent() == MBB)
61       return Kills[i];
62   return NULL;
63 }
64
65 void LiveVariables::VarInfo::dump() const {
66   dbgs() << "  Alive in blocks: ";
67   for (SparseBitVector<>::iterator I = AliveBlocks.begin(),
68            E = AliveBlocks.end(); I != E; ++I)
69     dbgs() << *I << ", ";
70   dbgs() << "\n  Killed by:";
71   if (Kills.empty())
72     dbgs() << " No instructions.\n";
73   else {
74     for (unsigned i = 0, e = Kills.size(); i != e; ++i)
75       dbgs() << "\n    #" << i << ": " << *Kills[i];
76     dbgs() << "\n";
77   }
78 }
79
80 /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
81 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) {
82   assert(TargetRegisterInfo::isVirtualRegister(RegIdx) &&
83          "getVarInfo: not a virtual register!");
84   VirtRegInfo.grow(RegIdx);
85   return VirtRegInfo[RegIdx];
86 }
87
88 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo,
89                                             MachineBasicBlock *DefBlock,
90                                             MachineBasicBlock *MBB,
91                                     std::vector<MachineBasicBlock*> &WorkList) {
92   unsigned BBNum = MBB->getNumber();
93   
94   // Check to see if this basic block is one of the killing blocks.  If so,
95   // remove it.
96   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
97     if (VRInfo.Kills[i]->getParent() == MBB) {
98       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
99       break;
100     }
101   
102   if (MBB == DefBlock) return;  // Terminate recursion
103
104   if (VRInfo.AliveBlocks.test(BBNum))
105     return;  // We already know the block is live
106
107   // Mark the variable known alive in this bb
108   VRInfo.AliveBlocks.set(BBNum);
109
110   WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
111 }
112
113 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
114                                             MachineBasicBlock *DefBlock,
115                                             MachineBasicBlock *MBB) {
116   std::vector<MachineBasicBlock*> WorkList;
117   MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
118
119   while (!WorkList.empty()) {
120     MachineBasicBlock *Pred = WorkList.back();
121     WorkList.pop_back();
122     MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
123   }
124 }
125
126 void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
127                                      MachineInstr *MI) {
128   assert(MRI->getVRegDef(reg) && "Register use before def!");
129
130   unsigned BBNum = MBB->getNumber();
131
132   VarInfo& VRInfo = getVarInfo(reg);
133
134   // Check to see if this basic block is already a kill block.
135   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
136     // Yes, this register is killed in this basic block already. Increase the
137     // live range by updating the kill instruction.
138     VRInfo.Kills.back() = MI;
139     return;
140   }
141
142 #ifndef NDEBUG
143   for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
144     assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
145 #endif
146
147   // This situation can occur:
148   //
149   //     ,------.
150   //     |      |
151   //     |      v
152   //     |   t2 = phi ... t1 ...
153   //     |      |
154   //     |      v
155   //     |   t1 = ...
156   //     |  ... = ... t1 ...
157   //     |      |
158   //     `------'
159   //
160   // where there is a use in a PHI node that's a predecessor to the defining
161   // block. We don't want to mark all predecessors as having the value "alive"
162   // in this case.
163   if (MBB == MRI->getVRegDef(reg)->getParent()) return;
164
165   // Add a new kill entry for this basic block. If this virtual register is
166   // already marked as alive in this basic block, that means it is alive in at
167   // least one of the successor blocks, it's not a kill.
168   if (!VRInfo.AliveBlocks.test(BBNum))
169     VRInfo.Kills.push_back(MI);
170
171   // Update all dominating blocks to mark them as "known live".
172   for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
173          E = MBB->pred_end(); PI != E; ++PI)
174     MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI);
175 }
176
177 void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr *MI) {
178   VarInfo &VRInfo = getVarInfo(Reg);
179
180   if (VRInfo.AliveBlocks.empty())
181     // If vr is not alive in any block, then defaults to dead.
182     VRInfo.Kills.push_back(MI);
183 }
184
185 /// FindLastPartialDef - Return the last partial def of the specified register.
186 /// Also returns the sub-registers that're defined by the instruction.
187 MachineInstr *LiveVariables::FindLastPartialDef(unsigned Reg,
188                                             SmallSet<unsigned,4> &PartDefRegs) {
189   unsigned LastDefReg = 0;
190   unsigned LastDefDist = 0;
191   MachineInstr *LastDef = NULL;
192   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
193        unsigned SubReg = *SubRegs; ++SubRegs) {
194     MachineInstr *Def = PhysRegDef[SubReg];
195     if (!Def)
196       continue;
197     unsigned Dist = DistanceMap[Def];
198     if (Dist > LastDefDist) {
199       LastDefReg  = SubReg;
200       LastDef     = Def;
201       LastDefDist = Dist;
202     }
203   }
204
205   if (!LastDef)
206     return 0;
207
208   PartDefRegs.insert(LastDefReg);
209   for (unsigned i = 0, e = LastDef->getNumOperands(); i != e; ++i) {
210     MachineOperand &MO = LastDef->getOperand(i);
211     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
212       continue;
213     unsigned DefReg = MO.getReg();
214     if (TRI->isSubRegister(Reg, DefReg)) {
215       PartDefRegs.insert(DefReg);
216       for (const unsigned *SubRegs = TRI->getSubRegisters(DefReg);
217            unsigned SubReg = *SubRegs; ++SubRegs)
218         PartDefRegs.insert(SubReg);
219     }
220   }
221   return LastDef;
222 }
223
224 /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
225 /// implicit defs to a machine instruction if there was an earlier def of its
226 /// super-register.
227 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
228   MachineInstr *LastDef = PhysRegDef[Reg];
229   // If there was a previous use or a "full" def all is well.
230   if (!LastDef && !PhysRegUse[Reg]) {
231     // Otherwise, the last sub-register def implicitly defines this register.
232     // e.g.
233     // AH =
234     // AL = ... <imp-def EAX>, <imp-kill AH>
235     //    = AH
236     // ...
237     //    = EAX
238     // All of the sub-registers must have been defined before the use of Reg!
239     SmallSet<unsigned, 4> PartDefRegs;
240     MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs);
241     // If LastPartialDef is NULL, it must be using a livein register.
242     if (LastPartialDef) {
243       LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
244                                                            true/*IsImp*/));
245       PhysRegDef[Reg] = LastPartialDef;
246       SmallSet<unsigned, 8> Processed;
247       for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
248            unsigned SubReg = *SubRegs; ++SubRegs) {
249         if (Processed.count(SubReg))
250           continue;
251         if (PartDefRegs.count(SubReg))
252           continue;
253         // This part of Reg was defined before the last partial def. It's killed
254         // here.
255         LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg,
256                                                              false/*IsDef*/,
257                                                              true/*IsImp*/));
258         PhysRegDef[SubReg] = LastPartialDef;
259         for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
260           Processed.insert(*SS);
261       }
262     }
263   } else if (LastDef && !PhysRegUse[Reg] &&
264              !LastDef->findRegisterDefOperand(Reg))
265     // Last def defines the super register, add an implicit def of reg.
266     LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
267                                                   true/*IsImp*/));
268
269   // Remember this use.
270   PhysRegUse[Reg]  = MI;
271   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
272        unsigned SubReg = *SubRegs; ++SubRegs)
273     PhysRegUse[SubReg] =  MI;
274 }
275
276 /// FindLastRefOrPartRef - Return the last reference or partial reference of
277 /// the specified register.
278 MachineInstr *LiveVariables::FindLastRefOrPartRef(unsigned Reg) {
279   MachineInstr *LastDef = PhysRegDef[Reg];
280   MachineInstr *LastUse = PhysRegUse[Reg];
281   if (!LastDef && !LastUse)
282     return 0;
283
284   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
285   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
286   unsigned LastPartDefDist = 0;
287   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
288        unsigned SubReg = *SubRegs; ++SubRegs) {
289     MachineInstr *Def = PhysRegDef[SubReg];
290     if (Def && Def != LastDef) {
291       // There was a def of this sub-register in between. This is a partial
292       // def, keep track of the last one.
293       unsigned Dist = DistanceMap[Def];
294       if (Dist > LastPartDefDist)
295         LastPartDefDist = Dist;
296     } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
297       unsigned Dist = DistanceMap[Use];
298       if (Dist > LastRefOrPartRefDist) {
299         LastRefOrPartRefDist = Dist;
300         LastRefOrPartRef = Use;
301       }
302     }
303   }
304
305   return LastRefOrPartRef;
306 }
307
308 bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) {
309   MachineInstr *LastDef = PhysRegDef[Reg];
310   MachineInstr *LastUse = PhysRegUse[Reg];
311   if (!LastDef && !LastUse)
312     return false;
313
314   MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
315   unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
316   // The whole register is used.
317   // AL =
318   // AH =
319   //
320   //    = AX
321   //    = AL, AX<imp-use, kill>
322   // AX =
323   //
324   // Or whole register is defined, but not used at all.
325   // AX<dead> =
326   // ...
327   // AX =
328   //
329   // Or whole register is defined, but only partly used.
330   // AX<dead> = AL<imp-def>
331   //    = AL<kill>
332   // AX = 
333   MachineInstr *LastPartDef = 0;
334   unsigned LastPartDefDist = 0;
335   SmallSet<unsigned, 8> PartUses;
336   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
337        unsigned SubReg = *SubRegs; ++SubRegs) {
338     MachineInstr *Def = PhysRegDef[SubReg];
339     if (Def && Def != LastDef) {
340       // There was a def of this sub-register in between. This is a partial
341       // def, keep track of the last one.
342       unsigned Dist = DistanceMap[Def];
343       if (Dist > LastPartDefDist) {
344         LastPartDefDist = Dist;
345         LastPartDef = Def;
346       }
347       continue;
348     }
349     if (MachineInstr *Use = PhysRegUse[SubReg]) {
350       PartUses.insert(SubReg);
351       for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
352         PartUses.insert(*SS);
353       unsigned Dist = DistanceMap[Use];
354       if (Dist > LastRefOrPartRefDist) {
355         LastRefOrPartRefDist = Dist;
356         LastRefOrPartRef = Use;
357       }
358     }
359   }
360
361   if (!PhysRegUse[Reg]) {
362     // Partial uses. Mark register def dead and add implicit def of
363     // sub-registers which are used.
364     // EAX<dead>  = op  AL<imp-def>
365     // That is, EAX def is dead but AL def extends pass it.
366     PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
367     for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
368          unsigned SubReg = *SubRegs; ++SubRegs) {
369       if (!PartUses.count(SubReg))
370         continue;
371       bool NeedDef = true;
372       if (PhysRegDef[Reg] == PhysRegDef[SubReg]) {
373         MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg);
374         if (MO) {
375           NeedDef = false;
376           assert(!MO->isDead());
377         }
378       }
379       if (NeedDef)
380         PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg,
381                                                  true/*IsDef*/, true/*IsImp*/));
382       MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
383       if (LastSubRef)
384         LastSubRef->addRegisterKilled(SubReg, TRI, true);
385       else {
386         LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
387         PhysRegUse[SubReg] = LastRefOrPartRef;
388         for (const unsigned *SSRegs = TRI->getSubRegisters(SubReg);
389              unsigned SSReg = *SSRegs; ++SSRegs)
390           PhysRegUse[SSReg] = LastRefOrPartRef;
391       }
392       for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
393         PartUses.erase(*SS);
394     }
395   } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) {
396     if (LastPartDef)
397       // The last partial def kills the register.
398       LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
399                                                 true/*IsImp*/, true/*IsKill*/));
400     else {
401       MachineOperand *MO =
402         LastRefOrPartRef->findRegisterDefOperand(Reg, false, TRI);
403       bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
404       // If the last reference is the last def, then it's not used at all.
405       // That is, unless we are currently processing the last reference itself.
406       LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
407       if (NeedEC) {
408         // If we are adding a subreg def and the superreg def is marked early
409         // clobber, add an early clobber marker to the subreg def.
410         MO = LastRefOrPartRef->findRegisterDefOperand(Reg);
411         if (MO)
412           MO->setIsEarlyClobber();
413       }
414     }
415   } else
416     LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
417   return true;
418 }
419
420 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
421                                      SmallVector<unsigned, 4> &Defs) {
422   // What parts of the register are previously defined?
423   SmallSet<unsigned, 32> Live;
424   if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
425     Live.insert(Reg);
426     for (const unsigned *SS = TRI->getSubRegisters(Reg); *SS; ++SS)
427       Live.insert(*SS);
428   } else {
429     for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
430          unsigned SubReg = *SubRegs; ++SubRegs) {
431       // If a register isn't itself defined, but all parts that make up of it
432       // are defined, then consider it also defined.
433       // e.g.
434       // AL =
435       // AH =
436       //    = AX
437       if (Live.count(SubReg))
438         continue;
439       if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
440         Live.insert(SubReg);
441         for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS)
442           Live.insert(*SS);
443       }
444     }
445   }
446
447   // Start from the largest piece, find the last time any part of the register
448   // is referenced.
449   HandlePhysRegKill(Reg, MI);
450   // Only some of the sub-registers are used.
451   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
452        unsigned SubReg = *SubRegs; ++SubRegs) {
453     if (!Live.count(SubReg))
454       // Skip if this sub-register isn't defined.
455       continue;
456     HandlePhysRegKill(SubReg, MI);
457   }
458
459   if (MI)
460     Defs.push_back(Reg);  // Remember this def.
461 }
462
463 void LiveVariables::UpdatePhysRegDefs(MachineInstr *MI,
464                                       SmallVector<unsigned, 4> &Defs) {
465   while (!Defs.empty()) {
466     unsigned Reg = Defs.back();
467     Defs.pop_back();
468     PhysRegDef[Reg]  = MI;
469     PhysRegUse[Reg]  = NULL;
470     for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
471          unsigned SubReg = *SubRegs; ++SubRegs) {
472       PhysRegDef[SubReg]  = MI;
473       PhysRegUse[SubReg]  = NULL;
474     }
475   }
476 }
477
478 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
479   MF = &mf;
480   MRI = &mf.getRegInfo();
481   TRI = MF->getTarget().getRegisterInfo();
482
483   ReservedRegisters = TRI->getReservedRegs(mf);
484
485   unsigned NumRegs = TRI->getNumRegs();
486   PhysRegDef  = new MachineInstr*[NumRegs];
487   PhysRegUse  = new MachineInstr*[NumRegs];
488   PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
489   std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
490   std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
491   PHIJoins.clear();
492
493   analyzePHINodes(mf);
494
495   // Calculate live variable information in depth first order on the CFG of the
496   // function.  This guarantees that we will see the definition of a virtual
497   // register before its uses due to dominance properties of SSA (except for PHI
498   // nodes, which are treated as a special case).
499   MachineBasicBlock *Entry = MF->begin();
500   SmallPtrSet<MachineBasicBlock*,16> Visited;
501
502   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
503          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
504        DFI != E; ++DFI) {
505     MachineBasicBlock *MBB = *DFI;
506
507     // Mark live-in registers as live-in.
508     SmallVector<unsigned, 4> Defs;
509     for (MachineBasicBlock::livein_iterator II = MBB->livein_begin(),
510            EE = MBB->livein_end(); II != EE; ++II) {
511       assert(TargetRegisterInfo::isPhysicalRegister(*II) &&
512              "Cannot have a live-in virtual register!");
513       HandlePhysRegDef(*II, 0, Defs);
514     }
515
516     // Loop over all of the instructions, processing them.
517     DistanceMap.clear();
518     unsigned Dist = 0;
519     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
520          I != E; ++I) {
521       MachineInstr *MI = I;
522       if (MI->isDebugValue())
523         continue;
524       DistanceMap.insert(std::make_pair(MI, Dist++));
525
526       // Process all of the operands of the instruction...
527       unsigned NumOperandsToProcess = MI->getNumOperands();
528
529       // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
530       // of the uses.  They will be handled in other basic blocks.
531       if (MI->isPHI())
532         NumOperandsToProcess = 1;
533
534       // Clear kill and dead markers. LV will recompute them.
535       SmallVector<unsigned, 4> UseRegs;
536       SmallVector<unsigned, 4> DefRegs;
537       for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
538         MachineOperand &MO = MI->getOperand(i);
539         if (!MO.isReg() || MO.getReg() == 0)
540           continue;
541         unsigned MOReg = MO.getReg();
542         if (MO.isUse()) {
543           MO.setIsKill(false);
544           UseRegs.push_back(MOReg);
545         } else /*MO.isDef()*/ {
546           MO.setIsDead(false);
547           DefRegs.push_back(MOReg);
548         }
549       }
550
551       // Process all uses.
552       for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) {
553         unsigned MOReg = UseRegs[i];
554         if (TargetRegisterInfo::isVirtualRegister(MOReg))
555           HandleVirtRegUse(MOReg, MBB, MI);
556         else if (!ReservedRegisters[MOReg])
557           HandlePhysRegUse(MOReg, MI);
558       }
559
560       // Process all defs.
561       for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) {
562         unsigned MOReg = DefRegs[i];
563         if (TargetRegisterInfo::isVirtualRegister(MOReg))
564           HandleVirtRegDef(MOReg, MI);
565         else if (!ReservedRegisters[MOReg])
566           HandlePhysRegDef(MOReg, MI, Defs);
567       }
568       UpdatePhysRegDefs(MI, Defs);
569     }
570
571     // Handle any virtual assignments from PHI nodes which might be at the
572     // bottom of this basic block.  We check all of our successor blocks to see
573     // if they have PHI nodes, and if so, we simulate an assignment at the end
574     // of the current block.
575     if (!PHIVarInfo[MBB->getNumber()].empty()) {
576       SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
577
578       for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
579              E = VarInfoVec.end(); I != E; ++I)
580         // Mark it alive only in the block we are representing.
581         MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(),
582                                 MBB);
583     }
584
585     // Finally, if the last instruction in the block is a return, make sure to
586     // mark it as using all of the live-out values in the function.
587     // Things marked both call and return are tail calls; do not do this for
588     // them.  The tail callee need not take the same registers as input
589     // that it produces as output, and there are dependencies for its input
590     // registers elsewhere.
591     if (!MBB->empty() && MBB->back().isReturn()
592         && !MBB->back().isCall()) {
593       MachineInstr *Ret = &MBB->back();
594
595       for (MachineRegisterInfo::liveout_iterator
596            I = MF->getRegInfo().liveout_begin(),
597            E = MF->getRegInfo().liveout_end(); I != E; ++I) {
598         assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
599                "Cannot have a live-out virtual register!");
600         HandlePhysRegUse(*I, Ret);
601
602         // Add live-out registers as implicit uses.
603         if (!Ret->readsRegister(*I))
604           Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
605       }
606     }
607
608     // MachineCSE may CSE instructions which write to non-allocatable physical
609     // registers across MBBs. Remember if any reserved register is liveout.
610     SmallSet<unsigned, 4> LiveOuts;
611     for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
612            SE = MBB->succ_end(); SI != SE; ++SI) {
613       MachineBasicBlock *SuccMBB = *SI;
614       if (SuccMBB->isLandingPad())
615         continue;
616       for (MachineBasicBlock::livein_iterator LI = SuccMBB->livein_begin(),
617              LE = SuccMBB->livein_end(); LI != LE; ++LI) {
618         unsigned LReg = *LI;
619         if (!TRI->isInAllocatableClass(LReg))
620           // Ignore other live-ins, e.g. those that are live into landing pads.
621           LiveOuts.insert(LReg);
622       }
623     }
624
625     // Loop over PhysRegDef / PhysRegUse, killing any registers that are
626     // available at the end of the basic block.
627     for (unsigned i = 0; i != NumRegs; ++i)
628       if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
629         HandlePhysRegDef(i, 0, Defs);
630
631     std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
632     std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
633   }
634
635   // Convert and transfer the dead / killed information we have gathered into
636   // VirtRegInfo onto MI's.
637   for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
638     const unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
639     for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
640       if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
641         VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
642       else
643         VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
644   }
645
646   // Check to make sure there are no unreachable blocks in the MC CFG for the
647   // function.  If so, it is due to a bug in the instruction selector or some
648   // other part of the code generator if this happens.
649 #ifndef NDEBUG
650   for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
651     assert(Visited.count(&*i) != 0 && "unreachable basic block found");
652 #endif
653
654   delete[] PhysRegDef;
655   delete[] PhysRegUse;
656   delete[] PHIVarInfo;
657
658   return false;
659 }
660
661 /// replaceKillInstruction - Update register kill info by replacing a kill
662 /// instruction with a new one.
663 void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr *OldMI,
664                                            MachineInstr *NewMI) {
665   VarInfo &VI = getVarInfo(Reg);
666   std::replace(VI.Kills.begin(), VI.Kills.end(), OldMI, NewMI);
667 }
668
669 /// removeVirtualRegistersKilled - Remove all killed info for the specified
670 /// instruction.
671 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
672   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
673     MachineOperand &MO = MI->getOperand(i);
674     if (MO.isReg() && MO.isKill()) {
675       MO.setIsKill(false);
676       unsigned Reg = MO.getReg();
677       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
678         bool removed = getVarInfo(Reg).removeKill(MI);
679         assert(removed && "kill not in register's VarInfo?");
680         (void)removed;
681       }
682     }
683   }
684 }
685
686 /// analyzePHINodes - Gather information about the PHI nodes in here. In
687 /// particular, we want to map the variable information of a virtual register
688 /// which is used in a PHI node. We map that to the BB the vreg is coming from.
689 ///
690 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
691   for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
692        I != E; ++I)
693     for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
694          BBI != BBE && BBI->isPHI(); ++BBI)
695       for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
696         PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()]
697           .push_back(BBI->getOperand(i).getReg());
698 }
699
700 bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB,
701                                       unsigned Reg,
702                                       MachineRegisterInfo &MRI) {
703   unsigned Num = MBB.getNumber();
704
705   // Reg is live-through.
706   if (AliveBlocks.test(Num))
707     return true;
708
709   // Registers defined in MBB cannot be live in.
710   const MachineInstr *Def = MRI.getVRegDef(Reg);
711   if (Def && Def->getParent() == &MBB)
712     return false;
713
714  // Reg was not defined in MBB, was it killed here?
715   return findKill(&MBB);
716 }
717
718 bool LiveVariables::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB) {
719   LiveVariables::VarInfo &VI = getVarInfo(Reg);
720
721   // Loop over all of the successors of the basic block, checking to see if
722   // the value is either live in the block, or if it is killed in the block.
723   SmallVector<MachineBasicBlock*, 8> OpSuccBlocks;
724   for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
725          E = MBB.succ_end(); SI != E; ++SI) {
726     MachineBasicBlock *SuccMBB = *SI;
727
728     // Is it alive in this successor?
729     unsigned SuccIdx = SuccMBB->getNumber();
730     if (VI.AliveBlocks.test(SuccIdx))
731       return true;
732     OpSuccBlocks.push_back(SuccMBB);
733   }
734
735   // Check to see if this value is live because there is a use in a successor
736   // that kills it.
737   switch (OpSuccBlocks.size()) {
738   case 1: {
739     MachineBasicBlock *SuccMBB = OpSuccBlocks[0];
740     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
741       if (VI.Kills[i]->getParent() == SuccMBB)
742         return true;
743     break;
744   }
745   case 2: {
746     MachineBasicBlock *SuccMBB1 = OpSuccBlocks[0], *SuccMBB2 = OpSuccBlocks[1];
747     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
748       if (VI.Kills[i]->getParent() == SuccMBB1 ||
749           VI.Kills[i]->getParent() == SuccMBB2)
750         return true;
751     break;
752   }
753   default:
754     std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());
755     for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i)
756       if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),
757                              VI.Kills[i]->getParent()))
758         return true;
759   }
760   return false;
761 }
762
763 /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
764 /// variables that are live out of DomBB will be marked as passing live through
765 /// BB.
766 void LiveVariables::addNewBlock(MachineBasicBlock *BB,
767                                 MachineBasicBlock *DomBB,
768                                 MachineBasicBlock *SuccBB) {
769   const unsigned NumNew = BB->getNumber();
770
771   // All registers used by PHI nodes in SuccBB must be live through BB.
772   for (MachineBasicBlock::iterator BBI = SuccBB->begin(),
773          BBE = SuccBB->end(); BBI != BBE && BBI->isPHI(); ++BBI)
774     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
775       if (BBI->getOperand(i+1).getMBB() == BB)
776         getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
777
778   // Update info for all live variables
779   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
780     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
781     VarInfo &VI = getVarInfo(Reg);
782     if (!VI.AliveBlocks.test(NumNew) && VI.isLiveIn(*SuccBB, Reg, *MRI))
783       VI.AliveBlocks.set(NumNew);
784   }
785 }