LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
LiveRangeEdit.cpp
Go to the documentation of this file.
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"
16 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Support/Debug.h"
24 
25 using namespace llvm;
26 
27 STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE");
28 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
29 STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE");
30 
31 void LiveRangeEdit::Delegate::anchor() { }
32 
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 
42 unsigned 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 
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 
61 void 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 
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.
83 bool 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.
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 
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 
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 
161  if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
162  LIS.removeInterval(Reg);
163 }
164 
165 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
167  MachineInstr *DefMI = 0, *UseMI = 0;
168 
169  // Check that there is a single def and a single use.
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 
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.
225 void 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
254  MOE = MI->operands_end(); MOI != MOE; ++MOI) {
255  if (!MOI->isReg())
256  continue;
257  unsigned Reg = MOI->getReg();
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 (LiveRange *LR = LIS.getCachedRegUnit(*Units)) {
266  if (VNInfo *VNI = LR->getVNInfoAt(Idx))
267  LR->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.Query(Idx).isKill()))
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);
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);
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 
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) {
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.
398 void
399 LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
400 {
401  if (VRM)
402  VRM->grow();
403 
404  NewRegs.push_back(VReg);
405 }
406 
407 void
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');
418  }
419 }
bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) const
const MachineFunction * getParent() const
mop_iterator operands_end()
Definition: MachineInstr.h:285
Calculate auxiliary information for a virtual register such as its spill weight and allocation hint...
MachineInstr * getParent()
const unsigned reg
Definition: LiveInterval.h:532
SlotIndex def
The index of the defining instruction.
Definition: LiveInterval.h:52
bool anyRematerializable(AliasAnalysis *)
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
bool addRegisterDead(unsigned Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
unsigned createVirtualRegister(const TargetRegisterClass *RegClass)
SlotIndex getInstructionIndex(const MachineInstr *instr) const
Returns the base index of the given instruction.
static bool isVirtualRegister(unsigned Reg)
bool readsVirtualRegister(unsigned Reg) const
Definition: MachineInstr.h:731
bool isKill() const
Definition: LiveInterval.h:107
virtual void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg, unsigned SubIdx, const MachineInstr *Orig, const TargetRegisterInfo &TRI) const
bool canFoldAsLoad(QueryType Type=IgnoreBundle) const
Definition: MachineInstr.h:454
MachineInstr * foldMemoryOperand(MachineBasicBlock::iterator MI, const SmallVectorImpl< unsigned > &Ops, int FrameIndex) const
bool empty() const
Definition: LiveInterval.h:311
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Definition: LiveInterval.h:350
LoopInfoBase< BlockT, LoopT > * LI
Definition: LoopInfoImpl.h:411
bool allDefsAreDead() const
bool checkRematerializable(VNInfo *VNI, const MachineInstr *DefMI, AliasAnalysis *)
Hexagon Hardware Loops
const char * getName() const
const TargetRegisterInfo * getTargetRegisterInfo() const
INITIALIZE_PASS(DeadMachineInstructionElim,"dead-mi-elimination","Remove dead machine instructions", false, false) bool DeadMachineInstructionElim bool SawStore
globalsmodref aa
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
Definition: SmallVector.h:430
bool isReg() const
isReg - Tests if this is a MO_Register operand.
const TargetRegisterClass * getRegClass(unsigned Reg) const
bool isUndef() const
unsigned Classify(const LiveInterval *LI)
void pop_back()
Remove the last element of the SetVector.
Definition: SetVector.h:167
unsigned getNumOperands() const
Definition: MachineInstr.h:265
bool isUnused() const
Returns true if this value is unused.
Definition: LiveInterval.h:76
void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI)
void RemoveOperand(unsigned i)
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:56
void setIsSplitFromReg(unsigned virtReg, unsigned SReg)
records virtReg is a split live interval from SReg.
Definition: VirtRegMap.h:138
bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=0)
bool isBundled() const
Definition: MachineInstr.h:216
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:59
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:109
LiveRange * getCachedRegUnit(unsigned Unit)
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:119
bundle_iterator< MachineInstr, instr_iterator > iterator
void removeValNo(VNInfo *ValNo)
void RemoveMachineInstrFromMaps(MachineInstr *MI)
unsigned createFrom(unsigned OldReg)
createFrom - Create a new virtual register based on OldReg.
SlotIndexes * getSlotIndexes() const
LiveQueryResult Query(SlotIndex Idx) const
Definition: LiveInterval.h:441
void removeInterval(unsigned Reg)
unsigned getOriginal(unsigned VirtReg) const
Definition: VirtRegMap.h:151
bool isReserved(unsigned PhysReg) const
bool isAsCheapAsAMove(QueryType Type=AllInBundle) const
Definition: MachineInstr.h:560
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:267
bool isCopy() const
Definition: MachineInstr.h:669
virtual bool LRE_CanEraseVirtReg(unsigned)
Definition: LiveRangeEdit.h:47
bool canRematerializeAt(Remat &RM, SlotIndex UseIdx, bool cheapAsAMove)
LiveInterval & getParent() const
virtual void LRE_WillEraseInstruction(MachineInstr *MI)
Called immediately before erasing a dead machine instruction.
Definition: LiveRangeEdit.h:43
unsigned getSubReg() const
const MCInstrDesc & get(unsigned Opcode) const
Definition: MCInstrInfo.h:48
void setDesc(const MCInstrDesc &tid)
Definition: MachineInstr.h:984
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
Definition: SlotIndexes.h:206
bool isInlineAsm() const
Definition: MachineInstr.h:651
void calculateSpillWeightAndHint(LiveInterval &li)
(re)compute li's spill weight and allocation hint.
LiveInterval & getInterval(unsigned Reg)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
Definition: Debug.cpp:101
LiveInterval & createEmptyInterval(unsigned Reg)
virtual void LRE_WillShrinkVirtReg(unsigned)
Called before shrinking the live range of a virtual register.
Definition: LiveRangeEdit.h:50
bool isSafeToMove(const TargetInstrInfo *TII, AliasAnalysis *AA, bool &SawStore) const
void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI)
static bool isPhysicalRegister(unsigned Reg)
SlotIndex rematerializeAt(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg, const Remat &RM, const TargetRegisterInfo &, bool Late=false)
bool recomputeRegClass(unsigned Reg, const TargetMachine &)
STATISTIC(NumDCEDeleted,"Number of instructions deleted by DCE")
bool hasOneNonDBGUse(unsigned RegNo) const
#define I(x, y, z)
Definition: MD5.cpp:54
virtual void LRE_DidCloneVirtReg(unsigned New, unsigned Old)
Definition: LiveRangeEdit.h:54
const TargetMachine & getTarget() const
const T & back() const
Return the last element of the SetVector.
Definition: SetVector.h:89
bool hasInterval(unsigned Reg) const
bool isTriviallyReMaterializable(const MachineInstr *MI, AliasAnalysis *AA=0) const
static reg_nodbg_iterator reg_nodbg_end()
Remat - Information needed to rematerialize at a specific location.
SlotIndex getRegSlot(bool EC=false) const
Definition: SlotIndexes.h:257
unsigned getReg() const
getReg - Returns the register number.
void eliminateDeadDefs(SmallVectorImpl< MachineInstr * > &Dead, ArrayRef< unsigned > RegsBeingSpilled=None)
mop_iterator operands_begin()
Definition: MachineInstr.h:284
LiveInterval & createEmptyIntervalFrom(unsigned OldReg)
createEmptyIntervalFrom - Create a new empty interval based on OldReg.
A vector that has set insertion semantics.
Definition: SetVector.h:37
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
#define DEBUG(X)
Definition: Debug.h:97
void calculateRegClassAndHint(MachineFunction &, const MachineLoopInfo &, const MachineBlockFrequencyInfo &)
void eraseVirtReg(unsigned Reg)
bool readsReg() const
unsigned size() const
reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:92
SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late=false)
Definition: SlotIndexes.h:569
bool reg_nodbg_empty(unsigned RegNo) const