1 //===- InlineSpiller.cpp - Insert spills and restores inline --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The inline spiller modifies the machine function directly instead of
10 // inserting spills and restores in VirtRegMap.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SplitKit.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/LiveInterval.h"
26 #include "llvm/CodeGen/LiveIntervalCalc.h"
27 #include "llvm/CodeGen/LiveIntervals.h"
28 #include "llvm/CodeGen/LiveRangeEdit.h"
29 #include "llvm/CodeGen/LiveStacks.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineInstrBundle.h"
38 #include "llvm/CodeGen/MachineLoopInfo.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/SlotIndexes.h"
42 #include "llvm/CodeGen/Spiller.h"
43 #include "llvm/CodeGen/StackMaps.h"
44 #include "llvm/CodeGen/TargetInstrInfo.h"
45 #include "llvm/CodeGen/TargetOpcodes.h"
46 #include "llvm/CodeGen/TargetRegisterInfo.h"
47 #include "llvm/CodeGen/TargetSubtargetInfo.h"
48 #include "llvm/CodeGen/VirtRegMap.h"
49 #include "llvm/Config/llvm-config.h"
50 #include "llvm/Support/BlockFrequency.h"
51 #include "llvm/Support/BranchProbability.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <cassert>
58 #include <iterator>
59 #include <tuple>
60 #include <utility>
61 #include <vector>
62
63 using namespace llvm;
64
65 #define DEBUG_TYPE "regalloc"
66
67 STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
68 STATISTIC(NumSnippets, "Number of spilled snippets");
69 STATISTIC(NumSpills, "Number of spills inserted");
70 STATISTIC(NumSpillsRemoved, "Number of spills removed");
71 STATISTIC(NumReloads, "Number of reloads inserted");
72 STATISTIC(NumReloadsRemoved, "Number of reloads removed");
73 STATISTIC(NumFolded, "Number of folded stack accesses");
74 STATISTIC(NumFoldedLoads, "Number of folded loads");
75 STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
76
77 static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
78 cl::desc("Disable inline spill hoisting"));
79 static cl::opt<bool>
80 RestrictStatepointRemat("restrict-statepoint-remat",
81 cl::init(false), cl::Hidden,
82 cl::desc("Restrict remat for statepoint operands"));
83
84 namespace {
85
86 class HoistSpillHelper : private LiveRangeEdit::Delegate {
87 MachineFunction &MF;
88 LiveIntervals &LIS;
89 LiveStacks &LSS;
90 AliasAnalysis *AA;
91 MachineDominatorTree &MDT;
92 MachineLoopInfo &Loops;
93 VirtRegMap &VRM;
94 MachineRegisterInfo &MRI;
95 const TargetInstrInfo &TII;
96 const TargetRegisterInfo &TRI;
97 const MachineBlockFrequencyInfo &MBFI;
98
99 InsertPointAnalysis IPA;
100
101 // Map from StackSlot to the LiveInterval of the original register.
102 // Note the LiveInterval of the original register may have been deleted
103 // after it is spilled. We keep a copy here to track the range where
104 // spills can be moved.
105 DenseMap<int, std::unique_ptr<LiveInterval>> StackSlotToOrigLI;
106
107 // Map from pair of (StackSlot and Original VNI) to a set of spills which
108 // have the same stackslot and have equal values defined by Original VNI.
109 // These spills are mergeable and are hoist candiates.
110 using MergeableSpillsMap =
111 MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
112 MergeableSpillsMap MergeableSpills;
113
114 /// This is the map from original register to a set containing all its
115 /// siblings. To hoist a spill to another BB, we need to find out a live
116 /// sibling there and use it as the source of the new spill.
117 DenseMap<Register, SmallSetVector<Register, 16>> Virt2SiblingsMap;
118
119 bool isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
120 MachineBasicBlock &BB, Register &LiveReg);
121
122 void rmRedundantSpills(
123 SmallPtrSet<MachineInstr *, 16> &Spills,
124 SmallVectorImpl<MachineInstr *> &SpillsToRm,
125 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
126
127 void getVisitOrders(
128 MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
129 SmallVectorImpl<MachineDomTreeNode *> &Orders,
130 SmallVectorImpl<MachineInstr *> &SpillsToRm,
131 DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
132 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
133
134 void runHoistSpills(LiveInterval &OrigLI, VNInfo &OrigVNI,
135 SmallPtrSet<MachineInstr *, 16> &Spills,
136 SmallVectorImpl<MachineInstr *> &SpillsToRm,
137 DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns);
138
139 public:
HoistSpillHelper(MachineFunctionPass & pass,MachineFunction & mf,VirtRegMap & vrm)140 HoistSpillHelper(MachineFunctionPass &pass, MachineFunction &mf,
141 VirtRegMap &vrm)
142 : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
143 LSS(pass.getAnalysis<LiveStacks>()),
144 AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
145 MDT(pass.getAnalysis<MachineDominatorTree>()),
146 Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
147 MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
148 TRI(*mf.getSubtarget().getRegisterInfo()),
149 MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
150 IPA(LIS, mf.getNumBlockIDs()) {}
151
152 void addToMergeableSpills(MachineInstr &Spill, int StackSlot,
153 unsigned Original);
154 bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
155 void hoistAllSpills();
156 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
157 };
158
159 class InlineSpiller : public Spiller {
160 MachineFunction &MF;
161 LiveIntervals &LIS;
162 LiveStacks &LSS;
163 AliasAnalysis *AA;
164 MachineDominatorTree &MDT;
165 MachineLoopInfo &Loops;
166 VirtRegMap &VRM;
167 MachineRegisterInfo &MRI;
168 const TargetInstrInfo &TII;
169 const TargetRegisterInfo &TRI;
170 const MachineBlockFrequencyInfo &MBFI;
171
172 // Variables that are valid during spill(), but used by multiple methods.
173 LiveRangeEdit *Edit;
174 LiveInterval *StackInt;
175 int StackSlot;
176 unsigned Original;
177
178 // All registers to spill to StackSlot, including the main register.
179 SmallVector<Register, 8> RegsToSpill;
180
181 // All COPY instructions to/from snippets.
182 // They are ignored since both operands refer to the same stack slot.
183 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
184
185 // Values that failed to remat at some point.
186 SmallPtrSet<VNInfo*, 8> UsedValues;
187
188 // Dead defs generated during spilling.
189 SmallVector<MachineInstr*, 8> DeadDefs;
190
191 // Object records spills information and does the hoisting.
192 HoistSpillHelper HSpiller;
193
194 ~InlineSpiller() override = default;
195
196 public:
InlineSpiller(MachineFunctionPass & pass,MachineFunction & mf,VirtRegMap & vrm)197 InlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
198 : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
199 LSS(pass.getAnalysis<LiveStacks>()),
200 AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
201 MDT(pass.getAnalysis<MachineDominatorTree>()),
202 Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
203 MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
204 TRI(*mf.getSubtarget().getRegisterInfo()),
205 MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
206 HSpiller(pass, mf, vrm) {}
207
208 void spill(LiveRangeEdit &) override;
209 void postOptimization() override;
210
211 private:
212 bool isSnippet(const LiveInterval &SnipLI);
213 void collectRegsToSpill();
214
isRegToSpill(Register Reg)215 bool isRegToSpill(Register Reg) { return is_contained(RegsToSpill, Reg); }
216
217 bool isSibling(Register Reg);
218 bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
219 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
220
221 void markValueUsed(LiveInterval*, VNInfo*);
222 bool canGuaranteeAssignmentAfterRemat(Register VReg, MachineInstr &MI);
223 bool reMaterializeFor(LiveInterval &, MachineInstr &MI);
224 void reMaterializeAll();
225
226 bool coalesceStackAccess(MachineInstr *MI, Register Reg);
227 bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
228 MachineInstr *LoadMI = nullptr);
229 void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
230 void insertSpill(Register VReg, bool isKill, MachineBasicBlock::iterator MI);
231
232 void spillAroundUses(Register Reg);
233 void spillAll();
234 };
235
236 } // end anonymous namespace
237
238 Spiller::~Spiller() = default;
239
anchor()240 void Spiller::anchor() {}
241
createInlineSpiller(MachineFunctionPass & pass,MachineFunction & mf,VirtRegMap & vrm)242 Spiller *llvm::createInlineSpiller(MachineFunctionPass &pass,
243 MachineFunction &mf,
244 VirtRegMap &vrm) {
245 return new InlineSpiller(pass, mf, vrm);
246 }
247
248 //===----------------------------------------------------------------------===//
249 // Snippets
250 //===----------------------------------------------------------------------===//
251
252 // When spilling a virtual register, we also spill any snippets it is connected
253 // to. The snippets are small live ranges that only have a single real use,
254 // leftovers from live range splitting. Spilling them enables memory operand
255 // folding or tightens the live range around the single use.
256 //
257 // This minimizes register pressure and maximizes the store-to-load distance for
258 // spill slots which can be important in tight loops.
259
260 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
261 /// otherwise return 0.
isFullCopyOf(const MachineInstr & MI,Register Reg)262 static Register isFullCopyOf(const MachineInstr &MI, Register Reg) {
263 if (!MI.isFullCopy())
264 return Register();
265 if (MI.getOperand(0).getReg() == Reg)
266 return MI.getOperand(1).getReg();
267 if (MI.getOperand(1).getReg() == Reg)
268 return MI.getOperand(0).getReg();
269 return Register();
270 }
271
272 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
273 /// It is assumed that SnipLI is a virtual register with the same original as
274 /// Edit->getReg().
isSnippet(const LiveInterval & SnipLI)275 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
276 Register Reg = Edit->getReg();
277
278 // A snippet is a tiny live range with only a single instruction using it
279 // besides copies to/from Reg or spills/fills. We accept:
280 //
281 // %snip = COPY %Reg / FILL fi#
282 // %snip = USE %snip
283 // %Reg = COPY %snip / SPILL %snip, fi#
284 //
285 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
286 return false;
287
288 MachineInstr *UseMI = nullptr;
289
290 // Check that all uses satisfy our criteria.
291 for (MachineRegisterInfo::reg_instr_nodbg_iterator
292 RI = MRI.reg_instr_nodbg_begin(SnipLI.reg),
293 E = MRI.reg_instr_nodbg_end(); RI != E; ) {
294 MachineInstr &MI = *RI++;
295
296 // Allow copies to/from Reg.
297 if (isFullCopyOf(MI, Reg))
298 continue;
299
300 // Allow stack slot loads.
301 int FI;
302 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
303 continue;
304
305 // Allow stack slot stores.
306 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
307 continue;
308
309 // Allow a single additional instruction.
310 if (UseMI && &MI != UseMI)
311 return false;
312 UseMI = &MI;
313 }
314 return true;
315 }
316
317 /// collectRegsToSpill - Collect live range snippets that only have a single
318 /// real use.
collectRegsToSpill()319 void InlineSpiller::collectRegsToSpill() {
320 Register Reg = Edit->getReg();
321
322 // Main register always spills.
323 RegsToSpill.assign(1, Reg);
324 SnippetCopies.clear();
325
326 // Snippets all have the same original, so there can't be any for an original
327 // register.
328 if (Original == Reg)
329 return;
330
331 for (MachineRegisterInfo::reg_instr_iterator
332 RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) {
333 MachineInstr &MI = *RI++;
334 Register SnipReg = isFullCopyOf(MI, Reg);
335 if (!isSibling(SnipReg))
336 continue;
337 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
338 if (!isSnippet(SnipLI))
339 continue;
340 SnippetCopies.insert(&MI);
341 if (isRegToSpill(SnipReg))
342 continue;
343 RegsToSpill.push_back(SnipReg);
344 LLVM_DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
345 ++NumSnippets;
346 }
347 }
348
isSibling(Register Reg)349 bool InlineSpiller::isSibling(Register Reg) {
350 return Reg.isVirtual() && VRM.getOriginal(Reg) == Original;
351 }
352
353 /// It is beneficial to spill to earlier place in the same BB in case
354 /// as follows:
355 /// There is an alternative def earlier in the same MBB.
356 /// Hoist the spill as far as possible in SpillMBB. This can ease
357 /// register pressure:
358 ///
359 /// x = def
360 /// y = use x
361 /// s = copy x
362 ///
363 /// Hoisting the spill of s to immediately after the def removes the
364 /// interference between x and y:
365 ///
366 /// x = def
367 /// spill x
368 /// y = use killed x
369 ///
370 /// This hoist only helps when the copy kills its source.
371 ///
hoistSpillInsideBB(LiveInterval & SpillLI,MachineInstr & CopyMI)372 bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
373 MachineInstr &CopyMI) {
374 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
375 #ifndef NDEBUG
376 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
377 assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
378 #endif
379
380 Register SrcReg = CopyMI.getOperand(1).getReg();
381 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
382 VNInfo *SrcVNI = SrcLI.getVNInfoAt(Idx);
383 LiveQueryResult SrcQ = SrcLI.Query(Idx);
384 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(SrcVNI->def);
385 if (DefMBB != CopyMI.getParent() || !SrcQ.isKill())
386 return false;
387
388 // Conservatively extend the stack slot range to the range of the original
389 // value. We may be able to do better with stack slot coloring by being more
390 // careful here.
391 assert(StackInt && "No stack slot assigned yet.");
392 LiveInterval &OrigLI = LIS.getInterval(Original);
393 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
394 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
395 LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
396 << *StackInt << '\n');
397
398 // We are going to spill SrcVNI immediately after its def, so clear out
399 // any later spills of the same value.
400 eliminateRedundantSpills(SrcLI, SrcVNI);
401
402 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SrcVNI->def);
403 MachineBasicBlock::iterator MII;
404 if (SrcVNI->isPHIDef())
405 MII = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
406 else {
407 MachineInstr *DefMI = LIS.getInstructionFromIndex(SrcVNI->def);
408 assert(DefMI && "Defining instruction disappeared");
409 MII = DefMI;
410 ++MII;
411 }
412 // Insert spill without kill flag immediately after def.
413 TII.storeRegToStackSlot(*MBB, MII, SrcReg, false, StackSlot,
414 MRI.getRegClass(SrcReg), &TRI);
415 --MII; // Point to store instruction.
416 LIS.InsertMachineInstrInMaps(*MII);
417 #if 0
418 // CHERI, with hardware floating point, lacks instructions for storing
419 // floating point via a capability. As such, the storeRegToStackSlot call
420 // will insert two instructions and we must update the maps for both of them.
421 if (MII != MBB->begin()) {
422 --MII; // Point to the instruction before the store instruction.
423 if (LIS.isNotInMIMap(*MII))
424 LIS.InsertMachineInstrInMaps(*MII);
425 }
426 #endif
427 LLVM_DEBUG(dbgs() << "\thoisted: " << SrcVNI->def << '\t' << *MII);
428
429 HSpiller.addToMergeableSpills(*MII, StackSlot, Original);
430 ++NumSpills;
431 return true;
432 }
433
434 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
435 /// redundant spills of this value in SLI.reg and sibling copies.
eliminateRedundantSpills(LiveInterval & SLI,VNInfo * VNI)436 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
437 assert(VNI && "Missing value");
438 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
439 WorkList.push_back(std::make_pair(&SLI, VNI));
440 assert(StackInt && "No stack slot assigned yet.");
441
442 do {
443 LiveInterval *LI;
444 std::tie(LI, VNI) = WorkList.pop_back_val();
445 Register Reg = LI->reg;
446 LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
447 << VNI->def << " in " << *LI << '\n');
448
449 // Regs to spill are taken care of.
450 if (isRegToSpill(Reg))
451 continue;
452
453 // Add all of VNI's live range to StackInt.
454 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
455 LLVM_DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
456
457 // Find all spills and copies of VNI.
458 for (MachineRegisterInfo::use_instr_nodbg_iterator
459 UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
460 UI != E; ) {
461 MachineInstr &MI = *UI++;
462 if (!MI.isCopy() && !MI.mayStore())
463 continue;
464 SlotIndex Idx = LIS.getInstructionIndex(MI);
465 if (LI->getVNInfoAt(Idx) != VNI)
466 continue;
467
468 // Follow sibling copies down the dominator tree.
469 if (Register DstReg = isFullCopyOf(MI, Reg)) {
470 if (isSibling(DstReg)) {
471 LiveInterval &DstLI = LIS.getInterval(DstReg);
472 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
473 assert(DstVNI && "Missing defined value");
474 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
475 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
476 }
477 continue;
478 }
479
480 // Erase spills.
481 int FI;
482 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
483 LLVM_DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << MI);
484 // eliminateDeadDefs won't normally remove stores, so switch opcode.
485 MI.setDesc(TII.get(TargetOpcode::KILL));
486 DeadDefs.push_back(&MI);
487 ++NumSpillsRemoved;
488 if (HSpiller.rmFromMergeableSpills(MI, StackSlot))
489 --NumSpills;
490 }
491 }
492 } while (!WorkList.empty());
493 }
494
495 //===----------------------------------------------------------------------===//
496 // Rematerialization
497 //===----------------------------------------------------------------------===//
498
499 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
500 /// instruction cannot be eliminated. See through snippet copies
markValueUsed(LiveInterval * LI,VNInfo * VNI)501 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
502 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
503 WorkList.push_back(std::make_pair(LI, VNI));
504 do {
505 std::tie(LI, VNI) = WorkList.pop_back_val();
506 if (!UsedValues.insert(VNI).second)
507 continue;
508
509 if (VNI->isPHIDef()) {
510 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
511 for (MachineBasicBlock *P : MBB->predecessors()) {
512 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(P));
513 if (PVNI)
514 WorkList.push_back(std::make_pair(LI, PVNI));
515 }
516 continue;
517 }
518
519 // Follow snippet copies.
520 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
521 if (!SnippetCopies.count(MI))
522 continue;
523 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
524 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
525 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
526 assert(SnipVNI && "Snippet undefined before copy");
527 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
528 } while (!WorkList.empty());
529 }
530
canGuaranteeAssignmentAfterRemat(Register VReg,MachineInstr & MI)531 bool InlineSpiller::canGuaranteeAssignmentAfterRemat(Register VReg,
532 MachineInstr &MI) {
533 if (!RestrictStatepointRemat)
534 return true;
535 // Here's a quick explanation of the problem we're trying to handle here:
536 // * There are some pseudo instructions with more vreg uses than there are
537 // physical registers on the machine.
538 // * This is normally handled by spilling the vreg, and folding the reload
539 // into the user instruction. (Thus decreasing the number of used vregs
540 // until the remainder can be assigned to physregs.)
541 // * However, since we may try to spill vregs in any order, we can end up
542 // trying to spill each operand to the instruction, and then rematting it
543 // instead. When that happens, the new live intervals (for the remats) are
544 // expected to be trivially assignable (i.e. RS_Done). However, since we
545 // may have more remats than physregs, we're guaranteed to fail to assign
546 // one.
547 // At the moment, we only handle this for STATEPOINTs since they're the only
548 // pseudo op where we've seen this. If we start seeing other instructions
549 // with the same problem, we need to revisit this.
550 if (MI.getOpcode() != TargetOpcode::STATEPOINT)
551 return true;
552 // For STATEPOINTs we allow re-materialization for fixed arguments only hoping
553 // that number of physical registers is enough to cover all fixed arguments.
554 // If it is not true we need to revisit it.
555 for (unsigned Idx = StatepointOpers(&MI).getVarIdx(),
556 EndIdx = MI.getNumOperands();
557 Idx < EndIdx; ++Idx) {
558 MachineOperand &MO = MI.getOperand(Idx);
559 if (MO.isReg() && MO.getReg() == VReg)
560 return false;
561 }
562 return true;
563 }
564
565 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
reMaterializeFor(LiveInterval & VirtReg,MachineInstr & MI)566 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, MachineInstr &MI) {
567 // Analyze instruction
568 SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
569 VirtRegInfo RI = AnalyzeVirtRegInBundle(MI, VirtReg.reg, &Ops);
570
571 if (!RI.Reads)
572 return false;
573
574 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
575 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
576
577 if (!ParentVNI) {
578 LLVM_DEBUG(dbgs() << "\tadding <undef> flags: ");
579 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
580 MachineOperand &MO = MI.getOperand(i);
581 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
582 MO.setIsUndef();
583 }
584 LLVM_DEBUG(dbgs() << UseIdx << '\t' << MI);
585 return true;
586 }
587
588 if (SnippetCopies.count(&MI))
589 return false;
590
591 LiveInterval &OrigLI = LIS.getInterval(Original);
592 VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
593 LiveRangeEdit::Remat RM(ParentVNI);
594 RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def);
595
596 if (!Edit->canRematerializeAt(RM, OrigVNI, UseIdx, false)) {
597 markValueUsed(&VirtReg, ParentVNI);
598 LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
599 return false;
600 }
601
602 // If the instruction also writes VirtReg.reg, it had better not require the
603 // same register for uses and defs.
604 if (RI.Tied) {
605 markValueUsed(&VirtReg, ParentVNI);
606 LLVM_DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << MI);
607 return false;
608 }
609
610 // Before rematerializing into a register for a single instruction, try to
611 // fold a load into the instruction. That avoids allocating a new register.
612 if (RM.OrigMI->canFoldAsLoad() &&
613 foldMemoryOperand(Ops, RM.OrigMI)) {
614 Edit->markRematerialized(RM.ParentVNI);
615 ++NumFoldedLoads;
616 return true;
617 }
618
619 // If we can't guarantee that we'll be able to actually assign the new vreg,
620 // we can't remat.
621 if (!canGuaranteeAssignmentAfterRemat(VirtReg.reg, MI)) {
622 markValueUsed(&VirtReg, ParentVNI);
623 LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
624 return false;
625 }
626
627 // Allocate a new register for the remat.
628 Register NewVReg = Edit->createFrom(Original);
629
630 // Finally we can rematerialize OrigMI before MI.
631 SlotIndex DefIdx =
632 Edit->rematerializeAt(*MI.getParent(), MI, NewVReg, RM, TRI);
633
634 // We take the DebugLoc from MI, since OrigMI may be attributed to a
635 // different source location.
636 auto *NewMI = LIS.getInstructionFromIndex(DefIdx);
637 NewMI->setDebugLoc(MI.getDebugLoc());
638
639 (void)DefIdx;
640 LLVM_DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
641 << *LIS.getInstructionFromIndex(DefIdx));
642
643 // Replace operands
644 for (const auto &OpPair : Ops) {
645 MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
646 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
647 MO.setReg(NewVReg);
648 MO.setIsKill();
649 }
650 }
651 LLVM_DEBUG(dbgs() << "\t " << UseIdx << '\t' << MI << '\n');
652
653 ++NumRemats;
654 return true;
655 }
656
657 /// reMaterializeAll - Try to rematerialize as many uses as possible,
658 /// and trim the live ranges after.
reMaterializeAll()659 void InlineSpiller::reMaterializeAll() {
660 if (!Edit->anyRematerializable(AA))
661 return;
662
663 UsedValues.clear();
664
665 // Try to remat before all uses of snippets.
666 bool anyRemat = false;
667 for (Register Reg : RegsToSpill) {
668 LiveInterval &LI = LIS.getInterval(Reg);
669 for (MachineRegisterInfo::reg_bundle_iterator
670 RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
671 RegI != E; ) {
672 MachineInstr &MI = *RegI++;
673
674 // Debug values are not allowed to affect codegen.
675 if (MI.isDebugValue())
676 continue;
677
678 assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "
679 "instruction that isn't a DBG_VALUE");
680
681 anyRemat |= reMaterializeFor(LI, MI);
682 }
683 }
684 if (!anyRemat)
685 return;
686
687 // Remove any values that were completely rematted.
688 for (Register Reg : RegsToSpill) {
689 LiveInterval &LI = LIS.getInterval(Reg);
690 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
691 I != E; ++I) {
692 VNInfo *VNI = *I;
693 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
694 continue;
695 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
696 MI->addRegisterDead(Reg, &TRI);
697 if (!MI->allDefsAreDead())
698 continue;
699 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI);
700 DeadDefs.push_back(MI);
701 }
702 }
703
704 // Eliminate dead code after remat. Note that some snippet copies may be
705 // deleted here.
706 if (DeadDefs.empty())
707 return;
708 LLVM_DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
709 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
710
711 // LiveRangeEdit::eliminateDeadDef is used to remove dead define instructions
712 // after rematerialization. To remove a VNI for a vreg from its LiveInterval,
713 // LiveIntervals::removeVRegDefAt is used. However, after non-PHI VNIs are all
714 // removed, PHI VNI are still left in the LiveInterval.
715 // So to get rid of unused reg, we need to check whether it has non-dbg
716 // reference instead of whether it has non-empty interval.
717 unsigned ResultPos = 0;
718 for (Register Reg : RegsToSpill) {
719 if (MRI.reg_nodbg_empty(Reg)) {
720 Edit->eraseVirtReg(Reg);
721 continue;
722 }
723
724 assert(LIS.hasInterval(Reg) &&
725 (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&
726 "Empty and not used live-range?!");
727
728 RegsToSpill[ResultPos++] = Reg;
729 }
730 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
731 LLVM_DEBUG(dbgs() << RegsToSpill.size()
732 << " registers to spill after remat.\n");
733 }
734
735 //===----------------------------------------------------------------------===//
736 // Spilling
737 //===----------------------------------------------------------------------===//
738
739 /// If MI is a load or store of StackSlot, it can be removed.
coalesceStackAccess(MachineInstr * MI,Register Reg)740 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
741 int FI = 0;
742 Register InstrReg = TII.isLoadFromStackSlot(*MI, FI);
743 bool IsLoad = InstrReg;
744 if (!IsLoad)
745 InstrReg = TII.isStoreToStackSlot(*MI, FI);
746
747 // We have a stack access. Is it the right register and slot?
748 if (InstrReg != Reg || FI != StackSlot)
749 return false;
750
751 if (!IsLoad)
752 HSpiller.rmFromMergeableSpills(*MI, StackSlot);
753
754 LLVM_DEBUG(dbgs() << "Coalescing stack access: " << *MI);
755 LIS.RemoveMachineInstrFromMaps(*MI);
756 MI->eraseFromParent();
757
758 if (IsLoad) {
759 ++NumReloadsRemoved;
760 --NumReloads;
761 } else {
762 ++NumSpillsRemoved;
763 --NumSpills;
764 }
765
766 return true;
767 }
768
769 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
770 LLVM_DUMP_METHOD
771 // Dump the range of instructions from B to E with their slot indexes.
dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,MachineBasicBlock::iterator E,LiveIntervals const & LIS,const char * const header,Register VReg=Register ())772 static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
773 MachineBasicBlock::iterator E,
774 LiveIntervals const &LIS,
775 const char *const header,
776 Register VReg = Register()) {
777 char NextLine = '\n';
778 char SlotIndent = '\t';
779
780 if (std::next(B) == E) {
781 NextLine = ' ';
782 SlotIndent = ' ';
783 }
784
785 dbgs() << '\t' << header << ": " << NextLine;
786
787 for (MachineBasicBlock::iterator I = B; I != E; ++I) {
788 SlotIndex Idx = LIS.getInstructionIndex(*I).getRegSlot();
789
790 // If a register was passed in and this instruction has it as a
791 // destination that is marked as an early clobber, print the
792 // early-clobber slot index.
793 if (VReg) {
794 MachineOperand *MO = I->findRegisterDefOperand(VReg);
795 if (MO && MO->isEarlyClobber())
796 Idx = Idx.getRegSlot(true);
797 }
798
799 dbgs() << SlotIndent << Idx << '\t' << *I;
800 }
801 }
802 #endif
803
804 /// foldMemoryOperand - Try folding stack slot references in Ops into their
805 /// instructions.
806 ///
807 /// @param Ops Operand indices from AnalyzeVirtRegInBundle().
808 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
809 /// @return True on success.
810 bool InlineSpiller::
foldMemoryOperand(ArrayRef<std::pair<MachineInstr *,unsigned>> Ops,MachineInstr * LoadMI)811 foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>> Ops,
812 MachineInstr *LoadMI) {
813 if (Ops.empty())
814 return false;
815 // Don't attempt folding in bundles.
816 MachineInstr *MI = Ops.front().first;
817 if (Ops.back().first != MI || MI->isBundled())
818 return false;
819
820 bool WasCopy = MI->isCopy();
821 Register ImpReg;
822
823 // Spill subregs if the target allows it.
824 // We always want to spill subregs for stackmap/patchpoint pseudos.
825 bool SpillSubRegs = TII.isSubregFoldable() ||
826 MI->getOpcode() == TargetOpcode::STATEPOINT ||
827 MI->getOpcode() == TargetOpcode::PATCHPOINT ||
828 MI->getOpcode() == TargetOpcode::STACKMAP;
829
830 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
831 // operands.
832 SmallVector<unsigned, 8> FoldOps;
833 for (const auto &OpPair : Ops) {
834 unsigned Idx = OpPair.second;
835 assert(MI == OpPair.first && "Instruction conflict during operand folding");
836 MachineOperand &MO = MI->getOperand(Idx);
837 if (MO.isImplicit()) {
838 ImpReg = MO.getReg();
839 continue;
840 }
841
842 if (!SpillSubRegs && MO.getSubReg())
843 return false;
844 // We cannot fold a load instruction into a def.
845 if (LoadMI && MO.isDef())
846 return false;
847 // Tied use operands should not be passed to foldMemoryOperand.
848 if (!MI->isRegTiedToDefOperand(Idx))
849 FoldOps.push_back(Idx);
850 }
851
852 // If we only have implicit uses, we won't be able to fold that.
853 // Moreover, TargetInstrInfo::foldMemoryOperand will assert if we try!
854 if (FoldOps.empty())
855 return false;
856
857 MachineInstrSpan MIS(MI, MI->getParent());
858
859 MachineInstr *FoldMI =
860 LoadMI ? TII.foldMemoryOperand(*MI, FoldOps, *LoadMI, &LIS)
861 : TII.foldMemoryOperand(*MI, FoldOps, StackSlot, &LIS, &VRM);
862 if (!FoldMI)
863 return false;
864
865 // Remove LIS for any dead defs in the original MI not in FoldMI.
866 for (MIBundleOperands MO(*MI); MO.isValid(); ++MO) {
867 if (!MO->isReg())
868 continue;
869 Register Reg = MO->getReg();
870 if (!Reg || Register::isVirtualRegister(Reg) || MRI.isReserved(Reg)) {
871 continue;
872 }
873 // Skip non-Defs, including undef uses and internal reads.
874 if (MO->isUse())
875 continue;
876 PhysRegInfo RI = AnalyzePhysRegInBundle(*FoldMI, Reg, &TRI);
877 if (RI.FullyDefined)
878 continue;
879 // FoldMI does not define this physreg. Remove the LI segment.
880 assert(MO->isDead() && "Cannot fold physreg def");
881 SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
882 LIS.removePhysRegDefAt(Reg, Idx);
883 }
884
885 int FI;
886 if (TII.isStoreToStackSlot(*MI, FI) &&
887 HSpiller.rmFromMergeableSpills(*MI, FI))
888 --NumSpills;
889 LIS.ReplaceMachineInstrInMaps(*MI, *FoldMI);
890 // Update the call site info.
891 if (MI->isCandidateForCallSiteEntry())
892 MI->getMF()->moveCallSiteInfo(MI, FoldMI);
893 MI->eraseFromParent();
894
895 // Insert any new instructions other than FoldMI into the LIS maps.
896 assert(!MIS.empty() && "Unexpected empty span of instructions!");
897 for (MachineInstr &MI : MIS)
898 if (&MI != FoldMI)
899 LIS.InsertMachineInstrInMaps(MI);
900
901 // TII.foldMemoryOperand may have left some implicit operands on the
902 // instruction. Strip them.
903 if (ImpReg)
904 for (unsigned i = FoldMI->getNumOperands(); i; --i) {
905 MachineOperand &MO = FoldMI->getOperand(i - 1);
906 if (!MO.isReg() || !MO.isImplicit())
907 break;
908 if (MO.getReg() == ImpReg)
909 FoldMI->RemoveOperand(i - 1);
910 }
911
912 LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
913 "folded"));
914
915 if (!WasCopy)
916 ++NumFolded;
917 else if (Ops.front().second == 0) {
918 ++NumSpills;
919 HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original);
920 } else
921 ++NumReloads;
922 return true;
923 }
924
insertReload(Register NewVReg,SlotIndex Idx,MachineBasicBlock::iterator MI)925 void InlineSpiller::insertReload(Register NewVReg,
926 SlotIndex Idx,
927 MachineBasicBlock::iterator MI) {
928 MachineBasicBlock &MBB = *MI->getParent();
929
930 MachineInstrSpan MIS(MI, &MBB);
931 TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
932 MRI.getRegClass(NewVReg), &TRI);
933
934 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
935
936 LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
937 NewVReg));
938 ++NumReloads;
939 }
940
941 /// Check if \p Def fully defines a VReg with an undefined value.
942 /// If that's the case, that means the value of VReg is actually
943 /// not relevant.
isRealSpill(const MachineInstr & Def)944 static bool isRealSpill(const MachineInstr &Def) {
945 if (!Def.isImplicitDef())
946 return true;
947 assert(Def.getNumOperands() == 1 &&
948 "Implicit def with more than one definition");
949 // We can say that the VReg defined by Def is undef, only if it is
950 // fully defined by Def. Otherwise, some of the lanes may not be
951 // undef and the value of the VReg matters.
952 return Def.getOperand(0).getSubReg();
953 }
954
955 /// insertSpill - Insert a spill of NewVReg after MI.
insertSpill(Register NewVReg,bool isKill,MachineBasicBlock::iterator MI)956 void InlineSpiller::insertSpill(Register NewVReg, bool isKill,
957 MachineBasicBlock::iterator MI) {
958 // Spill are not terminators, so inserting spills after terminators will
959 // violate invariants in MachineVerifier.
960 assert(!MI->isTerminator() && "Inserting a spill after a terminator");
961 MachineBasicBlock &MBB = *MI->getParent();
962
963 MachineInstrSpan MIS(MI, &MBB);
964 MachineBasicBlock::iterator SpillBefore = std::next(MI);
965 bool IsRealSpill = isRealSpill(*MI);
966 if (IsRealSpill)
967 TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, isKill, StackSlot,
968 MRI.getRegClass(NewVReg), &TRI);
969 else
970 // Don't spill undef value.
971 // Anything works for undef, in particular keeping the memory
972 // uninitialized is a viable option and it saves code size and
973 // run time.
974 BuildMI(MBB, SpillBefore, MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
975 .addReg(NewVReg, getKillRegState(isKill));
976
977 MachineBasicBlock::iterator Spill = std::next(MI);
978 LIS.InsertMachineInstrRangeInMaps(Spill, MIS.end());
979
980 LLVM_DEBUG(
981 dumpMachineInstrRangeWithSlotIndex(Spill, MIS.end(), LIS, "spill"));
982 ++NumSpills;
983 if (IsRealSpill)
984 HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
985 }
986
987 /// spillAroundUses - insert spill code around each use of Reg.
spillAroundUses(Register Reg)988 void InlineSpiller::spillAroundUses(Register Reg) {
989 LLVM_DEBUG(dbgs() << "spillAroundUses " << printReg(Reg) << '\n');
990 LiveInterval &OldLI = LIS.getInterval(Reg);
991
992 // Iterate over instructions using Reg.
993 for (MachineRegisterInfo::reg_bundle_iterator
994 RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
995 RegI != E; ) {
996 MachineInstr *MI = &*(RegI++);
997
998 // Debug values are not allowed to affect codegen.
999 if (MI->isDebugValue()) {
1000 // Modify DBG_VALUE now that the value is in a spill slot.
1001 MachineBasicBlock *MBB = MI->getParent();
1002 LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:\t" << *MI);
1003 buildDbgValueForSpill(*MBB, MI, *MI, StackSlot);
1004 MBB->erase(MI);
1005 continue;
1006 }
1007
1008 assert(!MI->isDebugInstr() && "Did not expect to find a use in debug "
1009 "instruction that isn't a DBG_VALUE");
1010
1011 // Ignore copies to/from snippets. We'll delete them.
1012 if (SnippetCopies.count(MI))
1013 continue;
1014
1015 // Stack slot accesses may coalesce away.
1016 if (coalesceStackAccess(MI, Reg))
1017 continue;
1018
1019 // Analyze instruction.
1020 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
1021 VirtRegInfo RI = AnalyzeVirtRegInBundle(*MI, Reg, &Ops);
1022
1023 // Find the slot index where this instruction reads and writes OldLI.
1024 // This is usually the def slot, except for tied early clobbers.
1025 SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
1026 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1027 if (SlotIndex::isSameInstr(Idx, VNI->def))
1028 Idx = VNI->def;
1029
1030 // Check for a sibling copy.
1031 Register SibReg = isFullCopyOf(*MI, Reg);
1032 if (SibReg && isSibling(SibReg)) {
1033 // This may actually be a copy between snippets.
1034 if (isRegToSpill(SibReg)) {
1035 LLVM_DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1036 SnippetCopies.insert(MI);
1037 continue;
1038 }
1039 if (RI.Writes) {
1040 if (hoistSpillInsideBB(OldLI, *MI)) {
1041 // This COPY is now dead, the value is already in the stack slot.
1042 MI->getOperand(0).setIsDead();
1043 DeadDefs.push_back(MI);
1044 continue;
1045 }
1046 } else {
1047 // This is a reload for a sib-reg copy. Drop spills downstream.
1048 LiveInterval &SibLI = LIS.getInterval(SibReg);
1049 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1050 // The COPY will fold to a reload below.
1051 }
1052 }
1053
1054 // Attempt to fold memory ops.
1055 if (foldMemoryOperand(Ops))
1056 continue;
1057
1058 // Create a new virtual register for spill/fill.
1059 // FIXME: Infer regclass from instruction alone.
1060 Register NewVReg = Edit->createFrom(Reg);
1061
1062 if (RI.Reads)
1063 insertReload(NewVReg, Idx, MI);
1064
1065 // Rewrite instruction operands.
1066 bool hasLiveDef = false;
1067 for (const auto &OpPair : Ops) {
1068 MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
1069 MO.setReg(NewVReg);
1070 if (MO.isUse()) {
1071 if (!OpPair.first->isRegTiedToDefOperand(OpPair.second))
1072 MO.setIsKill();
1073 } else {
1074 if (!MO.isDead())
1075 hasLiveDef = true;
1076 }
1077 }
1078 LLVM_DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n');
1079
1080 // FIXME: Use a second vreg if instruction has no tied ops.
1081 if (RI.Writes)
1082 if (hasLiveDef)
1083 insertSpill(NewVReg, true, MI);
1084 }
1085 }
1086
1087 /// spillAll - Spill all registers remaining after rematerialization.
spillAll()1088 void InlineSpiller::spillAll() {
1089 // Update LiveStacks now that we are committed to spilling.
1090 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1091 StackSlot = VRM.assignVirt2StackSlot(Original);
1092 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1093 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1094 } else
1095 StackInt = &LSS.getInterval(StackSlot);
1096
1097 if (Original != Edit->getReg())
1098 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1099
1100 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1101 for (Register Reg : RegsToSpill)
1102 StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
1103 StackInt->getValNumInfo(0));
1104 LLVM_DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1105
1106 // Spill around uses of all RegsToSpill.
1107 for (Register Reg : RegsToSpill)
1108 spillAroundUses(Reg);
1109
1110 // Hoisted spills may cause dead code.
1111 if (!DeadDefs.empty()) {
1112 LLVM_DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1113 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
1114 }
1115
1116 // Finally delete the SnippetCopies.
1117 for (Register Reg : RegsToSpill) {
1118 for (MachineRegisterInfo::reg_instr_iterator
1119 RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end();
1120 RI != E; ) {
1121 MachineInstr &MI = *(RI++);
1122 assert(SnippetCopies.count(&MI) && "Remaining use wasn't a snippet copy");
1123 // FIXME: Do this with a LiveRangeEdit callback.
1124 LIS.RemoveMachineInstrFromMaps(MI);
1125 MI.eraseFromParent();
1126 }
1127 }
1128
1129 // Delete all spilled registers.
1130 for (Register Reg : RegsToSpill)
1131 Edit->eraseVirtReg(Reg);
1132 }
1133
spill(LiveRangeEdit & edit)1134 void InlineSpiller::spill(LiveRangeEdit &edit) {
1135 ++NumSpilledRanges;
1136 Edit = &edit;
1137 assert(!Register::isStackSlot(edit.getReg()) &&
1138 "Trying to spill a stack slot.");
1139 // Share a stack slot among all descendants of Original.
1140 Original = VRM.getOriginal(edit.getReg());
1141 StackSlot = VRM.getStackSlot(Original);
1142 StackInt = nullptr;
1143
1144 LLVM_DEBUG(dbgs() << "Inline spilling "
1145 << TRI.getRegClassName(MRI.getRegClass(edit.getReg()))
1146 << ':' << edit.getParent() << "\nFrom original "
1147 << printReg(Original) << '\n');
1148 assert(edit.getParent().isSpillable() &&
1149 "Attempting to spill already spilled value.");
1150 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1151
1152 collectRegsToSpill();
1153 reMaterializeAll();
1154
1155 // Remat may handle everything.
1156 if (!RegsToSpill.empty())
1157 spillAll();
1158
1159 Edit->calculateRegClassAndHint(MF, Loops, MBFI);
1160 }
1161
1162 /// Optimizations after all the reg selections and spills are done.
postOptimization()1163 void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
1164
1165 /// When a spill is inserted, add the spill to MergeableSpills map.
addToMergeableSpills(MachineInstr & Spill,int StackSlot,unsigned Original)1166 void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
1167 unsigned Original) {
1168 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
1169 LiveInterval &OrigLI = LIS.getInterval(Original);
1170 // save a copy of LiveInterval in StackSlotToOrigLI because the original
1171 // LiveInterval may be cleared after all its references are spilled.
1172 if (StackSlotToOrigLI.find(StackSlot) == StackSlotToOrigLI.end()) {
1173 auto LI = std::make_unique<LiveInterval>(OrigLI.reg, OrigLI.weight);
1174 LI->assign(OrigLI, Allocator);
1175 StackSlotToOrigLI[StackSlot] = std::move(LI);
1176 }
1177 SlotIndex Idx = LIS.getInstructionIndex(Spill);
1178 VNInfo *OrigVNI = StackSlotToOrigLI[StackSlot]->getVNInfoAt(Idx.getRegSlot());
1179 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1180 MergeableSpills[MIdx].insert(&Spill);
1181 }
1182
1183 /// When a spill is removed, remove the spill from MergeableSpills map.
1184 /// Return true if the spill is removed successfully.
rmFromMergeableSpills(MachineInstr & Spill,int StackSlot)1185 bool HoistSpillHelper::rmFromMergeableSpills(MachineInstr &Spill,
1186 int StackSlot) {
1187 auto It = StackSlotToOrigLI.find(StackSlot);
1188 if (It == StackSlotToOrigLI.end())
1189 return false;
1190 SlotIndex Idx = LIS.getInstructionIndex(Spill);
1191 VNInfo *OrigVNI = It->second->getVNInfoAt(Idx.getRegSlot());
1192 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1193 return MergeableSpills[MIdx].erase(&Spill);
1194 }
1195
1196 /// Check BB to see if it is a possible target BB to place a hoisted spill,
1197 /// i.e., there should be a living sibling of OrigReg at the insert point.
isSpillCandBB(LiveInterval & OrigLI,VNInfo & OrigVNI,MachineBasicBlock & BB,Register & LiveReg)1198 bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
1199 MachineBasicBlock &BB, Register &LiveReg) {
1200 SlotIndex Idx;
1201 Register OrigReg = OrigLI.reg;
1202 MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, BB);
1203 if (MI != BB.end())
1204 Idx = LIS.getInstructionIndex(*MI);
1205 else
1206 Idx = LIS.getMBBEndIdx(&BB).getPrevSlot();
1207 SmallSetVector<Register, 16> &Siblings = Virt2SiblingsMap[OrigReg];
1208 assert(OrigLI.getVNInfoAt(Idx) == &OrigVNI && "Unexpected VNI");
1209
1210 for (const Register &SibReg : Siblings) {
1211 LiveInterval &LI = LIS.getInterval(SibReg);
1212 VNInfo *VNI = LI.getVNInfoAt(Idx);
1213 if (VNI) {
1214 LiveReg = SibReg;
1215 return true;
1216 }
1217 }
1218 return false;
1219 }
1220
1221 /// Remove redundant spills in the same BB. Save those redundant spills in
1222 /// SpillsToRm, and save the spill to keep and its BB in SpillBBToSpill map.
rmRedundantSpills(SmallPtrSet<MachineInstr *,16> & Spills,SmallVectorImpl<MachineInstr * > & SpillsToRm,DenseMap<MachineDomTreeNode *,MachineInstr * > & SpillBBToSpill)1223 void HoistSpillHelper::rmRedundantSpills(
1224 SmallPtrSet<MachineInstr *, 16> &Spills,
1225 SmallVectorImpl<MachineInstr *> &SpillsToRm,
1226 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
1227 // For each spill saw, check SpillBBToSpill[] and see if its BB already has
1228 // another spill inside. If a BB contains more than one spill, only keep the
1229 // earlier spill with smaller SlotIndex.
1230 for (const auto CurrentSpill : Spills) {
1231 MachineBasicBlock *Block = CurrentSpill->getParent();
1232 MachineDomTreeNode *Node = MDT.getBase().getNode(Block);
1233 MachineInstr *PrevSpill = SpillBBToSpill[Node];
1234 if (PrevSpill) {
1235 SlotIndex PIdx = LIS.getInstructionIndex(*PrevSpill);
1236 SlotIndex CIdx = LIS.getInstructionIndex(*CurrentSpill);
1237 MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill;
1238 MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill;
1239 SpillsToRm.push_back(SpillToRm);
1240 SpillBBToSpill[MDT.getBase().getNode(Block)] = SpillToKeep;
1241 } else {
1242 SpillBBToSpill[MDT.getBase().getNode(Block)] = CurrentSpill;
1243 }
1244 }
1245 for (const auto SpillToRm : SpillsToRm)
1246 Spills.erase(SpillToRm);
1247 }
1248
1249 /// Starting from \p Root find a top-down traversal order of the dominator
1250 /// tree to visit all basic blocks containing the elements of \p Spills.
1251 /// Redundant spills will be found and put into \p SpillsToRm at the same
1252 /// time. \p SpillBBToSpill will be populated as part of the process and
1253 /// maps a basic block to the first store occurring in the basic block.
1254 /// \post SpillsToRm.union(Spills\@post) == Spills\@pre
getVisitOrders(MachineBasicBlock * Root,SmallPtrSet<MachineInstr *,16> & Spills,SmallVectorImpl<MachineDomTreeNode * > & Orders,SmallVectorImpl<MachineInstr * > & SpillsToRm,DenseMap<MachineDomTreeNode *,unsigned> & SpillsToKeep,DenseMap<MachineDomTreeNode *,MachineInstr * > & SpillBBToSpill)1255 void HoistSpillHelper::getVisitOrders(
1256 MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
1257 SmallVectorImpl<MachineDomTreeNode *> &Orders,
1258 SmallVectorImpl<MachineInstr *> &SpillsToRm,
1259 DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
1260 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
1261 // The set contains all the possible BB nodes to which we may hoist
1262 // original spills.
1263 SmallPtrSet<MachineDomTreeNode *, 8> WorkSet;
1264 // Save the BB nodes on the path from the first BB node containing
1265 // non-redundant spill to the Root node.
1266 SmallPtrSet<MachineDomTreeNode *, 8> NodesOnPath;
1267 // All the spills to be hoisted must originate from a single def instruction
1268 // to the OrigReg. It means the def instruction should dominate all the spills
1269 // to be hoisted. We choose the BB where the def instruction is located as
1270 // the Root.
1271 MachineDomTreeNode *RootIDomNode = MDT[Root]->getIDom();
1272 // For every node on the dominator tree with spill, walk up on the dominator
1273 // tree towards the Root node until it is reached. If there is other node
1274 // containing spill in the middle of the path, the previous spill saw will
1275 // be redundant and the node containing it will be removed. All the nodes on
1276 // the path starting from the first node with non-redundant spill to the Root
1277 // node will be added to the WorkSet, which will contain all the possible
1278 // locations where spills may be hoisted to after the loop below is done.
1279 for (const auto Spill : Spills) {
1280 MachineBasicBlock *Block = Spill->getParent();
1281 MachineDomTreeNode *Node = MDT[Block];
1282 MachineInstr *SpillToRm = nullptr;
1283 while (Node != RootIDomNode) {
1284 // If Node dominates Block, and it already contains a spill, the spill in
1285 // Block will be redundant.
1286 if (Node != MDT[Block] && SpillBBToSpill[Node]) {
1287 SpillToRm = SpillBBToSpill[MDT[Block]];
1288 break;
1289 /// If we see the Node already in WorkSet, the path from the Node to
1290 /// the Root node must already be traversed by another spill.
1291 /// Then no need to repeat.
1292 } else if (WorkSet.count(Node)) {
1293 break;
1294 } else {
1295 NodesOnPath.insert(Node);
1296 }
1297 Node = Node->getIDom();
1298 }
1299 if (SpillToRm) {
1300 SpillsToRm.push_back(SpillToRm);
1301 } else {
1302 // Add a BB containing the original spills to SpillsToKeep -- i.e.,
1303 // set the initial status before hoisting start. The value of BBs
1304 // containing original spills is set to 0, in order to descriminate
1305 // with BBs containing hoisted spills which will be inserted to
1306 // SpillsToKeep later during hoisting.
1307 SpillsToKeep[MDT[Block]] = 0;
1308 WorkSet.insert(NodesOnPath.begin(), NodesOnPath.end());
1309 }
1310 NodesOnPath.clear();
1311 }
1312
1313 // Sort the nodes in WorkSet in top-down order and save the nodes
1314 // in Orders. Orders will be used for hoisting in runHoistSpills.
1315 unsigned idx = 0;
1316 Orders.push_back(MDT.getBase().getNode(Root));
1317 do {
1318 MachineDomTreeNode *Node = Orders[idx++];
1319 for (MachineDomTreeNode *Child : Node->children()) {
1320 if (WorkSet.count(Child))
1321 Orders.push_back(Child);
1322 }
1323 } while (idx != Orders.size());
1324 assert(Orders.size() == WorkSet.size() &&
1325 "Orders have different size with WorkSet");
1326
1327 #ifndef NDEBUG
1328 LLVM_DEBUG(dbgs() << "Orders size is " << Orders.size() << "\n");
1329 SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
1330 for (; RIt != Orders.rend(); RIt++)
1331 LLVM_DEBUG(dbgs() << "BB" << (*RIt)->getBlock()->getNumber() << ",");
1332 LLVM_DEBUG(dbgs() << "\n");
1333 #endif
1334 }
1335
1336 /// Try to hoist spills according to BB hotness. The spills to removed will
1337 /// be saved in \p SpillsToRm. The spills to be inserted will be saved in
1338 /// \p SpillsToIns.
runHoistSpills(LiveInterval & OrigLI,VNInfo & OrigVNI,SmallPtrSet<MachineInstr *,16> & Spills,SmallVectorImpl<MachineInstr * > & SpillsToRm,DenseMap<MachineBasicBlock *,unsigned> & SpillsToIns)1339 void HoistSpillHelper::runHoistSpills(
1340 LiveInterval &OrigLI, VNInfo &OrigVNI,
1341 SmallPtrSet<MachineInstr *, 16> &Spills,
1342 SmallVectorImpl<MachineInstr *> &SpillsToRm,
1343 DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns) {
1344 // Visit order of dominator tree nodes.
1345 SmallVector<MachineDomTreeNode *, 32> Orders;
1346 // SpillsToKeep contains all the nodes where spills are to be inserted
1347 // during hoisting. If the spill to be inserted is an original spill
1348 // (not a hoisted one), the value of the map entry is 0. If the spill
1349 // is a hoisted spill, the value of the map entry is the VReg to be used
1350 // as the source of the spill.
1351 DenseMap<MachineDomTreeNode *, unsigned> SpillsToKeep;
1352 // Map from BB to the first spill inside of it.
1353 DenseMap<MachineDomTreeNode *, MachineInstr *> SpillBBToSpill;
1354
1355 rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill);
1356
1357 MachineBasicBlock *Root = LIS.getMBBFromIndex(OrigVNI.def);
1358 getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep,
1359 SpillBBToSpill);
1360
1361 // SpillsInSubTreeMap keeps the map from a dom tree node to a pair of
1362 // nodes set and the cost of all the spills inside those nodes.
1363 // The nodes set are the locations where spills are to be inserted
1364 // in the subtree of current node.
1365 using NodesCostPair =
1366 std::pair<SmallPtrSet<MachineDomTreeNode *, 16>, BlockFrequency>;
1367 DenseMap<MachineDomTreeNode *, NodesCostPair> SpillsInSubTreeMap;
1368
1369 // Iterate Orders set in reverse order, which will be a bottom-up order
1370 // in the dominator tree. Once we visit a dom tree node, we know its
1371 // children have already been visited and the spill locations in the
1372 // subtrees of all the children have been determined.
1373 SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
1374 for (; RIt != Orders.rend(); RIt++) {
1375 MachineBasicBlock *Block = (*RIt)->getBlock();
1376
1377 // If Block contains an original spill, simply continue.
1378 if (SpillsToKeep.find(*RIt) != SpillsToKeep.end() && !SpillsToKeep[*RIt]) {
1379 SpillsInSubTreeMap[*RIt].first.insert(*RIt);
1380 // SpillsInSubTreeMap[*RIt].second contains the cost of spill.
1381 SpillsInSubTreeMap[*RIt].second = MBFI.getBlockFreq(Block);
1382 continue;
1383 }
1384
1385 // Collect spills in subtree of current node (*RIt) to
1386 // SpillsInSubTreeMap[*RIt].first.
1387 for (MachineDomTreeNode *Child : (*RIt)->children()) {
1388 if (SpillsInSubTreeMap.find(Child) == SpillsInSubTreeMap.end())
1389 continue;
1390 // The stmt "SpillsInSubTree = SpillsInSubTreeMap[*RIt].first" below
1391 // should be placed before getting the begin and end iterators of
1392 // SpillsInSubTreeMap[Child].first, or else the iterators may be
1393 // invalidated when SpillsInSubTreeMap[*RIt] is seen the first time
1394 // and the map grows and then the original buckets in the map are moved.
1395 SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
1396 SpillsInSubTreeMap[*RIt].first;
1397 BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
1398 SubTreeCost += SpillsInSubTreeMap[Child].second;
1399 auto BI = SpillsInSubTreeMap[Child].first.begin();
1400 auto EI = SpillsInSubTreeMap[Child].first.end();
1401 SpillsInSubTree.insert(BI, EI);
1402 SpillsInSubTreeMap.erase(Child);
1403 }
1404
1405 SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
1406 SpillsInSubTreeMap[*RIt].first;
1407 BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
1408 // No spills in subtree, simply continue.
1409 if (SpillsInSubTree.empty())
1410 continue;
1411
1412 // Check whether Block is a possible candidate to insert spill.
1413 Register LiveReg;
1414 if (!isSpillCandBB(OrigLI, OrigVNI, *Block, LiveReg))
1415 continue;
1416
1417 // If there are multiple spills that could be merged, bias a little
1418 // to hoist the spill.
1419 BranchProbability MarginProb = (SpillsInSubTree.size() > 1)
1420 ? BranchProbability(9, 10)
1421 : BranchProbability(1, 1);
1422 if (SubTreeCost > MBFI.getBlockFreq(Block) * MarginProb) {
1423 // Hoist: Move spills to current Block.
1424 for (const auto SpillBB : SpillsInSubTree) {
1425 // When SpillBB is a BB contains original spill, insert the spill
1426 // to SpillsToRm.
1427 if (SpillsToKeep.find(SpillBB) != SpillsToKeep.end() &&
1428 !SpillsToKeep[SpillBB]) {
1429 MachineInstr *SpillToRm = SpillBBToSpill[SpillBB];
1430 SpillsToRm.push_back(SpillToRm);
1431 }
1432 // SpillBB will not contain spill anymore, remove it from SpillsToKeep.
1433 SpillsToKeep.erase(SpillBB);
1434 }
1435 // Current Block is the BB containing the new hoisted spill. Add it to
1436 // SpillsToKeep. LiveReg is the source of the new spill.
1437 SpillsToKeep[*RIt] = LiveReg;
1438 LLVM_DEBUG({
1439 dbgs() << "spills in BB: ";
1440 for (const auto Rspill : SpillsInSubTree)
1441 dbgs() << Rspill->getBlock()->getNumber() << " ";
1442 dbgs() << "were promoted to BB" << (*RIt)->getBlock()->getNumber()
1443 << "\n";
1444 });
1445 SpillsInSubTree.clear();
1446 SpillsInSubTree.insert(*RIt);
1447 SubTreeCost = MBFI.getBlockFreq(Block);
1448 }
1449 }
1450 // For spills in SpillsToKeep with LiveReg set (i.e., not original spill),
1451 // save them to SpillsToIns.
1452 for (const auto &Ent : SpillsToKeep) {
1453 if (Ent.second)
1454 SpillsToIns[Ent.first->getBlock()] = Ent.second;
1455 }
1456 }
1457
1458 /// For spills with equal values, remove redundant spills and hoist those left
1459 /// to less hot spots.
1460 ///
1461 /// Spills with equal values will be collected into the same set in
1462 /// MergeableSpills when spill is inserted. These equal spills are originated
1463 /// from the same defining instruction and are dominated by the instruction.
1464 /// Before hoisting all the equal spills, redundant spills inside in the same
1465 /// BB are first marked to be deleted. Then starting from the spills left, walk
1466 /// up on the dominator tree towards the Root node where the define instruction
1467 /// is located, mark the dominated spills to be deleted along the way and
1468 /// collect the BB nodes on the path from non-dominated spills to the define
1469 /// instruction into a WorkSet. The nodes in WorkSet are the candidate places
1470 /// where we are considering to hoist the spills. We iterate the WorkSet in
1471 /// bottom-up order, and for each node, we will decide whether to hoist spills
1472 /// inside its subtree to that node. In this way, we can get benefit locally
1473 /// even if hoisting all the equal spills to one cold place is impossible.
hoistAllSpills()1474 void HoistSpillHelper::hoistAllSpills() {
1475 SmallVector<Register, 4> NewVRegs;
1476 LiveRangeEdit Edit(nullptr, NewVRegs, MF, LIS, &VRM, this);
1477
1478 for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
1479 Register Reg = Register::index2VirtReg(i);
1480 Register Original = VRM.getPreSplitReg(Reg);
1481 if (!MRI.def_empty(Reg))
1482 Virt2SiblingsMap[Original].insert(Reg);
1483 }
1484
1485 // Each entry in MergeableSpills contains a spill set with equal values.
1486 for (auto &Ent : MergeableSpills) {
1487 int Slot = Ent.first.first;
1488 LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
1489 VNInfo *OrigVNI = Ent.first.second;
1490 SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
1491 if (Ent.second.empty())
1492 continue;
1493
1494 LLVM_DEBUG({
1495 dbgs() << "\nFor Slot" << Slot << " and VN" << OrigVNI->id << ":\n"
1496 << "Equal spills in BB: ";
1497 for (const auto spill : EqValSpills)
1498 dbgs() << spill->getParent()->getNumber() << " ";
1499 dbgs() << "\n";
1500 });
1501
1502 // SpillsToRm is the spill set to be removed from EqValSpills.
1503 SmallVector<MachineInstr *, 16> SpillsToRm;
1504 // SpillsToIns is the spill set to be newly inserted after hoisting.
1505 DenseMap<MachineBasicBlock *, unsigned> SpillsToIns;
1506
1507 runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns);
1508
1509 LLVM_DEBUG({
1510 dbgs() << "Finally inserted spills in BB: ";
1511 for (const auto &Ispill : SpillsToIns)
1512 dbgs() << Ispill.first->getNumber() << " ";
1513 dbgs() << "\nFinally removed spills in BB: ";
1514 for (const auto Rspill : SpillsToRm)
1515 dbgs() << Rspill->getParent()->getNumber() << " ";
1516 dbgs() << "\n";
1517 });
1518
1519 // Stack live range update.
1520 LiveInterval &StackIntvl = LSS.getInterval(Slot);
1521 if (!SpillsToIns.empty() || !SpillsToRm.empty())
1522 StackIntvl.MergeValueInAsValue(OrigLI, OrigVNI,
1523 StackIntvl.getValNumInfo(0));
1524
1525 // Insert hoisted spills.
1526 for (auto const &Insert : SpillsToIns) {
1527 MachineBasicBlock *BB = Insert.first;
1528 Register LiveReg = Insert.second;
1529 MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, *BB);
1530 TII.storeRegToStackSlot(*BB, MI, LiveReg, false, Slot,
1531 MRI.getRegClass(LiveReg), &TRI);
1532 LIS.InsertMachineInstrRangeInMaps(std::prev(MI), MI);
1533 ++NumSpills;
1534 }
1535
1536 // Remove redundant spills or change them to dead instructions.
1537 NumSpills -= SpillsToRm.size();
1538 for (auto const RMEnt : SpillsToRm) {
1539 RMEnt->setDesc(TII.get(TargetOpcode::KILL));
1540 for (unsigned i = RMEnt->getNumOperands(); i; --i) {
1541 MachineOperand &MO = RMEnt->getOperand(i - 1);
1542 if (MO.isReg() && MO.isImplicit() && MO.isDef() && !MO.isDead())
1543 RMEnt->RemoveOperand(i - 1);
1544 }
1545 }
1546 Edit.eliminateDeadDefs(SpillsToRm, None, AA);
1547 }
1548 }
1549
1550 /// For VirtReg clone, the \p New register should have the same physreg or
1551 /// stackslot as the \p old register.
LRE_DidCloneVirtReg(unsigned New,unsigned Old)1552 void HoistSpillHelper::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
1553 if (VRM.hasPhys(Old))
1554 VRM.assignVirt2Phys(New, VRM.getPhys(Old));
1555 else if (VRM.getStackSlot(Old) != VirtRegMap::NO_STACK_SLOT)
1556 VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old));
1557 else
1558 llvm_unreachable("VReg should be assigned either physreg or stackslot");
1559 }
1560