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()))
98 LiveInterval &li = lis.getInterval(MO.getReg());
99 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
102 if (OVNI != li.getVNInfoAt(UseIdx))
108 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
111 LiveIntervals &lis) {
112 assert(scannedRemattable_ && "Call anyRematerializable first");
114 // Use scanRemattable info.
115 if (!remattable_.count(RM.ParentVNI))
118 // No defining instruction provided.
121 DefIdx = lis.getInstructionIndex(RM.OrigMI);
123 DefIdx = RM.ParentVNI->def;
124 RM.OrigMI = lis.getInstructionFromIndex(DefIdx);
125 assert(RM.OrigMI && "No defining instruction for remattable value");
128 // If only cheap remats were requested, bail out early.
129 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
132 // Verify that all used registers are available with the same values.
133 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx, lis))
139 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
140 MachineBasicBlock::iterator MI,
144 const TargetInstrInfo &tii,
145 const TargetRegisterInfo &tri,
147 assert(RM.OrigMI && "Invalid remat");
148 tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
149 rematted_.insert(RM.ParentVNI);
150 return lis.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
154 void LiveRangeEdit::eraseVirtReg(unsigned Reg, LiveIntervals &LIS) {
155 if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
156 LIS.removeInterval(Reg);
159 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
160 SmallVectorImpl<MachineInstr*> &Dead,
161 MachineRegisterInfo &MRI,
163 const TargetInstrInfo &TII) {
164 MachineInstr *DefMI = 0, *UseMI = 0;
166 // Check that there is a single def and a single use.
167 for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
168 E = MRI.reg_nodbg_end(); I != E; ++I) {
169 MachineOperand &MO = I.getOperand();
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 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
190 << " into single use: " << *UseMI);
192 SmallVector<unsigned, 8> Ops;
193 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
196 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
199 DEBUG(dbgs() << " folded: " << *FoldMI);
200 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
201 UseMI->eraseFromParent();
202 DefMI->addRegisterDead(LI->reg, 0);
203 Dead.push_back(DefMI);
208 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
209 LiveIntervals &LIS, VirtRegMap &VRM,
210 const TargetInstrInfo &TII,
211 ArrayRef<unsigned> RegsBeingSpilled) {
212 SetVector<LiveInterval*,
213 SmallVector<LiveInterval*, 8>,
214 SmallPtrSet<LiveInterval*, 8> > ToShrink;
215 MachineRegisterInfo &MRI = VRM.getRegInfo();
218 // Erase all dead defs.
219 while (!Dead.empty()) {
220 MachineInstr *MI = Dead.pop_back_val();
221 assert(MI->allDefsAreDead() && "Def isn't really dead");
222 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
224 // Never delete inline asm.
225 if (MI->isInlineAsm()) {
226 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
230 // Use the same criteria as DeadMachineInstructionElim.
231 bool SawStore = false;
232 if (!MI->isSafeToMove(&TII, 0, SawStore)) {
233 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
237 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
239 // Check for live intervals that may shrink
240 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
241 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
244 unsigned Reg = MOI->getReg();
245 if (!TargetRegisterInfo::isVirtualRegister(Reg))
247 LiveInterval &LI = LIS.getInterval(Reg);
249 // Shrink read registers, unless it is likely to be expensive and
250 // unlikely to change anything. We typically don't want to shrink the
251 // PIC base register that has lots of uses everywhere.
252 // Always shrink COPY uses that probably come from live range splitting.
253 if (MI->readsVirtualRegister(Reg) &&
254 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
256 ToShrink.insert(&LI);
258 // Remove defined value.
260 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
262 delegate_->LRE_WillShrinkVirtReg(LI.reg);
265 ToShrink.remove(&LI);
266 eraseVirtReg(Reg, LIS);
273 delegate_->LRE_WillEraseInstruction(MI);
274 LIS.RemoveMachineInstrFromMaps(MI);
275 MI->eraseFromParent();
279 if (ToShrink.empty())
282 // Shrink just one live interval. Then delete new dead defs.
283 LiveInterval *LI = ToShrink.back();
285 if (foldAsLoad(LI, Dead, MRI, LIS, TII))
288 delegate_->LRE_WillShrinkVirtReg(LI->reg);
289 if (!LIS.shrinkToUses(LI, &Dead))
292 // Don't create new intervals for a register being spilled.
293 // The new intervals would have to be spilled anyway so its not worth it.
294 // Also they currently aren't spilled so creating them and not spilling
295 // them results in incorrect code.
296 bool BeingSpilled = false;
297 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
298 if (LI->reg == RegsBeingSpilled[i]) {
304 if (BeingSpilled) continue;
307 // LI may have been separated, create new intervals.
308 LI->RenumberValues(LIS);
309 ConnectedVNInfoEqClasses ConEQ(LIS);
310 unsigned NumComp = ConEQ.Classify(LI);
314 bool IsOriginal = VRM.getOriginal(LI->reg) == LI->reg;
315 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
316 SmallVector<LiveInterval*, 8> Dups(1, LI);
317 for (unsigned i = 1; i != NumComp; ++i) {
318 Dups.push_back(&createFrom(LI->reg, LIS, VRM));
319 // If LI is an original interval that hasn't been split yet, make the new
320 // intervals their own originals instead of referring to LI. The original
321 // interval must contain all the split products, and LI doesn't.
323 VRM.setIsSplitFromReg(Dups.back()->reg, 0);
325 delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
327 ConEQ.Distribute(&Dups[0], MRI);
331 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
333 const MachineLoopInfo &Loops) {
334 VirtRegAuxInfo VRAI(MF, LIS, Loops);
335 MachineRegisterInfo &MRI = MF.getRegInfo();
336 for (iterator I = begin(), E = end(); I != E; ++I) {
337 LiveInterval &LI = **I;
338 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
339 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
340 << MRI.getRegClass(LI.reg)->getName() << '\n');
341 VRAI.CalculateWeightAndHint(LI);