Post-ra LICM should take care not to hoist an instruction that would clobber a
[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 "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"
25
26 using namespace llvm;
27
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");
31
32 void LiveRangeEdit::Delegate::anchor() { }
33
34 LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg,
35                                         LiveIntervals &LIS,
36                                         VirtRegMap &VRM) {
37   MachineRegisterInfo &MRI = VRM.getRegInfo();
38   unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
39   VRM.grow();
40   VRM.setIsSplitFromReg(VReg, VRM.getOriginal(OldReg));
41   LiveInterval &LI = LIS.getOrCreateInterval(VReg);
42   newRegs_.push_back(&LI);
43   return LI;
44 }
45
46 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
47                                           const MachineInstr *DefMI,
48                                           const TargetInstrInfo &tii,
49                                           AliasAnalysis *aa) {
50   assert(DefMI && "Missing instruction");
51   scannedRemattable_ = true;
52   if (!tii.isTriviallyReMaterializable(DefMI, aa))
53     return false;
54   remattable_.insert(VNI);
55   return true;
56 }
57
58 void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
59                                    const TargetInstrInfo &tii,
60                                    AliasAnalysis *aa) {
61   for (LiveInterval::vni_iterator I = parent_.vni_begin(),
62        E = parent_.vni_end(); I != E; ++I) {
63     VNInfo *VNI = *I;
64     if (VNI->isUnused())
65       continue;
66     MachineInstr *DefMI = lis.getInstructionFromIndex(VNI->def);
67     if (!DefMI)
68       continue;
69     checkRematerializable(VNI, DefMI, tii, aa);
70   }
71   scannedRemattable_ = true;
72 }
73
74 bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
75                                         const TargetInstrInfo &tii,
76                                         AliasAnalysis *aa) {
77   if (!scannedRemattable_)
78     scanRemattable(lis, tii, aa);
79   return !remattable_.empty();
80 }
81
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,
85                                        SlotIndex OrigIdx,
86                                        SlotIndex UseIdx,
87                                        LiveIntervals &lis) {
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())
93       continue;
94     // Reserved registers are OK.
95     if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
96       continue;
97
98     LiveInterval &li = lis.getInterval(MO.getReg());
99     const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
100     if (!OVNI)
101       continue;
102     if (OVNI != li.getVNInfoAt(UseIdx))
103       return false;
104   }
105   return true;
106 }
107
108 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
109                                        SlotIndex UseIdx,
110                                        bool cheapAsAMove,
111                                        LiveIntervals &lis) {
112   assert(scannedRemattable_ && "Call anyRematerializable first");
113
114   // Use scanRemattable info.
115   if (!remattable_.count(RM.ParentVNI))
116     return false;
117
118   // No defining instruction provided.
119   SlotIndex DefIdx;
120   if (RM.OrigMI)
121     DefIdx = lis.getInstructionIndex(RM.OrigMI);
122   else {
123     DefIdx = RM.ParentVNI->def;
124     RM.OrigMI = lis.getInstructionFromIndex(DefIdx);
125     assert(RM.OrigMI && "No defining instruction for remattable value");
126   }
127
128   // If only cheap remats were requested, bail out early.
129   if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
130     return false;
131
132   // Verify that all used registers are available with the same values.
133   if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx, lis))
134     return false;
135
136   return true;
137 }
138
139 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
140                                          MachineBasicBlock::iterator MI,
141                                          unsigned DestReg,
142                                          const Remat &RM,
143                                          LiveIntervals &lis,
144                                          const TargetInstrInfo &tii,
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, LiveIntervals &LIS) {
155   if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
156     LIS.removeInterval(Reg);
157 }
158
159 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
160                                SmallVectorImpl<MachineInstr*> &Dead,
161                                MachineRegisterInfo &MRI,
162                                LiveIntervals &LIS,
163                                const TargetInstrInfo &TII) {
164   MachineInstr *DefMI = 0, *UseMI = 0;
165
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();
171     if (MO.isDef()) {
172       if (DefMI && DefMI != MI)
173         return false;
174       if (!MI->canFoldAsLoad())
175         return false;
176       DefMI = MI;
177     } else if (!MO.isUndef()) {
178       if (UseMI && UseMI != MI)
179         return false;
180       // FIXME: Targets don't know how to fold subreg uses.
181       if (MO.getSubReg())
182         return false;
183       UseMI = MI;
184     }
185   }
186   if (!DefMI || !UseMI)
187     return false;
188
189   DEBUG(dbgs() << "Try to fold single def: " << *DefMI
190                << "       into single use: " << *UseMI);
191
192   SmallVector<unsigned, 8> Ops;
193   if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
194     return false;
195
196   MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
197   if (!FoldMI)
198     return false;
199   DEBUG(dbgs() << "                folded: " << *FoldMI);
200   LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
201   UseMI->eraseFromParent();
202   DefMI->addRegisterDead(LI->reg, 0);
203   Dead.push_back(DefMI);
204   ++NumDCEFoldedLoads;
205   return true;
206 }
207
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();
216
217   for (;;) {
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();
223
224       // Never delete inline asm.
225       if (MI->isInlineAsm()) {
226         DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
227         continue;
228       }
229
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);
234         continue;
235       }
236
237       DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
238
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) {
242         if (!MOI->isReg())
243           continue;
244         unsigned Reg = MOI->getReg();
245         if (!TargetRegisterInfo::isVirtualRegister(Reg))
246           continue;
247         LiveInterval &LI = LIS.getInterval(Reg);
248
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) ||
255              LI.killedAt(Idx)))
256           ToShrink.insert(&LI);
257
258         // Remove defined value.
259         if (MOI->isDef()) {
260           if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
261             if (delegate_)
262               delegate_->LRE_WillShrinkVirtReg(LI.reg);
263             LI.removeValNo(VNI);
264             if (LI.empty()) {
265               ToShrink.remove(&LI);
266               eraseVirtReg(Reg, LIS);
267             }
268           }
269         }
270       }
271
272       if (delegate_)
273         delegate_->LRE_WillEraseInstruction(MI);
274       LIS.RemoveMachineInstrFromMaps(MI);
275       MI->eraseFromParent();
276       ++NumDCEDeleted;
277     }
278
279     if (ToShrink.empty())
280       break;
281
282     // Shrink just one live interval. Then delete new dead defs.
283     LiveInterval *LI = ToShrink.back();
284     ToShrink.pop_back();
285     if (foldAsLoad(LI, Dead, MRI, LIS, TII))
286       continue;
287     if (delegate_)
288       delegate_->LRE_WillShrinkVirtReg(LI->reg);
289     if (!LIS.shrinkToUses(LI, &Dead))
290       continue;
291     
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]) {
299         BeingSpilled = true;
300         break;
301       }
302     }
303     
304     if (BeingSpilled) continue;
305     
306
307     // LI may have been separated, create new intervals.
308     LI->RenumberValues(LIS);
309     ConnectedVNInfoEqClasses ConEQ(LIS);
310     unsigned NumComp = ConEQ.Classify(LI);
311     if (NumComp <= 1)
312       continue;
313     ++NumFracRanges;
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.
322       if (IsOriginal)
323         VRM.setIsSplitFromReg(Dups.back()->reg, 0);
324       if (delegate_)
325         delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
326     }
327     ConEQ.Distribute(&Dups[0], MRI);
328   }
329 }
330
331 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
332                                              LiveIntervals &LIS,
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);
342   }
343 }