blob: 8034945778357a0b41bf188e44288e9c95dada63 [file] [log] [blame]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001//===- RegAllocGreedy.cpp - greedy register allocator ---------------------===//
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
Jakob Stoklund Olesen4d7432e2010-12-10 22:21:05 +000015#include "AllocationOrder.h"
Jakob Stoklund Olesen91cbcaf2011-04-02 06:03:35 +000016#include "InterferenceCache.h"
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +000017#include "LiveDebugVariables.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000018#include "RegAllocBase.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000019#include "SpillPlacement.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "Spiller.h"
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +000021#include "SplitKit.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000022#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/IndexedMap.h"
Marina Yatsinaf9371d82017-10-22 17:59:38 +000026#include "llvm/ADT/MapVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000027#include "llvm/ADT/SetVector.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SmallVector.h"
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000031#include "llvm/ADT/Statistic.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000032#include "llvm/ADT/StringRef.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000033#include "llvm/Analysis/AliasAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000034#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000035#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000036#include "llvm/CodeGen/EdgeBundles.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000037#include "llvm/CodeGen/LiveInterval.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000038#include "llvm/CodeGen/LiveIntervalUnion.h"
Matthias Braunf8422972017-12-13 02:51:04 +000039#include "llvm/CodeGen/LiveIntervals.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000040#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000041#include "llvm/CodeGen/LiveRegMatrix.h"
Matthias Braunef959692017-12-18 23:19:44 +000042#include "llvm/CodeGen/LiveStacks.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000043#include "llvm/CodeGen/MachineBasicBlock.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000044#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000045#include "llvm/CodeGen/MachineDominators.h"
Adam Nemeta9640662017-01-25 23:20:33 +000046#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000047#include "llvm/CodeGen/MachineFunction.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000048#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000049#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000050#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000051#include "llvm/CodeGen/MachineOperand.h"
Adam Nemeta9640662017-01-25 23:20:33 +000052#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000053#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000054#include "llvm/CodeGen/RegAllocRegistry.h"
Quentin Colombet1fb3362a2014-01-02 22:47:22 +000055#include "llvm/CodeGen/RegisterClassInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000056#include "llvm/CodeGen/SlotIndexes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000057#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000058#include "llvm/CodeGen/TargetRegisterInfo.h"
59#include "llvm/CodeGen/TargetSubtargetInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include "llvm/CodeGen/VirtRegMap.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000061#include "llvm/IR/Function.h"
Quentin Colombet96bd2a12014-04-04 02:05:21 +000062#include "llvm/IR/LLVMContext.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000063#include "llvm/MC/MCRegisterInfo.h"
64#include "llvm/Pass.h"
65#include "llvm/Support/BlockFrequency.h"
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +000066#include "llvm/Support/BranchProbability.h"
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +000067#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000068#include "llvm/Support/Debug.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000069#include "llvm/Support/MathExtras.h"
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +000070#include "llvm/Support/Timer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000071#include "llvm/Support/raw_ostream.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000072#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000073#include <algorithm>
74#include <cassert>
75#include <cstdint>
76#include <memory>
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000077#include <queue>
Eugene Zelenkofb69e662017-06-06 22:22:41 +000078#include <tuple>
79#include <utility>
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000080
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000081using namespace llvm;
82
Chandler Carruth1b9dde02014-04-22 02:02:50 +000083#define DEBUG_TYPE "regalloc"
84
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000085STATISTIC(NumGlobalSplits, "Number of split global live ranges");
86STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000087STATISTIC(NumEvicted, "Number of interferences evicted");
88
Wei Mi9a16d652016-04-13 03:08:27 +000089static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
90 "split-spill-mode", cl::Hidden,
91 cl::desc("Spill mode for splitting live ranges"),
92 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
93 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
Mehdi Amini732afdd2016-10-08 19:41:06 +000094 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
Wei Mi9a16d652016-04-13 03:08:27 +000095 cl::init(SplitEditor::SM_Speed));
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +000096
Quentin Colombet87769712014-02-05 22:13:59 +000097static cl::opt<unsigned>
98LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
99 cl::desc("Last chance recoloring max depth"),
100 cl::init(5));
101
102static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
103 "lcr-max-interf", cl::Hidden,
104 cl::desc("Last chance recoloring maximum number of considered"
105 " interference at a time"),
106 cl::init(8));
107
Zachary Turner8065f0b2017-12-01 00:53:10 +0000108static cl::opt<bool> ExhaustiveSearch(
109 "exhaustive-register-search", cl::NotHidden,
110 cl::desc("Exhaustive Search for registers bypassing the depth "
111 "and interference cutoffs of last chance recoloring"),
112 cl::Hidden);
Quentin Colombet567e30b2014-04-11 21:39:44 +0000113
Quentin Colombete1a36632014-07-01 14:08:37 +0000114static cl::opt<bool> EnableLocalReassignment(
115 "enable-local-reassign", cl::Hidden,
116 cl::desc("Local reassignment can yield better allocation decisions, but "
117 "may be compile time intensive"),
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000118 cl::init(false));
Quentin Colombete1a36632014-07-01 14:08:37 +0000119
Quentin Colombet11922942015-07-17 23:04:06 +0000120static cl::opt<bool> EnableDeferredSpilling(
121 "enable-deferred-spilling", cl::Hidden,
122 cl::desc("Instead of spilling a variable right away, defer the actual "
123 "code insertion to the end of the allocation. That way the "
124 "allocator might still find a suitable coloring for this "
125 "variable because of other evicted variables."),
126 cl::init(false));
127
Manman Ren78cf02a2014-03-25 00:16:25 +0000128// FIXME: Find a good default for this flag and remove the flag.
129static cl::opt<unsigned>
130CSRFirstTimeCost("regalloc-csr-first-time-cost",
131 cl::desc("Cost for first time use of callee-saved register."),
132 cl::init(0), cl::Hidden);
133
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000134static cl::opt<bool> ConsiderLocalIntervalCost(
135 "condsider-local-interval-cost", cl::Hidden,
136 cl::desc("Consider the cost of local intervals created by a split "
137 "candidate when choosing the best split candidate."),
138 cl::init(false));
139
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000140static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
141 createGreedyRegisterAllocator);
142
143namespace {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000144
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000145class RAGreedy : public MachineFunctionPass,
146 public RegAllocBase,
147 private LiveRangeEdit::Delegate {
Quentin Colombet87769712014-02-05 22:13:59 +0000148 // Convenient shortcuts.
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000149 using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
150 using SmallLISet = SmallPtrSet<LiveInterval *, 4>;
151 using SmallVirtRegSet = SmallSet<unsigned, 16>;
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000152
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000153 // context
154 MachineFunction *MF;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000155
Quentin Colombet1fb3362a2014-01-02 22:47:22 +0000156 // Shortcuts to some useful interface.
157 const TargetInstrInfo *TII;
158 const TargetRegisterInfo *TRI;
159 RegisterClassInfo RCI;
160
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000161 // analyses
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000162 SlotIndexes *Indexes;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000163 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000164 MachineDominatorTree *DomTree;
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +0000165 MachineLoopInfo *Loops;
Adam Nemeta9640662017-01-25 23:20:33 +0000166 MachineOptimizationRemarkEmitter *ORE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000167 EdgeBundles *Bundles;
168 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000169 LiveDebugVariables *DebugVars;
Wei Mic0223702016-07-08 21:08:09 +0000170 AliasAnalysis *AA;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000171
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000172 // state
Ahmed Charles56440fd2014-03-06 05:51:42 +0000173 std::unique_ptr<Spiller> SpillerInstance;
Quentin Colombet87769712014-02-05 22:13:59 +0000174 PQueue Queue;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000175 unsigned NextCascade;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000176
177 // Live ranges pass through a number of stages as we try to allocate them.
178 // Some of the stages may also create new live ranges:
179 //
180 // - Region splitting.
181 // - Per-block splitting.
182 // - Local splitting.
183 // - Spilling.
184 //
185 // Ranges produced by one of the stages skip the previous stages when they are
186 // dequeued. This improves performance because we can skip interference checks
187 // that are unlikely to give any results. It also guarantees that the live
188 // range splitting algorithm terminates, something that is otherwise hard to
189 // ensure.
190 enum LiveRangeStage {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000191 /// Newly created live range that has never been queued.
192 RS_New,
193
194 /// Only attempt assignment and eviction. Then requeue as RS_Split.
195 RS_Assign,
196
197 /// Attempt live range splitting if assignment is impossible.
198 RS_Split,
199
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000200 /// Attempt more aggressive live range splitting that is guaranteed to make
201 /// progress. This is used for split products that may not be making
202 /// progress.
203 RS_Split2,
204
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000205 /// Live range will be spilled. No more splitting will be attempted.
206 RS_Spill,
207
Quentin Colombet11922942015-07-17 23:04:06 +0000208
209 /// Live range is in memory. Because of other evictions, it might get moved
210 /// in a register in the end.
211 RS_Memory,
212
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000213 /// There is nothing more we can do to this live range. Abort compilation
214 /// if it can't be assigned.
215 RS_Done
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000216 };
217
Quentin Colombet96bd2a12014-04-04 02:05:21 +0000218 // Enum CutOffStage to keep a track whether the register allocation failed
219 // because of the cutoffs encountered in last chance recoloring.
220 // Note: This is used as bitmask. New value should be next power of 2.
221 enum CutOffStage {
222 // No cutoffs encountered
223 CO_None = 0,
224
225 // lcr-max-depth cutoff encountered
226 CO_Depth = 1,
227
228 // lcr-max-interf cutoff encountered
229 CO_Interf = 2
230 };
231
232 uint8_t CutOffInfo;
233
Eli Friedman78bffa52013-09-10 23:18:14 +0000234#ifndef NDEBUG
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000235 static const char *const StageName[];
Eli Friedman78bffa52013-09-10 23:18:14 +0000236#endif
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000237
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000238 // RegInfo - Keep additional information about each live range.
239 struct RegInfo {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000240 LiveRangeStage Stage = RS_New;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000241
242 // Cascade - Eviction loop prevention. See canEvictInterference().
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000243 unsigned Cascade = 0;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000244
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000245 RegInfo() = default;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000246 };
247
248 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000249
250 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000251 return ExtraRegInfo[VirtReg.reg].Stage;
252 }
253
254 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
255 ExtraRegInfo.resize(MRI->getNumVirtRegs());
256 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000257 }
258
259 template<typename Iterator>
260 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000261 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000262 for (;Begin != End; ++Begin) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000263 unsigned Reg = *Begin;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000264 if (ExtraRegInfo[Reg].Stage == RS_New)
265 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000266 }
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000267 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000268
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000269 /// Cost of evicting interference.
270 struct EvictionCost {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000271 unsigned BrokenHints = 0; ///< Total number of broken hints.
272 float MaxWeight = 0; ///< Maximum spill weight evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000273
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000274 EvictionCost() = default;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000275
Andrew Trick84852572013-07-25 18:35:14 +0000276 bool isMax() const { return BrokenHints == ~0u; }
277
Andrew Trick3621b8a2013-11-22 19:07:38 +0000278 void setMax() { BrokenHints = ~0u; }
279
280 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
281
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000282 bool operator<(const EvictionCost &O) const {
Benjamin Kramerb2f034b2014-03-03 19:58:30 +0000283 return std::tie(BrokenHints, MaxWeight) <
284 std::tie(O.BrokenHints, O.MaxWeight);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000285 }
286 };
287
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000288 /// EvictionTrack - Keeps track of past evictions in order to optimize region
289 /// split decision.
290 class EvictionTrack {
291
292 public:
293 using EvictorInfo =
294 std::pair<unsigned /* evictor */, unsigned /* physreg */>;
295 using EvicteeInfo = llvm::MapVector<unsigned /* evictee */, EvictorInfo>;
296
297 private:
298 /// Each Vreg that has been evicted in the last stage of selectOrSplit will
299 /// be mapped to the evictor Vreg and the PhysReg it was evicted from.
300 EvicteeInfo Evictees;
301
302 public:
303 /// \brief Clear all eviction information.
304 void clear() { Evictees.clear(); }
305
306 /// \brief Clear eviction information for the given evictee Vreg.
307 /// E.g. when Vreg get's a new allocation, the old eviction info is no
308 /// longer relevant.
309 /// \param Evictee The evictee Vreg for whom we want to clear collected
310 /// eviction info.
311 void clearEvicteeInfo(unsigned Evictee) { Evictees.erase(Evictee); }
312
313 /// \brief Track new eviction.
314 /// The Evictor vreg has evicted the Evictee vreg from Physreg.
315 /// \praram PhysReg The phisical register Evictee was evicted from.
316 /// \praram Evictor The evictor Vreg that evicted Evictee.
317 /// \praram Evictee The evictee Vreg.
318 void addEviction(unsigned PhysReg, unsigned Evictor, unsigned Evictee) {
319 Evictees[Evictee].first = Evictor;
320 Evictees[Evictee].second = PhysReg;
321 }
322
323 /// Return the Evictor Vreg which evicted Evictee Vreg from PhysReg.
324 /// \praram Evictee The evictee vreg.
325 /// \return The Evictor vreg which evicted Evictee vreg from PhysReg. 0 if
326 /// nobody has evicted Evictee from PhysReg.
327 EvictorInfo getEvictor(unsigned Evictee) {
328 if (Evictees.count(Evictee)) {
329 return Evictees[Evictee];
330 }
331
332 return EvictorInfo(0, 0);
333 }
334 };
335
336 // Keeps track of past evictions in order to optimize region split decision.
337 EvictionTrack LastEvicted;
338
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000339 // splitting state.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000340 std::unique_ptr<SplitAnalysis> SA;
341 std::unique_ptr<SplitEditor> SE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000342
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000343 /// Cached per-block interference maps
344 InterferenceCache IntfCache;
345
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000346 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000347 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000348
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000349 /// Global live range splitting candidate info.
350 struct GlobalSplitCandidate {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000351 // Register intended for assignment, or 0.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000352 unsigned PhysReg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000353
354 // SplitKit interval index for this candidate.
355 unsigned IntvIdx;
356
357 // Interference for PhysReg.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000358 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000359
360 // Bundles where this candidate should be live.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000361 BitVector LiveBundles;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000362 SmallVector<unsigned, 8> ActiveBlocks;
363
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000364 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000365 PhysReg = Reg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000366 IntvIdx = 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000367 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000368 LiveBundles.clear();
369 ActiveBlocks.clear();
370 }
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000371
372 // Set B[i] = C for every live bundle where B[i] was NoCand.
373 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
374 unsigned Count = 0;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +0000375 for (unsigned i : LiveBundles.set_bits())
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000376 if (B[i] == NoCand) {
377 B[i] = C;
378 Count++;
379 }
380 return Count;
381 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000382 };
383
Aditya Nandakumarc1fd0dd2013-11-19 23:51:32 +0000384 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000385 /// This vector never shrinks, but grows to the size of the largest register
386 /// class.
387 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
388
Alp Toker61007d82014-03-02 03:20:38 +0000389 enum : unsigned { NoCand = ~0u };
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000390
391 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
392 /// NoCand which indicates the stack interval.
393 SmallVector<unsigned, 32> BundleCand;
394
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000395 /// Callee-save register cost, calculated once per machine function.
396 BlockFrequency CSRCost;
397
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000398 /// Run or not the local reassignment heuristic. This information is
399 /// obtained from the TargetSubtargetInfo.
400 bool EnableLocalReassign;
401
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000402 /// Enable or not the consideration of the cost of local intervals created
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000403 /// by a split candidate when choosing the best split candidate.
404 bool EnableAdvancedRASplitCost;
405
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000406 /// Set of broken hints that may be reconciled later because of eviction.
407 SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
408
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000409public:
410 RAGreedy();
411
412 /// Return the pass name.
Mehdi Amini117296c2016-10-01 02:56:57 +0000413 StringRef getPassName() const override { return "Greedy Register Allocator"; }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000414
415 /// RAGreedy analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000416 void getAnalysisUsage(AnalysisUsage &AU) const override;
417 void releaseMemory() override;
418 Spiller &spiller() override { return *SpillerInstance; }
419 void enqueue(LiveInterval *LI) override;
420 LiveInterval *dequeue() override;
421 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000422 void aboutToRemoveInterval(LiveInterval &) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000423
424 /// Perform register allocation.
Craig Topper4584cd52014-03-07 09:26:03 +0000425 bool runOnMachineFunction(MachineFunction &mf) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000426
Matthias Braun90799ce2016-08-23 21:19:49 +0000427 MachineFunctionProperties getRequiredProperties() const override {
428 return MachineFunctionProperties().set(
429 MachineFunctionProperties::Property::NoPHIs);
430 }
431
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000432 static char ID;
Andrew Trickccef0982010-12-09 18:15:21 +0000433
434private:
Quentin Colombet87769712014-02-05 22:13:59 +0000435 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
436 SmallVirtRegSet &, unsigned = 0);
437
Craig Topper4584cd52014-03-07 09:26:03 +0000438 bool LRE_CanEraseVirtReg(unsigned) override;
439 void LRE_WillShrinkVirtReg(unsigned) override;
440 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
Quentin Colombet87769712014-02-05 22:13:59 +0000441 void enqueue(PQueue &CurQueue, LiveInterval *LI);
442 LiveInterval *dequeue(PQueue &CurQueue);
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000443
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000444 BlockFrequency calcSpillCost();
445 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000446 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000447 void growRegion(GlobalSplitCandidate &Cand);
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000448 bool splitCanCauseEvictionChain(unsigned Evictee, GlobalSplitCandidate &Cand,
449 unsigned BBNumber,
450 const AllocationOrder &Order);
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +0000451 bool splitCanCauseLocalSpill(unsigned VirtRegToSplit,
452 GlobalSplitCandidate &Cand, unsigned BBNumber,
453 const AllocationOrder &Order);
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000454 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate &,
455 const AllocationOrder &Order,
456 bool *CanCauseEvictionChain);
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000457 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000458 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000459 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000460 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000461 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
462 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000463 bool canEvictInterferenceInRange(LiveInterval &VirtReg, unsigned PhysReg,
464 SlotIndex Start, SlotIndex End,
465 EvictionCost &MaxCost);
466 unsigned getCheapestEvicteeWeight(const AllocationOrder &Order,
467 LiveInterval &VirtReg, SlotIndex Start,
468 SlotIndex End, float *BestEvictWeight);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000469 void evictInterference(LiveInterval&, unsigned,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000470 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000471 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
472 SmallLISet &RecoloringCandidates,
473 const SmallVirtRegSet &FixedRegisters);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000474
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000475 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000476 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000477 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000478 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000479 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000480 SmallVectorImpl<unsigned>&);
Manman Ren9db66b32014-03-24 23:23:42 +0000481 /// Calculate cost of region splitting.
482 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
483 AllocationOrder &Order,
484 BlockFrequency &BestCost,
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000485 unsigned &NumCands, bool IgnoreCSR,
486 bool *CanCauseEvictionChain = nullptr);
Manman Ren9db66b32014-03-24 23:23:42 +0000487 /// Perform region splitting.
488 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
489 bool HasCompact,
490 SmallVectorImpl<unsigned> &NewVRegs);
Manman Ren9dee4492014-03-27 21:21:57 +0000491 /// Check other options before using a callee-saved register for the first
492 /// time.
493 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
494 unsigned PhysReg, unsigned &CostPerUseLimit,
495 SmallVectorImpl<unsigned> &NewVRegs);
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000496 void initializeCSRCost();
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +0000497 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000498 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +0000499 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000500 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000501 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000502 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000503 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000504 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000505 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
506 SmallVectorImpl<unsigned> &,
507 SmallVirtRegSet &, unsigned);
508 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
509 SmallVirtRegSet &, unsigned);
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000510 void tryHintRecoloring(LiveInterval &);
511 void tryHintsRecoloring();
512
513 /// Model the information carried by one end of a copy.
514 struct HintInfo {
515 /// The frequency of the copy.
516 BlockFrequency Freq;
517 /// The virtual register or physical register.
518 unsigned Reg;
519 /// Its currently assigned register.
520 /// In case of a physical register Reg == PhysReg.
521 unsigned PhysReg;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000522
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000523 HintInfo(BlockFrequency Freq, unsigned Reg, unsigned PhysReg)
524 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
525 };
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000526 using HintsInfo = SmallVector<HintInfo, 4>;
527
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000528 BlockFrequency getBrokenHintFreq(const HintsInfo &, unsigned);
529 void collectHintInfo(unsigned, HintsInfo &);
Matthias Braun953393a2015-07-14 17:38:17 +0000530
531 bool isUnusedCalleeSavedReg(unsigned PhysReg) const;
Adam Nemeta9640662017-01-25 23:20:33 +0000532
533 /// Compute and report the number of spills and reloads for a loop.
534 void reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
535 unsigned &FoldedReloads, unsigned &Spills,
536 unsigned &FoldedSpills);
537
538 /// Report the number of spills and reloads for each loop.
539 void reportNumberOfSplillsReloads() {
540 for (MachineLoop *L : *Loops) {
541 unsigned Reloads, FoldedReloads, Spills, FoldedSpills;
542 reportNumberOfSplillsReloads(L, Reloads, FoldedReloads, Spills,
543 FoldedSpills);
544 }
545 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000546};
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000547
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000548} // end anonymous namespace
549
550char RAGreedy::ID = 0;
Tom Stellard11e60ff2016-11-14 21:50:13 +0000551char &llvm::RAGreedyID = RAGreedy::ID;
552
553INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
554 "Greedy Register Allocator", false, false)
555INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
556INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
557INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
558INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
559INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
560INITIALIZE_PASS_DEPENDENCY(LiveStacks)
561INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
562INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
563INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
564INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
565INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
566INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
Adam Nemeta9640662017-01-25 23:20:33 +0000567INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
Tom Stellard11e60ff2016-11-14 21:50:13 +0000568INITIALIZE_PASS_END(RAGreedy, "greedy",
569 "Greedy Register Allocator", false, false)
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000570
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000571#ifndef NDEBUG
572const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000573 "RS_New",
574 "RS_Assign",
575 "RS_Split",
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000576 "RS_Split2",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000577 "RS_Spill",
Quentin Colombet11922942015-07-17 23:04:06 +0000578 "RS_Memory",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000579 "RS_Done"
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000580};
581#endif
582
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000583// Hysteresis to use when comparing floats.
584// This helps stabilize decisions based on float comparisons.
NAKAMURA Takumia71003a2014-02-04 06:29:38 +0000585const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000586
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000587FunctionPass* llvm::createGreedyRegisterAllocator() {
588 return new RAGreedy();
589}
590
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000591RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000592}
593
594void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
595 AU.setPreservesCFG();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000596 AU.addRequired<MachineBlockFrequencyInfo>();
597 AU.addPreserved<MachineBlockFrequencyInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000598 AU.addRequired<AAResultsWrapperPass>();
599 AU.addPreserved<AAResultsWrapperPass>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000600 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen12243122012-06-08 23:44:45 +0000601 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000602 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000603 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000604 AU.addRequired<LiveDebugVariables>();
605 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000606 AU.addRequired<LiveStacks>();
607 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000608 AU.addRequired<MachineDominatorTree>();
609 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000610 AU.addRequired<MachineLoopInfo>();
611 AU.addPreserved<MachineLoopInfo>();
612 AU.addRequired<VirtRegMap>();
613 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000614 AU.addRequired<LiveRegMatrix>();
615 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000616 AU.addRequired<EdgeBundles>();
617 AU.addRequired<SpillPlacement>();
Adam Nemeta9640662017-01-25 23:20:33 +0000618 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000619 MachineFunctionPass::getAnalysisUsage(AU);
620}
621
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000622//===----------------------------------------------------------------------===//
623// LiveRangeEdit delegate methods
624//===----------------------------------------------------------------------===//
625
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000626bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jonas Paulsson6188f322017-09-15 07:47:38 +0000627 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000628 if (VRM->hasPhys(VirtReg)) {
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000629 Matrix->unassign(LI);
630 aboutToRemoveInterval(LI);
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000631 return true;
632 }
633 // Unassigned virtreg is probably in the priority queue.
634 // RegAllocBase will erase it after dequeueing.
Jonas Paulsson6188f322017-09-15 07:47:38 +0000635 // Nonetheless, clear the live-range so that the debug
636 // dump will show the right state for that VirtReg.
637 LI.clear();
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000638 return false;
639}
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000640
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000641void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000642 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000643 return;
644
645 // Register is assigned, put it back on the queue for reassignment.
646 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000647 Matrix->unassign(LI);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000648 enqueue(&LI);
649}
650
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000651void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen811b9c42011-09-14 17:34:37 +0000652 // Cloning a register we haven't even heard about yet? Just ignore it.
653 if (!ExtraRegInfo.inBounds(Old))
654 return;
655
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000656 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000657 // be split into connected components. The new components are much smaller
658 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000659 // same stage as the parent.
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000660 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000661 ExtraRegInfo.grow(New);
662 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000663}
664
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000665void RAGreedy::releaseMemory() {
David Blaikieb61064e2014-07-19 01:05:11 +0000666 SpillerInstance.reset();
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000667 ExtraRegInfo.clear();
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000668 GlobalCand.clear();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000669}
670
Quentin Colombet87769712014-02-05 22:13:59 +0000671void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
672
673void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000674 // Prioritize live ranges by size, assigning larger ranges first.
675 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000676 const unsigned Size = LI->getSize();
677 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000678 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
679 "Can only enqueue virtual registers");
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000680 unsigned Prio;
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000681
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000682 ExtraRegInfo.grow(Reg);
683 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000684 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000685
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000686 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000687 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +0000688 // everything else has been allocated.
689 Prio = Size;
Quentin Colombet11922942015-07-17 23:04:06 +0000690 } else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
691 // Memory operand should be considered last.
692 // Change the priority such that Memory operand are assigned in
693 // the reverse order that they came in.
694 // TODO: Make this a member variable and probably do something about hints.
695 static unsigned MemOp = 0;
696 Prio = MemOp++;
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000697 } else {
Andrew Trick52a00932014-02-26 22:07:26 +0000698 // Giant live ranges fall back to the global assignment heuristic, which
699 // prevents excessive spilling in pathological cases.
700 bool ReverseLocal = TRI->reverseLocalAssignment();
Matthias Brauna354cdd2015-03-31 19:57:53 +0000701 const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
Renato Golin4e31ae12014-10-03 12:20:53 +0000702 bool ForceGlobal = !ReverseLocal &&
Matthias Brauna354cdd2015-03-31 19:57:53 +0000703 (Size / SlotIndex::InstrDist) > (2 * RC.getNumRegs());
Andrew Trick52a00932014-02-26 22:07:26 +0000704
705 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
Andrew Trick84852572013-07-25 18:35:14 +0000706 LIS->intervalIsInOneMBB(*LI)) {
707 // Allocate original local ranges in linear instruction order. Since they
708 // are singly defined, this produces optimal coloring in the absence of
709 // global interference and other constraints.
Andrew Trick52a00932014-02-26 22:07:26 +0000710 if (!ReverseLocal)
Andrew Trick2d8826a2013-12-11 03:40:15 +0000711 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
712 else {
713 // Allocating bottom up may allow many short LRGs to be assigned first
714 // to one of the cheap registers. This could be much faster for very
715 // large blocks on targets with many physical registers.
Matthias Braunf5f89b92015-03-31 19:57:49 +0000716 Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
Andrew Trick2d8826a2013-12-11 03:40:15 +0000717 }
Matthias Brauna354cdd2015-03-31 19:57:53 +0000718 Prio |= RC.AllocationPriority << 24;
719 } else {
Andrew Trick84852572013-07-25 18:35:14 +0000720 // Allocate global and split ranges in long->short order. Long ranges that
721 // don't fit should be spilled (or split) ASAP so they don't create
722 // interference. Mark a bit to prioritize global above local ranges.
723 Prio = (1u << 29) + Size;
724 }
725 // Mark a higher bit to prioritize global and local above RS_Split.
726 Prio |= (1u << 31);
Jakob Stoklund Olesenb51f65c2011-02-23 00:56:56 +0000727
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000728 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen74052b02012-12-03 23:23:50 +0000729 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000730 Prio |= (1u << 30);
731 }
Andrew Trickf4b1ee32013-07-25 18:35:22 +0000732 // The virtual register number is a tie breaker for same-sized ranges.
733 // Give lower vreg numbers higher priority to assign them first.
Quentin Colombet87769712014-02-05 22:13:59 +0000734 CurQueue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000735}
736
Quentin Colombet87769712014-02-05 22:13:59 +0000737LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
738
739LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
740 if (CurQueue.empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000741 return nullptr;
Quentin Colombet87769712014-02-05 22:13:59 +0000742 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
743 CurQueue.pop();
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000744 return LI;
745}
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000746
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000747//===----------------------------------------------------------------------===//
748// Direct Assignment
749//===----------------------------------------------------------------------===//
750
751/// tryAssign - Try to assign VirtReg to an available register.
752unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
753 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000754 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000755 Order.rewind();
756 unsigned PhysReg;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000757 while ((PhysReg = Order.next()))
758 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000759 break;
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000760 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000761 return PhysReg;
762
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000763 // PhysReg is available, but there may be a better choice.
764
765 // If we missed a simple hint, try to cheaply evict interference from the
766 // preferred register.
767 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000768 if (Order.isHint(Hint)) {
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000769 DEBUG(dbgs() << "missed hint " << printReg(Hint, TRI) << '\n');
Andrew Trick3621b8a2013-11-22 19:07:38 +0000770 EvictionCost MaxCost;
771 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000772 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
773 evictInterference(VirtReg, Hint, NewVRegs);
774 return Hint;
775 }
Quentin Colombetfb9b0cd2016-11-16 01:07:12 +0000776 // Record the missed hint, we may be able to recover
777 // at the end if the surrounding allocation changed.
778 SetOfBrokenHints.insert(&VirtReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000779 }
780
781 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000782 unsigned Cost = TRI->getCostPerUse(PhysReg);
783
784 // Most registers have 0 additional cost.
785 if (!Cost)
786 return PhysReg;
787
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000788 DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost " << Cost
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000789 << '\n');
790 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
791 return CheapReg ? CheapReg : PhysReg;
792}
793
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000794//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000795// Interference eviction
796//===----------------------------------------------------------------------===//
797
Andrew Trick8bb0a252013-07-25 18:35:19 +0000798unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
Matthias Braun5d1f12d2015-07-15 22:16:00 +0000799 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000800 unsigned PhysReg;
801 while ((PhysReg = Order.next())) {
802 if (PhysReg == PrevReg)
803 continue;
804
805 MCRegUnitIterator Units(PhysReg, TRI);
806 for (; Units.isValid(); ++Units) {
807 // Instantiate a "subquery", not to be confused with the Queries array.
Matthias Braun173e1142017-03-01 21:48:12 +0000808 LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000809 if (subQ.checkInterference())
810 break;
811 }
812 // If no units have interference, break out with the current PhysReg.
813 if (!Units.isValid())
814 break;
815 }
816 if (PhysReg)
817 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000818 << printReg(PrevReg, TRI) << " to " << printReg(PhysReg, TRI)
Andrew Trick8bb0a252013-07-25 18:35:19 +0000819 << '\n');
820 return PhysReg;
821}
822
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000823/// shouldEvict - determine if A should evict the assigned live range B. The
824/// eviction policy defined by this function together with the allocation order
825/// defined by enqueue() decides which registers ultimately end up being split
826/// and spilled.
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000827///
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000828/// Cascade numbers are used to prevent infinite loops if this function is a
829/// cyclic relation.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000830///
831/// @param A The live range to be assigned.
832/// @param IsHint True when A is about to be assigned to its preferred
833/// register.
834/// @param B The live range to be evicted.
835/// @param BreaksHint True when B is already assigned to its preferred register.
836bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
837 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000838 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000839
840 // Be fairly aggressive about following hints as long as the evictee can be
841 // split.
842 if (CanSplit && IsHint && !BreaksHint)
843 return true;
844
Andrew Trick059e8002013-11-22 19:07:42 +0000845 if (A.weight > B.weight) {
846 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
847 return true;
848 }
849 return false;
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000850}
851
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000852/// canEvictInterference - Return true if all interferences between VirtReg and
Manman Renfa32ca12014-02-25 19:47:15 +0000853/// PhysReg can be evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000854///
855/// @param VirtReg Live range that is about to be assigned.
856/// @param PhysReg Desired register for assignment.
Dmitri Gribenko881929c2012-09-12 16:59:47 +0000857/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000858/// @param MaxCost Only look for cheaper candidates and update with new cost
859/// when returning true.
860/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000861bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000862 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000863 // It is only possible to evict virtual register interference.
864 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
865 return false;
866
Andrew Trick84852572013-07-25 18:35:14 +0000867 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
868
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000869 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
870 // involved in an eviction before. If a cascade number was assigned, deny
871 // evicting anything with the same or a newer cascade number. This prevents
872 // infinite eviction loops.
873 //
874 // This works out so a register without a cascade number is allowed to evict
875 // anything, and it can be evicted by anything.
876 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
877 if (!Cascade)
878 Cascade = NextCascade;
879
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000880 EvictionCost Cost;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000881 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
882 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000883 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000884 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000885 return false;
886
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000887 // Check if any interfering live range is heavier than MaxWeight.
888 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
889 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000890 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
891 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000892 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000893 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000894 return false;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000895 // Once a live range becomes small enough, it is urgent that we find a
896 // register for it. This is indicated by an infinite spill weight. These
897 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen05e22452012-05-30 21:46:58 +0000898 //
899 // Also allow urgent evictions of unspillable ranges from a strictly
900 // larger allocation order.
901 bool Urgent = !VirtReg.isSpillable() &&
902 (Intf->isSpillable() ||
903 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
904 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000905 // Only evict older cascades or live ranges without a cascade.
906 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
907 if (Cascade <= IntfCascade) {
908 if (!Urgent)
909 return false;
910 // We permit breaking cascades for urgent evictions. It should be the
911 // last resort, though, so make it really expensive.
912 Cost.BrokenHints += 10;
913 }
914 // Would this break a satisfied hint?
915 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
916 // Update eviction cost.
917 Cost.BrokenHints += BreaksHint;
918 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
919 // Abort if this would be too expensive.
920 if (!(Cost < MaxCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000921 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000922 if (Urgent)
923 continue;
Andrew Trickc2ab53a2013-11-29 23:49:38 +0000924 // Apply the eviction policy for non-urgent evictions.
925 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
926 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000927 // If !MaxCost.isMax(), then we're just looking for a cheap register.
928 // Evicting another local live range in this case could lead to suboptimal
929 // coloring.
Andrew Trick8bb0a252013-07-25 18:35:19 +0000930 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000931 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
Andrew Trick84852572013-07-25 18:35:14 +0000932 return false;
Andrew Trick8bb0a252013-07-25 18:35:19 +0000933 }
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000934 }
935 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000936 MaxCost = Cost;
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000937 return true;
938}
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000939
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000940/// \brief Return true if all interferences between VirtReg and PhysReg between
941/// Start and End can be evicted.
942///
943/// \param VirtReg Live range that is about to be assigned.
944/// \param PhysReg Desired register for assignment.
945/// \param Start Start of range to look for interferences.
946/// \param End End of range to look for interferences.
947/// \param MaxCost Only look for cheaper candidates and update with new cost
948/// when returning true.
949/// \return True when interference can be evicted cheaper than MaxCost.
950bool RAGreedy::canEvictInterferenceInRange(LiveInterval &VirtReg,
951 unsigned PhysReg, SlotIndex Start,
952 SlotIndex End,
953 EvictionCost &MaxCost) {
954 EvictionCost Cost;
955
956 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
957 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
958
959 // Check if any interfering live range is heavier than MaxWeight.
960 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
961 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
962
963 // Check if interference overlast the segment in interest.
964 if (!Intf->overlaps(Start, End))
965 continue;
966
967 // Cannot evict non virtual reg interference.
968 if (!TargetRegisterInfo::isVirtualRegister(Intf->reg))
969 return false;
970 // Never evict spill products. They cannot split or spill.
971 if (getStage(*Intf) == RS_Done)
972 return false;
973
974 // Would this break a satisfied hint?
975 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
976 // Update eviction cost.
977 Cost.BrokenHints += BreaksHint;
978 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
979 // Abort if this would be too expensive.
980 if (!(Cost < MaxCost))
981 return false;
982 }
983 }
984
985 if (Cost.MaxWeight == 0)
986 return false;
987
988 MaxCost = Cost;
989 return true;
990}
991
992/// \brief Return tthe physical register that will be best
993/// candidate for eviction by a local split interval that will be created
994/// between Start and End.
995///
996/// \param Order The allocation order
997/// \param VirtReg Live range that is about to be assigned.
998/// \param Start Start of range to look for interferences
999/// \param End End of range to look for interferences
1000/// \param BestEvictweight The eviction cost of that eviction
1001/// \return The PhysReg which is the best candidate for eviction and the
1002/// eviction cost in BestEvictweight
1003unsigned RAGreedy::getCheapestEvicteeWeight(const AllocationOrder &Order,
1004 LiveInterval &VirtReg,
1005 SlotIndex Start, SlotIndex End,
1006 float *BestEvictweight) {
1007 EvictionCost BestEvictCost;
1008 BestEvictCost.setMax();
1009 BestEvictCost.MaxWeight = VirtReg.weight;
1010 unsigned BestEvicteePhys = 0;
1011
1012 // Go over all physical registers and find the best candidate for eviction
1013 for (auto PhysReg : Order.getOrder()) {
1014
1015 if (!canEvictInterferenceInRange(VirtReg, PhysReg, Start, End,
1016 BestEvictCost))
1017 continue;
1018
1019 // Best so far.
1020 BestEvicteePhys = PhysReg;
1021 }
1022 *BestEvictweight = BestEvictCost.MaxWeight;
1023 return BestEvicteePhys;
1024}
1025
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001026/// evictInterference - Evict any interferring registers that prevent VirtReg
1027/// from being assigned to Physreg. This assumes that canEvictInterference
1028/// returned true.
1029void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001030 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001031 // Make sure that VirtReg has a cascade number, and assign that cascade
1032 // number to every evicted register. These live ranges than then only be
1033 // evicted by a newer cascade, preventing infinite loops.
1034 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
1035 if (!Cascade)
1036 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
1037
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001038 DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI)
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001039 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001040
1041 // Collect all interfering virtregs first.
1042 SmallVector<LiveInterval*, 8> Intfs;
1043 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1044 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Matthias Braunffe40dd2017-03-03 23:27:20 +00001045 // We usually have the interfering VRegs cached so collectInterferingVRegs()
1046 // should be fast, we may need to recalculate if when different physregs
1047 // overlap the same register unit so we had different SubRanges queried
1048 // against it.
1049 Q.collectInterferingVRegs();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001050 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
1051 Intfs.append(IVR.begin(), IVR.end());
1052 }
1053
1054 // Evict them second. This will invalidate the queries.
1055 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
1056 LiveInterval *Intf = Intfs[i];
1057 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
1058 if (!VRM->hasPhys(Intf->reg))
1059 continue;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001060
1061 LastEvicted.addEviction(PhysReg, VirtReg.reg, Intf->reg);
1062
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001063 Matrix->unassign(*Intf);
1064 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
1065 VirtReg.isSpillable() < Intf->isSpillable()) &&
1066 "Cannot decrease cascade number, illegal eviction");
1067 ExtraRegInfo[Intf->reg].Cascade = Cascade;
1068 ++NumEvicted;
Mark Laceyf9ea8852013-08-14 23:50:04 +00001069 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001070 }
1071}
1072
Matthias Braun953393a2015-07-14 17:38:17 +00001073/// Returns true if the given \p PhysReg is a callee saved register and has not
1074/// been used for allocation yet.
1075bool RAGreedy::isUnusedCalleeSavedReg(unsigned PhysReg) const {
1076 unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
1077 if (CSR == 0)
1078 return false;
1079
1080 return !Matrix->isPhysRegUsed(PhysReg);
1081}
1082
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001083/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001084/// @param VirtReg Currently unassigned virtual register.
1085/// @param Order Physregs to try.
1086/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001087unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
1088 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001089 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001090 unsigned CostPerUseLimit) {
Matthias Braun9f15a792016-11-18 19:43:18 +00001091 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
1092 TimePassesIsEnabled);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001093
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001094 // Keep track of the cheapest interference seen so far.
Andrew Trick3621b8a2013-11-22 19:07:38 +00001095 EvictionCost BestCost;
1096 BestCost.setMax();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001097 unsigned BestPhys = 0;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +00001098 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001099
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001100 // When we are just looking for a reduced cost per use, don't break any
1101 // hints, and only evict smaller spill weights.
1102 if (CostPerUseLimit < ~0u) {
1103 BestCost.BrokenHints = 0;
1104 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +00001105
1106 // Check of any registers in RC are below CostPerUseLimit.
1107 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
1108 unsigned MinCost = RegClassInfo.getMinCost(RC);
1109 if (MinCost >= CostPerUseLimit) {
Craig Toppercf0444b2014-11-17 05:50:14 +00001110 DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = " << MinCost
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +00001111 << ", no cheaper registers to be found.\n");
1112 return 0;
1113 }
1114
1115 // It is normal for register classes to have a long tail of registers with
1116 // the same cost. We don't need to look at them if they're too expensive.
1117 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
1118 OrderLimit = RegClassInfo.getLastCostChange(RC);
1119 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
1120 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001121 }
1122
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001123 Order.rewind();
Aditya Nandakumar73f3d332013-12-05 21:18:40 +00001124 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001125 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
1126 continue;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001127 // The first use of a callee-saved register in a function has cost 1.
1128 // Don't start using a CSR when the CostPerUseLimit is low.
Matthias Braun953393a2015-07-14 17:38:17 +00001129 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001130 DEBUG(dbgs() << printReg(PhysReg, TRI) << " would clobber CSR "
1131 << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
Matthias Braun953393a2015-07-14 17:38:17 +00001132 << '\n');
1133 continue;
1134 }
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001135
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001136 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001137 continue;
1138
1139 // Best so far.
1140 BestPhys = PhysReg;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001141
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +00001142 // Stop if the hint can be used.
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +00001143 if (Order.isHint())
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +00001144 break;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +00001145 }
1146
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001147 if (!BestPhys)
1148 return 0;
1149
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001150 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001151 return BestPhys;
Andrew Trickccef0982010-12-09 18:15:21 +00001152}
1153
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001154//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001155// Region Splitting
1156//===----------------------------------------------------------------------===//
1157
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001158/// addSplitConstraints - Fill out the SplitConstraints vector based on the
1159/// interference pattern in Physreg and its aliases. Add the constraints to
1160/// SpillPlacement and return the static cost of this split in Cost, assuming
1161/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001162/// Return false if there are no bundles with positive bias.
1163bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001164 BlockFrequency &Cost) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001165 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001166
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001167 // Reset interference dependent info.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001168 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001169 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001170 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1171 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001172 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001173
Jakob Stoklund Olesenb1b76ad2011-02-09 22:50:26 +00001174 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001175 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001176 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
1177 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie041f1aa2013-05-15 07:36:59 +00001178 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001179
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001180 if (!Intf.hasInterference())
1181 continue;
1182
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001183 // Number of spill code instructions to insert.
1184 unsigned Ins = 0;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001185
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001186 // Interference for the live-in value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001187 if (BI.LiveIn) {
Richard Trieu7a083812016-02-18 22:09:30 +00001188 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
1189 BC.Entry = SpillPlacement::MustSpill;
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001190 ++Ins;
Richard Trieu7a083812016-02-18 22:09:30 +00001191 } else if (Intf.first() < BI.FirstInstr) {
1192 BC.Entry = SpillPlacement::PrefSpill;
1193 ++Ins;
1194 } else if (Intf.first() < BI.LastInstr) {
1195 ++Ins;
1196 }
Jakob Stoklund Olesenf248b202011-02-08 23:02:58 +00001197 }
1198
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001199 // Interference for the live-out value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001200 if (BI.LiveOut) {
Richard Trieu7a083812016-02-18 22:09:30 +00001201 if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
1202 BC.Exit = SpillPlacement::MustSpill;
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001203 ++Ins;
Richard Trieu7a083812016-02-18 22:09:30 +00001204 } else if (Intf.last() > BI.LastInstr) {
1205 BC.Exit = SpillPlacement::PrefSpill;
1206 ++Ins;
1207 } else if (Intf.last() > BI.FirstInstr) {
1208 ++Ins;
1209 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001210 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001211
1212 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001213 while (Ins--)
1214 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001215 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001216 Cost = StaticCost;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001217
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001218 // Add constraints for use-blocks. Note that these are the only constraints
1219 // that may add a positive bias, it is downhill from here.
1220 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001221 return SpillPlacer->scanActiveBundles();
1222}
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001223
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001224/// addThroughConstraints - Add constraints and links to SpillPlacer from the
1225/// live-through blocks in Blocks.
1226void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
1227 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001228 const unsigned GroupSize = 8;
1229 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001230 unsigned TBS[GroupSize];
1231 unsigned B = 0, T = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001232
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001233 for (unsigned i = 0; i != Blocks.size(); ++i) {
1234 unsigned Number = Blocks[i];
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001235 Intf.moveToBlock(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001236
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001237 if (!Intf.hasInterference()) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001238 assert(T < GroupSize && "Array overflow");
1239 TBS[T] = Number;
1240 if (++T == GroupSize) {
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001241 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001242 T = 0;
1243 }
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001244 continue;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001245 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001246
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001247 assert(B < GroupSize && "Array overflow");
1248 BCS[B].Number = Number;
1249
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001250 // Interference for the live-in value.
1251 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
1252 BCS[B].Entry = SpillPlacement::MustSpill;
1253 else
1254 BCS[B].Entry = SpillPlacement::PrefSpill;
1255
1256 // Interference for the live-out value.
1257 if (Intf.last() >= SA->getLastSplitPoint(Number))
1258 BCS[B].Exit = SpillPlacement::MustSpill;
1259 else
1260 BCS[B].Exit = SpillPlacement::PrefSpill;
1261
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001262 if (++B == GroupSize) {
Craig Toppere1d12942014-08-27 05:25:25 +00001263 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001264 B = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001265 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001266 }
1267
Craig Toppere1d12942014-08-27 05:25:25 +00001268 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001269 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001270}
1271
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001272void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001273 // Keep track of through blocks that have not been added to SpillPlacer.
1274 BitVector Todo = SA->getThroughBlocks();
1275 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
1276 unsigned AddedTo = 0;
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001277#ifndef NDEBUG
1278 unsigned Visited = 0;
1279#endif
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001280
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001281 while (true) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001282 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001283 // Find new through blocks in the periphery of PrefRegBundles.
1284 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
1285 unsigned Bundle = NewBundles[i];
1286 // Look at all blocks connected to Bundle in the full graph.
1287 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
1288 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
1289 I != E; ++I) {
1290 unsigned Block = *I;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001291 if (!Todo.test(Block))
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001292 continue;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001293 Todo.reset(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001294 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001295 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001296#ifndef NDEBUG
1297 ++Visited;
1298#endif
1299 }
1300 }
1301 // Any new blocks to add?
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001302 if (ActiveBlocks.size() == AddedTo)
1303 break;
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001304
1305 // Compute through constraints from the interference, or assume that all
1306 // through blocks prefer spilling when forming compact regions.
Craig Toppere1d12942014-08-27 05:25:25 +00001307 auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001308 if (Cand.PhysReg)
1309 addThroughConstraints(Cand.Intf, NewBlocks);
1310 else
Jakob Stoklund Olesen86954522011-08-03 23:09:38 +00001311 // Provide a strong negative bias on through blocks to prevent unwanted
1312 // liveness on loop backedges.
1313 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001314 AddedTo = ActiveBlocks.size();
1315
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001316 // Perhaps iterating can enable more bundles?
1317 SpillPlacer->iterate();
1318 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001319 DEBUG(dbgs() << ", v=" << Visited);
1320}
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001321
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001322/// calcCompactRegion - Compute the set of edge bundles that should be live
1323/// when splitting the current live range into compact regions. Compact
1324/// regions can be computed without looking at interference. They are the
1325/// regions formed by removing all the live-through blocks from the live range.
1326///
1327/// Returns false if the current live range is already compact, or if the
1328/// compact regions would form single block regions anyway.
1329bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1330 // Without any through blocks, the live range is already compact.
1331 if (!SA->getNumThroughBlocks())
1332 return false;
1333
1334 // Compact regions don't correspond to any physreg.
1335 Cand.reset(IntfCache, 0);
1336
1337 DEBUG(dbgs() << "Compact region bundles");
1338
1339 // Use the spill placer to determine the live bundles. GrowRegion pretends
1340 // that all the through blocks have interference when PhysReg is unset.
1341 SpillPlacer->prepare(Cand.LiveBundles);
1342
1343 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001344 BlockFrequency Cost;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001345 if (!addSplitConstraints(Cand.Intf, Cost)) {
1346 DEBUG(dbgs() << ", none.\n");
1347 return false;
1348 }
1349
1350 growRegion(Cand);
1351 SpillPlacer->finish();
1352
1353 if (!Cand.LiveBundles.any()) {
1354 DEBUG(dbgs() << ", none.\n");
1355 return false;
1356 }
1357
1358 DEBUG({
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001359 for (int i : Cand.LiveBundles.set_bits())
1360 dbgs() << " EB#" << i;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001361 dbgs() << ".\n";
1362 });
1363 return true;
1364}
1365
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001366/// calcSpillCost - Compute how expensive it would be to split the live range in
1367/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001368BlockFrequency RAGreedy::calcSpillCost() {
1369 BlockFrequency Cost = 0;
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001370 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1371 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1372 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1373 unsigned Number = BI.MBB->getNumber();
1374 // We normally only need one spill instruction - a load or a store.
1375 Cost += SpillPlacer->getBlockFrequency(Number);
1376
1377 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3c145052011-08-02 23:04:08 +00001378 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1379 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001380 }
1381 return Cost;
1382}
1383
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001384/// \brief Check if splitting Evictee will create a local split interval in
1385/// basic block number BBNumber that may cause a bad eviction chain. This is
1386/// intended to prevent bad eviction sequences like:
1387/// movl %ebp, 8(%esp) # 4-byte Spill
1388/// movl %ecx, %ebp
1389/// movl %ebx, %ecx
1390/// movl %edi, %ebx
1391/// movl %edx, %edi
1392/// cltd
1393/// idivl %esi
1394/// movl %edi, %edx
1395/// movl %ebx, %edi
1396/// movl %ecx, %ebx
1397/// movl %ebp, %ecx
1398/// movl 16(%esp), %ebp # 4 - byte Reload
1399///
1400/// Such sequences are created in 2 scenarios:
1401///
1402/// Scenario #1:
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001403/// %0 is evicted from physreg0 by %1.
1404/// Evictee %0 is intended for region splitting with split candidate
1405/// physreg0 (the reg %0 was evicted from).
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001406/// Region splitting creates a local interval because of interference with the
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001407/// evictor %1 (normally region spliitting creates 2 interval, the "by reg"
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001408/// and "by stack" intervals and local interval created when interference
1409/// occurs).
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001410/// One of the split intervals ends up evicting %2 from physreg1.
1411/// Evictee %2 is intended for region splitting with split candidate
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001412/// physreg1.
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001413/// One of the split intervals ends up evicting %3 from physreg2, etc.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001414///
1415/// Scenario #2
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001416/// %0 is evicted from physreg0 by %1.
1417/// %2 is evicted from physreg2 by %3 etc.
1418/// Evictee %0 is intended for region splitting with split candidate
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001419/// physreg1.
1420/// Region splitting creates a local interval because of interference with the
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001421/// evictor %1.
1422/// One of the split intervals ends up evicting back original evictor %1
1423/// from physreg0 (the reg %0 was evicted from).
1424/// Another evictee %2 is intended for region splitting with split candidate
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001425/// physreg1.
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001426/// One of the split intervals ends up evicting %3 from physreg2, etc.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001427///
1428/// \param Evictee The register considered to be split.
1429/// \param Cand The split candidate that determines the physical register
1430/// we are splitting for and the interferences.
1431/// \param BBNumber The number of a BB for which the region split process will
1432/// create a local split interval.
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001433/// \param Order The physical registers that may get evicted by a split
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001434/// artifact of Evictee.
1435/// \return True if splitting Evictee may cause a bad eviction chain, false
1436/// otherwise.
1437bool RAGreedy::splitCanCauseEvictionChain(unsigned Evictee,
1438 GlobalSplitCandidate &Cand,
1439 unsigned BBNumber,
1440 const AllocationOrder &Order) {
1441 EvictionTrack::EvictorInfo VregEvictorInfo = LastEvicted.getEvictor(Evictee);
1442 unsigned Evictor = VregEvictorInfo.first;
1443 unsigned PhysReg = VregEvictorInfo.second;
1444
1445 // No actual evictor.
1446 if (!Evictor || !PhysReg)
1447 return false;
1448
1449 float MaxWeight = 0;
1450 unsigned FutureEvictedPhysReg =
1451 getCheapestEvicteeWeight(Order, LIS->getInterval(Evictee),
1452 Cand.Intf.first(), Cand.Intf.last(), &MaxWeight);
1453
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001454 // The bad eviction chain occurs when either the split candidate is the
1455 // evicting reg or one of the split artifact will evict the evicting reg.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001456 if ((PhysReg != Cand.PhysReg) && (PhysReg != FutureEvictedPhysReg))
1457 return false;
1458
1459 Cand.Intf.moveToBlock(BBNumber);
1460
1461 // Check to see if the Evictor contains interference (with Evictee) in the
1462 // given BB. If so, this interference caused the eviction of Evictee from
1463 // PhysReg. This suggest that we will create a local interval during the
1464 // region split to avoid this interference This local interval may cause a bad
1465 // eviction chain.
1466 if (!LIS->hasInterval(Evictor))
1467 return false;
1468 LiveInterval &EvictorLI = LIS->getInterval(Evictor);
1469 if (EvictorLI.FindSegmentContaining(Cand.Intf.first()) == EvictorLI.end())
1470 return false;
1471
1472 // Now, check to see if the local interval we will create is going to be
1473 // expensive enough to evict somebody If so, this may cause a bad eviction
1474 // chain.
1475 VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1476 float splitArtifactWeight =
1477 VRAI.futureWeight(LIS->getInterval(Evictee),
1478 Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1479 if (splitArtifactWeight >= 0 && splitArtifactWeight < MaxWeight)
1480 return false;
1481
1482 return true;
1483}
1484
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001485/// \brief Check if splitting VirtRegToSplit will create a local split interval
1486/// in basic block number BBNumber that may cause a spill.
1487///
1488/// \param VirtRegToSplit The register considered to be split.
1489/// \param Cand The split candidate that determines the physical
1490/// register we are splitting for and the interferences.
1491/// \param BBNumber The number of a BB for which the region split process
1492/// will create a local split interval.
1493/// \param Order The physical registers that may get evicted by a
1494/// split artifact of VirtRegToSplit.
1495/// \return True if splitting VirtRegToSplit may cause a spill, false
1496/// otherwise.
1497bool RAGreedy::splitCanCauseLocalSpill(unsigned VirtRegToSplit,
1498 GlobalSplitCandidate &Cand,
1499 unsigned BBNumber,
1500 const AllocationOrder &Order) {
1501 Cand.Intf.moveToBlock(BBNumber);
1502
1503 // Check if the local interval will find a non interfereing assignment.
1504 for (auto PhysReg : Order.getOrder()) {
1505 if (!Matrix->checkInterference(Cand.Intf.first().getPrevIndex(),
1506 Cand.Intf.last(), PhysReg))
1507 return false;
1508 }
1509
1510 // Check if the local interval will evict a cheaper interval.
1511 float CheapestEvictWeight = 0;
1512 unsigned FutureEvictedPhysReg = getCheapestEvicteeWeight(
1513 Order, LIS->getInterval(VirtRegToSplit), Cand.Intf.first(),
1514 Cand.Intf.last(), &CheapestEvictWeight);
1515
1516 // Have we found an interval that can be evicted?
1517 if (FutureEvictedPhysReg) {
1518 VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1519 float splitArtifactWeight =
1520 VRAI.futureWeight(LIS->getInterval(VirtRegToSplit),
1521 Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1522 // Will the weight of the local interval be higher than the cheapest evictee
1523 // weight? If so it will evict it and will not cause a spill.
1524 if (splitArtifactWeight >= 0 && splitArtifactWeight > CheapestEvictWeight)
1525 return false;
1526 }
1527
1528 // The local interval is not able to find non interferening assignment and not
1529 // able to evict a less worthy interval, therfore, it can cause a spill.
1530 return true;
1531}
1532
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001533/// calcGlobalSplitCost - Return the global split cost of following the split
1534/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001535/// interference pattern in SplitConstraints.
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001536///
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001537BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
1538 const AllocationOrder &Order,
1539 bool *CanCauseEvictionChain) {
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001540 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001541 const BitVector &LiveBundles = Cand.LiveBundles;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001542 unsigned VirtRegToSplit = SA->getParent().reg;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001543 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1544 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1545 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001546 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001547 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, false)];
1548 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)];
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001549 unsigned Ins = 0;
1550
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001551 Cand.Intf.moveToBlock(BC.Number);
1552 // Check wheather a local interval is going to be created during the region
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001553 // split. Calculate adavanced spilt cost (cost of local intervals) if option
1554 // is enabled.
1555 if (EnableAdvancedRASplitCost && Cand.Intf.hasInterference() && BI.LiveIn &&
1556 BI.LiveOut && RegIn && RegOut) {
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001557
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001558 if (CanCauseEvictionChain &&
1559 splitCanCauseEvictionChain(VirtRegToSplit, Cand, BC.Number, Order)) {
1560 // This interference causes our eviction from this assignment, we might
1561 // evict somebody else and eventually someone will spill, add that cost.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001562 // See splitCanCauseEvictionChain for detailed description of scenarios.
1563 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1564 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1565
1566 *CanCauseEvictionChain = true;
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001567
1568 } else if (splitCanCauseLocalSpill(VirtRegToSplit, Cand, BC.Number,
1569 Order)) {
1570 // This interference causes local interval to spill, add that cost.
1571 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1572 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001573 }
1574 }
1575
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001576 if (BI.LiveIn)
1577 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1578 if (BI.LiveOut)
1579 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001580 while (Ins--)
1581 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001582 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001583
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001584 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1585 unsigned Number = Cand.ActiveBlocks[i];
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001586 bool RegIn = LiveBundles[Bundles->getBundle(Number, false)];
1587 bool RegOut = LiveBundles[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001588 if (!RegIn && !RegOut)
1589 continue;
1590 if (RegIn && RegOut) {
1591 // We need double spill code if this block has interference.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001592 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001593 if (Cand.Intf.hasInterference()) {
1594 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1595 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001596
1597 // Check wheather a local interval is going to be created during the
1598 // region split.
1599 if (EnableAdvancedRASplitCost && CanCauseEvictionChain &&
1600 splitCanCauseEvictionChain(VirtRegToSplit, Cand, Number, Order)) {
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001601 // This interference cause our eviction from this assignment, we might
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001602 // evict somebody else, add that cost.
1603 // See splitCanCauseEvictionChain for detailed description of
1604 // scenarios.
1605 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1606 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1607
1608 *CanCauseEvictionChain = true;
1609 }
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001610 }
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001611 continue;
1612 }
1613 // live-in / stack-out or stack-in live-out.
1614 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001615 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001616 return GlobalCost;
1617}
1618
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001619/// splitAroundRegion - Split the current live range around the regions
1620/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001621///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001622/// Before calling this function, GlobalCand and BundleCand must be initialized
1623/// so each bundle is assigned to a valid candidate, or NoCand for the
1624/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1625/// objects must be initialized for the current live range, and intervals
1626/// created for the used candidates.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001627///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001628/// @param LREdit The LiveRangeEdit object handling the current split.
1629/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1630/// must appear in this list.
1631void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1632 ArrayRef<unsigned> UsedCands) {
1633 // These are the intervals created for new global ranges. We may create more
1634 // intervals for local ranges.
1635 const unsigned NumGlobalIntvs = LREdit.size();
1636 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1637 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001638
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001639 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen22f37a12011-08-06 18:20:24 +00001640 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001641 // is all copies.
1642 unsigned Reg = SA->getParent().reg;
1643 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1644
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001645 // First handle all the blocks with uses.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001646 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1647 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1648 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001649 unsigned Number = BI.MBB->getNumber();
1650 unsigned IntvIn = 0, IntvOut = 0;
1651 SlotIndex IntfIn, IntfOut;
1652 if (BI.LiveIn) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001653 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001654 if (CandIn != NoCand) {
1655 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1656 IntvIn = Cand.IntvIdx;
1657 Cand.Intf.moveToBlock(Number);
1658 IntfIn = Cand.Intf.first();
1659 }
1660 }
1661 if (BI.LiveOut) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001662 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001663 if (CandOut != NoCand) {
1664 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1665 IntvOut = Cand.IntvIdx;
1666 Cand.Intf.moveToBlock(Number);
1667 IntfOut = Cand.Intf.last();
1668 }
1669 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001670
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001671 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001672 if (!IntvIn && !IntvOut) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001673 DEBUG(dbgs() << printMBBReference(*BI.MBB) << " isolated.\n");
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001674 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001675 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001676 continue;
1677 }
1678
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001679 if (IntvIn && IntvOut)
1680 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1681 else if (IntvIn)
1682 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesen795da1c2011-07-15 21:47:57 +00001683 else
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001684 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001685 }
1686
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001687 // Handle live-through blocks. The relevant live-through blocks are stored in
1688 // the ActiveBlocks list with each candidate. We need to filter out
1689 // duplicates.
1690 BitVector Todo = SA->getThroughBlocks();
1691 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1692 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1693 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1694 unsigned Number = Blocks[i];
1695 if (!Todo.test(Number))
1696 continue;
1697 Todo.reset(Number);
1698
1699 unsigned IntvIn = 0, IntvOut = 0;
1700 SlotIndex IntfIn, IntfOut;
1701
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001702 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001703 if (CandIn != NoCand) {
1704 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1705 IntvIn = Cand.IntvIdx;
1706 Cand.Intf.moveToBlock(Number);
1707 IntfIn = Cand.Intf.first();
1708 }
1709
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001710 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001711 if (CandOut != NoCand) {
1712 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1713 IntvOut = Cand.IntvIdx;
1714 Cand.Intf.moveToBlock(Number);
1715 IntfOut = Cand.Intf.last();
1716 }
1717 if (!IntvIn && !IntvOut)
1718 continue;
1719 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1720 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001721 }
1722
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001723 ++NumGlobalSplits;
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001724
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001725 SmallVector<unsigned, 8> IntvMap;
1726 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001727 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001728
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001729 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen5cc91b22011-05-28 02:32:57 +00001730 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001731
1732 // Sort out the new intervals created by splitting. We get four kinds:
1733 // - Remainder intervals should not be split again.
1734 // - Candidate intervals can be assigned to Cand.PhysReg.
1735 // - Block-local splits are candidates for local splitting.
1736 // - DCE leftovers should go back on the queue.
1737 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001738 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001739
1740 // Ignore old intervals from DCE.
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001741 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001742 continue;
1743
1744 // Remainder interval. Don't try splitting again, spill if it doesn't
1745 // allocate.
1746 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001747 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001748 continue;
1749 }
1750
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001751 // Global intervals. Allow repeated splitting as long as the number of live
1752 // blocks is strictly decreasing.
1753 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001754 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001755 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1756 << " blocks as original.\n");
1757 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001758 setStage(Reg, RS_Split2);
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001759 }
1760 continue;
1761 }
1762
1763 // Other intervals are treated as new. This includes local intervals created
1764 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001765 }
1766
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +00001767 if (VerifyEnabled)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001768 MF->verify(this, "After splitting live range around region");
1769}
1770
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001771unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001772 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001773 unsigned NumCands = 0;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001774 BlockFrequency SpillCost = calcSpillCost();
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001775 BlockFrequency BestCost;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001776
1777 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +00001778 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001779 if (HasCompact) {
1780 // Yes, keep GlobalCand[0] as the compact region candidate.
1781 NumCands = 1;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001782 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001783 } else {
1784 // No benefit from the compact region, our fallback will be per-block
1785 // splitting. Make sure we find a solution that is cheaper than spilling.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001786 BestCost = SpillCost;
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001787 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1788 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001789 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001790
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001791 bool CanCauseEvictionChain = false;
Manman Ren9db66b32014-03-24 23:23:42 +00001792 unsigned BestCand =
Manman Ren78cf02a2014-03-25 00:16:25 +00001793 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001794 false /*IgnoreCSR*/, &CanCauseEvictionChain);
1795
1796 // Split candidates with compact regions can cause a bad eviction sequence.
1797 // See splitCanCauseEvictionChain for detailed description of scenarios.
1798 // To avoid it, we need to comapre the cost with the spill cost and not the
1799 // current max frequency.
1800 if (HasCompact && (BestCost > SpillCost) && (BestCand != NoCand) &&
1801 CanCauseEvictionChain) {
1802 return 0;
1803 }
Manman Ren9db66b32014-03-24 23:23:42 +00001804
1805 // No solutions found, fall back to single block splitting.
1806 if (!HasCompact && BestCand == NoCand)
1807 return 0;
1808
1809 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1810}
1811
1812unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1813 AllocationOrder &Order,
1814 BlockFrequency &BestCost,
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001815 unsigned &NumCands, bool IgnoreCSR,
1816 bool *CanCauseEvictionChain) {
Manman Ren9db66b32014-03-24 23:23:42 +00001817 unsigned BestCand = NoCand;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001818 Order.rewind();
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001819 while (unsigned PhysReg = Order.next()) {
Matthias Braun953393a2015-07-14 17:38:17 +00001820 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1821 continue;
Manman Ren78cf02a2014-03-25 00:16:25 +00001822
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001823 // Discard bad candidates before we run out of interference cache cursors.
1824 // This will only affect register classes with a lot of registers (>32).
1825 if (NumCands == IntfCache.getMaxCursors()) {
1826 unsigned WorstCount = ~0u;
1827 unsigned Worst = 0;
1828 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001829 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001830 continue;
1831 unsigned Count = GlobalCand[i].LiveBundles.count();
Richard Trieu7a083812016-02-18 22:09:30 +00001832 if (Count < WorstCount) {
1833 Worst = i;
1834 WorstCount = Count;
1835 }
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001836 }
1837 --NumCands;
1838 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen559d4dc2011-11-01 00:02:31 +00001839 if (BestCand == NumCands)
1840 BestCand = Worst;
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001841 }
1842
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001843 if (GlobalCand.size() <= NumCands)
1844 GlobalCand.resize(NumCands+1);
1845 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1846 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001847
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001848 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001849 BlockFrequency Cost;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001850 if (!addSplitConstraints(Cand.Intf, Cost)) {
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001851 DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001852 continue;
1853 }
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001854 DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tstatic = ";
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001855 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001856 if (Cost >= BestCost) {
1857 DEBUG({
1858 if (BestCand == NoCand)
1859 dbgs() << " worse than no bundles\n";
1860 else
1861 dbgs() << " worse than "
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001862 << printReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001863 });
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001864 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001865 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001866 growRegion(Cand);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001867
Jakob Stoklund Olesen36b5d8a2011-04-06 19:13:57 +00001868 SpillPlacer->finish();
1869
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001870 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001871 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001872 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001873 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001874 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001875
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001876 bool HasEvictionChain = false;
1877 Cost += calcGlobalSplitCost(Cand, Order, &HasEvictionChain);
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001878 DEBUG({
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001879 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1880 << " with bundles";
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001881 for (int i : Cand.LiveBundles.set_bits())
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001882 dbgs() << " EB#" << i;
1883 dbgs() << ".\n";
1884 });
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001885 if (Cost < BestCost) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001886 BestCand = NumCands;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001887 BestCost = Cost;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001888 // See splitCanCauseEvictionChain for detailed description of bad
1889 // eviction chain scenarios.
1890 if (CanCauseEvictionChain)
1891 *CanCauseEvictionChain = HasEvictionChain;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001892 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001893 ++NumCands;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001894 }
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001895
1896 if (CanCauseEvictionChain && BestCand != NoCand) {
1897 // See splitCanCauseEvictionChain for detailed description of bad
1898 // eviction chain scenarios.
1899 DEBUG(dbgs() << "Best split candidate of vreg "
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001900 << printReg(VirtReg.reg, TRI) << " may ");
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001901 if (!(*CanCauseEvictionChain))
1902 DEBUG(dbgs() << "not ");
1903 DEBUG(dbgs() << "cause bad eviction chain\n");
1904 }
1905
Manman Ren9db66b32014-03-24 23:23:42 +00001906 return BestCand;
1907}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001908
Manman Ren9db66b32014-03-24 23:23:42 +00001909unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1910 bool HasCompact,
1911 SmallVectorImpl<unsigned> &NewVRegs) {
1912 SmallVector<unsigned, 8> UsedCands;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001913 // Prepare split editor.
Wei Mi9a16d652016-04-13 03:08:27 +00001914 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001915 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001916
1917 // Assign all edge bundles to the preferred candidate, or NoCand.
1918 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1919
1920 // Assign bundles for the best candidate region.
1921 if (BestCand != NoCand) {
1922 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1923 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1924 UsedCands.push_back(BestCand);
1925 Cand.IntvIdx = SE->openIntv();
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001926 DEBUG(dbgs() << "Split for " << printReg(Cand.PhysReg, TRI) << " in "
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001927 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001928 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001929 }
1930 }
1931
1932 // Assign bundles for the compact region.
1933 if (HasCompact) {
1934 GlobalSplitCandidate &Cand = GlobalCand.front();
1935 assert(!Cand.PhysReg && "Compact region has no physreg");
1936 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1937 UsedCands.push_back(0);
1938 Cand.IntvIdx = SE->openIntv();
1939 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1940 << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001941 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001942 }
1943 }
1944
1945 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001946 return 0;
1947}
1948
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001949//===----------------------------------------------------------------------===//
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001950// Per-Block Splitting
1951//===----------------------------------------------------------------------===//
1952
1953/// tryBlockSplit - Split a global live range around every block with uses. This
1954/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1955/// they don't allocate.
1956unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001957 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001958 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1959 unsigned Reg = VirtReg.reg;
1960 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Wei Mi9a16d652016-04-13 03:08:27 +00001961 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001962 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001963 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1964 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1965 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1966 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1967 SE->splitSingleBlock(BI);
1968 }
1969 // No blocks were split.
1970 if (LREdit.empty())
1971 return 0;
1972
1973 // We did split for some blocks.
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001974 SmallVector<unsigned, 8> IntvMap;
1975 SE->finish(&IntvMap);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001976
1977 // Tell LiveDebugVariables about the new ranges.
Mark Laceyf9ea8852013-08-14 23:50:04 +00001978 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001979
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001980 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1981
1982 // Sort out the new intervals created by splitting. The remainder interval
1983 // goes straight to spilling, the new local ranges get to stay RS_New.
1984 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001985 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001986 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1987 setStage(LI, RS_Spill);
1988 }
1989
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001990 if (VerifyEnabled)
1991 MF->verify(this, "After splitting live range around basic blocks");
1992 return 0;
1993}
1994
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001995//===----------------------------------------------------------------------===//
1996// Per-Instruction Splitting
1997//===----------------------------------------------------------------------===//
1998
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001999/// Get the number of allocatable registers that match the constraints of \p Reg
2000/// on \p MI and that are also in \p SuperRC.
2001static unsigned getNumAllocatableRegsForConstraints(
2002 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
2003 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
2004 const RegisterClassInfo &RCI) {
2005 assert(SuperRC && "Invalid register class");
2006
2007 const TargetRegisterClass *ConstrainedRC =
2008 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
2009 /* ExploreBundle */ true);
2010 if (!ConstrainedRC)
2011 return 0;
2012 return RCI.getNumAllocatableRegs(ConstrainedRC);
2013}
2014
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002015/// tryInstructionSplit - Split a live range around individual instructions.
2016/// This is normally not worthwhile since the spiller is doing essentially the
2017/// same thing. However, when the live range is in a constrained register
2018/// class, it may help to insert copies such that parts of the live range can
2019/// be moved to a larger register class.
2020///
2021/// This is similar to spilling to a larger register class.
2022unsigned
2023RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002024 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002025 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002026 // There is no point to this if there are no larger sub-classes.
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002027 if (!RegClassInfo.isProperSubClass(CurRC))
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002028 return 0;
2029
2030 // Always enable split spill mode, since we're effectively spilling to a
2031 // register.
Wei Mi9a16d652016-04-13 03:08:27 +00002032 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002033 SE->reset(LREdit, SplitEditor::SM_Size);
2034
2035 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2036 if (Uses.size() <= 1)
2037 return 0;
2038
2039 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
2040
Eric Christopher433c4322015-03-10 23:46:01 +00002041 const TargetRegisterClass *SuperRC =
2042 TRI->getLargestLegalSuperClass(CurRC, *MF);
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002043 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
2044 // Split around every non-copy instruction if this split will relax
2045 // the constraints on the virtual register.
2046 // Otherwise, splitting just inserts uncoalescable copies that do not help
2047 // the allocation.
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002048 for (unsigned i = 0; i != Uses.size(); ++i) {
2049 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002050 if (MI->isFullCopy() ||
2051 SuperRCNumAllocatableRegs ==
2052 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
2053 TRI, RCI)) {
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002054 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
2055 continue;
2056 }
2057 SE->openIntv();
2058 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
2059 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
2060 SE->useIntv(SegStart, SegStop);
2061 }
2062
2063 if (LREdit.empty()) {
2064 DEBUG(dbgs() << "All uses were copies.\n");
2065 return 0;
2066 }
2067
2068 SmallVector<unsigned, 8> IntvMap;
2069 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00002070 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002071 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2072
2073 // Assign all new registers to RS_Spill. This was the last chance.
2074 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
2075 return 0;
2076}
2077
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00002078//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002079// Local Splitting
2080//===----------------------------------------------------------------------===//
2081
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002082/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
2083/// in order to use PhysReg between two entries in SA->UseSlots.
2084///
2085/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
2086///
2087void RAGreedy::calcGapWeights(unsigned PhysReg,
2088 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00002089 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
2090 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00002091 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002092 const unsigned NumGaps = Uses.size()-1;
2093
2094 // Start and end points for the interference check.
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00002095 SlotIndex StartIdx =
2096 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
2097 SlotIndex StopIdx =
2098 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002099
2100 GapWeight.assign(NumGaps, 0.0f);
2101
2102 // Add interference from each overlapping register.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002103 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2104 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
2105 .checkInterference())
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002106 continue;
2107
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00002108 // We know that VirtReg is a continuous interval from FirstInstr to
2109 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002110 //
2111 // Interference that overlaps an instruction is counted in both gaps
2112 // surrounding the instruction. The exception is interference before
2113 // StartIdx and after StopIdx.
2114 //
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002115 LiveIntervalUnion::SegmentIter IntI =
2116 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002117 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
2118 // Skip the gaps before IntI.
2119 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
2120 if (++Gap == NumGaps)
2121 break;
2122 if (Gap == NumGaps)
2123 break;
2124
2125 // Update the gaps covered by IntI.
2126 const float weight = IntI.value()->weight;
2127 for (; Gap != NumGaps; ++Gap) {
2128 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
2129 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
2130 break;
2131 }
2132 if (Gap == NumGaps)
2133 break;
2134 }
2135 }
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002136
2137 // Add fixed interference.
2138 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00002139 const LiveRange &LR = LIS->getRegUnit(*Units);
2140 LiveRange::const_iterator I = LR.find(StartIdx);
2141 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002142
2143 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
2144 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
2145 while (Uses[Gap+1].getBoundaryIndex() < I->start)
2146 if (++Gap == NumGaps)
2147 break;
2148 if (Gap == NumGaps)
2149 break;
2150
2151 for (; Gap != NumGaps; ++Gap) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002152 GapWeight[Gap] = huge_valf;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002153 if (Uses[Gap+1].getBaseIndex() >= I->end)
2154 break;
2155 }
2156 if (Gap == NumGaps)
2157 break;
2158 }
2159 }
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002160}
2161
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002162/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
2163/// basic block.
2164///
2165unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002166 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00002167 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
2168 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002169
2170 // Note that it is possible to have an interval that is live-in or live-out
2171 // while only covering a single block - A phi-def can use undef values from
2172 // predecessors, and the block could be a single-block loop.
2173 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00002174 // that the interval is continuous from FirstInstr to LastInstr. We should
2175 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002176
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00002177 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002178 if (Uses.size() <= 2)
2179 return 0;
2180 const unsigned NumGaps = Uses.size()-1;
2181
2182 DEBUG({
2183 dbgs() << "tryLocalSplit: ";
2184 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00002185 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002186 dbgs() << '\n';
2187 });
2188
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002189 // If VirtReg is live across any register mask operands, compute a list of
2190 // gaps with register masks.
2191 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002192 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002193 // Get regmask slots for the whole block.
2194 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002195 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002196 // Constrain to VirtReg's live range.
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002197 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
2198 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002199 unsigned re = RMS.size();
2200 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002201 // Look for Uses[i] <= RMS <= Uses[i+1].
2202 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
2203 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002204 continue;
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002205 // Skip a regmask on the same instruction as the last use. It doesn't
2206 // overlap the live range.
2207 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
2208 break;
2209 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002210 RegMaskGaps.push_back(i);
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002211 // Advance ri to the next gap. A regmask on one of the uses counts in
2212 // both gaps.
2213 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
2214 ++ri;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002215 }
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002216 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002217 }
2218
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002219 // Since we allow local split results to be split again, there is a risk of
2220 // creating infinite loops. It is tempting to require that the new live
2221 // ranges have less instructions than the original. That would guarantee
2222 // convergence, but it is too strict. A live range with 3 instructions can be
2223 // split 2+3 (including the COPY), and we want to allow that.
2224 //
2225 // Instead we use these rules:
2226 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002227 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002228 // noop split, of course).
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002229 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002230 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002231 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002232 // smaller ranges are marked RS_New.
2233 //
2234 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
2235 // excessive splitting and infinite loops.
2236 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002237 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002238
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002239 // Best split candidate.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002240 unsigned BestBefore = NumGaps;
2241 unsigned BestAfter = 0;
2242 float BestDiff = 0;
2243
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00002244 const float blockFreq =
2245 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Michael Gottesman5e985ee2013-12-14 02:37:38 +00002246 (1.0f / MBFI->getEntryFreq());
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002247 SmallVector<float, 8> GapWeight;
2248
2249 Order.rewind();
2250 while (unsigned PhysReg = Order.next()) {
2251 // Keep track of the largest spill weight that would need to be evicted in
2252 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
2253 calcGapWeights(PhysReg, GapWeight);
2254
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002255 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002256 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002257 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002258 GapWeight[RegMaskGaps[i]] = huge_valf;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002259
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002260 // Try to find the best sequence of gaps to close.
2261 // The new spill weight must be larger than any gap interference.
2262
2263 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002264 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002265
2266 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
2267 // It is the spill weight that needs to be evicted.
2268 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002269
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002270 while (true) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002271 // Live before/after split?
2272 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
2273 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
2274
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00002275 DEBUG(dbgs() << printReg(PhysReg, TRI) << ' '
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002276 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
2277 << " i=" << MaxGap);
2278
2279 // Stop before the interval gets so big we wouldn't be making progress.
2280 if (!LiveBefore && !LiveAfter) {
2281 DEBUG(dbgs() << " all\n");
2282 break;
2283 }
2284 // Should the interval be extended or shrunk?
2285 bool Shrink = true;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002286
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002287 // How many gaps would the new range have?
2288 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
2289
2290 // Legally, without causing looping?
2291 bool Legal = !ProgressRequired || NewGaps < NumGaps;
2292
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002293 if (Legal && MaxGap < huge_valf) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002294 // Estimate the new spill weight. Each instruction reads or writes the
2295 // register. Conservatively assume there are no read-modify-write
2296 // instructions.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002297 //
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002298 // Try to guess the size of the new interval.
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +00002299 const float EstWeight = normalizeSpillWeight(
2300 blockFreq * (NewGaps + 1),
2301 Uses[SplitBefore].distance(Uses[SplitAfter]) +
2302 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
2303 1);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002304 // Would this split be possible to allocate?
2305 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00002306 DEBUG(dbgs() << " w=" << EstWeight);
2307 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002308 Shrink = false;
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00002309 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002310 if (Diff > BestDiff) {
2311 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00002312 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002313 BestBefore = SplitBefore;
2314 BestAfter = SplitAfter;
2315 }
2316 }
2317 }
2318
2319 // Try to shrink.
2320 if (Shrink) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002321 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002322 DEBUG(dbgs() << " shrink\n");
2323 // Recompute the max when necessary.
2324 if (GapWeight[SplitBefore - 1] >= MaxGap) {
2325 MaxGap = GapWeight[SplitBefore];
2326 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
2327 MaxGap = std::max(MaxGap, GapWeight[i]);
2328 }
2329 continue;
2330 }
2331 MaxGap = 0;
2332 }
2333
2334 // Try to extend the interval.
2335 if (SplitAfter >= NumGaps) {
2336 DEBUG(dbgs() << " end\n");
2337 break;
2338 }
2339
2340 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002341 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002342 }
2343 }
2344
2345 // Didn't find any candidates?
2346 if (BestBefore == NumGaps)
2347 return 0;
2348
2349 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
2350 << '-' << Uses[BestAfter] << ", " << BestDiff
2351 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
2352
Wei Mi9a16d652016-04-13 03:08:27 +00002353 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00002354 SE->reset(LREdit);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002355
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00002356 SE->openIntv();
2357 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
2358 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
2359 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002360 SmallVector<unsigned, 8> IntvMap;
2361 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00002362 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002363
2364 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002365 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002366 // leave the new intervals as RS_New so they can compete.
2367 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
2368 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
2369 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
2370 if (NewGaps >= NumGaps) {
2371 DEBUG(dbgs() << "Tagging non-progress ranges: ");
2372 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002373 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
2374 if (IntvMap[i] == 1) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00002375 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00002376 DEBUG(dbgs() << printReg(LREdit.get(i)));
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002377 }
2378 DEBUG(dbgs() << '\n');
2379 }
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00002380 ++NumLocalSplits;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002381
2382 return 0;
2383}
2384
2385//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002386// Live Range Splitting
2387//===----------------------------------------------------------------------===//
2388
2389/// trySplit - Try to split VirtReg or one of its interferences, making it
2390/// assignable.
2391/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
2392unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002393 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesend4bb1d42011-08-05 23:50:33 +00002394 // Ranges must be Split2 or less.
2395 if (getStage(VirtReg) >= RS_Spill)
2396 return 0;
2397
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002398 // Local intervals are handled separately.
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00002399 if (LIS->intervalIsInOneMBB(VirtReg)) {
Matthias Braun9f15a792016-11-18 19:43:18 +00002400 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
2401 TimerGroupDescription, TimePassesIsEnabled);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002402 SA->analyze(&VirtReg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002403 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
2404 if (PhysReg || !NewVRegs.empty())
2405 return PhysReg;
2406 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00002407 }
2408
Matthias Braun9f15a792016-11-18 19:43:18 +00002409 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
2410 TimerGroupDescription, TimePassesIsEnabled);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002411
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002412 SA->analyze(&VirtReg);
2413
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00002414 // FIXME: SplitAnalysis may repair broken live ranges coming from the
2415 // coalescer. That may cause the range to become allocatable which means that
2416 // tryRegionSplit won't be making progress. This check should be replaced with
2417 // an assertion when the coalescer is fixed.
2418 if (SA->didRepairRange()) {
2419 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002420 Matrix->invalidateVirtRegs();
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00002421 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
2422 return PhysReg;
2423 }
2424
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002425 // First try to split around a region spanning multiple blocks. RS_Split2
2426 // ranges already made dubious progress with region splitting, so they go
2427 // straight to single block splitting.
2428 if (getStage(VirtReg) < RS_Split2) {
2429 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2430 if (PhysReg || !NewVRegs.empty())
2431 return PhysReg;
2432 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002433
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00002434 // Then isolate blocks.
2435 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002436}
2437
Quentin Colombet87769712014-02-05 22:13:59 +00002438//===----------------------------------------------------------------------===//
2439// Last Chance Recoloring
2440//===----------------------------------------------------------------------===//
2441
Mikael Holmen07f1e2e2017-09-28 08:22:35 +00002442/// Return true if \p reg has any tied def operand.
2443static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg) {
2444 for (const MachineOperand &MO : MRI->def_operands(reg))
2445 if (MO.isTied())
2446 return true;
2447
2448 return false;
2449}
2450
Quentin Colombet87769712014-02-05 22:13:59 +00002451/// mayRecolorAllInterferences - Check if the virtual registers that
2452/// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
2453/// recolored to free \p PhysReg.
2454/// When true is returned, \p RecoloringCandidates has been augmented with all
2455/// the live intervals that need to be recolored in order to free \p PhysReg
2456/// for \p VirtReg.
2457/// \p FixedRegisters contains all the virtual registers that cannot be
2458/// recolored.
2459bool
2460RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
2461 SmallLISet &RecoloringCandidates,
2462 const SmallVirtRegSet &FixedRegisters) {
2463 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
2464
2465 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2466 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
2467 // If there is LastChanceRecoloringMaxInterference or more interferences,
2468 // chances are one would not be recolorable.
2469 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
Quentin Colombet567e30b2014-04-11 21:39:44 +00002470 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
Quentin Colombet87769712014-02-05 22:13:59 +00002471 DEBUG(dbgs() << "Early abort: too many interferences.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002472 CutOffInfo |= CO_Interf;
Quentin Colombet87769712014-02-05 22:13:59 +00002473 return false;
2474 }
2475 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
2476 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
2477 // If Intf is done and sit on the same register class as VirtReg,
2478 // it would not be recolorable as it is in the same state as VirtReg.
Mikael Holmen07f1e2e2017-09-28 08:22:35 +00002479 // However, if VirtReg has tied defs and Intf doesn't, then
2480 // there is still a point in examining if it can be recolorable.
2481 if (((getStage(*Intf) == RS_Done &&
2482 MRI->getRegClass(Intf->reg) == CurRC) &&
2483 !(hasTiedDef(MRI, VirtReg.reg) && !hasTiedDef(MRI, Intf->reg))) ||
Quentin Colombet87769712014-02-05 22:13:59 +00002484 FixedRegisters.count(Intf->reg)) {
Mikael Holmen3bcc9f0c2017-09-27 11:27:50 +00002485 DEBUG(dbgs() << "Early abort: the interference is not recolorable.\n");
Quentin Colombet87769712014-02-05 22:13:59 +00002486 return false;
2487 }
2488 RecoloringCandidates.insert(Intf);
2489 }
2490 }
2491 return true;
2492}
2493
2494/// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
2495/// its interferences.
2496/// Last chance recoloring chooses a color for \p VirtReg and recolors every
2497/// virtual register that was using it. The recoloring process may recursively
2498/// use the last chance recoloring. Therefore, when a virtual register has been
2499/// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
2500/// be last-chance-recolored again during this recoloring "session".
2501/// E.g.,
2502/// Let
2503/// vA can use {R1, R2 }
2504/// vB can use { R2, R3}
2505/// vC can use {R1 }
2506/// Where vA, vB, and vC cannot be split anymore (they are reloads for
2507/// instance) and they all interfere.
2508///
2509/// vA is assigned R1
2510/// vB is assigned R2
2511/// vC tries to evict vA but vA is already done.
2512/// Regular register allocation fails.
2513///
2514/// Last chance recoloring kicks in:
2515/// vC does as if vA was evicted => vC uses R1.
2516/// vC is marked as fixed.
2517/// vA needs to find a color.
2518/// None are available.
2519/// vA cannot evict vC: vC is a fixed virtual register now.
2520/// vA does as if vB was evicted => vA uses R2.
2521/// vB needs to find a color.
2522/// R3 is available.
2523/// Recoloring => vC = R1, vA = R2, vB = R3
2524///
Alp Toker70b36992014-02-25 04:21:15 +00002525/// \p Order defines the preferred allocation order for \p VirtReg.
Quentin Colombet87769712014-02-05 22:13:59 +00002526/// \p NewRegs will contain any new virtual register that have been created
2527/// (split, spill) during the process and that must be assigned.
2528/// \p FixedRegisters contains all the virtual registers that cannot be
2529/// recolored.
2530/// \p Depth gives the current depth of the last chance recoloring.
2531/// \return a physical register that can be used for VirtReg or ~0u if none
2532/// exists.
2533unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2534 AllocationOrder &Order,
2535 SmallVectorImpl<unsigned> &NewVRegs,
2536 SmallVirtRegSet &FixedRegisters,
2537 unsigned Depth) {
2538 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2539 // Ranges must be Done.
Quentin Colombet0e3b5e02014-02-13 05:17:37 +00002540 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
Quentin Colombet87769712014-02-05 22:13:59 +00002541 "Last chance recoloring should really be last chance");
2542 // Set the max depth to LastChanceRecoloringMaxDepth.
2543 // We may want to reconsider that if we end up with a too large search space
2544 // for target with hundreds of registers.
2545 // Indeed, in that case we may want to cut the search space earlier.
Quentin Colombet567e30b2014-04-11 21:39:44 +00002546 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
Quentin Colombet87769712014-02-05 22:13:59 +00002547 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002548 CutOffInfo |= CO_Depth;
Quentin Colombet87769712014-02-05 22:13:59 +00002549 return ~0u;
2550 }
2551
2552 // Set of Live intervals that will need to be recolored.
2553 SmallLISet RecoloringCandidates;
2554 // Record the original mapping virtual register to physical register in case
2555 // the recoloring fails.
2556 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
2557 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2558 // this recoloring "session".
2559 FixedRegisters.insert(VirtReg.reg);
Quentin Colombet318582f2016-09-16 22:00:50 +00002560 SmallVector<unsigned, 4> CurrentNewVRegs;
Quentin Colombet87769712014-02-05 22:13:59 +00002561
2562 Order.rewind();
2563 while (unsigned PhysReg = Order.next()) {
2564 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00002565 << printReg(PhysReg, TRI) << '\n');
Quentin Colombet87769712014-02-05 22:13:59 +00002566 RecoloringCandidates.clear();
2567 VirtRegToPhysReg.clear();
Quentin Colombet318582f2016-09-16 22:00:50 +00002568 CurrentNewVRegs.clear();
Quentin Colombet87769712014-02-05 22:13:59 +00002569
2570 // It is only possible to recolor virtual register interference.
2571 if (Matrix->checkInterference(VirtReg, PhysReg) >
2572 LiveRegMatrix::IK_VirtReg) {
Mikael Holmen3bcc9f0c2017-09-27 11:27:50 +00002573 DEBUG(dbgs() << "Some interferences are not with virtual registers.\n");
Quentin Colombet87769712014-02-05 22:13:59 +00002574
2575 continue;
2576 }
2577
2578 // Early give up on this PhysReg if it is obvious we cannot recolor all
2579 // the interferences.
2580 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2581 FixedRegisters)) {
Mikael Holmen3bcc9f0c2017-09-27 11:27:50 +00002582 DEBUG(dbgs() << "Some interferences cannot be recolored.\n");
Quentin Colombet87769712014-02-05 22:13:59 +00002583 continue;
2584 }
2585
2586 // RecoloringCandidates contains all the virtual registers that interfer
2587 // with VirtReg on PhysReg (or one of its aliases).
2588 // Enqueue them for recoloring and perform the actual recoloring.
2589 PQueue RecoloringQueue;
2590 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2591 EndIt = RecoloringCandidates.end();
2592 It != EndIt; ++It) {
2593 unsigned ItVirtReg = (*It)->reg;
2594 enqueue(RecoloringQueue, *It);
2595 assert(VRM->hasPhys(ItVirtReg) &&
2596 "Interferences are supposed to be with allocated vairables");
2597
2598 // Record the current allocation.
2599 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2600 // unset the related struct.
2601 Matrix->unassign(**It);
2602 }
2603
2604 // Do as if VirtReg was assigned to PhysReg so that the underlying
2605 // recoloring has the right information about the interferes and
2606 // available colors.
2607 Matrix->assign(VirtReg, PhysReg);
2608
2609 // Save the current recoloring state.
2610 // If we cannot recolor all the interferences, we will have to start again
2611 // at this point for the next physical register.
2612 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
Quentin Colombet318582f2016-09-16 22:00:50 +00002613 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2614 FixedRegisters, Depth)) {
2615 // Push the queued vregs into the main queue.
2616 for (unsigned NewVReg : CurrentNewVRegs)
2617 NewVRegs.push_back(NewVReg);
Quentin Colombet87769712014-02-05 22:13:59 +00002618 // Do not mess up with the global assignment process.
2619 // I.e., VirtReg must be unassigned.
2620 Matrix->unassign(VirtReg);
2621 return PhysReg;
2622 }
2623
2624 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00002625 << printReg(PhysReg, TRI) << '\n');
Quentin Colombet87769712014-02-05 22:13:59 +00002626
2627 // The recoloring attempt failed, undo the changes.
2628 FixedRegisters = SaveFixedRegisters;
2629 Matrix->unassign(VirtReg);
2630
Wei Mib5cf9e52016-11-08 18:19:36 +00002631 // For a newly created vreg which is also in RecoloringCandidates,
2632 // don't add it to NewVRegs because its physical register will be restored
2633 // below. Other vregs in CurrentNewVRegs are created by calling
2634 // selectOrSplit and should be added into NewVRegs.
Quentin Colombet318582f2016-09-16 22:00:50 +00002635 for (SmallVectorImpl<unsigned>::iterator Next = CurrentNewVRegs.begin(),
2636 End = CurrentNewVRegs.end();
2637 Next != End; ++Next) {
Wei Mib5cf9e52016-11-08 18:19:36 +00002638 if (RecoloringCandidates.count(&LIS->getInterval(*Next)))
Quentin Colombet318582f2016-09-16 22:00:50 +00002639 continue;
2640 NewVRegs.push_back(*Next);
2641 }
2642
Quentin Colombet87769712014-02-05 22:13:59 +00002643 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2644 EndIt = RecoloringCandidates.end();
2645 It != EndIt; ++It) {
2646 unsigned ItVirtReg = (*It)->reg;
2647 if (VRM->hasPhys(ItVirtReg))
2648 Matrix->unassign(**It);
Matthias Braun953393a2015-07-14 17:38:17 +00002649 unsigned ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2650 Matrix->assign(**It, ItPhysReg);
Quentin Colombet87769712014-02-05 22:13:59 +00002651 }
2652 }
2653
2654 // Last chance recoloring did not worked either, give up.
2655 return ~0u;
2656}
2657
2658/// tryRecoloringCandidates - Try to assign a new color to every register
2659/// in \RecoloringQueue.
2660/// \p NewRegs will contain any new virtual register created during the
2661/// recoloring process.
2662/// \p FixedRegisters[in/out] contains all the registers that have been
2663/// recolored.
2664/// \return true if all virtual registers in RecoloringQueue were successfully
2665/// recolored, false otherwise.
2666bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2667 SmallVectorImpl<unsigned> &NewVRegs,
2668 SmallVirtRegSet &FixedRegisters,
2669 unsigned Depth) {
2670 while (!RecoloringQueue.empty()) {
2671 LiveInterval *LI = dequeue(RecoloringQueue);
2672 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2673 unsigned PhysReg;
2674 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
Quentin Colombet52ffa672016-10-13 19:27:48 +00002675 // When splitting happens, the live-range may actually be empty.
2676 // In that case, this is okay to continue the recoloring even
2677 // if we did not find an alternative color for it. Indeed,
2678 // there will not be anything to color for LI in the end.
2679 if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
Quentin Colombet87769712014-02-05 22:13:59 +00002680 return false;
Quentin Colombet52ffa672016-10-13 19:27:48 +00002681
2682 if (!PhysReg) {
2683 assert(LI->empty() && "Only empty live-range do not require a register");
2684 DEBUG(dbgs() << "Recoloring of " << *LI << " succeeded. Empty LI.\n");
2685 continue;
2686 }
Quentin Colombet87769712014-02-05 22:13:59 +00002687 DEBUG(dbgs() << "Recoloring of " << *LI
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00002688 << " succeeded with: " << printReg(PhysReg, TRI) << '\n');
Quentin Colombet52ffa672016-10-13 19:27:48 +00002689
Quentin Colombet87769712014-02-05 22:13:59 +00002690 Matrix->assign(*LI, PhysReg);
2691 FixedRegisters.insert(LI->reg);
2692 }
2693 return true;
2694}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002695
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002696//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002697// Main Entry Point
2698//===----------------------------------------------------------------------===//
2699
2700unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002701 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002702 CutOffInfo = CO_None;
Matthias Braunf1caa282017-12-15 22:22:58 +00002703 LLVMContext &Ctx = MF->getFunction().getContext();
Quentin Colombet87769712014-02-05 22:13:59 +00002704 SmallVirtRegSet FixedRegisters;
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002705 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2706 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2707 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2708 if (CutOffEncountered == CO_Depth)
Quentin Colombet567e30b2014-04-11 21:39:44 +00002709 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2710 "reached. Use -fexhaustive-register-search to skip "
2711 "cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002712 else if (CutOffEncountered == CO_Interf)
2713 Ctx.emitError("register allocation failed: maximum interference for "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002714 "recoloring reached. Use -fexhaustive-register-search "
2715 "to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002716 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2717 Ctx.emitError("register allocation failed: maximum interference and "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002718 "depth for recoloring reached. Use "
2719 "-fexhaustive-register-search to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002720 }
2721 return Reg;
Quentin Colombet87769712014-02-05 22:13:59 +00002722}
2723
Manman Ren9dee4492014-03-27 21:21:57 +00002724/// Using a CSR for the first time has a cost because it causes push|pop
2725/// to be added to prologue|epilogue. Splitting a cold section of the live
2726/// range can have lower cost than using the CSR for the first time;
2727/// Spilling a live range in the cold path can have lower cost than using
2728/// the CSR for the first time. Returns the physical register if we decide
2729/// to use the CSR; otherwise return 0.
2730unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2731 AllocationOrder &Order,
2732 unsigned PhysReg,
2733 unsigned &CostPerUseLimit,
2734 SmallVectorImpl<unsigned> &NewVRegs) {
Manman Ren9dee4492014-03-27 21:21:57 +00002735 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2736 // We choose spill over using the CSR for the first time if the spill cost
2737 // is lower than CSRCost.
2738 SA->analyze(&VirtReg);
2739 if (calcSpillCost() >= CSRCost)
2740 return PhysReg;
2741
2742 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2743 // we will not use a callee-saved register in tryEvict.
2744 CostPerUseLimit = 1;
2745 return 0;
2746 }
2747 if (getStage(VirtReg) < RS_Split) {
2748 // We choose pre-splitting over using the CSR for the first time if
2749 // the cost of splitting is lower than CSRCost.
2750 SA->analyze(&VirtReg);
2751 unsigned NumCands = 0;
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002752 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2753 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2754 NumCands, true /*IgnoreCSR*/);
Manman Ren9dee4492014-03-27 21:21:57 +00002755 if (BestCand == NoCand)
2756 // Use the CSR if we can't find a region split below CSRCost.
2757 return PhysReg;
2758
2759 // Perform the actual pre-splitting.
2760 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2761 return 0;
2762 }
2763 return PhysReg;
2764}
2765
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002766void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
2767 // Do not keep invalid information around.
2768 SetOfBrokenHints.remove(&LI);
2769}
2770
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002771void RAGreedy::initializeCSRCost() {
2772 // We use the larger one out of the command-line option and the value report
2773 // by TRI.
2774 CSRCost = BlockFrequency(
2775 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2776 if (!CSRCost.getFrequency())
2777 return;
2778
2779 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2780 uint64_t ActualEntry = MBFI->getEntryFreq();
2781 if (!ActualEntry) {
2782 CSRCost = 0;
2783 return;
2784 }
2785 uint64_t FixedEntry = 1 << 14;
2786 if (ActualEntry < FixedEntry)
2787 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2788 else if (ActualEntry <= UINT32_MAX)
2789 // Invert the fraction and divide.
2790 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2791 else
2792 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2793 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2794}
2795
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002796/// \brief Collect the hint info for \p Reg.
2797/// The results are stored into \p Out.
2798/// \p Out is not cleared before being populated.
2799void RAGreedy::collectHintInfo(unsigned Reg, HintsInfo &Out) {
2800 for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2801 if (!Instr.isFullCopy())
2802 continue;
2803 // Look for the other end of the copy.
2804 unsigned OtherReg = Instr.getOperand(0).getReg();
2805 if (OtherReg == Reg) {
2806 OtherReg = Instr.getOperand(1).getReg();
2807 if (OtherReg == Reg)
2808 continue;
2809 }
2810 // Get the current assignment.
2811 unsigned OtherPhysReg = TargetRegisterInfo::isPhysicalRegister(OtherReg)
2812 ? OtherReg
2813 : VRM->getPhys(OtherReg);
2814 // Push the collected information.
2815 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2816 OtherPhysReg));
2817 }
2818}
2819
2820/// \brief Using the given \p List, compute the cost of the broken hints if
2821/// \p PhysReg was used.
2822/// \return The cost of \p List for \p PhysReg.
2823BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2824 unsigned PhysReg) {
2825 BlockFrequency Cost = 0;
2826 for (const HintInfo &Info : List) {
2827 if (Info.PhysReg != PhysReg)
2828 Cost += Info.Freq;
2829 }
2830 return Cost;
2831}
2832
2833/// \brief Using the register assigned to \p VirtReg, try to recolor
2834/// all the live ranges that are copy-related with \p VirtReg.
2835/// The recoloring is then propagated to all the live-ranges that have
2836/// been recolored and so on, until no more copies can be coalesced or
2837/// it is not profitable.
2838/// For a given live range, profitability is determined by the sum of the
2839/// frequencies of the non-identity copies it would introduce with the old
2840/// and new register.
2841void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
2842 // We have a broken hint, check if it is possible to fix it by
2843 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2844 // some register and PhysReg may be available for the other live-ranges.
2845 SmallSet<unsigned, 4> Visited;
2846 SmallVector<unsigned, 2> RecoloringCandidates;
2847 HintsInfo Info;
2848 unsigned Reg = VirtReg.reg;
2849 unsigned PhysReg = VRM->getPhys(Reg);
2850 // Start the recoloring algorithm from the input live-interval, then
2851 // it will propagate to the ones that are copy-related with it.
2852 Visited.insert(Reg);
2853 RecoloringCandidates.push_back(Reg);
2854
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00002855 DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI) << '('
2856 << printReg(PhysReg, TRI) << ")\n");
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002857
2858 do {
2859 Reg = RecoloringCandidates.pop_back_val();
2860
Hiroshi Inouea86c9202017-07-10 12:44:25 +00002861 // We cannot recolor physical register.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002862 if (TargetRegisterInfo::isPhysicalRegister(Reg))
2863 continue;
2864
2865 assert(VRM->hasPhys(Reg) && "We have unallocated variable!!");
2866
2867 // Get the live interval mapped with this virtual register to be able
2868 // to check for the interference with the new color.
2869 LiveInterval &LI = LIS->getInterval(Reg);
2870 unsigned CurrPhys = VRM->getPhys(Reg);
2871 // Check that the new color matches the register class constraints and
2872 // that it is free for this live range.
2873 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2874 Matrix->checkInterference(LI, PhysReg)))
2875 continue;
2876
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00002877 DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI)
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002878 << ") is recolorable.\n");
2879
2880 // Gather the hint info.
2881 Info.clear();
2882 collectHintInfo(Reg, Info);
2883 // Check if recoloring the live-range will increase the cost of the
2884 // non-identity copies.
2885 if (CurrPhys != PhysReg) {
2886 DEBUG(dbgs() << "Checking profitability:\n");
2887 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2888 BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
2889 DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2890 << "\nNew Cost: " << NewCopiesCost.getFrequency() << '\n');
2891 if (OldCopiesCost < NewCopiesCost) {
2892 DEBUG(dbgs() << "=> Not profitable.\n");
2893 continue;
2894 }
2895 // At this point, the cost is either cheaper or equal. If it is
2896 // equal, we consider this is profitable because it may expose
2897 // more recoloring opportunities.
2898 DEBUG(dbgs() << "=> Profitable.\n");
2899 // Recolor the live-range.
2900 Matrix->unassign(LI);
2901 Matrix->assign(LI, PhysReg);
2902 }
2903 // Push all copy-related live-ranges to keep reconciling the broken
2904 // hints.
2905 for (const HintInfo &HI : Info) {
2906 if (Visited.insert(HI.Reg).second)
2907 RecoloringCandidates.push_back(HI.Reg);
2908 }
2909 } while (!RecoloringCandidates.empty());
2910}
2911
2912/// \brief Try to recolor broken hints.
2913/// Broken hints may be repaired by recoloring when an evicted variable
2914/// freed up a register for a larger live-range.
2915/// Consider the following example:
2916/// BB1:
2917/// a =
2918/// b =
2919/// BB2:
2920/// ...
2921/// = b
2922/// = a
2923/// Let us assume b gets split:
2924/// BB1:
2925/// a =
2926/// b =
2927/// BB2:
2928/// c = b
2929/// ...
2930/// d = c
2931/// = d
2932/// = a
2933/// Because of how the allocation work, b, c, and d may be assigned different
2934/// colors. Now, if a gets evicted later:
2935/// BB1:
2936/// a =
2937/// st a, SpillSlot
2938/// b =
2939/// BB2:
2940/// c = b
2941/// ...
2942/// d = c
2943/// = d
2944/// e = ld SpillSlot
2945/// = e
2946/// This is likely that we can assign the same register for b, c, and d,
2947/// getting rid of 2 copies.
2948void RAGreedy::tryHintsRecoloring() {
2949 for (LiveInterval *LI : SetOfBrokenHints) {
2950 assert(TargetRegisterInfo::isVirtualRegister(LI->reg) &&
2951 "Recoloring is possible only for virtual registers");
2952 // Some dead defs may be around (e.g., because of debug uses).
2953 // Ignore those.
2954 if (!VRM->hasPhys(LI->reg))
2955 continue;
2956 tryHintRecoloring(*LI);
2957 }
2958}
2959
Quentin Colombet87769712014-02-05 22:13:59 +00002960unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2961 SmallVectorImpl<unsigned> &NewVRegs,
2962 SmallVirtRegSet &FixedRegisters,
2963 unsigned Depth) {
Manman Ren78cf02a2014-03-25 00:16:25 +00002964 unsigned CostPerUseLimit = ~0u;
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002965 // First try assigning a free register.
Matthias Braun5d1f12d2015-07-15 22:16:00 +00002966 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
Manman Ren78cf02a2014-03-25 00:16:25 +00002967 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
Marina Yatsinaf9371d82017-10-22 17:59:38 +00002968 // If VirtReg got an assignment, the eviction info is no longre relevant.
2969 LastEvicted.clearEvicteeInfo(VirtReg.reg);
Manman Ren9dee4492014-03-27 21:21:57 +00002970 // When NewVRegs is not empty, we may have made decisions such as evicting
2971 // a virtual register, go with the earlier decisions and use the physical
2972 // register.
Matthias Braun953393a2015-07-14 17:38:17 +00002973 if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
2974 NewVRegs.empty()) {
Manman Ren9dee4492014-03-27 21:21:57 +00002975 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2976 CostPerUseLimit, NewVRegs);
2977 if (CSRReg || !NewVRegs.empty())
2978 // Return now if we decide to use a CSR or create new vregs due to
2979 // pre-splitting.
2980 return CSRReg;
Manman Ren78cf02a2014-03-25 00:16:25 +00002981 } else
2982 return PhysReg;
2983 }
Andrew Trickccef0982010-12-09 18:15:21 +00002984
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002985 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00002986 DEBUG(dbgs() << StageName[Stage]
2987 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002988
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002989 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002990 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002991 // get a second chance until they have been split.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002992 if (Stage != RS_Split)
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002993 if (unsigned PhysReg =
2994 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit)) {
2995 unsigned Hint = MRI->getSimpleHint(VirtReg.reg);
2996 // If VirtReg has a hint and that hint is broken record this
2997 // virtual register as a recoloring candidate for broken hint.
2998 // Indeed, since we evicted a variable in its neighborhood it is
2999 // likely we can at least partially recolor some of the
3000 // copy-related live-ranges.
3001 if (Hint && Hint != PhysReg)
3002 SetOfBrokenHints.insert(&VirtReg);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003003 // If VirtReg eviction someone, the eviction info for it as an evictee is
3004 // no longre relevant.
3005 LastEvicted.clearEvicteeInfo(VirtReg.reg);
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00003006 return PhysReg;
Quentin Colombeta799e2e2015-01-08 01:16:39 +00003007 }
Andrew Trickccef0982010-12-09 18:15:21 +00003008
Quentin Colombet63176862016-09-16 22:00:42 +00003009 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00003010
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00003011 // The first time we see a live range, don't try to split or spill.
3012 // Wait until the second time, when all smaller ranges have been allocated.
3013 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00003014 if (Stage < RS_Split) {
3015 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesen86985072011-03-19 23:02:47 +00003016 DEBUG(dbgs() << "wait for second round\n");
Mark Laceyf9ea8852013-08-14 23:50:04 +00003017 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00003018 return 0;
3019 }
3020
Dylan McKayc328fe52016-10-11 01:04:36 +00003021 if (Stage < RS_Spill) {
3022 // Try splitting VirtReg or interferences.
3023 unsigned NewVRegSizeBefore = NewVRegs.size();
3024 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003025 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore)) {
3026 // If VirtReg got split, the eviction info is no longre relevant.
3027 LastEvicted.clearEvicteeInfo(VirtReg.reg);
Dylan McKayc328fe52016-10-11 01:04:36 +00003028 return PhysReg;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003029 }
Dylan McKayc328fe52016-10-11 01:04:36 +00003030 }
3031
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00003032 // If we couldn't allocate a register from spilling, there is probably some
Hiroshi Inoueff8453d2017-06-29 18:03:28 +00003033 // invalid inline assembly. The base class will report it.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00003034 if (Stage >= RS_Done || !VirtReg.isSpillable())
Quentin Colombet87769712014-02-05 22:13:59 +00003035 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
3036 Depth);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00003037
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00003038 // Finally spill VirtReg itself.
Quentin Colombet11922942015-07-17 23:04:06 +00003039 if (EnableDeferredSpilling && getStage(VirtReg) < RS_Memory) {
3040 // TODO: This is experimental and in particular, we do not model
3041 // the live range splitting done by spilling correctly.
3042 // We would need a deep integration with the spiller to do the
3043 // right thing here. Anyway, that is still good for early testing.
3044 setStage(VirtReg, RS_Memory);
3045 DEBUG(dbgs() << "Do as if this register is in memory\n");
3046 NewVRegs.push_back(VirtReg.reg);
3047 } else {
Matthias Braun9f15a792016-11-18 19:43:18 +00003048 NamedRegionTimer T("spill", "Spiller", TimerGroupName,
3049 TimerGroupDescription, TimePassesIsEnabled);
Wei Mi9a16d652016-04-13 03:08:27 +00003050 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Quentin Colombet11922942015-07-17 23:04:06 +00003051 spiller().spill(LRE);
3052 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003053
Quentin Colombet11922942015-07-17 23:04:06 +00003054 if (VerifyEnabled)
3055 MF->verify(this, "After spilling");
3056 }
Jakob Stoklund Olesen557a82c2011-03-16 22:56:08 +00003057
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003058 // The live virtual register requesting allocation was spilled, so tell
3059 // the caller not to allocate anything during this round.
3060 return 0;
3061}
3062
Adam Nemeta9640662017-01-25 23:20:33 +00003063void RAGreedy::reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
3064 unsigned &FoldedReloads,
3065 unsigned &Spills,
3066 unsigned &FoldedSpills) {
3067 Reloads = 0;
3068 FoldedReloads = 0;
3069 Spills = 0;
3070 FoldedSpills = 0;
3071
3072 // Sum up the spill and reloads in subloops.
3073 for (MachineLoop *SubLoop : *L) {
3074 unsigned SubReloads;
3075 unsigned SubFoldedReloads;
3076 unsigned SubSpills;
3077 unsigned SubFoldedSpills;
3078
3079 reportNumberOfSplillsReloads(SubLoop, SubReloads, SubFoldedReloads,
3080 SubSpills, SubFoldedSpills);
3081 Reloads += SubReloads;
3082 FoldedReloads += SubFoldedReloads;
3083 Spills += SubSpills;
3084 FoldedSpills += SubFoldedSpills;
3085 }
3086
3087 const MachineFrameInfo &MFI = MF->getFrameInfo();
3088 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
3089 int FI;
3090
3091 for (MachineBasicBlock *MBB : L->getBlocks())
3092 // Handle blocks that were not included in subloops.
3093 if (Loops->getLoopFor(MBB) == L)
3094 for (MachineInstr &MI : *MBB) {
3095 const MachineMemOperand *MMO;
3096
3097 if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI))
3098 ++Reloads;
3099 else if (TII->hasLoadFromStackSlot(MI, MMO, FI) &&
3100 MFI.isSpillSlotObjectIndex(FI))
3101 ++FoldedReloads;
3102 else if (TII->isStoreToStackSlot(MI, FI) &&
3103 MFI.isSpillSlotObjectIndex(FI))
3104 ++Spills;
3105 else if (TII->hasStoreToStackSlot(MI, MMO, FI) &&
3106 MFI.isSpillSlotObjectIndex(FI))
3107 ++FoldedSpills;
3108 }
3109
3110 if (Reloads || FoldedReloads || Spills || FoldedSpills) {
3111 using namespace ore;
Eugene Zelenkofb69e662017-06-06 22:22:41 +00003112
Vivek Pandya95906582017-10-11 17:12:59 +00003113 ORE->emit([&]() {
3114 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReload",
3115 L->getStartLoc(), L->getHeader());
3116 if (Spills)
3117 R << NV("NumSpills", Spills) << " spills ";
3118 if (FoldedSpills)
3119 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
3120 if (Reloads)
3121 R << NV("NumReloads", Reloads) << " reloads ";
3122 if (FoldedReloads)
3123 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
3124 R << "generated in loop";
3125 return R;
3126 });
Adam Nemeta9640662017-01-25 23:20:33 +00003127 }
3128}
3129
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003130bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
3131 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikiec8c29202012-08-22 17:18:53 +00003132 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003133
3134 MF = &mf;
Eric Christopher60621802014-10-14 07:22:00 +00003135 TRI = MF->getSubtarget().getRegisterInfo();
3136 TII = MF->getSubtarget().getInstrInfo();
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00003137 RCI.runOnMachineFunction(mf);
Quentin Colombet5caa6a22014-07-02 18:32:04 +00003138
3139 EnableLocalReassign = EnableLocalReassignment ||
Eric Christopher60621802014-10-14 07:22:00 +00003140 MF->getSubtarget().enableRALocalReassignment(
3141 MF->getTarget().getOptLevel());
Quentin Colombet5caa6a22014-07-02 18:32:04 +00003142
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003143 EnableAdvancedRASplitCost = ConsiderLocalIntervalCost ||
3144 MF->getSubtarget().enableAdvancedRASplitCost();
3145
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00003146 if (VerifyEnabled)
Jakob Stoklund Olesenbf4550e2010-12-18 00:06:56 +00003147 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00003148
Jakob Stoklund Olesen2d2dec92012-06-20 22:52:29 +00003149 RegAllocBase::init(getAnalysis<VirtRegMap>(),
3150 getAnalysis<LiveIntervals>(),
3151 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00003152 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +00003153 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +00003154 DomTree = &getAnalysis<MachineDominatorTree>();
Adam Nemeta9640662017-01-25 23:20:33 +00003155 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
Jakob Stoklund Olesenadecb5e2010-12-10 22:54:44 +00003156 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00003157 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00003158 Bundles = &getAnalysis<EdgeBundles>();
3159 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00003160 DebugVars = &getAnalysis<LiveDebugVariables>();
Wei Mic0223702016-07-08 21:08:09 +00003161 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00003162
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00003163 initializeCSRCost();
3164
Robert Lougher11a44b72015-08-10 11:59:44 +00003165 calculateSpillWeightsAndHints(*LIS, mf, VRM, *Loops, *MBFI);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +00003166
Andrew Trick97064962013-07-25 07:26:26 +00003167 DEBUG(LIS->dump());
3168
Jakob Stoklund Olesenf1a60a62011-02-19 00:53:42 +00003169 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Wei Mic0223702016-07-08 21:08:09 +00003170 SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00003171 ExtraRegInfo.clear();
3172 ExtraRegInfo.resize(MRI->getNumVirtRegs());
3173 NextCascade = 1;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00003174 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00003175 GlobalCand.resize(32); // This will grow as needed.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00003176 SetOfBrokenHints.clear();
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003177 LastEvicted.clear();
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00003178
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003179 allocatePhysRegs();
Quentin Colombeta799e2e2015-01-08 01:16:39 +00003180 tryHintsRecoloring();
Wei Mi9a16d652016-04-13 03:08:27 +00003181 postOptimization();
Adam Nemeta9640662017-01-25 23:20:33 +00003182 reportNumberOfSplillsReloads();
Wei Mi9a16d652016-04-13 03:08:27 +00003183
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003184 releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003185 return true;
3186}