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 "VirtRegMap.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/CalcSpillWeights.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/LiveRangeEdit.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));
38 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
40 LiveInterval &LI = LIS.getOrCreateInterval(VReg);
41 NewRegs.push_back(&LI);
45 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
46 const MachineInstr *DefMI,
48 assert(DefMI && "Missing instruction");
49 ScannedRemattable = true;
50 if (!TII.isTriviallyReMaterializable(DefMI, aa))
52 Remattable.insert(VNI);
56 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
57 for (LiveInterval::vni_iterator I = getParent().vni_begin(),
58 E = getParent().vni_end(); I != E; ++I) {
62 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
65 checkRematerializable(VNI, DefMI, aa);
67 ScannedRemattable = true;
70 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
71 if (!ScannedRemattable)
73 return !Remattable.empty();
76 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
77 /// OrigIdx are also available with the same value at UseIdx.
78 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
81 OrigIdx = OrigIdx.getRegSlot(true);
82 UseIdx = UseIdx.getRegSlot(true);
83 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
84 const MachineOperand &MO = OrigMI->getOperand(i);
85 if (!MO.isReg() || !MO.getReg() || MO.isDef())
87 // Reserved registers are OK.
88 if (MO.isUndef() || !LIS.hasInterval(MO.getReg()))
91 LiveInterval &li = LIS.getInterval(MO.getReg());
92 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
95 if (OVNI != li.getVNInfoAt(UseIdx))
101 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
104 assert(ScannedRemattable && "Call anyRematerializable first");
106 // Use scanRemattable info.
107 if (!Remattable.count(RM.ParentVNI))
110 // No defining instruction provided.
113 DefIdx = LIS.getInstructionIndex(RM.OrigMI);
115 DefIdx = RM.ParentVNI->def;
116 RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
117 assert(RM.OrigMI && "No defining instruction for remattable value");
120 // If only cheap remats were requested, bail out early.
121 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
124 // Verify that all used registers are available with the same values.
125 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
131 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
132 MachineBasicBlock::iterator MI,
135 const TargetRegisterInfo &tri,
137 assert(RM.OrigMI && "Invalid remat");
138 TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
139 Rematted.insert(RM.ParentVNI);
140 return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
144 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
145 if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
146 LIS.removeInterval(Reg);
149 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
150 SmallVectorImpl<MachineInstr*> &Dead) {
151 MachineInstr *DefMI = 0, *UseMI = 0;
153 // Check that there is a single def and a single use.
154 for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
155 E = MRI.reg_nodbg_end(); I != E; ++I) {
156 MachineOperand &MO = I.getOperand();
157 MachineInstr *MI = MO.getParent();
159 if (DefMI && DefMI != MI)
161 if (!MI->canFoldAsLoad())
164 } else if (!MO.isUndef()) {
165 if (UseMI && UseMI != MI)
167 // FIXME: Targets don't know how to fold subreg uses.
173 if (!DefMI || !UseMI)
176 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
177 << " into single use: " << *UseMI);
179 SmallVector<unsigned, 8> Ops;
180 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
183 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
186 DEBUG(dbgs() << " folded: " << *FoldMI);
187 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
188 UseMI->eraseFromParent();
189 DefMI->addRegisterDead(LI->reg, 0);
190 Dead.push_back(DefMI);
195 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
196 ArrayRef<unsigned> RegsBeingSpilled) {
197 SetVector<LiveInterval*,
198 SmallVector<LiveInterval*, 8>,
199 SmallPtrSet<LiveInterval*, 8> > ToShrink;
202 // Erase all dead defs.
203 while (!Dead.empty()) {
204 MachineInstr *MI = Dead.pop_back_val();
205 assert(MI->allDefsAreDead() && "Def isn't really dead");
206 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
208 // Never delete inline asm.
209 if (MI->isInlineAsm()) {
210 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
214 // Use the same criteria as DeadMachineInstructionElim.
215 bool SawStore = false;
216 if (!MI->isSafeToMove(&TII, 0, SawStore)) {
217 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
221 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
223 // Collect virtual registers to be erased after MI is gone.
224 SmallVector<unsigned, 8> RegsToErase;
226 // Check for live intervals that may shrink
227 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
228 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
231 unsigned Reg = MOI->getReg();
232 if (!TargetRegisterInfo::isVirtualRegister(Reg))
234 LiveInterval &LI = LIS.getInterval(Reg);
236 // Shrink read registers, unless it is likely to be expensive and
237 // unlikely to change anything. We typically don't want to shrink the
238 // PIC base register that has lots of uses everywhere.
239 // Always shrink COPY uses that probably come from live range splitting.
240 if (MI->readsVirtualRegister(Reg) &&
241 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
243 ToShrink.insert(&LI);
245 // Remove defined value.
247 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
249 TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
252 RegsToErase.push_back(Reg);
258 TheDelegate->LRE_WillEraseInstruction(MI);
259 LIS.RemoveMachineInstrFromMaps(MI);
260 MI->eraseFromParent();
263 // Erase any virtregs that are now empty and unused. There may be <undef>
264 // uses around. Keep the empty live range in that case.
265 for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
266 unsigned Reg = RegsToErase[i];
267 if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
268 ToShrink.remove(&LIS.getInterval(Reg));
274 if (ToShrink.empty())
277 // Shrink just one live interval. Then delete new dead defs.
278 LiveInterval *LI = ToShrink.back();
280 if (foldAsLoad(LI, Dead))
283 TheDelegate->LRE_WillShrinkVirtReg(LI->reg);
284 if (!LIS.shrinkToUses(LI, &Dead))
287 // Don't create new intervals for a register being spilled.
288 // The new intervals would have to be spilled anyway so its not worth it.
289 // Also they currently aren't spilled so creating them and not spilling
290 // them results in incorrect code.
291 bool BeingSpilled = false;
292 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
293 if (LI->reg == RegsBeingSpilled[i]) {
299 if (BeingSpilled) continue;
301 // LI may have been separated, create new intervals.
302 LI->RenumberValues(LIS);
303 ConnectedVNInfoEqClasses ConEQ(LIS);
304 unsigned NumComp = ConEQ.Classify(LI);
308 bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg;
309 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
310 SmallVector<LiveInterval*, 8> Dups(1, LI);
311 for (unsigned i = 1; i != NumComp; ++i) {
312 Dups.push_back(&createFrom(LI->reg));
313 // If LI is an original interval that hasn't been split yet, make the new
314 // intervals their own originals instead of referring to LI. The original
315 // interval must contain all the split products, and LI doesn't.
317 VRM->setIsSplitFromReg(Dups.back()->reg, 0);
319 TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
321 ConEQ.Distribute(&Dups[0], MRI);
323 for (unsigned i = 0; i != NumComp; ++i)
324 dbgs() << '\t' << *Dups[i] << '\n';
329 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
330 const MachineLoopInfo &Loops) {
331 VirtRegAuxInfo VRAI(MF, LIS, Loops);
332 for (iterator I = begin(), E = end(); I != E; ++I) {
333 LiveInterval &LI = **I;
334 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
335 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
336 << MRI.getRegClass(LI.reg)->getName() << '\n');
337 VRAI.CalculateWeightAndHint(LI);