Remember to use the correct register when rematerializing for snippets.
[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/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23
24 using namespace llvm;
25
26 LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg,
27                                         LiveIntervals &LIS,
28                                         VirtRegMap &VRM) {
29   MachineRegisterInfo &MRI = VRM.getRegInfo();
30   unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
31   VRM.grow();
32   VRM.setIsSplitFromReg(VReg, VRM.getOriginal(OldReg));
33   LiveInterval &LI = LIS.getOrCreateInterval(VReg);
34   newRegs_.push_back(&LI);
35   return LI;
36 }
37
38 void LiveRangeEdit::checkRematerializable(VNInfo *VNI,
39                                           const MachineInstr *DefMI,
40                                           const TargetInstrInfo &tii,
41                                           AliasAnalysis *aa) {
42   assert(DefMI && "Missing instruction");
43   if (tii.isTriviallyReMaterializable(DefMI, aa))
44     remattable_.insert(VNI);
45   scannedRemattable_ = true;
46 }
47
48 void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
49                                    const TargetInstrInfo &tii,
50                                    AliasAnalysis *aa) {
51   for (LiveInterval::vni_iterator I = parent_.vni_begin(),
52        E = parent_.vni_end(); I != E; ++I) {
53     VNInfo *VNI = *I;
54     if (VNI->isUnused())
55       continue;
56     MachineInstr *DefMI = lis.getInstructionFromIndex(VNI->def);
57     if (!DefMI)
58       continue;
59     checkRematerializable(VNI, DefMI, tii, aa);
60   }
61 }
62
63 bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
64                                         const TargetInstrInfo &tii,
65                                         AliasAnalysis *aa) {
66   if (!scannedRemattable_)
67     scanRemattable(lis, tii, aa);
68   return !remattable_.empty();
69 }
70
71 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
72 /// OrigIdx are also available with the same value at UseIdx.
73 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
74                                        SlotIndex OrigIdx,
75                                        SlotIndex UseIdx,
76                                        LiveIntervals &lis) {
77   OrigIdx = OrigIdx.getUseIndex();
78   UseIdx = UseIdx.getUseIndex();
79   for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
80     const MachineOperand &MO = OrigMI->getOperand(i);
81     if (!MO.isReg() || !MO.getReg() || MO.isDef())
82       continue;
83     // Reserved registers are OK.
84     if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
85       continue;
86     // We cannot depend on virtual registers in uselessRegs_.
87     if (uselessRegs_)
88       for (unsigned ui = 0, ue = uselessRegs_->size(); ui != ue; ++ui)
89         if ((*uselessRegs_)[ui]->reg == MO.getReg())
90           return false;
91
92     LiveInterval &li = lis.getInterval(MO.getReg());
93     const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
94     if (!OVNI)
95       continue;
96     if (OVNI != li.getVNInfoAt(UseIdx))
97       return false;
98   }
99   return true;
100 }
101
102 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
103                                        SlotIndex UseIdx,
104                                        bool cheapAsAMove,
105                                        LiveIntervals &lis) {
106   assert(scannedRemattable_ && "Call anyRematerializable first");
107
108   // Use scanRemattable info.
109   if (!remattable_.count(RM.ParentVNI))
110     return false;
111
112   // No defining instruction provided.
113   SlotIndex DefIdx;
114   if (RM.OrigMI)
115     DefIdx = lis.getInstructionIndex(RM.OrigMI);
116   else {
117     DefIdx = RM.ParentVNI->def;
118     RM.OrigMI = lis.getInstructionFromIndex(DefIdx);
119     assert(RM.OrigMI && "No defining instruction for remattable value");
120   }
121
122   // If only cheap remats were requested, bail out early.
123   if (cheapAsAMove && !RM.OrigMI->getDesc().isAsCheapAsAMove())
124     return false;
125
126   // Verify that all used registers are available with the same values.
127   if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx, lis))
128     return false;
129
130   return true;
131 }
132
133 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
134                                          MachineBasicBlock::iterator MI,
135                                          unsigned DestReg,
136                                          const Remat &RM,
137                                          LiveIntervals &lis,
138                                          const TargetInstrInfo &tii,
139                                          const TargetRegisterInfo &tri) {
140   assert(RM.OrigMI && "Invalid remat");
141   tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
142   rematted_.insert(RM.ParentVNI);
143   return lis.InsertMachineInstrInMaps(--MI).getDefIndex();
144 }
145
146 void LiveRangeEdit::eraseVirtReg(unsigned Reg, LiveIntervals &LIS) {
147   if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
148     LIS.removeInterval(Reg);
149 }
150
151 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
152                                       LiveIntervals &LIS, VirtRegMap &VRM,
153                                       const TargetInstrInfo &TII) {
154   SetVector<LiveInterval*,
155             SmallVector<LiveInterval*, 8>,
156             SmallPtrSet<LiveInterval*, 8> > ToShrink;
157
158   for (;;) {
159     // Erase all dead defs.
160     while (!Dead.empty()) {
161       MachineInstr *MI = Dead.pop_back_val();
162       assert(MI->allDefsAreDead() && "Def isn't really dead");
163       SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
164
165       // Never delete inline asm.
166       if (MI->isInlineAsm()) {
167         DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
168         continue;
169       }
170
171       // Use the same criteria as DeadMachineInstructionElim.
172       bool SawStore = false;
173       if (!MI->isSafeToMove(&TII, 0, SawStore)) {
174         DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
175         continue;
176       }
177
178       DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
179
180       // Check for live intervals that may shrink
181       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
182              MOE = MI->operands_end(); MOI != MOE; ++MOI) {
183         if (!MOI->isReg())
184           continue;
185         unsigned Reg = MOI->getReg();
186         if (!TargetRegisterInfo::isVirtualRegister(Reg))
187           continue;
188         LiveInterval &LI = LIS.getInterval(Reg);
189
190         // Shrink read registers.
191         if (MI->readsVirtualRegister(Reg))
192           ToShrink.insert(&LI);
193
194         // Remove defined value.
195         if (MOI->isDef()) {
196           if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
197             if (delegate_)
198               delegate_->LRE_WillShrinkVirtReg(LI.reg);
199             LI.removeValNo(VNI);
200             if (LI.empty()) {
201               ToShrink.remove(&LI);
202               eraseVirtReg(Reg, LIS);
203             }
204           }
205         }
206       }
207
208       if (delegate_)
209         delegate_->LRE_WillEraseInstruction(MI);
210       LIS.RemoveMachineInstrFromMaps(MI);
211       MI->eraseFromParent();
212     }
213
214     if (ToShrink.empty())
215       break;
216
217     // Shrink just one live interval. Then delete new dead defs.
218     LiveInterval *LI = ToShrink.back();
219     ToShrink.pop_back();
220     if (delegate_)
221       delegate_->LRE_WillShrinkVirtReg(LI->reg);
222     if (!LIS.shrinkToUses(LI, &Dead))
223       continue;
224
225     // LI may have been separated, create new intervals.
226     LI->RenumberValues(LIS);
227     ConnectedVNInfoEqClasses ConEQ(LIS);
228     unsigned NumComp = ConEQ.Classify(LI);
229     if (NumComp <= 1)
230       continue;
231     DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
232     SmallVector<LiveInterval*, 8> Dups(1, LI);
233     for (unsigned i = 1; i != NumComp; ++i)
234       Dups.push_back(&createFrom(LI->reg, LIS, VRM));
235     ConEQ.Distribute(&Dups[0], VRM.getRegInfo());
236   }
237 }
238