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) {
35 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
37 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
38 LiveInterval &LI = LIS.getOrCreateInterval(VReg);
39 newRegs_.push_back(&LI);
43 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
44 const MachineInstr *DefMI,
46 assert(DefMI && "Missing instruction");
47 scannedRemattable_ = true;
48 if (!TII.isTriviallyReMaterializable(DefMI, aa))
50 remattable_.insert(VNI);
54 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
55 for (LiveInterval::vni_iterator I = parent_.vni_begin(),
56 E = parent_.vni_end(); I != E; ++I) {
60 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
63 checkRematerializable(VNI, DefMI, aa);
65 scannedRemattable_ = true;
68 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
69 if (!scannedRemattable_)
71 return !remattable_.empty();
74 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
75 /// OrigIdx are also available with the same value at UseIdx.
76 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
79 OrigIdx = OrigIdx.getRegSlot(true);
80 UseIdx = UseIdx.getRegSlot(true);
81 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
82 const MachineOperand &MO = OrigMI->getOperand(i);
83 if (!MO.isReg() || !MO.getReg() || MO.isDef())
85 // Reserved registers are OK.
86 if (MO.isUndef() || !LIS.hasInterval(MO.getReg()))
89 LiveInterval &li = LIS.getInterval(MO.getReg());
90 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
93 if (OVNI != li.getVNInfoAt(UseIdx))
99 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
102 assert(scannedRemattable_ && "Call anyRematerializable first");
104 // Use scanRemattable info.
105 if (!remattable_.count(RM.ParentVNI))
108 // No defining instruction provided.
111 DefIdx = LIS.getInstructionIndex(RM.OrigMI);
113 DefIdx = RM.ParentVNI->def;
114 RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
115 assert(RM.OrigMI && "No defining instruction for remattable value");
118 // If only cheap remats were requested, bail out early.
119 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
122 // Verify that all used registers are available with the same values.
123 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
129 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
130 MachineBasicBlock::iterator MI,
133 const TargetRegisterInfo &tri,
135 assert(RM.OrigMI && "Invalid remat");
136 TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
137 rematted_.insert(RM.ParentVNI);
138 return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
142 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
143 if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
144 LIS.removeInterval(Reg);
147 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
148 SmallVectorImpl<MachineInstr*> &Dead) {
149 MachineInstr *DefMI = 0, *UseMI = 0;
151 // Check that there is a single def and a single use.
152 for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
153 E = MRI.reg_nodbg_end(); I != E; ++I) {
154 MachineOperand &MO = I.getOperand();
155 MachineInstr *MI = MO.getParent();
157 if (DefMI && DefMI != MI)
159 if (!MI->canFoldAsLoad())
162 } else if (!MO.isUndef()) {
163 if (UseMI && UseMI != MI)
165 // FIXME: Targets don't know how to fold subreg uses.
171 if (!DefMI || !UseMI)
174 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
175 << " into single use: " << *UseMI);
177 SmallVector<unsigned, 8> Ops;
178 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
181 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
184 DEBUG(dbgs() << " folded: " << *FoldMI);
185 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
186 UseMI->eraseFromParent();
187 DefMI->addRegisterDead(LI->reg, 0);
188 Dead.push_back(DefMI);
193 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
194 ArrayRef<unsigned> RegsBeingSpilled) {
195 SetVector<LiveInterval*,
196 SmallVector<LiveInterval*, 8>,
197 SmallPtrSet<LiveInterval*, 8> > ToShrink;
200 // Erase all dead defs.
201 while (!Dead.empty()) {
202 MachineInstr *MI = Dead.pop_back_val();
203 assert(MI->allDefsAreDead() && "Def isn't really dead");
204 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
206 // Never delete inline asm.
207 if (MI->isInlineAsm()) {
208 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
212 // Use the same criteria as DeadMachineInstructionElim.
213 bool SawStore = false;
214 if (!MI->isSafeToMove(&TII, 0, SawStore)) {
215 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
219 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
221 // Check for live intervals that may shrink
222 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
223 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
226 unsigned Reg = MOI->getReg();
227 if (!TargetRegisterInfo::isVirtualRegister(Reg))
229 LiveInterval &LI = LIS.getInterval(Reg);
231 // Shrink read registers, unless it is likely to be expensive and
232 // unlikely to change anything. We typically don't want to shrink the
233 // PIC base register that has lots of uses everywhere.
234 // Always shrink COPY uses that probably come from live range splitting.
235 if (MI->readsVirtualRegister(Reg) &&
236 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
238 ToShrink.insert(&LI);
240 // Remove defined value.
242 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
244 delegate_->LRE_WillShrinkVirtReg(LI.reg);
247 ToShrink.remove(&LI);
255 delegate_->LRE_WillEraseInstruction(MI);
256 LIS.RemoveMachineInstrFromMaps(MI);
257 MI->eraseFromParent();
261 if (ToShrink.empty())
264 // Shrink just one live interval. Then delete new dead defs.
265 LiveInterval *LI = ToShrink.back();
267 if (foldAsLoad(LI, Dead))
270 delegate_->LRE_WillShrinkVirtReg(LI->reg);
271 if (!LIS.shrinkToUses(LI, &Dead))
276 // Don't create new intervals for a register being spilled.
277 // The new intervals would have to be spilled anyway so its not worth it.
278 // Also they currently aren't spilled so creating them and not spilling
279 // them results in incorrect code.
280 bool BeingSpilled = false;
281 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
282 if (LI->reg == RegsBeingSpilled[i]) {
288 if (BeingSpilled) continue;
291 // LI may have been separated, create new intervals.
292 LI->RenumberValues(LIS);
293 ConnectedVNInfoEqClasses ConEQ(LIS);
294 unsigned NumComp = ConEQ.Classify(LI);
298 bool IsOriginal = VRM->getOriginal(LI->reg) == LI->reg;
299 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
300 SmallVector<LiveInterval*, 8> Dups(1, LI);
301 for (unsigned i = 1; i != NumComp; ++i) {
302 Dups.push_back(&createFrom(LI->reg));
303 // If LI is an original interval that hasn't been split yet, make the new
304 // intervals their own originals instead of referring to LI. The original
305 // interval must contain all the split products, and LI doesn't.
307 VRM->setIsSplitFromReg(Dups.back()->reg, 0);
309 delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
311 ConEQ.Distribute(&Dups[0], MRI);
315 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
316 const MachineLoopInfo &Loops) {
317 VirtRegAuxInfo VRAI(MF, LIS, Loops);
318 for (iterator I = begin(), E = end(); I != E; ++I) {
319 LiveInterval &LI = **I;
320 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
321 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
322 << MRI.getRegClass(LI.reg)->getName() << '\n');
323 VRAI.CalculateWeightAndHint(LI);