1 //===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The LiveRangeEdit class represents changes done to a virtual register when it
11 // is spilled or split.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/LiveRangeEdit.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/CodeGen/CalcSpillWeights.h"
17 #include "llvm/CodeGen/LiveIntervals.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/TargetInstrInfo.h"
20 #include "llvm/CodeGen/VirtRegMap.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
26 #define DEBUG_TYPE "regalloc"
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");
32 void LiveRangeEdit::Delegate::anchor() { }
34 LiveInterval &LiveRangeEdit::createEmptyIntervalFrom(unsigned OldReg) {
35 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
37 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
39 LiveInterval &LI = LIS.createEmptyInterval(VReg);
40 if (Parent && !Parent->isSpillable())
41 LI.markNotSpillable();
42 // Create empty subranges if the OldReg's interval has them. Do not create
43 // the main range here---it will be constructed later after the subranges
44 // have been finalized.
45 LiveInterval &OldLI = LIS.getInterval(OldReg);
46 VNInfo::Allocator &Alloc = LIS.getVNInfoAllocator();
47 for (LiveInterval::SubRange &S : OldLI.subranges())
48 LI.createSubRange(Alloc, S.LaneMask);
52 unsigned LiveRangeEdit::createFrom(unsigned OldReg) {
53 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
55 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
57 // FIXME: Getting the interval here actually computes it.
58 // In theory, this may not be what we want, but in practice
59 // the createEmptyIntervalFrom API is used when this is not
60 // the case. Generally speaking we just want to annotate the
61 // LiveInterval when it gets created but we cannot do that at
63 if (Parent && !Parent->isSpillable())
64 LIS.getInterval(VReg).markNotSpillable();
68 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
69 const MachineInstr *DefMI,
71 assert(DefMI && "Missing instruction");
72 ScannedRemattable = true;
73 if (!TII.isTriviallyReMaterializable(*DefMI, aa))
75 Remattable.insert(VNI);
79 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
80 for (VNInfo *VNI : getParent().valnos) {
83 unsigned Original = VRM->getOriginal(getReg());
84 LiveInterval &OrigLI = LIS.getInterval(Original);
85 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
88 MachineInstr *DefMI = LIS.getInstructionFromIndex(OrigVNI->def);
91 checkRematerializable(OrigVNI, DefMI, aa);
93 ScannedRemattable = true;
96 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
97 if (!ScannedRemattable)
99 return !Remattable.empty();
102 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
103 /// OrigIdx are also available with the same value at UseIdx.
104 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
106 SlotIndex UseIdx) const {
107 OrigIdx = OrigIdx.getRegSlot(true);
108 UseIdx = UseIdx.getRegSlot(true);
109 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
110 const MachineOperand &MO = OrigMI->getOperand(i);
111 if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
114 // We can't remat physreg uses, unless it is a constant.
115 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
116 if (MRI.isConstantPhysReg(MO.getReg()))
121 LiveInterval &li = LIS.getInterval(MO.getReg());
122 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
126 // Don't allow rematerialization immediately after the original def.
127 // It would be incorrect if OrigMI redefines the register.
129 if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
132 if (OVNI != li.getVNInfoAt(UseIdx))
138 bool LiveRangeEdit::canRematerializeAt(Remat &RM, VNInfo *OrigVNI,
139 SlotIndex UseIdx, bool cheapAsAMove) {
140 assert(ScannedRemattable && "Call anyRematerializable first");
142 // Use scanRemattable info.
143 if (!Remattable.count(OrigVNI))
146 // No defining instruction provided.
148 assert(RM.OrigMI && "No defining instruction for remattable value");
149 DefIdx = LIS.getInstructionIndex(*RM.OrigMI);
151 // If only cheap remats were requested, bail out early.
152 if (cheapAsAMove && !TII.isAsCheapAsAMove(*RM.OrigMI))
155 // Verify that all used registers are available with the same values.
156 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
162 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
163 MachineBasicBlock::iterator MI,
166 const TargetRegisterInfo &tri,
168 assert(RM.OrigMI && "Invalid remat");
169 TII.reMaterialize(MBB, MI, DestReg, 0, *RM.OrigMI, tri);
170 // DestReg of the cloned instruction cannot be Dead. Set isDead of DestReg
171 // to false anyway in case the isDead flag of RM.OrigMI's dest register
173 (*--MI).getOperand(0).setIsDead(false);
174 Rematted.insert(RM.ParentVNI);
175 return LIS.getSlotIndexes()->insertMachineInstrInMaps(*MI, Late).getRegSlot();
178 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
179 if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
180 LIS.removeInterval(Reg);
183 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
184 SmallVectorImpl<MachineInstr*> &Dead) {
185 MachineInstr *DefMI = nullptr, *UseMI = nullptr;
187 // Check that there is a single def and a single use.
188 for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg)) {
189 MachineInstr *MI = MO.getParent();
191 if (DefMI && DefMI != MI)
193 if (!MI->canFoldAsLoad())
196 } else if (!MO.isUndef()) {
197 if (UseMI && UseMI != MI)
199 // FIXME: Targets don't know how to fold subreg uses.
205 if (!DefMI || !UseMI)
208 // Since we're moving the DefMI load, make sure we're not extending any live
210 if (!allUsesAvailableAt(DefMI, LIS.getInstructionIndex(*DefMI),
211 LIS.getInstructionIndex(*UseMI)))
214 // We also need to make sure it is safe to move the load.
215 // Assume there are stores between DefMI and UseMI.
216 bool SawStore = true;
217 if (!DefMI->isSafeToMove(nullptr, SawStore))
220 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
221 << " into single use: " << *UseMI);
223 SmallVector<unsigned, 8> Ops;
224 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
227 MachineInstr *FoldMI = TII.foldMemoryOperand(*UseMI, Ops, *DefMI, &LIS);
230 DEBUG(dbgs() << " folded: " << *FoldMI);
231 LIS.ReplaceMachineInstrInMaps(*UseMI, *FoldMI);
232 UseMI->eraseFromParent();
233 DefMI->addRegisterDead(LI->reg, nullptr);
234 Dead.push_back(DefMI);
239 bool LiveRangeEdit::useIsKill(const LiveInterval &LI,
240 const MachineOperand &MO) const {
241 const MachineInstr &MI = *MO.getParent();
242 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
243 if (LI.Query(Idx).isKill())
245 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
246 unsigned SubReg = MO.getSubReg();
247 LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
248 for (const LiveInterval::SubRange &S : LI.subranges()) {
249 if ((S.LaneMask & LaneMask).any() && S.Query(Idx).isKill())
255 /// Find all live intervals that need to shrink, then remove the instruction.
256 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink,
258 assert(MI->allDefsAreDead() && "Def isn't really dead");
259 SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
261 // Never delete a bundled instruction.
262 if (MI->isBundled()) {
265 // Never delete inline asm.
266 if (MI->isInlineAsm()) {
267 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
271 // Use the same criteria as DeadMachineInstructionElim.
272 bool SawStore = false;
273 if (!MI->isSafeToMove(nullptr, SawStore)) {
274 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
278 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
280 // Collect virtual registers to be erased after MI is gone.
281 SmallVector<unsigned, 8> RegsToErase;
282 bool ReadsPhysRegs = false;
283 bool isOrigDef = false;
285 // Only optimize rematerialize case when the instruction has one def, since
286 // otherwise we could leave some dead defs in the code. This case is
288 if (VRM && MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
289 MI->getDesc().getNumDefs() == 1) {
290 Dest = MI->getOperand(0).getReg();
291 unsigned Original = VRM->getOriginal(Dest);
292 LiveInterval &OrigLI = LIS.getInterval(Original);
293 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
294 // The original live-range may have been shrunk to
295 // an empty live-range. It happens when it is dead, but
296 // we still keep it around to be able to rematerialize
297 // other values that depend on it.
299 isOrigDef = SlotIndex::isSameInstr(OrigVNI->def, Idx);
302 // Check for live intervals that may shrink
303 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
304 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
307 unsigned Reg = MOI->getReg();
308 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
309 // Check if MI reads any unreserved physregs.
310 if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
311 ReadsPhysRegs = true;
312 else if (MOI->isDef())
313 LIS.removePhysRegDefAt(Reg, Idx);
316 LiveInterval &LI = LIS.getInterval(Reg);
318 // Shrink read registers, unless it is likely to be expensive and
319 // unlikely to change anything. We typically don't want to shrink the
320 // PIC base register that has lots of uses everywhere.
321 // Always shrink COPY uses that probably come from live range splitting.
322 if ((MI->readsVirtualRegister(Reg) && (MI->isCopy() || MOI->isDef())) ||
323 (MOI->readsReg() && (MRI.hasOneNonDBGUse(Reg) || useIsKill(LI, *MOI))))
324 ToShrink.insert(&LI);
326 // Remove defined value.
328 if (TheDelegate && LI.getVNInfoAt(Idx) != nullptr)
329 TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
330 LIS.removeVRegDefAt(LI, Idx);
332 RegsToErase.push_back(Reg);
336 // Currently, we don't support DCE of physreg live ranges. If MI reads
337 // any unreserved physregs, don't erase the instruction, but turn it into
338 // a KILL instead. This way, the physreg live ranges don't end up
340 // FIXME: It would be better to have something like shrinkToUses() for
341 // physregs. That could potentially enable more DCE and it would free up
342 // the physreg. It would not happen often, though.
344 MI->setDesc(TII.get(TargetOpcode::KILL));
345 // Remove all operands that aren't physregs.
346 for (unsigned i = MI->getNumOperands(); i; --i) {
347 const MachineOperand &MO = MI->getOperand(i-1);
348 if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
350 MI->RemoveOperand(i-1);
352 DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
354 // If the dest of MI is an original reg and MI is reMaterializable,
355 // don't delete the inst. Replace the dest with a new reg, and keep
356 // the inst for remat of other siblings. The inst is saved in
357 // LiveRangeEdit::DeadRemats and will be deleted after all the
358 // allocations of the func are done.
359 if (isOrigDef && DeadRemats && TII.isTriviallyReMaterializable(*MI, AA)) {
360 LiveInterval &NewLI = createEmptyIntervalFrom(Dest);
361 NewLI.removeEmptySubRanges();
362 VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
363 NewLI.addSegment(LiveInterval::Segment(Idx, Idx.getDeadSlot(), VNI));
366 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
367 MI->substituteRegister(Dest, NewLI.reg, 0, TRI);
368 MI->getOperand(0).setIsDead(true);
371 TheDelegate->LRE_WillEraseInstruction(MI);
372 LIS.RemoveMachineInstrFromMaps(*MI);
373 MI->eraseFromParent();
378 // Erase any virtregs that are now empty and unused. There may be <undef>
379 // uses around. Keep the empty live range in that case.
380 for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
381 unsigned Reg = RegsToErase[i];
382 if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
383 ToShrink.remove(&LIS.getInterval(Reg));
389 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr *> &Dead,
390 ArrayRef<unsigned> RegsBeingSpilled,
392 ToShrinkSet ToShrink;
395 // Erase all dead defs.
396 while (!Dead.empty())
397 eliminateDeadDef(Dead.pop_back_val(), ToShrink, AA);
399 if (ToShrink.empty())
402 // Shrink just one live interval. Then delete new dead defs.
403 LiveInterval *LI = ToShrink.back();
405 if (foldAsLoad(LI, Dead))
407 unsigned VReg = LI->reg;
409 TheDelegate->LRE_WillShrinkVirtReg(VReg);
410 if (!LIS.shrinkToUses(LI, &Dead))
413 // Don't create new intervals for a register being spilled.
414 // The new intervals would have to be spilled anyway so its not worth it.
415 // Also they currently aren't spilled so creating them and not spilling
416 // them results in incorrect code.
417 bool BeingSpilled = false;
418 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
419 if (VReg == RegsBeingSpilled[i]) {
425 if (BeingSpilled) continue;
427 // LI may have been separated, create new intervals.
428 LI->RenumberValues();
429 SmallVector<LiveInterval*, 8> SplitLIs;
430 LIS.splitSeparateComponents(*LI, SplitLIs);
431 if (!SplitLIs.empty())
434 unsigned Original = VRM ? VRM->getOriginal(VReg) : 0;
435 for (const LiveInterval *SplitLI : SplitLIs) {
436 // If LI is an original interval that hasn't been split yet, make the new
437 // intervals their own originals instead of referring to LI. The original
438 // interval must contain all the split products, and LI doesn't.
439 if (Original != VReg && Original != 0)
440 VRM->setIsSplitFromReg(SplitLI->reg, Original);
442 TheDelegate->LRE_DidCloneVirtReg(SplitLI->reg, VReg);
447 // Keep track of new virtual registers created via
448 // MachineRegisterInfo::createVirtualRegister.
450 LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
455 NewRegs.push_back(VReg);
459 LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
460 const MachineLoopInfo &Loops,
461 const MachineBlockFrequencyInfo &MBFI) {
462 VirtRegAuxInfo VRAI(MF, LIS, VRM, Loops, MBFI);
463 for (unsigned I = 0, Size = size(); I < Size; ++I) {
464 LiveInterval &LI = LIS.getInterval(get(I));
465 if (MRI.recomputeRegClass(LI.reg))
467 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
468 dbgs() << "Inflated " << printReg(LI.reg) << " to "
469 << TRI->getRegClassName(MRI.getRegClass(LI.reg)) << '\n';
471 VRAI.calculateSpillWeightAndHint(LI);