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