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/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"
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);
43 unsigned LiveRangeEdit::createFrom(unsigned OldReg) {
44 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
46 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
51 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
52 const MachineInstr *DefMI,
54 assert(DefMI && "Missing instruction");
55 ScannedRemattable = true;
56 if (!TII.isTriviallyReMaterializable(DefMI, aa))
58 Remattable.insert(VNI);
62 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
63 for (VNInfo *VNI : getParent().valnos) {
66 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
69 checkRematerializable(VNI, DefMI, aa);
71 ScannedRemattable = true;
74 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
75 if (!ScannedRemattable)
77 return !Remattable.empty();
80 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
81 /// OrigIdx are also available with the same value at UseIdx.
82 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
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())
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()))
99 LiveInterval &li = LIS.getInterval(MO.getReg());
100 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
104 // Don't allow rematerialization immediately after the original def.
105 // It would be incorrect if OrigMI redefines the register.
107 if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
110 if (OVNI != li.getVNInfoAt(UseIdx))
116 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
119 assert(ScannedRemattable && "Call anyRematerializable first");
121 // Use scanRemattable info.
122 if (!Remattable.count(RM.ParentVNI))
125 // No defining instruction provided.
128 DefIdx = LIS.getInstructionIndex(RM.OrigMI);
130 DefIdx = RM.ParentVNI->def;
131 RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
132 assert(RM.OrigMI && "No defining instruction for remattable value");
135 // If only cheap remats were requested, bail out early.
136 if (cheapAsAMove && !TII.isAsCheapAsAMove(RM.OrigMI))
139 // Verify that all used registers are available with the same values.
140 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
146 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
147 MachineBasicBlock::iterator MI,
150 const TargetRegisterInfo &tri,
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)
159 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
160 if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
161 LIS.removeInterval(Reg);
164 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
165 SmallVectorImpl<MachineInstr*> &Dead) {
166 MachineInstr *DefMI = nullptr, *UseMI = nullptr;
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();
172 if (DefMI && DefMI != MI)
174 if (!MI->canFoldAsLoad())
177 } else if (!MO.isUndef()) {
178 if (UseMI && UseMI != MI)
180 // FIXME: Targets don't know how to fold subreg uses.
186 if (!DefMI || !UseMI)
189 // Since we're moving the DefMI load, make sure we're not extending any live
191 if (!allUsesAvailableAt(DefMI,
192 LIS.getInstructionIndex(DefMI),
193 LIS.getInstructionIndex(UseMI)))
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))
202 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
203 << " into single use: " << *UseMI);
205 SmallVector<unsigned, 8> Ops;
206 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
209 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
212 DEBUG(dbgs() << " folded: " << *FoldMI);
213 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
214 UseMI->eraseFromParent();
215 DefMI->addRegisterDead(LI->reg, nullptr);
216 Dead.push_back(DefMI);
221 /// Find all live intervals that need to shrink, then remove the instruction.
222 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) {
223 assert(MI->allDefsAreDead() && "Def isn't really dead");
224 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
226 // Never delete a bundled instruction.
227 if (MI->isBundled()) {
230 // Never delete inline asm.
231 if (MI->isInlineAsm()) {
232 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
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);
243 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
245 // Collect virtual registers to be erased after MI is gone.
246 SmallVector<unsigned, 8> RegsToErase;
247 bool ReadsPhysRegs = false;
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) {
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 for (MCRegUnitIterator Units(Reg, MRI.getTargetRegisterInfo());
261 Units.isValid(); ++Units) {
262 if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) {
263 if (VNInfo *VNI = LR->getVNInfoAt(Idx))
264 LR->removeValNo(VNI);
270 LiveInterval &LI = LIS.getInterval(Reg);
272 // Shrink read registers, unless it is likely to be expensive and
273 // unlikely to change anything. We typically don't want to shrink the
274 // PIC base register that has lots of uses everywhere.
275 // Always shrink COPY uses that probably come from live range splitting.
276 if (MI->readsVirtualRegister(Reg) &&
277 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
278 LI.Query(Idx).isKill()))
279 ToShrink.insert(&LI);
281 // Remove defined value.
283 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
285 TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
288 RegsToErase.push_back(Reg);
290 // Also remove the value in subranges.
291 for (LiveInterval::SubRange &S : LI.subranges()) {
292 if (VNInfo *SVNI = S.getVNInfoAt(Idx))
295 LI.removeEmptySubRanges();
301 // Currently, we don't support DCE of physreg live ranges. If MI reads
302 // any unreserved physregs, don't erase the instruction, but turn it into
303 // a KILL instead. This way, the physreg live ranges don't end up
305 // FIXME: It would be better to have something like shrinkToUses() for
306 // physregs. That could potentially enable more DCE and it would free up
307 // the physreg. It would not happen often, though.
309 MI->setDesc(TII.get(TargetOpcode::KILL));
310 // Remove all operands that aren't physregs.
311 for (unsigned i = MI->getNumOperands(); i; --i) {
312 const MachineOperand &MO = MI->getOperand(i-1);
313 if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
315 MI->RemoveOperand(i-1);
317 DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
320 TheDelegate->LRE_WillEraseInstruction(MI);
321 LIS.RemoveMachineInstrFromMaps(MI);
322 MI->eraseFromParent();
326 // Erase any virtregs that are now empty and unused. There may be <undef>
327 // uses around. Keep the empty live range in that case.
328 for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
329 unsigned Reg = RegsToErase[i];
330 if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
331 ToShrink.remove(&LIS.getInterval(Reg));
337 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
338 ArrayRef<unsigned> RegsBeingSpilled) {
339 ToShrinkSet ToShrink;
342 // Erase all dead defs.
343 while (!Dead.empty())
344 eliminateDeadDef(Dead.pop_back_val(), ToShrink);
346 if (ToShrink.empty())
349 // Shrink just one live interval. Then delete new dead defs.
350 LiveInterval *LI = ToShrink.back();
352 if (foldAsLoad(LI, Dead))
355 TheDelegate->LRE_WillShrinkVirtReg(LI->reg);
356 if (!LIS.shrinkToUses(LI, &Dead))
359 // Don't create new intervals for a register being spilled.
360 // The new intervals would have to be spilled anyway so its not worth it.
361 // Also they currently aren't spilled so creating them and not spilling
362 // them results in incorrect code.
363 bool BeingSpilled = false;
364 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
365 if (LI->reg == RegsBeingSpilled[i]) {
371 if (BeingSpilled) continue;
373 // LI may have been separated, create new intervals.
374 LI->RenumberValues();
375 ConnectedVNInfoEqClasses ConEQ(LIS);
376 unsigned NumComp = ConEQ.Classify(LI);
380 bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg;
381 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
382 SmallVector<LiveInterval*, 8> Dups(1, LI);
383 for (unsigned i = 1; i != NumComp; ++i) {
384 Dups.push_back(&createEmptyIntervalFrom(LI->reg));
385 // If LI is an original interval that hasn't been split yet, make the new
386 // intervals their own originals instead of referring to LI. The original
387 // interval must contain all the split products, and LI doesn't.
389 VRM->setIsSplitFromReg(Dups.back()->reg, 0);
391 TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
393 ConEQ.Distribute(&Dups[0], MRI);
395 for (unsigned i = 0; i != NumComp; ++i)
396 dbgs() << '\t' << *Dups[i] << '\n';
401 // Keep track of new virtual registers created via
402 // MachineRegisterInfo::createVirtualRegister.
404 LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
409 NewRegs.push_back(VReg);
413 LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
414 const MachineLoopInfo &Loops,
415 const MachineBlockFrequencyInfo &MBFI) {
416 VirtRegAuxInfo VRAI(MF, LIS, Loops, MBFI);
417 for (unsigned I = 0, Size = size(); I < Size; ++I) {
418 LiveInterval &LI = LIS.getInterval(get(I));
419 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
421 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
422 dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
423 << TRI->getRegClassName(MRI.getRegClass(LI.reg)) << '\n';
425 VRAI.calculateSpillWeightAndHint(LI);