LiveVariables.cpp revision 4efe74129f7483bc8c48d68f095d632b974c353d
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>
38using namespace llvm;
39
40char LiveVariables::ID = 0;
41static RegisterPass<LiveVariables> X("livevars", "Live Variable Analysis");
42
43void LiveVariables::VarInfo::dump() const {
44  cerr << "Register Defined by: ";
45  if (DefInst)
46    cerr << *DefInst;
47  else
48    cerr << "<null>\n";
49  cerr << "  Alive in blocks: ";
50  for (unsigned i = 0, e = AliveBlocks.size(); i != e; ++i)
51    if (AliveBlocks[i]) cerr << i << ", ";
52  cerr << "\n  Killed by:";
53  if (Kills.empty())
54    cerr << " No instructions.\n";
55  else {
56    for (unsigned i = 0, e = Kills.size(); i != e; ++i)
57      cerr << "\n    #" << i << ": " << *Kills[i];
58    cerr << "\n";
59  }
60}
61
62LiveVariables::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  VarInfo &VI = VirtRegInfo[RegIdx];
73  VI.AliveBlocks.resize(MF->getNumBlockIDs());
74  return VI;
75}
76
77bool LiveVariables::KillsRegister(MachineInstr *MI, unsigned Reg) const {
78  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
79    MachineOperand &MO = MI->getOperand(i);
80    if (MO.isReg() && MO.isKill()) {
81      if ((MO.getReg() == Reg) ||
82          (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
83           MRegisterInfo::isPhysicalRegister(Reg) &&
84           RegInfo->isSubRegister(MO.getReg(), Reg)))
85        return true;
86    }
87  }
88  return false;
89}
90
91bool 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 ((MO.getReg() == Reg) ||
96          (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
97           MRegisterInfo::isPhysicalRegister(Reg) &&
98           RegInfo->isSubRegister(MO.getReg(), Reg)))
99        return true;
100    }
101  }
102  return false;
103}
104
105bool LiveVariables::ModifiesRegister(MachineInstr *MI, unsigned Reg) const {
106  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
107    MachineOperand &MO = MI->getOperand(i);
108    if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
109      return true;
110  }
111  return false;
112}
113
114void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
115                                            MachineBasicBlock *MBB,
116                                    std::vector<MachineBasicBlock*> &WorkList) {
117  unsigned BBNum = MBB->getNumber();
118
119  // Check to see if this basic block is one of the killing blocks.  If so,
120  // remove it...
121  for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
122    if (VRInfo.Kills[i]->getParent() == MBB) {
123      VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
124      break;
125    }
126
127  if (MBB == VRInfo.DefInst->getParent()) return;  // Terminate recursion
128
129  if (VRInfo.AliveBlocks[BBNum])
130    return;  // We already know the block is live
131
132  // Mark the variable known alive in this bb
133  VRInfo.AliveBlocks[BBNum] = true;
134
135  for (MachineBasicBlock::const_pred_reverse_iterator PI = MBB->pred_rbegin(),
136         E = MBB->pred_rend(); PI != E; ++PI)
137    WorkList.push_back(*PI);
138}
139
140void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo,
141                                            MachineBasicBlock *MBB) {
142  std::vector<MachineBasicBlock*> WorkList;
143  MarkVirtRegAliveInBlock(VRInfo, MBB, WorkList);
144  while (!WorkList.empty()) {
145    MachineBasicBlock *Pred = WorkList.back();
146    WorkList.pop_back();
147    MarkVirtRegAliveInBlock(VRInfo, Pred, WorkList);
148  }
149}
150
151
152void LiveVariables::HandleVirtRegUse(VarInfo &VRInfo, MachineBasicBlock *MBB,
153                                     MachineInstr *MI) {
154  assert(VRInfo.DefInst && "Register use before def!");
155
156  VRInfo.NumUses++;
157
158  // Check to see if this basic block is already a kill block...
159  if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
160    // Yes, this register is killed in this basic block already.  Increase the
161    // live range by updating the kill instruction.
162    VRInfo.Kills.back() = MI;
163    return;
164  }
165
166#ifndef NDEBUG
167  for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
168    assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!");
169#endif
170
171  assert(MBB != VRInfo.DefInst->getParent() &&
172         "Should have kill for defblock!");
173
174  // Add a new kill entry for this basic block.
175  // If this virtual register is already marked as alive in this basic block,
176  // that means it is alive in at least one of the successor block, it's not
177  // a kill.
178  if (!VRInfo.AliveBlocks[MBB->getNumber()])
179    VRInfo.Kills.push_back(MI);
180
181  // Update all dominating blocks to mark them known live.
182  for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
183         E = MBB->pred_end(); PI != E; ++PI)
184    MarkVirtRegAliveInBlock(VRInfo, *PI);
185}
186
187bool LiveVariables::addRegisterKilled(unsigned IncomingReg, MachineInstr *MI,
188                                      bool AddIfNotFound) {
189  bool Found = false;
190  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
191    MachineOperand &MO = MI->getOperand(i);
192    if (MO.isReg() && MO.isUse()) {
193      unsigned Reg = MO.getReg();
194      if (!Reg)
195        continue;
196      if (Reg == IncomingReg) {
197        MO.setIsKill();
198        Found = true;
199        break;
200      } else if (MRegisterInfo::isPhysicalRegister(Reg) &&
201                 MRegisterInfo::isPhysicalRegister(IncomingReg) &&
202                 RegInfo->isSuperRegister(IncomingReg, Reg) &&
203                 MO.isKill())
204        // A super-register kill already exists.
205        return true;
206    }
207  }
208
209  // If not found, this means an alias of one of the operand is killed. Add a
210  // new implicit operand if required.
211  if (!Found && AddIfNotFound) {
212    MI->addRegOperand(IncomingReg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
213    return true;
214  }
215  return Found;
216}
217
218bool LiveVariables::addRegisterDead(unsigned IncomingReg, MachineInstr *MI,
219                                    bool AddIfNotFound) {
220  bool Found = false;
221  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
222    MachineOperand &MO = MI->getOperand(i);
223    if (MO.isReg() && MO.isDef()) {
224      unsigned Reg = MO.getReg();
225      if (!Reg)
226        continue;
227      if (Reg == IncomingReg) {
228        MO.setIsDead();
229        Found = true;
230        break;
231      } else if (MRegisterInfo::isPhysicalRegister(Reg) &&
232                 MRegisterInfo::isPhysicalRegister(IncomingReg) &&
233                 RegInfo->isSuperRegister(IncomingReg, Reg) &&
234                 MO.isDead())
235        // There exists a super-register that's marked dead.
236        return true;
237    }
238  }
239
240  // If not found, this means an alias of one of the operand is dead. Add a
241  // new implicit operand.
242  if (!Found && AddIfNotFound) {
243    MI->addRegOperand(IncomingReg, true/*IsDef*/,true/*IsImp*/,false/*IsKill*/,
244                      true/*IsDead*/);
245    return true;
246  }
247  return Found;
248}
249
250void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) {
251  // There is a now a proper use, forget about the last partial use.
252  PhysRegPartUse[Reg] = NULL;
253
254  // Turn previous partial def's into read/mod/write.
255  for (unsigned i = 0, e = PhysRegPartDef[Reg].size(); i != e; ++i) {
256    MachineInstr *Def = PhysRegPartDef[Reg][i];
257    // First one is just a def. This means the use is reading some undef bits.
258    if (i != 0)
259      Def->addRegOperand(Reg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
260    Def->addRegOperand(Reg, true/*IsDef*/,true/*IsImp*/);
261  }
262  PhysRegPartDef[Reg].clear();
263
264  // There was an earlier def of a super-register. Add implicit def to that MI.
265  // A: EAX = ...
266  // B:     = AX
267  // Add implicit def to A.
268  if (PhysRegInfo[Reg] && !PhysRegUsed[Reg]) {
269    MachineInstr *Def = PhysRegInfo[Reg];
270    if (!Def->findRegisterDefOperand(Reg))
271      Def->addRegOperand(Reg, true/*IsDef*/,true/*IsImp*/);
272  }
273
274  PhysRegInfo[Reg] = MI;
275  PhysRegUsed[Reg] = true;
276
277  for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
278       unsigned SubReg = *SubRegs; ++SubRegs) {
279    PhysRegInfo[SubReg] = MI;
280    PhysRegUsed[SubReg] = true;
281  }
282
283  // Remember the partial uses.
284  for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
285       unsigned SuperReg = *SuperRegs; ++SuperRegs)
286    PhysRegPartUse[SuperReg] = MI;
287}
288
289bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *RefMI,
290                                      SmallSet<unsigned, 4> &SubKills) {
291  for (const unsigned *SubRegs = RegInfo->getImmediateSubRegisters(Reg);
292       unsigned SubReg = *SubRegs; ++SubRegs) {
293    MachineInstr *LastRef = PhysRegInfo[SubReg];
294    if (LastRef != RefMI)
295      SubKills.insert(SubReg);
296    else if (!HandlePhysRegKill(SubReg, RefMI, SubKills))
297      SubKills.insert(SubReg);
298  }
299
300  if (*RegInfo->getImmediateSubRegisters(Reg) == 0) {
301    // No sub-registers, just check if reg is killed by RefMI.
302    if (PhysRegInfo[Reg] == RefMI)
303      return true;
304  } else if (SubKills.empty())
305    // None of the sub-registers are killed elsewhere...
306    return true;
307  return false;
308}
309
310void LiveVariables::addRegisterKills(unsigned Reg, MachineInstr *MI,
311                                     SmallSet<unsigned, 4> &SubKills) {
312  if (SubKills.count(Reg) == 0)
313    addRegisterKilled(Reg, MI, true);
314  else {
315    for (const unsigned *SubRegs = RegInfo->getImmediateSubRegisters(Reg);
316         unsigned SubReg = *SubRegs; ++SubRegs)
317      addRegisterKills(SubReg, MI, SubKills);
318  }
319}
320
321bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *RefMI) {
322  SmallSet<unsigned, 4> SubKills;
323  if (HandlePhysRegKill(Reg, RefMI, SubKills)) {
324    addRegisterKilled(Reg, RefMI);
325    return true;
326  } else {
327    // Some sub-registers are killed by another MI.
328    for (const unsigned *SubRegs = RegInfo->getImmediateSubRegisters(Reg);
329         unsigned SubReg = *SubRegs; ++SubRegs)
330      addRegisterKills(SubReg, RefMI, SubKills);
331    return false;
332  }
333}
334
335void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI) {
336  // Does this kill a previous version of this register?
337  if (MachineInstr *LastRef = PhysRegInfo[Reg]) {
338    if (PhysRegUsed[Reg]) {
339      if (!HandlePhysRegKill(Reg, LastRef)) {
340        if (PhysRegPartUse[Reg])
341          addRegisterKilled(Reg, PhysRegPartUse[Reg], true);
342      }
343    } else if (PhysRegPartUse[Reg])
344      // Add implicit use / kill to last use of a sub-register.
345      addRegisterKilled(Reg, PhysRegPartUse[Reg], true);
346    else
347      addRegisterDead(Reg, LastRef);
348  }
349
350  for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
351       unsigned SubReg = *SubRegs; ++SubRegs) {
352    if (MachineInstr *LastRef = PhysRegInfo[SubReg]) {
353      if (PhysRegUsed[SubReg]) {
354        if (!HandlePhysRegKill(SubReg, LastRef)) {
355          if (PhysRegPartUse[SubReg])
356            addRegisterKilled(SubReg, PhysRegPartUse[SubReg], true);
357        }
358        //addRegisterKilled(SubReg, LastRef);
359      } else if (PhysRegPartUse[SubReg])
360        // Add implicit use / kill to last use of a sub-register.
361        addRegisterKilled(SubReg, PhysRegPartUse[SubReg], true);
362      else
363        addRegisterDead(SubReg, LastRef);
364    }
365  }
366
367  if (MI) {
368    for (const unsigned *SuperRegs = RegInfo->getSuperRegisters(Reg);
369         unsigned SuperReg = *SuperRegs; ++SuperRegs) {
370      if (PhysRegInfo[SuperReg]) {
371        // The larger register is previously defined. Now a smaller part is
372        // being re-defined. Treat it as read/mod/write.
373        // EAX =
374        // AX  =        EAX<imp-use,kill>, EAX<imp-def>
375        MI->addRegOperand(SuperReg, false/*IsDef*/,true/*IsImp*/,true/*IsKill*/);
376        MI->addRegOperand(SuperReg, true/*IsDef*/,true/*IsImp*/);
377        PhysRegInfo[SuperReg] = MI;
378        PhysRegUsed[SuperReg] = false;
379        PhysRegPartUse[SuperReg] = NULL;
380      } else {
381        // Remember this partial def.
382        PhysRegPartDef[SuperReg].push_back(MI);
383      }
384    }
385
386    PhysRegInfo[Reg] = MI;
387    PhysRegUsed[Reg] = false;
388    PhysRegPartUse[Reg] = NULL;
389    for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
390         unsigned SubReg = *SubRegs; ++SubRegs) {
391      PhysRegInfo[SubReg] = MI;
392      PhysRegUsed[SubReg] = false;
393      PhysRegPartUse[SubReg] = NULL;
394    }
395  }
396}
397
398bool LiveVariables::runOnMachineFunction(MachineFunction &mf) {
399  MF = &mf;
400  const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
401  RegInfo = MF->getTarget().getRegisterInfo();
402  assert(RegInfo && "Target doesn't have register information?");
403
404  ReservedRegisters = RegInfo->getReservedRegs(mf);
405
406  unsigned NumRegs = RegInfo->getNumRegs();
407  PhysRegInfo = new MachineInstr*[NumRegs];
408  PhysRegUsed = new bool[NumRegs];
409  PhysRegPartUse = new MachineInstr*[NumRegs];
410  PhysRegPartDef = new SmallVector<MachineInstr*,4>[NumRegs];
411  PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()];
412  std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
413  std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
414  std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
415
416  /// Get some space for a respectable number of registers...
417  VirtRegInfo.resize(64);
418
419  analyzePHINodes(mf);
420
421  // Calculate live variable information in depth first order on the CFG of the
422  // function.  This guarantees that we will see the definition of a virtual
423  // register before its uses due to dominance properties of SSA (except for PHI
424  // nodes, which are treated as a special case).
425  //
426  MachineBasicBlock *Entry = MF->begin();
427  std::set<MachineBasicBlock*> Visited;
428  for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
429         E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
430    MachineBasicBlock *MBB = *DFI;
431
432    // Mark live-in registers as live-in.
433    for (MachineBasicBlock::const_livein_iterator II = MBB->livein_begin(),
434           EE = MBB->livein_end(); II != EE; ++II) {
435      assert(MRegisterInfo::isPhysicalRegister(*II) &&
436             "Cannot have a live-in virtual register!");
437      HandlePhysRegDef(*II, 0);
438    }
439
440    // Loop over all of the instructions, processing them.
441    for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
442         I != E; ++I) {
443      MachineInstr *MI = I;
444
445      // Process all of the operands of the instruction...
446      unsigned NumOperandsToProcess = MI->getNumOperands();
447
448      // Unless it is a PHI node.  In this case, ONLY process the DEF, not any
449      // of the uses.  They will be handled in other basic blocks.
450      if (MI->getOpcode() == TargetInstrInfo::PHI)
451        NumOperandsToProcess = 1;
452
453      // Process all uses...
454      for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
455        MachineOperand &MO = MI->getOperand(i);
456        if (MO.isRegister() && MO.isUse() && MO.getReg()) {
457          if (MRegisterInfo::isVirtualRegister(MO.getReg())){
458            HandleVirtRegUse(getVarInfo(MO.getReg()), MBB, MI);
459          } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
460                     !ReservedRegisters[MO.getReg()]) {
461            HandlePhysRegUse(MO.getReg(), MI);
462          }
463        }
464      }
465
466      // Process all defs...
467      for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
468        MachineOperand &MO = MI->getOperand(i);
469        if (MO.isRegister() && MO.isDef() && MO.getReg()) {
470          if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
471            VarInfo &VRInfo = getVarInfo(MO.getReg());
472
473            assert(VRInfo.DefInst == 0 && "Variable multiply defined!");
474            VRInfo.DefInst = MI;
475            // Defaults to dead
476            VRInfo.Kills.push_back(MI);
477          } else if (MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
478                     !ReservedRegisters[MO.getReg()]) {
479            HandlePhysRegDef(MO.getReg(), MI);
480          }
481        }
482      }
483    }
484
485    // Handle any virtual assignments from PHI nodes which might be at the
486    // bottom of this basic block.  We check all of our successor blocks to see
487    // if they have PHI nodes, and if so, we simulate an assignment at the end
488    // of the current block.
489    if (!PHIVarInfo[MBB->getNumber()].empty()) {
490      SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()];
491
492      for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(),
493             E = VarInfoVec.end(); I != E; ++I) {
494        VarInfo& VRInfo = getVarInfo(*I);
495        assert(VRInfo.DefInst && "Register use before def (or no def)!");
496
497        // Only mark it alive only in the block we are representing.
498        MarkVirtRegAliveInBlock(VRInfo, MBB);
499      }
500    }
501
502    // Finally, if the last instruction in the block is a return, make sure to mark
503    // it as using all of the live-out values in the function.
504    if (!MBB->empty() && TII.isReturn(MBB->back().getOpcode())) {
505      MachineInstr *Ret = &MBB->back();
506      for (MachineFunction::liveout_iterator I = MF->liveout_begin(),
507             E = MF->liveout_end(); I != E; ++I) {
508        assert(MRegisterInfo::isPhysicalRegister(*I) &&
509               "Cannot have a live-in virtual register!");
510        HandlePhysRegUse(*I, Ret);
511        // Add live-out registers as implicit uses.
512        if (Ret->findRegisterUseOperandIdx(*I) == -1)
513          Ret->addRegOperand(*I, false, true);
514      }
515    }
516
517    // Loop over PhysRegInfo, killing any registers that are available at the
518    // end of the basic block.  This also resets the PhysRegInfo map.
519    for (unsigned i = 0; i != NumRegs; ++i)
520      if (PhysRegInfo[i])
521        HandlePhysRegDef(i, 0);
522
523    // Clear some states between BB's. These are purely local information.
524    for (unsigned i = 0; i != NumRegs; ++i)
525      PhysRegPartDef[i].clear();
526    std::fill(PhysRegInfo, PhysRegInfo + NumRegs, (MachineInstr*)0);
527    std::fill(PhysRegUsed, PhysRegUsed + NumRegs, false);
528    std::fill(PhysRegPartUse, PhysRegPartUse + NumRegs, (MachineInstr*)0);
529  }
530
531  // Convert and transfer the dead / killed information we have gathered into
532  // VirtRegInfo onto MI's.
533  //
534  for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i)
535    for (unsigned j = 0, e2 = VirtRegInfo[i].Kills.size(); j != e2; ++j) {
536      if (VirtRegInfo[i].Kills[j] == VirtRegInfo[i].DefInst)
537        addRegisterDead(i + MRegisterInfo::FirstVirtualRegister,
538                        VirtRegInfo[i].Kills[j]);
539      else
540        addRegisterKilled(i + MRegisterInfo::FirstVirtualRegister,
541                          VirtRegInfo[i].Kills[j]);
542    }
543
544  // Check to make sure there are no unreachable blocks in the MC CFG for the
545  // function.  If so, it is due to a bug in the instruction selector or some
546  // other part of the code generator if this happens.
547#ifndef NDEBUG
548  for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i)
549    assert(Visited.count(&*i) != 0 && "unreachable basic block found");
550#endif
551
552  delete[] PhysRegInfo;
553  delete[] PhysRegUsed;
554  delete[] PhysRegPartUse;
555  delete[] PhysRegPartDef;
556  delete[] PHIVarInfo;
557
558  return false;
559}
560
561/// instructionChanged - When the address of an instruction changes, this
562/// method should be called so that live variables can update its internal
563/// data structures.  This removes the records for OldMI, transfering them to
564/// the records for NewMI.
565void LiveVariables::instructionChanged(MachineInstr *OldMI,
566                                       MachineInstr *NewMI) {
567  // If the instruction defines any virtual registers, update the VarInfo,
568  // kill and dead information for the instruction.
569  for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
570    MachineOperand &MO = OldMI->getOperand(i);
571    if (MO.isRegister() && MO.getReg() &&
572        MRegisterInfo::isVirtualRegister(MO.getReg())) {
573      unsigned Reg = MO.getReg();
574      VarInfo &VI = getVarInfo(Reg);
575      if (MO.isDef()) {
576        if (MO.isDead()) {
577          MO.unsetIsDead();
578          addVirtualRegisterDead(Reg, NewMI);
579        }
580        // Update the defining instruction.
581        if (VI.DefInst == OldMI)
582          VI.DefInst = NewMI;
583      }
584      if (MO.isUse()) {
585        if (MO.isKill()) {
586          MO.unsetIsKill();
587          addVirtualRegisterKilled(Reg, NewMI);
588        }
589        // If this is a kill of the value, update the VI kills list.
590        if (VI.removeKill(OldMI))
591          VI.Kills.push_back(NewMI);   // Yes, there was a kill of it
592      }
593    }
594  }
595}
596
597/// removeVirtualRegistersKilled - Remove all killed info for the specified
598/// instruction.
599void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) {
600  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
601    MachineOperand &MO = MI->getOperand(i);
602    if (MO.isReg() && MO.isKill()) {
603      MO.unsetIsKill();
604      unsigned Reg = MO.getReg();
605      if (MRegisterInfo::isVirtualRegister(Reg)) {
606        bool removed = getVarInfo(Reg).removeKill(MI);
607        assert(removed && "kill not in register's VarInfo?");
608      }
609    }
610  }
611}
612
613/// removeVirtualRegistersDead - Remove all of the dead registers for the
614/// specified instruction from the live variable information.
615void LiveVariables::removeVirtualRegistersDead(MachineInstr *MI) {
616  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
617    MachineOperand &MO = MI->getOperand(i);
618    if (MO.isReg() && MO.isDead()) {
619      MO.unsetIsDead();
620      unsigned Reg = MO.getReg();
621      if (MRegisterInfo::isVirtualRegister(Reg)) {
622        bool removed = getVarInfo(Reg).removeKill(MI);
623        assert(removed && "kill not in register's VarInfo?");
624      }
625    }
626  }
627}
628
629/// analyzePHINodes - Gather information about the PHI nodes in here. In
630/// particular, we want to map the variable information of a virtual
631/// register which is used in a PHI node. We map that to the BB the vreg is
632/// coming from.
633///
634void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
635  for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end();
636       I != E; ++I)
637    for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end();
638         BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)
639      for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
640        PHIVarInfo[BBI->getOperand(i + 1).getMachineBasicBlock()->getNumber()].
641          push_back(BBI->getOperand(i).getReg());
642}
643