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