1 //===- CalcSpillWeights.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/CodeGen/CalcSpillWeights.h"
10 #include "llvm/ADT/SmallPtrSet.h"
11 #include "llvm/CodeGen/LiveInterval.h"
12 #include "llvm/CodeGen/LiveIntervals.h"
13 #include "llvm/CodeGen/MachineFunction.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/CodeGen/MachineLoopInfo.h"
16 #include "llvm/CodeGen/MachineOperand.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetInstrInfo.h"
19 #include "llvm/CodeGen/TargetRegisterInfo.h"
20 #include "llvm/CodeGen/TargetSubtargetInfo.h"
21 #include "llvm/CodeGen/VirtRegMap.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <cassert>
25 #include <tuple>
26 
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "calcspillweights"
30 
31 void VirtRegAuxInfo::calculateSpillWeightsAndHints() {
32   LLVM_DEBUG(dbgs() << "********** Compute Spill Weights **********\n"
33                     << "********** Function: " << MF.getName() << '\n');
34 
35   MachineRegisterInfo &MRI = MF.getRegInfo();
36   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
37     unsigned Reg = Register::index2VirtReg(I);
38     if (MRI.reg_nodbg_empty(Reg))
39       continue;
40     calculateSpillWeightAndHint(LIS.getInterval(Reg));
41   }
42 }
43 
44 // Return the preferred allocation register for reg, given a COPY instruction.
45 static Register copyHint(const MachineInstr *MI, unsigned Reg,
46                          const TargetRegisterInfo &TRI,
47                          const MachineRegisterInfo &MRI) {
48   unsigned Sub, HSub;
49   Register HReg;
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();
54   } else {
55     Sub = MI->getOperand(1).getSubReg();
56     HReg = MI->getOperand(0).getReg();
57     HSub = MI->getOperand(0).getSubReg();
58   }
59 
60   if (!HReg)
61     return 0;
62 
63   if (Register::isVirtualRegister(HReg))
64     return Sub == HSub ? HReg : Register();
65 
66   const TargetRegisterClass *rc = MRI.getRegClass(Reg);
67   MCRegister CopiedPReg = HSub ? TRI.getSubReg(HReg, HSub) : HReg.asMCReg();
68   if (rc->contains(CopiedPReg))
69     return CopiedPReg;
70 
71   // Check if reg:sub matches so that a super register could be hinted.
72   if (Sub)
73     return TRI.getMatchingSuperReg(CopiedPReg, Sub, rc);
74 
75   return 0;
76 }
77 
78 // Check if all values in LI are rematerializable
79 static bool isRematerializable(const LiveInterval &LI, const LiveIntervals &LIS,
80                                const VirtRegMap &VRM,
81                                const TargetInstrInfo &TII) {
82   unsigned Reg = LI.reg();
83   unsigned Original = VRM.getOriginal(Reg);
84   for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
85        I != E; ++I) {
86     const VNInfo *VNI = *I;
87     if (VNI->isUnused())
88       continue;
89     if (VNI->isPHIDef())
90       return false;
91 
92     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
93     assert(MI && "Dead valno in interval");
94 
95     // Trace copies introduced by live range splitting.  The inline
96     // spiller can rematerialize through these copies, so the spill
97     // weight must reflect this.
98     while (MI->isFullCopy()) {
99       // The copy destination must match the interval register.
100       if (MI->getOperand(0).getReg() != Reg)
101         return false;
102 
103       // Get the source register.
104       Reg = MI->getOperand(1).getReg();
105 
106       // If the original (pre-splitting) registers match this
107       // copy came from a split.
108       if (!Register::isVirtualRegister(Reg) || VRM.getOriginal(Reg) != Original)
109         return false;
110 
111       // Follow the copy live-in value.
112       const LiveInterval &SrcLI = LIS.getInterval(Reg);
113       LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
114       VNI = SrcQ.valueIn();
115       assert(VNI && "Copy from non-existing value");
116       if (VNI->isPHIDef())
117         return false;
118       MI = LIS.getInstructionFromIndex(VNI->def);
119       assert(MI && "Dead valno in interval");
120     }
121 
122     if (!TII.isTriviallyReMaterializable(*MI, LIS.getAliasAnalysis()))
123       return false;
124   }
125   return true;
126 }
127 
128 void VirtRegAuxInfo::calculateSpillWeightAndHint(LiveInterval &LI) {
129   float Weight = weightCalcHelper(LI);
130   // Check if unspillable.
131   if (Weight < 0)
132     return;
133   LI.setWeight(Weight);
134 }
135 
136 float VirtRegAuxInfo::futureWeight(LiveInterval &LI, SlotIndex Start,
137                                    SlotIndex End) {
138   return weightCalcHelper(LI, &Start, &End);
139 }
140 
141 float VirtRegAuxInfo::weightCalcHelper(LiveInterval &LI, SlotIndex *Start,
142                                        SlotIndex *End) {
143   MachineRegisterInfo &MRI = MF.getRegInfo();
144   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
145   MachineBasicBlock *MBB = nullptr;
146   MachineLoop *Loop = nullptr;
147   bool IsExiting = false;
148   float TotalWeight = 0;
149   unsigned NumInstr = 0; // Number of instructions using LI
150   SmallPtrSet<MachineInstr *, 8> Visited;
151 
152   std::pair<Register, Register> TargetHint = MRI.getRegAllocationHint(LI.reg());
153 
154   if (LI.isSpillable()) {
155     Register Reg = LI.reg();
156     Register Original = VRM.getOriginal(Reg);
157     const LiveInterval &OrigInt = LIS.getInterval(Original);
158     // li comes from a split of OrigInt. If OrigInt was marked
159     // as not spillable, make sure the new interval is marked
160     // as not spillable as well.
161     if (!OrigInt.isSpillable())
162       LI.markNotSpillable();
163   }
164 
165   // Don't recompute spill weight for an unspillable register.
166   bool IsSpillable = LI.isSpillable();
167 
168   bool IsLocalSplitArtifact = Start && End;
169 
170   // Do not update future local split artifacts.
171   bool ShouldUpdateLI = !IsLocalSplitArtifact;
172 
173   if (IsLocalSplitArtifact) {
174     MachineBasicBlock *localMBB = LIS.getMBBFromIndex(*End);
175     assert(localMBB == LIS.getMBBFromIndex(*Start) &&
176            "start and end are expected to be in the same basic block");
177 
178     // Local split artifact will have 2 additional copy instructions and they
179     // will be in the same BB.
180     // localLI = COPY other
181     // ...
182     // other   = COPY localLI
183     TotalWeight += LiveIntervals::getSpillWeight(true, false, &MBFI, localMBB);
184     TotalWeight += LiveIntervals::getSpillWeight(false, true, &MBFI, localMBB);
185 
186     NumInstr += 2;
187   }
188 
189   // CopyHint is a sortable hint derived from a COPY instruction.
190   struct CopyHint {
191     const Register Reg;
192     const float Weight;
193     CopyHint(Register R, float W) : Reg(R), Weight(W) {}
194     bool operator<(const CopyHint &Rhs) const {
195       // Always prefer any physreg hint.
196       if (Reg.isPhysical() != Rhs.Reg.isPhysical())
197         return Reg.isPhysical();
198       if (Weight != Rhs.Weight)
199         return (Weight > Rhs.Weight);
200       return Reg.id() < Rhs.Reg.id(); // Tie-breaker.
201     }
202   };
203 
204   std::set<CopyHint> CopyHints;
205   DenseMap<unsigned, float> Hint;
206   for (MachineRegisterInfo::reg_instr_nodbg_iterator
207            I = MRI.reg_instr_nodbg_begin(LI.reg()),
208            E = MRI.reg_instr_nodbg_end();
209        I != E;) {
210     MachineInstr *MI = &*(I++);
211 
212     // For local split artifacts, we are interested only in instructions between
213     // the expected start and end of the range.
214     SlotIndex SI = LIS.getInstructionIndex(*MI);
215     if (IsLocalSplitArtifact && ((SI < *Start) || (SI > *End)))
216       continue;
217 
218     NumInstr++;
219     if (MI->isIdentityCopy() || MI->isImplicitDef())
220       continue;
221     if (!Visited.insert(MI).second)
222       continue;
223 
224     float Weight = 1.0f;
225     if (IsSpillable) {
226       // Get loop info for mi.
227       if (MI->getParent() != MBB) {
228         MBB = MI->getParent();
229         Loop = Loops.getLoopFor(MBB);
230         IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
231       }
232 
233       // Calculate instr weight.
234       bool Reads, Writes;
235       std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
236       Weight = LiveIntervals::getSpillWeight(Writes, Reads, &MBFI, *MI);
237 
238       // Give extra weight to what looks like a loop induction variable update.
239       if (Writes && IsExiting && LIS.isLiveOutOfMBB(LI, MBB))
240         Weight *= 3;
241 
242       TotalWeight += Weight;
243     }
244 
245     // Get allocation hints from copies.
246     if (!MI->isCopy())
247       continue;
248     Register HintReg = copyHint(MI, LI.reg(), TRI, MRI);
249     if (!HintReg)
250       continue;
251     // Force hweight onto the stack so that x86 doesn't add hidden precision,
252     // making the comparison incorrectly pass (i.e., 1 > 1 == true??).
253     //
254     // FIXME: we probably shouldn't use floats at all.
255     volatile float HWeight = Hint[HintReg] += Weight;
256     if (HintReg.isVirtual() || MRI.isAllocatable(HintReg))
257       CopyHints.insert(CopyHint(HintReg, HWeight));
258   }
259 
260   // Pass all the sorted copy hints to mri.
261   if (ShouldUpdateLI && CopyHints.size()) {
262     // Remove a generic hint if previously added by target.
263     if (TargetHint.first == 0 && TargetHint.second)
264       MRI.clearSimpleHint(LI.reg());
265 
266     std::set<Register> HintedRegs;
267     for (auto &Hint : CopyHints) {
268       if (!HintedRegs.insert(Hint.Reg).second ||
269           (TargetHint.first != 0 && Hint.Reg == TargetHint.second))
270         // Don't add the same reg twice or the target-type hint again.
271         continue;
272       MRI.addRegAllocationHint(LI.reg(), Hint.Reg);
273     }
274 
275     // Weakly boost the spill weight of hinted registers.
276     TotalWeight *= 1.01F;
277   }
278 
279   // If the live interval was already unspillable, leave it that way.
280   if (!IsSpillable)
281     return -1.0;
282 
283   // Mark li as unspillable if all live ranges are tiny and the interval
284   // is not live at any reg mask.  If the interval is live at a reg mask
285   // spilling may be required.
286   if (ShouldUpdateLI && LI.isZeroLength(LIS.getSlotIndexes()) &&
287       !LI.isLiveAtIndexes(LIS.getRegMaskSlots())) {
288     LI.markNotSpillable();
289     return -1.0;
290   }
291 
292   // If all of the definitions of the interval are re-materializable,
293   // it is a preferred candidate for spilling.
294   // FIXME: this gets much more complicated once we support non-trivial
295   // re-materialization.
296   if (isRematerializable(LI, LIS, VRM, *MF.getSubtarget().getInstrInfo()))
297     TotalWeight *= 0.5F;
298 
299   if (IsLocalSplitArtifact)
300     return normalize(TotalWeight, Start->distance(*End), NumInstr);
301   return normalize(TotalWeight, LI.getSize(), NumInstr);
302 }
303