LiveRangeEdit.cpp revision 1362dcb5899bc88f0e567dd10e2e9003a79ace21
1//===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
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// The LiveRangeEdit class represents changes done to a virtual register when it
11// is spilled or split.
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "regalloc"
15#include "llvm/CodeGen/LiveRangeEdit.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/CodeGen/CalcSpillWeights.h"
18#include "llvm/CodeGen/LiveIntervalAnalysis.h"
19#include "llvm/CodeGen/MachineRegisterInfo.h"
20#include "llvm/CodeGen/VirtRegMap.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/Support/raw_ostream.h"
23#include "llvm/Target/TargetInstrInfo.h"
24
25using namespace llvm;
26
27STATISTIC(NumDCEDeleted,     "Number of instructions deleted by DCE");
28STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
29STATISTIC(NumFracRanges,     "Number of live ranges fractured by DCE");
30
31void LiveRangeEdit::Delegate::anchor() { }
32
33LiveInterval &LiveRangeEdit::createEmptyIntervalFrom(unsigned OldReg) {
34  unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
35  if (VRM) {
36    VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
37  }
38  LiveInterval &LI = LIS.createEmptyInterval(VReg);
39  return LI;
40}
41
42unsigned LiveRangeEdit::createFrom(unsigned OldReg) {
43  unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
44  if (VRM) {
45    VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
46  }
47  return VReg;
48}
49
50bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
51                                          const MachineInstr *DefMI,
52                                          AliasAnalysis *aa) {
53  assert(DefMI && "Missing instruction");
54  ScannedRemattable = true;
55  if (!TII.isTriviallyReMaterializable(DefMI, aa))
56    return false;
57  Remattable.insert(VNI);
58  return true;
59}
60
61void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
62  for (LiveInterval::vni_iterator I = getParent().vni_begin(),
63       E = getParent().vni_end(); I != E; ++I) {
64    VNInfo *VNI = *I;
65    if (VNI->isUnused())
66      continue;
67    MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
68    if (!DefMI)
69      continue;
70    checkRematerializable(VNI, DefMI, aa);
71  }
72  ScannedRemattable = true;
73}
74
75bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
76  if (!ScannedRemattable)
77    scanRemattable(aa);
78  return !Remattable.empty();
79}
80
81/// allUsesAvailableAt - Return true if all registers used by OrigMI at
82/// OrigIdx are also available with the same value at UseIdx.
83bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
84                                       SlotIndex OrigIdx,
85                                       SlotIndex UseIdx) const {
86  OrigIdx = OrigIdx.getRegSlot(true);
87  UseIdx = UseIdx.getRegSlot(true);
88  for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
89    const MachineOperand &MO = OrigMI->getOperand(i);
90    if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
91      continue;
92
93    // We can't remat physreg uses, unless it is a constant.
94    if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
95      if (MRI.isConstantPhysReg(MO.getReg(), *OrigMI->getParent()->getParent()))
96        continue;
97      return false;
98    }
99
100    LiveInterval &li = LIS.getInterval(MO.getReg());
101    const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
102    if (!OVNI)
103      continue;
104
105    // Don't allow rematerialization immediately after the original def.
106    // It would be incorrect if OrigMI redefines the register.
107    // See PR14098.
108    if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
109      return false;
110
111    if (OVNI != li.getVNInfoAt(UseIdx))
112      return false;
113  }
114  return true;
115}
116
117bool LiveRangeEdit::canRematerializeAt(Remat &RM,
118                                       SlotIndex UseIdx,
119                                       bool cheapAsAMove) {
120  assert(ScannedRemattable && "Call anyRematerializable first");
121
122  // Use scanRemattable info.
123  if (!Remattable.count(RM.ParentVNI))
124    return false;
125
126  // No defining instruction provided.
127  SlotIndex DefIdx;
128  if (RM.OrigMI)
129    DefIdx = LIS.getInstructionIndex(RM.OrigMI);
130  else {
131    DefIdx = RM.ParentVNI->def;
132    RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
133    assert(RM.OrigMI && "No defining instruction for remattable value");
134  }
135
136  // If only cheap remats were requested, bail out early.
137  if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
138    return false;
139
140  // Verify that all used registers are available with the same values.
141  if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
142    return false;
143
144  return true;
145}
146
147SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
148                                         MachineBasicBlock::iterator MI,
149                                         unsigned DestReg,
150                                         const Remat &RM,
151                                         const TargetRegisterInfo &tri,
152                                         bool Late) {
153  assert(RM.OrigMI && "Invalid remat");
154  TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
155  Rematted.insert(RM.ParentVNI);
156  return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
157           .getRegSlot();
158}
159
160void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
161  if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
162    LIS.removeInterval(Reg);
163}
164
165bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
166                               SmallVectorImpl<MachineInstr*> &Dead) {
167  MachineInstr *DefMI = 0, *UseMI = 0;
168
169  // Check that there is a single def and a single use.
170  for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
171       E = MRI.reg_nodbg_end(); I != E; ++I) {
172    MachineOperand &MO = I.getOperand();
173    MachineInstr *MI = MO.getParent();
174    if (MO.isDef()) {
175      if (DefMI && DefMI != MI)
176        return false;
177      if (!MI->canFoldAsLoad())
178        return false;
179      DefMI = MI;
180    } else if (!MO.isUndef()) {
181      if (UseMI && UseMI != MI)
182        return false;
183      // FIXME: Targets don't know how to fold subreg uses.
184      if (MO.getSubReg())
185        return false;
186      UseMI = MI;
187    }
188  }
189  if (!DefMI || !UseMI)
190    return false;
191
192  // Since we're moving the DefMI load, make sure we're not extending any live
193  // ranges.
194  if (!allUsesAvailableAt(DefMI,
195                          LIS.getInstructionIndex(DefMI),
196                          LIS.getInstructionIndex(UseMI)))
197    return false;
198
199  // We also need to make sure it is safe to move the load.
200  // Assume there are stores between DefMI and UseMI.
201  bool SawStore = true;
202  if (!DefMI->isSafeToMove(&TII, 0, SawStore))
203    return false;
204
205  DEBUG(dbgs() << "Try to fold single def: " << *DefMI
206               << "       into single use: " << *UseMI);
207
208  SmallVector<unsigned, 8> Ops;
209  if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
210    return false;
211
212  MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
213  if (!FoldMI)
214    return false;
215  DEBUG(dbgs() << "                folded: " << *FoldMI);
216  LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
217  UseMI->eraseFromParent();
218  DefMI->addRegisterDead(LI->reg, 0);
219  Dead.push_back(DefMI);
220  ++NumDCEFoldedLoads;
221  return true;
222}
223
224/// Find all live intervals that need to shrink, then remove the instruction.
225void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) {
226  assert(MI->allDefsAreDead() && "Def isn't really dead");
227  SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
228
229  // Never delete a bundled instruction.
230  if (MI->isBundled()) {
231    return;
232  }
233  // Never delete inline asm.
234  if (MI->isInlineAsm()) {
235    DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
236    return;
237  }
238
239  // Use the same criteria as DeadMachineInstructionElim.
240  bool SawStore = false;
241  if (!MI->isSafeToMove(&TII, 0, SawStore)) {
242    DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
243    return;
244  }
245
246  DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
247
248  // Collect virtual registers to be erased after MI is gone.
249  SmallVector<unsigned, 8> RegsToErase;
250  bool ReadsPhysRegs = false;
251
252  // Check for live intervals that may shrink
253  for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
254         MOE = MI->operands_end(); MOI != MOE; ++MOI) {
255    if (!MOI->isReg())
256      continue;
257    unsigned Reg = MOI->getReg();
258    if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
259      // Check if MI reads any unreserved physregs.
260      if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
261        ReadsPhysRegs = true;
262      else if (MOI->isDef()) {
263        for (MCRegUnitIterator Units(Reg, MRI.getTargetRegisterInfo());
264             Units.isValid(); ++Units) {
265          if (LiveInterval *LI = LIS.getCachedRegUnit(*Units)) {
266            if (VNInfo *VNI = LI->getVNInfoAt(Idx))
267              LI->removeValNo(VNI);
268          }
269        }
270      }
271      continue;
272    }
273    LiveInterval &LI = LIS.getInterval(Reg);
274
275    // Shrink read registers, unless it is likely to be expensive and
276    // unlikely to change anything. We typically don't want to shrink the
277    // PIC base register that has lots of uses everywhere.
278    // Always shrink COPY uses that probably come from live range splitting.
279    if (MI->readsVirtualRegister(Reg) &&
280        (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
281         LI.isKilledAtInstr(Idx)))
282      ToShrink.insert(&LI);
283
284    // Remove defined value.
285    if (MOI->isDef()) {
286      if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
287        if (TheDelegate)
288          TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
289        LI.removeValNo(VNI);
290        if (LI.empty())
291          RegsToErase.push_back(Reg);
292      }
293    }
294  }
295
296  // Currently, we don't support DCE of physreg live ranges. If MI reads
297  // any unreserved physregs, don't erase the instruction, but turn it into
298  // a KILL instead. This way, the physreg live ranges don't end up
299  // dangling.
300  // FIXME: It would be better to have something like shrinkToUses() for
301  // physregs. That could potentially enable more DCE and it would free up
302  // the physreg. It would not happen often, though.
303  if (ReadsPhysRegs) {
304    MI->setDesc(TII.get(TargetOpcode::KILL));
305    // Remove all operands that aren't physregs.
306    for (unsigned i = MI->getNumOperands(); i; --i) {
307      const MachineOperand &MO = MI->getOperand(i-1);
308      if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
309        continue;
310      MI->RemoveOperand(i-1);
311    }
312    DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
313  } else {
314    if (TheDelegate)
315      TheDelegate->LRE_WillEraseInstruction(MI);
316    LIS.RemoveMachineInstrFromMaps(MI);
317    MI->eraseFromParent();
318    ++NumDCEDeleted;
319  }
320
321  // Erase any virtregs that are now empty and unused. There may be <undef>
322  // uses around. Keep the empty live range in that case.
323  for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
324    unsigned Reg = RegsToErase[i];
325    if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
326      ToShrink.remove(&LIS.getInterval(Reg));
327      eraseVirtReg(Reg);
328    }
329  }
330}
331
332void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
333                                      ArrayRef<unsigned> RegsBeingSpilled) {
334  ToShrinkSet ToShrink;
335
336  for (;;) {
337    // Erase all dead defs.
338    while (!Dead.empty())
339      eliminateDeadDef(Dead.pop_back_val(), ToShrink);
340
341    if (ToShrink.empty())
342      break;
343
344    // Shrink just one live interval. Then delete new dead defs.
345    LiveInterval *LI = ToShrink.back();
346    ToShrink.pop_back();
347    if (foldAsLoad(LI, Dead))
348      continue;
349    if (TheDelegate)
350      TheDelegate->LRE_WillShrinkVirtReg(LI->reg);
351    if (!LIS.shrinkToUses(LI, &Dead))
352      continue;
353
354    // Don't create new intervals for a register being spilled.
355    // The new intervals would have to be spilled anyway so its not worth it.
356    // Also they currently aren't spilled so creating them and not spilling
357    // them results in incorrect code.
358    bool BeingSpilled = false;
359    for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
360      if (LI->reg == RegsBeingSpilled[i]) {
361        BeingSpilled = true;
362        break;
363      }
364    }
365
366    if (BeingSpilled) continue;
367
368    // LI may have been separated, create new intervals.
369    LI->RenumberValues();
370    ConnectedVNInfoEqClasses ConEQ(LIS);
371    unsigned NumComp = ConEQ.Classify(LI);
372    if (NumComp <= 1)
373      continue;
374    ++NumFracRanges;
375    bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg;
376    DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
377    SmallVector<LiveInterval*, 8> Dups(1, LI);
378    for (unsigned i = 1; i != NumComp; ++i) {
379      Dups.push_back(&createEmptyIntervalFrom(LI->reg));
380      // If LI is an original interval that hasn't been split yet, make the new
381      // intervals their own originals instead of referring to LI. The original
382      // interval must contain all the split products, and LI doesn't.
383      if (IsOriginal)
384        VRM->setIsSplitFromReg(Dups.back()->reg, 0);
385      if (TheDelegate)
386        TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
387    }
388    ConEQ.Distribute(&Dups[0], MRI);
389    DEBUG({
390      for (unsigned i = 0; i != NumComp; ++i)
391        dbgs() << '\t' << *Dups[i] << '\n';
392    });
393  }
394}
395
396// Keep track of new virtual registers created via
397// MachineRegisterInfo::createVirtualRegister.
398void
399LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
400{
401  if (VRM)
402    VRM->grow();
403
404  NewRegs.push_back(VReg);
405}
406
407void
408LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
409                                        const MachineLoopInfo &Loops,
410                                        const MachineBlockFrequencyInfo &MBFI) {
411  VirtRegAuxInfo VRAI(MF, LIS, Loops, MBFI);
412  for (unsigned I = 0, Size = size(); I < Size; ++I) {
413    LiveInterval &LI = LIS.getInterval(get(I));
414    if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
415      DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
416                   << MRI.getRegClass(LI.reg)->getName() << '\n');
417    VRAI.CalculateWeightAndHint(LI);
418  }
419}
420