blob: c651ae21a07457c7ee969b9295d2b0ede05487dd [file] [log] [blame]
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001//===- subzero/src/IceRegAlloc.cpp - Linear-scan implementation -----------===//
2//
3// The Subzero Code Generator
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Andrew Scull9612d322015-07-06 14:53:25 -07009///
10/// \file
11/// This file implements the LinearScan class, which performs the
12/// linear-scan register allocation after liveness analysis has been
13/// performed.
14///
Jim Stichnothd97c7df2014-06-04 11:57:08 -070015//===----------------------------------------------------------------------===//
16
John Porto67f8de92015-06-25 10:14:17 -070017#include "IceRegAlloc.h"
18
Jim Stichnothd97c7df2014-06-04 11:57:08 -070019#include "IceCfg.h"
Jim Stichnoth87ff3a12014-11-14 10:27:29 -080020#include "IceCfgNode.h"
Jim Stichnothd97c7df2014-06-04 11:57:08 -070021#include "IceInst.h"
22#include "IceOperand.h"
Jim Stichnothd97c7df2014-06-04 11:57:08 -070023#include "IceTargetLowering.h"
24
25namespace Ice {
26
Jim Stichnothad403532014-09-25 12:44:17 -070027namespace {
28
Jim Stichnothe34d79d2015-01-12 09:00:50 -080029// TODO(stichnot): Statically choose the size based on the target
30// being compiled.
John Porto67f8de92015-06-25 10:14:17 -070031constexpr size_t REGS_SIZE = 32;
Jim Stichnothe34d79d2015-01-12 09:00:50 -080032
Jim Stichnothad403532014-09-25 12:44:17 -070033// Returns true if Var has any definitions within Item's live range.
Jim Stichnoth037fa1d2014-10-07 11:09:33 -070034// TODO(stichnot): Consider trimming the Definitions list similar to
35// how the live ranges are trimmed, since all the overlapsDefs() tests
36// are whether some variable's definitions overlap Cur, and trimming
37// is with respect Cur.start. Initial tests show no measurable
38// performance difference, so we'll keep the code simple for now.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070039bool overlapsDefs(const Cfg *Func, const Variable *Item, const Variable *Var) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -070040 constexpr bool UseTrimmed = true;
Jim Stichnoth037fa1d2014-10-07 11:09:33 -070041 VariablesMetadata *VMetadata = Func->getVMetadata();
Jim Stichnoth877b04e2014-10-15 15:13:06 -070042 if (const Inst *FirstDef = VMetadata->getFirstDefinition(Var))
43 if (Item->getLiveRange().overlapsInst(FirstDef->getNumber(), UseTrimmed))
44 return true;
45 const InstDefList &Defs = VMetadata->getLatterDefinitions(Var);
Jim Stichnothad403532014-09-25 12:44:17 -070046 for (size_t i = 0; i < Defs.size(); ++i) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070047 if (Item->getLiveRange().overlapsInst(Defs[i]->getNumber(), UseTrimmed))
Jim Stichnothad403532014-09-25 12:44:17 -070048 return true;
49 }
50 return false;
51}
52
53void dumpDisableOverlap(const Cfg *Func, const Variable *Var,
54 const char *Reason) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -070055 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -080056 return;
Jim Stichnothfa4efea2015-01-27 05:06:03 -080057 if (Func->isVerbose(IceV_LinearScan)) {
Jim Stichnoth037fa1d2014-10-07 11:09:33 -070058 VariablesMetadata *VMetadata = Func->getVMetadata();
Jim Stichnothad403532014-09-25 12:44:17 -070059 Ostream &Str = Func->getContext()->getStrDump();
60 Str << "Disabling Overlap due to " << Reason << " " << *Var
61 << " LIVE=" << Var->getLiveRange() << " Defs=";
Jim Stichnoth877b04e2014-10-15 15:13:06 -070062 if (const Inst *FirstDef = VMetadata->getFirstDefinition(Var))
63 Str << FirstDef->getNumber();
64 const InstDefList &Defs = VMetadata->getLatterDefinitions(Var);
Jim Stichnothad403532014-09-25 12:44:17 -070065 for (size_t i = 0; i < Defs.size(); ++i) {
Jim Stichnoth877b04e2014-10-15 15:13:06 -070066 Str << "," << Defs[i]->getNumber();
Jim Stichnothad403532014-09-25 12:44:17 -070067 }
68 Str << "\n";
69 }
70}
71
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070072void dumpLiveRange(const Variable *Var, const Cfg *Func) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -070073 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -080074 return;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070075 Ostream &Str = Func->getContext()->getStrDump();
Jim Stichnotha3f57b92015-07-30 12:46:04 -070076 char buf[30];
77 snprintf(buf, llvm::array_lengthof(buf), "%2d", Var->getRegNumTmp());
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -070078 Str << "R=" << buf << " V=";
79 Var->dump(Func);
80 Str << " Range=" << Var->getLiveRange();
Jim Stichnothe22f8232014-10-13 16:20:59 -070081}
82
Jim Stichnothad403532014-09-25 12:44:17 -070083} // end of anonymous namespace
84
Jim Stichnoth70d0a052014-11-14 15:53:46 -080085// Prepare for full register allocation of all variables. We depend
86// on liveness analysis to have calculated live ranges.
87void LinearScan::initForGlobal() {
Jim Stichnoth87ff3a12014-11-14 10:27:29 -080088 TimerMarker T(TimerStack::TT_initUnhandled, Func);
Jim Stichnoth70d0a052014-11-14 15:53:46 -080089 FindPreference = true;
Jim Stichnotha3f57b92015-07-30 12:46:04 -070090 // For full register allocation, normally we want to enable FindOverlap
91 // (meaning we look for opportunities for two overlapping live ranges to
92 // safely share the same register). However, we disable it for phi-lowering
93 // register allocation since no overlap opportunities should be available and
94 // it's more expensive to look for opportunities.
95 FindOverlap = (Kind != RAK_Phi);
Jim Stichnoth87ff3a12014-11-14 10:27:29 -080096 const VarList &Vars = Func->getVariables();
97 Unhandled.reserve(Vars.size());
Jim Stichnoth4ead35a2014-12-03 20:30:34 -080098 UnhandledPrecolored.reserve(Vars.size());
Jim Stichnoth70d0a052014-11-14 15:53:46 -080099 // Gather the live ranges of all variables and add them to the
100 // Unhandled set.
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800101 for (Variable *Var : Vars) {
102 // Explicitly don't consider zero-weight variables, which are
103 // meant to be spill slots.
Jim Stichnothc6ead202015-02-24 09:30:30 -0800104 if (Var->getWeight().isZero())
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800105 continue;
106 // Don't bother if the variable has a null live range, which means
107 // it was never referenced.
108 if (Var->getLiveRange().isEmpty())
109 continue;
110 Var->untrimLiveRange();
111 Unhandled.push_back(Var);
112 if (Var->hasReg()) {
113 Var->setRegNumTmp(Var->getRegNum());
114 Var->setLiveRangeInfiniteWeight();
115 UnhandledPrecolored.push_back(Var);
116 }
117 }
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800118
119 // Build the (ordered) list of FakeKill instruction numbers.
120 Kills.clear();
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700121 // Phi lowering should not be creating new call instructions, so there should
122 // be no infinite-weight not-yet-colored live ranges that span a call
123 // instruction, hence no need to construct the Kills list.
124 if (Kind == RAK_Phi)
125 return;
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800126 for (CfgNode *Node : Func->getNodes()) {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800127 for (Inst &I : Node->getInsts()) {
128 if (auto Kill = llvm::dyn_cast<InstFakeKill>(&I)) {
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800129 if (!Kill->isDeleted() && !Kill->getLinked()->isDeleted())
Jim Stichnoth29841e82014-12-23 12:26:24 -0800130 Kills.push_back(I.getNumber());
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800131 }
132 }
133 }
134}
135
136// Prepare for very simple register allocation of only infinite-weight
137// Variables while respecting pre-colored Variables. Some properties
138// we take advantage of:
139//
140// * Live ranges of interest consist of a single segment.
141//
142// * Live ranges of interest never span a call instruction.
143//
144// * Phi instructions are not considered because either phis have
145// already been lowered, or they don't contain any pre-colored or
146// infinite-weight Variables.
147//
148// * We don't need to renumber instructions before computing live
149// ranges because all the high-level ICE instructions are deleted
150// prior to lowering, and the low-level instructions are added in
151// monotonically increasing order.
152//
153// * There are no opportunities for register preference or allowing
154// overlap.
155//
156// Some properties we aren't (yet) taking advantage of:
157//
Jim Stichnothe6d24782014-12-19 05:42:24 -0800158// * Because live ranges are a single segment, the Inactive set will
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800159// always be empty, and the live range trimming operation is
160// unnecessary.
161//
162// * Calculating overlap of single-segment live ranges could be
163// optimized a bit.
164void LinearScan::initForInfOnly() {
165 TimerMarker T(TimerStack::TT_initUnhandled, Func);
166 FindPreference = false;
167 FindOverlap = false;
168 SizeT NumVars = 0;
169 const VarList &Vars = Func->getVariables();
170
171 // Iterate across all instructions and record the begin and end of
172 // the live range for each variable that is pre-colored or infinite
173 // weight.
174 std::vector<InstNumberT> LRBegin(Vars.size(), Inst::NumberSentinel);
175 std::vector<InstNumberT> LREnd(Vars.size(), Inst::NumberSentinel);
176 for (CfgNode *Node : Func->getNodes()) {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800177 for (Inst &Inst : Node->getInsts()) {
178 if (Inst.isDeleted())
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800179 continue;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800180 if (const Variable *Var = Inst.getDest()) {
Jim Stichnothc6ead202015-02-24 09:30:30 -0800181 if (Var->hasReg() || Var->getWeight().isInf()) {
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800182 if (LRBegin[Var->getIndex()] == Inst::NumberSentinel) {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800183 LRBegin[Var->getIndex()] = Inst.getNumber();
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800184 ++NumVars;
185 }
186 }
187 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800188 for (SizeT I = 0; I < Inst.getSrcSize(); ++I) {
189 Operand *Src = Inst.getSrc(I);
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800190 SizeT NumVars = Src->getNumVars();
191 for (SizeT J = 0; J < NumVars; ++J) {
192 const Variable *Var = Src->getVar(J);
Jim Stichnothc6ead202015-02-24 09:30:30 -0800193 if (Var->hasReg() || Var->getWeight().isInf())
Jim Stichnoth29841e82014-12-23 12:26:24 -0800194 LREnd[Var->getIndex()] = Inst.getNumber();
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800195 }
196 }
197 }
198 }
199
200 Unhandled.reserve(NumVars);
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800201 UnhandledPrecolored.reserve(NumVars);
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800202 for (SizeT i = 0; i < Vars.size(); ++i) {
203 Variable *Var = Vars[i];
204 if (LRBegin[i] != Inst::NumberSentinel) {
205 assert(LREnd[i] != Inst::NumberSentinel);
206 Unhandled.push_back(Var);
207 Var->resetLiveRange();
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700208 constexpr uint32_t WeightDelta = 1;
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800209 Var->addLiveRange(LRBegin[i], LREnd[i], WeightDelta);
210 Var->untrimLiveRange();
211 if (Var->hasReg()) {
212 Var->setRegNumTmp(Var->getRegNum());
213 Var->setLiveRangeInfiniteWeight();
214 UnhandledPrecolored.push_back(Var);
215 }
216 --NumVars;
217 }
218 }
219 // This isn't actually a fatal condition, but it would be nice to
220 // know if we somehow pre-calculated Unhandled's size wrong.
221 assert(NumVars == 0);
222
223 // Don't build up the list of Kills because we know that no
224 // infinite-weight Variable has a live range spanning a call.
225 Kills.clear();
226}
227
228void LinearScan::init(RegAllocKind Kind) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700229 this->Kind = Kind;
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800230 Unhandled.clear();
231 UnhandledPrecolored.clear();
232 Handled.clear();
233 Inactive.clear();
234 Active.clear();
235
236 switch (Kind) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700237 case RAK_Unknown:
238 llvm::report_fatal_error("Invalid RAK_Unknown");
239 break;
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800240 case RAK_Global:
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700241 case RAK_Phi:
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800242 initForGlobal();
243 break;
244 case RAK_InfOnly:
245 initForInfOnly();
246 break;
247 }
248
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800249 struct CompareRanges {
250 bool operator()(const Variable *L, const Variable *R) {
251 InstNumberT Lstart = L->getLiveRange().getStart();
252 InstNumberT Rstart = R->getLiveRange().getStart();
253 if (Lstart == Rstart)
254 return L->getIndex() < R->getIndex();
255 return Lstart < Rstart;
256 }
257 };
258 // Do a reverse sort so that erasing elements (from the end) is fast.
259 std::sort(Unhandled.rbegin(), Unhandled.rend(), CompareRanges());
260 std::sort(UnhandledPrecolored.rbegin(), UnhandledPrecolored.rend(),
261 CompareRanges());
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800262
263 Handled.reserve(Unhandled.size());
264 Inactive.reserve(Unhandled.size());
265 Active.reserve(Unhandled.size());
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800266}
267
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700268// This is called when Cur must be allocated a register but no registers are
269// available across Cur's live range. To handle this, we find a register that
270// is not explicitly used during Cur's live range, spill that register to a
271// stack location right before Cur's live range begins, and fill (reload) the
272// register from the stack location right after Cur's live range ends.
273void LinearScan::addSpillFill(Variable *Cur, llvm::SmallBitVector RegMask) {
274 // Identify the actual instructions that begin and end Cur's live range.
275 // Iterate through Cur's node's instruction list until we find the actual
276 // instructions with instruction numbers corresponding to Cur's recorded live
277 // range endpoints. This sounds inefficient but shouldn't be a problem in
278 // practice because:
279 // (1) This function is almost never called in practice.
280 // (2) Since this register over-subscription problem happens only for
281 // phi-lowered instructions, the number of instructions in the node is
282 // proportional to the number of phi instructions in the original node,
283 // which is never very large in practice.
284 // (3) We still have to iterate through all instructions of Cur's live range
285 // to find all explicitly used registers (though the live range is usually
286 // only 2-3 instructions), so the main cost that could be avoided would be
287 // finding the instruction that begin's Cur's live range.
288 assert(!Cur->getLiveRange().isEmpty());
289 InstNumberT Start = Cur->getLiveRange().getStart();
290 InstNumberT End = Cur->getLiveRange().getEnd();
291 CfgNode *Node = Func->getVMetadata()->getLocalUseNode(Cur);
292 assert(Node);
293 InstList &Insts = Node->getInsts();
294 InstList::iterator SpillPoint = Insts.end();
295 InstList::iterator FillPoint = Insts.end();
296 // Stop searching after we have found both the SpillPoint and the FillPoint.
297 for (auto I = Insts.begin(), E = Insts.end();
298 I != E && (SpillPoint == E || FillPoint == E); ++I) {
299 if (I->getNumber() == Start)
300 SpillPoint = I;
301 if (I->getNumber() == End)
302 FillPoint = I;
303 if (SpillPoint != E) {
304 // Remove from RegMask any physical registers referenced during Cur's live
305 // range. Start looking after SpillPoint gets set, i.e. once Cur's live
306 // range begins.
307 for (SizeT i = 0; i < I->getSrcSize(); ++i) {
308 Operand *Src = I->getSrc(i);
309 SizeT NumVars = Src->getNumVars();
310 for (SizeT j = 0; j < NumVars; ++j) {
311 const Variable *Var = Src->getVar(j);
312 if (Var->hasRegTmp())
313 RegMask[Var->getRegNumTmp()] = false;
314 }
315 }
316 }
317 }
318 assert(SpillPoint != Insts.end());
319 assert(FillPoint != Insts.end());
320 ++FillPoint;
321 // TODO(stichnot): Randomize instead of find_first().
322 int32_t RegNum = RegMask.find_first();
323 assert(RegNum != -1);
324 Cur->setRegNumTmp(RegNum);
325 TargetLowering *Target = Func->getTarget();
326 Variable *Preg = Target->getPhysicalRegister(RegNum, Cur->getType());
327 // TODO(stichnot): Add SpillLoc to VariablesMetadata tracking so that SpillLoc
328 // is correctly identified as !isMultiBlock(), reducing stack frame size.
329 Variable *SpillLoc = Func->makeVariable(Cur->getType());
330 // Add "reg=FakeDef;spill=reg" before SpillPoint
331 Target->lowerInst(Node, SpillPoint, InstFakeDef::create(Func, Preg));
332 Target->lowerInst(Node, SpillPoint, InstAssign::create(Func, SpillLoc, Preg));
333 // add "reg=spill;FakeUse(reg)" before FillPoint
334 Target->lowerInst(Node, FillPoint, InstAssign::create(Func, Preg, SpillLoc));
335 Target->lowerInst(Node, FillPoint, InstFakeUse::create(Func, Preg));
336}
337
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700338// Implements the linear-scan algorithm. Based on "Linear Scan
339// Register Allocation in the Context of SSA Form and Register
340// Constraints" by Hanspeter Mössenböck and Michael Pfeiffer,
341// ftp://ftp.ssw.uni-linz.ac.at/pub/Papers/Moe02.PDF . This
342// implementation is modified to take affinity into account and allow
343// two interfering variables to share the same register in certain
344// cases.
345//
Jim Stichnoth800dab22014-09-20 12:25:02 -0700346// Requires running Cfg::liveness(Liveness_Intervals) in
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700347// preparation. Results are assigned to Variable::RegNum for each
348// Variable.
Jim Stichnothe6d24782014-12-19 05:42:24 -0800349void LinearScan::scan(const llvm::SmallBitVector &RegMaskFull,
350 bool Randomized) {
Jim Stichnoth8363a062014-10-07 10:02:38 -0700351 TimerMarker T(TimerStack::TT_linearScan, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700352 assert(RegMaskFull.any()); // Sanity check
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800353 GlobalContext *Ctx = Func->getContext();
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700354 const bool Verbose = BuildDefs::dump() && Func->isVerbose(IceV_LinearScan);
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800355 if (Verbose)
356 Ctx->lockStr();
Jim Stichnoth800dab22014-09-20 12:25:02 -0700357 Func->resetCurrentNode();
Jim Stichnothad403532014-09-25 12:44:17 -0700358 VariablesMetadata *VMetadata = Func->getVMetadata();
Jim Stichnothe6d24782014-12-19 05:42:24 -0800359 const size_t NumRegisters = RegMaskFull.size();
360 llvm::SmallBitVector PreDefinedRegisters(NumRegisters);
361 if (Randomized) {
362 for (Variable *Var : UnhandledPrecolored) {
363 PreDefinedRegisters[Var->getRegNum()] = true;
364 }
365 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700366
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800367 // Build a LiveRange representing the Kills list.
Jim Stichnoth2a7fcbb2014-12-04 11:45:03 -0800368 LiveRange KillsRange(Kills);
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800369 KillsRange.untrim();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700370
371 // RegUses[I] is the number of live ranges (variables) that register
372 // I is currently assigned to. It can be greater than 1 as a result
Jim Stichnothc4554d72014-09-30 16:49:38 -0700373 // of AllowOverlap inference below.
Jim Stichnothe34d79d2015-01-12 09:00:50 -0800374 llvm::SmallVector<int, REGS_SIZE> RegUses(NumRegisters);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700375 // Unhandled is already set to all ranges in increasing order of
376 // start points.
377 assert(Active.empty());
378 assert(Inactive.empty());
379 assert(Handled.empty());
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800380 const TargetLowering::RegSetMask RegsInclude =
381 TargetLowering::RegSet_CallerSave;
382 const TargetLowering::RegSetMask RegsExclude = TargetLowering::RegSet_None;
383 const llvm::SmallBitVector KillsMask =
384 Func->getTarget()->getRegisterSet(RegsInclude, RegsExclude);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700385
386 while (!Unhandled.empty()) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700387 Variable *Cur = Unhandled.back();
Jim Stichnothe22f8232014-10-13 16:20:59 -0700388 Unhandled.pop_back();
Jim Stichnothc4554d72014-09-30 16:49:38 -0700389 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800390 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700391 Str << "\nConsidering ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700392 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700393 Str << "\n";
394 }
395 const llvm::SmallBitVector RegMask =
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700396 RegMaskFull & Func->getTarget()->getRegisterSetForType(Cur->getType());
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800397 KillsRange.trim(Cur->getLiveRange().getStart());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700398
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700399 // Check for pre-colored ranges. If Cur is pre-colored, it
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700400 // definitely gets that register. Previously processed live
401 // ranges would have avoided that register due to it being
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700402 // pre-colored. Future processed live ranges won't evict that
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700403 // register because the live range has infinite weight.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700404 if (Cur->hasReg()) {
405 int32_t RegNum = Cur->getRegNum();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700406 // RegNumTmp should have already been set above.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700407 assert(Cur->getRegNumTmp() == RegNum);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700408 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800409 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700410 Str << "Precoloring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700411 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700412 Str << "\n";
413 }
414 Active.push_back(Cur);
415 assert(RegUses[RegNum] >= 0);
416 ++RegUses[RegNum];
Jim Stichnoth541ba662014-10-02 12:58:21 -0700417 assert(!UnhandledPrecolored.empty());
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700418 assert(UnhandledPrecolored.back() == Cur);
Jim Stichnothe22f8232014-10-13 16:20:59 -0700419 UnhandledPrecolored.pop_back();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700420 continue;
421 }
422
423 // Check for active ranges that have expired or become inactive.
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800424 for (SizeT I = Active.size(); I > 0; --I) {
425 const SizeT Index = I - 1;
426 Variable *Item = Active[Index];
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700427 Item->trimLiveRange(Cur->getLiveRange().getStart());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700428 bool Moved = false;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700429 if (Item->rangeEndsBefore(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700430 // Move Item from Active to Handled list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700431 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800432 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700433 Str << "Expiring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700434 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700435 Str << "\n";
436 }
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800437 moveItem(Active, Index, Handled);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700438 Moved = true;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700439 } else if (!Item->rangeOverlapsStart(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700440 // Move Item from Active to Inactive list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700441 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800442 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700443 Str << "Inactivating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700444 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700445 Str << "\n";
446 }
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800447 moveItem(Active, Index, Inactive);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700448 Moved = true;
449 }
450 if (Moved) {
451 // Decrement Item from RegUses[].
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700452 assert(Item->hasRegTmp());
453 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700454 --RegUses[RegNum];
455 assert(RegUses[RegNum] >= 0);
456 }
457 }
458
459 // Check for inactive ranges that have expired or reactivated.
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800460 for (SizeT I = Inactive.size(); I > 0; --I) {
461 const SizeT Index = I - 1;
462 Variable *Item = Inactive[Index];
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700463 Item->trimLiveRange(Cur->getLiveRange().getStart());
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700464 if (Item->rangeEndsBefore(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700465 // Move Item from Inactive to Handled list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700466 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800467 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700468 Str << "Expiring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700469 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700470 Str << "\n";
471 }
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800472 moveItem(Inactive, Index, Handled);
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700473 } else if (Item->rangeOverlapsStart(Cur)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700474 // Move Item from Inactive to Active list.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700475 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800476 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700477 Str << "Reactivating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700478 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700479 Str << "\n";
480 }
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800481 moveItem(Inactive, Index, Active);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700482 // Increment Item in RegUses[].
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700483 assert(Item->hasRegTmp());
484 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700485 assert(RegUses[RegNum] >= 0);
486 ++RegUses[RegNum];
487 }
488 }
489
490 // Calculate available registers into Free[].
491 llvm::SmallBitVector Free = RegMask;
492 for (SizeT i = 0; i < RegMask.size(); ++i) {
493 if (RegUses[i] > 0)
494 Free[i] = false;
495 }
496
Jim Stichnothad403532014-09-25 12:44:17 -0700497 // Infer register preference and allowable overlap. Only form a
498 // preference when the current Variable has an unambiguous "first"
499 // definition. The preference is some source Variable of the
500 // defining instruction that either is assigned a register that is
501 // currently free, or that is assigned a register that is not free
502 // but overlap is allowed. Overlap is allowed when the Variable
503 // under consideration is single-definition, and its definition is
504 // a simple assignment - i.e., the register gets copied/aliased
505 // but is never modified. Furthermore, overlap is only allowed
506 // when preferred Variable definition instructions do not appear
507 // within the current Variable's live range.
Jim Stichnothae953202014-12-20 06:17:49 -0800508 Variable *Prefer = nullptr;
Jim Stichnothad403532014-09-25 12:44:17 -0700509 int32_t PreferReg = Variable::NoRegister;
510 bool AllowOverlap = false;
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800511 if (FindPreference) {
512 if (const Inst *DefInst = VMetadata->getFirstDefinition(Cur)) {
513 assert(DefInst->getDest() == Cur);
514 bool IsAssign = DefInst->isSimpleAssign();
515 bool IsSingleDef = !VMetadata->isMultiDef(Cur);
516 for (SizeT i = 0; i < DefInst->getSrcSize(); ++i) {
517 // TODO(stichnot): Iterate through the actual Variables of the
518 // instruction, not just the source operands. This could
519 // capture Load instructions, including address mode
520 // optimization, for Prefer (but not for AllowOverlap).
521 if (Variable *SrcVar = llvm::dyn_cast<Variable>(DefInst->getSrc(i))) {
522 int32_t SrcReg = SrcVar->getRegNumTmp();
523 // Only consider source variables that have (so far) been
524 // assigned a register. That register must be one in the
525 // RegMask set, e.g. don't try to prefer the stack pointer
526 // as a result of the stacksave intrinsic.
527 if (SrcVar->hasRegTmp() && RegMask[SrcReg]) {
528 if (FindOverlap && !Free[SrcReg]) {
529 // Don't bother trying to enable AllowOverlap if the
530 // register is already free.
531 AllowOverlap =
532 IsSingleDef && IsAssign && !overlapsDefs(Func, Cur, SrcVar);
533 }
534 if (AllowOverlap || Free[SrcReg]) {
535 Prefer = SrcVar;
536 PreferReg = SrcReg;
537 }
Jim Stichnothad403532014-09-25 12:44:17 -0700538 }
539 }
540 }
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800541 if (Verbose && Prefer) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800542 Ostream &Str = Ctx->getStrDump();
Jim Stichnoth9a04c072014-12-11 15:51:42 -0800543 Str << "Initial Prefer=";
544 Prefer->dump(Func);
545 Str << " R=" << PreferReg << " LIVE=" << Prefer->getLiveRange()
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800546 << " Overlap=" << AllowOverlap << "\n";
547 }
Jim Stichnothad403532014-09-25 12:44:17 -0700548 }
549 }
550
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700551 // Remove registers from the Free[] list where an Inactive range
552 // overlaps with the current range.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700553 for (const Variable *Item : Inactive) {
554 if (Item->rangeOverlaps(Cur)) {
555 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700556 // Don't assert(Free[RegNum]) because in theory (though
557 // probably never in practice) there could be two inactive
Jim Stichnothc4554d72014-09-30 16:49:38 -0700558 // variables that were marked with AllowOverlap.
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700559 Free[RegNum] = false;
Jim Stichnothad403532014-09-25 12:44:17 -0700560 // Disable AllowOverlap if an Inactive variable, which is not
561 // Prefer, shares Prefer's register, and has a definition
562 // within Cur's live range.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700563 if (AllowOverlap && Item != Prefer && RegNum == PreferReg &&
564 overlapsDefs(Func, Cur, Item)) {
Jim Stichnothad403532014-09-25 12:44:17 -0700565 AllowOverlap = false;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700566 dumpDisableOverlap(Func, Item, "Inactive");
Jim Stichnothad403532014-09-25 12:44:17 -0700567 }
568 }
569 }
570
571 // Disable AllowOverlap if an Active variable, which is not
572 // Prefer, shares Prefer's register, and has a definition within
573 // Cur's live range.
Jim Stichnoth70d0a052014-11-14 15:53:46 -0800574 if (AllowOverlap) {
575 for (const Variable *Item : Active) {
576 int32_t RegNum = Item->getRegNumTmp();
577 if (Item != Prefer && RegNum == PreferReg &&
578 overlapsDefs(Func, Cur, Item)) {
579 AllowOverlap = false;
580 dumpDisableOverlap(Func, Item, "Active");
581 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700582 }
583 }
584
Jim Stichnothe34d79d2015-01-12 09:00:50 -0800585 llvm::SmallVector<RegWeight, REGS_SIZE> Weights(RegMask.size());
Jim Stichnoth541ba662014-10-02 12:58:21 -0700586
587 // Remove registers from the Free[] list where an Unhandled
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700588 // pre-colored range overlaps with the current range, and set those
Jim Stichnoth541ba662014-10-02 12:58:21 -0700589 // registers to infinite weight so that they aren't candidates for
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700590 // eviction. Cur->rangeEndsBefore(Item) is an early exit check
591 // that turns a guaranteed O(N^2) algorithm into expected linear
Jim Stichnoth541ba662014-10-02 12:58:21 -0700592 // complexity.
593 llvm::SmallBitVector PrecoloredUnhandledMask(RegMask.size());
594 // Note: PrecoloredUnhandledMask is only used for dumping.
Jim Stichnoth7e571362015-01-09 11:43:26 -0800595 for (Variable *Item : reverse_range(UnhandledPrecolored)) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700596 assert(Item->hasReg());
597 if (Cur->rangeEndsBefore(Item))
Jim Stichnothf44f3712014-10-01 14:05:51 -0700598 break;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700599 if (Item->rangeOverlaps(Cur)) {
600 int32_t ItemReg = Item->getRegNum(); // Note: not getRegNumTmp()
Jim Stichnoth541ba662014-10-02 12:58:21 -0700601 Weights[ItemReg].setWeight(RegWeight::Inf);
Jim Stichnothad403532014-09-25 12:44:17 -0700602 Free[ItemReg] = false;
Jim Stichnoth541ba662014-10-02 12:58:21 -0700603 PrecoloredUnhandledMask[ItemReg] = true;
Jim Stichnothad403532014-09-25 12:44:17 -0700604 // Disable AllowOverlap if the preferred register is one of
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700605 // these pre-colored unhandled overlapping ranges.
Jim Stichnothad403532014-09-25 12:44:17 -0700606 if (AllowOverlap && ItemReg == PreferReg) {
607 AllowOverlap = false;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700608 dumpDisableOverlap(Func, Item, "PrecoloredUnhandled");
Jim Stichnothad403532014-09-25 12:44:17 -0700609 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700610 }
611 }
612
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800613 // Remove scratch registers from the Free[] list, and mark their
614 // Weights[] as infinite, if KillsRange overlaps Cur's live range.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700615 constexpr bool UseTrimmed = true;
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800616 if (Cur->getLiveRange().overlaps(KillsRange, UseTrimmed)) {
617 Free.reset(KillsMask);
618 for (int i = KillsMask.find_first(); i != -1;
619 i = KillsMask.find_next(i)) {
620 Weights[i].setWeight(RegWeight::Inf);
621 if (PreferReg == i)
622 AllowOverlap = false;
623 }
624 }
625
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700626 // Print info about physical register availability.
Jim Stichnothc4554d72014-09-30 16:49:38 -0700627 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800628 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700629 for (SizeT i = 0; i < RegMask.size(); ++i) {
630 if (RegMask[i]) {
631 Str << Func->getTarget()->getRegName(i, IceType_i32)
Jim Stichnothca662e92014-07-10 15:32:36 -0700632 << "(U=" << RegUses[i] << ",F=" << Free[i]
Jim Stichnoth541ba662014-10-02 12:58:21 -0700633 << ",P=" << PrecoloredUnhandledMask[i] << ") ";
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700634 }
635 }
636 Str << "\n";
637 }
638
Jim Stichnothad403532014-09-25 12:44:17 -0700639 if (Prefer && (AllowOverlap || Free[PreferReg])) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700640 // First choice: a preferred register that is either free or is
641 // allowed to overlap with its linked variable.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700642 Cur->setRegNumTmp(PreferReg);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700643 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800644 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700645 Str << "Preferring ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700646 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700647 Str << "\n";
648 }
649 assert(RegUses[PreferReg] >= 0);
650 ++RegUses[PreferReg];
651 Active.push_back(Cur);
652 } else if (Free.any()) {
653 // Second choice: any free register. TODO: After explicit
654 // affinity is considered, is there a strategy better than just
655 // picking the lowest-numbered available register?
656 int32_t RegNum = Free.find_first();
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700657 Cur->setRegNumTmp(RegNum);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700658 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800659 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700660 Str << "Allocating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700661 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700662 Str << "\n";
663 }
664 assert(RegUses[RegNum] >= 0);
665 ++RegUses[RegNum];
666 Active.push_back(Cur);
667 } else {
668 // Fallback: there are no free registers, so we look for the
669 // lowest-weight register and see if Cur has higher weight.
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700670 // Check Active ranges.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700671 for (const Variable *Item : Active) {
672 assert(Item->rangeOverlaps(Cur));
673 int32_t RegNum = Item->getRegNumTmp();
674 assert(Item->hasRegTmp());
675 Weights[RegNum].addWeight(Item->getLiveRange().getWeight());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700676 }
677 // Same as above, but check Inactive ranges instead of Active.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700678 for (const Variable *Item : Inactive) {
679 int32_t RegNum = Item->getRegNumTmp();
680 assert(Item->hasRegTmp());
681 if (Item->rangeOverlaps(Cur))
682 Weights[RegNum].addWeight(Item->getLiveRange().getWeight());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700683 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700684
685 // All the weights are now calculated. Find the register with
686 // smallest weight.
687 int32_t MinWeightIndex = RegMask.find_first();
688 // MinWeightIndex must be valid because of the initial
689 // RegMask.any() test.
690 assert(MinWeightIndex >= 0);
691 for (SizeT i = MinWeightIndex + 1; i < Weights.size(); ++i) {
692 if (RegMask[i] && Weights[i] < Weights[MinWeightIndex])
693 MinWeightIndex = i;
694 }
695
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700696 if (Cur->getLiveRange().getWeight() <= Weights[MinWeightIndex]) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700697 // Cur doesn't have priority over any other live ranges, so
698 // don't allocate any register to it, and move it to the
699 // Handled state.
700 Handled.push_back(Cur);
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700701 if (Cur->getLiveRange().getWeight().isInf()) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700702 if (Kind == RAK_Phi)
703 addSpillFill(Cur, RegMask);
704 else
705 Func->setError("Unable to find a physical register for an "
706 "infinite-weight live range");
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700707 }
708 } else {
709 // Evict all live ranges in Active that register number
710 // MinWeightIndex is assigned to.
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800711 for (SizeT I = Active.size(); I > 0; --I) {
712 const SizeT Index = I - 1;
713 Variable *Item = Active[Index];
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700714 if (Item->getRegNumTmp() == MinWeightIndex) {
Jim Stichnothc4554d72014-09-30 16:49:38 -0700715 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800716 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700717 Str << "Evicting ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700718 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700719 Str << "\n";
720 }
721 --RegUses[MinWeightIndex];
722 assert(RegUses[MinWeightIndex] >= 0);
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700723 Item->setRegNumTmp(Variable::NoRegister);
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800724 moveItem(Active, Index, Handled);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700725 }
726 }
727 // Do the same for Inactive.
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800728 for (SizeT I = Inactive.size(); I > 0; --I) {
729 const SizeT Index = I - 1;
730 Variable *Item = Inactive[Index];
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700731 // Note: The Item->rangeOverlaps(Cur) clause is not part of the
Jim Stichnoth68e28192014-07-24 08:48:15 -0700732 // description of AssignMemLoc() in the original paper. But
733 // there doesn't seem to be any need to evict an inactive
734 // live range that doesn't overlap with the live range
735 // currently being considered. It's especially bad if we
736 // would end up evicting an infinite-weight but
737 // currently-inactive live range. The most common situation
738 // for this would be a scratch register kill set for call
739 // instructions.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700740 if (Item->getRegNumTmp() == MinWeightIndex &&
741 Item->rangeOverlaps(Cur)) {
Jim Stichnothc4554d72014-09-30 16:49:38 -0700742 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800743 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700744 Str << "Evicting ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700745 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700746 Str << "\n";
747 }
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700748 Item->setRegNumTmp(Variable::NoRegister);
Jim Stichnoth4ead35a2014-12-03 20:30:34 -0800749 moveItem(Inactive, Index, Handled);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700750 }
751 }
752 // Assign the register to Cur.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700753 Cur->setRegNumTmp(MinWeightIndex);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700754 assert(RegUses[MinWeightIndex] >= 0);
755 ++RegUses[MinWeightIndex];
756 Active.push_back(Cur);
Jim Stichnothc4554d72014-09-30 16:49:38 -0700757 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800758 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700759 Str << "Allocating ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700760 dumpLiveRange(Cur, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700761 Str << "\n";
762 }
763 }
764 }
765 dump(Func);
766 }
767 // Move anything Active or Inactive to Handled for easier handling.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700768 for (Variable *I : Active)
Jim Stichnothf44f3712014-10-01 14:05:51 -0700769 Handled.push_back(I);
770 Active.clear();
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700771 for (Variable *I : Inactive)
Jim Stichnothf44f3712014-10-01 14:05:51 -0700772 Handled.push_back(I);
773 Inactive.clear();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700774 dump(Func);
775
Jim Stichnothe6d24782014-12-19 05:42:24 -0800776 llvm::SmallVector<int32_t, REGS_SIZE> Permutation(NumRegisters);
777 if (Randomized) {
778 Func->getTarget()->makeRandomRegisterPermutation(
779 Permutation, PreDefinedRegisters | ~RegMaskFull);
780 }
781
782 // Finish up by assigning RegNumTmp->RegNum (or a random permutation
783 // thereof) for each Variable.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700784 for (Variable *Item : Handled) {
785 int32_t RegNum = Item->getRegNumTmp();
Jim Stichnothe6d24782014-12-19 05:42:24 -0800786 int32_t AssignedRegNum = RegNum;
787
788 if (Randomized && Item->hasRegTmp() && !Item->hasReg()) {
789 AssignedRegNum = Permutation[RegNum];
790 }
Jim Stichnothc4554d72014-09-30 16:49:38 -0700791 if (Verbose) {
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800792 Ostream &Str = Ctx->getStrDump();
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700793 if (!Item->hasRegTmp()) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700794 Str << "Not assigning ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700795 Item->dump(Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700796 Str << "\n";
797 } else {
Jim Stichnothe6d24782014-12-19 05:42:24 -0800798 Str << (AssignedRegNum == Item->getRegNum() ? "Reassigning "
799 : "Assigning ")
800 << Func->getTarget()->getRegName(AssignedRegNum, IceType_i32)
801 << "(r" << AssignedRegNum << ") to ";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700802 Item->dump(Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700803 Str << "\n";
804 }
805 }
Jim Stichnothe6d24782014-12-19 05:42:24 -0800806 Item->setRegNum(AssignedRegNum);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700807 }
808
809 // TODO: Consider running register allocation one more time, with
810 // infinite registers, for two reasons. First, evicted live ranges
811 // get a second chance for a register. Second, it allows coalescing
812 // of stack slots. If there is no time budget for the second
813 // register allocation run, each unallocated variable just gets its
814 // own slot.
815 //
816 // Another idea for coalescing stack slots is to initialize the
817 // Unhandled list with just the unallocated variables, saving time
818 // but not offering second-chance opportunities.
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800819
820 if (Verbose)
821 Ctx->unlockStr();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700822}
823
824// ======================== Dump routines ======================== //
825
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700826void LinearScan::dump(Cfg *Func) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700827 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800828 return;
Jim Stichnothfa4efea2015-01-27 05:06:03 -0800829 if (!Func->isVerbose(IceV_LinearScan))
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700830 return;
Jim Stichnothe4a8f402015-01-20 12:52:51 -0800831 Ostream &Str = Func->getContext()->getStrDump();
Jim Stichnoth800dab22014-09-20 12:25:02 -0700832 Func->resetCurrentNode();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700833 Str << "**** Current regalloc state:\n";
834 Str << "++++++ Handled:\n";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700835 for (const Variable *Item : Handled) {
836 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700837 Str << "\n";
838 }
839 Str << "++++++ Unhandled:\n";
Jim Stichnoth7e571362015-01-09 11:43:26 -0800840 for (const Variable *Item : reverse_range(Unhandled)) {
841 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700842 Str << "\n";
843 }
844 Str << "++++++ Active:\n";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700845 for (const Variable *Item : Active) {
846 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700847 Str << "\n";
848 }
849 Str << "++++++ Inactive:\n";
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700850 for (const Variable *Item : Inactive) {
851 dumpLiveRange(Item, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700852 Str << "\n";
853 }
854}
855
856} // end of namespace Ice