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