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/SetVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/CalcSpillWeights.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/VirtRegMap.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Target/TargetInstrInfo.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
anchor()32 void LiveRangeEdit::Delegate::anchor() { }
33
createFrom(unsigned OldReg)34 LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg) {
35 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
36 if (VRM) {
37 VRM->grow();
38 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
39 }
40 LiveInterval &LI = LIS.getOrCreateInterval(VReg);
41 NewRegs.push_back(&LI);
42 return LI;
43 }
44
checkRematerializable(VNInfo * VNI,const MachineInstr * DefMI,AliasAnalysis * aa)45 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
46 const MachineInstr *DefMI,
47 AliasAnalysis *aa) {
48 assert(DefMI && "Missing instruction");
49 ScannedRemattable = true;
50 if (!TII.isTriviallyReMaterializable(DefMI, aa))
51 return false;
52 Remattable.insert(VNI);
53 return true;
54 }
55
scanRemattable(AliasAnalysis * aa)56 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
57 for (LiveInterval::vni_iterator I = getParent().vni_begin(),
58 E = getParent().vni_end(); I != E; ++I) {
59 VNInfo *VNI = *I;
60 if (VNI->isUnused())
61 continue;
62 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
63 if (!DefMI)
64 continue;
65 checkRematerializable(VNI, DefMI, aa);
66 }
67 ScannedRemattable = true;
68 }
69
anyRematerializable(AliasAnalysis * aa)70 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
71 if (!ScannedRemattable)
72 scanRemattable(aa);
73 return !Remattable.empty();
74 }
75
76 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
77 /// OrigIdx are also available with the same value at UseIdx.
allUsesAvailableAt(const MachineInstr * OrigMI,SlotIndex OrigIdx,SlotIndex UseIdx)78 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
79 SlotIndex OrigIdx,
80 SlotIndex UseIdx) {
81 OrigIdx = OrigIdx.getRegSlot(true);
82 UseIdx = UseIdx.getRegSlot(true);
83 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
84 const MachineOperand &MO = OrigMI->getOperand(i);
85 if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
86 continue;
87
88 // We can't remat physreg uses, unless it is a constant.
89 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
90 if (MRI.isConstantPhysReg(MO.getReg(), *OrigMI->getParent()->getParent()))
91 continue;
92 return false;
93 }
94
95 LiveInterval &li = LIS.getInterval(MO.getReg());
96 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
97 if (!OVNI)
98 continue;
99
100 // Don't allow rematerialization immediately after the original def.
101 // It would be incorrect if OrigMI redefines the register.
102 // See PR14098.
103 if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
104 return false;
105
106 if (OVNI != li.getVNInfoAt(UseIdx))
107 return false;
108 }
109 return true;
110 }
111
canRematerializeAt(Remat & RM,SlotIndex UseIdx,bool cheapAsAMove)112 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
113 SlotIndex UseIdx,
114 bool cheapAsAMove) {
115 assert(ScannedRemattable && "Call anyRematerializable first");
116
117 // Use scanRemattable info.
118 if (!Remattable.count(RM.ParentVNI))
119 return false;
120
121 // No defining instruction provided.
122 SlotIndex DefIdx;
123 if (RM.OrigMI)
124 DefIdx = LIS.getInstructionIndex(RM.OrigMI);
125 else {
126 DefIdx = RM.ParentVNI->def;
127 RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
128 assert(RM.OrigMI && "No defining instruction for remattable value");
129 }
130
131 // If only cheap remats were requested, bail out early.
132 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
133 return false;
134
135 // Verify that all used registers are available with the same values.
136 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
137 return false;
138
139 return true;
140 }
141
rematerializeAt(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned DestReg,const Remat & RM,const TargetRegisterInfo & tri,bool Late)142 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
143 MachineBasicBlock::iterator MI,
144 unsigned DestReg,
145 const Remat &RM,
146 const TargetRegisterInfo &tri,
147 bool Late) {
148 assert(RM.OrigMI && "Invalid remat");
149 TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
150 Rematted.insert(RM.ParentVNI);
151 return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
152 .getRegSlot();
153 }
154
eraseVirtReg(unsigned Reg)155 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
156 if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
157 LIS.removeInterval(Reg);
158 }
159
foldAsLoad(LiveInterval * LI,SmallVectorImpl<MachineInstr * > & Dead)160 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
161 SmallVectorImpl<MachineInstr*> &Dead) {
162 MachineInstr *DefMI = 0, *UseMI = 0;
163
164 // Check that there is a single def and a single use.
165 for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
166 E = MRI.reg_nodbg_end(); I != E; ++I) {
167 MachineOperand &MO = I.getOperand();
168 MachineInstr *MI = MO.getParent();
169 if (MO.isDef()) {
170 if (DefMI && DefMI != MI)
171 return false;
172 if (!MI->canFoldAsLoad())
173 return false;
174 DefMI = MI;
175 } else if (!MO.isUndef()) {
176 if (UseMI && UseMI != MI)
177 return false;
178 // FIXME: Targets don't know how to fold subreg uses.
179 if (MO.getSubReg())
180 return false;
181 UseMI = MI;
182 }
183 }
184 if (!DefMI || !UseMI)
185 return false;
186
187 // Since we're moving the DefMI load, make sure we're not extending any live
188 // ranges.
189 if (!allUsesAvailableAt(DefMI,
190 LIS.getInstructionIndex(DefMI),
191 LIS.getInstructionIndex(UseMI)))
192 return false;
193
194 // We also need to make sure it is safe to move the load.
195 // Assume there are stores between DefMI and UseMI.
196 bool SawStore = true;
197 if (!DefMI->isSafeToMove(&TII, 0, SawStore))
198 return false;
199
200 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
201 << " into single use: " << *UseMI);
202
203 SmallVector<unsigned, 8> Ops;
204 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
205 return false;
206
207 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
208 if (!FoldMI)
209 return false;
210 DEBUG(dbgs() << " folded: " << *FoldMI);
211 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
212 UseMI->eraseFromParent();
213 DefMI->addRegisterDead(LI->reg, 0);
214 Dead.push_back(DefMI);
215 ++NumDCEFoldedLoads;
216 return true;
217 }
218
eliminateDeadDefs(SmallVectorImpl<MachineInstr * > & Dead,ArrayRef<unsigned> RegsBeingSpilled)219 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
220 ArrayRef<unsigned> RegsBeingSpilled) {
221 SetVector<LiveInterval*,
222 SmallVector<LiveInterval*, 8>,
223 SmallPtrSet<LiveInterval*, 8> > ToShrink;
224
225 for (;;) {
226 // Erase all dead defs.
227 while (!Dead.empty()) {
228 MachineInstr *MI = Dead.pop_back_val();
229 assert(MI->allDefsAreDead() && "Def isn't really dead");
230 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
231
232 // Never delete inline asm.
233 if (MI->isInlineAsm()) {
234 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
235 continue;
236 }
237
238 // Use the same criteria as DeadMachineInstructionElim.
239 bool SawStore = false;
240 if (!MI->isSafeToMove(&TII, 0, SawStore)) {
241 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
242 continue;
243 }
244
245 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
246
247 // Collect virtual registers to be erased after MI is gone.
248 SmallVector<unsigned, 8> RegsToErase;
249 bool ReadsPhysRegs = false;
250
251 // Check for live intervals that may shrink
252 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
253 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
254 if (!MOI->isReg())
255 continue;
256 unsigned Reg = MOI->getReg();
257 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
258 // Check if MI reads any unreserved physregs.
259 if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
260 ReadsPhysRegs = true;
261 continue;
262 }
263 LiveInterval &LI = LIS.getInterval(Reg);
264
265 // Shrink read registers, unless it is likely to be expensive and
266 // unlikely to change anything. We typically don't want to shrink the
267 // PIC base register that has lots of uses everywhere.
268 // Always shrink COPY uses that probably come from live range splitting.
269 if (MI->readsVirtualRegister(Reg) &&
270 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
271 LI.killedAt(Idx)))
272 ToShrink.insert(&LI);
273
274 // Remove defined value.
275 if (MOI->isDef()) {
276 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
277 if (TheDelegate)
278 TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
279 LI.removeValNo(VNI);
280 if (LI.empty())
281 RegsToErase.push_back(Reg);
282 }
283 }
284 }
285
286 // Currently, we don't support DCE of physreg live ranges. If MI reads
287 // any unreserved physregs, don't erase the instruction, but turn it into
288 // a KILL instead. This way, the physreg live ranges don't end up
289 // dangling.
290 // FIXME: It would be better to have something like shrinkToUses() for
291 // physregs. That could potentially enable more DCE and it would free up
292 // the physreg. It would not happen often, though.
293 if (ReadsPhysRegs) {
294 MI->setDesc(TII.get(TargetOpcode::KILL));
295 // Remove all operands that aren't physregs.
296 for (unsigned i = MI->getNumOperands(); i; --i) {
297 const MachineOperand &MO = MI->getOperand(i-1);
298 if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
299 continue;
300 MI->RemoveOperand(i-1);
301 }
302 DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
303 } else {
304 if (TheDelegate)
305 TheDelegate->LRE_WillEraseInstruction(MI);
306 LIS.RemoveMachineInstrFromMaps(MI);
307 MI->eraseFromParent();
308 ++NumDCEDeleted;
309 }
310
311 // Erase any virtregs that are now empty and unused. There may be <undef>
312 // uses around. Keep the empty live range in that case.
313 for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
314 unsigned Reg = RegsToErase[i];
315 if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
316 ToShrink.remove(&LIS.getInterval(Reg));
317 eraseVirtReg(Reg);
318 }
319 }
320 }
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
calculateRegClassAndHint(MachineFunction & MF,const MachineLoopInfo & Loops)377 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
378 const MachineLoopInfo &Loops) {
379 VirtRegAuxInfo VRAI(MF, LIS, Loops);
380 for (iterator I = begin(), E = end(); I != E; ++I) {
381 LiveInterval &LI = **I;
382 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
383 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
384 << MRI.getRegClass(LI.reg)->getName() << '\n');
385 VRAI.CalculateWeightAndHint(LI);
386 }
387 }
388