blob: 7164fdfb788671f34b16c62fc016075e1540103e [file] [log] [blame]
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +00001//===- CalcSpillWeights.cpp -----------------------------------------------===//
Lang Hamesd17e2962009-12-14 06:49:42 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Lang Hamesd17e2962009-12-14 06:49:42 +00006//
7//===----------------------------------------------------------------------===//
8
Lang Hamesd17e2962009-12-14 06:49:42 +00009#include "llvm/CodeGen/CalcSpillWeights.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000010#include "llvm/ADT/SmallPtrSet.h"
11#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunf8422972017-12-13 02:51:04 +000012#include "llvm/CodeGen/LiveIntervals.h"
Lang Hamesd17e2962009-12-14 06:49:42 +000013#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000014#include "llvm/CodeGen/MachineInstr.h"
Lang Hamesd17e2962009-12-14 06:49:42 +000015#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000016#include "llvm/CodeGen/MachineOperand.h"
Lang Hamesd17e2962009-12-14 06:49:42 +000017#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000018#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000019#include "llvm/CodeGen/TargetRegisterInfo.h"
20#include "llvm/CodeGen/TargetSubtargetInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/CodeGen/VirtRegMap.h"
Lang Hamesd17e2962009-12-14 06:49:42 +000022#include "llvm/Support/Debug.h"
23#include "llvm/Support/raw_ostream.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000024#include <cassert>
25#include <tuple>
26
Lang Hamesd17e2962009-12-14 06:49:42 +000027using namespace llvm;
28
Chandler Carruth1b9dde02014-04-22 02:02:50 +000029#define DEBUG_TYPE "calcspillweights"
30
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +000031void llvm::calculateSpillWeightsAndHints(LiveIntervals &LIS,
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +000032 MachineFunction &MF,
Robert Lougher11a44b72015-08-10 11:59:44 +000033 VirtRegMap *VRM,
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +000034 const MachineLoopInfo &MLI,
Arnaud A. de Grandmaisonf5f040f2013-11-11 19:56:14 +000035 const MachineBlockFrequencyInfo &MBFI,
36 VirtRegAuxInfo::NormalizingFn norm) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +000037 LLVM_DEBUG(dbgs() << "********** Compute Spill Weights **********\n"
38 << "********** Function: " << MF.getName() << '\n');
Lang Hamesd17e2962009-12-14 06:49:42 +000039
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +000040 MachineRegisterInfo &MRI = MF.getRegInfo();
Robert Lougher11a44b72015-08-10 11:59:44 +000041 VirtRegAuxInfo VRAI(MF, LIS, VRM, MLI, MBFI, norm);
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +000042 for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
43 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
44 if (MRI.reg_nodbg_empty(Reg))
45 continue;
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +000046 VRAI.calculateSpillWeightAndHint(LIS.getInterval(Reg));
Lang Hamesd17e2962009-12-14 06:49:42 +000047 }
Lang Hamesd17e2962009-12-14 06:49:42 +000048}
49
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +000050// Return the preferred allocation register for reg, given a COPY instruction.
51static unsigned copyHint(const MachineInstr *mi, unsigned reg,
52 const TargetRegisterInfo &tri,
53 const MachineRegisterInfo &mri) {
54 unsigned sub, hreg, hsub;
55 if (mi->getOperand(0).getReg() == reg) {
56 sub = mi->getOperand(0).getSubReg();
57 hreg = mi->getOperand(1).getReg();
58 hsub = mi->getOperand(1).getSubReg();
59 } else {
60 sub = mi->getOperand(1).getSubReg();
61 hreg = mi->getOperand(0).getReg();
62 hsub = mi->getOperand(0).getSubReg();
63 }
64
65 if (!hreg)
66 return 0;
67
68 if (TargetRegisterInfo::isVirtualRegister(hreg))
69 return sub == hsub ? hreg : 0;
70
71 const TargetRegisterClass *rc = mri.getRegClass(reg);
Jonas Paulsson86c40db2017-12-05 10:52:24 +000072 unsigned CopiedPReg = (hsub ? tri.getSubReg(hreg, hsub) : hreg);
73 if (rc->contains(CopiedPReg))
74 return CopiedPReg;
75
76 // Check if reg:sub matches so that a super register could be hinted.
77 if (sub)
78 return tri.getMatchingSuperReg(CopiedPReg, sub, rc);
79
80 return 0;
Lang Hamesd17e2962009-12-14 06:49:42 +000081}
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +000082
Jakob Stoklund Olesen9e27e262012-06-05 01:06:12 +000083// Check if all values in LI are rematerializable
84static bool isRematerializable(const LiveInterval &LI,
85 const LiveIntervals &LIS,
Robert Lougher11a44b72015-08-10 11:59:44 +000086 VirtRegMap *VRM,
Jakob Stoklund Olesen9e27e262012-06-05 01:06:12 +000087 const TargetInstrInfo &TII) {
Robert Lougher11a44b72015-08-10 11:59:44 +000088 unsigned Reg = LI.reg;
89 unsigned Original = VRM ? VRM->getOriginal(Reg) : 0;
Jakob Stoklund Olesen9e27e262012-06-05 01:06:12 +000090 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
91 I != E; ++I) {
92 const VNInfo *VNI = *I;
93 if (VNI->isUnused())
94 continue;
95 if (VNI->isPHIDef())
96 return false;
97
98 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
99 assert(MI && "Dead valno in interval");
100
Robert Lougher11a44b72015-08-10 11:59:44 +0000101 // Trace copies introduced by live range splitting. The inline
102 // spiller can rematerialize through these copies, so the spill
103 // weight must reflect this.
104 if (VRM) {
105 while (MI->isFullCopy()) {
106 // The copy destination must match the interval register.
107 if (MI->getOperand(0).getReg() != Reg)
108 return false;
109
110 // Get the source register.
111 Reg = MI->getOperand(1).getReg();
112
113 // If the original (pre-splitting) registers match this
114 // copy came from a split.
115 if (!TargetRegisterInfo::isVirtualRegister(Reg) ||
116 VRM->getOriginal(Reg) != Original)
117 return false;
118
119 // Follow the copy live-in value.
120 const LiveInterval &SrcLI = LIS.getInterval(Reg);
121 LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
122 VNI = SrcQ.valueIn();
123 assert(VNI && "Copy from non-existing value");
124 if (VNI->isPHIDef())
125 return false;
126 MI = LIS.getInstructionFromIndex(VNI->def);
127 assert(MI && "Dead valno in interval");
128 }
129 }
130
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000131 if (!TII.isTriviallyReMaterializable(*MI, LIS.getAliasAnalysis()))
Jakob Stoklund Olesen9e27e262012-06-05 01:06:12 +0000132 return false;
133 }
134 return true;
135}
136
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000137void VirtRegAuxInfo::calculateSpillWeightAndHint(LiveInterval &li) {
138 float weight = weightCalcHelper(li);
139 // Check if unspillable.
140 if (weight < 0)
141 return;
142 li.weight = weight;
143}
144
145float VirtRegAuxInfo::futureWeight(LiveInterval &li, SlotIndex start,
146 SlotIndex end) {
147 return weightCalcHelper(li, &start, &end);
148}
149
150float VirtRegAuxInfo::weightCalcHelper(LiveInterval &li, SlotIndex *start,
151 SlotIndex *end) {
Jakob Stoklund Olesen3b7b7bc2011-04-26 18:52:36 +0000152 MachineRegisterInfo &mri = MF.getRegInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000153 const TargetRegisterInfo &tri = *MF.getSubtarget().getRegisterInfo();
Craig Topperc0196b12014-04-14 00:51:57 +0000154 MachineBasicBlock *mbb = nullptr;
155 MachineLoop *loop = nullptr;
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000156 bool isExiting = false;
157 float totalWeight = 0;
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000158 unsigned numInstr = 0; // Number of instructions using li
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000159 SmallPtrSet<MachineInstr*, 8> visited;
160
Jonas Paulsson86c40db2017-12-05 10:52:24 +0000161 std::pair<unsigned, unsigned> TargetHint = mri.getRegAllocationHint(li.reg);
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000162
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +0000163 // Don't recompute spill weight for an unspillable register.
164 bool Spillable = li.isSpillable();
165
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000166 bool localSplitArtifact = start && end;
167
168 // Do not update future local split artifacts.
169 bool updateLI = !localSplitArtifact;
170
171 if (localSplitArtifact) {
172 MachineBasicBlock *localMBB = LIS.getMBBFromIndex(*end);
173 assert(localMBB == LIS.getMBBFromIndex(*start) &&
174 "start and end are expected to be in the same basic block");
175
176 // Local split artifact will have 2 additional copy instructions and they
177 // will be in the same BB.
178 // localLI = COPY other
179 // ...
180 // other = COPY localLI
181 totalWeight += LiveIntervals::getSpillWeight(true, false, &MBFI, localMBB);
182 totalWeight += LiveIntervals::getSpillWeight(false, true, &MBFI, localMBB);
183
184 numInstr += 2;
185 }
186
Jonas Paulsson86c40db2017-12-05 10:52:24 +0000187 // CopyHint is a sortable hint derived from a COPY instruction.
188 struct CopyHint {
189 unsigned Reg;
190 float Weight;
191 bool IsPhys;
Jonas Paulssonfaad1b32018-10-05 14:23:11 +0000192 CopyHint(unsigned R, float W, bool P) :
193 Reg(R), Weight(W), IsPhys(P) {}
Jonas Paulsson86c40db2017-12-05 10:52:24 +0000194 bool operator<(const CopyHint &rhs) const {
195 // Always prefer any physreg hint.
196 if (IsPhys != rhs.IsPhys)
197 return (IsPhys && !rhs.IsPhys);
198 if (Weight != rhs.Weight)
199 return (Weight > rhs.Weight);
Jonas Paulssonfaad1b32018-10-05 14:23:11 +0000200 return Reg < rhs.Reg; // Tie-breaker.
Jonas Paulsson86c40db2017-12-05 10:52:24 +0000201 }
202 };
203 std::set<CopyHint> CopyHints;
204
Owen Andersonabb90c92014-03-13 06:02:25 +0000205 for (MachineRegisterInfo::reg_instr_iterator
206 I = mri.reg_instr_begin(li.reg), E = mri.reg_instr_end();
207 I != E; ) {
208 MachineInstr *mi = &*(I++);
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000209
210 // For local split artifacts, we are interested only in instructions between
211 // the expected start and end of the range.
212 SlotIndex si = LIS.getInstructionIndex(*mi);
213 if (localSplitArtifact && ((si < *start) || (si > *end)))
214 continue;
215
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000216 numInstr++;
Shiva Chen801bf7e2018-05-09 02:42:00 +0000217 if (mi->isIdentityCopy() || mi->isImplicitDef() || mi->isDebugInstr())
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000218 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000219 if (!visited.insert(mi).second)
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000220 continue;
221
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +0000222 float weight = 1.0f;
223 if (Spillable) {
224 // Get loop info for mi.
225 if (mi->getParent() != mbb) {
226 mbb = mi->getParent();
Jakob Stoklund Olesen3b7b7bc2011-04-26 18:52:36 +0000227 loop = Loops.getLoopFor(mbb);
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +0000228 isExiting = loop ? loop->isLoopExiting(mbb) : false;
229 }
230
231 // Calculate instr weight.
232 bool reads, writes;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000233 std::tie(reads, writes) = mi->readsWritesVirtualRegister(li.reg);
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000234 weight = LiveIntervals::getSpillWeight(writes, reads, &MBFI, *mi);
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +0000235
236 // Give extra weight to what looks like a loop induction variable update.
Jakob Stoklund Olesen3b7b7bc2011-04-26 18:52:36 +0000237 if (writes && isExiting && LIS.isLiveOutOfMBB(li, mbb))
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +0000238 weight *= 3;
239
240 totalWeight += weight;
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000241 }
242
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000243 // Get allocation hints from copies.
Jonas Paulssonfaad1b32018-10-05 14:23:11 +0000244 if (!mi->isCopy())
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000245 continue;
246 unsigned hint = copyHint(mi, li.reg, tri, mri);
247 if (!hint)
248 continue;
Duncan P. N. Exon Smith7af34322014-04-21 17:57:01 +0000249 // Force hweight onto the stack so that x86 doesn't add hidden precision,
250 // making the comparison incorrectly pass (i.e., 1 > 1 == true??).
251 //
252 // FIXME: we probably shouldn't use floats at all.
253 volatile float hweight = Hint[hint] += weight;
Jonas Paulsson86c40db2017-12-05 10:52:24 +0000254 if (TargetRegisterInfo::isVirtualRegister(hint) || mri.isAllocatable(hint))
Jonas Paulssonfaad1b32018-10-05 14:23:11 +0000255 CopyHints.insert(CopyHint(hint, hweight, tri.isPhysicalRegister(hint)));
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000256 }
257
Jakob Stoklund Olesen3b7b7bc2011-04-26 18:52:36 +0000258 Hint.clear();
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000259
Jonas Paulsson86c40db2017-12-05 10:52:24 +0000260 // Pass all the sorted copy hints to mri.
261 if (updateLI && 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
Jonas Paulssonfb3a97b2018-10-03 12:51:19 +0000266 std::set<unsigned> HintedRegs;
Jonas Paulsson86c40db2017-12-05 10:52:24 +0000267 for (auto &Hint : CopyHints) {
Jonas Paulssonfb3a97b2018-10-03 12:51:19 +0000268 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.
Jonas Paulsson86c40db2017-12-05 10:52:24 +0000271 continue;
272 mri.addRegAllocationHint(li.reg, Hint.Reg);
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000273 }
Jonas Paulsson86c40db2017-12-05 10:52:24 +0000274
275 // Weakly boost the spill weight of hinted registers.
276 totalWeight *= 1.01F;
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000277 }
278
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +0000279 // If the live interval was already unspillable, leave it that way.
280 if (!Spillable)
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000281 return -1.0;
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +0000282
Andrew Kaylor12244882016-02-08 22:52:51 +0000283 // 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.
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000286 if (updateLI && li.isZeroLength(LIS.getSlotIndexes()) &&
Andrew Kaylor12244882016-02-08 22:52:51 +0000287 !li.isLiveAtIndexes(LIS.getRegMaskSlots())) {
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000288 li.markNotSpillable();
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000289 return -1.0;
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000290 }
291
292 // If all of the definitions of the interval are re-materializable,
Jakob Stoklund Olesen9e27e262012-06-05 01:06:12 +0000293 // it is a preferred candidate for spilling.
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000294 // FIXME: this gets much more complicated once we support non-trivial
295 // re-materialization.
Robert Lougher11a44b72015-08-10 11:59:44 +0000296 if (isRematerializable(li, LIS, VRM, *MF.getSubtarget().getInstrInfo()))
Jakob Stoklund Olesen9e27e262012-06-05 01:06:12 +0000297 totalWeight *= 0.5F;
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000298
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000299 if (localSplitArtifact)
300 return normalize(totalWeight, start->distance(*end), numInstr);
301 return normalize(totalWeight, li.getSize(), numInstr);
Jakob Stoklund Olesene00c49d2010-08-10 00:02:26 +0000302}