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