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 #define DEBUG_TYPE "regalloc"
15 #include "LiveRangeEdit.h"
16 #include "VirtRegMap.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/CalcSpillWeights.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
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::createFrom(unsigned OldReg,
37 MachineRegisterInfo &MRI = VRM.getRegInfo();
38 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
40 VRM.setIsSplitFromReg(VReg, VRM.getOriginal(OldReg));
41 LiveInterval &LI = LIS.getOrCreateInterval(VReg);
42 newRegs_.push_back(&LI);
46 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
47 const MachineInstr *DefMI,
48 const TargetInstrInfo &tii,
50 assert(DefMI && "Missing instruction");
51 scannedRemattable_ = true;
52 if (!tii.isTriviallyReMaterializable(DefMI, aa))
54 remattable_.insert(VNI);
58 void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
59 const TargetInstrInfo &tii,
61 for (LiveInterval::vni_iterator I = parent_.vni_begin(),
62 E = parent_.vni_end(); I != E; ++I) {
66 MachineInstr *DefMI = lis.getInstructionFromIndex(VNI->def);
69 checkRematerializable(VNI, DefMI, tii, aa);
71 scannedRemattable_ = true;
74 bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
75 const TargetInstrInfo &tii,
77 if (!scannedRemattable_)
78 scanRemattable(lis, tii, aa);
79 return !remattable_.empty();
82 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
83 /// OrigIdx are also available with the same value at UseIdx.
84 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
88 OrigIdx = OrigIdx.getRegSlot(true);
89 UseIdx = UseIdx.getRegSlot(true);
90 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
91 const MachineOperand &MO = OrigMI->getOperand(i);
92 if (!MO.isReg() || !MO.getReg() || MO.isDef())
94 // Reserved registers are OK.
95 if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
97 // We cannot depend on virtual registers in uselessRegs_.
99 for (unsigned ui = 0, ue = uselessRegs_->size(); ui != ue; ++ui)
100 if ((*uselessRegs_)[ui]->reg == MO.getReg())
103 LiveInterval &li = lis.getInterval(MO.getReg());
104 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
107 if (OVNI != li.getVNInfoAt(UseIdx))
113 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
116 LiveIntervals &lis) {
117 assert(scannedRemattable_ && "Call anyRematerializable first");
119 // Use scanRemattable info.
120 if (!remattable_.count(RM.ParentVNI))
123 // No defining instruction provided.
126 DefIdx = lis.getInstructionIndex(RM.OrigMI);
128 DefIdx = RM.ParentVNI->def;
129 RM.OrigMI = lis.getInstructionFromIndex(DefIdx);
130 assert(RM.OrigMI && "No defining instruction for remattable value");
133 // If only cheap remats were requested, bail out early.
134 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
137 // Verify that all used registers are available with the same values.
138 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx, lis))
144 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
145 MachineBasicBlock::iterator MI,
149 const TargetInstrInfo &tii,
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, LiveIntervals &LIS) {
160 if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
161 LIS.removeInterval(Reg);
164 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
165 SmallVectorImpl<MachineInstr*> &Dead,
166 MachineRegisterInfo &MRI,
168 const TargetInstrInfo &TII) {
169 MachineInstr *DefMI = 0, *UseMI = 0;
171 // Check that there is a single def and a single use.
172 for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
173 E = MRI.reg_nodbg_end(); I != E; ++I) {
174 MachineOperand &MO = I.getOperand();
175 MachineInstr *MI = MO.getParent();
177 if (DefMI && DefMI != MI)
179 if (!MI->canFoldAsLoad())
182 } else if (!MO.isUndef()) {
183 if (UseMI && UseMI != MI)
185 // FIXME: Targets don't know how to fold subreg uses.
191 if (!DefMI || !UseMI)
194 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
195 << " into single use: " << *UseMI);
197 SmallVector<unsigned, 8> Ops;
198 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
201 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
204 DEBUG(dbgs() << " folded: " << *FoldMI);
205 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
206 UseMI->eraseFromParent();
207 DefMI->addRegisterDead(LI->reg, 0);
208 Dead.push_back(DefMI);
213 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
214 LiveIntervals &LIS, VirtRegMap &VRM,
215 const TargetInstrInfo &TII,
216 ArrayRef<unsigned> RegsBeingSpilled) {
217 SetVector<LiveInterval*,
218 SmallVector<LiveInterval*, 8>,
219 SmallPtrSet<LiveInterval*, 8> > ToShrink;
220 MachineRegisterInfo &MRI = VRM.getRegInfo();
223 // Erase all dead defs.
224 while (!Dead.empty()) {
225 MachineInstr *MI = Dead.pop_back_val();
226 assert(MI->allDefsAreDead() && "Def isn't really dead");
227 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
229 // Never delete inline asm.
230 if (MI->isInlineAsm()) {
231 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
235 // Use the same criteria as DeadMachineInstructionElim.
236 bool SawStore = false;
237 if (!MI->isSafeToMove(&TII, 0, SawStore)) {
238 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
242 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
244 // Check for live intervals that may shrink
245 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
246 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
249 unsigned Reg = MOI->getReg();
250 if (!TargetRegisterInfo::isVirtualRegister(Reg))
252 LiveInterval &LI = LIS.getInterval(Reg);
254 // Shrink read registers, unless it is likely to be expensive and
255 // unlikely to change anything. We typically don't want to shrink the
256 // PIC base register that has lots of uses everywhere.
257 // Always shrink COPY uses that probably come from live range splitting.
258 if (MI->readsVirtualRegister(Reg) &&
259 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
261 ToShrink.insert(&LI);
263 // Remove defined value.
265 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
267 delegate_->LRE_WillShrinkVirtReg(LI.reg);
270 ToShrink.remove(&LI);
271 eraseVirtReg(Reg, LIS);
278 delegate_->LRE_WillEraseInstruction(MI);
279 LIS.RemoveMachineInstrFromMaps(MI);
280 MI->eraseFromParent();
284 if (ToShrink.empty())
287 // Shrink just one live interval. Then delete new dead defs.
288 LiveInterval *LI = ToShrink.back();
290 if (foldAsLoad(LI, Dead, MRI, LIS, TII))
293 delegate_->LRE_WillShrinkVirtReg(LI->reg);
294 if (!LIS.shrinkToUses(LI, &Dead))
297 // Don't create new intervals for a register being spilled.
298 // The new intervals would have to be spilled anyway so its not worth it.
299 // Also they currently aren't spilled so creating them and not spilling
300 // them results in incorrect code.
301 bool BeingSpilled = false;
302 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
303 if (LI->reg == RegsBeingSpilled[i]) {
309 if (BeingSpilled) continue;
312 // LI may have been separated, create new intervals.
313 LI->RenumberValues(LIS);
314 ConnectedVNInfoEqClasses ConEQ(LIS);
315 unsigned NumComp = ConEQ.Classify(LI);
319 bool IsOriginal = VRM.getOriginal(LI->reg) == LI->reg;
320 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
321 SmallVector<LiveInterval*, 8> Dups(1, LI);
322 for (unsigned i = 1; i != NumComp; ++i) {
323 Dups.push_back(&createFrom(LI->reg, LIS, VRM));
324 // If LI is an original interval that hasn't been split yet, make the new
325 // intervals their own originals instead of referring to LI. The original
326 // interval must contain all the split products, and LI doesn't.
328 VRM.setIsSplitFromReg(Dups.back()->reg, 0);
330 delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
332 ConEQ.Distribute(&Dups[0], MRI);
336 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
338 const MachineLoopInfo &Loops) {
339 VirtRegAuxInfo VRAI(MF, LIS, Loops);
340 MachineRegisterInfo &MRI = MF.getRegInfo();
341 for (iterator I = begin(), E = end(); I != E; ++I) {
342 LiveInterval &LI = **I;
343 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
344 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
345 << MRI.getRegClass(LI.reg)->getName() << '\n');
346 VRAI.CalculateWeightAndHint(LI);