blob: 6f0b7a936c55094bb0faf6023a6a6531e56ff853 [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"
26#include "llvm/ADT/SetVector.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SmallVector.h"
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000030#include "llvm/ADT/Statistic.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000031#include "llvm/ADT/StringRef.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000032#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000033#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000034#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000035#include "llvm/CodeGen/EdgeBundles.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000036#include "llvm/CodeGen/LiveInterval.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000037#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000038#include "llvm/CodeGen/LiveIntervalUnion.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000039#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000040#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000041#include "llvm/CodeGen/LiveStackAnalysis.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000042#include "llvm/CodeGen/MachineBasicBlock.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000043#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000044#include "llvm/CodeGen/MachineDominators.h"
Adam Nemeta9640662017-01-25 23:20:33 +000045#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000046#include "llvm/CodeGen/MachineFunction.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000047#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000048#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000049#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000050#include "llvm/CodeGen/MachineOperand.h"
Adam Nemeta9640662017-01-25 23:20:33 +000051#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000052#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000053#include "llvm/CodeGen/RegAllocRegistry.h"
Quentin Colombet1fb3362a2014-01-02 22:47:22 +000054#include "llvm/CodeGen/RegisterClassInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000055#include "llvm/CodeGen/SlotIndexes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/CodeGen/VirtRegMap.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000057#include "llvm/IR/Function.h"
Quentin Colombet96bd2a12014-04-04 02:05:21 +000058#include "llvm/IR/LLVMContext.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000059#include "llvm/MC/MCRegisterInfo.h"
60#include "llvm/Pass.h"
61#include "llvm/Support/BlockFrequency.h"
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +000062#include "llvm/Support/BranchProbability.h"
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +000063#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000064#include "llvm/Support/Debug.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000065#include "llvm/Support/MathExtras.h"
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +000066#include "llvm/Support/Timer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000067#include "llvm/Support/raw_ostream.h"
Wei Mi9a16d652016-04-13 03:08:27 +000068#include "llvm/Target/TargetInstrInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000069#include "llvm/Target/TargetMachine.h"
70#include "llvm/Target/TargetRegisterInfo.h"
Quentin Colombet5caa6a22014-07-02 18:32:04 +000071#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000072#include <algorithm>
73#include <cassert>
74#include <cstdint>
75#include <memory>
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000076#include <queue>
Eugene Zelenkofb69e662017-06-06 22:22:41 +000077#include <tuple>
78#include <utility>
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000079
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000080using namespace llvm;
81
Chandler Carruth1b9dde02014-04-22 02:02:50 +000082#define DEBUG_TYPE "regalloc"
83
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000084STATISTIC(NumGlobalSplits, "Number of split global live ranges");
85STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000086STATISTIC(NumEvicted, "Number of interferences evicted");
87
Wei Mi9a16d652016-04-13 03:08:27 +000088static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
89 "split-spill-mode", cl::Hidden,
90 cl::desc("Spill mode for splitting live ranges"),
91 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
92 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
Mehdi Amini732afdd2016-10-08 19:41:06 +000093 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
Wei Mi9a16d652016-04-13 03:08:27 +000094 cl::init(SplitEditor::SM_Speed));
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +000095
Quentin Colombet87769712014-02-05 22:13:59 +000096static cl::opt<unsigned>
97LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
98 cl::desc("Last chance recoloring max depth"),
99 cl::init(5));
100
101static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
102 "lcr-max-interf", cl::Hidden,
103 cl::desc("Last chance recoloring maximum number of considered"
104 " interference at a time"),
105 cl::init(8));
106
Quentin Colombet567e30b2014-04-11 21:39:44 +0000107static cl::opt<bool>
Quentin Colombet4344da12014-04-11 21:51:09 +0000108ExhaustiveSearch("exhaustive-register-search", cl::NotHidden,
Quentin Colombet567e30b2014-04-11 21:39:44 +0000109 cl::desc("Exhaustive Search for registers bypassing the depth "
110 "and interference cutoffs of last chance recoloring"));
111
Quentin Colombete1a36632014-07-01 14:08:37 +0000112static cl::opt<bool> EnableLocalReassignment(
113 "enable-local-reassign", cl::Hidden,
114 cl::desc("Local reassignment can yield better allocation decisions, but "
115 "may be compile time intensive"),
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000116 cl::init(false));
Quentin Colombete1a36632014-07-01 14:08:37 +0000117
Quentin Colombet11922942015-07-17 23:04:06 +0000118static cl::opt<bool> EnableDeferredSpilling(
119 "enable-deferred-spilling", cl::Hidden,
120 cl::desc("Instead of spilling a variable right away, defer the actual "
121 "code insertion to the end of the allocation. That way the "
122 "allocator might still find a suitable coloring for this "
123 "variable because of other evicted variables."),
124 cl::init(false));
125
Manman Ren78cf02a2014-03-25 00:16:25 +0000126// FIXME: Find a good default for this flag and remove the flag.
127static cl::opt<unsigned>
128CSRFirstTimeCost("regalloc-csr-first-time-cost",
129 cl::desc("Cost for first time use of callee-saved register."),
130 cl::init(0), cl::Hidden);
131
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000132static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
133 createGreedyRegisterAllocator);
134
135namespace {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000136
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000137class RAGreedy : public MachineFunctionPass,
138 public RegAllocBase,
139 private LiveRangeEdit::Delegate {
Quentin Colombet87769712014-02-05 22:13:59 +0000140 // Convenient shortcuts.
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000141 using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
142 using SmallLISet = SmallPtrSet<LiveInterval *, 4>;
143 using SmallVirtRegSet = SmallSet<unsigned, 16>;
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000144
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000145 // context
146 MachineFunction *MF;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000147
Quentin Colombet1fb3362a2014-01-02 22:47:22 +0000148 // Shortcuts to some useful interface.
149 const TargetInstrInfo *TII;
150 const TargetRegisterInfo *TRI;
151 RegisterClassInfo RCI;
152
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000153 // analyses
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000154 SlotIndexes *Indexes;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000155 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000156 MachineDominatorTree *DomTree;
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +0000157 MachineLoopInfo *Loops;
Adam Nemeta9640662017-01-25 23:20:33 +0000158 MachineOptimizationRemarkEmitter *ORE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000159 EdgeBundles *Bundles;
160 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000161 LiveDebugVariables *DebugVars;
Wei Mic0223702016-07-08 21:08:09 +0000162 AliasAnalysis *AA;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000163
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000164 // state
Ahmed Charles56440fd2014-03-06 05:51:42 +0000165 std::unique_ptr<Spiller> SpillerInstance;
Quentin Colombet87769712014-02-05 22:13:59 +0000166 PQueue Queue;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000167 unsigned NextCascade;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000168
169 // Live ranges pass through a number of stages as we try to allocate them.
170 // Some of the stages may also create new live ranges:
171 //
172 // - Region splitting.
173 // - Per-block splitting.
174 // - Local splitting.
175 // - Spilling.
176 //
177 // Ranges produced by one of the stages skip the previous stages when they are
178 // dequeued. This improves performance because we can skip interference checks
179 // that are unlikely to give any results. It also guarantees that the live
180 // range splitting algorithm terminates, something that is otherwise hard to
181 // ensure.
182 enum LiveRangeStage {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000183 /// Newly created live range that has never been queued.
184 RS_New,
185
186 /// Only attempt assignment and eviction. Then requeue as RS_Split.
187 RS_Assign,
188
189 /// Attempt live range splitting if assignment is impossible.
190 RS_Split,
191
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000192 /// Attempt more aggressive live range splitting that is guaranteed to make
193 /// progress. This is used for split products that may not be making
194 /// progress.
195 RS_Split2,
196
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000197 /// Live range will be spilled. No more splitting will be attempted.
198 RS_Spill,
199
Quentin Colombet11922942015-07-17 23:04:06 +0000200
201 /// Live range is in memory. Because of other evictions, it might get moved
202 /// in a register in the end.
203 RS_Memory,
204
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000205 /// There is nothing more we can do to this live range. Abort compilation
206 /// if it can't be assigned.
207 RS_Done
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000208 };
209
Quentin Colombet96bd2a12014-04-04 02:05:21 +0000210 // Enum CutOffStage to keep a track whether the register allocation failed
211 // because of the cutoffs encountered in last chance recoloring.
212 // Note: This is used as bitmask. New value should be next power of 2.
213 enum CutOffStage {
214 // No cutoffs encountered
215 CO_None = 0,
216
217 // lcr-max-depth cutoff encountered
218 CO_Depth = 1,
219
220 // lcr-max-interf cutoff encountered
221 CO_Interf = 2
222 };
223
224 uint8_t CutOffInfo;
225
Eli Friedman78bffa52013-09-10 23:18:14 +0000226#ifndef NDEBUG
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000227 static const char *const StageName[];
Eli Friedman78bffa52013-09-10 23:18:14 +0000228#endif
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000229
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000230 // RegInfo - Keep additional information about each live range.
231 struct RegInfo {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000232 LiveRangeStage Stage = RS_New;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000233
234 // Cascade - Eviction loop prevention. See canEvictInterference().
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000235 unsigned Cascade = 0;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000236
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000237 RegInfo() = default;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000238 };
239
240 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000241
242 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000243 return ExtraRegInfo[VirtReg.reg].Stage;
244 }
245
246 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
247 ExtraRegInfo.resize(MRI->getNumVirtRegs());
248 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000249 }
250
251 template<typename Iterator>
252 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000253 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000254 for (;Begin != End; ++Begin) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000255 unsigned Reg = *Begin;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000256 if (ExtraRegInfo[Reg].Stage == RS_New)
257 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000258 }
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000259 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000260
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000261 /// Cost of evicting interference.
262 struct EvictionCost {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000263 unsigned BrokenHints = 0; ///< Total number of broken hints.
264 float MaxWeight = 0; ///< Maximum spill weight evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000265
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000266 EvictionCost() = default;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000267
Andrew Trick84852572013-07-25 18:35:14 +0000268 bool isMax() const { return BrokenHints == ~0u; }
269
Andrew Trick3621b8a2013-11-22 19:07:38 +0000270 void setMax() { BrokenHints = ~0u; }
271
272 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
273
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000274 bool operator<(const EvictionCost &O) const {
Benjamin Kramerb2f034b2014-03-03 19:58:30 +0000275 return std::tie(BrokenHints, MaxWeight) <
276 std::tie(O.BrokenHints, O.MaxWeight);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000277 }
278 };
279
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000280 // splitting state.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000281 std::unique_ptr<SplitAnalysis> SA;
282 std::unique_ptr<SplitEditor> SE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000283
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000284 /// Cached per-block interference maps
285 InterferenceCache IntfCache;
286
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000287 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000288 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000289
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000290 /// Global live range splitting candidate info.
291 struct GlobalSplitCandidate {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000292 // Register intended for assignment, or 0.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000293 unsigned PhysReg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000294
295 // SplitKit interval index for this candidate.
296 unsigned IntvIdx;
297
298 // Interference for PhysReg.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000299 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000300
301 // Bundles where this candidate should be live.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000302 BitVector LiveBundles;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000303 SmallVector<unsigned, 8> ActiveBlocks;
304
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000305 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000306 PhysReg = Reg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000307 IntvIdx = 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000308 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000309 LiveBundles.clear();
310 ActiveBlocks.clear();
311 }
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000312
313 // Set B[i] = C for every live bundle where B[i] was NoCand.
314 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
315 unsigned Count = 0;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +0000316 for (unsigned i : LiveBundles.set_bits())
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000317 if (B[i] == NoCand) {
318 B[i] = C;
319 Count++;
320 }
321 return Count;
322 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000323 };
324
Aditya Nandakumarc1fd0dd2013-11-19 23:51:32 +0000325 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000326 /// This vector never shrinks, but grows to the size of the largest register
327 /// class.
328 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
329
Alp Toker61007d82014-03-02 03:20:38 +0000330 enum : unsigned { NoCand = ~0u };
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000331
332 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
333 /// NoCand which indicates the stack interval.
334 SmallVector<unsigned, 32> BundleCand;
335
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000336 /// Callee-save register cost, calculated once per machine function.
337 BlockFrequency CSRCost;
338
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000339 /// Run or not the local reassignment heuristic. This information is
340 /// obtained from the TargetSubtargetInfo.
341 bool EnableLocalReassign;
342
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000343 /// Set of broken hints that may be reconciled later because of eviction.
344 SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
345
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000346public:
347 RAGreedy();
348
349 /// Return the pass name.
Mehdi Amini117296c2016-10-01 02:56:57 +0000350 StringRef getPassName() const override { return "Greedy Register Allocator"; }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000351
352 /// RAGreedy analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000353 void getAnalysisUsage(AnalysisUsage &AU) const override;
354 void releaseMemory() override;
355 Spiller &spiller() override { return *SpillerInstance; }
356 void enqueue(LiveInterval *LI) override;
357 LiveInterval *dequeue() override;
358 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000359 void aboutToRemoveInterval(LiveInterval &) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000360
361 /// Perform register allocation.
Craig Topper4584cd52014-03-07 09:26:03 +0000362 bool runOnMachineFunction(MachineFunction &mf) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000363
Matthias Braun90799ce2016-08-23 21:19:49 +0000364 MachineFunctionProperties getRequiredProperties() const override {
365 return MachineFunctionProperties().set(
366 MachineFunctionProperties::Property::NoPHIs);
367 }
368
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000369 static char ID;
Andrew Trickccef0982010-12-09 18:15:21 +0000370
371private:
Quentin Colombet87769712014-02-05 22:13:59 +0000372 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
373 SmallVirtRegSet &, unsigned = 0);
374
Craig Topper4584cd52014-03-07 09:26:03 +0000375 bool LRE_CanEraseVirtReg(unsigned) override;
376 void LRE_WillShrinkVirtReg(unsigned) override;
377 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
Quentin Colombet87769712014-02-05 22:13:59 +0000378 void enqueue(PQueue &CurQueue, LiveInterval *LI);
379 LiveInterval *dequeue(PQueue &CurQueue);
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000380
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000381 BlockFrequency calcSpillCost();
382 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000383 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000384 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000385 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000386 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000387 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000388 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000389 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000390 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
391 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
392 void evictInterference(LiveInterval&, unsigned,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000393 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000394 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
395 SmallLISet &RecoloringCandidates,
396 const SmallVirtRegSet &FixedRegisters);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000397
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000398 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000399 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000400 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000401 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000402 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000403 SmallVectorImpl<unsigned>&);
Manman Ren9db66b32014-03-24 23:23:42 +0000404 /// Calculate cost of region splitting.
405 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
406 AllocationOrder &Order,
407 BlockFrequency &BestCost,
Manman Ren78cf02a2014-03-25 00:16:25 +0000408 unsigned &NumCands, bool IgnoreCSR);
Manman Ren9db66b32014-03-24 23:23:42 +0000409 /// Perform region splitting.
410 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
411 bool HasCompact,
412 SmallVectorImpl<unsigned> &NewVRegs);
Manman Ren9dee4492014-03-27 21:21:57 +0000413 /// Check other options before using a callee-saved register for the first
414 /// time.
415 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
416 unsigned PhysReg, unsigned &CostPerUseLimit,
417 SmallVectorImpl<unsigned> &NewVRegs);
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000418 void initializeCSRCost();
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +0000419 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000420 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +0000421 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000422 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000423 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000424 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000425 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000426 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000427 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
428 SmallVectorImpl<unsigned> &,
429 SmallVirtRegSet &, unsigned);
430 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
431 SmallVirtRegSet &, unsigned);
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000432 void tryHintRecoloring(LiveInterval &);
433 void tryHintsRecoloring();
434
435 /// Model the information carried by one end of a copy.
436 struct HintInfo {
437 /// The frequency of the copy.
438 BlockFrequency Freq;
439 /// The virtual register or physical register.
440 unsigned Reg;
441 /// Its currently assigned register.
442 /// In case of a physical register Reg == PhysReg.
443 unsigned PhysReg;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000444
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000445 HintInfo(BlockFrequency Freq, unsigned Reg, unsigned PhysReg)
446 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
447 };
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000448 using HintsInfo = SmallVector<HintInfo, 4>;
449
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000450 BlockFrequency getBrokenHintFreq(const HintsInfo &, unsigned);
451 void collectHintInfo(unsigned, HintsInfo &);
Matthias Braun953393a2015-07-14 17:38:17 +0000452
453 bool isUnusedCalleeSavedReg(unsigned PhysReg) const;
Adam Nemeta9640662017-01-25 23:20:33 +0000454
455 /// Compute and report the number of spills and reloads for a loop.
456 void reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
457 unsigned &FoldedReloads, unsigned &Spills,
458 unsigned &FoldedSpills);
459
460 /// Report the number of spills and reloads for each loop.
461 void reportNumberOfSplillsReloads() {
462 for (MachineLoop *L : *Loops) {
463 unsigned Reloads, FoldedReloads, Spills, FoldedSpills;
464 reportNumberOfSplillsReloads(L, Reloads, FoldedReloads, Spills,
465 FoldedSpills);
466 }
467 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000468};
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000469
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000470} // end anonymous namespace
471
472char RAGreedy::ID = 0;
Tom Stellard11e60ff2016-11-14 21:50:13 +0000473char &llvm::RAGreedyID = RAGreedy::ID;
474
475INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
476 "Greedy Register Allocator", false, false)
477INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
478INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
479INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
480INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
481INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
482INITIALIZE_PASS_DEPENDENCY(LiveStacks)
483INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
484INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
485INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
486INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
487INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
488INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
Adam Nemeta9640662017-01-25 23:20:33 +0000489INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
Tom Stellard11e60ff2016-11-14 21:50:13 +0000490INITIALIZE_PASS_END(RAGreedy, "greedy",
491 "Greedy Register Allocator", false, false)
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000492
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000493#ifndef NDEBUG
494const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000495 "RS_New",
496 "RS_Assign",
497 "RS_Split",
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000498 "RS_Split2",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000499 "RS_Spill",
Quentin Colombet11922942015-07-17 23:04:06 +0000500 "RS_Memory",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000501 "RS_Done"
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000502};
503#endif
504
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000505// Hysteresis to use when comparing floats.
506// This helps stabilize decisions based on float comparisons.
NAKAMURA Takumia71003a2014-02-04 06:29:38 +0000507const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000508
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000509FunctionPass* llvm::createGreedyRegisterAllocator() {
510 return new RAGreedy();
511}
512
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000513RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000514}
515
516void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
517 AU.setPreservesCFG();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000518 AU.addRequired<MachineBlockFrequencyInfo>();
519 AU.addPreserved<MachineBlockFrequencyInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000520 AU.addRequired<AAResultsWrapperPass>();
521 AU.addPreserved<AAResultsWrapperPass>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000522 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen12243122012-06-08 23:44:45 +0000523 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000524 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000525 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000526 AU.addRequired<LiveDebugVariables>();
527 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000528 AU.addRequired<LiveStacks>();
529 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000530 AU.addRequired<MachineDominatorTree>();
531 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000532 AU.addRequired<MachineLoopInfo>();
533 AU.addPreserved<MachineLoopInfo>();
534 AU.addRequired<VirtRegMap>();
535 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000536 AU.addRequired<LiveRegMatrix>();
537 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000538 AU.addRequired<EdgeBundles>();
539 AU.addRequired<SpillPlacement>();
Adam Nemeta9640662017-01-25 23:20:33 +0000540 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000541 MachineFunctionPass::getAnalysisUsage(AU);
542}
543
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000544//===----------------------------------------------------------------------===//
545// LiveRangeEdit delegate methods
546//===----------------------------------------------------------------------===//
547
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000548bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jonas Paulsson6188f322017-09-15 07:47:38 +0000549 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000550 if (VRM->hasPhys(VirtReg)) {
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000551 Matrix->unassign(LI);
552 aboutToRemoveInterval(LI);
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000553 return true;
554 }
555 // Unassigned virtreg is probably in the priority queue.
556 // RegAllocBase will erase it after dequeueing.
Jonas Paulsson6188f322017-09-15 07:47:38 +0000557 // Nonetheless, clear the live-range so that the debug
558 // dump will show the right state for that VirtReg.
559 LI.clear();
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000560 return false;
561}
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000562
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000563void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000564 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000565 return;
566
567 // Register is assigned, put it back on the queue for reassignment.
568 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000569 Matrix->unassign(LI);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000570 enqueue(&LI);
571}
572
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000573void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen811b9c42011-09-14 17:34:37 +0000574 // Cloning a register we haven't even heard about yet? Just ignore it.
575 if (!ExtraRegInfo.inBounds(Old))
576 return;
577
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000578 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000579 // be split into connected components. The new components are much smaller
580 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000581 // same stage as the parent.
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000582 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000583 ExtraRegInfo.grow(New);
584 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000585}
586
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000587void RAGreedy::releaseMemory() {
David Blaikieb61064e2014-07-19 01:05:11 +0000588 SpillerInstance.reset();
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000589 ExtraRegInfo.clear();
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000590 GlobalCand.clear();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000591}
592
Quentin Colombet87769712014-02-05 22:13:59 +0000593void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
594
595void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000596 // Prioritize live ranges by size, assigning larger ranges first.
597 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000598 const unsigned Size = LI->getSize();
599 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000600 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
601 "Can only enqueue virtual registers");
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000602 unsigned Prio;
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000603
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000604 ExtraRegInfo.grow(Reg);
605 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000606 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000607
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000608 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000609 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +0000610 // everything else has been allocated.
611 Prio = Size;
Quentin Colombet11922942015-07-17 23:04:06 +0000612 } else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
613 // Memory operand should be considered last.
614 // Change the priority such that Memory operand are assigned in
615 // the reverse order that they came in.
616 // TODO: Make this a member variable and probably do something about hints.
617 static unsigned MemOp = 0;
618 Prio = MemOp++;
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000619 } else {
Andrew Trick52a00932014-02-26 22:07:26 +0000620 // Giant live ranges fall back to the global assignment heuristic, which
621 // prevents excessive spilling in pathological cases.
622 bool ReverseLocal = TRI->reverseLocalAssignment();
Matthias Brauna354cdd2015-03-31 19:57:53 +0000623 const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
Renato Golin4e31ae12014-10-03 12:20:53 +0000624 bool ForceGlobal = !ReverseLocal &&
Matthias Brauna354cdd2015-03-31 19:57:53 +0000625 (Size / SlotIndex::InstrDist) > (2 * RC.getNumRegs());
Andrew Trick52a00932014-02-26 22:07:26 +0000626
627 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
Andrew Trick84852572013-07-25 18:35:14 +0000628 LIS->intervalIsInOneMBB(*LI)) {
629 // Allocate original local ranges in linear instruction order. Since they
630 // are singly defined, this produces optimal coloring in the absence of
631 // global interference and other constraints.
Andrew Trick52a00932014-02-26 22:07:26 +0000632 if (!ReverseLocal)
Andrew Trick2d8826a2013-12-11 03:40:15 +0000633 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
634 else {
635 // Allocating bottom up may allow many short LRGs to be assigned first
636 // to one of the cheap registers. This could be much faster for very
637 // large blocks on targets with many physical registers.
Matthias Braunf5f89b92015-03-31 19:57:49 +0000638 Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
Andrew Trick2d8826a2013-12-11 03:40:15 +0000639 }
Matthias Brauna354cdd2015-03-31 19:57:53 +0000640 Prio |= RC.AllocationPriority << 24;
641 } else {
Andrew Trick84852572013-07-25 18:35:14 +0000642 // Allocate global and split ranges in long->short order. Long ranges that
643 // don't fit should be spilled (or split) ASAP so they don't create
644 // interference. Mark a bit to prioritize global above local ranges.
645 Prio = (1u << 29) + Size;
646 }
647 // Mark a higher bit to prioritize global and local above RS_Split.
648 Prio |= (1u << 31);
Jakob Stoklund Olesenb51f65c2011-02-23 00:56:56 +0000649
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000650 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen74052b02012-12-03 23:23:50 +0000651 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000652 Prio |= (1u << 30);
653 }
Andrew Trickf4b1ee32013-07-25 18:35:22 +0000654 // The virtual register number is a tie breaker for same-sized ranges.
655 // Give lower vreg numbers higher priority to assign them first.
Quentin Colombet87769712014-02-05 22:13:59 +0000656 CurQueue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000657}
658
Quentin Colombet87769712014-02-05 22:13:59 +0000659LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
660
661LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
662 if (CurQueue.empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000663 return nullptr;
Quentin Colombet87769712014-02-05 22:13:59 +0000664 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
665 CurQueue.pop();
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000666 return LI;
667}
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000668
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000669//===----------------------------------------------------------------------===//
670// Direct Assignment
671//===----------------------------------------------------------------------===//
672
673/// tryAssign - Try to assign VirtReg to an available register.
674unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
675 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000676 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000677 Order.rewind();
678 unsigned PhysReg;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000679 while ((PhysReg = Order.next()))
680 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000681 break;
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000682 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000683 return PhysReg;
684
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000685 // PhysReg is available, but there may be a better choice.
686
687 // If we missed a simple hint, try to cheaply evict interference from the
688 // preferred register.
689 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000690 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000691 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
Andrew Trick3621b8a2013-11-22 19:07:38 +0000692 EvictionCost MaxCost;
693 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000694 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
695 evictInterference(VirtReg, Hint, NewVRegs);
696 return Hint;
697 }
Quentin Colombetfb9b0cd2016-11-16 01:07:12 +0000698 // Record the missed hint, we may be able to recover
699 // at the end if the surrounding allocation changed.
700 SetOfBrokenHints.insert(&VirtReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000701 }
702
703 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000704 unsigned Cost = TRI->getCostPerUse(PhysReg);
705
706 // Most registers have 0 additional cost.
707 if (!Cost)
708 return PhysReg;
709
710 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
711 << '\n');
712 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
713 return CheapReg ? CheapReg : PhysReg;
714}
715
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000716//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000717// Interference eviction
718//===----------------------------------------------------------------------===//
719
Andrew Trick8bb0a252013-07-25 18:35:19 +0000720unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
Matthias Braun5d1f12d2015-07-15 22:16:00 +0000721 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000722 unsigned PhysReg;
723 while ((PhysReg = Order.next())) {
724 if (PhysReg == PrevReg)
725 continue;
726
727 MCRegUnitIterator Units(PhysReg, TRI);
728 for (; Units.isValid(); ++Units) {
729 // Instantiate a "subquery", not to be confused with the Queries array.
Matthias Braun173e1142017-03-01 21:48:12 +0000730 LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000731 if (subQ.checkInterference())
732 break;
733 }
734 // If no units have interference, break out with the current PhysReg.
735 if (!Units.isValid())
736 break;
737 }
738 if (PhysReg)
739 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
740 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
741 << '\n');
742 return PhysReg;
743}
744
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000745/// shouldEvict - determine if A should evict the assigned live range B. The
746/// eviction policy defined by this function together with the allocation order
747/// defined by enqueue() decides which registers ultimately end up being split
748/// and spilled.
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000749///
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000750/// Cascade numbers are used to prevent infinite loops if this function is a
751/// cyclic relation.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000752///
753/// @param A The live range to be assigned.
754/// @param IsHint True when A is about to be assigned to its preferred
755/// register.
756/// @param B The live range to be evicted.
757/// @param BreaksHint True when B is already assigned to its preferred register.
758bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
759 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000760 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000761
762 // Be fairly aggressive about following hints as long as the evictee can be
763 // split.
764 if (CanSplit && IsHint && !BreaksHint)
765 return true;
766
Andrew Trick059e8002013-11-22 19:07:42 +0000767 if (A.weight > B.weight) {
768 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
769 return true;
770 }
771 return false;
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000772}
773
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000774/// canEvictInterference - Return true if all interferences between VirtReg and
Manman Renfa32ca12014-02-25 19:47:15 +0000775/// PhysReg can be evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000776///
777/// @param VirtReg Live range that is about to be assigned.
778/// @param PhysReg Desired register for assignment.
Dmitri Gribenko881929c2012-09-12 16:59:47 +0000779/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000780/// @param MaxCost Only look for cheaper candidates and update with new cost
781/// when returning true.
782/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000783bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000784 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000785 // It is only possible to evict virtual register interference.
786 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
787 return false;
788
Andrew Trick84852572013-07-25 18:35:14 +0000789 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
790
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000791 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
792 // involved in an eviction before. If a cascade number was assigned, deny
793 // evicting anything with the same or a newer cascade number. This prevents
794 // infinite eviction loops.
795 //
796 // This works out so a register without a cascade number is allowed to evict
797 // anything, and it can be evicted by anything.
798 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
799 if (!Cascade)
800 Cascade = NextCascade;
801
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000802 EvictionCost Cost;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000803 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
804 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000805 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000806 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000807 return false;
808
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000809 // Check if any interfering live range is heavier than MaxWeight.
810 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
811 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000812 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
813 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000814 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000815 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000816 return false;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000817 // Once a live range becomes small enough, it is urgent that we find a
818 // register for it. This is indicated by an infinite spill weight. These
819 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen05e22452012-05-30 21:46:58 +0000820 //
821 // Also allow urgent evictions of unspillable ranges from a strictly
822 // larger allocation order.
823 bool Urgent = !VirtReg.isSpillable() &&
824 (Intf->isSpillable() ||
825 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
826 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000827 // Only evict older cascades or live ranges without a cascade.
828 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
829 if (Cascade <= IntfCascade) {
830 if (!Urgent)
831 return false;
832 // We permit breaking cascades for urgent evictions. It should be the
833 // last resort, though, so make it really expensive.
834 Cost.BrokenHints += 10;
835 }
836 // Would this break a satisfied hint?
837 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
838 // Update eviction cost.
839 Cost.BrokenHints += BreaksHint;
840 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
841 // Abort if this would be too expensive.
842 if (!(Cost < MaxCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000843 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000844 if (Urgent)
845 continue;
Andrew Trickc2ab53a2013-11-29 23:49:38 +0000846 // Apply the eviction policy for non-urgent evictions.
847 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
848 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000849 // If !MaxCost.isMax(), then we're just looking for a cheap register.
850 // Evicting another local live range in this case could lead to suboptimal
851 // coloring.
Andrew Trick8bb0a252013-07-25 18:35:19 +0000852 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000853 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
Andrew Trick84852572013-07-25 18:35:14 +0000854 return false;
Andrew Trick8bb0a252013-07-25 18:35:19 +0000855 }
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000856 }
857 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000858 MaxCost = Cost;
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000859 return true;
860}
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000861
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000862/// evictInterference - Evict any interferring registers that prevent VirtReg
863/// from being assigned to Physreg. This assumes that canEvictInterference
864/// returned true.
865void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000866 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000867 // Make sure that VirtReg has a cascade number, and assign that cascade
868 // number to every evicted register. These live ranges than then only be
869 // evicted by a newer cascade, preventing infinite loops.
870 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
871 if (!Cascade)
872 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
873
874 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
875 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000876
877 // Collect all interfering virtregs first.
878 SmallVector<LiveInterval*, 8> Intfs;
879 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
880 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Matthias Braunffe40dd2017-03-03 23:27:20 +0000881 // We usually have the interfering VRegs cached so collectInterferingVRegs()
882 // should be fast, we may need to recalculate if when different physregs
883 // overlap the same register unit so we had different SubRanges queried
884 // against it.
885 Q.collectInterferingVRegs();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000886 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
887 Intfs.append(IVR.begin(), IVR.end());
888 }
889
890 // Evict them second. This will invalidate the queries.
891 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
892 LiveInterval *Intf = Intfs[i];
893 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
894 if (!VRM->hasPhys(Intf->reg))
895 continue;
896 Matrix->unassign(*Intf);
897 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
898 VirtReg.isSpillable() < Intf->isSpillable()) &&
899 "Cannot decrease cascade number, illegal eviction");
900 ExtraRegInfo[Intf->reg].Cascade = Cascade;
901 ++NumEvicted;
Mark Laceyf9ea8852013-08-14 23:50:04 +0000902 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000903 }
904}
905
Matthias Braun953393a2015-07-14 17:38:17 +0000906/// Returns true if the given \p PhysReg is a callee saved register and has not
907/// been used for allocation yet.
908bool RAGreedy::isUnusedCalleeSavedReg(unsigned PhysReg) const {
909 unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
910 if (CSR == 0)
911 return false;
912
913 return !Matrix->isPhysRegUsed(PhysReg);
914}
915
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000916/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +0000917/// @param VirtReg Currently unassigned virtual register.
918/// @param Order Physregs to try.
919/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000920unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
921 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000922 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000923 unsigned CostPerUseLimit) {
Matthias Braun9f15a792016-11-18 19:43:18 +0000924 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
925 TimePassesIsEnabled);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000926
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000927 // Keep track of the cheapest interference seen so far.
Andrew Trick3621b8a2013-11-22 19:07:38 +0000928 EvictionCost BestCost;
929 BestCost.setMax();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000930 unsigned BestPhys = 0;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000931 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000932
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000933 // When we are just looking for a reduced cost per use, don't break any
934 // hints, and only evict smaller spill weights.
935 if (CostPerUseLimit < ~0u) {
936 BestCost.BrokenHints = 0;
937 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000938
939 // Check of any registers in RC are below CostPerUseLimit.
940 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
941 unsigned MinCost = RegClassInfo.getMinCost(RC);
942 if (MinCost >= CostPerUseLimit) {
Craig Toppercf0444b2014-11-17 05:50:14 +0000943 DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = " << MinCost
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000944 << ", no cheaper registers to be found.\n");
945 return 0;
946 }
947
948 // It is normal for register classes to have a long tail of registers with
949 // the same cost. We don't need to look at them if they're too expensive.
950 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
951 OrderLimit = RegClassInfo.getLastCostChange(RC);
952 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
953 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000954 }
955
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000956 Order.rewind();
Aditya Nandakumar73f3d332013-12-05 21:18:40 +0000957 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000958 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
959 continue;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000960 // The first use of a callee-saved register in a function has cost 1.
961 // Don't start using a CSR when the CostPerUseLimit is low.
Matthias Braun953393a2015-07-14 17:38:17 +0000962 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
963 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
964 << PrintReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
965 << '\n');
966 continue;
967 }
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000968
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000969 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000970 continue;
971
972 // Best so far.
973 BestPhys = PhysReg;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000974
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000975 // Stop if the hint can be used.
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000976 if (Order.isHint())
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000977 break;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000978 }
979
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000980 if (!BestPhys)
981 return 0;
982
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000983 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000984 return BestPhys;
Andrew Trickccef0982010-12-09 18:15:21 +0000985}
986
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000987//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000988// Region Splitting
989//===----------------------------------------------------------------------===//
990
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000991/// addSplitConstraints - Fill out the SplitConstraints vector based on the
992/// interference pattern in Physreg and its aliases. Add the constraints to
993/// SpillPlacement and return the static cost of this split in Cost, assuming
994/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000995/// Return false if there are no bundles with positive bias.
996bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000997 BlockFrequency &Cost) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000998 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000999
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001000 // Reset interference dependent info.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001001 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001002 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001003 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1004 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001005 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001006
Jakob Stoklund Olesenb1b76ad2011-02-09 22:50:26 +00001007 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001008 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001009 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
1010 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie041f1aa2013-05-15 07:36:59 +00001011 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001012
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001013 if (!Intf.hasInterference())
1014 continue;
1015
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001016 // Number of spill code instructions to insert.
1017 unsigned Ins = 0;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001018
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001019 // Interference for the live-in value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001020 if (BI.LiveIn) {
Richard Trieu7a083812016-02-18 22:09:30 +00001021 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
1022 BC.Entry = SpillPlacement::MustSpill;
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001023 ++Ins;
Richard Trieu7a083812016-02-18 22:09:30 +00001024 } else if (Intf.first() < BI.FirstInstr) {
1025 BC.Entry = SpillPlacement::PrefSpill;
1026 ++Ins;
1027 } else if (Intf.first() < BI.LastInstr) {
1028 ++Ins;
1029 }
Jakob Stoklund Olesenf248b202011-02-08 23:02:58 +00001030 }
1031
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001032 // Interference for the live-out value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001033 if (BI.LiveOut) {
Richard Trieu7a083812016-02-18 22:09:30 +00001034 if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
1035 BC.Exit = SpillPlacement::MustSpill;
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001036 ++Ins;
Richard Trieu7a083812016-02-18 22:09:30 +00001037 } else if (Intf.last() > BI.LastInstr) {
1038 BC.Exit = SpillPlacement::PrefSpill;
1039 ++Ins;
1040 } else if (Intf.last() > BI.FirstInstr) {
1041 ++Ins;
1042 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001043 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001044
1045 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001046 while (Ins--)
1047 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001048 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001049 Cost = StaticCost;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001050
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001051 // Add constraints for use-blocks. Note that these are the only constraints
1052 // that may add a positive bias, it is downhill from here.
1053 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001054 return SpillPlacer->scanActiveBundles();
1055}
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001056
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001057/// addThroughConstraints - Add constraints and links to SpillPlacer from the
1058/// live-through blocks in Blocks.
1059void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
1060 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001061 const unsigned GroupSize = 8;
1062 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001063 unsigned TBS[GroupSize];
1064 unsigned B = 0, T = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001065
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001066 for (unsigned i = 0; i != Blocks.size(); ++i) {
1067 unsigned Number = Blocks[i];
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001068 Intf.moveToBlock(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001069
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001070 if (!Intf.hasInterference()) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001071 assert(T < GroupSize && "Array overflow");
1072 TBS[T] = Number;
1073 if (++T == GroupSize) {
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001074 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001075 T = 0;
1076 }
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001077 continue;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001078 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001079
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001080 assert(B < GroupSize && "Array overflow");
1081 BCS[B].Number = Number;
1082
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001083 // Interference for the live-in value.
1084 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
1085 BCS[B].Entry = SpillPlacement::MustSpill;
1086 else
1087 BCS[B].Entry = SpillPlacement::PrefSpill;
1088
1089 // Interference for the live-out value.
1090 if (Intf.last() >= SA->getLastSplitPoint(Number))
1091 BCS[B].Exit = SpillPlacement::MustSpill;
1092 else
1093 BCS[B].Exit = SpillPlacement::PrefSpill;
1094
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001095 if (++B == GroupSize) {
Craig Toppere1d12942014-08-27 05:25:25 +00001096 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001097 B = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001098 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001099 }
1100
Craig Toppere1d12942014-08-27 05:25:25 +00001101 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001102 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001103}
1104
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001105void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001106 // Keep track of through blocks that have not been added to SpillPlacer.
1107 BitVector Todo = SA->getThroughBlocks();
1108 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
1109 unsigned AddedTo = 0;
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001110#ifndef NDEBUG
1111 unsigned Visited = 0;
1112#endif
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001113
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001114 while (true) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001115 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001116 // Find new through blocks in the periphery of PrefRegBundles.
1117 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
1118 unsigned Bundle = NewBundles[i];
1119 // Look at all blocks connected to Bundle in the full graph.
1120 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
1121 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
1122 I != E; ++I) {
1123 unsigned Block = *I;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001124 if (!Todo.test(Block))
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001125 continue;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001126 Todo.reset(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001127 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001128 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001129#ifndef NDEBUG
1130 ++Visited;
1131#endif
1132 }
1133 }
1134 // Any new blocks to add?
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001135 if (ActiveBlocks.size() == AddedTo)
1136 break;
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001137
1138 // Compute through constraints from the interference, or assume that all
1139 // through blocks prefer spilling when forming compact regions.
Craig Toppere1d12942014-08-27 05:25:25 +00001140 auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001141 if (Cand.PhysReg)
1142 addThroughConstraints(Cand.Intf, NewBlocks);
1143 else
Jakob Stoklund Olesen86954522011-08-03 23:09:38 +00001144 // Provide a strong negative bias on through blocks to prevent unwanted
1145 // liveness on loop backedges.
1146 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001147 AddedTo = ActiveBlocks.size();
1148
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001149 // Perhaps iterating can enable more bundles?
1150 SpillPlacer->iterate();
1151 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001152 DEBUG(dbgs() << ", v=" << Visited);
1153}
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001154
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001155/// calcCompactRegion - Compute the set of edge bundles that should be live
1156/// when splitting the current live range into compact regions. Compact
1157/// regions can be computed without looking at interference. They are the
1158/// regions formed by removing all the live-through blocks from the live range.
1159///
1160/// Returns false if the current live range is already compact, or if the
1161/// compact regions would form single block regions anyway.
1162bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1163 // Without any through blocks, the live range is already compact.
1164 if (!SA->getNumThroughBlocks())
1165 return false;
1166
1167 // Compact regions don't correspond to any physreg.
1168 Cand.reset(IntfCache, 0);
1169
1170 DEBUG(dbgs() << "Compact region bundles");
1171
1172 // Use the spill placer to determine the live bundles. GrowRegion pretends
1173 // that all the through blocks have interference when PhysReg is unset.
1174 SpillPlacer->prepare(Cand.LiveBundles);
1175
1176 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001177 BlockFrequency Cost;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001178 if (!addSplitConstraints(Cand.Intf, Cost)) {
1179 DEBUG(dbgs() << ", none.\n");
1180 return false;
1181 }
1182
1183 growRegion(Cand);
1184 SpillPlacer->finish();
1185
1186 if (!Cand.LiveBundles.any()) {
1187 DEBUG(dbgs() << ", none.\n");
1188 return false;
1189 }
1190
1191 DEBUG({
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001192 for (int i : Cand.LiveBundles.set_bits())
1193 dbgs() << " EB#" << i;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001194 dbgs() << ".\n";
1195 });
1196 return true;
1197}
1198
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001199/// calcSpillCost - Compute how expensive it would be to split the live range in
1200/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001201BlockFrequency RAGreedy::calcSpillCost() {
1202 BlockFrequency Cost = 0;
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001203 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1204 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1205 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1206 unsigned Number = BI.MBB->getNumber();
1207 // We normally only need one spill instruction - a load or a store.
1208 Cost += SpillPlacer->getBlockFrequency(Number);
1209
1210 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3c145052011-08-02 23:04:08 +00001211 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1212 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001213 }
1214 return Cost;
1215}
1216
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001217/// calcGlobalSplitCost - Return the global split cost of following the split
1218/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001219/// interference pattern in SplitConstraints.
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001220///
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001221BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1222 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001223 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001224 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1225 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1226 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001227 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001228 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, false)];
1229 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)];
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001230 unsigned Ins = 0;
1231
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001232 if (BI.LiveIn)
1233 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1234 if (BI.LiveOut)
1235 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001236 while (Ins--)
1237 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001238 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001239
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001240 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1241 unsigned Number = Cand.ActiveBlocks[i];
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001242 bool RegIn = LiveBundles[Bundles->getBundle(Number, false)];
1243 bool RegOut = LiveBundles[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001244 if (!RegIn && !RegOut)
1245 continue;
1246 if (RegIn && RegOut) {
1247 // We need double spill code if this block has interference.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001248 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001249 if (Cand.Intf.hasInterference()) {
1250 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1251 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1252 }
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001253 continue;
1254 }
1255 // live-in / stack-out or stack-in live-out.
1256 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001257 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001258 return GlobalCost;
1259}
1260
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001261/// splitAroundRegion - Split the current live range around the regions
1262/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001263///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001264/// Before calling this function, GlobalCand and BundleCand must be initialized
1265/// so each bundle is assigned to a valid candidate, or NoCand for the
1266/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1267/// objects must be initialized for the current live range, and intervals
1268/// created for the used candidates.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001269///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001270/// @param LREdit The LiveRangeEdit object handling the current split.
1271/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1272/// must appear in this list.
1273void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1274 ArrayRef<unsigned> UsedCands) {
1275 // These are the intervals created for new global ranges. We may create more
1276 // intervals for local ranges.
1277 const unsigned NumGlobalIntvs = LREdit.size();
1278 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1279 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001280
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001281 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen22f37a12011-08-06 18:20:24 +00001282 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001283 // is all copies.
1284 unsigned Reg = SA->getParent().reg;
1285 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1286
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001287 // First handle all the blocks with uses.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001288 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1289 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1290 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001291 unsigned Number = BI.MBB->getNumber();
1292 unsigned IntvIn = 0, IntvOut = 0;
1293 SlotIndex IntfIn, IntfOut;
1294 if (BI.LiveIn) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001295 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001296 if (CandIn != NoCand) {
1297 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1298 IntvIn = Cand.IntvIdx;
1299 Cand.Intf.moveToBlock(Number);
1300 IntfIn = Cand.Intf.first();
1301 }
1302 }
1303 if (BI.LiveOut) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001304 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001305 if (CandOut != NoCand) {
1306 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1307 IntvOut = Cand.IntvIdx;
1308 Cand.Intf.moveToBlock(Number);
1309 IntfOut = Cand.Intf.last();
1310 }
1311 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001312
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001313 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001314 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001315 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001316 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001317 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001318 continue;
1319 }
1320
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001321 if (IntvIn && IntvOut)
1322 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1323 else if (IntvIn)
1324 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesen795da1c2011-07-15 21:47:57 +00001325 else
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001326 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001327 }
1328
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001329 // Handle live-through blocks. The relevant live-through blocks are stored in
1330 // the ActiveBlocks list with each candidate. We need to filter out
1331 // duplicates.
1332 BitVector Todo = SA->getThroughBlocks();
1333 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1334 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1335 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1336 unsigned Number = Blocks[i];
1337 if (!Todo.test(Number))
1338 continue;
1339 Todo.reset(Number);
1340
1341 unsigned IntvIn = 0, IntvOut = 0;
1342 SlotIndex IntfIn, IntfOut;
1343
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001344 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001345 if (CandIn != NoCand) {
1346 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1347 IntvIn = Cand.IntvIdx;
1348 Cand.Intf.moveToBlock(Number);
1349 IntfIn = Cand.Intf.first();
1350 }
1351
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001352 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001353 if (CandOut != NoCand) {
1354 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1355 IntvOut = Cand.IntvIdx;
1356 Cand.Intf.moveToBlock(Number);
1357 IntfOut = Cand.Intf.last();
1358 }
1359 if (!IntvIn && !IntvOut)
1360 continue;
1361 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1362 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001363 }
1364
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001365 ++NumGlobalSplits;
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001366
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001367 SmallVector<unsigned, 8> IntvMap;
1368 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001369 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001370
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001371 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen5cc91b22011-05-28 02:32:57 +00001372 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001373
1374 // Sort out the new intervals created by splitting. We get four kinds:
1375 // - Remainder intervals should not be split again.
1376 // - Candidate intervals can be assigned to Cand.PhysReg.
1377 // - Block-local splits are candidates for local splitting.
1378 // - DCE leftovers should go back on the queue.
1379 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001380 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001381
1382 // Ignore old intervals from DCE.
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001383 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001384 continue;
1385
1386 // Remainder interval. Don't try splitting again, spill if it doesn't
1387 // allocate.
1388 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001389 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001390 continue;
1391 }
1392
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001393 // Global intervals. Allow repeated splitting as long as the number of live
1394 // blocks is strictly decreasing.
1395 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001396 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001397 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1398 << " blocks as original.\n");
1399 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001400 setStage(Reg, RS_Split2);
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001401 }
1402 continue;
1403 }
1404
1405 // Other intervals are treated as new. This includes local intervals created
1406 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001407 }
1408
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +00001409 if (VerifyEnabled)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001410 MF->verify(this, "After splitting live range around region");
1411}
1412
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001413unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001414 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001415 unsigned NumCands = 0;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001416 BlockFrequency BestCost;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001417
1418 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +00001419 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001420 if (HasCompact) {
1421 // Yes, keep GlobalCand[0] as the compact region candidate.
1422 NumCands = 1;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001423 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001424 } else {
1425 // No benefit from the compact region, our fallback will be per-block
1426 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001427 BestCost = calcSpillCost();
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001428 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1429 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001430 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001431
Manman Ren9db66b32014-03-24 23:23:42 +00001432 unsigned BestCand =
Manman Ren78cf02a2014-03-25 00:16:25 +00001433 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1434 false/*IgnoreCSR*/);
Manman Ren9db66b32014-03-24 23:23:42 +00001435
1436 // No solutions found, fall back to single block splitting.
1437 if (!HasCompact && BestCand == NoCand)
1438 return 0;
1439
1440 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1441}
1442
1443unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1444 AllocationOrder &Order,
1445 BlockFrequency &BestCost,
Manman Ren78cf02a2014-03-25 00:16:25 +00001446 unsigned &NumCands,
1447 bool IgnoreCSR) {
Manman Ren9db66b32014-03-24 23:23:42 +00001448 unsigned BestCand = NoCand;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001449 Order.rewind();
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001450 while (unsigned PhysReg = Order.next()) {
Matthias Braun953393a2015-07-14 17:38:17 +00001451 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1452 continue;
Manman Ren78cf02a2014-03-25 00:16:25 +00001453
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001454 // Discard bad candidates before we run out of interference cache cursors.
1455 // This will only affect register classes with a lot of registers (>32).
1456 if (NumCands == IntfCache.getMaxCursors()) {
1457 unsigned WorstCount = ~0u;
1458 unsigned Worst = 0;
1459 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001460 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001461 continue;
1462 unsigned Count = GlobalCand[i].LiveBundles.count();
Richard Trieu7a083812016-02-18 22:09:30 +00001463 if (Count < WorstCount) {
1464 Worst = i;
1465 WorstCount = Count;
1466 }
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001467 }
1468 --NumCands;
1469 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen559d4dc2011-11-01 00:02:31 +00001470 if (BestCand == NumCands)
1471 BestCand = Worst;
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001472 }
1473
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001474 if (GlobalCand.size() <= NumCands)
1475 GlobalCand.resize(NumCands+1);
1476 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1477 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001478
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001479 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001480 BlockFrequency Cost;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001481 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001482 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001483 continue;
1484 }
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001485 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1486 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001487 if (Cost >= BestCost) {
1488 DEBUG({
1489 if (BestCand == NoCand)
1490 dbgs() << " worse than no bundles\n";
1491 else
1492 dbgs() << " worse than "
1493 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1494 });
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001495 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001496 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001497 growRegion(Cand);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001498
Jakob Stoklund Olesen36b5d8a2011-04-06 19:13:57 +00001499 SpillPlacer->finish();
1500
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001501 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001502 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001503 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001504 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001505 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001506
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001507 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001508 DEBUG({
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001509 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1510 << " with bundles";
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001511 for (int i : Cand.LiveBundles.set_bits())
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001512 dbgs() << " EB#" << i;
1513 dbgs() << ".\n";
1514 });
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001515 if (Cost < BestCost) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001516 BestCand = NumCands;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001517 BestCost = Cost;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001518 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001519 ++NumCands;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001520 }
Manman Ren9db66b32014-03-24 23:23:42 +00001521 return BestCand;
1522}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001523
Manman Ren9db66b32014-03-24 23:23:42 +00001524unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1525 bool HasCompact,
1526 SmallVectorImpl<unsigned> &NewVRegs) {
1527 SmallVector<unsigned, 8> UsedCands;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001528 // Prepare split editor.
Wei Mi9a16d652016-04-13 03:08:27 +00001529 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001530 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001531
1532 // Assign all edge bundles to the preferred candidate, or NoCand.
1533 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1534
1535 // Assign bundles for the best candidate region.
1536 if (BestCand != NoCand) {
1537 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1538 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1539 UsedCands.push_back(BestCand);
1540 Cand.IntvIdx = SE->openIntv();
1541 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1542 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001543 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001544 }
1545 }
1546
1547 // Assign bundles for the compact region.
1548 if (HasCompact) {
1549 GlobalSplitCandidate &Cand = GlobalCand.front();
1550 assert(!Cand.PhysReg && "Compact region has no physreg");
1551 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1552 UsedCands.push_back(0);
1553 Cand.IntvIdx = SE->openIntv();
1554 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1555 << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001556 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001557 }
1558 }
1559
1560 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001561 return 0;
1562}
1563
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001564//===----------------------------------------------------------------------===//
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001565// Per-Block Splitting
1566//===----------------------------------------------------------------------===//
1567
1568/// tryBlockSplit - Split a global live range around every block with uses. This
1569/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1570/// they don't allocate.
1571unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001572 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001573 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1574 unsigned Reg = VirtReg.reg;
1575 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Wei Mi9a16d652016-04-13 03:08:27 +00001576 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001577 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001578 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1579 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1580 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1581 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1582 SE->splitSingleBlock(BI);
1583 }
1584 // No blocks were split.
1585 if (LREdit.empty())
1586 return 0;
1587
1588 // We did split for some blocks.
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001589 SmallVector<unsigned, 8> IntvMap;
1590 SE->finish(&IntvMap);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001591
1592 // Tell LiveDebugVariables about the new ranges.
Mark Laceyf9ea8852013-08-14 23:50:04 +00001593 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001594
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001595 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1596
1597 // Sort out the new intervals created by splitting. The remainder interval
1598 // goes straight to spilling, the new local ranges get to stay RS_New.
1599 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001600 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001601 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1602 setStage(LI, RS_Spill);
1603 }
1604
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001605 if (VerifyEnabled)
1606 MF->verify(this, "After splitting live range around basic blocks");
1607 return 0;
1608}
1609
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001610//===----------------------------------------------------------------------===//
1611// Per-Instruction Splitting
1612//===----------------------------------------------------------------------===//
1613
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001614/// Get the number of allocatable registers that match the constraints of \p Reg
1615/// on \p MI and that are also in \p SuperRC.
1616static unsigned getNumAllocatableRegsForConstraints(
1617 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1618 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1619 const RegisterClassInfo &RCI) {
1620 assert(SuperRC && "Invalid register class");
1621
1622 const TargetRegisterClass *ConstrainedRC =
1623 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1624 /* ExploreBundle */ true);
1625 if (!ConstrainedRC)
1626 return 0;
1627 return RCI.getNumAllocatableRegs(ConstrainedRC);
1628}
1629
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001630/// tryInstructionSplit - Split a live range around individual instructions.
1631/// This is normally not worthwhile since the spiller is doing essentially the
1632/// same thing. However, when the live range is in a constrained register
1633/// class, it may help to insert copies such that parts of the live range can
1634/// be moved to a larger register class.
1635///
1636/// This is similar to spilling to a larger register class.
1637unsigned
1638RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001639 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001640 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001641 // There is no point to this if there are no larger sub-classes.
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001642 if (!RegClassInfo.isProperSubClass(CurRC))
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001643 return 0;
1644
1645 // Always enable split spill mode, since we're effectively spilling to a
1646 // register.
Wei Mi9a16d652016-04-13 03:08:27 +00001647 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001648 SE->reset(LREdit, SplitEditor::SM_Size);
1649
1650 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1651 if (Uses.size() <= 1)
1652 return 0;
1653
1654 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1655
Eric Christopher433c4322015-03-10 23:46:01 +00001656 const TargetRegisterClass *SuperRC =
1657 TRI->getLargestLegalSuperClass(CurRC, *MF);
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001658 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1659 // Split around every non-copy instruction if this split will relax
1660 // the constraints on the virtual register.
1661 // Otherwise, splitting just inserts uncoalescable copies that do not help
1662 // the allocation.
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001663 for (unsigned i = 0; i != Uses.size(); ++i) {
1664 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001665 if (MI->isFullCopy() ||
1666 SuperRCNumAllocatableRegs ==
1667 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1668 TRI, RCI)) {
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001669 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1670 continue;
1671 }
1672 SE->openIntv();
1673 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1674 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1675 SE->useIntv(SegStart, SegStop);
1676 }
1677
1678 if (LREdit.empty()) {
1679 DEBUG(dbgs() << "All uses were copies.\n");
1680 return 0;
1681 }
1682
1683 SmallVector<unsigned, 8> IntvMap;
1684 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001685 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001686 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1687
1688 // Assign all new registers to RS_Spill. This was the last chance.
1689 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1690 return 0;
1691}
1692
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001693//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001694// Local Splitting
1695//===----------------------------------------------------------------------===//
1696
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001697/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1698/// in order to use PhysReg between two entries in SA->UseSlots.
1699///
1700/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1701///
1702void RAGreedy::calcGapWeights(unsigned PhysReg,
1703 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001704 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1705 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001706 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001707 const unsigned NumGaps = Uses.size()-1;
1708
1709 // Start and end points for the interference check.
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001710 SlotIndex StartIdx =
1711 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1712 SlotIndex StopIdx =
1713 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001714
1715 GapWeight.assign(NumGaps, 0.0f);
1716
1717 // Add interference from each overlapping register.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001718 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1719 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1720 .checkInterference())
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001721 continue;
1722
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001723 // We know that VirtReg is a continuous interval from FirstInstr to
1724 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001725 //
1726 // Interference that overlaps an instruction is counted in both gaps
1727 // surrounding the instruction. The exception is interference before
1728 // StartIdx and after StopIdx.
1729 //
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001730 LiveIntervalUnion::SegmentIter IntI =
1731 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001732 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1733 // Skip the gaps before IntI.
1734 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1735 if (++Gap == NumGaps)
1736 break;
1737 if (Gap == NumGaps)
1738 break;
1739
1740 // Update the gaps covered by IntI.
1741 const float weight = IntI.value()->weight;
1742 for (; Gap != NumGaps; ++Gap) {
1743 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1744 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1745 break;
1746 }
1747 if (Gap == NumGaps)
1748 break;
1749 }
1750 }
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001751
1752 // Add fixed interference.
1753 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001754 const LiveRange &LR = LIS->getRegUnit(*Units);
1755 LiveRange::const_iterator I = LR.find(StartIdx);
1756 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001757
1758 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1759 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1760 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1761 if (++Gap == NumGaps)
1762 break;
1763 if (Gap == NumGaps)
1764 break;
1765
1766 for (; Gap != NumGaps; ++Gap) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001767 GapWeight[Gap] = huge_valf;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001768 if (Uses[Gap+1].getBaseIndex() >= I->end)
1769 break;
1770 }
1771 if (Gap == NumGaps)
1772 break;
1773 }
1774 }
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001775}
1776
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001777/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1778/// basic block.
1779///
1780unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001781 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001782 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1783 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001784
1785 // Note that it is possible to have an interval that is live-in or live-out
1786 // while only covering a single block - A phi-def can use undef values from
1787 // predecessors, and the block could be a single-block loop.
1788 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001789 // that the interval is continuous from FirstInstr to LastInstr. We should
1790 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001791
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001792 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001793 if (Uses.size() <= 2)
1794 return 0;
1795 const unsigned NumGaps = Uses.size()-1;
1796
1797 DEBUG({
1798 dbgs() << "tryLocalSplit: ";
1799 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001800 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001801 dbgs() << '\n';
1802 });
1803
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001804 // If VirtReg is live across any register mask operands, compute a list of
1805 // gaps with register masks.
1806 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001807 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001808 // Get regmask slots for the whole block.
1809 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001810 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001811 // Constrain to VirtReg's live range.
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001812 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1813 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001814 unsigned re = RMS.size();
1815 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001816 // Look for Uses[i] <= RMS <= Uses[i+1].
1817 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1818 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001819 continue;
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001820 // Skip a regmask on the same instruction as the last use. It doesn't
1821 // overlap the live range.
1822 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1823 break;
1824 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001825 RegMaskGaps.push_back(i);
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001826 // Advance ri to the next gap. A regmask on one of the uses counts in
1827 // both gaps.
1828 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1829 ++ri;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001830 }
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001831 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001832 }
1833
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001834 // Since we allow local split results to be split again, there is a risk of
1835 // creating infinite loops. It is tempting to require that the new live
1836 // ranges have less instructions than the original. That would guarantee
1837 // convergence, but it is too strict. A live range with 3 instructions can be
1838 // split 2+3 (including the COPY), and we want to allow that.
1839 //
1840 // Instead we use these rules:
1841 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001842 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001843 // noop split, of course).
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001844 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001845 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001846 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001847 // smaller ranges are marked RS_New.
1848 //
1849 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1850 // excessive splitting and infinite loops.
1851 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001852 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001853
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001854 // Best split candidate.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001855 unsigned BestBefore = NumGaps;
1856 unsigned BestAfter = 0;
1857 float BestDiff = 0;
1858
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001859 const float blockFreq =
1860 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Michael Gottesman5e985ee2013-12-14 02:37:38 +00001861 (1.0f / MBFI->getEntryFreq());
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001862 SmallVector<float, 8> GapWeight;
1863
1864 Order.rewind();
1865 while (unsigned PhysReg = Order.next()) {
1866 // Keep track of the largest spill weight that would need to be evicted in
1867 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1868 calcGapWeights(PhysReg, GapWeight);
1869
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001870 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001871 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001872 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001873 GapWeight[RegMaskGaps[i]] = huge_valf;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001874
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001875 // Try to find the best sequence of gaps to close.
1876 // The new spill weight must be larger than any gap interference.
1877
1878 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001879 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001880
1881 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1882 // It is the spill weight that needs to be evicted.
1883 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001884
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001885 while (true) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001886 // Live before/after split?
1887 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1888 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1889
1890 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1891 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1892 << " i=" << MaxGap);
1893
1894 // Stop before the interval gets so big we wouldn't be making progress.
1895 if (!LiveBefore && !LiveAfter) {
1896 DEBUG(dbgs() << " all\n");
1897 break;
1898 }
1899 // Should the interval be extended or shrunk?
1900 bool Shrink = true;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001901
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001902 // How many gaps would the new range have?
1903 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1904
1905 // Legally, without causing looping?
1906 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1907
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001908 if (Legal && MaxGap < huge_valf) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001909 // Estimate the new spill weight. Each instruction reads or writes the
1910 // register. Conservatively assume there are no read-modify-write
1911 // instructions.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001912 //
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001913 // Try to guess the size of the new interval.
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +00001914 const float EstWeight = normalizeSpillWeight(
1915 blockFreq * (NewGaps + 1),
1916 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1917 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
1918 1);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001919 // Would this split be possible to allocate?
1920 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001921 DEBUG(dbgs() << " w=" << EstWeight);
1922 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001923 Shrink = false;
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001924 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001925 if (Diff > BestDiff) {
1926 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001927 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001928 BestBefore = SplitBefore;
1929 BestAfter = SplitAfter;
1930 }
1931 }
1932 }
1933
1934 // Try to shrink.
1935 if (Shrink) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001936 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001937 DEBUG(dbgs() << " shrink\n");
1938 // Recompute the max when necessary.
1939 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1940 MaxGap = GapWeight[SplitBefore];
1941 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1942 MaxGap = std::max(MaxGap, GapWeight[i]);
1943 }
1944 continue;
1945 }
1946 MaxGap = 0;
1947 }
1948
1949 // Try to extend the interval.
1950 if (SplitAfter >= NumGaps) {
1951 DEBUG(dbgs() << " end\n");
1952 break;
1953 }
1954
1955 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001956 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001957 }
1958 }
1959
1960 // Didn't find any candidates?
1961 if (BestBefore == NumGaps)
1962 return 0;
1963
1964 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1965 << '-' << Uses[BestAfter] << ", " << BestDiff
1966 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1967
Wei Mi9a16d652016-04-13 03:08:27 +00001968 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001969 SE->reset(LREdit);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001970
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001971 SE->openIntv();
1972 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1973 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1974 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001975 SmallVector<unsigned, 8> IntvMap;
1976 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001977 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001978
1979 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001980 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001981 // leave the new intervals as RS_New so they can compete.
1982 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1983 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1984 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1985 if (NewGaps >= NumGaps) {
1986 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1987 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001988 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1989 if (IntvMap[i] == 1) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001990 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1991 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001992 }
1993 DEBUG(dbgs() << '\n');
1994 }
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001995 ++NumLocalSplits;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001996
1997 return 0;
1998}
1999
2000//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002001// Live Range Splitting
2002//===----------------------------------------------------------------------===//
2003
2004/// trySplit - Try to split VirtReg or one of its interferences, making it
2005/// assignable.
2006/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
2007unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002008 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesend4bb1d42011-08-05 23:50:33 +00002009 // Ranges must be Split2 or less.
2010 if (getStage(VirtReg) >= RS_Spill)
2011 return 0;
2012
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002013 // Local intervals are handled separately.
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00002014 if (LIS->intervalIsInOneMBB(VirtReg)) {
Matthias Braun9f15a792016-11-18 19:43:18 +00002015 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
2016 TimerGroupDescription, TimePassesIsEnabled);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002017 SA->analyze(&VirtReg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002018 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
2019 if (PhysReg || !NewVRegs.empty())
2020 return PhysReg;
2021 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00002022 }
2023
Matthias Braun9f15a792016-11-18 19:43:18 +00002024 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
2025 TimerGroupDescription, TimePassesIsEnabled);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002026
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002027 SA->analyze(&VirtReg);
2028
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00002029 // FIXME: SplitAnalysis may repair broken live ranges coming from the
2030 // coalescer. That may cause the range to become allocatable which means that
2031 // tryRegionSplit won't be making progress. This check should be replaced with
2032 // an assertion when the coalescer is fixed.
2033 if (SA->didRepairRange()) {
2034 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002035 Matrix->invalidateVirtRegs();
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00002036 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
2037 return PhysReg;
2038 }
2039
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002040 // First try to split around a region spanning multiple blocks. RS_Split2
2041 // ranges already made dubious progress with region splitting, so they go
2042 // straight to single block splitting.
2043 if (getStage(VirtReg) < RS_Split2) {
2044 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2045 if (PhysReg || !NewVRegs.empty())
2046 return PhysReg;
2047 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002048
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00002049 // Then isolate blocks.
2050 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002051}
2052
Quentin Colombet87769712014-02-05 22:13:59 +00002053//===----------------------------------------------------------------------===//
2054// Last Chance Recoloring
2055//===----------------------------------------------------------------------===//
2056
2057/// mayRecolorAllInterferences - Check if the virtual registers that
2058/// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
2059/// recolored to free \p PhysReg.
2060/// When true is returned, \p RecoloringCandidates has been augmented with all
2061/// the live intervals that need to be recolored in order to free \p PhysReg
2062/// for \p VirtReg.
2063/// \p FixedRegisters contains all the virtual registers that cannot be
2064/// recolored.
2065bool
2066RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
2067 SmallLISet &RecoloringCandidates,
2068 const SmallVirtRegSet &FixedRegisters) {
2069 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
2070
2071 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2072 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
2073 // If there is LastChanceRecoloringMaxInterference or more interferences,
2074 // chances are one would not be recolorable.
2075 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
Quentin Colombet567e30b2014-04-11 21:39:44 +00002076 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
Quentin Colombet87769712014-02-05 22:13:59 +00002077 DEBUG(dbgs() << "Early abort: too many interferences.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002078 CutOffInfo |= CO_Interf;
Quentin Colombet87769712014-02-05 22:13:59 +00002079 return false;
2080 }
2081 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
2082 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
2083 // If Intf is done and sit on the same register class as VirtReg,
2084 // it would not be recolorable as it is in the same state as VirtReg.
2085 if ((getStage(*Intf) == RS_Done &&
2086 MRI->getRegClass(Intf->reg) == CurRC) ||
2087 FixedRegisters.count(Intf->reg)) {
2088 DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
2089 return false;
2090 }
2091 RecoloringCandidates.insert(Intf);
2092 }
2093 }
2094 return true;
2095}
2096
2097/// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
2098/// its interferences.
2099/// Last chance recoloring chooses a color for \p VirtReg and recolors every
2100/// virtual register that was using it. The recoloring process may recursively
2101/// use the last chance recoloring. Therefore, when a virtual register has been
2102/// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
2103/// be last-chance-recolored again during this recoloring "session".
2104/// E.g.,
2105/// Let
2106/// vA can use {R1, R2 }
2107/// vB can use { R2, R3}
2108/// vC can use {R1 }
2109/// Where vA, vB, and vC cannot be split anymore (they are reloads for
2110/// instance) and they all interfere.
2111///
2112/// vA is assigned R1
2113/// vB is assigned R2
2114/// vC tries to evict vA but vA is already done.
2115/// Regular register allocation fails.
2116///
2117/// Last chance recoloring kicks in:
2118/// vC does as if vA was evicted => vC uses R1.
2119/// vC is marked as fixed.
2120/// vA needs to find a color.
2121/// None are available.
2122/// vA cannot evict vC: vC is a fixed virtual register now.
2123/// vA does as if vB was evicted => vA uses R2.
2124/// vB needs to find a color.
2125/// R3 is available.
2126/// Recoloring => vC = R1, vA = R2, vB = R3
2127///
Alp Toker70b36992014-02-25 04:21:15 +00002128/// \p Order defines the preferred allocation order for \p VirtReg.
Quentin Colombet87769712014-02-05 22:13:59 +00002129/// \p NewRegs will contain any new virtual register that have been created
2130/// (split, spill) during the process and that must be assigned.
2131/// \p FixedRegisters contains all the virtual registers that cannot be
2132/// recolored.
2133/// \p Depth gives the current depth of the last chance recoloring.
2134/// \return a physical register that can be used for VirtReg or ~0u if none
2135/// exists.
2136unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2137 AllocationOrder &Order,
2138 SmallVectorImpl<unsigned> &NewVRegs,
2139 SmallVirtRegSet &FixedRegisters,
2140 unsigned Depth) {
2141 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2142 // Ranges must be Done.
Quentin Colombet0e3b5e02014-02-13 05:17:37 +00002143 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
Quentin Colombet87769712014-02-05 22:13:59 +00002144 "Last chance recoloring should really be last chance");
2145 // Set the max depth to LastChanceRecoloringMaxDepth.
2146 // We may want to reconsider that if we end up with a too large search space
2147 // for target with hundreds of registers.
2148 // Indeed, in that case we may want to cut the search space earlier.
Quentin Colombet567e30b2014-04-11 21:39:44 +00002149 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
Quentin Colombet87769712014-02-05 22:13:59 +00002150 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002151 CutOffInfo |= CO_Depth;
Quentin Colombet87769712014-02-05 22:13:59 +00002152 return ~0u;
2153 }
2154
2155 // Set of Live intervals that will need to be recolored.
2156 SmallLISet RecoloringCandidates;
2157 // Record the original mapping virtual register to physical register in case
2158 // the recoloring fails.
2159 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
2160 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2161 // this recoloring "session".
2162 FixedRegisters.insert(VirtReg.reg);
Quentin Colombet318582f2016-09-16 22:00:50 +00002163 SmallVector<unsigned, 4> CurrentNewVRegs;
Quentin Colombet87769712014-02-05 22:13:59 +00002164
2165 Order.rewind();
2166 while (unsigned PhysReg = Order.next()) {
2167 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2168 << PrintReg(PhysReg, TRI) << '\n');
2169 RecoloringCandidates.clear();
2170 VirtRegToPhysReg.clear();
Quentin Colombet318582f2016-09-16 22:00:50 +00002171 CurrentNewVRegs.clear();
Quentin Colombet87769712014-02-05 22:13:59 +00002172
2173 // It is only possible to recolor virtual register interference.
2174 if (Matrix->checkInterference(VirtReg, PhysReg) >
2175 LiveRegMatrix::IK_VirtReg) {
2176 DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
2177
2178 continue;
2179 }
2180
2181 // Early give up on this PhysReg if it is obvious we cannot recolor all
2182 // the interferences.
2183 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2184 FixedRegisters)) {
2185 DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
2186 continue;
2187 }
2188
2189 // RecoloringCandidates contains all the virtual registers that interfer
2190 // with VirtReg on PhysReg (or one of its aliases).
2191 // Enqueue them for recoloring and perform the actual recoloring.
2192 PQueue RecoloringQueue;
2193 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2194 EndIt = RecoloringCandidates.end();
2195 It != EndIt; ++It) {
2196 unsigned ItVirtReg = (*It)->reg;
2197 enqueue(RecoloringQueue, *It);
2198 assert(VRM->hasPhys(ItVirtReg) &&
2199 "Interferences are supposed to be with allocated vairables");
2200
2201 // Record the current allocation.
2202 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2203 // unset the related struct.
2204 Matrix->unassign(**It);
2205 }
2206
2207 // Do as if VirtReg was assigned to PhysReg so that the underlying
2208 // recoloring has the right information about the interferes and
2209 // available colors.
2210 Matrix->assign(VirtReg, PhysReg);
2211
2212 // Save the current recoloring state.
2213 // If we cannot recolor all the interferences, we will have to start again
2214 // at this point for the next physical register.
2215 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
Quentin Colombet318582f2016-09-16 22:00:50 +00002216 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2217 FixedRegisters, Depth)) {
2218 // Push the queued vregs into the main queue.
2219 for (unsigned NewVReg : CurrentNewVRegs)
2220 NewVRegs.push_back(NewVReg);
Quentin Colombet87769712014-02-05 22:13:59 +00002221 // Do not mess up with the global assignment process.
2222 // I.e., VirtReg must be unassigned.
2223 Matrix->unassign(VirtReg);
2224 return PhysReg;
2225 }
2226
2227 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2228 << PrintReg(PhysReg, TRI) << '\n');
2229
2230 // The recoloring attempt failed, undo the changes.
2231 FixedRegisters = SaveFixedRegisters;
2232 Matrix->unassign(VirtReg);
2233
Wei Mib5cf9e52016-11-08 18:19:36 +00002234 // For a newly created vreg which is also in RecoloringCandidates,
2235 // don't add it to NewVRegs because its physical register will be restored
2236 // below. Other vregs in CurrentNewVRegs are created by calling
2237 // selectOrSplit and should be added into NewVRegs.
Quentin Colombet318582f2016-09-16 22:00:50 +00002238 for (SmallVectorImpl<unsigned>::iterator Next = CurrentNewVRegs.begin(),
2239 End = CurrentNewVRegs.end();
2240 Next != End; ++Next) {
Wei Mib5cf9e52016-11-08 18:19:36 +00002241 if (RecoloringCandidates.count(&LIS->getInterval(*Next)))
Quentin Colombet318582f2016-09-16 22:00:50 +00002242 continue;
2243 NewVRegs.push_back(*Next);
2244 }
2245
Quentin Colombet87769712014-02-05 22:13:59 +00002246 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2247 EndIt = RecoloringCandidates.end();
2248 It != EndIt; ++It) {
2249 unsigned ItVirtReg = (*It)->reg;
2250 if (VRM->hasPhys(ItVirtReg))
2251 Matrix->unassign(**It);
Matthias Braun953393a2015-07-14 17:38:17 +00002252 unsigned ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2253 Matrix->assign(**It, ItPhysReg);
Quentin Colombet87769712014-02-05 22:13:59 +00002254 }
2255 }
2256
2257 // Last chance recoloring did not worked either, give up.
2258 return ~0u;
2259}
2260
2261/// tryRecoloringCandidates - Try to assign a new color to every register
2262/// in \RecoloringQueue.
2263/// \p NewRegs will contain any new virtual register created during the
2264/// recoloring process.
2265/// \p FixedRegisters[in/out] contains all the registers that have been
2266/// recolored.
2267/// \return true if all virtual registers in RecoloringQueue were successfully
2268/// recolored, false otherwise.
2269bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2270 SmallVectorImpl<unsigned> &NewVRegs,
2271 SmallVirtRegSet &FixedRegisters,
2272 unsigned Depth) {
2273 while (!RecoloringQueue.empty()) {
2274 LiveInterval *LI = dequeue(RecoloringQueue);
2275 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2276 unsigned PhysReg;
2277 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
Quentin Colombet52ffa672016-10-13 19:27:48 +00002278 // When splitting happens, the live-range may actually be empty.
2279 // In that case, this is okay to continue the recoloring even
2280 // if we did not find an alternative color for it. Indeed,
2281 // there will not be anything to color for LI in the end.
2282 if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
Quentin Colombet87769712014-02-05 22:13:59 +00002283 return false;
Quentin Colombet52ffa672016-10-13 19:27:48 +00002284
2285 if (!PhysReg) {
2286 assert(LI->empty() && "Only empty live-range do not require a register");
2287 DEBUG(dbgs() << "Recoloring of " << *LI << " succeeded. Empty LI.\n");
2288 continue;
2289 }
Quentin Colombet87769712014-02-05 22:13:59 +00002290 DEBUG(dbgs() << "Recoloring of " << *LI
2291 << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
Quentin Colombet52ffa672016-10-13 19:27:48 +00002292
Quentin Colombet87769712014-02-05 22:13:59 +00002293 Matrix->assign(*LI, PhysReg);
2294 FixedRegisters.insert(LI->reg);
2295 }
2296 return true;
2297}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002298
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002299//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002300// Main Entry Point
2301//===----------------------------------------------------------------------===//
2302
2303unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002304 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002305 CutOffInfo = CO_None;
2306 LLVMContext &Ctx = MF->getFunction()->getContext();
Quentin Colombet87769712014-02-05 22:13:59 +00002307 SmallVirtRegSet FixedRegisters;
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002308 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2309 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2310 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2311 if (CutOffEncountered == CO_Depth)
Quentin Colombet567e30b2014-04-11 21:39:44 +00002312 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2313 "reached. Use -fexhaustive-register-search to skip "
2314 "cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002315 else if (CutOffEncountered == CO_Interf)
2316 Ctx.emitError("register allocation failed: maximum interference for "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002317 "recoloring reached. Use -fexhaustive-register-search "
2318 "to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002319 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2320 Ctx.emitError("register allocation failed: maximum interference and "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002321 "depth for recoloring reached. Use "
2322 "-fexhaustive-register-search to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002323 }
2324 return Reg;
Quentin Colombet87769712014-02-05 22:13:59 +00002325}
2326
Manman Ren9dee4492014-03-27 21:21:57 +00002327/// Using a CSR for the first time has a cost because it causes push|pop
2328/// to be added to prologue|epilogue. Splitting a cold section of the live
2329/// range can have lower cost than using the CSR for the first time;
2330/// Spilling a live range in the cold path can have lower cost than using
2331/// the CSR for the first time. Returns the physical register if we decide
2332/// to use the CSR; otherwise return 0.
2333unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2334 AllocationOrder &Order,
2335 unsigned PhysReg,
2336 unsigned &CostPerUseLimit,
2337 SmallVectorImpl<unsigned> &NewVRegs) {
Manman Ren9dee4492014-03-27 21:21:57 +00002338 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2339 // We choose spill over using the CSR for the first time if the spill cost
2340 // is lower than CSRCost.
2341 SA->analyze(&VirtReg);
2342 if (calcSpillCost() >= CSRCost)
2343 return PhysReg;
2344
2345 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2346 // we will not use a callee-saved register in tryEvict.
2347 CostPerUseLimit = 1;
2348 return 0;
2349 }
2350 if (getStage(VirtReg) < RS_Split) {
2351 // We choose pre-splitting over using the CSR for the first time if
2352 // the cost of splitting is lower than CSRCost.
2353 SA->analyze(&VirtReg);
2354 unsigned NumCands = 0;
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002355 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2356 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2357 NumCands, true /*IgnoreCSR*/);
Manman Ren9dee4492014-03-27 21:21:57 +00002358 if (BestCand == NoCand)
2359 // Use the CSR if we can't find a region split below CSRCost.
2360 return PhysReg;
2361
2362 // Perform the actual pre-splitting.
2363 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2364 return 0;
2365 }
2366 return PhysReg;
2367}
2368
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002369void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
2370 // Do not keep invalid information around.
2371 SetOfBrokenHints.remove(&LI);
2372}
2373
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002374void RAGreedy::initializeCSRCost() {
2375 // We use the larger one out of the command-line option and the value report
2376 // by TRI.
2377 CSRCost = BlockFrequency(
2378 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2379 if (!CSRCost.getFrequency())
2380 return;
2381
2382 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2383 uint64_t ActualEntry = MBFI->getEntryFreq();
2384 if (!ActualEntry) {
2385 CSRCost = 0;
2386 return;
2387 }
2388 uint64_t FixedEntry = 1 << 14;
2389 if (ActualEntry < FixedEntry)
2390 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2391 else if (ActualEntry <= UINT32_MAX)
2392 // Invert the fraction and divide.
2393 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2394 else
2395 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2396 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2397}
2398
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002399/// \brief Collect the hint info for \p Reg.
2400/// The results are stored into \p Out.
2401/// \p Out is not cleared before being populated.
2402void RAGreedy::collectHintInfo(unsigned Reg, HintsInfo &Out) {
2403 for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2404 if (!Instr.isFullCopy())
2405 continue;
2406 // Look for the other end of the copy.
2407 unsigned OtherReg = Instr.getOperand(0).getReg();
2408 if (OtherReg == Reg) {
2409 OtherReg = Instr.getOperand(1).getReg();
2410 if (OtherReg == Reg)
2411 continue;
2412 }
2413 // Get the current assignment.
2414 unsigned OtherPhysReg = TargetRegisterInfo::isPhysicalRegister(OtherReg)
2415 ? OtherReg
2416 : VRM->getPhys(OtherReg);
2417 // Push the collected information.
2418 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2419 OtherPhysReg));
2420 }
2421}
2422
2423/// \brief Using the given \p List, compute the cost of the broken hints if
2424/// \p PhysReg was used.
2425/// \return The cost of \p List for \p PhysReg.
2426BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2427 unsigned PhysReg) {
2428 BlockFrequency Cost = 0;
2429 for (const HintInfo &Info : List) {
2430 if (Info.PhysReg != PhysReg)
2431 Cost += Info.Freq;
2432 }
2433 return Cost;
2434}
2435
2436/// \brief Using the register assigned to \p VirtReg, try to recolor
2437/// all the live ranges that are copy-related with \p VirtReg.
2438/// The recoloring is then propagated to all the live-ranges that have
2439/// been recolored and so on, until no more copies can be coalesced or
2440/// it is not profitable.
2441/// For a given live range, profitability is determined by the sum of the
2442/// frequencies of the non-identity copies it would introduce with the old
2443/// and new register.
2444void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
2445 // We have a broken hint, check if it is possible to fix it by
2446 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2447 // some register and PhysReg may be available for the other live-ranges.
2448 SmallSet<unsigned, 4> Visited;
2449 SmallVector<unsigned, 2> RecoloringCandidates;
2450 HintsInfo Info;
2451 unsigned Reg = VirtReg.reg;
2452 unsigned PhysReg = VRM->getPhys(Reg);
2453 // Start the recoloring algorithm from the input live-interval, then
2454 // it will propagate to the ones that are copy-related with it.
2455 Visited.insert(Reg);
2456 RecoloringCandidates.push_back(Reg);
2457
2458 DEBUG(dbgs() << "Trying to reconcile hints for: " << PrintReg(Reg, TRI) << '('
2459 << PrintReg(PhysReg, TRI) << ")\n");
2460
2461 do {
2462 Reg = RecoloringCandidates.pop_back_val();
2463
Hiroshi Inouea86c9202017-07-10 12:44:25 +00002464 // We cannot recolor physical register.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002465 if (TargetRegisterInfo::isPhysicalRegister(Reg))
2466 continue;
2467
2468 assert(VRM->hasPhys(Reg) && "We have unallocated variable!!");
2469
2470 // Get the live interval mapped with this virtual register to be able
2471 // to check for the interference with the new color.
2472 LiveInterval &LI = LIS->getInterval(Reg);
2473 unsigned CurrPhys = VRM->getPhys(Reg);
2474 // Check that the new color matches the register class constraints and
2475 // that it is free for this live range.
2476 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2477 Matrix->checkInterference(LI, PhysReg)))
2478 continue;
2479
2480 DEBUG(dbgs() << PrintReg(Reg, TRI) << '(' << PrintReg(CurrPhys, TRI)
2481 << ") is recolorable.\n");
2482
2483 // Gather the hint info.
2484 Info.clear();
2485 collectHintInfo(Reg, Info);
2486 // Check if recoloring the live-range will increase the cost of the
2487 // non-identity copies.
2488 if (CurrPhys != PhysReg) {
2489 DEBUG(dbgs() << "Checking profitability:\n");
2490 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2491 BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
2492 DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2493 << "\nNew Cost: " << NewCopiesCost.getFrequency() << '\n');
2494 if (OldCopiesCost < NewCopiesCost) {
2495 DEBUG(dbgs() << "=> Not profitable.\n");
2496 continue;
2497 }
2498 // At this point, the cost is either cheaper or equal. If it is
2499 // equal, we consider this is profitable because it may expose
2500 // more recoloring opportunities.
2501 DEBUG(dbgs() << "=> Profitable.\n");
2502 // Recolor the live-range.
2503 Matrix->unassign(LI);
2504 Matrix->assign(LI, PhysReg);
2505 }
2506 // Push all copy-related live-ranges to keep reconciling the broken
2507 // hints.
2508 for (const HintInfo &HI : Info) {
2509 if (Visited.insert(HI.Reg).second)
2510 RecoloringCandidates.push_back(HI.Reg);
2511 }
2512 } while (!RecoloringCandidates.empty());
2513}
2514
2515/// \brief Try to recolor broken hints.
2516/// Broken hints may be repaired by recoloring when an evicted variable
2517/// freed up a register for a larger live-range.
2518/// Consider the following example:
2519/// BB1:
2520/// a =
2521/// b =
2522/// BB2:
2523/// ...
2524/// = b
2525/// = a
2526/// Let us assume b gets split:
2527/// BB1:
2528/// a =
2529/// b =
2530/// BB2:
2531/// c = b
2532/// ...
2533/// d = c
2534/// = d
2535/// = a
2536/// Because of how the allocation work, b, c, and d may be assigned different
2537/// colors. Now, if a gets evicted later:
2538/// BB1:
2539/// a =
2540/// st a, SpillSlot
2541/// b =
2542/// BB2:
2543/// c = b
2544/// ...
2545/// d = c
2546/// = d
2547/// e = ld SpillSlot
2548/// = e
2549/// This is likely that we can assign the same register for b, c, and d,
2550/// getting rid of 2 copies.
2551void RAGreedy::tryHintsRecoloring() {
2552 for (LiveInterval *LI : SetOfBrokenHints) {
2553 assert(TargetRegisterInfo::isVirtualRegister(LI->reg) &&
2554 "Recoloring is possible only for virtual registers");
2555 // Some dead defs may be around (e.g., because of debug uses).
2556 // Ignore those.
2557 if (!VRM->hasPhys(LI->reg))
2558 continue;
2559 tryHintRecoloring(*LI);
2560 }
2561}
2562
Quentin Colombet87769712014-02-05 22:13:59 +00002563unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2564 SmallVectorImpl<unsigned> &NewVRegs,
2565 SmallVirtRegSet &FixedRegisters,
2566 unsigned Depth) {
Manman Ren78cf02a2014-03-25 00:16:25 +00002567 unsigned CostPerUseLimit = ~0u;
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002568 // First try assigning a free register.
Matthias Braun5d1f12d2015-07-15 22:16:00 +00002569 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
Manman Ren78cf02a2014-03-25 00:16:25 +00002570 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
Manman Ren9dee4492014-03-27 21:21:57 +00002571 // When NewVRegs is not empty, we may have made decisions such as evicting
2572 // a virtual register, go with the earlier decisions and use the physical
2573 // register.
Matthias Braun953393a2015-07-14 17:38:17 +00002574 if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
2575 NewVRegs.empty()) {
Manman Ren9dee4492014-03-27 21:21:57 +00002576 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2577 CostPerUseLimit, NewVRegs);
2578 if (CSRReg || !NewVRegs.empty())
2579 // Return now if we decide to use a CSR or create new vregs due to
2580 // pre-splitting.
2581 return CSRReg;
Manman Ren78cf02a2014-03-25 00:16:25 +00002582 } else
2583 return PhysReg;
2584 }
Andrew Trickccef0982010-12-09 18:15:21 +00002585
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002586 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00002587 DEBUG(dbgs() << StageName[Stage]
2588 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002589
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002590 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002591 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002592 // get a second chance until they have been split.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002593 if (Stage != RS_Split)
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002594 if (unsigned PhysReg =
2595 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit)) {
2596 unsigned Hint = MRI->getSimpleHint(VirtReg.reg);
2597 // If VirtReg has a hint and that hint is broken record this
2598 // virtual register as a recoloring candidate for broken hint.
2599 // Indeed, since we evicted a variable in its neighborhood it is
2600 // likely we can at least partially recolor some of the
2601 // copy-related live-ranges.
2602 if (Hint && Hint != PhysReg)
2603 SetOfBrokenHints.insert(&VirtReg);
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002604 return PhysReg;
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002605 }
Andrew Trickccef0982010-12-09 18:15:21 +00002606
Quentin Colombet63176862016-09-16 22:00:42 +00002607 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002608
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00002609 // The first time we see a live range, don't try to split or spill.
2610 // Wait until the second time, when all smaller ranges have been allocated.
2611 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002612 if (Stage < RS_Split) {
2613 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesen86985072011-03-19 23:02:47 +00002614 DEBUG(dbgs() << "wait for second round\n");
Mark Laceyf9ea8852013-08-14 23:50:04 +00002615 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00002616 return 0;
2617 }
2618
Dylan McKayc328fe52016-10-11 01:04:36 +00002619 if (Stage < RS_Spill) {
2620 // Try splitting VirtReg or interferences.
2621 unsigned NewVRegSizeBefore = NewVRegs.size();
2622 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2623 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore))
2624 return PhysReg;
2625 }
2626
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00002627 // If we couldn't allocate a register from spilling, there is probably some
Hiroshi Inoueff8453d2017-06-29 18:03:28 +00002628 // invalid inline assembly. The base class will report it.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002629 if (Stage >= RS_Done || !VirtReg.isSpillable())
Quentin Colombet87769712014-02-05 22:13:59 +00002630 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2631 Depth);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002632
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002633 // Finally spill VirtReg itself.
Quentin Colombet11922942015-07-17 23:04:06 +00002634 if (EnableDeferredSpilling && getStage(VirtReg) < RS_Memory) {
2635 // TODO: This is experimental and in particular, we do not model
2636 // the live range splitting done by spilling correctly.
2637 // We would need a deep integration with the spiller to do the
2638 // right thing here. Anyway, that is still good for early testing.
2639 setStage(VirtReg, RS_Memory);
2640 DEBUG(dbgs() << "Do as if this register is in memory\n");
2641 NewVRegs.push_back(VirtReg.reg);
2642 } else {
Matthias Braun9f15a792016-11-18 19:43:18 +00002643 NamedRegionTimer T("spill", "Spiller", TimerGroupName,
2644 TimerGroupDescription, TimePassesIsEnabled);
Wei Mi9a16d652016-04-13 03:08:27 +00002645 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Quentin Colombet11922942015-07-17 23:04:06 +00002646 spiller().spill(LRE);
2647 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002648
Quentin Colombet11922942015-07-17 23:04:06 +00002649 if (VerifyEnabled)
2650 MF->verify(this, "After spilling");
2651 }
Jakob Stoklund Olesen557a82c2011-03-16 22:56:08 +00002652
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002653 // The live virtual register requesting allocation was spilled, so tell
2654 // the caller not to allocate anything during this round.
2655 return 0;
2656}
2657
Adam Nemeta9640662017-01-25 23:20:33 +00002658void RAGreedy::reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
2659 unsigned &FoldedReloads,
2660 unsigned &Spills,
2661 unsigned &FoldedSpills) {
2662 Reloads = 0;
2663 FoldedReloads = 0;
2664 Spills = 0;
2665 FoldedSpills = 0;
2666
2667 // Sum up the spill and reloads in subloops.
2668 for (MachineLoop *SubLoop : *L) {
2669 unsigned SubReloads;
2670 unsigned SubFoldedReloads;
2671 unsigned SubSpills;
2672 unsigned SubFoldedSpills;
2673
2674 reportNumberOfSplillsReloads(SubLoop, SubReloads, SubFoldedReloads,
2675 SubSpills, SubFoldedSpills);
2676 Reloads += SubReloads;
2677 FoldedReloads += SubFoldedReloads;
2678 Spills += SubSpills;
2679 FoldedSpills += SubFoldedSpills;
2680 }
2681
2682 const MachineFrameInfo &MFI = MF->getFrameInfo();
2683 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2684 int FI;
2685
2686 for (MachineBasicBlock *MBB : L->getBlocks())
2687 // Handle blocks that were not included in subloops.
2688 if (Loops->getLoopFor(MBB) == L)
2689 for (MachineInstr &MI : *MBB) {
2690 const MachineMemOperand *MMO;
2691
2692 if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI))
2693 ++Reloads;
2694 else if (TII->hasLoadFromStackSlot(MI, MMO, FI) &&
2695 MFI.isSpillSlotObjectIndex(FI))
2696 ++FoldedReloads;
2697 else if (TII->isStoreToStackSlot(MI, FI) &&
2698 MFI.isSpillSlotObjectIndex(FI))
2699 ++Spills;
2700 else if (TII->hasStoreToStackSlot(MI, MMO, FI) &&
2701 MFI.isSpillSlotObjectIndex(FI))
2702 ++FoldedSpills;
2703 }
2704
2705 if (Reloads || FoldedReloads || Spills || FoldedSpills) {
2706 using namespace ore;
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002707
Adam Nemeta9640662017-01-25 23:20:33 +00002708 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReload",
2709 L->getStartLoc(), L->getHeader());
2710 if (Spills)
2711 R << NV("NumSpills", Spills) << " spills ";
2712 if (FoldedSpills)
2713 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
2714 if (Reloads)
2715 R << NV("NumReloads", Reloads) << " reloads ";
2716 if (FoldedReloads)
2717 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
2718 ORE->emit(R << "generated in loop");
2719 }
2720}
2721
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002722bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2723 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikiec8c29202012-08-22 17:18:53 +00002724 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002725
2726 MF = &mf;
Eric Christopher60621802014-10-14 07:22:00 +00002727 TRI = MF->getSubtarget().getRegisterInfo();
2728 TII = MF->getSubtarget().getInstrInfo();
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002729 RCI.runOnMachineFunction(mf);
Quentin Colombet5caa6a22014-07-02 18:32:04 +00002730
2731 EnableLocalReassign = EnableLocalReassignment ||
Eric Christopher60621802014-10-14 07:22:00 +00002732 MF->getSubtarget().enableRALocalReassignment(
2733 MF->getTarget().getOptLevel());
Quentin Colombet5caa6a22014-07-02 18:32:04 +00002734
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00002735 if (VerifyEnabled)
Jakob Stoklund Olesenbf4550e2010-12-18 00:06:56 +00002736 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00002737
Jakob Stoklund Olesen2d2dec92012-06-20 22:52:29 +00002738 RegAllocBase::init(getAnalysis<VirtRegMap>(),
2739 getAnalysis<LiveIntervals>(),
2740 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002741 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +00002742 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +00002743 DomTree = &getAnalysis<MachineDominatorTree>();
Adam Nemeta9640662017-01-25 23:20:33 +00002744 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
Jakob Stoklund Olesenadecb5e2010-12-10 22:54:44 +00002745 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00002746 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002747 Bundles = &getAnalysis<EdgeBundles>();
2748 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00002749 DebugVars = &getAnalysis<LiveDebugVariables>();
Wei Mic0223702016-07-08 21:08:09 +00002750 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002751
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002752 initializeCSRCost();
2753
Robert Lougher11a44b72015-08-10 11:59:44 +00002754 calculateSpillWeightsAndHints(*LIS, mf, VRM, *Loops, *MBFI);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +00002755
Andrew Trick97064962013-07-25 07:26:26 +00002756 DEBUG(LIS->dump());
2757
Jakob Stoklund Olesenf1a60a62011-02-19 00:53:42 +00002758 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Wei Mic0223702016-07-08 21:08:09 +00002759 SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00002760 ExtraRegInfo.clear();
2761 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2762 NextCascade = 1;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002763 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00002764 GlobalCand.resize(32); // This will grow as needed.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002765 SetOfBrokenHints.clear();
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00002766
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002767 allocatePhysRegs();
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002768 tryHintsRecoloring();
Wei Mi9a16d652016-04-13 03:08:27 +00002769 postOptimization();
Adam Nemeta9640662017-01-25 23:20:33 +00002770 reportNumberOfSplillsReloads();
Wei Mi9a16d652016-04-13 03:08:27 +00002771
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002772 releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002773 return true;
2774}