1 //===------------------------ CalcSpillWeights.cpp ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/CodeGen/VirtRegMap.h"
11 #include "llvm/CodeGen/CalcSpillWeights.h"
12 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
13 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineLoopInfo.h"
16 #include "llvm/CodeGen/MachineRegisterInfo.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Target/TargetSubtargetInfo.h"
24 #define DEBUG_TYPE "calcspillweights"
26 void llvm::calculateSpillWeightsAndHints(LiveIntervals &LIS,
29 const MachineLoopInfo &MLI,
30 const MachineBlockFrequencyInfo &MBFI,
31 VirtRegAuxInfo::NormalizingFn norm) {
32 DEBUG(dbgs() << "********** Compute Spill Weights **********\n"
33 << "********** Function: " << MF.getName() << '\n');
35 MachineRegisterInfo &MRI = MF.getRegInfo();
36 VirtRegAuxInfo VRAI(MF, LIS, VRM, MLI, MBFI, norm);
37 for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
38 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
39 if (MRI.reg_nodbg_empty(Reg))
41 VRAI.calculateSpillWeightAndHint(LIS.getInterval(Reg));
45 // Return the preferred allocation register for reg, given a COPY instruction.
46 static unsigned copyHint(const MachineInstr *mi, unsigned reg,
47 const TargetRegisterInfo &tri,
48 const MachineRegisterInfo &mri) {
49 unsigned sub, hreg, hsub;
50 if (mi->getOperand(0).getReg() == reg) {
51 sub = mi->getOperand(0).getSubReg();
52 hreg = mi->getOperand(1).getReg();
53 hsub = mi->getOperand(1).getSubReg();
55 sub = mi->getOperand(1).getSubReg();
56 hreg = mi->getOperand(0).getReg();
57 hsub = mi->getOperand(0).getSubReg();
63 if (TargetRegisterInfo::isVirtualRegister(hreg))
64 return sub == hsub ? hreg : 0;
66 const TargetRegisterClass *rc = mri.getRegClass(reg);
68 // Only allow physreg hints in rc.
70 return rc->contains(hreg) ? hreg : 0;
72 // reg:sub should match the physreg hreg.
73 return tri.getMatchingSuperReg(hreg, sub, rc);
76 // Check if all values in LI are rematerializable
77 static bool isRematerializable(const LiveInterval &LI,
78 const LiveIntervals &LIS,
80 const TargetInstrInfo &TII) {
81 unsigned Reg = LI.reg;
82 unsigned Original = VRM ? VRM->getOriginal(Reg) : 0;
83 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
85 const VNInfo *VNI = *I;
91 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
92 assert(MI && "Dead valno in interval");
94 // Trace copies introduced by live range splitting. The inline
95 // spiller can rematerialize through these copies, so the spill
96 // weight must reflect this.
98 while (MI->isFullCopy()) {
99 // The copy destination must match the interval register.
100 if (MI->getOperand(0).getReg() != Reg)
103 // Get the source register.
104 Reg = MI->getOperand(1).getReg();
106 // If the original (pre-splitting) registers match this
107 // copy came from a split.
108 if (!TargetRegisterInfo::isVirtualRegister(Reg) ||
109 VRM->getOriginal(Reg) != Original)
112 // Follow the copy live-in value.
113 const LiveInterval &SrcLI = LIS.getInterval(Reg);
114 LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
115 VNI = SrcQ.valueIn();
116 assert(VNI && "Copy from non-existing value");
119 MI = LIS.getInstructionFromIndex(VNI->def);
120 assert(MI && "Dead valno in interval");
124 if (!TII.isTriviallyReMaterializable(MI, LIS.getAliasAnalysis()))
131 VirtRegAuxInfo::calculateSpillWeightAndHint(LiveInterval &li) {
132 MachineRegisterInfo &mri = MF.getRegInfo();
133 const TargetRegisterInfo &tri = *MF.getSubtarget().getRegisterInfo();
134 MachineBasicBlock *mbb = nullptr;
135 MachineLoop *loop = nullptr;
136 bool isExiting = false;
137 float totalWeight = 0;
138 unsigned numInstr = 0; // Number of instructions using li
139 SmallPtrSet<MachineInstr*, 8> visited;
141 // Find the best physreg hint and the best virtreg hint.
142 float bestPhys = 0, bestVirt = 0;
143 unsigned hintPhys = 0, hintVirt = 0;
145 // Don't recompute a target specific hint.
146 bool noHint = mri.getRegAllocationHint(li.reg).first != 0;
148 // Don't recompute spill weight for an unspillable register.
149 bool Spillable = li.isSpillable();
151 for (MachineRegisterInfo::reg_instr_iterator
152 I = mri.reg_instr_begin(li.reg), E = mri.reg_instr_end();
154 MachineInstr *mi = &*(I++);
156 if (mi->isIdentityCopy() || mi->isImplicitDef() || mi->isDebugValue())
158 if (!visited.insert(mi).second)
163 // Get loop info for mi.
164 if (mi->getParent() != mbb) {
165 mbb = mi->getParent();
166 loop = Loops.getLoopFor(mbb);
167 isExiting = loop ? loop->isLoopExiting(mbb) : false;
170 // Calculate instr weight.
172 std::tie(reads, writes) = mi->readsWritesVirtualRegister(li.reg);
173 weight = LiveIntervals::getSpillWeight(
174 writes, reads, &MBFI, mi);
176 // Give extra weight to what looks like a loop induction variable update.
177 if (writes && isExiting && LIS.isLiveOutOfMBB(li, mbb))
180 totalWeight += weight;
183 // Get allocation hints from copies.
184 if (noHint || !mi->isCopy())
186 unsigned hint = copyHint(mi, li.reg, tri, mri);
189 // Force hweight onto the stack so that x86 doesn't add hidden precision,
190 // making the comparison incorrectly pass (i.e., 1 > 1 == true??).
192 // FIXME: we probably shouldn't use floats at all.
193 volatile float hweight = Hint[hint] += weight;
194 if (TargetRegisterInfo::isPhysicalRegister(hint)) {
195 if (hweight > bestPhys && mri.isAllocatable(hint))
196 bestPhys = hweight, hintPhys = hint;
198 if (hweight > bestVirt)
199 bestVirt = hweight, hintVirt = hint;
205 // Always prefer the physreg hint.
206 if (unsigned hint = hintPhys ? hintPhys : hintVirt) {
207 mri.setRegAllocationHint(li.reg, 0, hint);
208 // Weakly boost the spill weight of hinted registers.
209 totalWeight *= 1.01F;
212 // If the live interval was already unspillable, leave it that way.
216 // Mark li as unspillable if all live ranges are tiny.
217 if (li.isZeroLength(LIS.getSlotIndexes())) {
218 li.markNotSpillable();
222 // If all of the definitions of the interval are re-materializable,
223 // it is a preferred candidate for spilling.
224 // FIXME: this gets much more complicated once we support non-trivial
225 // re-materialization.
226 if (isRematerializable(li, LIS, VRM, *MF.getSubtarget().getInstrInfo()))
229 li.weight = normalize(totalWeight, li.getSize(), numInstr);