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