Remove dead code. Improve llvm_unreachable text. Simplify some control flow.
[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     // We cannot depend on virtual registers in uselessRegs_.
98     if (uselessRegs_)
99       for (unsigned ui = 0, ue = uselessRegs_->size(); ui != ue; ++ui)
100         if ((*uselessRegs_)[ui]->reg == MO.getReg())
101           return false;
102
103     LiveInterval &li = lis.getInterval(MO.getReg());
104     const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
105     if (!OVNI)
106       continue;
107     if (OVNI != li.getVNInfoAt(UseIdx))
108       return false;
109   }
110   return true;
111 }
112
113 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
114                                        SlotIndex UseIdx,
115                                        bool cheapAsAMove,
116                                        LiveIntervals &lis) {
117   assert(scannedRemattable_ && "Call anyRematerializable first");
118
119   // Use scanRemattable info.
120   if (!remattable_.count(RM.ParentVNI))
121     return false;
122
123   // No defining instruction provided.
124   SlotIndex DefIdx;
125   if (RM.OrigMI)
126     DefIdx = lis.getInstructionIndex(RM.OrigMI);
127   else {
128     DefIdx = RM.ParentVNI->def;
129     RM.OrigMI = lis.getInstructionFromIndex(DefIdx);
130     assert(RM.OrigMI && "No defining instruction for remattable value");
131   }
132
133   // If only cheap remats were requested, bail out early.
134   if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
135     return false;
136
137   // Verify that all used registers are available with the same values.
138   if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx, lis))
139     return false;
140
141   return true;
142 }
143
144 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
145                                          MachineBasicBlock::iterator MI,
146                                          unsigned DestReg,
147                                          const Remat &RM,
148                                          LiveIntervals &lis,
149                                          const TargetInstrInfo &tii,
150                                          const TargetRegisterInfo &tri,
151                                          bool Late) {
152   assert(RM.OrigMI && "Invalid remat");
153   tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
154   rematted_.insert(RM.ParentVNI);
155   return lis.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
156            .getRegSlot();
157 }
158
159 void LiveRangeEdit::eraseVirtReg(unsigned Reg, LiveIntervals &LIS) {
160   if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
161     LIS.removeInterval(Reg);
162 }
163
164 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
165                                SmallVectorImpl<MachineInstr*> &Dead,
166                                MachineRegisterInfo &MRI,
167                                LiveIntervals &LIS,
168                                const TargetInstrInfo &TII) {
169   MachineInstr *DefMI = 0, *UseMI = 0;
170
171   // Check that there is a single def and a single use.
172   for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
173        E = MRI.reg_nodbg_end(); I != E; ++I) {
174     MachineOperand &MO = I.getOperand();
175     MachineInstr *MI = MO.getParent();
176     if (MO.isDef()) {
177       if (DefMI && DefMI != MI)
178         return false;
179       if (!MI->canFoldAsLoad())
180         return false;
181       DefMI = MI;
182     } else if (!MO.isUndef()) {
183       if (UseMI && UseMI != MI)
184         return false;
185       // FIXME: Targets don't know how to fold subreg uses.
186       if (MO.getSubReg())
187         return false;
188       UseMI = MI;
189     }
190   }
191   if (!DefMI || !UseMI)
192     return false;
193
194   DEBUG(dbgs() << "Try to fold single def: " << *DefMI
195                << "       into single use: " << *UseMI);
196
197   SmallVector<unsigned, 8> Ops;
198   if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
199     return false;
200
201   MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
202   if (!FoldMI)
203     return false;
204   DEBUG(dbgs() << "                folded: " << *FoldMI);
205   LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
206   UseMI->eraseFromParent();
207   DefMI->addRegisterDead(LI->reg, 0);
208   Dead.push_back(DefMI);
209   ++NumDCEFoldedLoads;
210   return true;
211 }
212
213 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
214                                       LiveIntervals &LIS, VirtRegMap &VRM,
215                                       const TargetInstrInfo &TII,
216                                       ArrayRef<unsigned> RegsBeingSpilled) {
217   SetVector<LiveInterval*,
218             SmallVector<LiveInterval*, 8>,
219             SmallPtrSet<LiveInterval*, 8> > ToShrink;
220   MachineRegisterInfo &MRI = VRM.getRegInfo();
221
222   for (;;) {
223     // Erase all dead defs.
224     while (!Dead.empty()) {
225       MachineInstr *MI = Dead.pop_back_val();
226       assert(MI->allDefsAreDead() && "Def isn't really dead");
227       SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
228
229       // Never delete inline asm.
230       if (MI->isInlineAsm()) {
231         DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
232         continue;
233       }
234
235       // Use the same criteria as DeadMachineInstructionElim.
236       bool SawStore = false;
237       if (!MI->isSafeToMove(&TII, 0, SawStore)) {
238         DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
239         continue;
240       }
241
242       DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
243
244       // Check for live intervals that may shrink
245       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
246              MOE = MI->operands_end(); MOI != MOE; ++MOI) {
247         if (!MOI->isReg())
248           continue;
249         unsigned Reg = MOI->getReg();
250         if (!TargetRegisterInfo::isVirtualRegister(Reg))
251           continue;
252         LiveInterval &LI = LIS.getInterval(Reg);
253
254         // Shrink read registers, unless it is likely to be expensive and
255         // unlikely to change anything. We typically don't want to shrink the
256         // PIC base register that has lots of uses everywhere.
257         // Always shrink COPY uses that probably come from live range splitting.
258         if (MI->readsVirtualRegister(Reg) &&
259             (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
260              LI.killedAt(Idx)))
261           ToShrink.insert(&LI);
262
263         // Remove defined value.
264         if (MOI->isDef()) {
265           if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
266             if (delegate_)
267               delegate_->LRE_WillShrinkVirtReg(LI.reg);
268             LI.removeValNo(VNI);
269             if (LI.empty()) {
270               ToShrink.remove(&LI);
271               eraseVirtReg(Reg, LIS);
272             }
273           }
274         }
275       }
276
277       if (delegate_)
278         delegate_->LRE_WillEraseInstruction(MI);
279       LIS.RemoveMachineInstrFromMaps(MI);
280       MI->eraseFromParent();
281       ++NumDCEDeleted;
282     }
283
284     if (ToShrink.empty())
285       break;
286
287     // Shrink just one live interval. Then delete new dead defs.
288     LiveInterval *LI = ToShrink.back();
289     ToShrink.pop_back();
290     if (foldAsLoad(LI, Dead, MRI, LIS, TII))
291       continue;
292     if (delegate_)
293       delegate_->LRE_WillShrinkVirtReg(LI->reg);
294     if (!LIS.shrinkToUses(LI, &Dead))
295       continue;
296     
297     // Don't create new intervals for a register being spilled.
298     // The new intervals would have to be spilled anyway so its not worth it.
299     // Also they currently aren't spilled so creating them and not spilling
300     // them results in incorrect code.
301     bool BeingSpilled = false;
302     for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
303       if (LI->reg == RegsBeingSpilled[i]) {
304         BeingSpilled = true;
305         break;
306       }
307     }
308     
309     if (BeingSpilled) continue;
310     
311
312     // LI may have been separated, create new intervals.
313     LI->RenumberValues(LIS);
314     ConnectedVNInfoEqClasses ConEQ(LIS);
315     unsigned NumComp = ConEQ.Classify(LI);
316     if (NumComp <= 1)
317       continue;
318     ++NumFracRanges;
319     bool IsOriginal = VRM.getOriginal(LI->reg) == LI->reg;
320     DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
321     SmallVector<LiveInterval*, 8> Dups(1, LI);
322     for (unsigned i = 1; i != NumComp; ++i) {
323       Dups.push_back(&createFrom(LI->reg, LIS, VRM));
324       // If LI is an original interval that hasn't been split yet, make the new
325       // intervals their own originals instead of referring to LI. The original
326       // interval must contain all the split products, and LI doesn't.
327       if (IsOriginal)
328         VRM.setIsSplitFromReg(Dups.back()->reg, 0);
329       if (delegate_)
330         delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
331     }
332     ConEQ.Distribute(&Dups[0], MRI);
333   }
334 }
335
336 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
337                                              LiveIntervals &LIS,
338                                              const MachineLoopInfo &Loops) {
339   VirtRegAuxInfo VRAI(MF, LIS, Loops);
340   MachineRegisterInfo &MRI = MF.getRegInfo();
341   for (iterator I = begin(), E = end(); I != E; ++I) {
342     LiveInterval &LI = **I;
343     if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
344       DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
345                    << MRI.getRegClass(LI.reg)->getName() << '\n');
346     VRAI.CalculateWeightAndHint(LI);
347   }
348 }