1 //===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The LiveRangeEdit class represents changes done to a virtual register when it
10 // is spilled or split.
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/LiveRangeEdit.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/CodeGen/CalcSpillWeights.h"
16 #include "llvm/CodeGen/LiveIntervals.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetInstrInfo.h"
19 #include "llvm/CodeGen/VirtRegMap.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "regalloc"
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 
33 LiveInterval &LiveRangeEdit::createEmptyIntervalFrom(Register OldReg,
34                                                      bool createSubRanges) {
35   Register VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
36   if (VRM)
37     VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
38 
39   LiveInterval &LI = LIS.createEmptyInterval(VReg);
40   if (Parent && !Parent->isSpillable())
41     LI.markNotSpillable();
42   if (createSubRanges) {
43     // Create empty subranges if the OldReg's interval has them. Do not create
44     // the main range here---it will be constructed later after the subranges
45     // have been finalized.
46     LiveInterval &OldLI = LIS.getInterval(OldReg);
47     VNInfo::Allocator &Alloc = LIS.getVNInfoAllocator();
48     for (LiveInterval::SubRange &S : OldLI.subranges())
49       LI.createSubRange(Alloc, S.LaneMask);
50   }
51   return LI;
52 }
53 
54 Register LiveRangeEdit::createFrom(Register OldReg) {
55   Register VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
56   if (VRM) {
57     VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
58   }
59   // FIXME: Getting the interval here actually computes it.
60   // In theory, this may not be what we want, but in practice
61   // the createEmptyIntervalFrom API is used when this is not
62   // the case. Generally speaking we just want to annotate the
63   // LiveInterval when it gets created but we cannot do that at
64   // the moment.
65   if (Parent && !Parent->isSpillable())
66     LIS.getInterval(VReg).markNotSpillable();
67   return VReg;
68 }
69 
70 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
71                                           const MachineInstr *DefMI,
72                                           AAResults *aa) {
73   assert(DefMI && "Missing instruction");
74   ScannedRemattable = true;
75   if (!TII.isTriviallyReMaterializable(*DefMI, aa))
76     return false;
77   Remattable.insert(VNI);
78   return true;
79 }
80 
81 void LiveRangeEdit::scanRemattable(AAResults *aa) {
82   for (VNInfo *VNI : getParent().valnos) {
83     if (VNI->isUnused())
84       continue;
85     unsigned Original = VRM->getOriginal(getReg());
86     LiveInterval &OrigLI = LIS.getInterval(Original);
87     VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
88     if (!OrigVNI)
89       continue;
90     MachineInstr *DefMI = LIS.getInstructionFromIndex(OrigVNI->def);
91     if (!DefMI)
92       continue;
93     checkRematerializable(OrigVNI, DefMI, aa);
94   }
95   ScannedRemattable = true;
96 }
97 
98 bool LiveRangeEdit::anyRematerializable(AAResults *aa) {
99   if (!ScannedRemattable)
100     scanRemattable(aa);
101   return !Remattable.empty();
102 }
103 
104 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
105 /// OrigIdx are also available with the same value at UseIdx.
106 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
107                                        SlotIndex OrigIdx,
108                                        SlotIndex UseIdx) const {
109   OrigIdx = OrigIdx.getRegSlot(true);
110   UseIdx = std::max(UseIdx, UseIdx.getRegSlot(true));
111   for (const MachineOperand &MO : OrigMI->operands()) {
112     if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
113       continue;
114 
115     // We can't remat physreg uses, unless it is a constant or target wants
116     // to ignore this use.
117     if (Register::isPhysicalRegister(MO.getReg())) {
118       if (MRI.isConstantPhysReg(MO.getReg()) || TII.isIgnorableUse(MO))
119         continue;
120       return false;
121     }
122 
123     LiveInterval &li = LIS.getInterval(MO.getReg());
124     const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
125     if (!OVNI)
126       continue;
127 
128     // Don't allow rematerialization immediately after the original def.
129     // It would be incorrect if OrigMI redefines the register.
130     // See PR14098.
131     if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
132       return false;
133 
134     if (OVNI != li.getVNInfoAt(UseIdx))
135       return false;
136 
137     // Check that subrange is live at UseIdx.
138     if (MO.getSubReg()) {
139       const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
140       LaneBitmask LM = TRI->getSubRegIndexLaneMask(MO.getSubReg());
141       for (LiveInterval::SubRange &SR : li.subranges()) {
142         if ((SR.LaneMask & LM).none())
143           continue;
144         if (!SR.liveAt(UseIdx))
145           return false;
146         // Early exit if all used lanes are checked. No need to continue.
147         LM &= ~SR.LaneMask;
148         if (LM.none())
149           break;
150       }
151     }
152   }
153   return true;
154 }
155 
156 bool LiveRangeEdit::canRematerializeAt(Remat &RM, VNInfo *OrigVNI,
157                                        SlotIndex UseIdx, bool cheapAsAMove) {
158   assert(ScannedRemattable && "Call anyRematerializable first");
159 
160   // Use scanRemattable info.
161   if (!Remattable.count(OrigVNI))
162     return false;
163 
164   // No defining instruction provided.
165   SlotIndex DefIdx;
166   assert(RM.OrigMI && "No defining instruction for remattable value");
167   DefIdx = LIS.getInstructionIndex(*RM.OrigMI);
168 
169   // If only cheap remats were requested, bail out early.
170   if (cheapAsAMove && !TII.isAsCheapAsAMove(*RM.OrigMI))
171     return false;
172 
173   // Verify that all used registers are available with the same values.
174   if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
175     return false;
176 
177   return true;
178 }
179 
180 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
181                                          MachineBasicBlock::iterator MI,
182                                          unsigned DestReg,
183                                          const Remat &RM,
184                                          const TargetRegisterInfo &tri,
185                                          bool Late) {
186   assert(RM.OrigMI && "Invalid remat");
187   TII.reMaterialize(MBB, MI, DestReg, 0, *RM.OrigMI, tri);
188   // DestReg of the cloned instruction cannot be Dead. Set isDead of DestReg
189   // to false anyway in case the isDead flag of RM.OrigMI's dest register
190   // is true.
191   (*--MI).getOperand(0).setIsDead(false);
192   Rematted.insert(RM.ParentVNI);
193   return LIS.getSlotIndexes()->insertMachineInstrInMaps(*MI, Late).getRegSlot();
194 }
195 
196 void LiveRangeEdit::eraseVirtReg(Register Reg) {
197   if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
198     LIS.removeInterval(Reg);
199 }
200 
201 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
202                                SmallVectorImpl<MachineInstr*> &Dead) {
203   MachineInstr *DefMI = nullptr, *UseMI = nullptr;
204 
205   // Check that there is a single def and a single use.
206   for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg())) {
207     MachineInstr *MI = MO.getParent();
208     if (MO.isDef()) {
209       if (DefMI && DefMI != MI)
210         return false;
211       if (!MI->canFoldAsLoad())
212         return false;
213       DefMI = MI;
214     } else if (!MO.isUndef()) {
215       if (UseMI && UseMI != MI)
216         return false;
217       // FIXME: Targets don't know how to fold subreg uses.
218       if (MO.getSubReg())
219         return false;
220       UseMI = MI;
221     }
222   }
223   if (!DefMI || !UseMI)
224     return false;
225 
226   // Since we're moving the DefMI load, make sure we're not extending any live
227   // ranges.
228   if (!allUsesAvailableAt(DefMI, LIS.getInstructionIndex(*DefMI),
229                           LIS.getInstructionIndex(*UseMI)))
230     return false;
231 
232   // We also need to make sure it is safe to move the load.
233   // Assume there are stores between DefMI and UseMI.
234   bool SawStore = true;
235   if (!DefMI->isSafeToMove(nullptr, SawStore))
236     return false;
237 
238   LLVM_DEBUG(dbgs() << "Try to fold single def: " << *DefMI
239                     << "       into single use: " << *UseMI);
240 
241   SmallVector<unsigned, 8> Ops;
242   if (UseMI->readsWritesVirtualRegister(LI->reg(), &Ops).second)
243     return false;
244 
245   MachineInstr *FoldMI = TII.foldMemoryOperand(*UseMI, Ops, *DefMI, &LIS);
246   if (!FoldMI)
247     return false;
248   LLVM_DEBUG(dbgs() << "                folded: " << *FoldMI);
249   LIS.ReplaceMachineInstrInMaps(*UseMI, *FoldMI);
250   // Update the call site info.
251   if (UseMI->shouldUpdateCallSiteInfo())
252     UseMI->getMF()->moveCallSiteInfo(UseMI, FoldMI);
253   UseMI->eraseFromParent();
254   DefMI->addRegisterDead(LI->reg(), nullptr);
255   Dead.push_back(DefMI);
256   ++NumDCEFoldedLoads;
257   return true;
258 }
259 
260 bool LiveRangeEdit::useIsKill(const LiveInterval &LI,
261                               const MachineOperand &MO) const {
262   const MachineInstr &MI = *MO.getParent();
263   SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
264   if (LI.Query(Idx).isKill())
265     return true;
266   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
267   unsigned SubReg = MO.getSubReg();
268   LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
269   for (const LiveInterval::SubRange &S : LI.subranges()) {
270     if ((S.LaneMask & LaneMask).any() && S.Query(Idx).isKill())
271       return true;
272   }
273   return false;
274 }
275 
276 /// Find all live intervals that need to shrink, then remove the instruction.
277 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink,
278                                      AAResults *AA) {
279   assert(MI->allDefsAreDead() && "Def isn't really dead");
280   SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
281 
282   // Never delete a bundled instruction.
283   if (MI->isBundled()) {
284     return;
285   }
286   // Never delete inline asm.
287   if (MI->isInlineAsm()) {
288     LLVM_DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
289     return;
290   }
291 
292   // Use the same criteria as DeadMachineInstructionElim.
293   bool SawStore = false;
294   if (!MI->isSafeToMove(nullptr, SawStore)) {
295     LLVM_DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
296     return;
297   }
298 
299   LLVM_DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
300 
301   // Collect virtual registers to be erased after MI is gone.
302   SmallVector<unsigned, 8> RegsToErase;
303   bool ReadsPhysRegs = false;
304   bool isOrigDef = false;
305   unsigned Dest;
306   // Only optimize rematerialize case when the instruction has one def, since
307   // otherwise we could leave some dead defs in the code.  This case is
308   // extremely rare.
309   if (VRM && MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
310       MI->getDesc().getNumDefs() == 1) {
311     Dest = MI->getOperand(0).getReg();
312     unsigned Original = VRM->getOriginal(Dest);
313     LiveInterval &OrigLI = LIS.getInterval(Original);
314     VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
315     // The original live-range may have been shrunk to
316     // an empty live-range. It happens when it is dead, but
317     // we still keep it around to be able to rematerialize
318     // other values that depend on it.
319     if (OrigVNI)
320       isOrigDef = SlotIndex::isSameInstr(OrigVNI->def, Idx);
321   }
322 
323   bool HasLiveVRegUses = false;
324 
325   // Check for live intervals that may shrink
326   for (const MachineOperand &MO : MI->operands()) {
327     if (!MO.isReg())
328       continue;
329     Register Reg = MO.getReg();
330     if (!Register::isVirtualRegister(Reg)) {
331       // Check if MI reads any unreserved physregs.
332       if (Reg && MO.readsReg() && !MRI.isReserved(Reg))
333         ReadsPhysRegs = true;
334       else if (MO.isDef())
335         LIS.removePhysRegDefAt(Reg.asMCReg(), Idx);
336       continue;
337     }
338     LiveInterval &LI = LIS.getInterval(Reg);
339 
340     // Shrink read registers, unless it is likely to be expensive and
341     // unlikely to change anything. We typically don't want to shrink the
342     // PIC base register that has lots of uses everywhere.
343     // Always shrink COPY uses that probably come from live range splitting.
344     if ((MI->readsVirtualRegister(Reg) && (MI->isCopy() || MO.isDef())) ||
345         (MO.readsReg() && (MRI.hasOneNonDBGUse(Reg) || useIsKill(LI, MO))))
346       ToShrink.insert(&LI);
347     else if (MO.readsReg())
348       HasLiveVRegUses = true;
349 
350     // Remove defined value.
351     if (MO.isDef()) {
352       if (TheDelegate && LI.getVNInfoAt(Idx) != nullptr)
353         TheDelegate->LRE_WillShrinkVirtReg(LI.reg());
354       LIS.removeVRegDefAt(LI, Idx);
355       if (LI.empty())
356         RegsToErase.push_back(Reg);
357     }
358   }
359 
360   // Currently, we don't support DCE of physreg live ranges. If MI reads
361   // any unreserved physregs, don't erase the instruction, but turn it into
362   // a KILL instead. This way, the physreg live ranges don't end up
363   // dangling.
364   // FIXME: It would be better to have something like shrinkToUses() for
365   // physregs. That could potentially enable more DCE and it would free up
366   // the physreg. It would not happen often, though.
367   if (ReadsPhysRegs) {
368     MI->setDesc(TII.get(TargetOpcode::KILL));
369     // Remove all operands that aren't physregs.
370     for (unsigned i = MI->getNumOperands(); i; --i) {
371       const MachineOperand &MO = MI->getOperand(i-1);
372       if (MO.isReg() && Register::isPhysicalRegister(MO.getReg()))
373         continue;
374       MI->RemoveOperand(i-1);
375     }
376     LLVM_DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
377   } else {
378     // If the dest of MI is an original reg and MI is reMaterializable,
379     // don't delete the inst. Replace the dest with a new reg, and keep
380     // the inst for remat of other siblings. The inst is saved in
381     // LiveRangeEdit::DeadRemats and will be deleted after all the
382     // allocations of the func are done.
383     // However, immediately delete instructions which have unshrunk virtual
384     // register uses. That may provoke RA to split an interval at the KILL
385     // and later result in an invalid live segment end.
386     if (isOrigDef && DeadRemats && !HasLiveVRegUses &&
387         TII.isTriviallyReMaterializable(*MI, AA)) {
388       LiveInterval &NewLI = createEmptyIntervalFrom(Dest, false);
389       VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
390       NewLI.addSegment(LiveInterval::Segment(Idx, Idx.getDeadSlot(), VNI));
391       pop_back();
392       DeadRemats->insert(MI);
393       const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
394       MI->substituteRegister(Dest, NewLI.reg(), 0, TRI);
395       MI->getOperand(0).setIsDead(true);
396     } else {
397       if (TheDelegate)
398         TheDelegate->LRE_WillEraseInstruction(MI);
399       LIS.RemoveMachineInstrFromMaps(*MI);
400       MI->eraseFromParent();
401       ++NumDCEDeleted;
402     }
403   }
404 
405   // Erase any virtregs that are now empty and unused. There may be <undef>
406   // uses around. Keep the empty live range in that case.
407   for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
408     Register Reg = RegsToErase[i];
409     if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
410       ToShrink.remove(&LIS.getInterval(Reg));
411       eraseVirtReg(Reg);
412     }
413   }
414 }
415 
416 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr *> &Dead,
417                                       ArrayRef<Register> RegsBeingSpilled,
418                                       AAResults *AA) {
419   ToShrinkSet ToShrink;
420 
421   for (;;) {
422     // Erase all dead defs.
423     while (!Dead.empty())
424       eliminateDeadDef(Dead.pop_back_val(), ToShrink, AA);
425 
426     if (ToShrink.empty())
427       break;
428 
429     // Shrink just one live interval. Then delete new dead defs.
430     LiveInterval *LI = ToShrink.pop_back_val();
431     if (foldAsLoad(LI, Dead))
432       continue;
433     unsigned VReg = LI->reg();
434     if (TheDelegate)
435       TheDelegate->LRE_WillShrinkVirtReg(VReg);
436     if (!LIS.shrinkToUses(LI, &Dead))
437       continue;
438 
439     // Don't create new intervals for a register being spilled.
440     // The new intervals would have to be spilled anyway so its not worth it.
441     // Also they currently aren't spilled so creating them and not spilling
442     // them results in incorrect code.
443     if (llvm::is_contained(RegsBeingSpilled, VReg))
444       continue;
445 
446     // LI may have been separated, create new intervals.
447     LI->RenumberValues();
448     SmallVector<LiveInterval*, 8> SplitLIs;
449     LIS.splitSeparateComponents(*LI, SplitLIs);
450     if (!SplitLIs.empty())
451       ++NumFracRanges;
452 
453     Register Original = VRM ? VRM->getOriginal(VReg) : Register();
454     for (const LiveInterval *SplitLI : SplitLIs) {
455       // If LI is an original interval that hasn't been split yet, make the new
456       // intervals their own originals instead of referring to LI. The original
457       // interval must contain all the split products, and LI doesn't.
458       if (Original != VReg && Original != 0)
459         VRM->setIsSplitFromReg(SplitLI->reg(), Original);
460       if (TheDelegate)
461         TheDelegate->LRE_DidCloneVirtReg(SplitLI->reg(), VReg);
462     }
463   }
464 }
465 
466 // Keep track of new virtual registers created via
467 // MachineRegisterInfo::createVirtualRegister.
468 void
469 LiveRangeEdit::MRI_NoteNewVirtualRegister(Register VReg) {
470   if (VRM)
471     VRM->grow();
472 
473   NewRegs.push_back(VReg);
474 }
475 
476 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
477                                              VirtRegAuxInfo &VRAI) {
478   for (unsigned I = 0, Size = size(); I < Size; ++I) {
479     LiveInterval &LI = LIS.getInterval(get(I));
480     if (MRI.recomputeRegClass(LI.reg()))
481       LLVM_DEBUG({
482         const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
483         dbgs() << "Inflated " << printReg(LI.reg()) << " to "
484                << TRI->getRegClassName(MRI.getRegClass(LI.reg())) << '\n';
485       });
486     VRAI.calculateSpillWeightAndHint(LI);
487   }
488 }
489