12cab237bSDimitry Andric //===- InlineSpiller.cpp - Insert spills and restores inline --------------===//
2ffd1746dSEd Schouten //
3ffd1746dSEd Schouten // The LLVM Compiler Infrastructure
4ffd1746dSEd Schouten //
5ffd1746dSEd Schouten // This file is distributed under the University of Illinois Open Source
6ffd1746dSEd Schouten // License. See LICENSE.TXT for details.
7ffd1746dSEd Schouten //
8ffd1746dSEd Schouten //===----------------------------------------------------------------------===//
9ffd1746dSEd Schouten //
10ffd1746dSEd Schouten // The inline spiller modifies the machine function directly instead of
11ffd1746dSEd Schouten // inserting spills and restores in VirtRegMap.
12ffd1746dSEd Schouten //
13ffd1746dSEd Schouten //===----------------------------------------------------------------------===//
14ffd1746dSEd Schouten
152cab237bSDimitry Andric #include "LiveRangeCalc.h"
16ffd1746dSEd Schouten #include "Spiller.h"
173ca95b02SDimitry Andric #include "SplitKit.h"
182cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
192cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
203ca95b02SDimitry Andric #include "llvm/ADT/MapVector.h"
212cab237bSDimitry Andric #include "llvm/ADT/None.h"
222cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
23f785676fSDimitry Andric #include "llvm/ADT/SetVector.h"
242cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
252cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
26bd5abe19SDimitry Andric #include "llvm/ADT/Statistic.h"
272754fe60SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
282cab237bSDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
292cab237bSDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
30dff0c46cSDimitry Andric #include "llvm/CodeGen/LiveRangeEdit.h"
31da09e106SDimitry Andric #include "llvm/CodeGen/LiveStacks.h"
322cab237bSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
33f785676fSDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
3491bc56edSDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
35ffd1746dSEd Schouten #include "llvm/CodeGen/MachineFunction.h"
362cab237bSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
372cab237bSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
38f785676fSDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
39139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h"
403b0f4066SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
412cab237bSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
42ffd1746dSEd Schouten #include "llvm/CodeGen/MachineRegisterInfo.h"
432cab237bSDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
442cab237bSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
452cab237bSDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
462cab237bSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
472cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
48139f7f9bSDimitry Andric #include "llvm/CodeGen/VirtRegMap.h"
49*4ba319b5SDimitry Andric #include "llvm/Config/llvm-config.h"
502cab237bSDimitry Andric #include "llvm/Support/BlockFrequency.h"
512cab237bSDimitry Andric #include "llvm/Support/BranchProbability.h"
526122f3e6SDimitry Andric #include "llvm/Support/CommandLine.h"
532cab237bSDimitry Andric #include "llvm/Support/Compiler.h"
54ffd1746dSEd Schouten #include "llvm/Support/Debug.h"
552cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
56ffd1746dSEd Schouten #include "llvm/Support/raw_ostream.h"
572cab237bSDimitry Andric #include <cassert>
582cab237bSDimitry Andric #include <iterator>
592cab237bSDimitry Andric #include <tuple>
602cab237bSDimitry Andric #include <utility>
612cab237bSDimitry Andric #include <vector>
62ffd1746dSEd Schouten
63ffd1746dSEd Schouten using namespace llvm;
64ffd1746dSEd Schouten
6591bc56edSDimitry Andric #define DEBUG_TYPE "regalloc"
6691bc56edSDimitry Andric
67bd5abe19SDimitry Andric STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
686122f3e6SDimitry Andric STATISTIC(NumSnippets, "Number of spilled snippets");
69bd5abe19SDimitry Andric STATISTIC(NumSpills, "Number of spills inserted");
706122f3e6SDimitry Andric STATISTIC(NumSpillsRemoved, "Number of spills removed");
71bd5abe19SDimitry Andric STATISTIC(NumReloads, "Number of reloads inserted");
726122f3e6SDimitry Andric STATISTIC(NumReloadsRemoved, "Number of reloads removed");
73bd5abe19SDimitry Andric STATISTIC(NumFolded, "Number of folded stack accesses");
74bd5abe19SDimitry Andric STATISTIC(NumFoldedLoads, "Number of folded loads");
75bd5abe19SDimitry Andric STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
766122f3e6SDimitry Andric
776122f3e6SDimitry Andric static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
786122f3e6SDimitry Andric cl::desc("Disable inline spill hoisting"));
79bd5abe19SDimitry Andric
80ffd1746dSEd Schouten namespace {
812cab237bSDimitry Andric
823ca95b02SDimitry Andric class HoistSpillHelper : private LiveRangeEdit::Delegate {
833ca95b02SDimitry Andric MachineFunction &MF;
843ca95b02SDimitry Andric LiveIntervals &LIS;
853ca95b02SDimitry Andric LiveStacks &LSS;
863ca95b02SDimitry Andric AliasAnalysis *AA;
873ca95b02SDimitry Andric MachineDominatorTree &MDT;
883ca95b02SDimitry Andric MachineLoopInfo &Loops;
893ca95b02SDimitry Andric VirtRegMap &VRM;
903ca95b02SDimitry Andric MachineRegisterInfo &MRI;
913ca95b02SDimitry Andric const TargetInstrInfo &TII;
923ca95b02SDimitry Andric const TargetRegisterInfo &TRI;
933ca95b02SDimitry Andric const MachineBlockFrequencyInfo &MBFI;
943ca95b02SDimitry Andric
953ca95b02SDimitry Andric InsertPointAnalysis IPA;
963ca95b02SDimitry Andric
972cab237bSDimitry Andric // Map from StackSlot to the LiveInterval of the original register.
982cab237bSDimitry Andric // Note the LiveInterval of the original register may have been deleted
992cab237bSDimitry Andric // after it is spilled. We keep a copy here to track the range where
1002cab237bSDimitry Andric // spills can be moved.
1012cab237bSDimitry Andric DenseMap<int, std::unique_ptr<LiveInterval>> StackSlotToOrigLI;
1022cab237bSDimitry Andric
1033ca95b02SDimitry Andric // Map from pair of (StackSlot and Original VNI) to a set of spills which
1043ca95b02SDimitry Andric // have the same stackslot and have equal values defined by Original VNI.
1053ca95b02SDimitry Andric // These spills are mergeable and are hoist candiates.
1062cab237bSDimitry Andric using MergeableSpillsMap =
1072cab237bSDimitry Andric MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
1083ca95b02SDimitry Andric MergeableSpillsMap MergeableSpills;
1093ca95b02SDimitry Andric
1103ca95b02SDimitry Andric /// This is the map from original register to a set containing all its
1113ca95b02SDimitry Andric /// siblings. To hoist a spill to another BB, we need to find out a live
1123ca95b02SDimitry Andric /// sibling there and use it as the source of the new spill.
1133ca95b02SDimitry Andric DenseMap<unsigned, SmallSetVector<unsigned, 16>> Virt2SiblingsMap;
1143ca95b02SDimitry Andric
1152cab237bSDimitry Andric bool isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
1162cab237bSDimitry Andric MachineBasicBlock &BB, unsigned &LiveReg);
1173ca95b02SDimitry Andric
1183ca95b02SDimitry Andric void rmRedundantSpills(
1193ca95b02SDimitry Andric SmallPtrSet<MachineInstr *, 16> &Spills,
1203ca95b02SDimitry Andric SmallVectorImpl<MachineInstr *> &SpillsToRm,
1213ca95b02SDimitry Andric DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
1223ca95b02SDimitry Andric
1233ca95b02SDimitry Andric void getVisitOrders(
1243ca95b02SDimitry Andric MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
1253ca95b02SDimitry Andric SmallVectorImpl<MachineDomTreeNode *> &Orders,
1263ca95b02SDimitry Andric SmallVectorImpl<MachineInstr *> &SpillsToRm,
1273ca95b02SDimitry Andric DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
1283ca95b02SDimitry Andric DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
1293ca95b02SDimitry Andric
1302cab237bSDimitry Andric void runHoistSpills(LiveInterval &OrigLI, VNInfo &OrigVNI,
1313ca95b02SDimitry Andric SmallPtrSet<MachineInstr *, 16> &Spills,
1323ca95b02SDimitry Andric SmallVectorImpl<MachineInstr *> &SpillsToRm,
1333ca95b02SDimitry Andric DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns);
1343ca95b02SDimitry Andric
1353ca95b02SDimitry Andric public:
HoistSpillHelper(MachineFunctionPass & pass,MachineFunction & mf,VirtRegMap & vrm)1363ca95b02SDimitry Andric HoistSpillHelper(MachineFunctionPass &pass, MachineFunction &mf,
1373ca95b02SDimitry Andric VirtRegMap &vrm)
1383ca95b02SDimitry Andric : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
1393ca95b02SDimitry Andric LSS(pass.getAnalysis<LiveStacks>()),
1403ca95b02SDimitry Andric AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
1413ca95b02SDimitry Andric MDT(pass.getAnalysis<MachineDominatorTree>()),
1423ca95b02SDimitry Andric Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
1432cab237bSDimitry Andric MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
1443ca95b02SDimitry Andric TRI(*mf.getSubtarget().getRegisterInfo()),
1453ca95b02SDimitry Andric MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
1463ca95b02SDimitry Andric IPA(LIS, mf.getNumBlockIDs()) {}
1473ca95b02SDimitry Andric
1483ca95b02SDimitry Andric void addToMergeableSpills(MachineInstr &Spill, int StackSlot,
1493ca95b02SDimitry Andric unsigned Original);
1503ca95b02SDimitry Andric bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
1513ca95b02SDimitry Andric void hoistAllSpills();
1523ca95b02SDimitry Andric void LRE_DidCloneVirtReg(unsigned, unsigned) override;
1533ca95b02SDimitry Andric };
1543ca95b02SDimitry Andric
155ffd1746dSEd Schouten class InlineSpiller : public Spiller {
1563b0f4066SDimitry Andric MachineFunction &MF;
1573b0f4066SDimitry Andric LiveIntervals &LIS;
1583b0f4066SDimitry Andric LiveStacks &LSS;
1593b0f4066SDimitry Andric AliasAnalysis *AA;
1603b0f4066SDimitry Andric MachineDominatorTree &MDT;
1613b0f4066SDimitry Andric MachineLoopInfo &Loops;
1623b0f4066SDimitry Andric VirtRegMap &VRM;
1633b0f4066SDimitry Andric MachineRegisterInfo &MRI;
1643b0f4066SDimitry Andric const TargetInstrInfo &TII;
1653b0f4066SDimitry Andric const TargetRegisterInfo &TRI;
166f785676fSDimitry Andric const MachineBlockFrequencyInfo &MBFI;
167ffd1746dSEd Schouten
168ffd1746dSEd Schouten // Variables that are valid during spill(), but used by multiple methods.
1693b0f4066SDimitry Andric LiveRangeEdit *Edit;
1703b0f4066SDimitry Andric LiveInterval *StackInt;
1713b0f4066SDimitry Andric int StackSlot;
1723b0f4066SDimitry Andric unsigned Original;
1733b0f4066SDimitry Andric
1743b0f4066SDimitry Andric // All registers to spill to StackSlot, including the main register.
1753b0f4066SDimitry Andric SmallVector<unsigned, 8> RegsToSpill;
1763b0f4066SDimitry Andric
1773b0f4066SDimitry Andric // All COPY instructions to/from snippets.
1783b0f4066SDimitry Andric // They are ignored since both operands refer to the same stack slot.
1793b0f4066SDimitry Andric SmallPtrSet<MachineInstr*, 8> SnippetCopies;
180ffd1746dSEd Schouten
1812754fe60SDimitry Andric // Values that failed to remat at some point.
1823b0f4066SDimitry Andric SmallPtrSet<VNInfo*, 8> UsedValues;
1833b0f4066SDimitry Andric
1843b0f4066SDimitry Andric // Dead defs generated during spilling.
1853b0f4066SDimitry Andric SmallVector<MachineInstr*, 8> DeadDefs;
186ffd1746dSEd Schouten
1873ca95b02SDimitry Andric // Object records spills information and does the hoisting.
1883ca95b02SDimitry Andric HoistSpillHelper HSpiller;
1893ca95b02SDimitry Andric
1902cab237bSDimitry Andric ~InlineSpiller() override = default;
191ffd1746dSEd Schouten
192ffd1746dSEd Schouten public:
InlineSpiller(MachineFunctionPass & pass,MachineFunction & mf,VirtRegMap & vrm)19339d628a0SDimitry Andric InlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
19439d628a0SDimitry Andric : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
1953b0f4066SDimitry Andric LSS(pass.getAnalysis<LiveStacks>()),
1967d523365SDimitry Andric AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
1973b0f4066SDimitry Andric MDT(pass.getAnalysis<MachineDominatorTree>()),
19839d628a0SDimitry Andric Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
1992cab237bSDimitry Andric MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
20039d628a0SDimitry Andric TRI(*mf.getSubtarget().getRegisterInfo()),
2013ca95b02SDimitry Andric MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
2023ca95b02SDimitry Andric HSpiller(pass, mf, vrm) {}
2032754fe60SDimitry Andric
20491bc56edSDimitry Andric void spill(LiveRangeEdit &) override;
2053ca95b02SDimitry Andric void postOptimization() override;
206ffd1746dSEd Schouten
207ffd1746dSEd Schouten private:
2083b0f4066SDimitry Andric bool isSnippet(const LiveInterval &SnipLI);
2093b0f4066SDimitry Andric void collectRegsToSpill();
2103b0f4066SDimitry Andric
isRegToSpill(unsigned Reg)211d88c1a5aSDimitry Andric bool isRegToSpill(unsigned Reg) { return is_contained(RegsToSpill, Reg); }
2123b0f4066SDimitry Andric
2133b0f4066SDimitry Andric bool isSibling(unsigned Reg);
2143ca95b02SDimitry Andric bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
2153b0f4066SDimitry Andric void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
2163b0f4066SDimitry Andric
2173b0f4066SDimitry Andric void markValueUsed(LiveInterval*, VNInfo*);
2183ca95b02SDimitry Andric bool reMaterializeFor(LiveInterval &, MachineInstr &MI);
219ffd1746dSEd Schouten void reMaterializeAll();
220ffd1746dSEd Schouten
2213b0f4066SDimitry Andric bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
222dff0c46cSDimitry Andric bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
22391bc56edSDimitry Andric MachineInstr *LoadMI = nullptr);
224f785676fSDimitry Andric void insertReload(unsigned VReg, SlotIndex, MachineBasicBlock::iterator MI);
225f785676fSDimitry Andric void insertSpill(unsigned VReg, bool isKill, MachineBasicBlock::iterator MI);
2263b0f4066SDimitry Andric
2273b0f4066SDimitry Andric void spillAroundUses(unsigned Reg);
2283b0f4066SDimitry Andric void spillAll();
229ffd1746dSEd Schouten };
230ffd1746dSEd Schouten
2312cab237bSDimitry Andric } // end anonymous namespace
23239d628a0SDimitry Andric
2332cab237bSDimitry Andric Spiller::~Spiller() = default;
2342cab237bSDimitry Andric
anchor()23539d628a0SDimitry Andric void Spiller::anchor() {}
23639d628a0SDimitry Andric
createInlineSpiller(MachineFunctionPass & pass,MachineFunction & mf,VirtRegMap & vrm)2372cab237bSDimitry Andric Spiller *llvm::createInlineSpiller(MachineFunctionPass &pass,
238e580952dSDimitry Andric MachineFunction &mf,
239e580952dSDimitry Andric VirtRegMap &vrm) {
240e580952dSDimitry Andric return new InlineSpiller(pass, mf, vrm);
241ffd1746dSEd Schouten }
24239d628a0SDimitry Andric
2433b0f4066SDimitry Andric //===----------------------------------------------------------------------===//
2443b0f4066SDimitry Andric // Snippets
2453b0f4066SDimitry Andric //===----------------------------------------------------------------------===//
2462754fe60SDimitry Andric
2473b0f4066SDimitry Andric // When spilling a virtual register, we also spill any snippets it is connected
2483b0f4066SDimitry Andric // to. The snippets are small live ranges that only have a single real use,
2493b0f4066SDimitry Andric // leftovers from live range splitting. Spilling them enables memory operand
2503b0f4066SDimitry Andric // folding or tightens the live range around the single use.
2513b0f4066SDimitry Andric //
2523b0f4066SDimitry Andric // This minimizes register pressure and maximizes the store-to-load distance for
2533b0f4066SDimitry Andric // spill slots which can be important in tight loops.
2543b0f4066SDimitry Andric
2553b0f4066SDimitry Andric /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
2563b0f4066SDimitry Andric /// otherwise return 0.
isFullCopyOf(const MachineInstr & MI,unsigned Reg)2573ca95b02SDimitry Andric static unsigned isFullCopyOf(const MachineInstr &MI, unsigned Reg) {
2583ca95b02SDimitry Andric if (!MI.isFullCopy())
2593b0f4066SDimitry Andric return 0;
2603ca95b02SDimitry Andric if (MI.getOperand(0).getReg() == Reg)
2613ca95b02SDimitry Andric return MI.getOperand(1).getReg();
2623ca95b02SDimitry Andric if (MI.getOperand(1).getReg() == Reg)
2633ca95b02SDimitry Andric return MI.getOperand(0).getReg();
2643b0f4066SDimitry Andric return 0;
2653b0f4066SDimitry Andric }
2663b0f4066SDimitry Andric
2673b0f4066SDimitry Andric /// isSnippet - Identify if a live interval is a snippet that should be spilled.
2683b0f4066SDimitry Andric /// It is assumed that SnipLI is a virtual register with the same original as
2693b0f4066SDimitry Andric /// Edit->getReg().
isSnippet(const LiveInterval & SnipLI)2703b0f4066SDimitry Andric bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
2713b0f4066SDimitry Andric unsigned Reg = Edit->getReg();
2723b0f4066SDimitry Andric
2733b0f4066SDimitry Andric // A snippet is a tiny live range with only a single instruction using it
2743b0f4066SDimitry Andric // besides copies to/from Reg or spills/fills. We accept:
2753b0f4066SDimitry Andric //
2763b0f4066SDimitry Andric // %snip = COPY %Reg / FILL fi#
2773b0f4066SDimitry Andric // %snip = USE %snip
2783b0f4066SDimitry Andric // %Reg = COPY %snip / SPILL %snip, fi#
2793b0f4066SDimitry Andric //
2803b0f4066SDimitry Andric if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
2813b0f4066SDimitry Andric return false;
2823b0f4066SDimitry Andric
28391bc56edSDimitry Andric MachineInstr *UseMI = nullptr;
2843b0f4066SDimitry Andric
2853b0f4066SDimitry Andric // Check that all uses satisfy our criteria.
28691bc56edSDimitry Andric for (MachineRegisterInfo::reg_instr_nodbg_iterator
28791bc56edSDimitry Andric RI = MRI.reg_instr_nodbg_begin(SnipLI.reg),
28891bc56edSDimitry Andric E = MRI.reg_instr_nodbg_end(); RI != E; ) {
2893ca95b02SDimitry Andric MachineInstr &MI = *RI++;
2903b0f4066SDimitry Andric
2913b0f4066SDimitry Andric // Allow copies to/from Reg.
2923b0f4066SDimitry Andric if (isFullCopyOf(MI, Reg))
2933b0f4066SDimitry Andric continue;
2943b0f4066SDimitry Andric
2953b0f4066SDimitry Andric // Allow stack slot loads.
2963b0f4066SDimitry Andric int FI;
2973b0f4066SDimitry Andric if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
2983b0f4066SDimitry Andric continue;
2993b0f4066SDimitry Andric
3003b0f4066SDimitry Andric // Allow stack slot stores.
3013b0f4066SDimitry Andric if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
3023b0f4066SDimitry Andric continue;
3033b0f4066SDimitry Andric
3043b0f4066SDimitry Andric // Allow a single additional instruction.
3053ca95b02SDimitry Andric if (UseMI && &MI != UseMI)
3063b0f4066SDimitry Andric return false;
3073ca95b02SDimitry Andric UseMI = &MI;
3083b0f4066SDimitry Andric }
3093b0f4066SDimitry Andric return true;
3103b0f4066SDimitry Andric }
3113b0f4066SDimitry Andric
3123b0f4066SDimitry Andric /// collectRegsToSpill - Collect live range snippets that only have a single
3133b0f4066SDimitry Andric /// real use.
collectRegsToSpill()3143b0f4066SDimitry Andric void InlineSpiller::collectRegsToSpill() {
3153b0f4066SDimitry Andric unsigned Reg = Edit->getReg();
3163b0f4066SDimitry Andric
3173b0f4066SDimitry Andric // Main register always spills.
3183b0f4066SDimitry Andric RegsToSpill.assign(1, Reg);
3193b0f4066SDimitry Andric SnippetCopies.clear();
3203b0f4066SDimitry Andric
3213b0f4066SDimitry Andric // Snippets all have the same original, so there can't be any for an original
3223b0f4066SDimitry Andric // register.
3233b0f4066SDimitry Andric if (Original == Reg)
3243b0f4066SDimitry Andric return;
3253b0f4066SDimitry Andric
32691bc56edSDimitry Andric for (MachineRegisterInfo::reg_instr_iterator
32791bc56edSDimitry Andric RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) {
3283ca95b02SDimitry Andric MachineInstr &MI = *RI++;
3293b0f4066SDimitry Andric unsigned SnipReg = isFullCopyOf(MI, Reg);
3303b0f4066SDimitry Andric if (!isSibling(SnipReg))
3313b0f4066SDimitry Andric continue;
3323b0f4066SDimitry Andric LiveInterval &SnipLI = LIS.getInterval(SnipReg);
3333b0f4066SDimitry Andric if (!isSnippet(SnipLI))
3343b0f4066SDimitry Andric continue;
3353ca95b02SDimitry Andric SnippetCopies.insert(&MI);
336bd5abe19SDimitry Andric if (isRegToSpill(SnipReg))
337bd5abe19SDimitry Andric continue;
3383b0f4066SDimitry Andric RegsToSpill.push_back(SnipReg);
339*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
340bd5abe19SDimitry Andric ++NumSnippets;
3413b0f4066SDimitry Andric }
3423b0f4066SDimitry Andric }
3433b0f4066SDimitry Andric
isSibling(unsigned Reg)3443b0f4066SDimitry Andric bool InlineSpiller::isSibling(unsigned Reg) {
3453b0f4066SDimitry Andric return TargetRegisterInfo::isVirtualRegister(Reg) &&
3463b0f4066SDimitry Andric VRM.getOriginal(Reg) == Original;
3473b0f4066SDimitry Andric }
3483b0f4066SDimitry Andric
3493ca95b02SDimitry Andric /// It is beneficial to spill to earlier place in the same BB in case
3503ca95b02SDimitry Andric /// as follows:
3513ca95b02SDimitry Andric /// There is an alternative def earlier in the same MBB.
3523ca95b02SDimitry Andric /// Hoist the spill as far as possible in SpillMBB. This can ease
3533ca95b02SDimitry Andric /// register pressure:
3546122f3e6SDimitry Andric ///
3553ca95b02SDimitry Andric /// x = def
3563ca95b02SDimitry Andric /// y = use x
3573ca95b02SDimitry Andric /// s = copy x
3586122f3e6SDimitry Andric ///
3593ca95b02SDimitry Andric /// Hoisting the spill of s to immediately after the def removes the
3603ca95b02SDimitry Andric /// interference between x and y:
3616122f3e6SDimitry Andric ///
3623ca95b02SDimitry Andric /// x = def
3633ca95b02SDimitry Andric /// spill x
3642cab237bSDimitry Andric /// y = use killed x
3656122f3e6SDimitry Andric ///
3663ca95b02SDimitry Andric /// This hoist only helps when the copy kills its source.
3673b0f4066SDimitry Andric ///
hoistSpillInsideBB(LiveInterval & SpillLI,MachineInstr & CopyMI)3683ca95b02SDimitry Andric bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
3693ca95b02SDimitry Andric MachineInstr &CopyMI) {
3703b0f4066SDimitry Andric SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
3713ca95b02SDimitry Andric #ifndef NDEBUG
372dff0c46cSDimitry Andric VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
373dff0c46cSDimitry Andric assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
3743ca95b02SDimitry Andric #endif
3753b0f4066SDimitry Andric
3763ca95b02SDimitry Andric unsigned SrcReg = CopyMI.getOperand(1).getReg();
3773ca95b02SDimitry Andric LiveInterval &SrcLI = LIS.getInterval(SrcReg);
3783ca95b02SDimitry Andric VNInfo *SrcVNI = SrcLI.getVNInfoAt(Idx);
3793ca95b02SDimitry Andric LiveQueryResult SrcQ = SrcLI.Query(Idx);
3803ca95b02SDimitry Andric MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(SrcVNI->def);
3813ca95b02SDimitry Andric if (DefMBB != CopyMI.getParent() || !SrcQ.isKill())
3823b0f4066SDimitry Andric return false;
3833b0f4066SDimitry Andric
3843b0f4066SDimitry Andric // Conservatively extend the stack slot range to the range of the original
3853b0f4066SDimitry Andric // value. We may be able to do better with stack slot coloring by being more
3863b0f4066SDimitry Andric // careful here.
3873b0f4066SDimitry Andric assert(StackInt && "No stack slot assigned yet.");
3883b0f4066SDimitry Andric LiveInterval &OrigLI = LIS.getInterval(Original);
3893b0f4066SDimitry Andric VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
3903b0f4066SDimitry Andric StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
391*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
3923b0f4066SDimitry Andric << *StackInt << '\n');
3933b0f4066SDimitry Andric
3943ca95b02SDimitry Andric // We are going to spill SrcVNI immediately after its def, so clear out
3953b0f4066SDimitry Andric // any later spills of the same value.
3963ca95b02SDimitry Andric eliminateRedundantSpills(SrcLI, SrcVNI);
3973b0f4066SDimitry Andric
3983ca95b02SDimitry Andric MachineBasicBlock *MBB = LIS.getMBBFromIndex(SrcVNI->def);
3993b0f4066SDimitry Andric MachineBasicBlock::iterator MII;
4003ca95b02SDimitry Andric if (SrcVNI->isPHIDef())
401d88c1a5aSDimitry Andric MII = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
4023b0f4066SDimitry Andric else {
4033ca95b02SDimitry Andric MachineInstr *DefMI = LIS.getInstructionFromIndex(SrcVNI->def);
4043b0f4066SDimitry Andric assert(DefMI && "Defining instruction disappeared");
4053b0f4066SDimitry Andric MII = DefMI;
4063b0f4066SDimitry Andric ++MII;
4073b0f4066SDimitry Andric }
4083b0f4066SDimitry Andric // Insert spill without kill flag immediately after def.
4093ca95b02SDimitry Andric TII.storeRegToStackSlot(*MBB, MII, SrcReg, false, StackSlot,
4103ca95b02SDimitry Andric MRI.getRegClass(SrcReg), &TRI);
4113b0f4066SDimitry Andric --MII; // Point to store instruction.
4123ca95b02SDimitry Andric LIS.InsertMachineInstrInMaps(*MII);
413*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\thoisted: " << SrcVNI->def << '\t' << *MII);
414bd5abe19SDimitry Andric
4153ca95b02SDimitry Andric HSpiller.addToMergeableSpills(*MII, StackSlot, Original);
4166122f3e6SDimitry Andric ++NumSpills;
4173b0f4066SDimitry Andric return true;
4183b0f4066SDimitry Andric }
4193b0f4066SDimitry Andric
4203b0f4066SDimitry Andric /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
4213b0f4066SDimitry Andric /// redundant spills of this value in SLI.reg and sibling copies.
eliminateRedundantSpills(LiveInterval & SLI,VNInfo * VNI)4223b0f4066SDimitry Andric void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
4233b0f4066SDimitry Andric assert(VNI && "Missing value");
4243b0f4066SDimitry Andric SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
4253b0f4066SDimitry Andric WorkList.push_back(std::make_pair(&SLI, VNI));
4263b0f4066SDimitry Andric assert(StackInt && "No stack slot assigned yet.");
4273b0f4066SDimitry Andric
4283b0f4066SDimitry Andric do {
4293b0f4066SDimitry Andric LiveInterval *LI;
43091bc56edSDimitry Andric std::tie(LI, VNI) = WorkList.pop_back_val();
4313b0f4066SDimitry Andric unsigned Reg = LI->reg;
432*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
433*4ba319b5SDimitry Andric << VNI->def << " in " << *LI << '\n');
4343b0f4066SDimitry Andric
4353b0f4066SDimitry Andric // Regs to spill are taken care of.
4363b0f4066SDimitry Andric if (isRegToSpill(Reg))
4373b0f4066SDimitry Andric continue;
4383b0f4066SDimitry Andric
4393b0f4066SDimitry Andric // Add all of VNI's live range to StackInt.
4403b0f4066SDimitry Andric StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
441*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
4423b0f4066SDimitry Andric
4433b0f4066SDimitry Andric // Find all spills and copies of VNI.
44491bc56edSDimitry Andric for (MachineRegisterInfo::use_instr_nodbg_iterator
44591bc56edSDimitry Andric UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
44691bc56edSDimitry Andric UI != E; ) {
4473ca95b02SDimitry Andric MachineInstr &MI = *UI++;
4483ca95b02SDimitry Andric if (!MI.isCopy() && !MI.mayStore())
4493b0f4066SDimitry Andric continue;
4503b0f4066SDimitry Andric SlotIndex Idx = LIS.getInstructionIndex(MI);
4513b0f4066SDimitry Andric if (LI->getVNInfoAt(Idx) != VNI)
4523b0f4066SDimitry Andric continue;
4533b0f4066SDimitry Andric
4543b0f4066SDimitry Andric // Follow sibling copies down the dominator tree.
4553b0f4066SDimitry Andric if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
4563b0f4066SDimitry Andric if (isSibling(DstReg)) {
4573b0f4066SDimitry Andric LiveInterval &DstLI = LIS.getInterval(DstReg);
458dff0c46cSDimitry Andric VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
4593b0f4066SDimitry Andric assert(DstVNI && "Missing defined value");
460dff0c46cSDimitry Andric assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
4613b0f4066SDimitry Andric WorkList.push_back(std::make_pair(&DstLI, DstVNI));
4623b0f4066SDimitry Andric }
4633b0f4066SDimitry Andric continue;
4643b0f4066SDimitry Andric }
4653b0f4066SDimitry Andric
4663b0f4066SDimitry Andric // Erase spills.
4673b0f4066SDimitry Andric int FI;
4683b0f4066SDimitry Andric if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
469*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << MI);
4703b0f4066SDimitry Andric // eliminateDeadDefs won't normally remove stores, so switch opcode.
4713ca95b02SDimitry Andric MI.setDesc(TII.get(TargetOpcode::KILL));
4723ca95b02SDimitry Andric DeadDefs.push_back(&MI);
4736122f3e6SDimitry Andric ++NumSpillsRemoved;
4743ca95b02SDimitry Andric if (HSpiller.rmFromMergeableSpills(MI, StackSlot))
4756122f3e6SDimitry Andric --NumSpills;
4763b0f4066SDimitry Andric }
4773b0f4066SDimitry Andric }
4783b0f4066SDimitry Andric } while (!WorkList.empty());
4793b0f4066SDimitry Andric }
4803b0f4066SDimitry Andric
4813b0f4066SDimitry Andric //===----------------------------------------------------------------------===//
4823b0f4066SDimitry Andric // Rematerialization
4833b0f4066SDimitry Andric //===----------------------------------------------------------------------===//
4843b0f4066SDimitry Andric
4853b0f4066SDimitry Andric /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
4863b0f4066SDimitry Andric /// instruction cannot be eliminated. See through snippet copies
markValueUsed(LiveInterval * LI,VNInfo * VNI)4873b0f4066SDimitry Andric void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
4883b0f4066SDimitry Andric SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
4893b0f4066SDimitry Andric WorkList.push_back(std::make_pair(LI, VNI));
4903b0f4066SDimitry Andric do {
49191bc56edSDimitry Andric std::tie(LI, VNI) = WorkList.pop_back_val();
49239d628a0SDimitry Andric if (!UsedValues.insert(VNI).second)
4933b0f4066SDimitry Andric continue;
4943b0f4066SDimitry Andric
4953b0f4066SDimitry Andric if (VNI->isPHIDef()) {
4963b0f4066SDimitry Andric MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
4977d523365SDimitry Andric for (MachineBasicBlock *P : MBB->predecessors()) {
4987d523365SDimitry Andric VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(P));
4993b0f4066SDimitry Andric if (PVNI)
5003b0f4066SDimitry Andric WorkList.push_back(std::make_pair(LI, PVNI));
5013b0f4066SDimitry Andric }
5023b0f4066SDimitry Andric continue;
5033b0f4066SDimitry Andric }
5043b0f4066SDimitry Andric
5053b0f4066SDimitry Andric // Follow snippet copies.
5063b0f4066SDimitry Andric MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
5073b0f4066SDimitry Andric if (!SnippetCopies.count(MI))
5083b0f4066SDimitry Andric continue;
5093b0f4066SDimitry Andric LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
5103b0f4066SDimitry Andric assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
511dff0c46cSDimitry Andric VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
5123b0f4066SDimitry Andric assert(SnipVNI && "Snippet undefined before copy");
5133b0f4066SDimitry Andric WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
5143b0f4066SDimitry Andric } while (!WorkList.empty());
5153b0f4066SDimitry Andric }
5163b0f4066SDimitry Andric
5173b0f4066SDimitry Andric /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
reMaterializeFor(LiveInterval & VirtReg,MachineInstr & MI)5183ca95b02SDimitry Andric bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, MachineInstr &MI) {
51939d628a0SDimitry Andric // Analyze instruction
52039d628a0SDimitry Andric SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
52139d628a0SDimitry Andric MIBundleOperands::VirtRegInfo RI =
52239d628a0SDimitry Andric MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
52339d628a0SDimitry Andric
52439d628a0SDimitry Andric if (!RI.Reads)
52539d628a0SDimitry Andric return false;
52639d628a0SDimitry Andric
527dff0c46cSDimitry Andric SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
5286122f3e6SDimitry Andric VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
5293b0f4066SDimitry Andric
5303b0f4066SDimitry Andric if (!ParentVNI) {
531*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\tadding <undef> flags: ");
5323ca95b02SDimitry Andric for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
5333ca95b02SDimitry Andric MachineOperand &MO = MI.getOperand(i);
5343b0f4066SDimitry Andric if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
535ffd1746dSEd Schouten MO.setIsUndef();
536ffd1746dSEd Schouten }
537*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << UseIdx << '\t' << MI);
538ffd1746dSEd Schouten return true;
539ffd1746dSEd Schouten }
5402754fe60SDimitry Andric
5413ca95b02SDimitry Andric if (SnippetCopies.count(&MI))
5423b0f4066SDimitry Andric return false;
5433b0f4066SDimitry Andric
5443ca95b02SDimitry Andric LiveInterval &OrigLI = LIS.getInterval(Original);
5453ca95b02SDimitry Andric VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
5463b0f4066SDimitry Andric LiveRangeEdit::Remat RM(ParentVNI);
5473ca95b02SDimitry Andric RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def);
5483ca95b02SDimitry Andric
5493ca95b02SDimitry Andric if (!Edit->canRematerializeAt(RM, OrigVNI, UseIdx, false)) {
5503b0f4066SDimitry Andric markValueUsed(&VirtReg, ParentVNI);
551*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
552ffd1746dSEd Schouten return false;
553ffd1746dSEd Schouten }
554ffd1746dSEd Schouten
5553b0f4066SDimitry Andric // If the instruction also writes VirtReg.reg, it had better not require the
5563b0f4066SDimitry Andric // same register for uses and defs.
557dff0c46cSDimitry Andric if (RI.Tied) {
5583b0f4066SDimitry Andric markValueUsed(&VirtReg, ParentVNI);
559*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << MI);
560ffd1746dSEd Schouten return false;
561ffd1746dSEd Schouten }
562ffd1746dSEd Schouten
5632754fe60SDimitry Andric // Before rematerializing into a register for a single instruction, try to
5642754fe60SDimitry Andric // fold a load into the instruction. That avoids allocating a new register.
565dff0c46cSDimitry Andric if (RM.OrigMI->canFoldAsLoad() &&
566dff0c46cSDimitry Andric foldMemoryOperand(Ops, RM.OrigMI)) {
5673b0f4066SDimitry Andric Edit->markRematerialized(RM.ParentVNI);
568bd5abe19SDimitry Andric ++NumFoldedLoads;
5692754fe60SDimitry Andric return true;
5702754fe60SDimitry Andric }
5712754fe60SDimitry Andric
572d88c1a5aSDimitry Andric // Allocate a new register for the remat.
573f785676fSDimitry Andric unsigned NewVReg = Edit->createFrom(Original);
5742754fe60SDimitry Andric
575ffd1746dSEd Schouten // Finally we can rematerialize OrigMI before MI.
5763ca95b02SDimitry Andric SlotIndex DefIdx =
5773ca95b02SDimitry Andric Edit->rematerializeAt(*MI.getParent(), MI, NewVReg, RM, TRI);
578d88c1a5aSDimitry Andric
579d88c1a5aSDimitry Andric // We take the DebugLoc from MI, since OrigMI may be attributed to a
580d88c1a5aSDimitry Andric // different source location.
581d88c1a5aSDimitry Andric auto *NewMI = LIS.getInstructionFromIndex(DefIdx);
582d88c1a5aSDimitry Andric NewMI->setDebugLoc(MI.getDebugLoc());
583d88c1a5aSDimitry Andric
584f785676fSDimitry Andric (void)DefIdx;
585*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
5863b0f4066SDimitry Andric << *LIS.getInstructionFromIndex(DefIdx));
587ffd1746dSEd Schouten
588ffd1746dSEd Schouten // Replace operands
5897d523365SDimitry Andric for (const auto &OpPair : Ops) {
5907d523365SDimitry Andric MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
5913b0f4066SDimitry Andric if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
592f785676fSDimitry Andric MO.setReg(NewVReg);
593ffd1746dSEd Schouten MO.setIsKill();
594ffd1746dSEd Schouten }
595ffd1746dSEd Schouten }
596*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\t " << UseIdx << '\t' << MI << '\n');
597ffd1746dSEd Schouten
598bd5abe19SDimitry Andric ++NumRemats;
599ffd1746dSEd Schouten return true;
600ffd1746dSEd Schouten }
601ffd1746dSEd Schouten
6022754fe60SDimitry Andric /// reMaterializeAll - Try to rematerialize as many uses as possible,
603ffd1746dSEd Schouten /// and trim the live ranges after.
reMaterializeAll()604ffd1746dSEd Schouten void InlineSpiller::reMaterializeAll() {
605dff0c46cSDimitry Andric if (!Edit->anyRematerializable(AA))
606ffd1746dSEd Schouten return;
607ffd1746dSEd Schouten
6083b0f4066SDimitry Andric UsedValues.clear();
6092754fe60SDimitry Andric
6103b0f4066SDimitry Andric // Try to remat before all uses of snippets.
611ffd1746dSEd Schouten bool anyRemat = false;
6127d523365SDimitry Andric for (unsigned Reg : RegsToSpill) {
6133b0f4066SDimitry Andric LiveInterval &LI = LIS.getInterval(Reg);
61439d628a0SDimitry Andric for (MachineRegisterInfo::reg_bundle_iterator
61539d628a0SDimitry Andric RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
61639d628a0SDimitry Andric RegI != E; ) {
6173ca95b02SDimitry Andric MachineInstr &MI = *RegI++;
61839d628a0SDimitry Andric
61939d628a0SDimitry Andric // Debug values are not allowed to affect codegen.
6203ca95b02SDimitry Andric if (MI.isDebugValue())
62139d628a0SDimitry Andric continue;
62239d628a0SDimitry Andric
623*4ba319b5SDimitry Andric assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "
624*4ba319b5SDimitry Andric "instruction that isn't a DBG_VALUE");
625*4ba319b5SDimitry Andric
6263b0f4066SDimitry Andric anyRemat |= reMaterializeFor(LI, MI);
6273b0f4066SDimitry Andric }
62891bc56edSDimitry Andric }
629ffd1746dSEd Schouten if (!anyRemat)
630ffd1746dSEd Schouten return;
631ffd1746dSEd Schouten
632ffd1746dSEd Schouten // Remove any values that were completely rematted.
6337d523365SDimitry Andric for (unsigned Reg : RegsToSpill) {
6343b0f4066SDimitry Andric LiveInterval &LI = LIS.getInterval(Reg);
6353b0f4066SDimitry Andric for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
6363b0f4066SDimitry Andric I != E; ++I) {
637ffd1746dSEd Schouten VNInfo *VNI = *I;
6383b0f4066SDimitry Andric if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
639ffd1746dSEd Schouten continue;
6403b0f4066SDimitry Andric MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
6413b0f4066SDimitry Andric MI->addRegisterDead(Reg, &TRI);
6423b0f4066SDimitry Andric if (!MI->allDefsAreDead())
6433b0f4066SDimitry Andric continue;
644*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "All defs dead: " << *MI);
6453b0f4066SDimitry Andric DeadDefs.push_back(MI);
6463b0f4066SDimitry Andric }
647ffd1746dSEd Schouten }
648ffd1746dSEd Schouten
6493b0f4066SDimitry Andric // Eliminate dead code after remat. Note that some snippet copies may be
6503b0f4066SDimitry Andric // deleted here.
6513b0f4066SDimitry Andric if (DeadDefs.empty())
652ffd1746dSEd Schouten return;
653*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
6543ca95b02SDimitry Andric Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
655ffd1746dSEd Schouten
6563ca95b02SDimitry Andric // LiveRangeEdit::eliminateDeadDef is used to remove dead define instructions
6573ca95b02SDimitry Andric // after rematerialization. To remove a VNI for a vreg from its LiveInterval,
6583ca95b02SDimitry Andric // LiveIntervals::removeVRegDefAt is used. However, after non-PHI VNIs are all
6593ca95b02SDimitry Andric // removed, PHI VNI are still left in the LiveInterval.
6603ca95b02SDimitry Andric // So to get rid of unused reg, we need to check whether it has non-dbg
6613ca95b02SDimitry Andric // reference instead of whether it has non-empty interval.
662284c1978SDimitry Andric unsigned ResultPos = 0;
6637d523365SDimitry Andric for (unsigned Reg : RegsToSpill) {
6643ca95b02SDimitry Andric if (MRI.reg_nodbg_empty(Reg)) {
665dff0c46cSDimitry Andric Edit->eraseVirtReg(Reg);
666284c1978SDimitry Andric continue;
667ffd1746dSEd Schouten }
66837cd60a3SDimitry Andric
66937cd60a3SDimitry Andric assert(LIS.hasInterval(Reg) &&
67037cd60a3SDimitry Andric (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&
67137cd60a3SDimitry Andric "Empty and not used live-range?!");
67237cd60a3SDimitry Andric
673284c1978SDimitry Andric RegsToSpill[ResultPos++] = Reg;
674284c1978SDimitry Andric }
675284c1978SDimitry Andric RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
676*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << RegsToSpill.size()
677*4ba319b5SDimitry Andric << " registers to spill after remat.\n");
678ffd1746dSEd Schouten }
679ffd1746dSEd Schouten
6803b0f4066SDimitry Andric //===----------------------------------------------------------------------===//
6813b0f4066SDimitry Andric // Spilling
6823b0f4066SDimitry Andric //===----------------------------------------------------------------------===//
6833b0f4066SDimitry Andric
6843b0f4066SDimitry Andric /// If MI is a load or store of StackSlot, it can be removed.
coalesceStackAccess(MachineInstr * MI,unsigned Reg)6853b0f4066SDimitry Andric bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
686e580952dSDimitry Andric int FI = 0;
6873ca95b02SDimitry Andric unsigned InstrReg = TII.isLoadFromStackSlot(*MI, FI);
6886122f3e6SDimitry Andric bool IsLoad = InstrReg;
6896122f3e6SDimitry Andric if (!IsLoad)
6903ca95b02SDimitry Andric InstrReg = TII.isStoreToStackSlot(*MI, FI);
691e580952dSDimitry Andric
692e580952dSDimitry Andric // We have a stack access. Is it the right register and slot?
6933b0f4066SDimitry Andric if (InstrReg != Reg || FI != StackSlot)
694e580952dSDimitry Andric return false;
695e580952dSDimitry Andric
6963ca95b02SDimitry Andric if (!IsLoad)
6973ca95b02SDimitry Andric HSpiller.rmFromMergeableSpills(*MI, StackSlot);
6983ca95b02SDimitry Andric
699*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Coalescing stack access: " << *MI);
7003ca95b02SDimitry Andric LIS.RemoveMachineInstrFromMaps(*MI);
701e580952dSDimitry Andric MI->eraseFromParent();
7026122f3e6SDimitry Andric
7036122f3e6SDimitry Andric if (IsLoad) {
7046122f3e6SDimitry Andric ++NumReloadsRemoved;
7056122f3e6SDimitry Andric --NumReloads;
7066122f3e6SDimitry Andric } else {
7076122f3e6SDimitry Andric ++NumSpillsRemoved;
7086122f3e6SDimitry Andric --NumSpills;
7096122f3e6SDimitry Andric }
7106122f3e6SDimitry Andric
711e580952dSDimitry Andric return true;
712e580952dSDimitry Andric }
713e580952dSDimitry Andric
7147a7e6055SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7157a7e6055SDimitry Andric LLVM_DUMP_METHOD
716f785676fSDimitry Andric // 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,unsigned VReg=0)717f785676fSDimitry Andric static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
718f785676fSDimitry Andric MachineBasicBlock::iterator E,
719f785676fSDimitry Andric LiveIntervals const &LIS,
720f785676fSDimitry Andric const char *const header,
721f785676fSDimitry Andric unsigned VReg =0) {
722f785676fSDimitry Andric char NextLine = '\n';
723f785676fSDimitry Andric char SlotIndent = '\t';
724f785676fSDimitry Andric
72591bc56edSDimitry Andric if (std::next(B) == E) {
726f785676fSDimitry Andric NextLine = ' ';
727f785676fSDimitry Andric SlotIndent = ' ';
728f785676fSDimitry Andric }
729f785676fSDimitry Andric
730f785676fSDimitry Andric dbgs() << '\t' << header << ": " << NextLine;
731f785676fSDimitry Andric
732f785676fSDimitry Andric for (MachineBasicBlock::iterator I = B; I != E; ++I) {
7333ca95b02SDimitry Andric SlotIndex Idx = LIS.getInstructionIndex(*I).getRegSlot();
734f785676fSDimitry Andric
735f785676fSDimitry Andric // If a register was passed in and this instruction has it as a
736f785676fSDimitry Andric // destination that is marked as an early clobber, print the
737f785676fSDimitry Andric // early-clobber slot index.
738f785676fSDimitry Andric if (VReg) {
739f785676fSDimitry Andric MachineOperand *MO = I->findRegisterDefOperand(VReg);
740f785676fSDimitry Andric if (MO && MO->isEarlyClobber())
741f785676fSDimitry Andric Idx = Idx.getRegSlot(true);
742f785676fSDimitry Andric }
743f785676fSDimitry Andric
744f785676fSDimitry Andric dbgs() << SlotIndent << Idx << '\t' << *I;
745f785676fSDimitry Andric }
746f785676fSDimitry Andric }
747f785676fSDimitry Andric #endif
748f785676fSDimitry Andric
749dff0c46cSDimitry Andric /// foldMemoryOperand - Try folding stack slot references in Ops into their
750dff0c46cSDimitry Andric /// instructions.
751dff0c46cSDimitry Andric ///
752dff0c46cSDimitry Andric /// @param Ops Operand indices from analyzeVirtReg().
7532754fe60SDimitry Andric /// @param LoadMI Load instruction to use instead of stack slot when non-null.
754dff0c46cSDimitry Andric /// @return True on success.
755dff0c46cSDimitry Andric bool InlineSpiller::
foldMemoryOperand(ArrayRef<std::pair<MachineInstr *,unsigned>> Ops,MachineInstr * LoadMI)756dff0c46cSDimitry Andric foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>> Ops,
7572754fe60SDimitry Andric MachineInstr *LoadMI) {
758dff0c46cSDimitry Andric if (Ops.empty())
759dff0c46cSDimitry Andric return false;
760dff0c46cSDimitry Andric // Don't attempt folding in bundles.
761dff0c46cSDimitry Andric MachineInstr *MI = Ops.front().first;
762dff0c46cSDimitry Andric if (Ops.back().first != MI || MI->isBundled())
763dff0c46cSDimitry Andric return false;
764dff0c46cSDimitry Andric
7656122f3e6SDimitry Andric bool WasCopy = MI->isCopy();
766dff0c46cSDimitry Andric unsigned ImpReg = 0;
767dff0c46cSDimitry Andric
768d88c1a5aSDimitry Andric // Spill subregs if the target allows it.
769d88c1a5aSDimitry Andric // We always want to spill subregs for stackmap/patchpoint pseudos.
770d88c1a5aSDimitry Andric bool SpillSubRegs = TII.isSubregFoldable() ||
771d88c1a5aSDimitry Andric MI->getOpcode() == TargetOpcode::STATEPOINT ||
77239d628a0SDimitry Andric MI->getOpcode() == TargetOpcode::PATCHPOINT ||
773d88c1a5aSDimitry Andric MI->getOpcode() == TargetOpcode::STACKMAP;
774f785676fSDimitry Andric
775ffd1746dSEd Schouten // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
776ffd1746dSEd Schouten // operands.
777ffd1746dSEd Schouten SmallVector<unsigned, 8> FoldOps;
7787d523365SDimitry Andric for (const auto &OpPair : Ops) {
7797d523365SDimitry Andric unsigned Idx = OpPair.second;
7807d523365SDimitry Andric assert(MI == OpPair.first && "Instruction conflict during operand folding");
781ffd1746dSEd Schouten MachineOperand &MO = MI->getOperand(Idx);
782dff0c46cSDimitry Andric if (MO.isImplicit()) {
783dff0c46cSDimitry Andric ImpReg = MO.getReg();
784ffd1746dSEd Schouten continue;
785dff0c46cSDimitry Andric }
786d88c1a5aSDimitry Andric
787f785676fSDimitry Andric if (!SpillSubRegs && MO.getSubReg())
788ffd1746dSEd Schouten return false;
7892754fe60SDimitry Andric // We cannot fold a load instruction into a def.
7902754fe60SDimitry Andric if (LoadMI && MO.isDef())
7912754fe60SDimitry Andric return false;
792ffd1746dSEd Schouten // Tied use operands should not be passed to foldMemoryOperand.
793ffd1746dSEd Schouten if (!MI->isRegTiedToDefOperand(Idx))
794ffd1746dSEd Schouten FoldOps.push_back(Idx);
795ffd1746dSEd Schouten }
796ffd1746dSEd Schouten
797d88c1a5aSDimitry Andric // If we only have implicit uses, we won't be able to fold that.
798d88c1a5aSDimitry Andric // Moreover, TargetInstrInfo::foldMemoryOperand will assert if we try!
799d88c1a5aSDimitry Andric if (FoldOps.empty())
800d88c1a5aSDimitry Andric return false;
801d88c1a5aSDimitry Andric
802f785676fSDimitry Andric MachineInstrSpan MIS(MI);
803f785676fSDimitry Andric
8042754fe60SDimitry Andric MachineInstr *FoldMI =
8053ca95b02SDimitry Andric LoadMI ? TII.foldMemoryOperand(*MI, FoldOps, *LoadMI, &LIS)
8063ca95b02SDimitry Andric : TII.foldMemoryOperand(*MI, FoldOps, StackSlot, &LIS);
807ffd1746dSEd Schouten if (!FoldMI)
808ffd1746dSEd Schouten return false;
809f785676fSDimitry Andric
810f785676fSDimitry Andric // Remove LIS for any dead defs in the original MI not in FoldMI.
8113ca95b02SDimitry Andric for (MIBundleOperands MO(*MI); MO.isValid(); ++MO) {
812f785676fSDimitry Andric if (!MO->isReg())
813f785676fSDimitry Andric continue;
814f785676fSDimitry Andric unsigned Reg = MO->getReg();
815f785676fSDimitry Andric if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) ||
816f785676fSDimitry Andric MRI.isReserved(Reg)) {
817f785676fSDimitry Andric continue;
818f785676fSDimitry Andric }
81991bc56edSDimitry Andric // Skip non-Defs, including undef uses and internal reads.
82091bc56edSDimitry Andric if (MO->isUse())
82191bc56edSDimitry Andric continue;
822f785676fSDimitry Andric MIBundleOperands::PhysRegInfo RI =
8233ca95b02SDimitry Andric MIBundleOperands(*FoldMI).analyzePhysReg(Reg, &TRI);
8247d523365SDimitry Andric if (RI.FullyDefined)
825f785676fSDimitry Andric continue;
826f785676fSDimitry Andric // FoldMI does not define this physreg. Remove the LI segment.
827f785676fSDimitry Andric assert(MO->isDead() && "Cannot fold physreg def");
8283ca95b02SDimitry Andric SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
829ff0cc061SDimitry Andric LIS.removePhysRegDefAt(Reg, Idx);
830f785676fSDimitry Andric }
831f785676fSDimitry Andric
8323ca95b02SDimitry Andric int FI;
8333ca95b02SDimitry Andric if (TII.isStoreToStackSlot(*MI, FI) &&
8343ca95b02SDimitry Andric HSpiller.rmFromMergeableSpills(*MI, FI))
8353ca95b02SDimitry Andric --NumSpills;
8363ca95b02SDimitry Andric LIS.ReplaceMachineInstrInMaps(*MI, *FoldMI);
837ffd1746dSEd Schouten MI->eraseFromParent();
838dff0c46cSDimitry Andric
839f785676fSDimitry Andric // Insert any new instructions other than FoldMI into the LIS maps.
840f785676fSDimitry Andric assert(!MIS.empty() && "Unexpected empty span of instructions!");
8417d523365SDimitry Andric for (MachineInstr &MI : MIS)
8427d523365SDimitry Andric if (&MI != FoldMI)
8433ca95b02SDimitry Andric LIS.InsertMachineInstrInMaps(MI);
844f785676fSDimitry Andric
845dff0c46cSDimitry Andric // TII.foldMemoryOperand may have left some implicit operands on the
846dff0c46cSDimitry Andric // instruction. Strip them.
847dff0c46cSDimitry Andric if (ImpReg)
848dff0c46cSDimitry Andric for (unsigned i = FoldMI->getNumOperands(); i; --i) {
849dff0c46cSDimitry Andric MachineOperand &MO = FoldMI->getOperand(i - 1);
850dff0c46cSDimitry Andric if (!MO.isReg() || !MO.isImplicit())
851dff0c46cSDimitry Andric break;
852dff0c46cSDimitry Andric if (MO.getReg() == ImpReg)
853dff0c46cSDimitry Andric FoldMI->RemoveOperand(i - 1);
854dff0c46cSDimitry Andric }
855dff0c46cSDimitry Andric
856*4ba319b5SDimitry Andric LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
857f785676fSDimitry Andric "folded"));
858f785676fSDimitry Andric
8596122f3e6SDimitry Andric if (!WasCopy)
860bd5abe19SDimitry Andric ++NumFolded;
8613ca95b02SDimitry Andric else if (Ops.front().second == 0) {
8626122f3e6SDimitry Andric ++NumSpills;
8633ca95b02SDimitry Andric HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original);
8643ca95b02SDimitry Andric } else
8656122f3e6SDimitry Andric ++NumReloads;
866ffd1746dSEd Schouten return true;
867ffd1746dSEd Schouten }
868ffd1746dSEd Schouten
insertReload(unsigned NewVReg,SlotIndex Idx,MachineBasicBlock::iterator MI)869f785676fSDimitry Andric void InlineSpiller::insertReload(unsigned NewVReg,
8703b0f4066SDimitry Andric SlotIndex Idx,
871ffd1746dSEd Schouten MachineBasicBlock::iterator MI) {
872ffd1746dSEd Schouten MachineBasicBlock &MBB = *MI->getParent();
873f785676fSDimitry Andric
874f785676fSDimitry Andric MachineInstrSpan MIS(MI);
875f785676fSDimitry Andric TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
876f785676fSDimitry Andric MRI.getRegClass(NewVReg), &TRI);
877f785676fSDimitry Andric
878f785676fSDimitry Andric LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
879f785676fSDimitry Andric
880*4ba319b5SDimitry Andric LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
881f785676fSDimitry Andric NewVReg));
882bd5abe19SDimitry Andric ++NumReloads;
883ffd1746dSEd Schouten }
884ffd1746dSEd Schouten
885db17bf38SDimitry Andric /// Check if \p Def fully defines a VReg with an undefined value.
886db17bf38SDimitry Andric /// If that's the case, that means the value of VReg is actually
887db17bf38SDimitry Andric /// not relevant.
isFullUndefDef(const MachineInstr & Def)888db17bf38SDimitry Andric static bool isFullUndefDef(const MachineInstr &Def) {
889db17bf38SDimitry Andric if (!Def.isImplicitDef())
890db17bf38SDimitry Andric return false;
891db17bf38SDimitry Andric assert(Def.getNumOperands() == 1 &&
892db17bf38SDimitry Andric "Implicit def with more than one definition");
893db17bf38SDimitry Andric // We can say that the VReg defined by Def is undef, only if it is
894db17bf38SDimitry Andric // fully defined by Def. Otherwise, some of the lanes may not be
895db17bf38SDimitry Andric // undef and the value of the VReg matters.
896db17bf38SDimitry Andric return !Def.getOperand(0).getSubReg();
897db17bf38SDimitry Andric }
898db17bf38SDimitry Andric
899f785676fSDimitry Andric /// insertSpill - Insert a spill of NewVReg after MI.
insertSpill(unsigned NewVReg,bool isKill,MachineBasicBlock::iterator MI)900f785676fSDimitry Andric void InlineSpiller::insertSpill(unsigned NewVReg, bool isKill,
901f785676fSDimitry Andric MachineBasicBlock::iterator MI) {
902ffd1746dSEd Schouten MachineBasicBlock &MBB = *MI->getParent();
903f785676fSDimitry Andric
904f785676fSDimitry Andric MachineInstrSpan MIS(MI);
905db17bf38SDimitry Andric bool IsRealSpill = true;
906db17bf38SDimitry Andric if (isFullUndefDef(*MI)) {
907db17bf38SDimitry Andric // Don't spill undef value.
908db17bf38SDimitry Andric // Anything works for undef, in particular keeping the memory
909db17bf38SDimitry Andric // uninitialized is a viable option and it saves code size and
910db17bf38SDimitry Andric // run time.
911db17bf38SDimitry Andric BuildMI(MBB, std::next(MI), MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
912db17bf38SDimitry Andric .addReg(NewVReg, getKillRegState(isKill));
913db17bf38SDimitry Andric IsRealSpill = false;
914db17bf38SDimitry Andric } else
91591bc56edSDimitry Andric TII.storeRegToStackSlot(MBB, std::next(MI), NewVReg, isKill, StackSlot,
916f785676fSDimitry Andric MRI.getRegClass(NewVReg), &TRI);
917f785676fSDimitry Andric
91891bc56edSDimitry Andric LIS.InsertMachineInstrRangeInMaps(std::next(MI), MIS.end());
919f785676fSDimitry Andric
920*4ba319b5SDimitry Andric LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(std::next(MI), MIS.end(), LIS,
921f785676fSDimitry Andric "spill"));
922bd5abe19SDimitry Andric ++NumSpills;
923db17bf38SDimitry Andric if (IsRealSpill)
9243ca95b02SDimitry Andric HSpiller.addToMergeableSpills(*std::next(MI), StackSlot, Original);
925ffd1746dSEd Schouten }
926ffd1746dSEd Schouten
9273b0f4066SDimitry Andric /// spillAroundUses - insert spill code around each use of Reg.
spillAroundUses(unsigned Reg)9283b0f4066SDimitry Andric void InlineSpiller::spillAroundUses(unsigned Reg) {
929*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "spillAroundUses " << printReg(Reg) << '\n');
9303b0f4066SDimitry Andric LiveInterval &OldLI = LIS.getInterval(Reg);
931ffd1746dSEd Schouten
9323b0f4066SDimitry Andric // Iterate over instructions using Reg.
93391bc56edSDimitry Andric for (MachineRegisterInfo::reg_bundle_iterator
93491bc56edSDimitry Andric RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
93591bc56edSDimitry Andric RegI != E; ) {
93691bc56edSDimitry Andric MachineInstr *MI = &*(RegI++);
937ffd1746dSEd Schouten
938ffd1746dSEd Schouten // Debug values are not allowed to affect codegen.
939ffd1746dSEd Schouten if (MI->isDebugValue()) {
940ffd1746dSEd Schouten // Modify DBG_VALUE now that the value is in a spill slot.
941ffd1746dSEd Schouten MachineBasicBlock *MBB = MI->getParent();
942*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:\t" << *MI);
9436bc11b14SDimitry Andric buildDbgValueForSpill(*MBB, MI, *MI, StackSlot);
9446bc11b14SDimitry Andric MBB->erase(MI);
945ffd1746dSEd Schouten continue;
946ffd1746dSEd Schouten }
947ffd1746dSEd Schouten
948*4ba319b5SDimitry Andric assert(!MI->isDebugInstr() && "Did not expect to find a use in debug "
949*4ba319b5SDimitry Andric "instruction that isn't a DBG_VALUE");
950*4ba319b5SDimitry Andric
9513b0f4066SDimitry Andric // Ignore copies to/from snippets. We'll delete them.
9523b0f4066SDimitry Andric if (SnippetCopies.count(MI))
9533b0f4066SDimitry Andric continue;
9543b0f4066SDimitry Andric
955e580952dSDimitry Andric // Stack slot accesses may coalesce away.
9563b0f4066SDimitry Andric if (coalesceStackAccess(MI, Reg))
957e580952dSDimitry Andric continue;
958e580952dSDimitry Andric
959ffd1746dSEd Schouten // Analyze instruction.
960dff0c46cSDimitry Andric SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
9613861d79fSDimitry Andric MIBundleOperands::VirtRegInfo RI =
9623ca95b02SDimitry Andric MIBundleOperands(*MI).analyzeVirtReg(Reg, &Ops);
9633b0f4066SDimitry Andric
9643b0f4066SDimitry Andric // Find the slot index where this instruction reads and writes OldLI.
9653b0f4066SDimitry Andric // This is usually the def slot, except for tied early clobbers.
9663ca95b02SDimitry Andric SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
967dff0c46cSDimitry Andric if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
9683b0f4066SDimitry Andric if (SlotIndex::isSameInstr(Idx, VNI->def))
9693b0f4066SDimitry Andric Idx = VNI->def;
9703b0f4066SDimitry Andric
9713b0f4066SDimitry Andric // Check for a sibling copy.
9723ca95b02SDimitry Andric unsigned SibReg = isFullCopyOf(*MI, Reg);
9733b0f4066SDimitry Andric if (SibReg && isSibling(SibReg)) {
974bd5abe19SDimitry Andric // This may actually be a copy between snippets.
975bd5abe19SDimitry Andric if (isRegToSpill(SibReg)) {
976*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Found new snippet copy: " << *MI);
977bd5abe19SDimitry Andric SnippetCopies.insert(MI);
978bd5abe19SDimitry Andric continue;
979bd5abe19SDimitry Andric }
980dff0c46cSDimitry Andric if (RI.Writes) {
9813ca95b02SDimitry Andric if (hoistSpillInsideBB(OldLI, *MI)) {
9823b0f4066SDimitry Andric // This COPY is now dead, the value is already in the stack slot.
9833b0f4066SDimitry Andric MI->getOperand(0).setIsDead();
9843b0f4066SDimitry Andric DeadDefs.push_back(MI);
9853b0f4066SDimitry Andric continue;
9863b0f4066SDimitry Andric }
9873b0f4066SDimitry Andric } else {
9883b0f4066SDimitry Andric // This is a reload for a sib-reg copy. Drop spills downstream.
9893b0f4066SDimitry Andric LiveInterval &SibLI = LIS.getInterval(SibReg);
9903b0f4066SDimitry Andric eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
9913b0f4066SDimitry Andric // The COPY will fold to a reload below.
9923b0f4066SDimitry Andric }
9933b0f4066SDimitry Andric }
994ffd1746dSEd Schouten
995ffd1746dSEd Schouten // Attempt to fold memory ops.
996dff0c46cSDimitry Andric if (foldMemoryOperand(Ops))
997ffd1746dSEd Schouten continue;
998ffd1746dSEd Schouten
999f785676fSDimitry Andric // Create a new virtual register for spill/fill.
1000ffd1746dSEd Schouten // FIXME: Infer regclass from instruction alone.
1001f785676fSDimitry Andric unsigned NewVReg = Edit->createFrom(Reg);
1002ffd1746dSEd Schouten
1003dff0c46cSDimitry Andric if (RI.Reads)
1004f785676fSDimitry Andric insertReload(NewVReg, Idx, MI);
1005ffd1746dSEd Schouten
1006ffd1746dSEd Schouten // Rewrite instruction operands.
1007ffd1746dSEd Schouten bool hasLiveDef = false;
10087d523365SDimitry Andric for (const auto &OpPair : Ops) {
10097d523365SDimitry Andric MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
1010f785676fSDimitry Andric MO.setReg(NewVReg);
1011ffd1746dSEd Schouten if (MO.isUse()) {
10127d523365SDimitry Andric if (!OpPair.first->isRegTiedToDefOperand(OpPair.second))
1013ffd1746dSEd Schouten MO.setIsKill();
1014ffd1746dSEd Schouten } else {
1015ffd1746dSEd Schouten if (!MO.isDead())
1016ffd1746dSEd Schouten hasLiveDef = true;
1017ffd1746dSEd Schouten }
1018ffd1746dSEd Schouten }
1019*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n');
1020ffd1746dSEd Schouten
1021ffd1746dSEd Schouten // FIXME: Use a second vreg if instruction has no tied ops.
1022f785676fSDimitry Andric if (RI.Writes)
10236122f3e6SDimitry Andric if (hasLiveDef)
1024f785676fSDimitry Andric insertSpill(NewVReg, true, MI);
1025ffd1746dSEd Schouten }
1026ffd1746dSEd Schouten }
10273b0f4066SDimitry Andric
10283b0f4066SDimitry Andric /// spillAll - Spill all registers remaining after rematerialization.
spillAll()10293b0f4066SDimitry Andric void InlineSpiller::spillAll() {
10303b0f4066SDimitry Andric // Update LiveStacks now that we are committed to spilling.
10313b0f4066SDimitry Andric if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
10323b0f4066SDimitry Andric StackSlot = VRM.assignVirt2StackSlot(Original);
10333b0f4066SDimitry Andric StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1034dff0c46cSDimitry Andric StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
10353b0f4066SDimitry Andric } else
10363b0f4066SDimitry Andric StackInt = &LSS.getInterval(StackSlot);
10373b0f4066SDimitry Andric
10383b0f4066SDimitry Andric if (Original != Edit->getReg())
10393b0f4066SDimitry Andric VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
10403b0f4066SDimitry Andric
10413b0f4066SDimitry Andric assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
10427d523365SDimitry Andric for (unsigned Reg : RegsToSpill)
10437d523365SDimitry Andric StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
10443b0f4066SDimitry Andric StackInt->getValNumInfo(0));
1045*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
10463b0f4066SDimitry Andric
10473b0f4066SDimitry Andric // Spill around uses of all RegsToSpill.
10487d523365SDimitry Andric for (unsigned Reg : RegsToSpill)
10497d523365SDimitry Andric spillAroundUses(Reg);
10503b0f4066SDimitry Andric
10513b0f4066SDimitry Andric // Hoisted spills may cause dead code.
10523b0f4066SDimitry Andric if (!DeadDefs.empty()) {
1053*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
10543ca95b02SDimitry Andric Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
10553b0f4066SDimitry Andric }
10563b0f4066SDimitry Andric
10573b0f4066SDimitry Andric // Finally delete the SnippetCopies.
10587d523365SDimitry Andric for (unsigned Reg : RegsToSpill) {
105991bc56edSDimitry Andric for (MachineRegisterInfo::reg_instr_iterator
10607d523365SDimitry Andric RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end();
106191bc56edSDimitry Andric RI != E; ) {
10623ca95b02SDimitry Andric MachineInstr &MI = *(RI++);
10633ca95b02SDimitry Andric assert(SnippetCopies.count(&MI) && "Remaining use wasn't a snippet copy");
10643b0f4066SDimitry Andric // FIXME: Do this with a LiveRangeEdit callback.
10653b0f4066SDimitry Andric LIS.RemoveMachineInstrFromMaps(MI);
10663ca95b02SDimitry Andric MI.eraseFromParent();
10673b0f4066SDimitry Andric }
1068bd5abe19SDimitry Andric }
10693b0f4066SDimitry Andric
10703b0f4066SDimitry Andric // Delete all spilled registers.
10717d523365SDimitry Andric for (unsigned Reg : RegsToSpill)
10727d523365SDimitry Andric Edit->eraseVirtReg(Reg);
10733b0f4066SDimitry Andric }
10743b0f4066SDimitry Andric
spill(LiveRangeEdit & edit)10753b0f4066SDimitry Andric void InlineSpiller::spill(LiveRangeEdit &edit) {
1076bd5abe19SDimitry Andric ++NumSpilledRanges;
10773b0f4066SDimitry Andric Edit = &edit;
10783b0f4066SDimitry Andric assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
10793b0f4066SDimitry Andric && "Trying to spill a stack slot.");
10803b0f4066SDimitry Andric // Share a stack slot among all descendants of Original.
10813b0f4066SDimitry Andric Original = VRM.getOriginal(edit.getReg());
10823b0f4066SDimitry Andric StackSlot = VRM.getStackSlot(Original);
108391bc56edSDimitry Andric StackInt = nullptr;
10843b0f4066SDimitry Andric
1085*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Inline spilling "
108639d628a0SDimitry Andric << TRI.getRegClassName(MRI.getRegClass(edit.getReg()))
1087*4ba319b5SDimitry Andric << ':' << edit.getParent() << "\nFrom original "
1088*4ba319b5SDimitry Andric << printReg(Original) << '\n');
10893b0f4066SDimitry Andric assert(edit.getParent().isSpillable() &&
10903b0f4066SDimitry Andric "Attempting to spill already spilled value.");
10913b0f4066SDimitry Andric assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
10923b0f4066SDimitry Andric
10933b0f4066SDimitry Andric collectRegsToSpill();
10943b0f4066SDimitry Andric reMaterializeAll();
10953b0f4066SDimitry Andric
10963b0f4066SDimitry Andric // Remat may handle everything.
10973b0f4066SDimitry Andric if (!RegsToSpill.empty())
10983b0f4066SDimitry Andric spillAll();
10993b0f4066SDimitry Andric
1100f785676fSDimitry Andric Edit->calculateRegClassAndHint(MF, Loops, MBFI);
11013b0f4066SDimitry Andric }
11023ca95b02SDimitry Andric
11033ca95b02SDimitry Andric /// Optimizations after all the reg selections and spills are done.
postOptimization()11043ca95b02SDimitry Andric void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
11053ca95b02SDimitry Andric
11063ca95b02SDimitry Andric /// When a spill is inserted, add the spill to MergeableSpills map.
addToMergeableSpills(MachineInstr & Spill,int StackSlot,unsigned Original)11073ca95b02SDimitry Andric void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
11083ca95b02SDimitry Andric unsigned Original) {
11092cab237bSDimitry Andric BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
11102cab237bSDimitry Andric LiveInterval &OrigLI = LIS.getInterval(Original);
11112cab237bSDimitry Andric // save a copy of LiveInterval in StackSlotToOrigLI because the original
11122cab237bSDimitry Andric // LiveInterval may be cleared after all its references are spilled.
11132cab237bSDimitry Andric if (StackSlotToOrigLI.find(StackSlot) == StackSlotToOrigLI.end()) {
11142cab237bSDimitry Andric auto LI = llvm::make_unique<LiveInterval>(OrigLI.reg, OrigLI.weight);
11152cab237bSDimitry Andric LI->assign(OrigLI, Allocator);
11162cab237bSDimitry Andric StackSlotToOrigLI[StackSlot] = std::move(LI);
11172cab237bSDimitry Andric }
11183ca95b02SDimitry Andric SlotIndex Idx = LIS.getInstructionIndex(Spill);
11192cab237bSDimitry Andric VNInfo *OrigVNI = StackSlotToOrigLI[StackSlot]->getVNInfoAt(Idx.getRegSlot());
11203ca95b02SDimitry Andric std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
11213ca95b02SDimitry Andric MergeableSpills[MIdx].insert(&Spill);
11223ca95b02SDimitry Andric }
11233ca95b02SDimitry Andric
11243ca95b02SDimitry Andric /// When a spill is removed, remove the spill from MergeableSpills map.
11253ca95b02SDimitry Andric /// Return true if the spill is removed successfully.
rmFromMergeableSpills(MachineInstr & Spill,int StackSlot)11263ca95b02SDimitry Andric bool HoistSpillHelper::rmFromMergeableSpills(MachineInstr &Spill,
11273ca95b02SDimitry Andric int StackSlot) {
11282cab237bSDimitry Andric auto It = StackSlotToOrigLI.find(StackSlot);
11292cab237bSDimitry Andric if (It == StackSlotToOrigLI.end())
11303ca95b02SDimitry Andric return false;
11313ca95b02SDimitry Andric SlotIndex Idx = LIS.getInstructionIndex(Spill);
11322cab237bSDimitry Andric VNInfo *OrigVNI = It->second->getVNInfoAt(Idx.getRegSlot());
11333ca95b02SDimitry Andric std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
11343ca95b02SDimitry Andric return MergeableSpills[MIdx].erase(&Spill);
11353ca95b02SDimitry Andric }
11363ca95b02SDimitry Andric
11373ca95b02SDimitry Andric /// Check BB to see if it is a possible target BB to place a hoisted spill,
11383ca95b02SDimitry Andric /// i.e., there should be a living sibling of OrigReg at the insert point.
isSpillCandBB(LiveInterval & OrigLI,VNInfo & OrigVNI,MachineBasicBlock & BB,unsigned & LiveReg)11392cab237bSDimitry Andric bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
11403ca95b02SDimitry Andric MachineBasicBlock &BB, unsigned &LiveReg) {
11413ca95b02SDimitry Andric SlotIndex Idx;
11422cab237bSDimitry Andric unsigned OrigReg = OrigLI.reg;
11433ca95b02SDimitry Andric MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, BB);
11443ca95b02SDimitry Andric if (MI != BB.end())
11453ca95b02SDimitry Andric Idx = LIS.getInstructionIndex(*MI);
11463ca95b02SDimitry Andric else
11473ca95b02SDimitry Andric Idx = LIS.getMBBEndIdx(&BB).getPrevSlot();
11483ca95b02SDimitry Andric SmallSetVector<unsigned, 16> &Siblings = Virt2SiblingsMap[OrigReg];
11492cab237bSDimitry Andric assert(OrigLI.getVNInfoAt(Idx) == &OrigVNI && "Unexpected VNI");
11503ca95b02SDimitry Andric
11513ca95b02SDimitry Andric for (auto const SibReg : Siblings) {
11523ca95b02SDimitry Andric LiveInterval &LI = LIS.getInterval(SibReg);
11533ca95b02SDimitry Andric VNInfo *VNI = LI.getVNInfoAt(Idx);
11543ca95b02SDimitry Andric if (VNI) {
11553ca95b02SDimitry Andric LiveReg = SibReg;
11563ca95b02SDimitry Andric return true;
11573ca95b02SDimitry Andric }
11583ca95b02SDimitry Andric }
11593ca95b02SDimitry Andric return false;
11603ca95b02SDimitry Andric }
11613ca95b02SDimitry Andric
11623ca95b02SDimitry Andric /// Remove redundant spills in the same BB. Save those redundant spills in
11633ca95b02SDimitry Andric /// 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)11643ca95b02SDimitry Andric void HoistSpillHelper::rmRedundantSpills(
11653ca95b02SDimitry Andric SmallPtrSet<MachineInstr *, 16> &Spills,
11663ca95b02SDimitry Andric SmallVectorImpl<MachineInstr *> &SpillsToRm,
11673ca95b02SDimitry Andric DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
11683ca95b02SDimitry Andric // For each spill saw, check SpillBBToSpill[] and see if its BB already has
11693ca95b02SDimitry Andric // another spill inside. If a BB contains more than one spill, only keep the
11703ca95b02SDimitry Andric // earlier spill with smaller SlotIndex.
11713ca95b02SDimitry Andric for (const auto CurrentSpill : Spills) {
11723ca95b02SDimitry Andric MachineBasicBlock *Block = CurrentSpill->getParent();
11738e0f8b8cSDimitry Andric MachineDomTreeNode *Node = MDT.getBase().getNode(Block);
11743ca95b02SDimitry Andric MachineInstr *PrevSpill = SpillBBToSpill[Node];
11753ca95b02SDimitry Andric if (PrevSpill) {
11763ca95b02SDimitry Andric SlotIndex PIdx = LIS.getInstructionIndex(*PrevSpill);
11773ca95b02SDimitry Andric SlotIndex CIdx = LIS.getInstructionIndex(*CurrentSpill);
11783ca95b02SDimitry Andric MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill;
11793ca95b02SDimitry Andric MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill;
11803ca95b02SDimitry Andric SpillsToRm.push_back(SpillToRm);
11818e0f8b8cSDimitry Andric SpillBBToSpill[MDT.getBase().getNode(Block)] = SpillToKeep;
11823ca95b02SDimitry Andric } else {
11838e0f8b8cSDimitry Andric SpillBBToSpill[MDT.getBase().getNode(Block)] = CurrentSpill;
11843ca95b02SDimitry Andric }
11853ca95b02SDimitry Andric }
11863ca95b02SDimitry Andric for (const auto SpillToRm : SpillsToRm)
11873ca95b02SDimitry Andric Spills.erase(SpillToRm);
11883ca95b02SDimitry Andric }
11893ca95b02SDimitry Andric
11903ca95b02SDimitry Andric /// Starting from \p Root find a top-down traversal order of the dominator
11913ca95b02SDimitry Andric /// tree to visit all basic blocks containing the elements of \p Spills.
11923ca95b02SDimitry Andric /// Redundant spills will be found and put into \p SpillsToRm at the same
11933ca95b02SDimitry Andric /// time. \p SpillBBToSpill will be populated as part of the process and
11943ca95b02SDimitry Andric /// maps a basic block to the first store occurring in the basic block.
11953ca95b02SDimitry Andric /// \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)11963ca95b02SDimitry Andric void HoistSpillHelper::getVisitOrders(
11973ca95b02SDimitry Andric MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
11983ca95b02SDimitry Andric SmallVectorImpl<MachineDomTreeNode *> &Orders,
11993ca95b02SDimitry Andric SmallVectorImpl<MachineInstr *> &SpillsToRm,
12003ca95b02SDimitry Andric DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
12013ca95b02SDimitry Andric DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
12023ca95b02SDimitry Andric // The set contains all the possible BB nodes to which we may hoist
12033ca95b02SDimitry Andric // original spills.
12043ca95b02SDimitry Andric SmallPtrSet<MachineDomTreeNode *, 8> WorkSet;
12053ca95b02SDimitry Andric // Save the BB nodes on the path from the first BB node containing
12063ca95b02SDimitry Andric // non-redundant spill to the Root node.
12073ca95b02SDimitry Andric SmallPtrSet<MachineDomTreeNode *, 8> NodesOnPath;
12083ca95b02SDimitry Andric // All the spills to be hoisted must originate from a single def instruction
12093ca95b02SDimitry Andric // to the OrigReg. It means the def instruction should dominate all the spills
12103ca95b02SDimitry Andric // to be hoisted. We choose the BB where the def instruction is located as
12113ca95b02SDimitry Andric // the Root.
12123ca95b02SDimitry Andric MachineDomTreeNode *RootIDomNode = MDT[Root]->getIDom();
12133ca95b02SDimitry Andric // For every node on the dominator tree with spill, walk up on the dominator
12143ca95b02SDimitry Andric // tree towards the Root node until it is reached. If there is other node
12153ca95b02SDimitry Andric // containing spill in the middle of the path, the previous spill saw will
12163ca95b02SDimitry Andric // be redundant and the node containing it will be removed. All the nodes on
12173ca95b02SDimitry Andric // the path starting from the first node with non-redundant spill to the Root
12183ca95b02SDimitry Andric // node will be added to the WorkSet, which will contain all the possible
12193ca95b02SDimitry Andric // locations where spills may be hoisted to after the loop below is done.
12203ca95b02SDimitry Andric for (const auto Spill : Spills) {
12213ca95b02SDimitry Andric MachineBasicBlock *Block = Spill->getParent();
12223ca95b02SDimitry Andric MachineDomTreeNode *Node = MDT[Block];
12233ca95b02SDimitry Andric MachineInstr *SpillToRm = nullptr;
12243ca95b02SDimitry Andric while (Node != RootIDomNode) {
12253ca95b02SDimitry Andric // If Node dominates Block, and it already contains a spill, the spill in
12263ca95b02SDimitry Andric // Block will be redundant.
12273ca95b02SDimitry Andric if (Node != MDT[Block] && SpillBBToSpill[Node]) {
12283ca95b02SDimitry Andric SpillToRm = SpillBBToSpill[MDT[Block]];
12293ca95b02SDimitry Andric break;
12303ca95b02SDimitry Andric /// If we see the Node already in WorkSet, the path from the Node to
12313ca95b02SDimitry Andric /// the Root node must already be traversed by another spill.
12323ca95b02SDimitry Andric /// Then no need to repeat.
12333ca95b02SDimitry Andric } else if (WorkSet.count(Node)) {
12343ca95b02SDimitry Andric break;
12353ca95b02SDimitry Andric } else {
12363ca95b02SDimitry Andric NodesOnPath.insert(Node);
12373ca95b02SDimitry Andric }
12383ca95b02SDimitry Andric Node = Node->getIDom();
12393ca95b02SDimitry Andric }
12403ca95b02SDimitry Andric if (SpillToRm) {
12413ca95b02SDimitry Andric SpillsToRm.push_back(SpillToRm);
12423ca95b02SDimitry Andric } else {
12433ca95b02SDimitry Andric // Add a BB containing the original spills to SpillsToKeep -- i.e.,
12443ca95b02SDimitry Andric // set the initial status before hoisting start. The value of BBs
12453ca95b02SDimitry Andric // containing original spills is set to 0, in order to descriminate
12463ca95b02SDimitry Andric // with BBs containing hoisted spills which will be inserted to
12473ca95b02SDimitry Andric // SpillsToKeep later during hoisting.
12483ca95b02SDimitry Andric SpillsToKeep[MDT[Block]] = 0;
12493ca95b02SDimitry Andric WorkSet.insert(NodesOnPath.begin(), NodesOnPath.end());
12503ca95b02SDimitry Andric }
12513ca95b02SDimitry Andric NodesOnPath.clear();
12523ca95b02SDimitry Andric }
12533ca95b02SDimitry Andric
12543ca95b02SDimitry Andric // Sort the nodes in WorkSet in top-down order and save the nodes
12553ca95b02SDimitry Andric // in Orders. Orders will be used for hoisting in runHoistSpills.
12563ca95b02SDimitry Andric unsigned idx = 0;
12578e0f8b8cSDimitry Andric Orders.push_back(MDT.getBase().getNode(Root));
12583ca95b02SDimitry Andric do {
12593ca95b02SDimitry Andric MachineDomTreeNode *Node = Orders[idx++];
12603ca95b02SDimitry Andric const std::vector<MachineDomTreeNode *> &Children = Node->getChildren();
12613ca95b02SDimitry Andric unsigned NumChildren = Children.size();
12623ca95b02SDimitry Andric for (unsigned i = 0; i != NumChildren; ++i) {
12633ca95b02SDimitry Andric MachineDomTreeNode *Child = Children[i];
12643ca95b02SDimitry Andric if (WorkSet.count(Child))
12653ca95b02SDimitry Andric Orders.push_back(Child);
12663ca95b02SDimitry Andric }
12673ca95b02SDimitry Andric } while (idx != Orders.size());
12683ca95b02SDimitry Andric assert(Orders.size() == WorkSet.size() &&
12693ca95b02SDimitry Andric "Orders have different size with WorkSet");
12703ca95b02SDimitry Andric
12713ca95b02SDimitry Andric #ifndef NDEBUG
1272*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Orders size is " << Orders.size() << "\n");
12733ca95b02SDimitry Andric SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
12743ca95b02SDimitry Andric for (; RIt != Orders.rend(); RIt++)
1275*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "BB" << (*RIt)->getBlock()->getNumber() << ",");
1276*4ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
12773ca95b02SDimitry Andric #endif
12783ca95b02SDimitry Andric }
12793ca95b02SDimitry Andric
12803ca95b02SDimitry Andric /// Try to hoist spills according to BB hotness. The spills to removed will
12813ca95b02SDimitry Andric /// be saved in \p SpillsToRm. The spills to be inserted will be saved in
12823ca95b02SDimitry Andric /// \p SpillsToIns.
runHoistSpills(LiveInterval & OrigLI,VNInfo & OrigVNI,SmallPtrSet<MachineInstr *,16> & Spills,SmallVectorImpl<MachineInstr * > & SpillsToRm,DenseMap<MachineBasicBlock *,unsigned> & SpillsToIns)12833ca95b02SDimitry Andric void HoistSpillHelper::runHoistSpills(
12842cab237bSDimitry Andric LiveInterval &OrigLI, VNInfo &OrigVNI,
12852cab237bSDimitry Andric SmallPtrSet<MachineInstr *, 16> &Spills,
12863ca95b02SDimitry Andric SmallVectorImpl<MachineInstr *> &SpillsToRm,
12873ca95b02SDimitry Andric DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns) {
12883ca95b02SDimitry Andric // Visit order of dominator tree nodes.
12893ca95b02SDimitry Andric SmallVector<MachineDomTreeNode *, 32> Orders;
12903ca95b02SDimitry Andric // SpillsToKeep contains all the nodes where spills are to be inserted
12913ca95b02SDimitry Andric // during hoisting. If the spill to be inserted is an original spill
12923ca95b02SDimitry Andric // (not a hoisted one), the value of the map entry is 0. If the spill
12933ca95b02SDimitry Andric // is a hoisted spill, the value of the map entry is the VReg to be used
12943ca95b02SDimitry Andric // as the source of the spill.
12953ca95b02SDimitry Andric DenseMap<MachineDomTreeNode *, unsigned> SpillsToKeep;
12963ca95b02SDimitry Andric // Map from BB to the first spill inside of it.
12973ca95b02SDimitry Andric DenseMap<MachineDomTreeNode *, MachineInstr *> SpillBBToSpill;
12983ca95b02SDimitry Andric
12993ca95b02SDimitry Andric rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill);
13003ca95b02SDimitry Andric
13013ca95b02SDimitry Andric MachineBasicBlock *Root = LIS.getMBBFromIndex(OrigVNI.def);
13023ca95b02SDimitry Andric getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep,
13033ca95b02SDimitry Andric SpillBBToSpill);
13043ca95b02SDimitry Andric
13053ca95b02SDimitry Andric // SpillsInSubTreeMap keeps the map from a dom tree node to a pair of
13063ca95b02SDimitry Andric // nodes set and the cost of all the spills inside those nodes.
13073ca95b02SDimitry Andric // The nodes set are the locations where spills are to be inserted
13083ca95b02SDimitry Andric // in the subtree of current node.
13092cab237bSDimitry Andric using NodesCostPair =
13102cab237bSDimitry Andric std::pair<SmallPtrSet<MachineDomTreeNode *, 16>, BlockFrequency>;
13113ca95b02SDimitry Andric DenseMap<MachineDomTreeNode *, NodesCostPair> SpillsInSubTreeMap;
13122cab237bSDimitry Andric
13133ca95b02SDimitry Andric // Iterate Orders set in reverse order, which will be a bottom-up order
13143ca95b02SDimitry Andric // in the dominator tree. Once we visit a dom tree node, we know its
13153ca95b02SDimitry Andric // children have already been visited and the spill locations in the
13163ca95b02SDimitry Andric // subtrees of all the children have been determined.
13173ca95b02SDimitry Andric SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
13183ca95b02SDimitry Andric for (; RIt != Orders.rend(); RIt++) {
13193ca95b02SDimitry Andric MachineBasicBlock *Block = (*RIt)->getBlock();
13203ca95b02SDimitry Andric
13213ca95b02SDimitry Andric // If Block contains an original spill, simply continue.
13223ca95b02SDimitry Andric if (SpillsToKeep.find(*RIt) != SpillsToKeep.end() && !SpillsToKeep[*RIt]) {
13233ca95b02SDimitry Andric SpillsInSubTreeMap[*RIt].first.insert(*RIt);
13243ca95b02SDimitry Andric // SpillsInSubTreeMap[*RIt].second contains the cost of spill.
13253ca95b02SDimitry Andric SpillsInSubTreeMap[*RIt].second = MBFI.getBlockFreq(Block);
13263ca95b02SDimitry Andric continue;
13273ca95b02SDimitry Andric }
13283ca95b02SDimitry Andric
13293ca95b02SDimitry Andric // Collect spills in subtree of current node (*RIt) to
13303ca95b02SDimitry Andric // SpillsInSubTreeMap[*RIt].first.
13313ca95b02SDimitry Andric const std::vector<MachineDomTreeNode *> &Children = (*RIt)->getChildren();
13323ca95b02SDimitry Andric unsigned NumChildren = Children.size();
13333ca95b02SDimitry Andric for (unsigned i = 0; i != NumChildren; ++i) {
13343ca95b02SDimitry Andric MachineDomTreeNode *Child = Children[i];
13353ca95b02SDimitry Andric if (SpillsInSubTreeMap.find(Child) == SpillsInSubTreeMap.end())
13363ca95b02SDimitry Andric continue;
13373ca95b02SDimitry Andric // The stmt "SpillsInSubTree = SpillsInSubTreeMap[*RIt].first" below
13383ca95b02SDimitry Andric // should be placed before getting the begin and end iterators of
13393ca95b02SDimitry Andric // SpillsInSubTreeMap[Child].first, or else the iterators may be
13403ca95b02SDimitry Andric // invalidated when SpillsInSubTreeMap[*RIt] is seen the first time
13413ca95b02SDimitry Andric // and the map grows and then the original buckets in the map are moved.
13423ca95b02SDimitry Andric SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
13433ca95b02SDimitry Andric SpillsInSubTreeMap[*RIt].first;
13443ca95b02SDimitry Andric BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
13453ca95b02SDimitry Andric SubTreeCost += SpillsInSubTreeMap[Child].second;
13463ca95b02SDimitry Andric auto BI = SpillsInSubTreeMap[Child].first.begin();
13473ca95b02SDimitry Andric auto EI = SpillsInSubTreeMap[Child].first.end();
13483ca95b02SDimitry Andric SpillsInSubTree.insert(BI, EI);
13493ca95b02SDimitry Andric SpillsInSubTreeMap.erase(Child);
13503ca95b02SDimitry Andric }
13513ca95b02SDimitry Andric
13523ca95b02SDimitry Andric SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
13533ca95b02SDimitry Andric SpillsInSubTreeMap[*RIt].first;
13543ca95b02SDimitry Andric BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
13553ca95b02SDimitry Andric // No spills in subtree, simply continue.
13563ca95b02SDimitry Andric if (SpillsInSubTree.empty())
13573ca95b02SDimitry Andric continue;
13583ca95b02SDimitry Andric
13593ca95b02SDimitry Andric // Check whether Block is a possible candidate to insert spill.
13603ca95b02SDimitry Andric unsigned LiveReg = 0;
13612cab237bSDimitry Andric if (!isSpillCandBB(OrigLI, OrigVNI, *Block, LiveReg))
13623ca95b02SDimitry Andric continue;
13633ca95b02SDimitry Andric
13643ca95b02SDimitry Andric // If there are multiple spills that could be merged, bias a little
13653ca95b02SDimitry Andric // to hoist the spill.
13663ca95b02SDimitry Andric BranchProbability MarginProb = (SpillsInSubTree.size() > 1)
13673ca95b02SDimitry Andric ? BranchProbability(9, 10)
13683ca95b02SDimitry Andric : BranchProbability(1, 1);
13693ca95b02SDimitry Andric if (SubTreeCost > MBFI.getBlockFreq(Block) * MarginProb) {
13703ca95b02SDimitry Andric // Hoist: Move spills to current Block.
13713ca95b02SDimitry Andric for (const auto SpillBB : SpillsInSubTree) {
13723ca95b02SDimitry Andric // When SpillBB is a BB contains original spill, insert the spill
13733ca95b02SDimitry Andric // to SpillsToRm.
13743ca95b02SDimitry Andric if (SpillsToKeep.find(SpillBB) != SpillsToKeep.end() &&
13753ca95b02SDimitry Andric !SpillsToKeep[SpillBB]) {
13763ca95b02SDimitry Andric MachineInstr *SpillToRm = SpillBBToSpill[SpillBB];
13773ca95b02SDimitry Andric SpillsToRm.push_back(SpillToRm);
13783ca95b02SDimitry Andric }
13793ca95b02SDimitry Andric // SpillBB will not contain spill anymore, remove it from SpillsToKeep.
13803ca95b02SDimitry Andric SpillsToKeep.erase(SpillBB);
13813ca95b02SDimitry Andric }
13823ca95b02SDimitry Andric // Current Block is the BB containing the new hoisted spill. Add it to
13833ca95b02SDimitry Andric // SpillsToKeep. LiveReg is the source of the new spill.
13843ca95b02SDimitry Andric SpillsToKeep[*RIt] = LiveReg;
1385*4ba319b5SDimitry Andric LLVM_DEBUG({
13863ca95b02SDimitry Andric dbgs() << "spills in BB: ";
13873ca95b02SDimitry Andric for (const auto Rspill : SpillsInSubTree)
13883ca95b02SDimitry Andric dbgs() << Rspill->getBlock()->getNumber() << " ";
13893ca95b02SDimitry Andric dbgs() << "were promoted to BB" << (*RIt)->getBlock()->getNumber()
13903ca95b02SDimitry Andric << "\n";
13913ca95b02SDimitry Andric });
13923ca95b02SDimitry Andric SpillsInSubTree.clear();
13933ca95b02SDimitry Andric SpillsInSubTree.insert(*RIt);
13943ca95b02SDimitry Andric SubTreeCost = MBFI.getBlockFreq(Block);
13953ca95b02SDimitry Andric }
13963ca95b02SDimitry Andric }
13973ca95b02SDimitry Andric // For spills in SpillsToKeep with LiveReg set (i.e., not original spill),
13983ca95b02SDimitry Andric // save them to SpillsToIns.
13993ca95b02SDimitry Andric for (const auto Ent : SpillsToKeep) {
14003ca95b02SDimitry Andric if (Ent.second)
14013ca95b02SDimitry Andric SpillsToIns[Ent.first->getBlock()] = Ent.second;
14023ca95b02SDimitry Andric }
14033ca95b02SDimitry Andric }
14043ca95b02SDimitry Andric
14053ca95b02SDimitry Andric /// For spills with equal values, remove redundant spills and hoist those left
14063ca95b02SDimitry Andric /// to less hot spots.
14073ca95b02SDimitry Andric ///
14083ca95b02SDimitry Andric /// Spills with equal values will be collected into the same set in
14093ca95b02SDimitry Andric /// MergeableSpills when spill is inserted. These equal spills are originated
14103ca95b02SDimitry Andric /// from the same defining instruction and are dominated by the instruction.
14113ca95b02SDimitry Andric /// Before hoisting all the equal spills, redundant spills inside in the same
14123ca95b02SDimitry Andric /// BB are first marked to be deleted. Then starting from the spills left, walk
14133ca95b02SDimitry Andric /// up on the dominator tree towards the Root node where the define instruction
14143ca95b02SDimitry Andric /// is located, mark the dominated spills to be deleted along the way and
14153ca95b02SDimitry Andric /// collect the BB nodes on the path from non-dominated spills to the define
14163ca95b02SDimitry Andric /// instruction into a WorkSet. The nodes in WorkSet are the candidate places
14173ca95b02SDimitry Andric /// where we are considering to hoist the spills. We iterate the WorkSet in
14183ca95b02SDimitry Andric /// bottom-up order, and for each node, we will decide whether to hoist spills
14193ca95b02SDimitry Andric /// inside its subtree to that node. In this way, we can get benefit locally
14203ca95b02SDimitry Andric /// even if hoisting all the equal spills to one cold place is impossible.
hoistAllSpills()14213ca95b02SDimitry Andric void HoistSpillHelper::hoistAllSpills() {
14223ca95b02SDimitry Andric SmallVector<unsigned, 4> NewVRegs;
14233ca95b02SDimitry Andric LiveRangeEdit Edit(nullptr, NewVRegs, MF, LIS, &VRM, this);
14243ca95b02SDimitry Andric
14253ca95b02SDimitry Andric for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
14263ca95b02SDimitry Andric unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
14273ca95b02SDimitry Andric unsigned Original = VRM.getPreSplitReg(Reg);
14283ca95b02SDimitry Andric if (!MRI.def_empty(Reg))
14293ca95b02SDimitry Andric Virt2SiblingsMap[Original].insert(Reg);
14303ca95b02SDimitry Andric }
14313ca95b02SDimitry Andric
14323ca95b02SDimitry Andric // Each entry in MergeableSpills contains a spill set with equal values.
14333ca95b02SDimitry Andric for (auto &Ent : MergeableSpills) {
14343ca95b02SDimitry Andric int Slot = Ent.first.first;
14352cab237bSDimitry Andric LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
14363ca95b02SDimitry Andric VNInfo *OrigVNI = Ent.first.second;
14373ca95b02SDimitry Andric SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
14383ca95b02SDimitry Andric if (Ent.second.empty())
14393ca95b02SDimitry Andric continue;
14403ca95b02SDimitry Andric
1441*4ba319b5SDimitry Andric LLVM_DEBUG({
14423ca95b02SDimitry Andric dbgs() << "\nFor Slot" << Slot << " and VN" << OrigVNI->id << ":\n"
14433ca95b02SDimitry Andric << "Equal spills in BB: ";
14443ca95b02SDimitry Andric for (const auto spill : EqValSpills)
14453ca95b02SDimitry Andric dbgs() << spill->getParent()->getNumber() << " ";
14463ca95b02SDimitry Andric dbgs() << "\n";
14473ca95b02SDimitry Andric });
14483ca95b02SDimitry Andric
14493ca95b02SDimitry Andric // SpillsToRm is the spill set to be removed from EqValSpills.
14503ca95b02SDimitry Andric SmallVector<MachineInstr *, 16> SpillsToRm;
14513ca95b02SDimitry Andric // SpillsToIns is the spill set to be newly inserted after hoisting.
14523ca95b02SDimitry Andric DenseMap<MachineBasicBlock *, unsigned> SpillsToIns;
14533ca95b02SDimitry Andric
14542cab237bSDimitry Andric runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns);
14553ca95b02SDimitry Andric
1456*4ba319b5SDimitry Andric LLVM_DEBUG({
14573ca95b02SDimitry Andric dbgs() << "Finally inserted spills in BB: ";
14583ca95b02SDimitry Andric for (const auto Ispill : SpillsToIns)
14593ca95b02SDimitry Andric dbgs() << Ispill.first->getNumber() << " ";
14603ca95b02SDimitry Andric dbgs() << "\nFinally removed spills in BB: ";
14613ca95b02SDimitry Andric for (const auto Rspill : SpillsToRm)
14623ca95b02SDimitry Andric dbgs() << Rspill->getParent()->getNumber() << " ";
14633ca95b02SDimitry Andric dbgs() << "\n";
14643ca95b02SDimitry Andric });
14653ca95b02SDimitry Andric
14663ca95b02SDimitry Andric // Stack live range update.
14673ca95b02SDimitry Andric LiveInterval &StackIntvl = LSS.getInterval(Slot);
14683ca95b02SDimitry Andric if (!SpillsToIns.empty() || !SpillsToRm.empty())
14693ca95b02SDimitry Andric StackIntvl.MergeValueInAsValue(OrigLI, OrigVNI,
14703ca95b02SDimitry Andric StackIntvl.getValNumInfo(0));
14713ca95b02SDimitry Andric
14723ca95b02SDimitry Andric // Insert hoisted spills.
14733ca95b02SDimitry Andric for (auto const Insert : SpillsToIns) {
14743ca95b02SDimitry Andric MachineBasicBlock *BB = Insert.first;
14753ca95b02SDimitry Andric unsigned LiveReg = Insert.second;
14763ca95b02SDimitry Andric MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, *BB);
14773ca95b02SDimitry Andric TII.storeRegToStackSlot(*BB, MI, LiveReg, false, Slot,
14783ca95b02SDimitry Andric MRI.getRegClass(LiveReg), &TRI);
14793ca95b02SDimitry Andric LIS.InsertMachineInstrRangeInMaps(std::prev(MI), MI);
14803ca95b02SDimitry Andric ++NumSpills;
14813ca95b02SDimitry Andric }
14823ca95b02SDimitry Andric
14833ca95b02SDimitry Andric // Remove redundant spills or change them to dead instructions.
14843ca95b02SDimitry Andric NumSpills -= SpillsToRm.size();
14853ca95b02SDimitry Andric for (auto const RMEnt : SpillsToRm) {
14863ca95b02SDimitry Andric RMEnt->setDesc(TII.get(TargetOpcode::KILL));
14873ca95b02SDimitry Andric for (unsigned i = RMEnt->getNumOperands(); i; --i) {
14883ca95b02SDimitry Andric MachineOperand &MO = RMEnt->getOperand(i - 1);
14893ca95b02SDimitry Andric if (MO.isReg() && MO.isImplicit() && MO.isDef() && !MO.isDead())
14903ca95b02SDimitry Andric RMEnt->RemoveOperand(i - 1);
14913ca95b02SDimitry Andric }
14923ca95b02SDimitry Andric }
14933ca95b02SDimitry Andric Edit.eliminateDeadDefs(SpillsToRm, None, AA);
14943ca95b02SDimitry Andric }
14953ca95b02SDimitry Andric }
14963ca95b02SDimitry Andric
14973ca95b02SDimitry Andric /// For VirtReg clone, the \p New register should have the same physreg or
14983ca95b02SDimitry Andric /// stackslot as the \p old register.
LRE_DidCloneVirtReg(unsigned New,unsigned Old)14993ca95b02SDimitry Andric void HoistSpillHelper::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
15003ca95b02SDimitry Andric if (VRM.hasPhys(Old))
15013ca95b02SDimitry Andric VRM.assignVirt2Phys(New, VRM.getPhys(Old));
15023ca95b02SDimitry Andric else if (VRM.getStackSlot(Old) != VirtRegMap::NO_STACK_SLOT)
15033ca95b02SDimitry Andric VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old));
15043ca95b02SDimitry Andric else
15053ca95b02SDimitry Andric llvm_unreachable("VReg should be assigned either physreg or stackslot");
15063ca95b02SDimitry Andric }
1507