Refactor LiveRangeEdit::eliminateDeadDefs.
[oota-llvm.git] / lib / CodeGen / LiveRangeEdit.cpp
1 //===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The LiveRangeEdit class represents changes done to a virtual register when it
11 // is spilled or split.
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "regalloc"
15 #include "llvm/CodeGen/LiveRangeEdit.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/CodeGen/CalcSpillWeights.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/VirtRegMap.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24
25 using namespace llvm;
26
27 STATISTIC(NumDCEDeleted,     "Number of instructions deleted by DCE");
28 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
29 STATISTIC(NumFracRanges,     "Number of live ranges fractured by DCE");
30
31 void LiveRangeEdit::Delegate::anchor() { }
32
33 LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg) {
34   unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
35   if (VRM) {
36     VRM->grow();
37     VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
38   }
39   LiveInterval &LI = LIS.getOrCreateInterval(VReg);
40   NewRegs.push_back(&LI);
41   return LI;
42 }
43
44 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
45                                           const MachineInstr *DefMI,
46                                           AliasAnalysis *aa) {
47   assert(DefMI && "Missing instruction");
48   ScannedRemattable = true;
49   if (!TII.isTriviallyReMaterializable(DefMI, aa))
50     return false;
51   Remattable.insert(VNI);
52   return true;
53 }
54
55 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
56   for (LiveInterval::vni_iterator I = getParent().vni_begin(),
57        E = getParent().vni_end(); I != E; ++I) {
58     VNInfo *VNI = *I;
59     if (VNI->isUnused())
60       continue;
61     MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
62     if (!DefMI)
63       continue;
64     checkRematerializable(VNI, DefMI, aa);
65   }
66   ScannedRemattable = true;
67 }
68
69 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
70   if (!ScannedRemattable)
71     scanRemattable(aa);
72   return !Remattable.empty();
73 }
74
75 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
76 /// OrigIdx are also available with the same value at UseIdx.
77 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
78                                        SlotIndex OrigIdx,
79                                        SlotIndex UseIdx) const {
80   OrigIdx = OrigIdx.getRegSlot(true);
81   UseIdx = UseIdx.getRegSlot(true);
82   for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
83     const MachineOperand &MO = OrigMI->getOperand(i);
84     if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
85       continue;
86
87     // We can't remat physreg uses, unless it is a constant.
88     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
89       if (MRI.isConstantPhysReg(MO.getReg(), *OrigMI->getParent()->getParent()))
90         continue;
91       return false;
92     }
93
94     LiveInterval &li = LIS.getInterval(MO.getReg());
95     const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
96     if (!OVNI)
97       continue;
98
99     // Don't allow rematerialization immediately after the original def.
100     // It would be incorrect if OrigMI redefines the register.
101     // See PR14098.
102     if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
103       return false;
104
105     if (OVNI != li.getVNInfoAt(UseIdx))
106       return false;
107   }
108   return true;
109 }
110
111 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
112                                        SlotIndex UseIdx,
113                                        bool cheapAsAMove) {
114   assert(ScannedRemattable && "Call anyRematerializable first");
115
116   // Use scanRemattable info.
117   if (!Remattable.count(RM.ParentVNI))
118     return false;
119
120   // No defining instruction provided.
121   SlotIndex DefIdx;
122   if (RM.OrigMI)
123     DefIdx = LIS.getInstructionIndex(RM.OrigMI);
124   else {
125     DefIdx = RM.ParentVNI->def;
126     RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
127     assert(RM.OrigMI && "No defining instruction for remattable value");
128   }
129
130   // If only cheap remats were requested, bail out early.
131   if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
132     return false;
133
134   // Verify that all used registers are available with the same values.
135   if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
136     return false;
137
138   return true;
139 }
140
141 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
142                                          MachineBasicBlock::iterator MI,
143                                          unsigned DestReg,
144                                          const Remat &RM,
145                                          const TargetRegisterInfo &tri,
146                                          bool Late) {
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)
151            .getRegSlot();
152 }
153
154 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
155   if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
156     LIS.removeInterval(Reg);
157 }
158
159 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
160                                SmallVectorImpl<MachineInstr*> &Dead) {
161   MachineInstr *DefMI = 0, *UseMI = 0;
162
163   // Check that there is a single def and a single use.
164   for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
165        E = MRI.reg_nodbg_end(); I != E; ++I) {
166     MachineOperand &MO = I.getOperand();
167     MachineInstr *MI = MO.getParent();
168     if (MO.isDef()) {
169       if (DefMI && DefMI != MI)
170         return false;
171       if (!MI->canFoldAsLoad())
172         return false;
173       DefMI = MI;
174     } else if (!MO.isUndef()) {
175       if (UseMI && UseMI != MI)
176         return false;
177       // FIXME: Targets don't know how to fold subreg uses.
178       if (MO.getSubReg())
179         return false;
180       UseMI = MI;
181     }
182   }
183   if (!DefMI || !UseMI)
184     return false;
185
186   // Since we're moving the DefMI load, make sure we're not extending any live
187   // ranges.
188   if (!allUsesAvailableAt(DefMI,
189                           LIS.getInstructionIndex(DefMI),
190                           LIS.getInstructionIndex(UseMI)))
191     return false;
192
193   // We also need to make sure it is safe to move the load.
194   // Assume there are stores between DefMI and UseMI.
195   bool SawStore = true;
196   if (!DefMI->isSafeToMove(&TII, 0, SawStore))
197     return false;
198
199   DEBUG(dbgs() << "Try to fold single def: " << *DefMI
200                << "       into single use: " << *UseMI);
201
202   SmallVector<unsigned, 8> Ops;
203   if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
204     return false;
205
206   MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
207   if (!FoldMI)
208     return false;
209   DEBUG(dbgs() << "                folded: " << *FoldMI);
210   LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
211   UseMI->eraseFromParent();
212   DefMI->addRegisterDead(LI->reg, 0);
213   Dead.push_back(DefMI);
214   ++NumDCEFoldedLoads;
215   return true;
216 }
217
218 /// Find all live intervals that need to shrink, then remove the instruction.
219 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) {
220   assert(MI->allDefsAreDead() && "Def isn't really dead");
221   SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
222
223   // Never delete inline asm.
224   if (MI->isInlineAsm()) {
225     DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
226     return;
227   }
228
229   // Use the same criteria as DeadMachineInstructionElim.
230   bool SawStore = false;
231   if (!MI->isSafeToMove(&TII, 0, SawStore)) {
232     DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
233     return;
234   }
235
236   DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
237
238   // Collect virtual registers to be erased after MI is gone.
239   SmallVector<unsigned, 8> RegsToErase;
240   bool ReadsPhysRegs = false;
241
242   // Check for live intervals that may shrink
243   for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
244          MOE = MI->operands_end(); MOI != MOE; ++MOI) {
245     if (!MOI->isReg())
246       continue;
247     unsigned Reg = MOI->getReg();
248     if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
249       // Check if MI reads any unreserved physregs.
250       if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
251         ReadsPhysRegs = true;
252       continue;
253     }
254     LiveInterval &LI = LIS.getInterval(Reg);
255
256     // Shrink read registers, unless it is likely to be expensive and
257     // unlikely to change anything. We typically don't want to shrink the
258     // PIC base register that has lots of uses everywhere.
259     // Always shrink COPY uses that probably come from live range splitting.
260     if (MI->readsVirtualRegister(Reg) &&
261         (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
262          LI.killedAt(Idx)))
263       ToShrink.insert(&LI);
264
265     // Remove defined value.
266     if (MOI->isDef()) {
267       if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
268         if (TheDelegate)
269           TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
270         LI.removeValNo(VNI);
271         if (LI.empty())
272           RegsToErase.push_back(Reg);
273       }
274     }
275   }
276
277   // Currently, we don't support DCE of physreg live ranges. If MI reads
278   // any unreserved physregs, don't erase the instruction, but turn it into
279   // a KILL instead. This way, the physreg live ranges don't end up
280   // dangling.
281   // FIXME: It would be better to have something like shrinkToUses() for
282   // physregs. That could potentially enable more DCE and it would free up
283   // the physreg. It would not happen often, though.
284   if (ReadsPhysRegs) {
285     MI->setDesc(TII.get(TargetOpcode::KILL));
286     // Remove all operands that aren't physregs.
287     for (unsigned i = MI->getNumOperands(); i; --i) {
288       const MachineOperand &MO = MI->getOperand(i-1);
289       if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
290         continue;
291       MI->RemoveOperand(i-1);
292     }
293     DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
294   } else {
295     if (TheDelegate)
296       TheDelegate->LRE_WillEraseInstruction(MI);
297     LIS.RemoveMachineInstrFromMaps(MI);
298     MI->eraseFromParent();
299     ++NumDCEDeleted;
300   }
301
302   // Erase any virtregs that are now empty and unused. There may be <undef>
303   // uses around. Keep the empty live range in that case.
304   for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
305     unsigned Reg = RegsToErase[i];
306     if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
307       ToShrink.remove(&LIS.getInterval(Reg));
308       eraseVirtReg(Reg);
309     }
310   }
311 }
312
313 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
314                                       ArrayRef<unsigned> RegsBeingSpilled) {
315   ToShrinkSet ToShrink;
316
317   for (;;) {
318     // Erase all dead defs.
319     while (!Dead.empty())
320       eliminateDeadDef(Dead.pop_back_val(), ToShrink);
321
322     if (ToShrink.empty())
323       break;
324
325     // Shrink just one live interval. Then delete new dead defs.
326     LiveInterval *LI = ToShrink.back();
327     ToShrink.pop_back();
328     if (foldAsLoad(LI, Dead))
329       continue;
330     if (TheDelegate)
331       TheDelegate->LRE_WillShrinkVirtReg(LI->reg);
332     if (!LIS.shrinkToUses(LI, &Dead))
333       continue;
334
335     // Don't create new intervals for a register being spilled.
336     // The new intervals would have to be spilled anyway so its not worth it.
337     // Also they currently aren't spilled so creating them and not spilling
338     // them results in incorrect code.
339     bool BeingSpilled = false;
340     for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
341       if (LI->reg == RegsBeingSpilled[i]) {
342         BeingSpilled = true;
343         break;
344       }
345     }
346
347     if (BeingSpilled) continue;
348
349     // LI may have been separated, create new intervals.
350     LI->RenumberValues(LIS);
351     ConnectedVNInfoEqClasses ConEQ(LIS);
352     unsigned NumComp = ConEQ.Classify(LI);
353     if (NumComp <= 1)
354       continue;
355     ++NumFracRanges;
356     bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg;
357     DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
358     SmallVector<LiveInterval*, 8> Dups(1, LI);
359     for (unsigned i = 1; i != NumComp; ++i) {
360       Dups.push_back(&createFrom(LI->reg));
361       // If LI is an original interval that hasn't been split yet, make the new
362       // intervals their own originals instead of referring to LI. The original
363       // interval must contain all the split products, and LI doesn't.
364       if (IsOriginal)
365         VRM->setIsSplitFromReg(Dups.back()->reg, 0);
366       if (TheDelegate)
367         TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
368     }
369     ConEQ.Distribute(&Dups[0], MRI);
370     DEBUG({
371       for (unsigned i = 0; i != NumComp; ++i)
372         dbgs() << '\t' << *Dups[i] << '\n';
373     });
374   }
375 }
376
377 void
378 LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
379                                         const MachineLoopInfo &Loops,
380                                         const MachineBlockFrequencyInfo &MBFI) {
381   VirtRegAuxInfo VRAI(MF, LIS, Loops, MBFI);
382   for (iterator I = begin(), E = end(); I != E; ++I) {
383     LiveInterval &LI = **I;
384     if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
385       DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
386                    << MRI.getRegClass(LI.reg)->getName() << '\n');
387     VRAI.CalculateWeightAndHint(LI);
388   }
389 }