blob: e8e6cf21f1c4cf811db610ddf52740dfcf893e58 [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
Wei Mi40c4aa72018-07-16 15:42:20 +0000128static cl::opt<unsigned>
129 HugeSizeForSplit("huge-size-for-split", cl::Hidden,
130 cl::desc("Last chance recoloring max depth"),
131 cl::init(5000));
132
Manman Ren78cf02a2014-03-25 00:16:25 +0000133// FIXME: Find a good default for this flag and remove the flag.
134static cl::opt<unsigned>
135CSRFirstTimeCost("regalloc-csr-first-time-cost",
136 cl::desc("Cost for first time use of callee-saved register."),
137 cl::init(0), cl::Hidden);
138
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000139static cl::opt<bool> ConsiderLocalIntervalCost(
140 "condsider-local-interval-cost", cl::Hidden,
141 cl::desc("Consider the cost of local intervals created by a split "
142 "candidate when choosing the best split candidate."),
143 cl::init(false));
144
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000145static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
146 createGreedyRegisterAllocator);
147
148namespace {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000149
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000150class RAGreedy : public MachineFunctionPass,
151 public RegAllocBase,
152 private LiveRangeEdit::Delegate {
Quentin Colombet87769712014-02-05 22:13:59 +0000153 // Convenient shortcuts.
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000154 using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
155 using SmallLISet = SmallPtrSet<LiveInterval *, 4>;
156 using SmallVirtRegSet = SmallSet<unsigned, 16>;
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000157
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000158 // context
159 MachineFunction *MF;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000160
Quentin Colombet1fb3362a2014-01-02 22:47:22 +0000161 // Shortcuts to some useful interface.
162 const TargetInstrInfo *TII;
163 const TargetRegisterInfo *TRI;
164 RegisterClassInfo RCI;
165
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000166 // analyses
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000167 SlotIndexes *Indexes;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000168 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000169 MachineDominatorTree *DomTree;
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +0000170 MachineLoopInfo *Loops;
Adam Nemeta9640662017-01-25 23:20:33 +0000171 MachineOptimizationRemarkEmitter *ORE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000172 EdgeBundles *Bundles;
173 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000174 LiveDebugVariables *DebugVars;
Wei Mic0223702016-07-08 21:08:09 +0000175 AliasAnalysis *AA;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000176
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000177 // state
Ahmed Charles56440fd2014-03-06 05:51:42 +0000178 std::unique_ptr<Spiller> SpillerInstance;
Quentin Colombet87769712014-02-05 22:13:59 +0000179 PQueue Queue;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000180 unsigned NextCascade;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000181
182 // Live ranges pass through a number of stages as we try to allocate them.
183 // Some of the stages may also create new live ranges:
184 //
185 // - Region splitting.
186 // - Per-block splitting.
187 // - Local splitting.
188 // - Spilling.
189 //
190 // Ranges produced by one of the stages skip the previous stages when they are
191 // dequeued. This improves performance because we can skip interference checks
192 // that are unlikely to give any results. It also guarantees that the live
193 // range splitting algorithm terminates, something that is otherwise hard to
194 // ensure.
195 enum LiveRangeStage {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000196 /// Newly created live range that has never been queued.
197 RS_New,
198
199 /// Only attempt assignment and eviction. Then requeue as RS_Split.
200 RS_Assign,
201
202 /// Attempt live range splitting if assignment is impossible.
203 RS_Split,
204
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000205 /// Attempt more aggressive live range splitting that is guaranteed to make
206 /// progress. This is used for split products that may not be making
207 /// progress.
208 RS_Split2,
209
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000210 /// Live range will be spilled. No more splitting will be attempted.
211 RS_Spill,
212
Quentin Colombet11922942015-07-17 23:04:06 +0000213
214 /// Live range is in memory. Because of other evictions, it might get moved
215 /// in a register in the end.
216 RS_Memory,
217
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000218 /// There is nothing more we can do to this live range. Abort compilation
219 /// if it can't be assigned.
220 RS_Done
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000221 };
222
Quentin Colombet96bd2a12014-04-04 02:05:21 +0000223 // Enum CutOffStage to keep a track whether the register allocation failed
224 // because of the cutoffs encountered in last chance recoloring.
225 // Note: This is used as bitmask. New value should be next power of 2.
226 enum CutOffStage {
227 // No cutoffs encountered
228 CO_None = 0,
229
230 // lcr-max-depth cutoff encountered
231 CO_Depth = 1,
232
233 // lcr-max-interf cutoff encountered
234 CO_Interf = 2
235 };
236
237 uint8_t CutOffInfo;
238
Eli Friedman78bffa52013-09-10 23:18:14 +0000239#ifndef NDEBUG
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000240 static const char *const StageName[];
Eli Friedman78bffa52013-09-10 23:18:14 +0000241#endif
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000242
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000243 // RegInfo - Keep additional information about each live range.
244 struct RegInfo {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000245 LiveRangeStage Stage = RS_New;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000246
247 // Cascade - Eviction loop prevention. See canEvictInterference().
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000248 unsigned Cascade = 0;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000249
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000250 RegInfo() = default;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000251 };
252
253 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000254
255 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000256 return ExtraRegInfo[VirtReg.reg].Stage;
257 }
258
259 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
260 ExtraRegInfo.resize(MRI->getNumVirtRegs());
261 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000262 }
263
264 template<typename Iterator>
265 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000266 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000267 for (;Begin != End; ++Begin) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000268 unsigned Reg = *Begin;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000269 if (ExtraRegInfo[Reg].Stage == RS_New)
270 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000271 }
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000272 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000273
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000274 /// Cost of evicting interference.
275 struct EvictionCost {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000276 unsigned BrokenHints = 0; ///< Total number of broken hints.
277 float MaxWeight = 0; ///< Maximum spill weight evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000278
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000279 EvictionCost() = default;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000280
Andrew Trick84852572013-07-25 18:35:14 +0000281 bool isMax() const { return BrokenHints == ~0u; }
282
Andrew Trick3621b8a2013-11-22 19:07:38 +0000283 void setMax() { BrokenHints = ~0u; }
284
285 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
286
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000287 bool operator<(const EvictionCost &O) const {
Benjamin Kramerb2f034b2014-03-03 19:58:30 +0000288 return std::tie(BrokenHints, MaxWeight) <
289 std::tie(O.BrokenHints, O.MaxWeight);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000290 }
291 };
292
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000293 /// EvictionTrack - Keeps track of past evictions in order to optimize region
294 /// split decision.
295 class EvictionTrack {
296
297 public:
298 using EvictorInfo =
299 std::pair<unsigned /* evictor */, unsigned /* physreg */>;
Nirav Davee5eb9962018-06-05 03:16:28 +0000300 using EvicteeInfo = llvm::DenseMap<unsigned /* evictee */, EvictorInfo>;
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000301
302 private:
303 /// Each Vreg that has been evicted in the last stage of selectOrSplit will
304 /// be mapped to the evictor Vreg and the PhysReg it was evicted from.
305 EvicteeInfo Evictees;
306
307 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000308 /// Clear all eviction information.
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000309 void clear() { Evictees.clear(); }
310
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000311 /// Clear eviction information for the given evictee Vreg.
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000312 /// E.g. when Vreg get's a new allocation, the old eviction info is no
313 /// longer relevant.
314 /// \param Evictee The evictee Vreg for whom we want to clear collected
315 /// eviction info.
316 void clearEvicteeInfo(unsigned Evictee) { Evictees.erase(Evictee); }
317
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000318 /// Track new eviction.
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000319 /// The Evictor vreg has evicted the Evictee vreg from Physreg.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +0000320 /// \param PhysReg The phisical register Evictee was evicted from.
321 /// \param Evictor The evictor Vreg that evicted Evictee.
322 /// \param Evictee The evictee Vreg.
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000323 void addEviction(unsigned PhysReg, unsigned Evictor, unsigned Evictee) {
324 Evictees[Evictee].first = Evictor;
325 Evictees[Evictee].second = PhysReg;
326 }
327
328 /// Return the Evictor Vreg which evicted Evictee Vreg from PhysReg.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +0000329 /// \param Evictee The evictee vreg.
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000330 /// \return The Evictor vreg which evicted Evictee vreg from PhysReg. 0 if
331 /// nobody has evicted Evictee from PhysReg.
332 EvictorInfo getEvictor(unsigned Evictee) {
333 if (Evictees.count(Evictee)) {
334 return Evictees[Evictee];
335 }
336
337 return EvictorInfo(0, 0);
338 }
339 };
340
341 // Keeps track of past evictions in order to optimize region split decision.
342 EvictionTrack LastEvicted;
343
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000344 // splitting state.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000345 std::unique_ptr<SplitAnalysis> SA;
346 std::unique_ptr<SplitEditor> SE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000347
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000348 /// Cached per-block interference maps
349 InterferenceCache IntfCache;
350
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000351 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000352 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000353
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000354 /// Global live range splitting candidate info.
355 struct GlobalSplitCandidate {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000356 // Register intended for assignment, or 0.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000357 unsigned PhysReg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000358
359 // SplitKit interval index for this candidate.
360 unsigned IntvIdx;
361
362 // Interference for PhysReg.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000363 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000364
365 // Bundles where this candidate should be live.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000366 BitVector LiveBundles;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000367 SmallVector<unsigned, 8> ActiveBlocks;
368
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000369 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000370 PhysReg = Reg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000371 IntvIdx = 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000372 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000373 LiveBundles.clear();
374 ActiveBlocks.clear();
375 }
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000376
377 // Set B[i] = C for every live bundle where B[i] was NoCand.
378 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
379 unsigned Count = 0;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +0000380 for (unsigned i : LiveBundles.set_bits())
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000381 if (B[i] == NoCand) {
382 B[i] = C;
383 Count++;
384 }
385 return Count;
386 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000387 };
388
Aditya Nandakumarc1fd0dd2013-11-19 23:51:32 +0000389 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000390 /// This vector never shrinks, but grows to the size of the largest register
391 /// class.
392 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
393
Alp Toker61007d82014-03-02 03:20:38 +0000394 enum : unsigned { NoCand = ~0u };
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000395
396 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
397 /// NoCand which indicates the stack interval.
398 SmallVector<unsigned, 32> BundleCand;
399
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000400 /// Callee-save register cost, calculated once per machine function.
401 BlockFrequency CSRCost;
402
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000403 /// Run or not the local reassignment heuristic. This information is
404 /// obtained from the TargetSubtargetInfo.
405 bool EnableLocalReassign;
406
Hiroshi Inoue8f976ba2018-01-17 12:29:38 +0000407 /// Enable or not the consideration of the cost of local intervals created
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000408 /// by a split candidate when choosing the best split candidate.
409 bool EnableAdvancedRASplitCost;
410
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000411 /// Set of broken hints that may be reconciled later because of eviction.
412 SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
413
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000414public:
415 RAGreedy();
416
417 /// Return the pass name.
Mehdi Amini117296c2016-10-01 02:56:57 +0000418 StringRef getPassName() const override { return "Greedy Register Allocator"; }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000419
420 /// RAGreedy analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000421 void getAnalysisUsage(AnalysisUsage &AU) const override;
422 void releaseMemory() override;
423 Spiller &spiller() override { return *SpillerInstance; }
424 void enqueue(LiveInterval *LI) override;
425 LiveInterval *dequeue() override;
426 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000427 void aboutToRemoveInterval(LiveInterval &) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000428
429 /// Perform register allocation.
Craig Topper4584cd52014-03-07 09:26:03 +0000430 bool runOnMachineFunction(MachineFunction &mf) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000431
Matthias Braun90799ce2016-08-23 21:19:49 +0000432 MachineFunctionProperties getRequiredProperties() const override {
433 return MachineFunctionProperties().set(
434 MachineFunctionProperties::Property::NoPHIs);
435 }
436
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000437 static char ID;
Andrew Trickccef0982010-12-09 18:15:21 +0000438
439private:
Quentin Colombet87769712014-02-05 22:13:59 +0000440 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
441 SmallVirtRegSet &, unsigned = 0);
442
Craig Topper4584cd52014-03-07 09:26:03 +0000443 bool LRE_CanEraseVirtReg(unsigned) override;
444 void LRE_WillShrinkVirtReg(unsigned) override;
445 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
Quentin Colombet87769712014-02-05 22:13:59 +0000446 void enqueue(PQueue &CurQueue, LiveInterval *LI);
447 LiveInterval *dequeue(PQueue &CurQueue);
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000448
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000449 BlockFrequency calcSpillCost();
450 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000451 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000452 void growRegion(GlobalSplitCandidate &Cand);
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000453 bool splitCanCauseEvictionChain(unsigned Evictee, GlobalSplitCandidate &Cand,
454 unsigned BBNumber,
455 const AllocationOrder &Order);
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +0000456 bool splitCanCauseLocalSpill(unsigned VirtRegToSplit,
457 GlobalSplitCandidate &Cand, unsigned BBNumber,
458 const AllocationOrder &Order);
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000459 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate &,
460 const AllocationOrder &Order,
461 bool *CanCauseEvictionChain);
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000462 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000463 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000464 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000465 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000466 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
467 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000468 bool canEvictInterferenceInRange(LiveInterval &VirtReg, unsigned PhysReg,
469 SlotIndex Start, SlotIndex End,
470 EvictionCost &MaxCost);
471 unsigned getCheapestEvicteeWeight(const AllocationOrder &Order,
472 LiveInterval &VirtReg, SlotIndex Start,
473 SlotIndex End, float *BestEvictWeight);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000474 void evictInterference(LiveInterval&, unsigned,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000475 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000476 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
477 SmallLISet &RecoloringCandidates,
478 const SmallVirtRegSet &FixedRegisters);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000479
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000480 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000481 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000482 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000483 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000484 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000485 SmallVectorImpl<unsigned>&);
Wei Mi40c4aa72018-07-16 15:42:20 +0000486 unsigned isSplitBenefitWorthCost(LiveInterval &VirtReg);
Manman Ren9db66b32014-03-24 23:23:42 +0000487 /// Calculate cost of region splitting.
488 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
489 AllocationOrder &Order,
490 BlockFrequency &BestCost,
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000491 unsigned &NumCands, bool IgnoreCSR,
492 bool *CanCauseEvictionChain = nullptr);
Manman Ren9db66b32014-03-24 23:23:42 +0000493 /// Perform region splitting.
494 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
495 bool HasCompact,
496 SmallVectorImpl<unsigned> &NewVRegs);
Manman Ren9dee4492014-03-27 21:21:57 +0000497 /// Check other options before using a callee-saved register for the first
498 /// time.
499 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
500 unsigned PhysReg, unsigned &CostPerUseLimit,
501 SmallVectorImpl<unsigned> &NewVRegs);
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000502 void initializeCSRCost();
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +0000503 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000504 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +0000505 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000506 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000507 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000508 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000509 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000510 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000511 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
512 SmallVectorImpl<unsigned> &,
513 SmallVirtRegSet &, unsigned);
514 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
515 SmallVirtRegSet &, unsigned);
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000516 void tryHintRecoloring(LiveInterval &);
517 void tryHintsRecoloring();
518
519 /// Model the information carried by one end of a copy.
520 struct HintInfo {
521 /// The frequency of the copy.
522 BlockFrequency Freq;
523 /// The virtual register or physical register.
524 unsigned Reg;
525 /// Its currently assigned register.
526 /// In case of a physical register Reg == PhysReg.
527 unsigned PhysReg;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000528
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000529 HintInfo(BlockFrequency Freq, unsigned Reg, unsigned PhysReg)
530 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
531 };
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000532 using HintsInfo = SmallVector<HintInfo, 4>;
533
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000534 BlockFrequency getBrokenHintFreq(const HintsInfo &, unsigned);
535 void collectHintInfo(unsigned, HintsInfo &);
Matthias Braun953393a2015-07-14 17:38:17 +0000536
537 bool isUnusedCalleeSavedReg(unsigned PhysReg) const;
Adam Nemeta9640662017-01-25 23:20:33 +0000538
539 /// Compute and report the number of spills and reloads for a loop.
540 void reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
541 unsigned &FoldedReloads, unsigned &Spills,
542 unsigned &FoldedSpills);
543
544 /// Report the number of spills and reloads for each loop.
545 void reportNumberOfSplillsReloads() {
546 for (MachineLoop *L : *Loops) {
547 unsigned Reloads, FoldedReloads, Spills, FoldedSpills;
548 reportNumberOfSplillsReloads(L, Reloads, FoldedReloads, Spills,
549 FoldedSpills);
550 }
551 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000552};
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000553
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000554} // end anonymous namespace
555
556char RAGreedy::ID = 0;
Tom Stellard11e60ff2016-11-14 21:50:13 +0000557char &llvm::RAGreedyID = RAGreedy::ID;
558
559INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
560 "Greedy Register Allocator", false, false)
561INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
562INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
563INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
564INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
565INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
566INITIALIZE_PASS_DEPENDENCY(LiveStacks)
567INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
568INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
569INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
570INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
571INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
572INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
Adam Nemeta9640662017-01-25 23:20:33 +0000573INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
Tom Stellard11e60ff2016-11-14 21:50:13 +0000574INITIALIZE_PASS_END(RAGreedy, "greedy",
575 "Greedy Register Allocator", false, false)
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000576
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000577#ifndef NDEBUG
578const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000579 "RS_New",
580 "RS_Assign",
581 "RS_Split",
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000582 "RS_Split2",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000583 "RS_Spill",
Quentin Colombet11922942015-07-17 23:04:06 +0000584 "RS_Memory",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000585 "RS_Done"
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000586};
587#endif
588
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000589// Hysteresis to use when comparing floats.
590// This helps stabilize decisions based on float comparisons.
NAKAMURA Takumia71003a2014-02-04 06:29:38 +0000591const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000592
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000593FunctionPass* llvm::createGreedyRegisterAllocator() {
594 return new RAGreedy();
595}
596
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000597RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000598}
599
600void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
601 AU.setPreservesCFG();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000602 AU.addRequired<MachineBlockFrequencyInfo>();
603 AU.addPreserved<MachineBlockFrequencyInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000604 AU.addRequired<AAResultsWrapperPass>();
605 AU.addPreserved<AAResultsWrapperPass>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000606 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen12243122012-06-08 23:44:45 +0000607 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000608 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000609 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000610 AU.addRequired<LiveDebugVariables>();
611 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000612 AU.addRequired<LiveStacks>();
613 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000614 AU.addRequired<MachineDominatorTree>();
615 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000616 AU.addRequired<MachineLoopInfo>();
617 AU.addPreserved<MachineLoopInfo>();
618 AU.addRequired<VirtRegMap>();
619 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000620 AU.addRequired<LiveRegMatrix>();
621 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000622 AU.addRequired<EdgeBundles>();
623 AU.addRequired<SpillPlacement>();
Adam Nemeta9640662017-01-25 23:20:33 +0000624 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000625 MachineFunctionPass::getAnalysisUsage(AU);
626}
627
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000628//===----------------------------------------------------------------------===//
629// LiveRangeEdit delegate methods
630//===----------------------------------------------------------------------===//
631
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000632bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jonas Paulsson6188f322017-09-15 07:47:38 +0000633 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000634 if (VRM->hasPhys(VirtReg)) {
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000635 Matrix->unassign(LI);
636 aboutToRemoveInterval(LI);
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000637 return true;
638 }
639 // Unassigned virtreg is probably in the priority queue.
640 // RegAllocBase will erase it after dequeueing.
Jonas Paulsson6188f322017-09-15 07:47:38 +0000641 // Nonetheless, clear the live-range so that the debug
642 // dump will show the right state for that VirtReg.
643 LI.clear();
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000644 return false;
645}
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000646
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000647void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000648 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000649 return;
650
651 // Register is assigned, put it back on the queue for reassignment.
652 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000653 Matrix->unassign(LI);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000654 enqueue(&LI);
655}
656
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000657void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen811b9c42011-09-14 17:34:37 +0000658 // Cloning a register we haven't even heard about yet? Just ignore it.
659 if (!ExtraRegInfo.inBounds(Old))
660 return;
661
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000662 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000663 // be split into connected components. The new components are much smaller
664 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000665 // same stage as the parent.
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000666 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000667 ExtraRegInfo.grow(New);
668 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000669}
670
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000671void RAGreedy::releaseMemory() {
David Blaikieb61064e2014-07-19 01:05:11 +0000672 SpillerInstance.reset();
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000673 ExtraRegInfo.clear();
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000674 GlobalCand.clear();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000675}
676
Quentin Colombet87769712014-02-05 22:13:59 +0000677void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
678
679void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000680 // Prioritize live ranges by size, assigning larger ranges first.
681 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000682 const unsigned Size = LI->getSize();
683 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000684 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
685 "Can only enqueue virtual registers");
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000686 unsigned Prio;
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000687
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000688 ExtraRegInfo.grow(Reg);
689 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000690 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000691
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000692 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000693 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +0000694 // everything else has been allocated.
695 Prio = Size;
Quentin Colombet11922942015-07-17 23:04:06 +0000696 } else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
697 // Memory operand should be considered last.
698 // Change the priority such that Memory operand are assigned in
699 // the reverse order that they came in.
700 // TODO: Make this a member variable and probably do something about hints.
701 static unsigned MemOp = 0;
702 Prio = MemOp++;
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000703 } else {
Andrew Trick52a00932014-02-26 22:07:26 +0000704 // Giant live ranges fall back to the global assignment heuristic, which
705 // prevents excessive spilling in pathological cases.
706 bool ReverseLocal = TRI->reverseLocalAssignment();
Matthias Brauna354cdd2015-03-31 19:57:53 +0000707 const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
Renato Golin4e31ae12014-10-03 12:20:53 +0000708 bool ForceGlobal = !ReverseLocal &&
Matthias Brauna354cdd2015-03-31 19:57:53 +0000709 (Size / SlotIndex::InstrDist) > (2 * RC.getNumRegs());
Andrew Trick52a00932014-02-26 22:07:26 +0000710
711 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
Andrew Trick84852572013-07-25 18:35:14 +0000712 LIS->intervalIsInOneMBB(*LI)) {
713 // Allocate original local ranges in linear instruction order. Since they
714 // are singly defined, this produces optimal coloring in the absence of
715 // global interference and other constraints.
Andrew Trick52a00932014-02-26 22:07:26 +0000716 if (!ReverseLocal)
Andrew Trick2d8826a2013-12-11 03:40:15 +0000717 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
718 else {
719 // Allocating bottom up may allow many short LRGs to be assigned first
720 // to one of the cheap registers. This could be much faster for very
721 // large blocks on targets with many physical registers.
Matthias Braunf5f89b92015-03-31 19:57:49 +0000722 Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
Andrew Trick2d8826a2013-12-11 03:40:15 +0000723 }
Matthias Brauna354cdd2015-03-31 19:57:53 +0000724 Prio |= RC.AllocationPriority << 24;
725 } else {
Andrew Trick84852572013-07-25 18:35:14 +0000726 // Allocate global and split ranges in long->short order. Long ranges that
727 // don't fit should be spilled (or split) ASAP so they don't create
728 // interference. Mark a bit to prioritize global above local ranges.
729 Prio = (1u << 29) + Size;
730 }
731 // Mark a higher bit to prioritize global and local above RS_Split.
732 Prio |= (1u << 31);
Jakob Stoklund Olesenb51f65c2011-02-23 00:56:56 +0000733
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000734 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen74052b02012-12-03 23:23:50 +0000735 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000736 Prio |= (1u << 30);
737 }
Andrew Trickf4b1ee32013-07-25 18:35:22 +0000738 // The virtual register number is a tie breaker for same-sized ranges.
739 // Give lower vreg numbers higher priority to assign them first.
Quentin Colombet87769712014-02-05 22:13:59 +0000740 CurQueue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000741}
742
Quentin Colombet87769712014-02-05 22:13:59 +0000743LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
744
745LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
746 if (CurQueue.empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000747 return nullptr;
Quentin Colombet87769712014-02-05 22:13:59 +0000748 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
749 CurQueue.pop();
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000750 return LI;
751}
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000752
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000753//===----------------------------------------------------------------------===//
754// Direct Assignment
755//===----------------------------------------------------------------------===//
756
757/// tryAssign - Try to assign VirtReg to an available register.
758unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
759 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000760 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000761 Order.rewind();
762 unsigned PhysReg;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000763 while ((PhysReg = Order.next()))
764 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000765 break;
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000766 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000767 return PhysReg;
768
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000769 // PhysReg is available, but there may be a better choice.
770
771 // If we missed a simple hint, try to cheaply evict interference from the
772 // preferred register.
773 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000774 if (Order.isHint(Hint)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000775 LLVM_DEBUG(dbgs() << "missed hint " << printReg(Hint, TRI) << '\n');
Andrew Trick3621b8a2013-11-22 19:07:38 +0000776 EvictionCost MaxCost;
777 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000778 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
779 evictInterference(VirtReg, Hint, NewVRegs);
780 return Hint;
781 }
Quentin Colombetfb9b0cd2016-11-16 01:07:12 +0000782 // Record the missed hint, we may be able to recover
783 // at the end if the surrounding allocation changed.
784 SetOfBrokenHints.insert(&VirtReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000785 }
786
787 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000788 unsigned Cost = TRI->getCostPerUse(PhysReg);
789
790 // Most registers have 0 additional cost.
791 if (!Cost)
792 return PhysReg;
793
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000794 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost "
795 << Cost << '\n');
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000796 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
797 return CheapReg ? CheapReg : PhysReg;
798}
799
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000800//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000801// Interference eviction
802//===----------------------------------------------------------------------===//
803
Andrew Trick8bb0a252013-07-25 18:35:19 +0000804unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
Matthias Braun5d1f12d2015-07-15 22:16:00 +0000805 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000806 unsigned PhysReg;
807 while ((PhysReg = Order.next())) {
808 if (PhysReg == PrevReg)
809 continue;
810
811 MCRegUnitIterator Units(PhysReg, TRI);
812 for (; Units.isValid(); ++Units) {
813 // Instantiate a "subquery", not to be confused with the Queries array.
Matthias Braun173e1142017-03-01 21:48:12 +0000814 LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000815 if (subQ.checkInterference())
816 break;
817 }
818 // If no units have interference, break out with the current PhysReg.
819 if (!Units.isValid())
820 break;
821 }
822 if (PhysReg)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000823 LLVM_DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
824 << printReg(PrevReg, TRI) << " to "
825 << printReg(PhysReg, TRI) << '\n');
Andrew Trick8bb0a252013-07-25 18:35:19 +0000826 return PhysReg;
827}
828
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000829/// shouldEvict - determine if A should evict the assigned live range B. The
830/// eviction policy defined by this function together with the allocation order
831/// defined by enqueue() decides which registers ultimately end up being split
832/// and spilled.
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000833///
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000834/// Cascade numbers are used to prevent infinite loops if this function is a
835/// cyclic relation.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000836///
837/// @param A The live range to be assigned.
838/// @param IsHint True when A is about to be assigned to its preferred
839/// register.
840/// @param B The live range to be evicted.
841/// @param BreaksHint True when B is already assigned to its preferred register.
842bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
843 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000844 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000845
846 // Be fairly aggressive about following hints as long as the evictee can be
847 // split.
848 if (CanSplit && IsHint && !BreaksHint)
849 return true;
850
Andrew Trick059e8002013-11-22 19:07:42 +0000851 if (A.weight > B.weight) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000852 LLVM_DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
Andrew Trick059e8002013-11-22 19:07:42 +0000853 return true;
854 }
855 return false;
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000856}
857
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000858/// canEvictInterference - Return true if all interferences between VirtReg and
Manman Renfa32ca12014-02-25 19:47:15 +0000859/// PhysReg can be evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000860///
861/// @param VirtReg Live range that is about to be assigned.
862/// @param PhysReg Desired register for assignment.
Dmitri Gribenko881929c2012-09-12 16:59:47 +0000863/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000864/// @param MaxCost Only look for cheaper candidates and update with new cost
865/// when returning true.
866/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000867bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000868 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000869 // It is only possible to evict virtual register interference.
870 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
871 return false;
872
Andrew Trick84852572013-07-25 18:35:14 +0000873 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
874
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000875 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
876 // involved in an eviction before. If a cascade number was assigned, deny
877 // evicting anything with the same or a newer cascade number. This prevents
878 // infinite eviction loops.
879 //
880 // This works out so a register without a cascade number is allowed to evict
881 // anything, and it can be evicted by anything.
882 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
883 if (!Cascade)
884 Cascade = NextCascade;
885
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000886 EvictionCost Cost;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000887 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
888 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000889 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000890 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000891 return false;
892
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000893 // Check if any interfering live range is heavier than MaxWeight.
894 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
895 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000896 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
897 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000898 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000899 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000900 return false;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000901 // Once a live range becomes small enough, it is urgent that we find a
902 // register for it. This is indicated by an infinite spill weight. These
903 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen05e22452012-05-30 21:46:58 +0000904 //
905 // Also allow urgent evictions of unspillable ranges from a strictly
906 // larger allocation order.
907 bool Urgent = !VirtReg.isSpillable() &&
908 (Intf->isSpillable() ||
909 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
910 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000911 // Only evict older cascades or live ranges without a cascade.
912 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
913 if (Cascade <= IntfCascade) {
914 if (!Urgent)
915 return false;
916 // We permit breaking cascades for urgent evictions. It should be the
917 // last resort, though, so make it really expensive.
918 Cost.BrokenHints += 10;
919 }
920 // Would this break a satisfied hint?
921 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
922 // Update eviction cost.
923 Cost.BrokenHints += BreaksHint;
924 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
925 // Abort if this would be too expensive.
926 if (!(Cost < MaxCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000927 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000928 if (Urgent)
929 continue;
Andrew Trickc2ab53a2013-11-29 23:49:38 +0000930 // Apply the eviction policy for non-urgent evictions.
931 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
932 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000933 // If !MaxCost.isMax(), then we're just looking for a cheap register.
934 // Evicting another local live range in this case could lead to suboptimal
935 // coloring.
Andrew Trick8bb0a252013-07-25 18:35:19 +0000936 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000937 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
Andrew Trick84852572013-07-25 18:35:14 +0000938 return false;
Andrew Trick8bb0a252013-07-25 18:35:19 +0000939 }
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000940 }
941 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000942 MaxCost = Cost;
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000943 return true;
944}
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000945
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000946/// Return true if all interferences between VirtReg and PhysReg between
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000947/// Start and End can be evicted.
948///
949/// \param VirtReg Live range that is about to be assigned.
950/// \param PhysReg Desired register for assignment.
951/// \param Start Start of range to look for interferences.
952/// \param End End of range to look for interferences.
953/// \param MaxCost Only look for cheaper candidates and update with new cost
954/// when returning true.
955/// \return True when interference can be evicted cheaper than MaxCost.
956bool RAGreedy::canEvictInterferenceInRange(LiveInterval &VirtReg,
957 unsigned PhysReg, SlotIndex Start,
958 SlotIndex End,
959 EvictionCost &MaxCost) {
960 EvictionCost Cost;
961
962 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
963 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
964
965 // Check if any interfering live range is heavier than MaxWeight.
966 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
967 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
968
969 // Check if interference overlast the segment in interest.
970 if (!Intf->overlaps(Start, End))
971 continue;
972
973 // Cannot evict non virtual reg interference.
974 if (!TargetRegisterInfo::isVirtualRegister(Intf->reg))
975 return false;
976 // Never evict spill products. They cannot split or spill.
977 if (getStage(*Intf) == RS_Done)
978 return false;
979
980 // Would this break a satisfied hint?
981 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
982 // Update eviction cost.
983 Cost.BrokenHints += BreaksHint;
984 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
985 // Abort if this would be too expensive.
986 if (!(Cost < MaxCost))
987 return false;
988 }
989 }
990
991 if (Cost.MaxWeight == 0)
992 return false;
993
994 MaxCost = Cost;
995 return true;
996}
997
Hiroshi Inouec73b6d62018-06-20 05:29:26 +0000998/// Return the physical register that will be best
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000999/// candidate for eviction by a local split interval that will be created
1000/// between Start and End.
1001///
1002/// \param Order The allocation order
1003/// \param VirtReg Live range that is about to be assigned.
1004/// \param Start Start of range to look for interferences
1005/// \param End End of range to look for interferences
1006/// \param BestEvictweight The eviction cost of that eviction
1007/// \return The PhysReg which is the best candidate for eviction and the
1008/// eviction cost in BestEvictweight
1009unsigned RAGreedy::getCheapestEvicteeWeight(const AllocationOrder &Order,
1010 LiveInterval &VirtReg,
1011 SlotIndex Start, SlotIndex End,
1012 float *BestEvictweight) {
1013 EvictionCost BestEvictCost;
1014 BestEvictCost.setMax();
1015 BestEvictCost.MaxWeight = VirtReg.weight;
1016 unsigned BestEvicteePhys = 0;
1017
1018 // Go over all physical registers and find the best candidate for eviction
1019 for (auto PhysReg : Order.getOrder()) {
1020
1021 if (!canEvictInterferenceInRange(VirtReg, PhysReg, Start, End,
1022 BestEvictCost))
1023 continue;
1024
1025 // Best so far.
1026 BestEvicteePhys = PhysReg;
1027 }
1028 *BestEvictweight = BestEvictCost.MaxWeight;
1029 return BestEvicteePhys;
1030}
1031
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001032/// evictInterference - Evict any interferring registers that prevent VirtReg
1033/// from being assigned to Physreg. This assumes that canEvictInterference
1034/// returned true.
1035void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001036 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001037 // Make sure that VirtReg has a cascade number, and assign that cascade
1038 // number to every evicted register. These live ranges than then only be
1039 // evicted by a newer cascade, preventing infinite loops.
1040 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
1041 if (!Cascade)
1042 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
1043
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001044 LLVM_DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI)
1045 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001046
1047 // Collect all interfering virtregs first.
1048 SmallVector<LiveInterval*, 8> Intfs;
1049 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1050 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Matthias Braunffe40dd2017-03-03 23:27:20 +00001051 // We usually have the interfering VRegs cached so collectInterferingVRegs()
1052 // should be fast, we may need to recalculate if when different physregs
1053 // overlap the same register unit so we had different SubRanges queried
1054 // against it.
1055 Q.collectInterferingVRegs();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001056 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
1057 Intfs.append(IVR.begin(), IVR.end());
1058 }
1059
1060 // Evict them second. This will invalidate the queries.
1061 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
1062 LiveInterval *Intf = Intfs[i];
1063 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
1064 if (!VRM->hasPhys(Intf->reg))
1065 continue;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001066
1067 LastEvicted.addEviction(PhysReg, VirtReg.reg, Intf->reg);
1068
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001069 Matrix->unassign(*Intf);
1070 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
1071 VirtReg.isSpillable() < Intf->isSpillable()) &&
1072 "Cannot decrease cascade number, illegal eviction");
1073 ExtraRegInfo[Intf->reg].Cascade = Cascade;
1074 ++NumEvicted;
Mark Laceyf9ea8852013-08-14 23:50:04 +00001075 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001076 }
1077}
1078
Matthias Braun953393a2015-07-14 17:38:17 +00001079/// Returns true if the given \p PhysReg is a callee saved register and has not
1080/// been used for allocation yet.
1081bool RAGreedy::isUnusedCalleeSavedReg(unsigned PhysReg) const {
1082 unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
1083 if (CSR == 0)
1084 return false;
1085
1086 return !Matrix->isPhysRegUsed(PhysReg);
1087}
1088
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001089/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001090/// @param VirtReg Currently unassigned virtual register.
1091/// @param Order Physregs to try.
1092/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001093unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
1094 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001095 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001096 unsigned CostPerUseLimit) {
Matthias Braun9f15a792016-11-18 19:43:18 +00001097 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
1098 TimePassesIsEnabled);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001099
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001100 // Keep track of the cheapest interference seen so far.
Andrew Trick3621b8a2013-11-22 19:07:38 +00001101 EvictionCost BestCost;
1102 BestCost.setMax();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001103 unsigned BestPhys = 0;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +00001104 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001105
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001106 // When we are just looking for a reduced cost per use, don't break any
1107 // hints, and only evict smaller spill weights.
1108 if (CostPerUseLimit < ~0u) {
1109 BestCost.BrokenHints = 0;
1110 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +00001111
1112 // Check of any registers in RC are below CostPerUseLimit.
1113 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
1114 unsigned MinCost = RegClassInfo.getMinCost(RC);
1115 if (MinCost >= CostPerUseLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001116 LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = "
1117 << MinCost << ", no cheaper registers to be found.\n");
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +00001118 return 0;
1119 }
1120
1121 // It is normal for register classes to have a long tail of registers with
1122 // the same cost. We don't need to look at them if they're too expensive.
1123 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
1124 OrderLimit = RegClassInfo.getLastCostChange(RC);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001125 LLVM_DEBUG(dbgs() << "Only trying the first " << OrderLimit
1126 << " regs.\n");
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +00001127 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001128 }
1129
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001130 Order.rewind();
Aditya Nandakumar73f3d332013-12-05 21:18:40 +00001131 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001132 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
1133 continue;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001134 // The first use of a callee-saved register in a function has cost 1.
1135 // Don't start using a CSR when the CostPerUseLimit is low.
Matthias Braun953393a2015-07-14 17:38:17 +00001136 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001137 LLVM_DEBUG(
1138 dbgs() << printReg(PhysReg, TRI) << " would clobber CSR "
1139 << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
1140 << '\n');
Matthias Braun953393a2015-07-14 17:38:17 +00001141 continue;
1142 }
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001143
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001144 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001145 continue;
1146
1147 // Best so far.
1148 BestPhys = PhysReg;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001149
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +00001150 // Stop if the hint can be used.
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +00001151 if (Order.isHint())
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +00001152 break;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +00001153 }
1154
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001155 if (!BestPhys)
1156 return 0;
1157
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001158 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001159 return BestPhys;
Andrew Trickccef0982010-12-09 18:15:21 +00001160}
1161
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001162//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001163// Region Splitting
1164//===----------------------------------------------------------------------===//
1165
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001166/// addSplitConstraints - Fill out the SplitConstraints vector based on the
1167/// interference pattern in Physreg and its aliases. Add the constraints to
1168/// SpillPlacement and return the static cost of this split in Cost, assuming
1169/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001170/// Return false if there are no bundles with positive bias.
1171bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001172 BlockFrequency &Cost) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001173 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001174
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001175 // Reset interference dependent info.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001176 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001177 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001178 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1179 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001180 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001181
Jakob Stoklund Olesenb1b76ad2011-02-09 22:50:26 +00001182 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001183 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001184 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
1185 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie041f1aa2013-05-15 07:36:59 +00001186 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001187
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001188 if (!Intf.hasInterference())
1189 continue;
1190
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001191 // Number of spill code instructions to insert.
1192 unsigned Ins = 0;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001193
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001194 // Interference for the live-in value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001195 if (BI.LiveIn) {
Richard Trieu7a083812016-02-18 22:09:30 +00001196 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
1197 BC.Entry = SpillPlacement::MustSpill;
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001198 ++Ins;
Richard Trieu7a083812016-02-18 22:09:30 +00001199 } else if (Intf.first() < BI.FirstInstr) {
1200 BC.Entry = SpillPlacement::PrefSpill;
1201 ++Ins;
1202 } else if (Intf.first() < BI.LastInstr) {
1203 ++Ins;
1204 }
Jakob Stoklund Olesenf248b202011-02-08 23:02:58 +00001205 }
1206
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001207 // Interference for the live-out value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001208 if (BI.LiveOut) {
Richard Trieu7a083812016-02-18 22:09:30 +00001209 if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
1210 BC.Exit = SpillPlacement::MustSpill;
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001211 ++Ins;
Richard Trieu7a083812016-02-18 22:09:30 +00001212 } else if (Intf.last() > BI.LastInstr) {
1213 BC.Exit = SpillPlacement::PrefSpill;
1214 ++Ins;
1215 } else if (Intf.last() > BI.FirstInstr) {
1216 ++Ins;
1217 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001218 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001219
1220 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001221 while (Ins--)
1222 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001223 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001224 Cost = StaticCost;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001225
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001226 // Add constraints for use-blocks. Note that these are the only constraints
1227 // that may add a positive bias, it is downhill from here.
1228 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001229 return SpillPlacer->scanActiveBundles();
1230}
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001231
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001232/// addThroughConstraints - Add constraints and links to SpillPlacer from the
1233/// live-through blocks in Blocks.
1234void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
1235 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001236 const unsigned GroupSize = 8;
1237 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001238 unsigned TBS[GroupSize];
1239 unsigned B = 0, T = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001240
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001241 for (unsigned i = 0; i != Blocks.size(); ++i) {
1242 unsigned Number = Blocks[i];
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001243 Intf.moveToBlock(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001244
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001245 if (!Intf.hasInterference()) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001246 assert(T < GroupSize && "Array overflow");
1247 TBS[T] = Number;
1248 if (++T == GroupSize) {
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001249 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001250 T = 0;
1251 }
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001252 continue;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001253 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001254
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001255 assert(B < GroupSize && "Array overflow");
1256 BCS[B].Number = Number;
1257
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001258 // Interference for the live-in value.
1259 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
1260 BCS[B].Entry = SpillPlacement::MustSpill;
1261 else
1262 BCS[B].Entry = SpillPlacement::PrefSpill;
1263
1264 // Interference for the live-out value.
1265 if (Intf.last() >= SA->getLastSplitPoint(Number))
1266 BCS[B].Exit = SpillPlacement::MustSpill;
1267 else
1268 BCS[B].Exit = SpillPlacement::PrefSpill;
1269
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001270 if (++B == GroupSize) {
Craig Toppere1d12942014-08-27 05:25:25 +00001271 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001272 B = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001273 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001274 }
1275
Craig Toppere1d12942014-08-27 05:25:25 +00001276 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001277 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001278}
1279
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001280void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001281 // Keep track of through blocks that have not been added to SpillPlacer.
1282 BitVector Todo = SA->getThroughBlocks();
1283 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
1284 unsigned AddedTo = 0;
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001285#ifndef NDEBUG
1286 unsigned Visited = 0;
1287#endif
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001288
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001289 while (true) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001290 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001291 // Find new through blocks in the periphery of PrefRegBundles.
1292 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
1293 unsigned Bundle = NewBundles[i];
1294 // Look at all blocks connected to Bundle in the full graph.
1295 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
1296 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
1297 I != E; ++I) {
1298 unsigned Block = *I;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001299 if (!Todo.test(Block))
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001300 continue;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001301 Todo.reset(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001302 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001303 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001304#ifndef NDEBUG
1305 ++Visited;
1306#endif
1307 }
1308 }
1309 // Any new blocks to add?
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001310 if (ActiveBlocks.size() == AddedTo)
1311 break;
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001312
1313 // Compute through constraints from the interference, or assume that all
1314 // through blocks prefer spilling when forming compact regions.
Craig Toppere1d12942014-08-27 05:25:25 +00001315 auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001316 if (Cand.PhysReg)
1317 addThroughConstraints(Cand.Intf, NewBlocks);
1318 else
Jakob Stoklund Olesen86954522011-08-03 23:09:38 +00001319 // Provide a strong negative bias on through blocks to prevent unwanted
1320 // liveness on loop backedges.
1321 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001322 AddedTo = ActiveBlocks.size();
1323
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001324 // Perhaps iterating can enable more bundles?
1325 SpillPlacer->iterate();
1326 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001327 LLVM_DEBUG(dbgs() << ", v=" << Visited);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001328}
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001329
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001330/// calcCompactRegion - Compute the set of edge bundles that should be live
1331/// when splitting the current live range into compact regions. Compact
1332/// regions can be computed without looking at interference. They are the
1333/// regions formed by removing all the live-through blocks from the live range.
1334///
1335/// Returns false if the current live range is already compact, or if the
1336/// compact regions would form single block regions anyway.
1337bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1338 // Without any through blocks, the live range is already compact.
1339 if (!SA->getNumThroughBlocks())
1340 return false;
1341
1342 // Compact regions don't correspond to any physreg.
1343 Cand.reset(IntfCache, 0);
1344
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001345 LLVM_DEBUG(dbgs() << "Compact region bundles");
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001346
1347 // Use the spill placer to determine the live bundles. GrowRegion pretends
1348 // that all the through blocks have interference when PhysReg is unset.
1349 SpillPlacer->prepare(Cand.LiveBundles);
1350
1351 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001352 BlockFrequency Cost;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001353 if (!addSplitConstraints(Cand.Intf, Cost)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001354 LLVM_DEBUG(dbgs() << ", none.\n");
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001355 return false;
1356 }
1357
1358 growRegion(Cand);
1359 SpillPlacer->finish();
1360
1361 if (!Cand.LiveBundles.any()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001362 LLVM_DEBUG(dbgs() << ", none.\n");
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001363 return false;
1364 }
1365
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001366 LLVM_DEBUG({
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001367 for (int i : Cand.LiveBundles.set_bits())
1368 dbgs() << " EB#" << i;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001369 dbgs() << ".\n";
1370 });
1371 return true;
1372}
1373
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001374/// calcSpillCost - Compute how expensive it would be to split the live range in
1375/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001376BlockFrequency RAGreedy::calcSpillCost() {
1377 BlockFrequency Cost = 0;
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001378 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1379 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1380 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1381 unsigned Number = BI.MBB->getNumber();
1382 // We normally only need one spill instruction - a load or a store.
1383 Cost += SpillPlacer->getBlockFrequency(Number);
1384
1385 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3c145052011-08-02 23:04:08 +00001386 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1387 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001388 }
1389 return Cost;
1390}
1391
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001392/// Check if splitting Evictee will create a local split interval in
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001393/// basic block number BBNumber that may cause a bad eviction chain. This is
1394/// intended to prevent bad eviction sequences like:
1395/// movl %ebp, 8(%esp) # 4-byte Spill
1396/// movl %ecx, %ebp
1397/// movl %ebx, %ecx
1398/// movl %edi, %ebx
1399/// movl %edx, %edi
1400/// cltd
1401/// idivl %esi
1402/// movl %edi, %edx
1403/// movl %ebx, %edi
1404/// movl %ecx, %ebx
1405/// movl %ebp, %ecx
1406/// movl 16(%esp), %ebp # 4 - byte Reload
1407///
1408/// Such sequences are created in 2 scenarios:
1409///
1410/// Scenario #1:
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001411/// %0 is evicted from physreg0 by %1.
1412/// Evictee %0 is intended for region splitting with split candidate
1413/// physreg0 (the reg %0 was evicted from).
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001414/// Region splitting creates a local interval because of interference with the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001415/// evictor %1 (normally region splitting creates 2 interval, the "by reg"
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001416/// and "by stack" intervals and local interval created when interference
1417/// occurs).
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001418/// One of the split intervals ends up evicting %2 from physreg1.
1419/// Evictee %2 is intended for region splitting with split candidate
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001420/// physreg1.
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001421/// One of the split intervals ends up evicting %3 from physreg2, etc.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001422///
1423/// Scenario #2
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001424/// %0 is evicted from physreg0 by %1.
1425/// %2 is evicted from physreg2 by %3 etc.
1426/// Evictee %0 is intended for region splitting with split candidate
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001427/// physreg1.
1428/// Region splitting creates a local interval because of interference with the
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001429/// evictor %1.
1430/// One of the split intervals ends up evicting back original evictor %1
1431/// from physreg0 (the reg %0 was evicted from).
1432/// Another evictee %2 is intended for region splitting with split candidate
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001433/// physreg1.
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001434/// One of the split intervals ends up evicting %3 from physreg2, etc.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001435///
1436/// \param Evictee The register considered to be split.
1437/// \param Cand The split candidate that determines the physical register
1438/// we are splitting for and the interferences.
1439/// \param BBNumber The number of a BB for which the region split process will
1440/// create a local split interval.
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001441/// \param Order The physical registers that may get evicted by a split
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001442/// artifact of Evictee.
1443/// \return True if splitting Evictee may cause a bad eviction chain, false
1444/// otherwise.
1445bool RAGreedy::splitCanCauseEvictionChain(unsigned Evictee,
1446 GlobalSplitCandidate &Cand,
1447 unsigned BBNumber,
1448 const AllocationOrder &Order) {
1449 EvictionTrack::EvictorInfo VregEvictorInfo = LastEvicted.getEvictor(Evictee);
1450 unsigned Evictor = VregEvictorInfo.first;
1451 unsigned PhysReg = VregEvictorInfo.second;
1452
1453 // No actual evictor.
1454 if (!Evictor || !PhysReg)
1455 return false;
1456
1457 float MaxWeight = 0;
1458 unsigned FutureEvictedPhysReg =
1459 getCheapestEvicteeWeight(Order, LIS->getInterval(Evictee),
1460 Cand.Intf.first(), Cand.Intf.last(), &MaxWeight);
1461
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001462 // The bad eviction chain occurs when either the split candidate is the
1463 // evicting reg or one of the split artifact will evict the evicting reg.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001464 if ((PhysReg != Cand.PhysReg) && (PhysReg != FutureEvictedPhysReg))
1465 return false;
1466
1467 Cand.Intf.moveToBlock(BBNumber);
1468
1469 // Check to see if the Evictor contains interference (with Evictee) in the
1470 // given BB. If so, this interference caused the eviction of Evictee from
1471 // PhysReg. This suggest that we will create a local interval during the
1472 // region split to avoid this interference This local interval may cause a bad
1473 // eviction chain.
1474 if (!LIS->hasInterval(Evictor))
1475 return false;
1476 LiveInterval &EvictorLI = LIS->getInterval(Evictor);
1477 if (EvictorLI.FindSegmentContaining(Cand.Intf.first()) == EvictorLI.end())
1478 return false;
1479
1480 // Now, check to see if the local interval we will create is going to be
1481 // expensive enough to evict somebody If so, this may cause a bad eviction
1482 // chain.
1483 VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1484 float splitArtifactWeight =
1485 VRAI.futureWeight(LIS->getInterval(Evictee),
1486 Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1487 if (splitArtifactWeight >= 0 && splitArtifactWeight < MaxWeight)
1488 return false;
1489
1490 return true;
1491}
1492
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001493/// Check if splitting VirtRegToSplit will create a local split interval
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001494/// in basic block number BBNumber that may cause a spill.
1495///
1496/// \param VirtRegToSplit The register considered to be split.
1497/// \param Cand The split candidate that determines the physical
1498/// register we are splitting for and the interferences.
1499/// \param BBNumber The number of a BB for which the region split process
1500/// will create a local split interval.
1501/// \param Order The physical registers that may get evicted by a
1502/// split artifact of VirtRegToSplit.
1503/// \return True if splitting VirtRegToSplit may cause a spill, false
1504/// otherwise.
1505bool RAGreedy::splitCanCauseLocalSpill(unsigned VirtRegToSplit,
1506 GlobalSplitCandidate &Cand,
1507 unsigned BBNumber,
1508 const AllocationOrder &Order) {
1509 Cand.Intf.moveToBlock(BBNumber);
1510
1511 // Check if the local interval will find a non interfereing assignment.
1512 for (auto PhysReg : Order.getOrder()) {
1513 if (!Matrix->checkInterference(Cand.Intf.first().getPrevIndex(),
1514 Cand.Intf.last(), PhysReg))
1515 return false;
1516 }
1517
1518 // Check if the local interval will evict a cheaper interval.
1519 float CheapestEvictWeight = 0;
1520 unsigned FutureEvictedPhysReg = getCheapestEvicteeWeight(
1521 Order, LIS->getInterval(VirtRegToSplit), Cand.Intf.first(),
1522 Cand.Intf.last(), &CheapestEvictWeight);
1523
1524 // Have we found an interval that can be evicted?
1525 if (FutureEvictedPhysReg) {
1526 VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1527 float splitArtifactWeight =
1528 VRAI.futureWeight(LIS->getInterval(VirtRegToSplit),
1529 Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1530 // Will the weight of the local interval be higher than the cheapest evictee
1531 // weight? If so it will evict it and will not cause a spill.
1532 if (splitArtifactWeight >= 0 && splitArtifactWeight > CheapestEvictWeight)
1533 return false;
1534 }
1535
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001536 // The local interval is not able to find non interferencing assignment and
1537 // not able to evict a less worthy interval, therfore, it can cause a spill.
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001538 return true;
1539}
1540
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001541/// calcGlobalSplitCost - Return the global split cost of following the split
1542/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001543/// interference pattern in SplitConstraints.
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001544///
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001545BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
1546 const AllocationOrder &Order,
1547 bool *CanCauseEvictionChain) {
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001548 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001549 const BitVector &LiveBundles = Cand.LiveBundles;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001550 unsigned VirtRegToSplit = SA->getParent().reg;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001551 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1552 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1553 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001554 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001555 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, false)];
1556 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)];
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001557 unsigned Ins = 0;
1558
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001559 Cand.Intf.moveToBlock(BC.Number);
1560 // Check wheather a local interval is going to be created during the region
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001561 // split. Calculate adavanced spilt cost (cost of local intervals) if option
1562 // is enabled.
1563 if (EnableAdvancedRASplitCost && Cand.Intf.hasInterference() && BI.LiveIn &&
1564 BI.LiveOut && RegIn && RegOut) {
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001565
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001566 if (CanCauseEvictionChain &&
1567 splitCanCauseEvictionChain(VirtRegToSplit, Cand, BC.Number, Order)) {
1568 // This interference causes our eviction from this assignment, we might
1569 // evict somebody else and eventually someone will spill, add that cost.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001570 // See splitCanCauseEvictionChain for detailed description of scenarios.
1571 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1572 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1573
1574 *CanCauseEvictionChain = true;
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001575
1576 } else if (splitCanCauseLocalSpill(VirtRegToSplit, Cand, BC.Number,
1577 Order)) {
1578 // This interference causes local interval to spill, add that cost.
1579 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1580 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001581 }
1582 }
1583
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001584 if (BI.LiveIn)
1585 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1586 if (BI.LiveOut)
1587 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001588 while (Ins--)
1589 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001590 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001591
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001592 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1593 unsigned Number = Cand.ActiveBlocks[i];
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001594 bool RegIn = LiveBundles[Bundles->getBundle(Number, false)];
1595 bool RegOut = LiveBundles[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001596 if (!RegIn && !RegOut)
1597 continue;
1598 if (RegIn && RegOut) {
1599 // We need double spill code if this block has interference.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001600 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001601 if (Cand.Intf.hasInterference()) {
1602 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1603 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001604
1605 // Check wheather a local interval is going to be created during the
1606 // region split.
1607 if (EnableAdvancedRASplitCost && CanCauseEvictionChain &&
1608 splitCanCauseEvictionChain(VirtRegToSplit, Cand, Number, Order)) {
Marina Yatsinacd5bc4a2018-01-31 13:31:08 +00001609 // This interference cause our eviction from this assignment, we might
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001610 // evict somebody else, add that cost.
1611 // See splitCanCauseEvictionChain for detailed description of
1612 // scenarios.
1613 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1614 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1615
1616 *CanCauseEvictionChain = true;
1617 }
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001618 }
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001619 continue;
1620 }
1621 // live-in / stack-out or stack-in live-out.
1622 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001623 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001624 return GlobalCost;
1625}
1626
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001627/// splitAroundRegion - Split the current live range around the regions
1628/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001629///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001630/// Before calling this function, GlobalCand and BundleCand must be initialized
1631/// so each bundle is assigned to a valid candidate, or NoCand for the
1632/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1633/// objects must be initialized for the current live range, and intervals
1634/// created for the used candidates.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001635///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001636/// @param LREdit The LiveRangeEdit object handling the current split.
1637/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1638/// must appear in this list.
1639void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1640 ArrayRef<unsigned> UsedCands) {
1641 // These are the intervals created for new global ranges. We may create more
1642 // intervals for local ranges.
1643 const unsigned NumGlobalIntvs = LREdit.size();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001644 LLVM_DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs
1645 << " globals.\n");
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001646 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001647
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001648 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen22f37a12011-08-06 18:20:24 +00001649 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001650 // is all copies.
1651 unsigned Reg = SA->getParent().reg;
1652 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1653
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001654 // First handle all the blocks with uses.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001655 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1656 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1657 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001658 unsigned Number = BI.MBB->getNumber();
1659 unsigned IntvIn = 0, IntvOut = 0;
1660 SlotIndex IntfIn, IntfOut;
1661 if (BI.LiveIn) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001662 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001663 if (CandIn != NoCand) {
1664 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1665 IntvIn = Cand.IntvIdx;
1666 Cand.Intf.moveToBlock(Number);
1667 IntfIn = Cand.Intf.first();
1668 }
1669 }
1670 if (BI.LiveOut) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001671 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001672 if (CandOut != NoCand) {
1673 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1674 IntvOut = Cand.IntvIdx;
1675 Cand.Intf.moveToBlock(Number);
1676 IntfOut = Cand.Intf.last();
1677 }
1678 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001679
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001680 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001681 if (!IntvIn && !IntvOut) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001682 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " isolated.\n");
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001683 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001684 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001685 continue;
1686 }
1687
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001688 if (IntvIn && IntvOut)
1689 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1690 else if (IntvIn)
1691 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesen795da1c2011-07-15 21:47:57 +00001692 else
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001693 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001694 }
1695
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001696 // Handle live-through blocks. The relevant live-through blocks are stored in
1697 // the ActiveBlocks list with each candidate. We need to filter out
1698 // duplicates.
1699 BitVector Todo = SA->getThroughBlocks();
1700 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1701 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1702 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1703 unsigned Number = Blocks[i];
1704 if (!Todo.test(Number))
1705 continue;
1706 Todo.reset(Number);
1707
1708 unsigned IntvIn = 0, IntvOut = 0;
1709 SlotIndex IntfIn, IntfOut;
1710
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001711 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001712 if (CandIn != NoCand) {
1713 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1714 IntvIn = Cand.IntvIdx;
1715 Cand.Intf.moveToBlock(Number);
1716 IntfIn = Cand.Intf.first();
1717 }
1718
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001719 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001720 if (CandOut != NoCand) {
1721 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1722 IntvOut = Cand.IntvIdx;
1723 Cand.Intf.moveToBlock(Number);
1724 IntfOut = Cand.Intf.last();
1725 }
1726 if (!IntvIn && !IntvOut)
1727 continue;
1728 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1729 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001730 }
1731
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001732 ++NumGlobalSplits;
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001733
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001734 SmallVector<unsigned, 8> IntvMap;
1735 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001736 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001737
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001738 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen5cc91b22011-05-28 02:32:57 +00001739 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001740
1741 // Sort out the new intervals created by splitting. We get four kinds:
1742 // - Remainder intervals should not be split again.
1743 // - Candidate intervals can be assigned to Cand.PhysReg.
1744 // - Block-local splits are candidates for local splitting.
1745 // - DCE leftovers should go back on the queue.
1746 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001747 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001748
1749 // Ignore old intervals from DCE.
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001750 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001751 continue;
1752
1753 // Remainder interval. Don't try splitting again, spill if it doesn't
1754 // allocate.
1755 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001756 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001757 continue;
1758 }
1759
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001760 // Global intervals. Allow repeated splitting as long as the number of live
1761 // blocks is strictly decreasing.
1762 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001763 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001764 LLVM_DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1765 << " blocks as original.\n");
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001766 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001767 setStage(Reg, RS_Split2);
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001768 }
1769 continue;
1770 }
1771
1772 // Other intervals are treated as new. This includes local intervals created
1773 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001774 }
1775
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +00001776 if (VerifyEnabled)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001777 MF->verify(this, "After splitting live range around region");
1778}
1779
Wei Mi40c4aa72018-07-16 15:42:20 +00001780// Global split has high compile time cost especially for large live range.
1781// Return false for the case here where the potential benefit will never
1782// worth the cost.
1783unsigned RAGreedy::isSplitBenefitWorthCost(LiveInterval &VirtReg) {
1784 MachineInstr *MI = MRI->getUniqueVRegDef(VirtReg.reg);
1785 if (MI && TII->isTriviallyReMaterializable(*MI, AA) &&
1786 VirtReg.size() > HugeSizeForSplit)
1787 return false;
1788 return true;
1789}
1790
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001791unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001792 SmallVectorImpl<unsigned> &NewVRegs) {
Wei Mi40c4aa72018-07-16 15:42:20 +00001793 if (!isSplitBenefitWorthCost(VirtReg))
1794 return 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001795 unsigned NumCands = 0;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001796 BlockFrequency SpillCost = calcSpillCost();
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001797 BlockFrequency BestCost;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001798
1799 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +00001800 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001801 if (HasCompact) {
1802 // Yes, keep GlobalCand[0] as the compact region candidate.
1803 NumCands = 1;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001804 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001805 } else {
1806 // No benefit from the compact region, our fallback will be per-block
1807 // splitting. Make sure we find a solution that is cheaper than spilling.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001808 BestCost = SpillCost;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001809 LLVM_DEBUG(dbgs() << "Cost of isolating all blocks = ";
1810 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001811 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001812
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001813 bool CanCauseEvictionChain = false;
Manman Ren9db66b32014-03-24 23:23:42 +00001814 unsigned BestCand =
Manman Ren78cf02a2014-03-25 00:16:25 +00001815 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001816 false /*IgnoreCSR*/, &CanCauseEvictionChain);
1817
1818 // Split candidates with compact regions can cause a bad eviction sequence.
1819 // See splitCanCauseEvictionChain for detailed description of scenarios.
1820 // To avoid it, we need to comapre the cost with the spill cost and not the
1821 // current max frequency.
1822 if (HasCompact && (BestCost > SpillCost) && (BestCand != NoCand) &&
1823 CanCauseEvictionChain) {
1824 return 0;
1825 }
Manman Ren9db66b32014-03-24 23:23:42 +00001826
1827 // No solutions found, fall back to single block splitting.
1828 if (!HasCompact && BestCand == NoCand)
1829 return 0;
1830
1831 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1832}
1833
1834unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1835 AllocationOrder &Order,
1836 BlockFrequency &BestCost,
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001837 unsigned &NumCands, bool IgnoreCSR,
1838 bool *CanCauseEvictionChain) {
Manman Ren9db66b32014-03-24 23:23:42 +00001839 unsigned BestCand = NoCand;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001840 Order.rewind();
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001841 while (unsigned PhysReg = Order.next()) {
Matthias Braun953393a2015-07-14 17:38:17 +00001842 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1843 continue;
Manman Ren78cf02a2014-03-25 00:16:25 +00001844
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001845 // Discard bad candidates before we run out of interference cache cursors.
1846 // This will only affect register classes with a lot of registers (>32).
1847 if (NumCands == IntfCache.getMaxCursors()) {
1848 unsigned WorstCount = ~0u;
1849 unsigned Worst = 0;
1850 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001851 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001852 continue;
1853 unsigned Count = GlobalCand[i].LiveBundles.count();
Richard Trieu7a083812016-02-18 22:09:30 +00001854 if (Count < WorstCount) {
1855 Worst = i;
1856 WorstCount = Count;
1857 }
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001858 }
1859 --NumCands;
1860 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen559d4dc2011-11-01 00:02:31 +00001861 if (BestCand == NumCands)
1862 BestCand = Worst;
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001863 }
1864
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001865 if (GlobalCand.size() <= NumCands)
1866 GlobalCand.resize(NumCands+1);
1867 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1868 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001869
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001870 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001871 BlockFrequency Cost;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001872 if (!addSplitConstraints(Cand.Intf, Cost)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001873 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001874 continue;
1875 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001876 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tstatic = ";
1877 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001878 if (Cost >= BestCost) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001879 LLVM_DEBUG({
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001880 if (BestCand == NoCand)
1881 dbgs() << " worse than no bundles\n";
1882 else
1883 dbgs() << " worse than "
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001884 << printReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001885 });
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001886 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001887 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001888 growRegion(Cand);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001889
Jakob Stoklund Olesen36b5d8a2011-04-06 19:13:57 +00001890 SpillPlacer->finish();
1891
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001892 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001893 if (!Cand.LiveBundles.any()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001894 LLVM_DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001895 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001896 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001897
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001898 bool HasEvictionChain = false;
1899 Cost += calcGlobalSplitCost(Cand, Order, &HasEvictionChain);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001900 LLVM_DEBUG({
1901 dbgs() << ", total = ";
1902 MBFI->printBlockFreq(dbgs(), Cost) << " with bundles";
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001903 for (int i : Cand.LiveBundles.set_bits())
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001904 dbgs() << " EB#" << i;
1905 dbgs() << ".\n";
1906 });
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001907 if (Cost < BestCost) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001908 BestCand = NumCands;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001909 BestCost = Cost;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001910 // See splitCanCauseEvictionChain for detailed description of bad
1911 // eviction chain scenarios.
1912 if (CanCauseEvictionChain)
1913 *CanCauseEvictionChain = HasEvictionChain;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001914 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001915 ++NumCands;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001916 }
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001917
1918 if (CanCauseEvictionChain && BestCand != NoCand) {
1919 // See splitCanCauseEvictionChain for detailed description of bad
1920 // eviction chain scenarios.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001921 LLVM_DEBUG(dbgs() << "Best split candidate of vreg "
1922 << printReg(VirtReg.reg, TRI) << " may ");
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001923 if (!(*CanCauseEvictionChain))
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001924 LLVM_DEBUG(dbgs() << "not ");
1925 LLVM_DEBUG(dbgs() << "cause bad eviction chain\n");
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001926 }
1927
Manman Ren9db66b32014-03-24 23:23:42 +00001928 return BestCand;
1929}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001930
Manman Ren9db66b32014-03-24 23:23:42 +00001931unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1932 bool HasCompact,
1933 SmallVectorImpl<unsigned> &NewVRegs) {
1934 SmallVector<unsigned, 8> UsedCands;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001935 // Prepare split editor.
Wei Mi9a16d652016-04-13 03:08:27 +00001936 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001937 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001938
1939 // Assign all edge bundles to the preferred candidate, or NoCand.
1940 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1941
1942 // Assign bundles for the best candidate region.
1943 if (BestCand != NoCand) {
1944 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1945 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1946 UsedCands.push_back(BestCand);
1947 Cand.IntvIdx = SE->openIntv();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001948 LLVM_DEBUG(dbgs() << "Split for " << printReg(Cand.PhysReg, TRI) << " in "
1949 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001950 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001951 }
1952 }
1953
1954 // Assign bundles for the compact region.
1955 if (HasCompact) {
1956 GlobalSplitCandidate &Cand = GlobalCand.front();
1957 assert(!Cand.PhysReg && "Compact region has no physreg");
1958 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1959 UsedCands.push_back(0);
1960 Cand.IntvIdx = SE->openIntv();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001961 LLVM_DEBUG(dbgs() << "Split for compact region in " << B
1962 << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001963 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001964 }
1965 }
1966
1967 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001968 return 0;
1969}
1970
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001971//===----------------------------------------------------------------------===//
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001972// Per-Block Splitting
1973//===----------------------------------------------------------------------===//
1974
1975/// tryBlockSplit - Split a global live range around every block with uses. This
1976/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1977/// they don't allocate.
1978unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001979 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001980 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1981 unsigned Reg = VirtReg.reg;
1982 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Wei Mi9a16d652016-04-13 03:08:27 +00001983 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001984 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001985 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1986 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1987 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1988 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1989 SE->splitSingleBlock(BI);
1990 }
1991 // No blocks were split.
1992 if (LREdit.empty())
1993 return 0;
1994
1995 // We did split for some blocks.
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001996 SmallVector<unsigned, 8> IntvMap;
1997 SE->finish(&IntvMap);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001998
1999 // Tell LiveDebugVariables about the new ranges.
Mark Laceyf9ea8852013-08-14 23:50:04 +00002000 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00002001
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00002002 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2003
2004 // Sort out the new intervals created by splitting. The remainder interval
2005 // goes straight to spilling, the new local ranges get to stay RS_New.
2006 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00002007 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00002008 if (getStage(LI) == RS_New && IntvMap[i] == 0)
2009 setStage(LI, RS_Spill);
2010 }
2011
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00002012 if (VerifyEnabled)
2013 MF->verify(this, "After splitting live range around basic blocks");
2014 return 0;
2015}
2016
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002017//===----------------------------------------------------------------------===//
2018// Per-Instruction Splitting
2019//===----------------------------------------------------------------------===//
2020
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002021/// Get the number of allocatable registers that match the constraints of \p Reg
2022/// on \p MI and that are also in \p SuperRC.
2023static unsigned getNumAllocatableRegsForConstraints(
2024 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
2025 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
2026 const RegisterClassInfo &RCI) {
2027 assert(SuperRC && "Invalid register class");
2028
2029 const TargetRegisterClass *ConstrainedRC =
2030 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
2031 /* ExploreBundle */ true);
2032 if (!ConstrainedRC)
2033 return 0;
2034 return RCI.getNumAllocatableRegs(ConstrainedRC);
2035}
2036
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002037/// tryInstructionSplit - Split a live range around individual instructions.
2038/// This is normally not worthwhile since the spiller is doing essentially the
2039/// same thing. However, when the live range is in a constrained register
2040/// class, it may help to insert copies such that parts of the live range can
2041/// be moved to a larger register class.
2042///
2043/// This is similar to spilling to a larger register class.
2044unsigned
2045RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002046 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002047 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002048 // There is no point to this if there are no larger sub-classes.
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002049 if (!RegClassInfo.isProperSubClass(CurRC))
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002050 return 0;
2051
2052 // Always enable split spill mode, since we're effectively spilling to a
2053 // register.
Wei Mi9a16d652016-04-13 03:08:27 +00002054 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002055 SE->reset(LREdit, SplitEditor::SM_Size);
2056
2057 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2058 if (Uses.size() <= 1)
2059 return 0;
2060
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002061 LLVM_DEBUG(dbgs() << "Split around " << Uses.size()
2062 << " individual instrs.\n");
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002063
Eric Christopher433c4322015-03-10 23:46:01 +00002064 const TargetRegisterClass *SuperRC =
2065 TRI->getLargestLegalSuperClass(CurRC, *MF);
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002066 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
2067 // Split around every non-copy instruction if this split will relax
2068 // the constraints on the virtual register.
2069 // Otherwise, splitting just inserts uncoalescable copies that do not help
2070 // the allocation.
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002071 for (unsigned i = 0; i != Uses.size(); ++i) {
2072 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002073 if (MI->isFullCopy() ||
2074 SuperRCNumAllocatableRegs ==
2075 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
2076 TRI, RCI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002077 LLVM_DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002078 continue;
2079 }
2080 SE->openIntv();
2081 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
2082 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
2083 SE->useIntv(SegStart, SegStop);
2084 }
2085
2086 if (LREdit.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002087 LLVM_DEBUG(dbgs() << "All uses were copies.\n");
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002088 return 0;
2089 }
2090
2091 SmallVector<unsigned, 8> IntvMap;
2092 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00002093 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002094 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2095
2096 // Assign all new registers to RS_Spill. This was the last chance.
2097 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
2098 return 0;
2099}
2100
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00002101//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002102// Local Splitting
2103//===----------------------------------------------------------------------===//
2104
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002105/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
2106/// in order to use PhysReg between two entries in SA->UseSlots.
2107///
2108/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
2109///
2110void RAGreedy::calcGapWeights(unsigned PhysReg,
2111 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00002112 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
2113 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00002114 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002115 const unsigned NumGaps = Uses.size()-1;
2116
2117 // Start and end points for the interference check.
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00002118 SlotIndex StartIdx =
2119 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
2120 SlotIndex StopIdx =
2121 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002122
2123 GapWeight.assign(NumGaps, 0.0f);
2124
2125 // Add interference from each overlapping register.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002126 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2127 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
2128 .checkInterference())
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002129 continue;
2130
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00002131 // We know that VirtReg is a continuous interval from FirstInstr to
2132 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002133 //
2134 // Interference that overlaps an instruction is counted in both gaps
2135 // surrounding the instruction. The exception is interference before
2136 // StartIdx and after StopIdx.
2137 //
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002138 LiveIntervalUnion::SegmentIter IntI =
2139 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002140 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
2141 // Skip the gaps before IntI.
2142 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
2143 if (++Gap == NumGaps)
2144 break;
2145 if (Gap == NumGaps)
2146 break;
2147
2148 // Update the gaps covered by IntI.
2149 const float weight = IntI.value()->weight;
2150 for (; Gap != NumGaps; ++Gap) {
2151 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
2152 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
2153 break;
2154 }
2155 if (Gap == NumGaps)
2156 break;
2157 }
2158 }
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002159
2160 // Add fixed interference.
2161 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00002162 const LiveRange &LR = LIS->getRegUnit(*Units);
2163 LiveRange::const_iterator I = LR.find(StartIdx);
2164 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002165
2166 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
2167 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
2168 while (Uses[Gap+1].getBoundaryIndex() < I->start)
2169 if (++Gap == NumGaps)
2170 break;
2171 if (Gap == NumGaps)
2172 break;
2173
2174 for (; Gap != NumGaps; ++Gap) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002175 GapWeight[Gap] = huge_valf;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002176 if (Uses[Gap+1].getBaseIndex() >= I->end)
2177 break;
2178 }
2179 if (Gap == NumGaps)
2180 break;
2181 }
2182 }
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002183}
2184
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002185/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
2186/// basic block.
2187///
2188unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002189 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00002190 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
2191 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002192
2193 // Note that it is possible to have an interval that is live-in or live-out
2194 // while only covering a single block - A phi-def can use undef values from
2195 // predecessors, and the block could be a single-block loop.
2196 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00002197 // that the interval is continuous from FirstInstr to LastInstr. We should
2198 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002199
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00002200 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002201 if (Uses.size() <= 2)
2202 return 0;
2203 const unsigned NumGaps = Uses.size()-1;
2204
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002205 LLVM_DEBUG({
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002206 dbgs() << "tryLocalSplit: ";
2207 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00002208 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002209 dbgs() << '\n';
2210 });
2211
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002212 // If VirtReg is live across any register mask operands, compute a list of
2213 // gaps with register masks.
2214 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002215 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002216 // Get regmask slots for the whole block.
2217 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002218 LLVM_DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002219 // Constrain to VirtReg's live range.
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002220 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
2221 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002222 unsigned re = RMS.size();
2223 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002224 // Look for Uses[i] <= RMS <= Uses[i+1].
2225 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
2226 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002227 continue;
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002228 // Skip a regmask on the same instruction as the last use. It doesn't
2229 // overlap the live range.
2230 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
2231 break;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002232 LLVM_DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-'
2233 << Uses[i + 1]);
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002234 RegMaskGaps.push_back(i);
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002235 // Advance ri to the next gap. A regmask on one of the uses counts in
2236 // both gaps.
2237 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
2238 ++ri;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002239 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002240 LLVM_DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002241 }
2242
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002243 // Since we allow local split results to be split again, there is a risk of
2244 // creating infinite loops. It is tempting to require that the new live
2245 // ranges have less instructions than the original. That would guarantee
2246 // convergence, but it is too strict. A live range with 3 instructions can be
2247 // split 2+3 (including the COPY), and we want to allow that.
2248 //
2249 // Instead we use these rules:
2250 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002251 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002252 // noop split, of course).
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002253 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002254 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002255 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002256 // smaller ranges are marked RS_New.
2257 //
2258 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
2259 // excessive splitting and infinite loops.
2260 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002261 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002262
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002263 // Best split candidate.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002264 unsigned BestBefore = NumGaps;
2265 unsigned BestAfter = 0;
2266 float BestDiff = 0;
2267
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00002268 const float blockFreq =
2269 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Michael Gottesman5e985ee2013-12-14 02:37:38 +00002270 (1.0f / MBFI->getEntryFreq());
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002271 SmallVector<float, 8> GapWeight;
2272
2273 Order.rewind();
2274 while (unsigned PhysReg = Order.next()) {
2275 // Keep track of the largest spill weight that would need to be evicted in
2276 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
2277 calcGapWeights(PhysReg, GapWeight);
2278
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002279 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002280 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002281 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002282 GapWeight[RegMaskGaps[i]] = huge_valf;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002283
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002284 // Try to find the best sequence of gaps to close.
2285 // The new spill weight must be larger than any gap interference.
2286
2287 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002288 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002289
2290 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
2291 // It is the spill weight that needs to be evicted.
2292 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002293
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002294 while (true) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002295 // Live before/after split?
2296 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
2297 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
2298
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002299 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << ' ' << Uses[SplitBefore]
2300 << '-' << Uses[SplitAfter] << " i=" << MaxGap);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002301
2302 // Stop before the interval gets so big we wouldn't be making progress.
2303 if (!LiveBefore && !LiveAfter) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002304 LLVM_DEBUG(dbgs() << " all\n");
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002305 break;
2306 }
2307 // Should the interval be extended or shrunk?
2308 bool Shrink = true;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002309
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002310 // How many gaps would the new range have?
2311 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
2312
2313 // Legally, without causing looping?
2314 bool Legal = !ProgressRequired || NewGaps < NumGaps;
2315
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002316 if (Legal && MaxGap < huge_valf) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002317 // Estimate the new spill weight. Each instruction reads or writes the
2318 // register. Conservatively assume there are no read-modify-write
2319 // instructions.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002320 //
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002321 // Try to guess the size of the new interval.
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +00002322 const float EstWeight = normalizeSpillWeight(
2323 blockFreq * (NewGaps + 1),
2324 Uses[SplitBefore].distance(Uses[SplitAfter]) +
2325 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
2326 1);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002327 // Would this split be possible to allocate?
2328 // Never allocate all gaps, we wouldn't be making progress.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002329 LLVM_DEBUG(dbgs() << " w=" << EstWeight);
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00002330 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002331 Shrink = false;
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00002332 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002333 if (Diff > BestDiff) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002334 LLVM_DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00002335 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002336 BestBefore = SplitBefore;
2337 BestAfter = SplitAfter;
2338 }
2339 }
2340 }
2341
2342 // Try to shrink.
2343 if (Shrink) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002344 if (++SplitBefore < SplitAfter) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002345 LLVM_DEBUG(dbgs() << " shrink\n");
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002346 // Recompute the max when necessary.
2347 if (GapWeight[SplitBefore - 1] >= MaxGap) {
2348 MaxGap = GapWeight[SplitBefore];
2349 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
2350 MaxGap = std::max(MaxGap, GapWeight[i]);
2351 }
2352 continue;
2353 }
2354 MaxGap = 0;
2355 }
2356
2357 // Try to extend the interval.
2358 if (SplitAfter >= NumGaps) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002359 LLVM_DEBUG(dbgs() << " end\n");
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002360 break;
2361 }
2362
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002363 LLVM_DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002364 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002365 }
2366 }
2367
2368 // Didn't find any candidates?
2369 if (BestBefore == NumGaps)
2370 return 0;
2371
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002372 LLVM_DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore] << '-'
2373 << Uses[BestAfter] << ", " << BestDiff << ", "
2374 << (BestAfter - BestBefore + 1) << " instrs\n");
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002375
Wei Mi9a16d652016-04-13 03:08:27 +00002376 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00002377 SE->reset(LREdit);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002378
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00002379 SE->openIntv();
2380 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
2381 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
2382 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002383 SmallVector<unsigned, 8> IntvMap;
2384 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00002385 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002386
2387 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002388 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002389 // leave the new intervals as RS_New so they can compete.
2390 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
2391 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
2392 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
2393 if (NewGaps >= NumGaps) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002394 LLVM_DEBUG(dbgs() << "Tagging non-progress ranges: ");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002395 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002396 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
2397 if (IntvMap[i] == 1) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00002398 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002399 LLVM_DEBUG(dbgs() << printReg(LREdit.get(i)));
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002400 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002401 LLVM_DEBUG(dbgs() << '\n');
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002402 }
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00002403 ++NumLocalSplits;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002404
2405 return 0;
2406}
2407
2408//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002409// Live Range Splitting
2410//===----------------------------------------------------------------------===//
2411
2412/// trySplit - Try to split VirtReg or one of its interferences, making it
2413/// assignable.
2414/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
2415unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002416 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesend4bb1d42011-08-05 23:50:33 +00002417 // Ranges must be Split2 or less.
2418 if (getStage(VirtReg) >= RS_Spill)
2419 return 0;
2420
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002421 // Local intervals are handled separately.
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00002422 if (LIS->intervalIsInOneMBB(VirtReg)) {
Matthias Braun9f15a792016-11-18 19:43:18 +00002423 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
2424 TimerGroupDescription, TimePassesIsEnabled);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002425 SA->analyze(&VirtReg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002426 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
2427 if (PhysReg || !NewVRegs.empty())
2428 return PhysReg;
2429 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00002430 }
2431
Matthias Braun9f15a792016-11-18 19:43:18 +00002432 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
2433 TimerGroupDescription, TimePassesIsEnabled);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002434
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002435 SA->analyze(&VirtReg);
2436
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00002437 // FIXME: SplitAnalysis may repair broken live ranges coming from the
2438 // coalescer. That may cause the range to become allocatable which means that
2439 // tryRegionSplit won't be making progress. This check should be replaced with
2440 // an assertion when the coalescer is fixed.
2441 if (SA->didRepairRange()) {
2442 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002443 Matrix->invalidateVirtRegs();
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00002444 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
2445 return PhysReg;
2446 }
2447
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002448 // First try to split around a region spanning multiple blocks. RS_Split2
2449 // ranges already made dubious progress with region splitting, so they go
2450 // straight to single block splitting.
2451 if (getStage(VirtReg) < RS_Split2) {
2452 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2453 if (PhysReg || !NewVRegs.empty())
2454 return PhysReg;
2455 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002456
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00002457 // Then isolate blocks.
2458 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002459}
2460
Quentin Colombet87769712014-02-05 22:13:59 +00002461//===----------------------------------------------------------------------===//
2462// Last Chance Recoloring
2463//===----------------------------------------------------------------------===//
2464
Mikael Holmen07f1e2e2017-09-28 08:22:35 +00002465/// Return true if \p reg has any tied def operand.
2466static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg) {
2467 for (const MachineOperand &MO : MRI->def_operands(reg))
2468 if (MO.isTied())
2469 return true;
2470
2471 return false;
2472}
2473
Quentin Colombet87769712014-02-05 22:13:59 +00002474/// mayRecolorAllInterferences - Check if the virtual registers that
2475/// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
2476/// recolored to free \p PhysReg.
2477/// When true is returned, \p RecoloringCandidates has been augmented with all
2478/// the live intervals that need to be recolored in order to free \p PhysReg
2479/// for \p VirtReg.
2480/// \p FixedRegisters contains all the virtual registers that cannot be
2481/// recolored.
2482bool
2483RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
2484 SmallLISet &RecoloringCandidates,
2485 const SmallVirtRegSet &FixedRegisters) {
2486 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
2487
2488 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2489 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
2490 // If there is LastChanceRecoloringMaxInterference or more interferences,
2491 // chances are one would not be recolorable.
2492 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
Quentin Colombet567e30b2014-04-11 21:39:44 +00002493 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002494 LLVM_DEBUG(dbgs() << "Early abort: too many interferences.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002495 CutOffInfo |= CO_Interf;
Quentin Colombet87769712014-02-05 22:13:59 +00002496 return false;
2497 }
2498 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
2499 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
2500 // If Intf is done and sit on the same register class as VirtReg,
2501 // it would not be recolorable as it is in the same state as VirtReg.
Mikael Holmen07f1e2e2017-09-28 08:22:35 +00002502 // However, if VirtReg has tied defs and Intf doesn't, then
2503 // there is still a point in examining if it can be recolorable.
2504 if (((getStage(*Intf) == RS_Done &&
2505 MRI->getRegClass(Intf->reg) == CurRC) &&
2506 !(hasTiedDef(MRI, VirtReg.reg) && !hasTiedDef(MRI, Intf->reg))) ||
Quentin Colombet87769712014-02-05 22:13:59 +00002507 FixedRegisters.count(Intf->reg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002508 LLVM_DEBUG(
2509 dbgs() << "Early abort: the interference is not recolorable.\n");
Quentin Colombet87769712014-02-05 22:13:59 +00002510 return false;
2511 }
2512 RecoloringCandidates.insert(Intf);
2513 }
2514 }
2515 return true;
2516}
2517
2518/// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
2519/// its interferences.
2520/// Last chance recoloring chooses a color for \p VirtReg and recolors every
2521/// virtual register that was using it. The recoloring process may recursively
2522/// use the last chance recoloring. Therefore, when a virtual register has been
2523/// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
2524/// be last-chance-recolored again during this recoloring "session".
2525/// E.g.,
2526/// Let
2527/// vA can use {R1, R2 }
2528/// vB can use { R2, R3}
2529/// vC can use {R1 }
2530/// Where vA, vB, and vC cannot be split anymore (they are reloads for
2531/// instance) and they all interfere.
2532///
2533/// vA is assigned R1
2534/// vB is assigned R2
2535/// vC tries to evict vA but vA is already done.
2536/// Regular register allocation fails.
2537///
2538/// Last chance recoloring kicks in:
2539/// vC does as if vA was evicted => vC uses R1.
2540/// vC is marked as fixed.
2541/// vA needs to find a color.
2542/// None are available.
2543/// vA cannot evict vC: vC is a fixed virtual register now.
2544/// vA does as if vB was evicted => vA uses R2.
2545/// vB needs to find a color.
2546/// R3 is available.
2547/// Recoloring => vC = R1, vA = R2, vB = R3
2548///
Alp Toker70b36992014-02-25 04:21:15 +00002549/// \p Order defines the preferred allocation order for \p VirtReg.
Quentin Colombet87769712014-02-05 22:13:59 +00002550/// \p NewRegs will contain any new virtual register that have been created
2551/// (split, spill) during the process and that must be assigned.
2552/// \p FixedRegisters contains all the virtual registers that cannot be
2553/// recolored.
2554/// \p Depth gives the current depth of the last chance recoloring.
2555/// \return a physical register that can be used for VirtReg or ~0u if none
2556/// exists.
2557unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2558 AllocationOrder &Order,
2559 SmallVectorImpl<unsigned> &NewVRegs,
2560 SmallVirtRegSet &FixedRegisters,
2561 unsigned Depth) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002562 LLVM_DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
Quentin Colombet87769712014-02-05 22:13:59 +00002563 // Ranges must be Done.
Quentin Colombet0e3b5e02014-02-13 05:17:37 +00002564 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
Quentin Colombet87769712014-02-05 22:13:59 +00002565 "Last chance recoloring should really be last chance");
2566 // Set the max depth to LastChanceRecoloringMaxDepth.
2567 // We may want to reconsider that if we end up with a too large search space
2568 // for target with hundreds of registers.
2569 // Indeed, in that case we may want to cut the search space earlier.
Quentin Colombet567e30b2014-04-11 21:39:44 +00002570 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002571 LLVM_DEBUG(dbgs() << "Abort because max depth has been reached.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002572 CutOffInfo |= CO_Depth;
Quentin Colombet87769712014-02-05 22:13:59 +00002573 return ~0u;
2574 }
2575
2576 // Set of Live intervals that will need to be recolored.
2577 SmallLISet RecoloringCandidates;
2578 // Record the original mapping virtual register to physical register in case
2579 // the recoloring fails.
2580 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
2581 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2582 // this recoloring "session".
2583 FixedRegisters.insert(VirtReg.reg);
Quentin Colombet318582f2016-09-16 22:00:50 +00002584 SmallVector<unsigned, 4> CurrentNewVRegs;
Quentin Colombet87769712014-02-05 22:13:59 +00002585
2586 Order.rewind();
2587 while (unsigned PhysReg = Order.next()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002588 LLVM_DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2589 << printReg(PhysReg, TRI) << '\n');
Quentin Colombet87769712014-02-05 22:13:59 +00002590 RecoloringCandidates.clear();
2591 VirtRegToPhysReg.clear();
Quentin Colombet318582f2016-09-16 22:00:50 +00002592 CurrentNewVRegs.clear();
Quentin Colombet87769712014-02-05 22:13:59 +00002593
2594 // It is only possible to recolor virtual register interference.
2595 if (Matrix->checkInterference(VirtReg, PhysReg) >
2596 LiveRegMatrix::IK_VirtReg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002597 LLVM_DEBUG(
2598 dbgs() << "Some interferences are not with virtual registers.\n");
Quentin Colombet87769712014-02-05 22:13:59 +00002599
2600 continue;
2601 }
2602
2603 // Early give up on this PhysReg if it is obvious we cannot recolor all
2604 // the interferences.
2605 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2606 FixedRegisters)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002607 LLVM_DEBUG(dbgs() << "Some interferences cannot be recolored.\n");
Quentin Colombet87769712014-02-05 22:13:59 +00002608 continue;
2609 }
2610
2611 // RecoloringCandidates contains all the virtual registers that interfer
2612 // with VirtReg on PhysReg (or one of its aliases).
2613 // Enqueue them for recoloring and perform the actual recoloring.
2614 PQueue RecoloringQueue;
2615 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2616 EndIt = RecoloringCandidates.end();
2617 It != EndIt; ++It) {
2618 unsigned ItVirtReg = (*It)->reg;
2619 enqueue(RecoloringQueue, *It);
2620 assert(VRM->hasPhys(ItVirtReg) &&
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002621 "Interferences are supposed to be with allocated variables");
Quentin Colombet87769712014-02-05 22:13:59 +00002622
2623 // Record the current allocation.
2624 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2625 // unset the related struct.
2626 Matrix->unassign(**It);
2627 }
2628
2629 // Do as if VirtReg was assigned to PhysReg so that the underlying
2630 // recoloring has the right information about the interferes and
2631 // available colors.
2632 Matrix->assign(VirtReg, PhysReg);
2633
2634 // Save the current recoloring state.
2635 // If we cannot recolor all the interferences, we will have to start again
2636 // at this point for the next physical register.
2637 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
Quentin Colombet318582f2016-09-16 22:00:50 +00002638 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2639 FixedRegisters, Depth)) {
2640 // Push the queued vregs into the main queue.
2641 for (unsigned NewVReg : CurrentNewVRegs)
2642 NewVRegs.push_back(NewVReg);
Quentin Colombet87769712014-02-05 22:13:59 +00002643 // Do not mess up with the global assignment process.
2644 // I.e., VirtReg must be unassigned.
2645 Matrix->unassign(VirtReg);
2646 return PhysReg;
2647 }
2648
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002649 LLVM_DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2650 << printReg(PhysReg, TRI) << '\n');
Quentin Colombet87769712014-02-05 22:13:59 +00002651
2652 // The recoloring attempt failed, undo the changes.
2653 FixedRegisters = SaveFixedRegisters;
2654 Matrix->unassign(VirtReg);
2655
Wei Mib5cf9e52016-11-08 18:19:36 +00002656 // For a newly created vreg which is also in RecoloringCandidates,
2657 // don't add it to NewVRegs because its physical register will be restored
2658 // below. Other vregs in CurrentNewVRegs are created by calling
2659 // selectOrSplit and should be added into NewVRegs.
Quentin Colombet318582f2016-09-16 22:00:50 +00002660 for (SmallVectorImpl<unsigned>::iterator Next = CurrentNewVRegs.begin(),
2661 End = CurrentNewVRegs.end();
2662 Next != End; ++Next) {
Wei Mib5cf9e52016-11-08 18:19:36 +00002663 if (RecoloringCandidates.count(&LIS->getInterval(*Next)))
Quentin Colombet318582f2016-09-16 22:00:50 +00002664 continue;
2665 NewVRegs.push_back(*Next);
2666 }
2667
Quentin Colombet87769712014-02-05 22:13:59 +00002668 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2669 EndIt = RecoloringCandidates.end();
2670 It != EndIt; ++It) {
2671 unsigned ItVirtReg = (*It)->reg;
2672 if (VRM->hasPhys(ItVirtReg))
2673 Matrix->unassign(**It);
Matthias Braun953393a2015-07-14 17:38:17 +00002674 unsigned ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2675 Matrix->assign(**It, ItPhysReg);
Quentin Colombet87769712014-02-05 22:13:59 +00002676 }
2677 }
2678
2679 // Last chance recoloring did not worked either, give up.
2680 return ~0u;
2681}
2682
2683/// tryRecoloringCandidates - Try to assign a new color to every register
2684/// in \RecoloringQueue.
2685/// \p NewRegs will contain any new virtual register created during the
2686/// recoloring process.
2687/// \p FixedRegisters[in/out] contains all the registers that have been
2688/// recolored.
2689/// \return true if all virtual registers in RecoloringQueue were successfully
2690/// recolored, false otherwise.
2691bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2692 SmallVectorImpl<unsigned> &NewVRegs,
2693 SmallVirtRegSet &FixedRegisters,
2694 unsigned Depth) {
2695 while (!RecoloringQueue.empty()) {
2696 LiveInterval *LI = dequeue(RecoloringQueue);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002697 LLVM_DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
Quentin Colombet87769712014-02-05 22:13:59 +00002698 unsigned PhysReg;
2699 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
Quentin Colombet52ffa672016-10-13 19:27:48 +00002700 // When splitting happens, the live-range may actually be empty.
2701 // In that case, this is okay to continue the recoloring even
2702 // if we did not find an alternative color for it. Indeed,
2703 // there will not be anything to color for LI in the end.
2704 if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
Quentin Colombet87769712014-02-05 22:13:59 +00002705 return false;
Quentin Colombet52ffa672016-10-13 19:27:48 +00002706
2707 if (!PhysReg) {
2708 assert(LI->empty() && "Only empty live-range do not require a register");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002709 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2710 << " succeeded. Empty LI.\n");
Quentin Colombet52ffa672016-10-13 19:27:48 +00002711 continue;
2712 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002713 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2714 << " succeeded with: " << printReg(PhysReg, TRI) << '\n');
Quentin Colombet52ffa672016-10-13 19:27:48 +00002715
Quentin Colombet87769712014-02-05 22:13:59 +00002716 Matrix->assign(*LI, PhysReg);
2717 FixedRegisters.insert(LI->reg);
2718 }
2719 return true;
2720}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002721
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002722//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002723// Main Entry Point
2724//===----------------------------------------------------------------------===//
2725
2726unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002727 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002728 CutOffInfo = CO_None;
Matthias Braunf1caa282017-12-15 22:22:58 +00002729 LLVMContext &Ctx = MF->getFunction().getContext();
Quentin Colombet87769712014-02-05 22:13:59 +00002730 SmallVirtRegSet FixedRegisters;
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002731 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2732 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2733 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2734 if (CutOffEncountered == CO_Depth)
Quentin Colombet567e30b2014-04-11 21:39:44 +00002735 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2736 "reached. Use -fexhaustive-register-search to skip "
2737 "cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002738 else if (CutOffEncountered == CO_Interf)
2739 Ctx.emitError("register allocation failed: maximum interference for "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002740 "recoloring reached. Use -fexhaustive-register-search "
2741 "to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002742 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2743 Ctx.emitError("register allocation failed: maximum interference and "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002744 "depth for recoloring reached. Use "
2745 "-fexhaustive-register-search to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002746 }
2747 return Reg;
Quentin Colombet87769712014-02-05 22:13:59 +00002748}
2749
Manman Ren9dee4492014-03-27 21:21:57 +00002750/// Using a CSR for the first time has a cost because it causes push|pop
2751/// to be added to prologue|epilogue. Splitting a cold section of the live
2752/// range can have lower cost than using the CSR for the first time;
2753/// Spilling a live range in the cold path can have lower cost than using
2754/// the CSR for the first time. Returns the physical register if we decide
2755/// to use the CSR; otherwise return 0.
2756unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2757 AllocationOrder &Order,
2758 unsigned PhysReg,
2759 unsigned &CostPerUseLimit,
2760 SmallVectorImpl<unsigned> &NewVRegs) {
Manman Ren9dee4492014-03-27 21:21:57 +00002761 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2762 // We choose spill over using the CSR for the first time if the spill cost
2763 // is lower than CSRCost.
2764 SA->analyze(&VirtReg);
2765 if (calcSpillCost() >= CSRCost)
2766 return PhysReg;
2767
2768 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2769 // we will not use a callee-saved register in tryEvict.
2770 CostPerUseLimit = 1;
2771 return 0;
2772 }
2773 if (getStage(VirtReg) < RS_Split) {
2774 // We choose pre-splitting over using the CSR for the first time if
2775 // the cost of splitting is lower than CSRCost.
2776 SA->analyze(&VirtReg);
2777 unsigned NumCands = 0;
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002778 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2779 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2780 NumCands, true /*IgnoreCSR*/);
Manman Ren9dee4492014-03-27 21:21:57 +00002781 if (BestCand == NoCand)
2782 // Use the CSR if we can't find a region split below CSRCost.
2783 return PhysReg;
2784
2785 // Perform the actual pre-splitting.
2786 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2787 return 0;
2788 }
2789 return PhysReg;
2790}
2791
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002792void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
2793 // Do not keep invalid information around.
2794 SetOfBrokenHints.remove(&LI);
2795}
2796
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002797void RAGreedy::initializeCSRCost() {
2798 // We use the larger one out of the command-line option and the value report
2799 // by TRI.
2800 CSRCost = BlockFrequency(
2801 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2802 if (!CSRCost.getFrequency())
2803 return;
2804
2805 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2806 uint64_t ActualEntry = MBFI->getEntryFreq();
2807 if (!ActualEntry) {
2808 CSRCost = 0;
2809 return;
2810 }
2811 uint64_t FixedEntry = 1 << 14;
2812 if (ActualEntry < FixedEntry)
2813 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2814 else if (ActualEntry <= UINT32_MAX)
2815 // Invert the fraction and divide.
2816 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2817 else
2818 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2819 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2820}
2821
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002822/// Collect the hint info for \p Reg.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002823/// The results are stored into \p Out.
2824/// \p Out is not cleared before being populated.
2825void RAGreedy::collectHintInfo(unsigned Reg, HintsInfo &Out) {
2826 for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2827 if (!Instr.isFullCopy())
2828 continue;
2829 // Look for the other end of the copy.
2830 unsigned OtherReg = Instr.getOperand(0).getReg();
2831 if (OtherReg == Reg) {
2832 OtherReg = Instr.getOperand(1).getReg();
2833 if (OtherReg == Reg)
2834 continue;
2835 }
2836 // Get the current assignment.
2837 unsigned OtherPhysReg = TargetRegisterInfo::isPhysicalRegister(OtherReg)
2838 ? OtherReg
2839 : VRM->getPhys(OtherReg);
2840 // Push the collected information.
2841 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2842 OtherPhysReg));
2843 }
2844}
2845
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002846/// Using the given \p List, compute the cost of the broken hints if
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002847/// \p PhysReg was used.
2848/// \return The cost of \p List for \p PhysReg.
2849BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2850 unsigned PhysReg) {
2851 BlockFrequency Cost = 0;
2852 for (const HintInfo &Info : List) {
2853 if (Info.PhysReg != PhysReg)
2854 Cost += Info.Freq;
2855 }
2856 return Cost;
2857}
2858
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002859/// Using the register assigned to \p VirtReg, try to recolor
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002860/// all the live ranges that are copy-related with \p VirtReg.
2861/// The recoloring is then propagated to all the live-ranges that have
2862/// been recolored and so on, until no more copies can be coalesced or
2863/// it is not profitable.
2864/// For a given live range, profitability is determined by the sum of the
2865/// frequencies of the non-identity copies it would introduce with the old
2866/// and new register.
2867void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
2868 // We have a broken hint, check if it is possible to fix it by
2869 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2870 // some register and PhysReg may be available for the other live-ranges.
2871 SmallSet<unsigned, 4> Visited;
2872 SmallVector<unsigned, 2> RecoloringCandidates;
2873 HintsInfo Info;
2874 unsigned Reg = VirtReg.reg;
2875 unsigned PhysReg = VRM->getPhys(Reg);
2876 // Start the recoloring algorithm from the input live-interval, then
2877 // it will propagate to the ones that are copy-related with it.
2878 Visited.insert(Reg);
2879 RecoloringCandidates.push_back(Reg);
2880
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002881 LLVM_DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI)
2882 << '(' << printReg(PhysReg, TRI) << ")\n");
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002883
2884 do {
2885 Reg = RecoloringCandidates.pop_back_val();
2886
Hiroshi Inouea86c9202017-07-10 12:44:25 +00002887 // We cannot recolor physical register.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002888 if (TargetRegisterInfo::isPhysicalRegister(Reg))
2889 continue;
2890
2891 assert(VRM->hasPhys(Reg) && "We have unallocated variable!!");
2892
2893 // Get the live interval mapped with this virtual register to be able
2894 // to check for the interference with the new color.
2895 LiveInterval &LI = LIS->getInterval(Reg);
2896 unsigned CurrPhys = VRM->getPhys(Reg);
2897 // Check that the new color matches the register class constraints and
2898 // that it is free for this live range.
2899 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2900 Matrix->checkInterference(LI, PhysReg)))
2901 continue;
2902
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002903 LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI)
2904 << ") is recolorable.\n");
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002905
2906 // Gather the hint info.
2907 Info.clear();
2908 collectHintInfo(Reg, Info);
2909 // Check if recoloring the live-range will increase the cost of the
2910 // non-identity copies.
2911 if (CurrPhys != PhysReg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002912 LLVM_DEBUG(dbgs() << "Checking profitability:\n");
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002913 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2914 BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002915 LLVM_DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2916 << "\nNew Cost: " << NewCopiesCost.getFrequency()
2917 << '\n');
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002918 if (OldCopiesCost < NewCopiesCost) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002919 LLVM_DEBUG(dbgs() << "=> Not profitable.\n");
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002920 continue;
2921 }
2922 // At this point, the cost is either cheaper or equal. If it is
2923 // equal, we consider this is profitable because it may expose
2924 // more recoloring opportunities.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002925 LLVM_DEBUG(dbgs() << "=> Profitable.\n");
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002926 // Recolor the live-range.
2927 Matrix->unassign(LI);
2928 Matrix->assign(LI, PhysReg);
2929 }
2930 // Push all copy-related live-ranges to keep reconciling the broken
2931 // hints.
2932 for (const HintInfo &HI : Info) {
2933 if (Visited.insert(HI.Reg).second)
2934 RecoloringCandidates.push_back(HI.Reg);
2935 }
2936 } while (!RecoloringCandidates.empty());
2937}
2938
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002939/// Try to recolor broken hints.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002940/// Broken hints may be repaired by recoloring when an evicted variable
2941/// freed up a register for a larger live-range.
2942/// Consider the following example:
2943/// BB1:
2944/// a =
2945/// b =
2946/// BB2:
2947/// ...
2948/// = b
2949/// = a
2950/// Let us assume b gets split:
2951/// BB1:
2952/// a =
2953/// b =
2954/// BB2:
2955/// c = b
2956/// ...
2957/// d = c
2958/// = d
2959/// = a
2960/// Because of how the allocation work, b, c, and d may be assigned different
2961/// colors. Now, if a gets evicted later:
2962/// BB1:
2963/// a =
2964/// st a, SpillSlot
2965/// b =
2966/// BB2:
2967/// c = b
2968/// ...
2969/// d = c
2970/// = d
2971/// e = ld SpillSlot
2972/// = e
2973/// This is likely that we can assign the same register for b, c, and d,
2974/// getting rid of 2 copies.
2975void RAGreedy::tryHintsRecoloring() {
2976 for (LiveInterval *LI : SetOfBrokenHints) {
2977 assert(TargetRegisterInfo::isVirtualRegister(LI->reg) &&
2978 "Recoloring is possible only for virtual registers");
2979 // Some dead defs may be around (e.g., because of debug uses).
2980 // Ignore those.
2981 if (!VRM->hasPhys(LI->reg))
2982 continue;
2983 tryHintRecoloring(*LI);
2984 }
2985}
2986
Quentin Colombet87769712014-02-05 22:13:59 +00002987unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2988 SmallVectorImpl<unsigned> &NewVRegs,
2989 SmallVirtRegSet &FixedRegisters,
2990 unsigned Depth) {
Manman Ren78cf02a2014-03-25 00:16:25 +00002991 unsigned CostPerUseLimit = ~0u;
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002992 // First try assigning a free register.
Matthias Braun5d1f12d2015-07-15 22:16:00 +00002993 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
Manman Ren78cf02a2014-03-25 00:16:25 +00002994 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
Marina Yatsinaf9371d82017-10-22 17:59:38 +00002995 // If VirtReg got an assignment, the eviction info is no longre relevant.
2996 LastEvicted.clearEvicteeInfo(VirtReg.reg);
Manman Ren9dee4492014-03-27 21:21:57 +00002997 // When NewVRegs is not empty, we may have made decisions such as evicting
2998 // a virtual register, go with the earlier decisions and use the physical
2999 // register.
Matthias Braun953393a2015-07-14 17:38:17 +00003000 if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
3001 NewVRegs.empty()) {
Manman Ren9dee4492014-03-27 21:21:57 +00003002 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
3003 CostPerUseLimit, NewVRegs);
3004 if (CSRReg || !NewVRegs.empty())
3005 // Return now if we decide to use a CSR or create new vregs due to
3006 // pre-splitting.
3007 return CSRReg;
Manman Ren78cf02a2014-03-25 00:16:25 +00003008 } else
3009 return PhysReg;
3010 }
Andrew Trickccef0982010-12-09 18:15:21 +00003011
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00003012 LiveRangeStage Stage = getStage(VirtReg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003013 LLVM_DEBUG(dbgs() << StageName[Stage] << " Cascade "
3014 << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00003015
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00003016 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00003017 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00003018 // get a second chance until they have been split.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00003019 if (Stage != RS_Split)
Quentin Colombeta799e2e2015-01-08 01:16:39 +00003020 if (unsigned PhysReg =
3021 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit)) {
3022 unsigned Hint = MRI->getSimpleHint(VirtReg.reg);
3023 // If VirtReg has a hint and that hint is broken record this
3024 // virtual register as a recoloring candidate for broken hint.
3025 // Indeed, since we evicted a variable in its neighborhood it is
3026 // likely we can at least partially recolor some of the
3027 // copy-related live-ranges.
3028 if (Hint && Hint != PhysReg)
3029 SetOfBrokenHints.insert(&VirtReg);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003030 // If VirtReg eviction someone, the eviction info for it as an evictee is
3031 // no longre relevant.
3032 LastEvicted.clearEvicteeInfo(VirtReg.reg);
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00003033 return PhysReg;
Quentin Colombeta799e2e2015-01-08 01:16:39 +00003034 }
Andrew Trickccef0982010-12-09 18:15:21 +00003035
Quentin Colombet63176862016-09-16 22:00:42 +00003036 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00003037
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00003038 // The first time we see a live range, don't try to split or spill.
3039 // Wait until the second time, when all smaller ranges have been allocated.
3040 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00003041 if (Stage < RS_Split) {
3042 setStage(VirtReg, RS_Split);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003043 LLVM_DEBUG(dbgs() << "wait for second round\n");
Mark Laceyf9ea8852013-08-14 23:50:04 +00003044 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00003045 return 0;
3046 }
3047
Dylan McKayc328fe52016-10-11 01:04:36 +00003048 if (Stage < RS_Spill) {
3049 // Try splitting VirtReg or interferences.
3050 unsigned NewVRegSizeBefore = NewVRegs.size();
3051 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003052 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore)) {
3053 // If VirtReg got split, the eviction info is no longre relevant.
3054 LastEvicted.clearEvicteeInfo(VirtReg.reg);
Dylan McKayc328fe52016-10-11 01:04:36 +00003055 return PhysReg;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003056 }
Dylan McKayc328fe52016-10-11 01:04:36 +00003057 }
3058
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00003059 // If we couldn't allocate a register from spilling, there is probably some
Hiroshi Inoueff8453d2017-06-29 18:03:28 +00003060 // invalid inline assembly. The base class will report it.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00003061 if (Stage >= RS_Done || !VirtReg.isSpillable())
Quentin Colombet87769712014-02-05 22:13:59 +00003062 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
3063 Depth);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00003064
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00003065 // Finally spill VirtReg itself.
Quentin Colombet11922942015-07-17 23:04:06 +00003066 if (EnableDeferredSpilling && getStage(VirtReg) < RS_Memory) {
3067 // TODO: This is experimental and in particular, we do not model
3068 // the live range splitting done by spilling correctly.
3069 // We would need a deep integration with the spiller to do the
3070 // right thing here. Anyway, that is still good for early testing.
3071 setStage(VirtReg, RS_Memory);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003072 LLVM_DEBUG(dbgs() << "Do as if this register is in memory\n");
Quentin Colombet11922942015-07-17 23:04:06 +00003073 NewVRegs.push_back(VirtReg.reg);
3074 } else {
Matthias Braun9f15a792016-11-18 19:43:18 +00003075 NamedRegionTimer T("spill", "Spiller", TimerGroupName,
3076 TimerGroupDescription, TimePassesIsEnabled);
Wei Mi9a16d652016-04-13 03:08:27 +00003077 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Quentin Colombet11922942015-07-17 23:04:06 +00003078 spiller().spill(LRE);
3079 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003080
Quentin Colombet11922942015-07-17 23:04:06 +00003081 if (VerifyEnabled)
3082 MF->verify(this, "After spilling");
3083 }
Jakob Stoklund Olesen557a82c2011-03-16 22:56:08 +00003084
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003085 // The live virtual register requesting allocation was spilled, so tell
3086 // the caller not to allocate anything during this round.
3087 return 0;
3088}
3089
Adam Nemeta9640662017-01-25 23:20:33 +00003090void RAGreedy::reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
3091 unsigned &FoldedReloads,
3092 unsigned &Spills,
3093 unsigned &FoldedSpills) {
3094 Reloads = 0;
3095 FoldedReloads = 0;
3096 Spills = 0;
3097 FoldedSpills = 0;
3098
3099 // Sum up the spill and reloads in subloops.
3100 for (MachineLoop *SubLoop : *L) {
3101 unsigned SubReloads;
3102 unsigned SubFoldedReloads;
3103 unsigned SubSpills;
3104 unsigned SubFoldedSpills;
3105
3106 reportNumberOfSplillsReloads(SubLoop, SubReloads, SubFoldedReloads,
3107 SubSpills, SubFoldedSpills);
3108 Reloads += SubReloads;
3109 FoldedReloads += SubFoldedReloads;
3110 Spills += SubSpills;
3111 FoldedSpills += SubFoldedSpills;
3112 }
3113
3114 const MachineFrameInfo &MFI = MF->getFrameInfo();
3115 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
3116 int FI;
3117
3118 for (MachineBasicBlock *MBB : L->getBlocks())
3119 // Handle blocks that were not included in subloops.
3120 if (Loops->getLoopFor(MBB) == L)
3121 for (MachineInstr &MI : *MBB) {
3122 const MachineMemOperand *MMO;
3123
3124 if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI))
3125 ++Reloads;
3126 else if (TII->hasLoadFromStackSlot(MI, MMO, FI) &&
3127 MFI.isSpillSlotObjectIndex(FI))
3128 ++FoldedReloads;
3129 else if (TII->isStoreToStackSlot(MI, FI) &&
3130 MFI.isSpillSlotObjectIndex(FI))
3131 ++Spills;
3132 else if (TII->hasStoreToStackSlot(MI, MMO, FI) &&
3133 MFI.isSpillSlotObjectIndex(FI))
3134 ++FoldedSpills;
3135 }
3136
3137 if (Reloads || FoldedReloads || Spills || FoldedSpills) {
3138 using namespace ore;
Eugene Zelenkofb69e662017-06-06 22:22:41 +00003139
Vivek Pandya95906582017-10-11 17:12:59 +00003140 ORE->emit([&]() {
3141 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReload",
3142 L->getStartLoc(), L->getHeader());
3143 if (Spills)
3144 R << NV("NumSpills", Spills) << " spills ";
3145 if (FoldedSpills)
3146 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
3147 if (Reloads)
3148 R << NV("NumReloads", Reloads) << " reloads ";
3149 if (FoldedReloads)
3150 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
3151 R << "generated in loop";
3152 return R;
3153 });
Adam Nemeta9640662017-01-25 23:20:33 +00003154 }
3155}
3156
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003157bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003158 LLVM_DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
3159 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003160
3161 MF = &mf;
Eric Christopher60621802014-10-14 07:22:00 +00003162 TRI = MF->getSubtarget().getRegisterInfo();
3163 TII = MF->getSubtarget().getInstrInfo();
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00003164 RCI.runOnMachineFunction(mf);
Quentin Colombet5caa6a22014-07-02 18:32:04 +00003165
3166 EnableLocalReassign = EnableLocalReassignment ||
Eric Christopher60621802014-10-14 07:22:00 +00003167 MF->getSubtarget().enableRALocalReassignment(
3168 MF->getTarget().getOptLevel());
Quentin Colombet5caa6a22014-07-02 18:32:04 +00003169
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003170 EnableAdvancedRASplitCost = ConsiderLocalIntervalCost ||
3171 MF->getSubtarget().enableAdvancedRASplitCost();
3172
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00003173 if (VerifyEnabled)
Jakob Stoklund Olesenbf4550e2010-12-18 00:06:56 +00003174 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00003175
Jakob Stoklund Olesen2d2dec92012-06-20 22:52:29 +00003176 RegAllocBase::init(getAnalysis<VirtRegMap>(),
3177 getAnalysis<LiveIntervals>(),
3178 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00003179 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +00003180 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +00003181 DomTree = &getAnalysis<MachineDominatorTree>();
Adam Nemeta9640662017-01-25 23:20:33 +00003182 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
Jakob Stoklund Olesenadecb5e2010-12-10 22:54:44 +00003183 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00003184 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00003185 Bundles = &getAnalysis<EdgeBundles>();
3186 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00003187 DebugVars = &getAnalysis<LiveDebugVariables>();
Wei Mic0223702016-07-08 21:08:09 +00003188 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00003189
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00003190 initializeCSRCost();
3191
Robert Lougher11a44b72015-08-10 11:59:44 +00003192 calculateSpillWeightsAndHints(*LIS, mf, VRM, *Loops, *MBFI);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +00003193
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003194 LLVM_DEBUG(LIS->dump());
Andrew Trick97064962013-07-25 07:26:26 +00003195
Jakob Stoklund Olesenf1a60a62011-02-19 00:53:42 +00003196 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Wei Mic0223702016-07-08 21:08:09 +00003197 SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00003198 ExtraRegInfo.clear();
3199 ExtraRegInfo.resize(MRI->getNumVirtRegs());
3200 NextCascade = 1;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00003201 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00003202 GlobalCand.resize(32); // This will grow as needed.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00003203 SetOfBrokenHints.clear();
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003204 LastEvicted.clear();
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00003205
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003206 allocatePhysRegs();
Quentin Colombeta799e2e2015-01-08 01:16:39 +00003207 tryHintsRecoloring();
Wei Mi9a16d652016-04-13 03:08:27 +00003208 postOptimization();
Adam Nemeta9640662017-01-25 23:20:33 +00003209 reportNumberOfSplillsReloads();
Wei Mi9a16d652016-04-13 03:08:27 +00003210
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003211 releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003212 return true;
3213}