1//===- RegAllocGreedy.cpp - greedy register allocator ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the RAGreedy function pass for register allocation in
10// optimized builds.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RegAllocGreedy.h"
15#include "AllocationOrder.h"
16#include "InterferenceCache.h"
17#include "RegAllocBase.h"
18#include "SplitKit.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/IndexedMap.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/Analysis/OptimizationRemarkEmitter.h"
27#include "llvm/CodeGen/CalcSpillWeights.h"
28#include "llvm/CodeGen/EdgeBundles.h"
29#include "llvm/CodeGen/LiveDebugVariables.h"
30#include "llvm/CodeGen/LiveInterval.h"
31#include "llvm/CodeGen/LiveIntervalUnion.h"
32#include "llvm/CodeGen/LiveIntervals.h"
33#include "llvm/CodeGen/LiveRangeEdit.h"
34#include "llvm/CodeGen/LiveRegMatrix.h"
35#include "llvm/CodeGen/LiveStacks.h"
36#include "llvm/CodeGen/MachineBasicBlock.h"
37#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
38#include "llvm/CodeGen/MachineDominators.h"
39#include "llvm/CodeGen/MachineFrameInfo.h"
40#include "llvm/CodeGen/MachineFunction.h"
41#include "llvm/CodeGen/MachineFunctionPass.h"
42#include "llvm/CodeGen/MachineInstr.h"
43#include "llvm/CodeGen/MachineLoopInfo.h"
44#include "llvm/CodeGen/MachineOperand.h"
45#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
46#include "llvm/CodeGen/MachinePassManager.h"
47#include "llvm/CodeGen/MachineRegisterInfo.h"
48#include "llvm/CodeGen/RegAllocEvictionAdvisor.h"
49#include "llvm/CodeGen/RegAllocGreedyPass.h"
50#include "llvm/CodeGen/RegAllocPriorityAdvisor.h"
51#include "llvm/CodeGen/RegAllocRegistry.h"
52#include "llvm/CodeGen/RegisterClassInfo.h"
53#include "llvm/CodeGen/SlotIndexes.h"
54#include "llvm/CodeGen/SpillPlacement.h"
55#include "llvm/CodeGen/Spiller.h"
56#include "llvm/CodeGen/TargetInstrInfo.h"
57#include "llvm/CodeGen/TargetRegisterInfo.h"
58#include "llvm/CodeGen/TargetSubtargetInfo.h"
59#include "llvm/CodeGen/VirtRegMap.h"
60#include "llvm/IR/Analysis.h"
61#include "llvm/IR/DebugInfoMetadata.h"
62#include "llvm/IR/Function.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/PassTimingInfo.h"
65#include "llvm/Pass.h"
66#include "llvm/Support/BlockFrequency.h"
67#include "llvm/Support/BranchProbability.h"
68#include "llvm/Support/CommandLine.h"
69#include "llvm/Support/Debug.h"
70#include "llvm/Support/MathExtras.h"
71#include "llvm/Support/Timer.h"
72#include "llvm/Support/raw_ostream.h"
73#include <algorithm>
74#include <cassert>
75#include <cstdint>
76#include <utility>
77
78using namespace llvm;
79
80#define DEBUG_TYPE "regalloc"
81
82STATISTIC(NumGlobalSplits, "Number of split global live ranges");
83STATISTIC(NumLocalSplits, "Number of split local live ranges");
84STATISTIC(NumEvicted, "Number of interferences evicted");
85
86static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
87 "split-spill-mode", cl::Hidden,
88 cl::desc("Spill mode for splitting live ranges"),
89 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
90 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
91 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
92 cl::init(Val: SplitEditor::SM_Speed));
93
94static cl::opt<unsigned>
95LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
96 cl::desc("Last chance recoloring max depth"),
97 cl::init(Val: 5));
98
99static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
100 "lcr-max-interf", cl::Hidden,
101 cl::desc("Last chance recoloring maximum number of considered"
102 " interference at a time"),
103 cl::init(Val: 8));
104
105static cl::opt<bool> ExhaustiveSearch(
106 "exhaustive-register-search", cl::NotHidden,
107 cl::desc("Exhaustive Search for registers bypassing the depth "
108 "and interference cutoffs of last chance recoloring"),
109 cl::Hidden);
110
111// This option should be deprecated!
112// FIXME: Find a good default for this flag and remove the flag.
113static cl::opt<unsigned>
114CSRFirstTimeCost("regalloc-csr-first-time-cost",
115 cl::desc("Cost for first time use of callee-saved register."),
116 cl::init(Val: 0), cl::Hidden);
117
118static cl::opt<unsigned> CSRCostScale(
119 "regalloc-csr-cost-scale",
120 cl::desc("Scale for the callee-saved register cost, in percentage."),
121 cl::init(Val: 80), cl::Hidden);
122
123static cl::opt<unsigned long> GrowRegionComplexityBudget(
124 "grow-region-complexity-budget",
125 cl::desc("growRegion() does not scale with the number of BB edges, so "
126 "limit its budget and bail out once we reach the limit."),
127 cl::init(Val: 10000), cl::Hidden);
128
129static cl::opt<bool> GreedyRegClassPriorityTrumpsGlobalness(
130 "greedy-regclass-priority-trumps-globalness",
131 cl::desc("Change the greedy register allocator's live range priority "
132 "calculation to make the AllocationPriority of the register class "
133 "more important then whether the range is global"),
134 cl::Hidden);
135
136static cl::opt<bool> GreedyReverseLocalAssignment(
137 "greedy-reverse-local-assignment",
138 cl::desc("Reverse allocation order of local live ranges, such that "
139 "shorter local live ranges will tend to be allocated first"),
140 cl::Hidden);
141
142static cl::opt<unsigned> SplitThresholdForRegWithHint(
143 "split-threshold-for-reg-with-hint",
144 cl::desc("The threshold for splitting a virtual register with a hint, in "
145 "percentage"),
146 cl::init(Val: 75), cl::Hidden);
147
148static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
149 createGreedyRegisterAllocator);
150
151namespace {
152class RAGreedyLegacy : public MachineFunctionPass {
153 RegAllocFilterFunc F;
154
155public:
156 RAGreedyLegacy(const RegAllocFilterFunc F = nullptr);
157
158 static char ID;
159 /// Return the pass name.
160 StringRef getPassName() const override { return "Greedy Register Allocator"; }
161
162 /// RAGreedy analysis usage.
163 void getAnalysisUsage(AnalysisUsage &AU) const override;
164 /// Perform register allocation.
165 bool runOnMachineFunction(MachineFunction &mf) override;
166
167 MachineFunctionProperties getRequiredProperties() const override {
168 return MachineFunctionProperties().setNoPHIs();
169 }
170
171 MachineFunctionProperties getClearedProperties() const override {
172 return MachineFunctionProperties().setIsSSA();
173 }
174};
175
176} // end anonymous namespace
177
178RAGreedyLegacy::RAGreedyLegacy(const RegAllocFilterFunc F)
179 : MachineFunctionPass(ID), F(std::move(F)) {}
180
181struct RAGreedy::RequiredAnalyses {
182 VirtRegMap *VRM = nullptr;
183 LiveIntervals *LIS = nullptr;
184 LiveRegMatrix *LRM = nullptr;
185 SlotIndexes *Indexes = nullptr;
186 MachineBlockFrequencyInfo *MBFI = nullptr;
187 MachineDominatorTree *DomTree = nullptr;
188 MachineLoopInfo *Loops = nullptr;
189 MachineOptimizationRemarkEmitter *ORE = nullptr;
190 EdgeBundles *Bundles = nullptr;
191 SpillPlacement *SpillPlacer = nullptr;
192 LiveDebugVariables *DebugVars = nullptr;
193
194 // Used by InlineSpiller
195 LiveStacks *LSS;
196 // Proxies for eviction and priority advisors
197 RegAllocEvictionAdvisorProvider *EvictProvider;
198 RegAllocPriorityAdvisorProvider *PriorityProvider;
199
200 RequiredAnalyses() = delete;
201 RequiredAnalyses(Pass &P);
202 RequiredAnalyses(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM);
203};
204
205RAGreedy::RAGreedy(RequiredAnalyses &Analyses, const RegAllocFilterFunc F)
206 : RegAllocBase(F) {
207 VRM = Analyses.VRM;
208 LIS = Analyses.LIS;
209 Matrix = Analyses.LRM;
210 Indexes = Analyses.Indexes;
211 MBFI = Analyses.MBFI;
212 DomTree = Analyses.DomTree;
213 Loops = Analyses.Loops;
214 ORE = Analyses.ORE;
215 Bundles = Analyses.Bundles;
216 SpillPlacer = Analyses.SpillPlacer;
217 DebugVars = Analyses.DebugVars;
218 LSS = Analyses.LSS;
219 EvictProvider = Analyses.EvictProvider;
220 PriorityProvider = Analyses.PriorityProvider;
221}
222
223void RAGreedyPass::printPipeline(
224 raw_ostream &OS,
225 function_ref<StringRef(StringRef)> MapClassName2PassName) const {
226 StringRef FilterName = Opts.FilterName.empty() ? "all" : Opts.FilterName;
227 OS << "greedy<" << FilterName << '>';
228}
229
230RAGreedy::RequiredAnalyses::RequiredAnalyses(
231 MachineFunction &MF, MachineFunctionAnalysisManager &MFAM) {
232 LIS = &MFAM.getResult<LiveIntervalsAnalysis>(IR&: MF);
233 LRM = &MFAM.getResult<LiveRegMatrixAnalysis>(IR&: MF);
234 LSS = &MFAM.getResult<LiveStacksAnalysis>(IR&: MF);
235 Indexes = &MFAM.getResult<SlotIndexesAnalysis>(IR&: MF);
236 MBFI = &MFAM.getResult<MachineBlockFrequencyAnalysis>(IR&: MF);
237 DomTree = &MFAM.getResult<MachineDominatorTreeAnalysis>(IR&: MF);
238 ORE = &MFAM.getResult<MachineOptimizationRemarkEmitterAnalysis>(IR&: MF);
239 Loops = &MFAM.getResult<MachineLoopAnalysis>(IR&: MF);
240 Bundles = &MFAM.getResult<EdgeBundlesAnalysis>(IR&: MF);
241 SpillPlacer = &MFAM.getResult<SpillPlacementAnalysis>(IR&: MF);
242 DebugVars = &MFAM.getResult<LiveDebugVariablesAnalysis>(IR&: MF);
243 EvictProvider = MFAM.getResult<RegAllocEvictionAdvisorAnalysis>(IR&: MF).Provider;
244 PriorityProvider =
245 MFAM.getResult<RegAllocPriorityAdvisorAnalysis>(IR&: MF).Provider;
246 VRM = &MFAM.getResult<VirtRegMapAnalysis>(IR&: MF);
247}
248
249PreservedAnalyses RAGreedyPass::run(MachineFunction &MF,
250 MachineFunctionAnalysisManager &MFAM) {
251 MFPropsModifier _(*this, MF);
252
253 RAGreedy::RequiredAnalyses Analyses(MF, MFAM);
254 RAGreedy Impl(Analyses, Opts.Filter);
255
256 bool Changed = Impl.run(mf&: MF);
257 if (!Changed)
258 return PreservedAnalyses::all();
259 auto PA = getMachineFunctionPassPreservedAnalyses();
260 PA.preserveSet<CFGAnalyses>();
261 PA.preserve<LiveIntervalsAnalysis>();
262 PA.preserve<SlotIndexesAnalysis>();
263 PA.preserve<LiveDebugVariablesAnalysis>();
264 PA.preserve<LiveStacksAnalysis>();
265 PA.preserve<VirtRegMapAnalysis>();
266 PA.preserve<LiveRegMatrixAnalysis>();
267 return PA;
268}
269
270RAGreedy::RequiredAnalyses::RequiredAnalyses(Pass &P) {
271 VRM = &P.getAnalysis<VirtRegMapWrapperLegacy>().getVRM();
272 LIS = &P.getAnalysis<LiveIntervalsWrapperPass>().getLIS();
273 LSS = &P.getAnalysis<LiveStacksWrapperLegacy>().getLS();
274 LRM = &P.getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM();
275 Indexes = &P.getAnalysis<SlotIndexesWrapperPass>().getSI();
276 MBFI = &P.getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
277 DomTree = &P.getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
278 ORE = &P.getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
279 Loops = &P.getAnalysis<MachineLoopInfoWrapperPass>().getLI();
280 Bundles = &P.getAnalysis<EdgeBundlesWrapperLegacy>().getEdgeBundles();
281 SpillPlacer = &P.getAnalysis<SpillPlacementWrapperLegacy>().getResult();
282 DebugVars = &P.getAnalysis<LiveDebugVariablesWrapperLegacy>().getLDV();
283 EvictProvider =
284 &P.getAnalysis<RegAllocEvictionAdvisorAnalysisLegacy>().getProvider();
285 PriorityProvider =
286 &P.getAnalysis<RegAllocPriorityAdvisorAnalysisLegacy>().getProvider();
287}
288
289bool RAGreedyLegacy::runOnMachineFunction(MachineFunction &MF) {
290 RAGreedy::RequiredAnalyses Analyses(*this);
291 RAGreedy Impl(Analyses, F);
292 return Impl.run(mf&: MF);
293}
294
295char RAGreedyLegacy::ID = 0;
296char &llvm::RAGreedyLegacyID = RAGreedyLegacy::ID;
297
298INITIALIZE_PASS_BEGIN(RAGreedyLegacy, "greedy", "Greedy Register Allocator",
299 false, false)
300INITIALIZE_PASS_DEPENDENCY(LiveDebugVariablesWrapperLegacy)
301INITIALIZE_PASS_DEPENDENCY(SlotIndexesWrapperPass)
302INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
303INITIALIZE_PASS_DEPENDENCY(RegisterCoalescerLegacy)
304INITIALIZE_PASS_DEPENDENCY(MachineSchedulerLegacy)
305INITIALIZE_PASS_DEPENDENCY(LiveStacksWrapperLegacy)
306INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
307INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
308INITIALIZE_PASS_DEPENDENCY(VirtRegMapWrapperLegacy)
309INITIALIZE_PASS_DEPENDENCY(LiveRegMatrixWrapperLegacy)
310INITIALIZE_PASS_DEPENDENCY(EdgeBundlesWrapperLegacy)
311INITIALIZE_PASS_DEPENDENCY(SpillPlacementWrapperLegacy)
312INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
313INITIALIZE_PASS_DEPENDENCY(RegAllocEvictionAdvisorAnalysisLegacy)
314INITIALIZE_PASS_DEPENDENCY(RegAllocPriorityAdvisorAnalysisLegacy)
315INITIALIZE_PASS_END(RAGreedyLegacy, "greedy", "Greedy Register Allocator",
316 false, false)
317
318#ifndef NDEBUG
319const char *const RAGreedy::StageName[] = {
320 "RS_New",
321 "RS_Assign",
322 "RS_Split",
323 "RS_Split2",
324 "RS_Spill",
325 "RS_Done"
326};
327#endif
328
329// Hysteresis to use when comparing floats.
330// This helps stabilize decisions based on float comparisons.
331const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
332
333FunctionPass* llvm::createGreedyRegisterAllocator() {
334 return new RAGreedyLegacy();
335}
336
337FunctionPass *llvm::createGreedyRegisterAllocator(RegAllocFilterFunc Ftor) {
338 return new RAGreedyLegacy(Ftor);
339}
340
341void RAGreedyLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
342 AU.setPreservesCFG();
343 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
344 AU.addRequired<LiveIntervalsWrapperPass>();
345 AU.addPreserved<LiveIntervalsWrapperPass>();
346 AU.addRequired<SlotIndexesWrapperPass>();
347 AU.addPreserved<SlotIndexesWrapperPass>();
348 AU.addRequired<LiveDebugVariablesWrapperLegacy>();
349 AU.addPreserved<LiveDebugVariablesWrapperLegacy>();
350 AU.addRequired<LiveStacksWrapperLegacy>();
351 AU.addPreserved<LiveStacksWrapperLegacy>();
352 AU.addRequired<MachineDominatorTreeWrapperPass>();
353 AU.addRequired<MachineLoopInfoWrapperPass>();
354 AU.addRequired<VirtRegMapWrapperLegacy>();
355 AU.addPreserved<VirtRegMapWrapperLegacy>();
356 AU.addRequired<LiveRegMatrixWrapperLegacy>();
357 AU.addPreserved<LiveRegMatrixWrapperLegacy>();
358 AU.addRequired<EdgeBundlesWrapperLegacy>();
359 AU.addRequired<SpillPlacementWrapperLegacy>();
360 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
361 AU.addRequired<RegAllocEvictionAdvisorAnalysisLegacy>();
362 AU.addRequired<RegAllocPriorityAdvisorAnalysisLegacy>();
363 MachineFunctionPass::getAnalysisUsage(AU);
364}
365
366//===----------------------------------------------------------------------===//
367// LiveRangeEdit delegate methods
368//===----------------------------------------------------------------------===//
369
370bool RAGreedy::LRE_CanEraseVirtReg(Register VirtReg) {
371 LiveInterval &LI = LIS->getInterval(Reg: VirtReg);
372 if (VRM->hasPhys(virtReg: VirtReg)) {
373 Matrix->unassign(VirtReg: LI);
374 aboutToRemoveInterval(LI);
375 return true;
376 }
377 // Unassigned virtreg is probably in the priority queue.
378 // RegAllocBase will erase it after dequeueing.
379 // Nonetheless, clear the live-range so that the debug
380 // dump will show the right state for that VirtReg.
381 LI.clear();
382 return false;
383}
384
385void RAGreedy::LRE_WillShrinkVirtReg(Register VirtReg) {
386 if (!VRM->hasPhys(virtReg: VirtReg))
387 return;
388
389 // Register is assigned, put it back on the queue for reassignment.
390 LiveInterval &LI = LIS->getInterval(Reg: VirtReg);
391 Matrix->unassign(VirtReg: LI);
392 RegAllocBase::enqueue(LI: &LI);
393}
394
395void RAGreedy::LRE_DidCloneVirtReg(Register New, Register Old) {
396 ExtraInfo->LRE_DidCloneVirtReg(New, Old);
397}
398
399void RAGreedy::ExtraRegInfo::LRE_DidCloneVirtReg(Register New, Register Old) {
400 // Cloning a register we haven't even heard about yet? Just ignore it.
401 if (!Info.inBounds(N: Old))
402 return;
403
404 // LRE may clone a virtual register because dead code elimination causes it to
405 // be split into connected components. The new components are much smaller
406 // than the original, so they should get a new chance at being assigned.
407 // same stage as the parent.
408 Info[Old].Stage = RS_Assign;
409 Info.grow(N: New.id());
410 Info[New] = Info[Old];
411}
412
413void RAGreedy::releaseMemory() {
414 SpillerInstance.reset();
415 GlobalCand.clear();
416}
417
418void RAGreedy::enqueueImpl(const LiveInterval *LI) { enqueue(CurQueue&: Queue, LI); }
419
420void RAGreedy::enqueue(PQueue &CurQueue, const LiveInterval *LI) {
421 // Prioritize live ranges by size, assigning larger ranges first.
422 // The queue holds (size, reg) pairs.
423 const Register Reg = LI->reg();
424 assert(Reg.isVirtual() && "Can only enqueue virtual registers");
425
426 auto Stage = ExtraInfo->getOrInitStage(Reg);
427 if (Stage == RS_New) {
428 Stage = RS_Assign;
429 ExtraInfo->setStage(Reg, Stage);
430 }
431
432 unsigned Ret = PriorityAdvisor->getPriority(LI: *LI);
433
434 // The virtual register number is a tie breaker for same-sized ranges.
435 // Give lower vreg numbers higher priority to assign them first.
436 CurQueue.push(x: std::make_pair(x&: Ret, y: ~Reg.id()));
437}
438
439unsigned DefaultPriorityAdvisor::getPriority(const LiveInterval &LI) const {
440 const unsigned Size = LI.getSize();
441 const Register Reg = LI.reg();
442 unsigned Prio;
443 LiveRangeStage Stage = RA.getExtraInfo().getStage(VirtReg: LI);
444
445 if (Stage == RS_Split) {
446 // Unsplit ranges that couldn't be allocated immediately are deferred until
447 // everything else has been allocated.
448 Prio = Size;
449 } else {
450 // Giant live ranges fall back to the global assignment heuristic, which
451 // prevents excessive spilling in pathological cases.
452 const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
453 bool ForceGlobal = RC.GlobalPriority ||
454 (!ReverseLocalAssignment &&
455 (Size / SlotIndex::InstrDist) >
456 (2 * RegClassInfo.getNumAllocatableRegs(RC: &RC)));
457 unsigned GlobalBit = 0;
458
459 if (Stage == RS_Assign && !ForceGlobal && !LI.empty() &&
460 LIS->intervalIsInOneMBB(LI)) {
461 // Allocate original local ranges in linear instruction order. Since they
462 // are singly defined, this produces optimal coloring in the absence of
463 // global interference and other constraints.
464 if (!ReverseLocalAssignment)
465 Prio = LI.beginIndex().getApproxInstrDistance(other: Indexes->getLastIndex());
466 else {
467 // Allocating bottom up may allow many short LRGs to be assigned first
468 // to one of the cheap registers. This could be much faster for very
469 // large blocks on targets with many physical registers.
470 Prio = Indexes->getZeroIndex().getApproxInstrDistance(other: LI.endIndex());
471 }
472 } else {
473 // Allocate global and split ranges in long->short order. Long ranges that
474 // don't fit should be spilled (or split) ASAP so they don't create
475 // interference. Mark a bit to prioritize global above local ranges.
476 Prio = Size;
477 GlobalBit = 1;
478 }
479
480 // Priority bit layout:
481 // 31 RS_Assign priority
482 // 30 Preference priority
483 // if (RegClassPriorityTrumpsGlobalness)
484 // 29-25 AllocPriority
485 // 24 GlobalBit
486 // else
487 // 29 Global bit
488 // 28-24 AllocPriority
489 // 0-23 Size/Instr distance
490
491 // Clamp the size to fit with the priority masking scheme
492 Prio = std::min(a: Prio, b: (unsigned)maxUIntN(N: 24));
493 assert(isUInt<5>(RC.AllocationPriority) && "allocation priority overflow");
494
495 if (RegClassPriorityTrumpsGlobalness)
496 Prio |= RC.AllocationPriority << 25 | GlobalBit << 24;
497 else
498 Prio |= GlobalBit << 29 | RC.AllocationPriority << 24;
499
500 // Mark a higher bit to prioritize global and local above RS_Split.
501 Prio |= (1u << 31);
502
503 // Boost ranges that have a physical register hint.
504 if (VRM->hasKnownPreference(VirtReg: Reg))
505 Prio |= (1u << 30);
506 }
507
508 return Prio;
509}
510
511unsigned DummyPriorityAdvisor::getPriority(const LiveInterval &LI) const {
512 // Prioritize by virtual register number, lowest first.
513 Register Reg = LI.reg();
514 return ~Reg.virtRegIndex();
515}
516
517const LiveInterval *RAGreedy::dequeue() { return dequeue(CurQueue&: Queue); }
518
519const LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
520 if (CurQueue.empty())
521 return nullptr;
522 LiveInterval *LI = &LIS->getInterval(Reg: ~CurQueue.top().second);
523 CurQueue.pop();
524 return LI;
525}
526
527//===----------------------------------------------------------------------===//
528// Direct Assignment
529//===----------------------------------------------------------------------===//
530
531/// tryAssign - Try to assign VirtReg to an available register.
532MCRegister RAGreedy::tryAssign(const LiveInterval &VirtReg,
533 AllocationOrder &Order,
534 SmallVectorImpl<Register> &NewVRegs,
535 const SmallVirtRegSet &FixedRegisters) {
536 MCRegister PhysReg;
537 for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) {
538 assert(*I);
539 if (!Matrix->checkInterference(VirtReg, PhysReg: *I)) {
540 if (I.isHint())
541 return *I;
542 else
543 PhysReg = *I;
544 }
545 }
546 if (!PhysReg.isValid())
547 return PhysReg;
548
549 // PhysReg is available, but there may be a better choice.
550
551 // If we missed a simple hint, try to cheaply evict interference from the
552 // preferred register.
553 if (Register Hint = MRI->getSimpleHint(VReg: VirtReg.reg()))
554 if (Order.isHint(Reg: Hint)) {
555 MCRegister PhysHint = Hint.asMCReg();
556 LLVM_DEBUG(dbgs() << "missed hint " << printReg(PhysHint, TRI) << '\n');
557
558 if (EvictAdvisor->canEvictHintInterference(VirtReg, PhysReg: PhysHint,
559 FixedRegisters)) {
560 evictInterference(VirtReg, PhysHint, NewVRegs);
561 return PhysHint;
562 }
563
564 // We can also split the virtual register in cold blocks.
565 if (trySplitAroundHintReg(Hint: PhysHint, VirtReg, NewVRegs, Order))
566 return MCRegister();
567
568 // Record the missed hint, we may be able to recover
569 // at the end if the surrounding allocation changed.
570 SetOfBrokenHints.insert(X: &VirtReg);
571 }
572
573 // Try to evict interference from a cheaper alternative.
574 uint8_t Cost = RegCosts[PhysReg.id()];
575
576 // Most registers have 0 additional cost.
577 if (!Cost)
578 return PhysReg;
579
580 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost "
581 << (unsigned)Cost << '\n');
582 MCRegister CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost, FixedRegisters);
583 return CheapReg ? CheapReg : PhysReg;
584}
585
586//===----------------------------------------------------------------------===//
587// Interference eviction
588//===----------------------------------------------------------------------===//
589
590bool RegAllocEvictionAdvisor::canReassign(const LiveInterval &VirtReg,
591 MCRegister FromReg) const {
592 auto HasRegUnitInterference = [&](MCRegUnit Unit) {
593 // Instantiate a "subquery", not to be confused with the Queries array.
594 LiveIntervalUnion::Query SubQ(
595 VirtReg, Matrix->getLiveUnions()[static_cast<unsigned>(Unit)]);
596 return SubQ.checkInterference();
597 };
598
599 for (MCRegister Reg :
600 AllocationOrder::create(VirtReg: VirtReg.reg(), VRM: *VRM, RegClassInfo, Matrix)) {
601 if (Reg == FromReg)
602 continue;
603 // If no units have interference, reassignment is possible.
604 if (none_of(Range: TRI->regunits(Reg), P: HasRegUnitInterference)) {
605 LLVM_DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
606 << printReg(FromReg, TRI) << " to "
607 << printReg(Reg, TRI) << '\n');
608 return true;
609 }
610 }
611 return false;
612}
613
614/// evictInterference - Evict any interferring registers that prevent VirtReg
615/// from being assigned to Physreg. This assumes that canEvictInterference
616/// returned true.
617void RAGreedy::evictInterference(const LiveInterval &VirtReg,
618 MCRegister PhysReg,
619 SmallVectorImpl<Register> &NewVRegs) {
620 // Make sure that VirtReg has a cascade number, and assign that cascade
621 // number to every evicted register. These live ranges than then only be
622 // evicted by a newer cascade, preventing infinite loops.
623 unsigned Cascade = ExtraInfo->getOrAssignNewCascade(Reg: VirtReg.reg());
624
625 LLVM_DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI)
626 << " interference: Cascade " << Cascade << '\n');
627
628 // Collect all interfering virtregs first.
629 SmallVector<const LiveInterval *, 8> Intfs;
630 for (MCRegUnit Unit : TRI->regunits(Reg: PhysReg)) {
631 LiveIntervalUnion::Query &Q = Matrix->query(LR: VirtReg, RegUnit: Unit);
632 // We usually have the interfering VRegs cached so collectInterferingVRegs()
633 // should be fast, we may need to recalculate if when different physregs
634 // overlap the same register unit so we had different SubRanges queried
635 // against it.
636 ArrayRef<const LiveInterval *> IVR = Q.interferingVRegs();
637 Intfs.append(in_start: IVR.begin(), in_end: IVR.end());
638 }
639
640 // Evict them second. This will invalidate the queries.
641 for (const LiveInterval *Intf : Intfs) {
642 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
643 if (!VRM->hasPhys(virtReg: Intf->reg()))
644 continue;
645
646 Matrix->unassign(VirtReg: *Intf);
647 assert((ExtraInfo->getCascade(Intf->reg()) < Cascade ||
648 (Cascade < ExtraInfo->getCascade(Intf->reg()) &&
649 EvictAdvisor->isUrgentEviction(VirtReg, *Intf)) ||
650 VirtReg.isSpillable() < Intf->isSpillable()) &&
651 "Cannot decrease cascade number, illegal eviction");
652 ExtraInfo->setCascade(Reg: Intf->reg(), Cascade);
653 ++NumEvicted;
654 NewVRegs.push_back(Elt: Intf->reg());
655 }
656}
657
658/// Returns true if the given \p PhysReg is a callee saved register and has not
659/// been used for allocation yet.
660bool RegAllocEvictionAdvisor::isUnusedCalleeSavedReg(MCRegister PhysReg) const {
661 MCRegister CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
662 if (!CSR)
663 return false;
664
665 return !Matrix->isPhysRegUsed(PhysReg);
666}
667
668std::optional<unsigned>
669RegAllocEvictionAdvisor::getOrderLimit(const LiveInterval &VirtReg,
670 const AllocationOrder &Order,
671 unsigned CostPerUseLimit) const {
672 unsigned OrderLimit = Order.getOrder().size();
673
674 if (CostPerUseLimit < uint8_t(~0u)) {
675 // Check of any registers in RC are below CostPerUseLimit.
676 const TargetRegisterClass *RC = MRI->getRegClass(Reg: VirtReg.reg());
677 uint8_t MinCost = RegClassInfo.getMinCost(RC);
678 if (MinCost >= CostPerUseLimit) {
679 LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = "
680 << MinCost << ", no cheaper registers to be found.\n");
681 return std::nullopt;
682 }
683
684 // It is normal for register classes to have a long tail of registers with
685 // the same cost. We don't need to look at them if they're too expensive.
686 if (RegCosts[Order.getOrder().back()] >= CostPerUseLimit) {
687 OrderLimit = RegClassInfo.getLastCostChange(RC);
688 LLVM_DEBUG(dbgs() << "Only trying the first " << OrderLimit
689 << " regs.\n");
690 }
691 }
692 return OrderLimit;
693}
694
695bool RegAllocEvictionAdvisor::canAllocatePhysReg(unsigned CostPerUseLimit,
696 MCRegister PhysReg) const {
697 if (RegCosts[PhysReg.id()] >= CostPerUseLimit)
698 return false;
699 // The first use of a callee-saved register in a function has cost 1.
700 // Don't start using a CSR when the CostPerUseLimit is low.
701 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
702 LLVM_DEBUG(
703 dbgs() << printReg(PhysReg, TRI) << " would clobber CSR "
704 << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
705 << '\n');
706 return false;
707 }
708 return true;
709}
710
711/// tryEvict - Try to evict all interferences for a physreg.
712/// @param VirtReg Currently unassigned virtual register.
713/// @param Order Physregs to try.
714/// @return Physreg to assign VirtReg, or 0.
715MCRegister RAGreedy::tryEvict(const LiveInterval &VirtReg,
716 AllocationOrder &Order,
717 SmallVectorImpl<Register> &NewVRegs,
718 uint8_t CostPerUseLimit,
719 const SmallVirtRegSet &FixedRegisters) {
720 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
721 TimePassesIsEnabled);
722
723 MCRegister BestPhys = EvictAdvisor->tryFindEvictionCandidate(
724 VirtReg, Order, CostPerUseLimit, FixedRegisters);
725 if (BestPhys.isValid())
726 evictInterference(VirtReg, PhysReg: BestPhys, NewVRegs);
727 return BestPhys;
728}
729
730//===----------------------------------------------------------------------===//
731// Region Splitting
732//===----------------------------------------------------------------------===//
733
734/// addSplitConstraints - Fill out the SplitConstraints vector based on the
735/// interference pattern in Physreg and its aliases. Add the constraints to
736/// SpillPlacement and return the static cost of this split in Cost, assuming
737/// that all preferences in SplitConstraints are met.
738/// Return false if there are no bundles with positive bias.
739bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
740 BlockFrequency &Cost) {
741 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
742
743 // Reset interference dependent info.
744 SplitConstraints.resize(N: UseBlocks.size());
745 BlockFrequency StaticCost = BlockFrequency(0);
746 for (unsigned I = 0; I != UseBlocks.size(); ++I) {
747 const SplitAnalysis::BlockInfo &BI = UseBlocks[I];
748 SpillPlacement::BlockConstraint &BC = SplitConstraints[I];
749
750 BC.Number = BI.MBB->getNumber();
751 Intf.moveToBlock(MBBNum: BC.Number);
752 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
753 BC.Exit = (BI.LiveOut &&
754 !LIS->getInstructionFromIndex(index: BI.LastInstr)->isImplicitDef())
755 ? SpillPlacement::PrefReg
756 : SpillPlacement::DontCare;
757 BC.ChangesValue = BI.FirstDef.isValid();
758
759 if (!Intf.hasInterference())
760 continue;
761
762 // Number of spill code instructions to insert.
763 unsigned Ins = 0;
764
765 // Interference for the live-in value.
766 if (BI.LiveIn) {
767 if (Intf.first() <= Indexes->getMBBStartIdx(mbb: BI.MBB)) {
768 BC.Entry = SpillPlacement::MustSpill;
769 ++Ins;
770 } else if (Intf.first() < BI.FirstInstr) {
771 BC.Entry = SpillPlacement::PrefSpill;
772 ++Ins;
773 } else if (Intf.first() < BI.LastInstr) {
774 ++Ins;
775 }
776
777 // Abort if the spill cannot be inserted at the MBB' start
778 if (((BC.Entry == SpillPlacement::MustSpill) ||
779 (BC.Entry == SpillPlacement::PrefSpill)) &&
780 SlotIndex::isEarlierInstr(A: BI.FirstInstr,
781 B: SA->getFirstSplitPoint(Num: BC.Number)))
782 return false;
783 }
784
785 // Interference for the live-out value.
786 if (BI.LiveOut) {
787 if (Intf.last() >= SA->getLastSplitPoint(Num: BC.Number)) {
788 BC.Exit = SpillPlacement::MustSpill;
789 ++Ins;
790 } else if (Intf.last() > BI.LastInstr) {
791 BC.Exit = SpillPlacement::PrefSpill;
792 ++Ins;
793 } else if (Intf.last() > BI.FirstInstr) {
794 ++Ins;
795 }
796 }
797
798 // Accumulate the total frequency of inserted spill code.
799 while (Ins--)
800 StaticCost += SpillPlacer->getBlockFrequency(Number: BC.Number);
801 }
802 Cost = StaticCost;
803
804 // Add constraints for use-blocks. Note that these are the only constraints
805 // that may add a positive bias, it is downhill from here.
806 SpillPlacer->addConstraints(LiveBlocks: SplitConstraints);
807 return SpillPlacer->scanActiveBundles();
808}
809
810/// addThroughConstraints - Add constraints and links to SpillPlacer from the
811/// live-through blocks in Blocks.
812bool RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
813 ArrayRef<unsigned> Blocks) {
814 const unsigned GroupSize = 8;
815 SpillPlacement::BlockConstraint BCS[GroupSize];
816 unsigned TBS[GroupSize];
817 unsigned B = 0, T = 0;
818
819 for (unsigned Number : Blocks) {
820 Intf.moveToBlock(MBBNum: Number);
821
822 if (!Intf.hasInterference()) {
823 assert(T < GroupSize && "Array overflow");
824 TBS[T] = Number;
825 if (++T == GroupSize) {
826 SpillPlacer->addLinks(Links: ArrayRef(TBS, T));
827 T = 0;
828 }
829 continue;
830 }
831
832 assert(B < GroupSize && "Array overflow");
833 BCS[B].Number = Number;
834
835 // Abort if the spill cannot be inserted at the MBB' start
836 MachineBasicBlock *MBB = MF->getBlockNumbered(N: Number);
837 auto FirstNonDebugInstr = MBB->getFirstNonDebugInstr();
838 if (FirstNonDebugInstr != MBB->end() &&
839 SlotIndex::isEarlierInstr(A: LIS->getInstructionIndex(Instr: *FirstNonDebugInstr),
840 B: SA->getFirstSplitPoint(Num: Number)))
841 return false;
842
843 // Interference for the live-in value.
844 Register Reg = SA->getParent().reg();
845 auto InsertPt = MBB->SkipPHIsLabelsAndDebug(I: MBB->begin(), Reg);
846 SlotIndex InsertIdx = InsertPt == MBB->end()
847 ? Indexes->getMBBEndIdx(mbb: MBB)
848 : LIS->getInstructionIndex(Instr: *InsertPt);
849 if (Intf.first() <= Indexes->getMBBStartIdx(mbb: MBB) ||
850 SlotIndex::isEarlierInstr(A: Intf.first(), B: InsertIdx))
851 BCS[B].Entry = SpillPlacement::MustSpill;
852 else
853 BCS[B].Entry = SpillPlacement::PrefSpill;
854
855 // Interference for the live-out value.
856 if (Intf.last() >= SA->getLastSplitPoint(Num: Number))
857 BCS[B].Exit = SpillPlacement::MustSpill;
858 else
859 BCS[B].Exit = SpillPlacement::PrefSpill;
860
861 if (++B == GroupSize) {
862 SpillPlacer->addConstraints(LiveBlocks: ArrayRef(BCS, B));
863 B = 0;
864 }
865 }
866
867 SpillPlacer->addConstraints(LiveBlocks: ArrayRef(BCS, B));
868 SpillPlacer->addLinks(Links: ArrayRef(TBS, T));
869 return true;
870}
871
872bool RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
873 // Keep track of through blocks that have not been added to SpillPlacer.
874 BitVector Todo = SA->getThroughBlocks();
875 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
876 unsigned AddedTo = 0;
877#ifndef NDEBUG
878 unsigned Visited = 0;
879#endif
880
881 unsigned long Budget = GrowRegionComplexityBudget;
882 while (true) {
883 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
884 // Find new through blocks in the periphery of PrefRegBundles.
885 for (unsigned Bundle : NewBundles) {
886 // Look at all blocks connected to Bundle in the full graph.
887 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
888 // Limit compilation time by bailing out after we use all our budget.
889 if (Blocks.size() >= Budget)
890 return false;
891 Budget -= Blocks.size();
892 for (unsigned Block : Blocks) {
893 if (!Todo.test(Idx: Block))
894 continue;
895 Todo.reset(Idx: Block);
896 // This is a new through block. Add it to SpillPlacer later.
897 ActiveBlocks.push_back(Elt: Block);
898#ifndef NDEBUG
899 ++Visited;
900#endif
901 }
902 }
903 // Any new blocks to add?
904 if (ActiveBlocks.size() == AddedTo)
905 break;
906
907 // Compute through constraints from the interference, or assume that all
908 // through blocks prefer spilling when forming compact regions.
909 auto NewBlocks = ArrayRef(ActiveBlocks).slice(N: AddedTo);
910 if (Cand.PhysReg) {
911 if (!addThroughConstraints(Intf: Cand.Intf, Blocks: NewBlocks))
912 return false;
913 } else {
914 // Providing that the variable being spilled does not look like a loop
915 // induction variable, which is expensive to spill around and better
916 // pushed into a condition inside the loop if possible, provide a strong
917 // negative bias on through blocks to prevent unwanted liveness on loop
918 // backedges.
919 bool PrefSpill = true;
920 if (SA->looksLikeLoopIV() && NewBlocks.size() >= 2) {
921 // Check that the current bundle is adding a Header + start+end of
922 // loop-internal blocks. If the block is indeed a header, don't make
923 // the NewBlocks as PrefSpill to allow the variable to be live in
924 // Header<->Latch.
925 MachineLoop *L = Loops->getLoopFor(BB: MF->getBlockNumbered(N: NewBlocks[0]));
926 if (L && L->getHeader()->getNumber() == (int)NewBlocks[0] &&
927 all_of(Range: NewBlocks.drop_front(), P: [&](unsigned Block) {
928 return L == Loops->getLoopFor(BB: MF->getBlockNumbered(N: Block));
929 }))
930 PrefSpill = false;
931 }
932 if (PrefSpill)
933 SpillPlacer->addPrefSpill(Blocks: NewBlocks, /* Strong= */ true);
934 }
935 AddedTo = ActiveBlocks.size();
936
937 // Perhaps iterating can enable more bundles?
938 SpillPlacer->iterate();
939 }
940 LLVM_DEBUG(dbgs() << ", v=" << Visited);
941 return true;
942}
943
944/// calcCompactRegion - Compute the set of edge bundles that should be live
945/// when splitting the current live range into compact regions. Compact
946/// regions can be computed without looking at interference. They are the
947/// regions formed by removing all the live-through blocks from the live range.
948///
949/// Returns false if the current live range is already compact, or if the
950/// compact regions would form single block regions anyway.
951bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
952 // Without any through blocks, the live range is already compact.
953 if (!SA->getNumThroughBlocks())
954 return false;
955
956 // Compact regions don't correspond to any physreg.
957 Cand.reset(Cache&: IntfCache, Reg: MCRegister::NoRegister);
958
959 LLVM_DEBUG(dbgs() << "Compact region bundles");
960
961 // Use the spill placer to determine the live bundles. GrowRegion pretends
962 // that all the through blocks have interference when PhysReg is unset.
963 SpillPlacer->prepare(RegBundles&: Cand.LiveBundles);
964
965 // The static split cost will be zero since Cand.Intf reports no interference.
966 BlockFrequency Cost;
967 if (!addSplitConstraints(Intf: Cand.Intf, Cost)) {
968 LLVM_DEBUG(dbgs() << ", none.\n");
969 return false;
970 }
971
972 if (!growRegion(Cand)) {
973 LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
974 return false;
975 }
976
977 SpillPlacer->finish();
978
979 if (!Cand.LiveBundles.any()) {
980 LLVM_DEBUG(dbgs() << ", none.\n");
981 return false;
982 }
983
984 LLVM_DEBUG({
985 for (int I : Cand.LiveBundles.set_bits())
986 dbgs() << " EB#" << I;
987 dbgs() << ".\n";
988 });
989 return true;
990}
991
992/// calcBlockSplitCost - Compute how expensive it would be to split the live
993/// range in SA around all use blocks instead of forming bundle regions.
994BlockFrequency RAGreedy::calcBlockSplitCost() {
995 BlockFrequency Cost = BlockFrequency(0);
996 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
997 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
998 unsigned Number = BI.MBB->getNumber();
999 // We normally only need one spill instruction - a load or a store.
1000 Cost += SpillPlacer->getBlockFrequency(Number);
1001
1002 // Unless the value is redefined in the block.
1003 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1004 Cost += SpillPlacer->getBlockFrequency(Number);
1005 }
1006 return Cost;
1007}
1008
1009/// calcGlobalSplitCost - Return the global split cost of following the split
1010/// pattern in LiveBundles. This cost should be added to the local cost of the
1011/// interference pattern in SplitConstraints.
1012///
1013BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
1014 const AllocationOrder &Order) {
1015 BlockFrequency GlobalCost = BlockFrequency(0);
1016 const BitVector &LiveBundles = Cand.LiveBundles;
1017 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1018 for (unsigned I = 0; I != UseBlocks.size(); ++I) {
1019 const SplitAnalysis::BlockInfo &BI = UseBlocks[I];
1020 SpillPlacement::BlockConstraint &BC = SplitConstraints[I];
1021 bool RegIn = LiveBundles[Bundles->getBundle(N: BC.Number, Out: false)];
1022 bool RegOut = LiveBundles[Bundles->getBundle(N: BC.Number, Out: true)];
1023 unsigned Ins = 0;
1024
1025 Cand.Intf.moveToBlock(MBBNum: BC.Number);
1026
1027 if (BI.LiveIn)
1028 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1029 if (BI.LiveOut)
1030 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
1031 while (Ins--)
1032 GlobalCost += SpillPlacer->getBlockFrequency(Number: BC.Number);
1033 }
1034
1035 for (unsigned Number : Cand.ActiveBlocks) {
1036 bool RegIn = LiveBundles[Bundles->getBundle(N: Number, Out: false)];
1037 bool RegOut = LiveBundles[Bundles->getBundle(N: Number, Out: true)];
1038 if (!RegIn && !RegOut)
1039 continue;
1040 if (RegIn && RegOut) {
1041 // We need double spill code if this block has interference.
1042 Cand.Intf.moveToBlock(MBBNum: Number);
1043 if (Cand.Intf.hasInterference()) {
1044 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1045 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1046 }
1047 continue;
1048 }
1049 // live-in / stack-out or stack-in live-out.
1050 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1051 }
1052 return GlobalCost;
1053}
1054
1055/// splitAroundRegion - Split the current live range around the regions
1056/// determined by BundleCand and GlobalCand.
1057///
1058/// Before calling this function, GlobalCand and BundleCand must be initialized
1059/// so each bundle is assigned to a valid candidate, or NoCand for the
1060/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1061/// objects must be initialized for the current live range, and intervals
1062/// created for the used candidates.
1063///
1064/// @param LREdit The LiveRangeEdit object handling the current split.
1065/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1066/// must appear in this list.
1067void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1068 ArrayRef<unsigned> UsedCands) {
1069 // These are the intervals created for new global ranges. We may create more
1070 // intervals for local ranges.
1071 const unsigned NumGlobalIntvs = LREdit.size();
1072 LLVM_DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs
1073 << " globals.\n");
1074 assert(NumGlobalIntvs && "No global intervals configured");
1075
1076 // Isolate even single instructions when dealing with a proper sub-class.
1077 // That guarantees register class inflation for the stack interval because it
1078 // is all copies.
1079 Register Reg = SA->getParent().reg();
1080 bool SingleInstrs = RegClassInfo.isProperSubClass(RC: MRI->getRegClass(Reg));
1081
1082 // First handle all the blocks with uses.
1083 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1084 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
1085 unsigned Number = BI.MBB->getNumber();
1086 unsigned IntvIn = 0, IntvOut = 0;
1087 SlotIndex IntfIn, IntfOut;
1088 if (BI.LiveIn) {
1089 unsigned CandIn = BundleCand[Bundles->getBundle(N: Number, Out: false)];
1090 if (CandIn != NoCand) {
1091 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1092 IntvIn = Cand.IntvIdx;
1093 Cand.Intf.moveToBlock(MBBNum: Number);
1094 IntfIn = Cand.Intf.first();
1095 }
1096 }
1097 if (BI.LiveOut) {
1098 unsigned CandOut = BundleCand[Bundles->getBundle(N: Number, Out: true)];
1099 if (CandOut != NoCand) {
1100 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1101 IntvOut = Cand.IntvIdx;
1102 Cand.Intf.moveToBlock(MBBNum: Number);
1103 IntfOut = Cand.Intf.last();
1104 }
1105 }
1106
1107 // Create separate intervals for isolated blocks with multiple uses.
1108 if (!IntvIn && !IntvOut) {
1109 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " isolated.\n");
1110 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1111 SE->splitSingleBlock(BI);
1112 continue;
1113 }
1114
1115 if (IntvIn && IntvOut)
1116 SE->splitLiveThroughBlock(MBBNum: Number, IntvIn, LeaveBefore: IntfIn, IntvOut, EnterAfter: IntfOut);
1117 else if (IntvIn)
1118 SE->splitRegInBlock(BI, IntvIn, LeaveBefore: IntfIn);
1119 else
1120 SE->splitRegOutBlock(BI, IntvOut, EnterAfter: IntfOut);
1121 }
1122
1123 // Handle live-through blocks. The relevant live-through blocks are stored in
1124 // the ActiveBlocks list with each candidate. We need to filter out
1125 // duplicates.
1126 BitVector Todo = SA->getThroughBlocks();
1127 for (unsigned UsedCand : UsedCands) {
1128 ArrayRef<unsigned> Blocks = GlobalCand[UsedCand].ActiveBlocks;
1129 for (unsigned Number : Blocks) {
1130 if (!Todo.test(Idx: Number))
1131 continue;
1132 Todo.reset(Idx: Number);
1133
1134 unsigned IntvIn = 0, IntvOut = 0;
1135 SlotIndex IntfIn, IntfOut;
1136
1137 unsigned CandIn = BundleCand[Bundles->getBundle(N: Number, Out: false)];
1138 if (CandIn != NoCand) {
1139 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1140 IntvIn = Cand.IntvIdx;
1141 Cand.Intf.moveToBlock(MBBNum: Number);
1142 IntfIn = Cand.Intf.first();
1143 }
1144
1145 unsigned CandOut = BundleCand[Bundles->getBundle(N: Number, Out: true)];
1146 if (CandOut != NoCand) {
1147 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1148 IntvOut = Cand.IntvIdx;
1149 Cand.Intf.moveToBlock(MBBNum: Number);
1150 IntfOut = Cand.Intf.last();
1151 }
1152 if (!IntvIn && !IntvOut)
1153 continue;
1154 SE->splitLiveThroughBlock(MBBNum: Number, IntvIn, LeaveBefore: IntfIn, IntvOut, EnterAfter: IntfOut);
1155 }
1156 }
1157
1158 ++NumGlobalSplits;
1159
1160 SmallVector<unsigned, 8> IntvMap;
1161 SE->finish(LRMap: &IntvMap);
1162 DebugVars->splitRegister(OldReg: Reg, NewRegs: LREdit.regs(), LIS&: *LIS);
1163
1164 unsigned OrigBlocks = SA->getNumLiveBlocks();
1165
1166 // Sort out the new intervals created by splitting. We get four kinds:
1167 // - Remainder intervals should not be split again.
1168 // - Candidate intervals can be assigned to Cand.PhysReg.
1169 // - Block-local splits are candidates for local splitting.
1170 // - DCE leftovers should go back on the queue.
1171 for (unsigned I = 0, E = LREdit.size(); I != E; ++I) {
1172 const LiveInterval &Reg = LIS->getInterval(Reg: LREdit.get(idx: I));
1173
1174 // Ignore old intervals from DCE.
1175 if (ExtraInfo->getOrInitStage(Reg: Reg.reg()) != RS_New)
1176 continue;
1177
1178 // Remainder interval. Don't try splitting again, spill if it doesn't
1179 // allocate.
1180 if (IntvMap[I] == 0) {
1181 ExtraInfo->setStage(VirtReg: Reg, Stage: RS_Spill);
1182 continue;
1183 }
1184
1185 // Global intervals. Allow repeated splitting as long as the number of live
1186 // blocks is strictly decreasing.
1187 if (IntvMap[I] < NumGlobalIntvs) {
1188 if (SA->countLiveBlocks(li: &Reg) >= OrigBlocks) {
1189 LLVM_DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1190 << " blocks as original.\n");
1191 // Don't allow repeated splitting as a safe guard against looping.
1192 ExtraInfo->setStage(VirtReg: Reg, Stage: RS_Split2);
1193 }
1194 continue;
1195 }
1196
1197 // Other intervals are treated as new. This includes local intervals created
1198 // for blocks with multiple uses, and anything created by DCE.
1199 }
1200
1201 if (VerifyEnabled)
1202 MF->verify(LiveInts: LIS, Indexes, Banner: "After splitting live range around region",
1203 OS: &errs());
1204}
1205
1206MCRegister RAGreedy::tryRegionSplit(const LiveInterval &VirtReg,
1207 AllocationOrder &Order,
1208 SmallVectorImpl<Register> &NewVRegs) {
1209 if (!TRI->shouldRegionSplitForVirtReg(MF: *MF, VirtReg))
1210 return MCRegister::NoRegister;
1211 unsigned NumCands = 0;
1212 BlockFrequency SpillCost = calcBlockSplitCost();
1213 BlockFrequency BestCost;
1214
1215 // Check if we can split this live range around a compact region.
1216 bool HasCompact = calcCompactRegion(Cand&: GlobalCand.front());
1217 if (HasCompact) {
1218 // Yes, keep GlobalCand[0] as the compact region candidate.
1219 NumCands = 1;
1220 BestCost = BlockFrequency::max();
1221 } else {
1222 // No benefit from the compact region, our fallback will be per-block
1223 // splitting. Make sure we find a solution that is cheaper than spilling.
1224 BestCost = SpillCost;
1225 LLVM_DEBUG(dbgs() << "Cost of isolating all blocks = "
1226 << printBlockFreq(*MBFI, BestCost) << '\n');
1227 }
1228
1229 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
1230 NumCands, IgnoreCSR: false /*IgnoreCSR*/);
1231
1232 // No solutions found, fall back to single block splitting.
1233 if (!HasCompact && BestCand == NoCand)
1234 return MCRegister::NoRegister;
1235
1236 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1237}
1238
1239unsigned RAGreedy::calculateRegionSplitCostAroundReg(MCRegister PhysReg,
1240 AllocationOrder &Order,
1241 BlockFrequency &BestCost,
1242 unsigned &NumCands,
1243 unsigned &BestCand) {
1244 // Discard bad candidates before we run out of interference cache cursors.
1245 // This will only affect register classes with a lot of registers (>32).
1246 if (NumCands == IntfCache.getMaxCursors()) {
1247 unsigned WorstCount = ~0u;
1248 unsigned Worst = 0;
1249 for (unsigned CandIndex = 0; CandIndex != NumCands; ++CandIndex) {
1250 if (CandIndex == BestCand || !GlobalCand[CandIndex].PhysReg)
1251 continue;
1252 unsigned Count = GlobalCand[CandIndex].LiveBundles.count();
1253 if (Count < WorstCount) {
1254 Worst = CandIndex;
1255 WorstCount = Count;
1256 }
1257 }
1258 --NumCands;
1259 GlobalCand[Worst] = GlobalCand[NumCands];
1260 if (BestCand == NumCands)
1261 BestCand = Worst;
1262 }
1263
1264 if (GlobalCand.size() <= NumCands)
1265 GlobalCand.resize(N: NumCands+1);
1266 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1267 Cand.reset(Cache&: IntfCache, Reg: PhysReg);
1268
1269 SpillPlacer->prepare(RegBundles&: Cand.LiveBundles);
1270 BlockFrequency Cost;
1271 if (!addSplitConstraints(Intf: Cand.Intf, Cost)) {
1272 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tno positive bundles\n");
1273 return BestCand;
1274 }
1275 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI)
1276 << "\tstatic = " << printBlockFreq(*MBFI, Cost));
1277 if (Cost >= BestCost) {
1278 LLVM_DEBUG({
1279 if (BestCand == NoCand)
1280 dbgs() << " worse than no bundles\n";
1281 else
1282 dbgs() << " worse than "
1283 << printReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1284 });
1285 return BestCand;
1286 }
1287 if (!growRegion(Cand)) {
1288 LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
1289 return BestCand;
1290 }
1291
1292 SpillPlacer->finish();
1293
1294 // No live bundles, defer to splitSingleBlocks().
1295 if (!Cand.LiveBundles.any()) {
1296 LLVM_DEBUG(dbgs() << " no bundles.\n");
1297 return BestCand;
1298 }
1299
1300 Cost += calcGlobalSplitCost(Cand, Order);
1301 LLVM_DEBUG({
1302 dbgs() << ", total = " << printBlockFreq(*MBFI, Cost) << " with bundles";
1303 for (int I : Cand.LiveBundles.set_bits())
1304 dbgs() << " EB#" << I;
1305 dbgs() << ".\n";
1306 });
1307 if (Cost < BestCost) {
1308 BestCand = NumCands;
1309 BestCost = Cost;
1310 }
1311 ++NumCands;
1312
1313 return BestCand;
1314}
1315
1316unsigned RAGreedy::calculateRegionSplitCost(const LiveInterval &VirtReg,
1317 AllocationOrder &Order,
1318 BlockFrequency &BestCost,
1319 unsigned &NumCands,
1320 bool IgnoreCSR) {
1321 unsigned BestCand = NoCand;
1322 for (MCRegister PhysReg : Order) {
1323 assert(PhysReg);
1324 if (IgnoreCSR && EvictAdvisor->isUnusedCalleeSavedReg(PhysReg))
1325 continue;
1326
1327 calculateRegionSplitCostAroundReg(PhysReg, Order, BestCost, NumCands,
1328 BestCand);
1329 }
1330
1331 return BestCand;
1332}
1333
1334MCRegister RAGreedy::doRegionSplit(const LiveInterval &VirtReg,
1335 unsigned BestCand, bool HasCompact,
1336 SmallVectorImpl<Register> &NewVRegs) {
1337 SmallVector<unsigned, 8> UsedCands;
1338 // Prepare split editor.
1339 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1340 SE->reset(LREdit, SplitSpillMode);
1341
1342 // Assign all edge bundles to the preferred candidate, or NoCand.
1343 BundleCand.assign(NumElts: Bundles->getNumBundles(), Elt: NoCand);
1344
1345 // Assign bundles for the best candidate region.
1346 if (BestCand != NoCand) {
1347 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1348 if (unsigned B = Cand.getBundles(B&: BundleCand, C: BestCand)) {
1349 UsedCands.push_back(Elt: BestCand);
1350 Cand.IntvIdx = SE->openIntv();
1351 LLVM_DEBUG(dbgs() << "Split for " << printReg(Cand.PhysReg, TRI) << " in "
1352 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1353 (void)B;
1354 }
1355 }
1356
1357 // Assign bundles for the compact region.
1358 if (HasCompact) {
1359 GlobalSplitCandidate &Cand = GlobalCand.front();
1360 assert(!Cand.PhysReg && "Compact region has no physreg");
1361 if (unsigned B = Cand.getBundles(B&: BundleCand, C: 0)) {
1362 UsedCands.push_back(Elt: 0);
1363 Cand.IntvIdx = SE->openIntv();
1364 LLVM_DEBUG(dbgs() << "Split for compact region in " << B
1365 << " bundles, intv " << Cand.IntvIdx << ".\n");
1366 (void)B;
1367 }
1368 }
1369
1370 splitAroundRegion(LREdit, UsedCands);
1371 return MCRegister();
1372}
1373
1374// VirtReg has a physical Hint, this function tries to split VirtReg around
1375// Hint if we can place new COPY instructions in cold blocks.
1376bool RAGreedy::trySplitAroundHintReg(MCRegister Hint,
1377 const LiveInterval &VirtReg,
1378 SmallVectorImpl<Register> &NewVRegs,
1379 AllocationOrder &Order) {
1380 // Split the VirtReg may generate COPY instructions in multiple cold basic
1381 // blocks, and increase code size. So we avoid it when the function is
1382 // optimized for size.
1383 if (MF->getFunction().hasOptSize())
1384 return false;
1385
1386 // Don't allow repeated splitting as a safe guard against looping.
1387 if (ExtraInfo->getStage(VirtReg) >= RS_Split2)
1388 return false;
1389
1390 BlockFrequency Cost = BlockFrequency(0);
1391 Register Reg = VirtReg.reg();
1392
1393 // Compute the cost of assigning a non Hint physical register to VirtReg.
1394 // We define it as the total frequency of broken COPY instructions to/from
1395 // Hint register, and after split, they can be deleted.
1396
1397 // FIXME: This is miscounting the costs with subregisters. In particular, this
1398 // should support recognizing SplitKit formed copy bundles instead of direct
1399 // copy instructions, which will appear in the same block.
1400 for (const MachineOperand &Opnd : MRI->reg_nodbg_operands(Reg)) {
1401 const MachineInstr &Instr = *Opnd.getParent();
1402 if (!Instr.isCopy() || Opnd.isImplicit())
1403 continue;
1404
1405 // Look for the other end of the copy.
1406 const bool IsDef = Opnd.isDef();
1407 const MachineOperand &OtherOpnd = Instr.getOperand(i: IsDef);
1408 Register OtherReg = OtherOpnd.getReg();
1409 assert(Reg == Opnd.getReg());
1410 if (OtherReg == Reg)
1411 continue;
1412
1413 unsigned SubReg = Opnd.getSubReg();
1414 unsigned OtherSubReg = OtherOpnd.getSubReg();
1415 if (SubReg && OtherSubReg && SubReg != OtherSubReg)
1416 continue;
1417
1418 // Check if VirtReg interferes with OtherReg after this COPY instruction.
1419 if (Opnd.readsReg()) {
1420 SlotIndex Index = LIS->getInstructionIndex(Instr).getRegSlot();
1421
1422 if (SubReg) {
1423 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubIdx: SubReg);
1424 if (IsDef)
1425 Mask = ~Mask;
1426
1427 if (any_of(Range: VirtReg.subranges(), P: [=](const LiveInterval::SubRange &S) {
1428 return (S.LaneMask & Mask).any() && S.liveAt(index: Index);
1429 })) {
1430 continue;
1431 }
1432 } else {
1433 if (VirtReg.liveAt(index: Index))
1434 continue;
1435 }
1436 }
1437
1438 MCRegister OtherPhysReg =
1439 OtherReg.isPhysical() ? OtherReg.asMCReg() : VRM->getPhys(virtReg: OtherReg);
1440 MCRegister ThisHint = SubReg ? TRI->getSubReg(Reg: Hint, Idx: SubReg) : Hint;
1441 if (OtherPhysReg == ThisHint)
1442 Cost += MBFI->getBlockFreq(MBB: Instr.getParent());
1443 }
1444
1445 // Decrease the cost so it will be split in colder blocks.
1446 BranchProbability Threshold(SplitThresholdForRegWithHint, 100);
1447 Cost *= Threshold;
1448 if (Cost == BlockFrequency(0))
1449 return false;
1450
1451 unsigned NumCands = 0;
1452 unsigned BestCand = NoCand;
1453 SA->analyze(li: &VirtReg);
1454 calculateRegionSplitCostAroundReg(PhysReg: Hint, Order, BestCost&: Cost, NumCands, BestCand);
1455 if (BestCand == NoCand)
1456 return false;
1457
1458 doRegionSplit(VirtReg, BestCand, HasCompact: false/*HasCompact*/, NewVRegs);
1459 return true;
1460}
1461
1462//===----------------------------------------------------------------------===//
1463// Per-Block Splitting
1464//===----------------------------------------------------------------------===//
1465
1466/// tryBlockSplit - Split a global live range around every block with uses. This
1467/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1468/// they don't allocate.
1469MCRegister RAGreedy::tryBlockSplit(const LiveInterval &VirtReg,
1470 AllocationOrder &Order,
1471 SmallVectorImpl<Register> &NewVRegs) {
1472 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1473 Register Reg = VirtReg.reg();
1474 bool SingleInstrs = RegClassInfo.isProperSubClass(RC: MRI->getRegClass(Reg));
1475 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1476 SE->reset(LREdit, SplitSpillMode);
1477 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1478 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
1479 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1480 SE->splitSingleBlock(BI);
1481 }
1482 // No blocks were split.
1483 if (LREdit.empty())
1484 return MCRegister();
1485
1486 // We did split for some blocks.
1487 SmallVector<unsigned, 8> IntvMap;
1488 SE->finish(LRMap: &IntvMap);
1489
1490 // Tell LiveDebugVariables about the new ranges.
1491 DebugVars->splitRegister(OldReg: Reg, NewRegs: LREdit.regs(), LIS&: *LIS);
1492
1493 // Sort out the new intervals created by splitting. The remainder interval
1494 // goes straight to spilling, the new local ranges get to stay RS_New.
1495 for (unsigned I = 0, E = LREdit.size(); I != E; ++I) {
1496 const LiveInterval &LI = LIS->getInterval(Reg: LREdit.get(idx: I));
1497 if (ExtraInfo->getOrInitStage(Reg: LI.reg()) == RS_New && IntvMap[I] == 0)
1498 ExtraInfo->setStage(VirtReg: LI, Stage: RS_Spill);
1499 }
1500
1501 if (VerifyEnabled)
1502 MF->verify(LiveInts: LIS, Indexes, Banner: "After splitting live range around basic blocks",
1503 OS: &errs());
1504 return MCRegister();
1505}
1506
1507//===----------------------------------------------------------------------===//
1508// Per-Instruction Splitting
1509//===----------------------------------------------------------------------===//
1510
1511/// Get the number of allocatable registers that match the constraints of \p Reg
1512/// on \p MI and that are also in \p SuperRC.
1513static unsigned getNumAllocatableRegsForConstraints(
1514 const MachineInstr *MI, Register Reg, const TargetRegisterClass *SuperRC,
1515 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1516 const RegisterClassInfo &RCI) {
1517 assert(SuperRC && "Invalid register class");
1518
1519 const TargetRegisterClass *ConstrainedRC =
1520 MI->getRegClassConstraintEffectForVReg(Reg, CurRC: SuperRC, TII, TRI,
1521 /* ExploreBundle */ true);
1522 if (!ConstrainedRC)
1523 return 0;
1524 return RCI.getNumAllocatableRegs(RC: ConstrainedRC);
1525}
1526
1527static LaneBitmask getInstReadLaneMask(const MachineRegisterInfo &MRI,
1528 const TargetRegisterInfo &TRI,
1529 const MachineInstr &FirstMI,
1530 Register Reg) {
1531 LaneBitmask Mask;
1532 SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
1533 (void)AnalyzeVirtRegInBundle(MI&: const_cast<MachineInstr &>(FirstMI), Reg, Ops: &Ops);
1534
1535 for (auto [MI, OpIdx] : Ops) {
1536 const MachineOperand &MO = MI->getOperand(i: OpIdx);
1537 assert(MO.isReg() && MO.getReg() == Reg);
1538 unsigned SubReg = MO.getSubReg();
1539 if (SubReg == 0 && MO.isUse()) {
1540 if (MO.isUndef())
1541 continue;
1542 return MRI.getMaxLaneMaskForVReg(Reg);
1543 }
1544
1545 LaneBitmask SubRegMask = TRI.getSubRegIndexLaneMask(SubIdx: SubReg);
1546 if (MO.isDef()) {
1547 if (!MO.isUndef())
1548 Mask |= ~SubRegMask;
1549 } else
1550 Mask |= SubRegMask;
1551 }
1552
1553 return Mask;
1554}
1555
1556/// Return true if \p MI at \P Use reads a subset of the lanes live in \p
1557/// VirtReg.
1558static bool readsLaneSubset(const MachineRegisterInfo &MRI,
1559 const MachineInstr *MI, const LiveInterval &VirtReg,
1560 const TargetRegisterInfo *TRI, SlotIndex Use,
1561 const TargetInstrInfo *TII) {
1562 // Early check the common case. Beware of the semi-formed bundles SplitKit
1563 // creates by setting the bundle flag on copies without a matching BUNDLE.
1564
1565 auto DestSrc = TII->isCopyInstr(MI: *MI);
1566 if (DestSrc && !MI->isBundled() &&
1567 DestSrc->Destination->getSubReg() == DestSrc->Source->getSubReg())
1568 return false;
1569
1570 // FIXME: We're only considering uses, but should be consider defs too?
1571 LaneBitmask ReadMask = getInstReadLaneMask(MRI, TRI: *TRI, FirstMI: *MI, Reg: VirtReg.reg());
1572
1573 LaneBitmask LiveAtMask;
1574 for (const LiveInterval::SubRange &S : VirtReg.subranges()) {
1575 if (S.liveAt(index: Use))
1576 LiveAtMask |= S.LaneMask;
1577 }
1578
1579 // If the live lanes aren't different from the lanes used by the instruction,
1580 // this doesn't help.
1581 return (ReadMask & ~(LiveAtMask & TRI->getCoveringLanes())).any();
1582}
1583
1584/// tryInstructionSplit - Split a live range around individual instructions.
1585/// This is normally not worthwhile since the spiller is doing essentially the
1586/// same thing. However, when the live range is in a constrained register
1587/// class, it may help to insert copies such that parts of the live range can
1588/// be moved to a larger register class.
1589///
1590/// This is similar to spilling to a larger register class.
1591MCRegister RAGreedy::tryInstructionSplit(const LiveInterval &VirtReg,
1592 AllocationOrder &Order,
1593 SmallVectorImpl<Register> &NewVRegs) {
1594 const TargetRegisterClass *CurRC = MRI->getRegClass(Reg: VirtReg.reg());
1595 // There is no point to this if there are no larger sub-classes.
1596
1597 bool SplitSubClass = true;
1598 if (!RegClassInfo.isProperSubClass(RC: CurRC)) {
1599 if (!VirtReg.hasSubRanges())
1600 return MCRegister();
1601 SplitSubClass = false;
1602 }
1603
1604 // Always enable split spill mode, since we're effectively spilling to a
1605 // register.
1606 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1607 SE->reset(LREdit, SplitEditor::SM_Size);
1608
1609 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1610 if (Uses.size() <= 1)
1611 return MCRegister();
1612
1613 LLVM_DEBUG(dbgs() << "Split around " << Uses.size()
1614 << " individual instrs.\n");
1615
1616 const TargetRegisterClass *SuperRC =
1617 TRI->getLargestLegalSuperClass(RC: CurRC, *MF);
1618 unsigned SuperRCNumAllocatableRegs =
1619 RegClassInfo.getNumAllocatableRegs(RC: SuperRC);
1620 // Split around every non-copy instruction if this split will relax
1621 // the constraints on the virtual register.
1622 // Otherwise, splitting just inserts uncoalescable copies that do not help
1623 // the allocation.
1624 for (const SlotIndex Use : Uses) {
1625 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(index: Use)) {
1626 if (TII->isFullCopyInstr(MI: *MI) ||
1627 (SplitSubClass &&
1628 SuperRCNumAllocatableRegs ==
1629 getNumAllocatableRegsForConstraints(MI, Reg: VirtReg.reg(), SuperRC,
1630 TII, TRI, RCI: RegClassInfo)) ||
1631 // TODO: Handle split for subranges with subclass constraints?
1632 (!SplitSubClass && VirtReg.hasSubRanges() &&
1633 !readsLaneSubset(MRI: *MRI, MI, VirtReg, TRI, Use, TII))) {
1634 LLVM_DEBUG(dbgs() << " skip:\t" << Use << '\t' << *MI);
1635 continue;
1636 }
1637 }
1638 SE->openIntv();
1639 SlotIndex SegStart = SE->enterIntvBefore(Idx: Use);
1640 SlotIndex SegStop = SE->leaveIntvAfter(Idx: Use);
1641 SE->useIntv(Start: SegStart, End: SegStop);
1642 }
1643
1644 if (LREdit.empty()) {
1645 LLVM_DEBUG(dbgs() << "All uses were copies.\n");
1646 return MCRegister();
1647 }
1648
1649 SmallVector<unsigned, 8> IntvMap;
1650 SE->finish(LRMap: &IntvMap);
1651 DebugVars->splitRegister(OldReg: VirtReg.reg(), NewRegs: LREdit.regs(), LIS&: *LIS);
1652 // Assign all new registers to RS_Spill. This was the last chance.
1653 ExtraInfo->setStage(Begin: LREdit.begin(), End: LREdit.end(), NewStage: RS_Spill);
1654 return MCRegister();
1655}
1656
1657//===----------------------------------------------------------------------===//
1658// Local Splitting
1659//===----------------------------------------------------------------------===//
1660
1661/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1662/// in order to use PhysReg between two entries in SA->UseSlots.
1663///
1664/// GapWeight[I] represents the gap between UseSlots[I] and UseSlots[I + 1].
1665///
1666void RAGreedy::calcGapWeights(MCRegister PhysReg,
1667 SmallVectorImpl<float> &GapWeight) {
1668 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1669 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1670 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1671 const unsigned NumGaps = Uses.size()-1;
1672
1673 // Start and end points for the interference check.
1674 SlotIndex StartIdx =
1675 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1676 SlotIndex StopIdx =
1677 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1678
1679 GapWeight.assign(NumElts: NumGaps, Elt: 0.0f);
1680
1681 // Add interference from each overlapping register.
1682 for (MCRegUnit Unit : TRI->regunits(Reg: PhysReg)) {
1683 if (!Matrix->query(LR: const_cast<LiveInterval &>(SA->getParent()), RegUnit: Unit)
1684 .checkInterference())
1685 continue;
1686
1687 // We know that VirtReg is a continuous interval from FirstInstr to
1688 // LastInstr, so we don't need InterferenceQuery.
1689 //
1690 // Interference that overlaps an instruction is counted in both gaps
1691 // surrounding the instruction. The exception is interference before
1692 // StartIdx and after StopIdx.
1693 //
1694 LiveIntervalUnion::SegmentIter IntI =
1695 Matrix->getLiveUnions()[static_cast<unsigned>(Unit)].find(x: StartIdx);
1696 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1697 // Skip the gaps before IntI.
1698 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1699 if (++Gap == NumGaps)
1700 break;
1701 if (Gap == NumGaps)
1702 break;
1703
1704 // Update the gaps covered by IntI.
1705 const float weight = IntI.value()->weight();
1706 for (; Gap != NumGaps; ++Gap) {
1707 GapWeight[Gap] = std::max(a: GapWeight[Gap], b: weight);
1708 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1709 break;
1710 }
1711 if (Gap == NumGaps)
1712 break;
1713 }
1714 }
1715
1716 // Add fixed interference.
1717 for (MCRegUnit Unit : TRI->regunits(Reg: PhysReg)) {
1718 const LiveRange &LR = LIS->getRegUnit(Unit);
1719 LiveRange::const_iterator I = LR.find(Pos: StartIdx);
1720 LiveRange::const_iterator E = LR.end();
1721
1722 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1723 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1724 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1725 if (++Gap == NumGaps)
1726 break;
1727 if (Gap == NumGaps)
1728 break;
1729
1730 for (; Gap != NumGaps; ++Gap) {
1731 GapWeight[Gap] = huge_valf;
1732 if (Uses[Gap+1].getBaseIndex() >= I->end)
1733 break;
1734 }
1735 if (Gap == NumGaps)
1736 break;
1737 }
1738 }
1739}
1740
1741/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1742/// basic block.
1743///
1744MCRegister RAGreedy::tryLocalSplit(const LiveInterval &VirtReg,
1745 AllocationOrder &Order,
1746 SmallVectorImpl<Register> &NewVRegs) {
1747 // TODO: the function currently only handles a single UseBlock; it should be
1748 // possible to generalize.
1749 if (SA->getUseBlocks().size() != 1)
1750 return MCRegister();
1751
1752 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1753
1754 // Note that it is possible to have an interval that is live-in or live-out
1755 // while only covering a single block - A phi-def can use undef values from
1756 // predecessors, and the block could be a single-block loop.
1757 // We don't bother doing anything clever about such a case, we simply assume
1758 // that the interval is continuous from FirstInstr to LastInstr. We should
1759 // make sure that we don't do anything illegal to such an interval, though.
1760
1761 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1762 if (Uses.size() <= 2)
1763 return MCRegister();
1764 const unsigned NumGaps = Uses.size()-1;
1765
1766 LLVM_DEBUG({
1767 dbgs() << "tryLocalSplit: ";
1768 for (const auto &Use : Uses)
1769 dbgs() << ' ' << Use;
1770 dbgs() << '\n';
1771 });
1772
1773 // If VirtReg is live across any register mask operands, compute a list of
1774 // gaps with register masks.
1775 SmallVector<unsigned, 8> RegMaskGaps;
1776 if (Matrix->checkRegMaskInterference(VirtReg)) {
1777 // Get regmask slots for the whole block.
1778 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(MBBNum: BI.MBB->getNumber());
1779 LLVM_DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1780 // Constrain to VirtReg's live range.
1781 unsigned RI =
1782 llvm::lower_bound(Range&: RMS, Value: Uses.front().getRegSlot()) - RMS.begin();
1783 unsigned RE = RMS.size();
1784 for (unsigned I = 0; I != NumGaps && RI != RE; ++I) {
1785 // Look for Uses[I] <= RMS <= Uses[I + 1].
1786 assert(!SlotIndex::isEarlierInstr(RMS[RI], Uses[I]));
1787 if (SlotIndex::isEarlierInstr(A: Uses[I + 1], B: RMS[RI]))
1788 continue;
1789 // Skip a regmask on the same instruction as the last use. It doesn't
1790 // overlap the live range.
1791 if (SlotIndex::isSameInstr(A: Uses[I + 1], B: RMS[RI]) && I + 1 == NumGaps)
1792 break;
1793 LLVM_DEBUG(dbgs() << ' ' << RMS[RI] << ':' << Uses[I] << '-'
1794 << Uses[I + 1]);
1795 RegMaskGaps.push_back(Elt: I);
1796 // Advance ri to the next gap. A regmask on one of the uses counts in
1797 // both gaps.
1798 while (RI != RE && SlotIndex::isEarlierInstr(A: RMS[RI], B: Uses[I + 1]))
1799 ++RI;
1800 }
1801 LLVM_DEBUG(dbgs() << '\n');
1802 }
1803
1804 // Since we allow local split results to be split again, there is a risk of
1805 // creating infinite loops. It is tempting to require that the new live
1806 // ranges have less instructions than the original. That would guarantee
1807 // convergence, but it is too strict. A live range with 3 instructions can be
1808 // split 2+3 (including the COPY), and we want to allow that.
1809 //
1810 // Instead we use these rules:
1811 //
1812 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1813 // noop split, of course).
1814 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1815 // the new ranges must have fewer instructions than before the split.
1816 // 3. New ranges with the same number of instructions are marked RS_Split2,
1817 // smaller ranges are marked RS_New.
1818 //
1819 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1820 // excessive splitting and infinite loops.
1821 //
1822 bool ProgressRequired = ExtraInfo->getStage(VirtReg) >= RS_Split2;
1823
1824 // Best split candidate.
1825 unsigned BestBefore = NumGaps;
1826 unsigned BestAfter = 0;
1827 float BestDiff = 0;
1828
1829 const float blockFreq =
1830 SpillPlacer->getBlockFrequency(Number: BI.MBB->getNumber()).getFrequency() *
1831 (1.0f / MBFI->getEntryFreq().getFrequency());
1832 SmallVector<float, 8> GapWeight;
1833
1834 for (MCRegister PhysReg : Order) {
1835 assert(PhysReg);
1836 // Keep track of the largest spill weight that would need to be evicted in
1837 // order to make use of PhysReg between UseSlots[I] and UseSlots[I + 1].
1838 calcGapWeights(PhysReg, GapWeight);
1839
1840 // Remove any gaps with regmask clobbers.
1841 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1842 for (unsigned Gap : RegMaskGaps)
1843 GapWeight[Gap] = huge_valf;
1844
1845 // Try to find the best sequence of gaps to close.
1846 // The new spill weight must be larger than any gap interference.
1847
1848 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1849 unsigned SplitBefore = 0, SplitAfter = 1;
1850
1851 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1852 // It is the spill weight that needs to be evicted.
1853 float MaxGap = GapWeight[0];
1854
1855 while (true) {
1856 // Live before/after split?
1857 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1858 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1859
1860 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << ' ' << Uses[SplitBefore]
1861 << '-' << Uses[SplitAfter] << " I=" << MaxGap);
1862
1863 // Stop before the interval gets so big we wouldn't be making progress.
1864 if (!LiveBefore && !LiveAfter) {
1865 LLVM_DEBUG(dbgs() << " all\n");
1866 break;
1867 }
1868 // Should the interval be extended or shrunk?
1869 bool Shrink = true;
1870
1871 // How many gaps would the new range have?
1872 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1873
1874 // Legally, without causing looping?
1875 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1876
1877 if (Legal && MaxGap < huge_valf) {
1878 // Estimate the new spill weight. Each instruction reads or writes the
1879 // register. Conservatively assume there are no read-modify-write
1880 // instructions.
1881 //
1882 // Try to guess the size of the new interval.
1883 const float EstWeight = normalizeSpillWeight(
1884 UseDefFreq: blockFreq * (NewGaps + 1),
1885 Size: Uses[SplitBefore].distance(other: Uses[SplitAfter]) +
1886 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
1887 NumInstr: 1);
1888 // Would this split be possible to allocate?
1889 // Never allocate all gaps, we wouldn't be making progress.
1890 LLVM_DEBUG(dbgs() << " w=" << EstWeight);
1891 if (EstWeight * Hysteresis >= MaxGap) {
1892 Shrink = false;
1893 float Diff = EstWeight - MaxGap;
1894 if (Diff > BestDiff) {
1895 LLVM_DEBUG(dbgs() << " (best)");
1896 BestDiff = Hysteresis * Diff;
1897 BestBefore = SplitBefore;
1898 BestAfter = SplitAfter;
1899 }
1900 }
1901 }
1902
1903 // Try to shrink.
1904 if (Shrink) {
1905 if (++SplitBefore < SplitAfter) {
1906 LLVM_DEBUG(dbgs() << " shrink\n");
1907 // Recompute the max when necessary.
1908 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1909 MaxGap = GapWeight[SplitBefore];
1910 for (unsigned I = SplitBefore + 1; I != SplitAfter; ++I)
1911 MaxGap = std::max(a: MaxGap, b: GapWeight[I]);
1912 }
1913 continue;
1914 }
1915 MaxGap = 0;
1916 }
1917
1918 // Try to extend the interval.
1919 if (SplitAfter >= NumGaps) {
1920 LLVM_DEBUG(dbgs() << " end\n");
1921 break;
1922 }
1923
1924 LLVM_DEBUG(dbgs() << " extend\n");
1925 MaxGap = std::max(a: MaxGap, b: GapWeight[SplitAfter++]);
1926 }
1927 }
1928
1929 // Didn't find any candidates?
1930 if (BestBefore == NumGaps)
1931 return MCRegister();
1932
1933 LLVM_DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore] << '-'
1934 << Uses[BestAfter] << ", " << BestDiff << ", "
1935 << (BestAfter - BestBefore + 1) << " instrs\n");
1936
1937 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1938 SE->reset(LREdit);
1939
1940 SE->openIntv();
1941 SlotIndex SegStart = SE->enterIntvBefore(Idx: Uses[BestBefore]);
1942 SlotIndex SegStop = SE->leaveIntvAfter(Idx: Uses[BestAfter]);
1943 SE->useIntv(Start: SegStart, End: SegStop);
1944 SmallVector<unsigned, 8> IntvMap;
1945 SE->finish(LRMap: &IntvMap);
1946 DebugVars->splitRegister(OldReg: VirtReg.reg(), NewRegs: LREdit.regs(), LIS&: *LIS);
1947 // If the new range has the same number of instructions as before, mark it as
1948 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1949 // leave the new intervals as RS_New so they can compete.
1950 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1951 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1952 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1953 if (NewGaps >= NumGaps) {
1954 LLVM_DEBUG(dbgs() << "Tagging non-progress ranges:");
1955 assert(!ProgressRequired && "Didn't make progress when it was required.");
1956 for (unsigned I = 0, E = IntvMap.size(); I != E; ++I)
1957 if (IntvMap[I] == 1) {
1958 ExtraInfo->setStage(VirtReg: LIS->getInterval(Reg: LREdit.get(idx: I)), Stage: RS_Split2);
1959 LLVM_DEBUG(dbgs() << ' ' << printReg(LREdit.get(I)));
1960 }
1961 LLVM_DEBUG(dbgs() << '\n');
1962 }
1963 ++NumLocalSplits;
1964
1965 return MCRegister();
1966}
1967
1968//===----------------------------------------------------------------------===//
1969// Live Range Splitting
1970//===----------------------------------------------------------------------===//
1971
1972/// trySplit - Try to split VirtReg or one of its interferences, making it
1973/// assignable.
1974/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1975MCRegister RAGreedy::trySplit(const LiveInterval &VirtReg,
1976 AllocationOrder &Order,
1977 SmallVectorImpl<Register> &NewVRegs,
1978 const SmallVirtRegSet &FixedRegisters) {
1979 // Ranges must be Split2 or less.
1980 if (ExtraInfo->getStage(VirtReg) >= RS_Spill)
1981 return MCRegister();
1982
1983 // Local intervals are handled separately.
1984 if (LIS->intervalIsInOneMBB(LI: VirtReg)) {
1985 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
1986 TimerGroupDescription, TimePassesIsEnabled);
1987 SA->analyze(li: &VirtReg);
1988 MCRegister PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1989 if (PhysReg || !NewVRegs.empty())
1990 return PhysReg;
1991 return tryInstructionSplit(VirtReg, Order, NewVRegs);
1992 }
1993
1994 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
1995 TimerGroupDescription, TimePassesIsEnabled);
1996
1997 SA->analyze(li: &VirtReg);
1998
1999 // First try to split around a region spanning multiple blocks. RS_Split2
2000 // ranges already made dubious progress with region splitting, so they go
2001 // straight to single block splitting.
2002 if (ExtraInfo->getStage(VirtReg) < RS_Split2) {
2003 MCRegister PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2004 if (PhysReg || !NewVRegs.empty())
2005 return PhysReg;
2006 }
2007
2008 // Then isolate blocks.
2009 return tryBlockSplit(VirtReg, Order, NewVRegs);
2010}
2011
2012//===----------------------------------------------------------------------===//
2013// Last Chance Recoloring
2014//===----------------------------------------------------------------------===//
2015
2016/// Return true if \p reg has any tied def operand.
2017static bool hasTiedDef(MachineRegisterInfo *MRI, Register reg) {
2018 for (const MachineOperand &MO : MRI->def_operands(Reg: reg))
2019 if (MO.isTied())
2020 return true;
2021
2022 return false;
2023}
2024
2025/// Return true if the existing assignment of \p Intf overlaps, but is not the
2026/// same, as \p PhysReg.
2027static bool assignedRegPartiallyOverlaps(const TargetRegisterInfo &TRI,
2028 const VirtRegMap &VRM,
2029 MCRegister PhysReg,
2030 const LiveInterval &Intf) {
2031 MCRegister AssignedReg = VRM.getPhys(virtReg: Intf.reg());
2032 if (PhysReg == AssignedReg)
2033 return false;
2034 return TRI.regsOverlap(RegA: PhysReg, RegB: AssignedReg);
2035}
2036
2037/// mayRecolorAllInterferences - Check if the virtual registers that
2038/// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
2039/// recolored to free \p PhysReg.
2040/// When true is returned, \p RecoloringCandidates has been augmented with all
2041/// the live intervals that need to be recolored in order to free \p PhysReg
2042/// for \p VirtReg.
2043/// \p FixedRegisters contains all the virtual registers that cannot be
2044/// recolored.
2045bool RAGreedy::mayRecolorAllInterferences(
2046 MCRegister PhysReg, const LiveInterval &VirtReg,
2047 SmallLISet &RecoloringCandidates, const SmallVirtRegSet &FixedRegisters) {
2048 const TargetRegisterClass *CurRC = MRI->getRegClass(Reg: VirtReg.reg());
2049
2050 for (MCRegUnit Unit : TRI->regunits(Reg: PhysReg)) {
2051 LiveIntervalUnion::Query &Q = Matrix->query(LR: VirtReg, RegUnit: Unit);
2052 // If there is LastChanceRecoloringMaxInterference or more interferences,
2053 // chances are one would not be recolorable.
2054 if (Q.interferingVRegs(MaxInterferingRegs: LastChanceRecoloringMaxInterference).size() >=
2055 LastChanceRecoloringMaxInterference &&
2056 !ExhaustiveSearch) {
2057 LLVM_DEBUG(dbgs() << "Early abort: too many interferences.\n");
2058 CutOffInfo |= CO_Interf;
2059 return false;
2060 }
2061 for (const LiveInterval *Intf : reverse(C: Q.interferingVRegs())) {
2062 // If Intf is done and sits on the same register class as VirtReg, it
2063 // would not be recolorable as it is in the same state as
2064 // VirtReg. However there are at least two exceptions.
2065 //
2066 // If VirtReg has tied defs and Intf doesn't, then
2067 // there is still a point in examining if it can be recolorable.
2068 //
2069 // Additionally, if the register class has overlapping tuple members, it
2070 // may still be recolorable using a different tuple. This is more likely
2071 // if the existing assignment aliases with the candidate.
2072 //
2073 if (((ExtraInfo->getStage(VirtReg: *Intf) == RS_Done &&
2074 MRI->getRegClass(Reg: Intf->reg()) == CurRC &&
2075 !assignedRegPartiallyOverlaps(TRI: *TRI, VRM: *VRM, PhysReg, Intf: *Intf)) &&
2076 !(hasTiedDef(MRI, reg: VirtReg.reg()) &&
2077 !hasTiedDef(MRI, reg: Intf->reg()))) ||
2078 FixedRegisters.count(V: Intf->reg())) {
2079 LLVM_DEBUG(
2080 dbgs() << "Early abort: the interference is not recolorable.\n");
2081 return false;
2082 }
2083 RecoloringCandidates.insert(X: Intf);
2084 }
2085 }
2086 return true;
2087}
2088
2089/// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
2090/// its interferences.
2091/// Last chance recoloring chooses a color for \p VirtReg and recolors every
2092/// virtual register that was using it. The recoloring process may recursively
2093/// use the last chance recoloring. Therefore, when a virtual register has been
2094/// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
2095/// be last-chance-recolored again during this recoloring "session".
2096/// E.g.,
2097/// Let
2098/// vA can use {R1, R2 }
2099/// vB can use { R2, R3}
2100/// vC can use {R1 }
2101/// Where vA, vB, and vC cannot be split anymore (they are reloads for
2102/// instance) and they all interfere.
2103///
2104/// vA is assigned R1
2105/// vB is assigned R2
2106/// vC tries to evict vA but vA is already done.
2107/// Regular register allocation fails.
2108///
2109/// Last chance recoloring kicks in:
2110/// vC does as if vA was evicted => vC uses R1.
2111/// vC is marked as fixed.
2112/// vA needs to find a color.
2113/// None are available.
2114/// vA cannot evict vC: vC is a fixed virtual register now.
2115/// vA does as if vB was evicted => vA uses R2.
2116/// vB needs to find a color.
2117/// R3 is available.
2118/// Recoloring => vC = R1, vA = R2, vB = R3
2119///
2120/// \p Order defines the preferred allocation order for \p VirtReg.
2121/// \p NewRegs will contain any new virtual register that have been created
2122/// (split, spill) during the process and that must be assigned.
2123/// \p FixedRegisters contains all the virtual registers that cannot be
2124/// recolored.
2125///
2126/// \p RecolorStack tracks the original assignments of successfully recolored
2127/// registers.
2128///
2129/// \p Depth gives the current depth of the last chance recoloring.
2130/// \return a physical register that can be used for VirtReg or ~0u if none
2131/// exists.
2132MCRegister RAGreedy::tryLastChanceRecoloring(
2133 const LiveInterval &VirtReg, AllocationOrder &Order,
2134 SmallVectorImpl<Register> &NewVRegs, SmallVirtRegSet &FixedRegisters,
2135 RecoloringStack &RecolorStack, unsigned Depth) {
2136 if (!TRI->shouldUseLastChanceRecoloringForVirtReg(MF: *MF, VirtReg))
2137 return ~0u;
2138
2139 LLVM_DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2140
2141 const ssize_t EntryStackSize = RecolorStack.size();
2142
2143 // Ranges must be Done.
2144 assert((ExtraInfo->getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
2145 "Last chance recoloring should really be last chance");
2146 // Set the max depth to LastChanceRecoloringMaxDepth.
2147 // We may want to reconsider that if we end up with a too large search space
2148 // for target with hundreds of registers.
2149 // Indeed, in that case we may want to cut the search space earlier.
2150 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
2151 LLVM_DEBUG(dbgs() << "Abort because max depth has been reached.\n");
2152 CutOffInfo |= CO_Depth;
2153 return ~0u;
2154 }
2155
2156 // Set of Live intervals that will need to be recolored.
2157 SmallLISet RecoloringCandidates;
2158
2159 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2160 // this recoloring "session".
2161 assert(!FixedRegisters.count(VirtReg.reg()));
2162 FixedRegisters.insert(V: VirtReg.reg());
2163 SmallVector<Register, 4> CurrentNewVRegs;
2164
2165 for (MCRegister PhysReg : Order) {
2166 assert(PhysReg.isValid());
2167 LLVM_DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2168 << printReg(PhysReg, TRI) << '\n');
2169 RecoloringCandidates.clear();
2170 CurrentNewVRegs.clear();
2171
2172 // It is only possible to recolor virtual register interference.
2173 if (Matrix->checkInterference(VirtReg, PhysReg) >
2174 LiveRegMatrix::IK_VirtReg) {
2175 LLVM_DEBUG(
2176 dbgs() << "Some interferences 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 LLVM_DEBUG(dbgs() << "Some interferences cannot be recolored.\n");
2186 continue;
2187 }
2188
2189 // RecoloringCandidates contains all the virtual registers that interfere
2190 // with VirtReg on PhysReg (or one of its aliases). Enqueue them for
2191 // recoloring and perform the actual recoloring.
2192 PQueue RecoloringQueue;
2193 for (const LiveInterval *RC : RecoloringCandidates) {
2194 Register ItVirtReg = RC->reg();
2195 enqueue(CurQueue&: RecoloringQueue, LI: RC);
2196 assert(VRM->hasPhys(ItVirtReg) &&
2197 "Interferences are supposed to be with allocated variables");
2198
2199 // Record the current allocation.
2200 RecolorStack.push_back(Elt: std::make_pair(x&: RC, y: VRM->getPhys(virtReg: ItVirtReg)));
2201
2202 // unset the related struct.
2203 Matrix->unassign(VirtReg: *RC);
2204 }
2205
2206 // Do as if VirtReg was assigned to PhysReg so that the underlying
2207 // recoloring has the right information about the interferes and
2208 // available colors.
2209 Matrix->assign(VirtReg, PhysReg);
2210
2211 // VirtReg may be deleted during tryRecoloringCandidates, save a copy.
2212 Register ThisVirtReg = VirtReg.reg();
2213
2214 // Save the current recoloring state.
2215 // If we cannot recolor all the interferences, we will have to start again
2216 // at this point for the next physical register.
2217 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2218 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2219 FixedRegisters, RecolorStack, Depth)) {
2220 // Push the queued vregs into the main queue.
2221 llvm::append_range(C&: NewVRegs, R&: CurrentNewVRegs);
2222 // Do not mess up with the global assignment process.
2223 // I.e., VirtReg must be unassigned.
2224 if (VRM->hasPhys(virtReg: ThisVirtReg)) {
2225 Matrix->unassign(VirtReg);
2226 return PhysReg;
2227 }
2228
2229 // It is possible VirtReg will be deleted during tryRecoloringCandidates.
2230 LLVM_DEBUG(dbgs() << "tryRecoloringCandidates deleted a fixed register "
2231 << printReg(ThisVirtReg) << '\n');
2232 FixedRegisters.erase(V: ThisVirtReg);
2233 return MCRegister();
2234 }
2235
2236 LLVM_DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2237 << printReg(PhysReg, TRI) << '\n');
2238
2239 // The recoloring attempt failed, undo the changes.
2240 FixedRegisters = SaveFixedRegisters;
2241 Matrix->unassign(VirtReg);
2242
2243 // For a newly created vreg which is also in RecoloringCandidates,
2244 // don't add it to NewVRegs because its physical register will be restored
2245 // below. Other vregs in CurrentNewVRegs are created by calling
2246 // selectOrSplit and should be added into NewVRegs.
2247 for (Register R : CurrentNewVRegs) {
2248 if (RecoloringCandidates.count(key: &LIS->getInterval(Reg: R)))
2249 continue;
2250 NewVRegs.push_back(Elt: R);
2251 }
2252
2253 // Roll back our unsuccessful recoloring. Also roll back any successful
2254 // recolorings in any recursive recoloring attempts, since it's possible
2255 // they would have introduced conflicts with assignments we will be
2256 // restoring further up the stack. Perform all unassignments prior to
2257 // reassigning, since sub-recolorings may have conflicted with the registers
2258 // we are going to restore to their original assignments.
2259 for (ssize_t I = RecolorStack.size() - 1; I >= EntryStackSize; --I) {
2260 const LiveInterval *LI;
2261 MCRegister PhysReg;
2262 std::tie(args&: LI, args&: PhysReg) = RecolorStack[I];
2263
2264 if (VRM->hasPhys(virtReg: LI->reg()))
2265 Matrix->unassign(VirtReg: *LI);
2266 }
2267
2268 for (size_t I = EntryStackSize; I != RecolorStack.size(); ++I) {
2269 const LiveInterval *LI;
2270 MCRegister PhysReg;
2271 std::tie(args&: LI, args&: PhysReg) = RecolorStack[I];
2272 if (!LI->empty() && !MRI->reg_nodbg_empty(RegNo: LI->reg()))
2273 Matrix->assign(VirtReg: *LI, PhysReg);
2274 }
2275
2276 // Pop the stack of recoloring attempts.
2277 RecolorStack.resize(N: EntryStackSize);
2278 }
2279
2280 // Last chance recoloring did not worked either, give up.
2281 return ~0u;
2282}
2283
2284/// tryRecoloringCandidates - Try to assign a new color to every register
2285/// in \RecoloringQueue.
2286/// \p NewRegs will contain any new virtual register created during the
2287/// recoloring process.
2288/// \p FixedRegisters[in/out] contains all the registers that have been
2289/// recolored.
2290/// \return true if all virtual registers in RecoloringQueue were successfully
2291/// recolored, false otherwise.
2292bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2293 SmallVectorImpl<Register> &NewVRegs,
2294 SmallVirtRegSet &FixedRegisters,
2295 RecoloringStack &RecolorStack,
2296 unsigned Depth) {
2297 while (!RecoloringQueue.empty()) {
2298 const LiveInterval *LI = dequeue(CurQueue&: RecoloringQueue);
2299 LLVM_DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2300 MCRegister PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters,
2301 RecolorStack, Depth + 1);
2302 // When splitting happens, the live-range may actually be empty.
2303 // In that case, this is okay to continue the recoloring even
2304 // if we did not find an alternative color for it. Indeed,
2305 // there will not be anything to color for LI in the end.
2306 if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
2307 return false;
2308
2309 if (!PhysReg) {
2310 assert(LI->empty() && "Only empty live-range do not require a register");
2311 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2312 << " succeeded. Empty LI.\n");
2313 continue;
2314 }
2315 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2316 << " succeeded with: " << printReg(PhysReg, TRI) << '\n');
2317
2318 Matrix->assign(VirtReg: *LI, PhysReg);
2319 FixedRegisters.insert(V: LI->reg());
2320 }
2321 return true;
2322}
2323
2324//===----------------------------------------------------------------------===//
2325// Main Entry Point
2326//===----------------------------------------------------------------------===//
2327
2328MCRegister RAGreedy::selectOrSplit(const LiveInterval &VirtReg,
2329 SmallVectorImpl<Register> &NewVRegs) {
2330 CutOffInfo = CO_None;
2331 LLVMContext &Ctx = MF->getFunction().getContext();
2332 SmallVirtRegSet FixedRegisters;
2333 RecoloringStack RecolorStack;
2334 MCRegister Reg =
2335 selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters, RecolorStack);
2336 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2337 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2338 if (CutOffEncountered == CO_Depth)
2339 Ctx.emitError(ErrorStr: "register allocation failed: maximum depth for recoloring "
2340 "reached. Use -fexhaustive-register-search to skip "
2341 "cutoffs");
2342 else if (CutOffEncountered == CO_Interf)
2343 Ctx.emitError(ErrorStr: "register allocation failed: maximum interference for "
2344 "recoloring reached. Use -fexhaustive-register-search "
2345 "to skip cutoffs");
2346 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2347 Ctx.emitError(ErrorStr: "register allocation failed: maximum interference and "
2348 "depth for recoloring reached. Use "
2349 "-fexhaustive-register-search to skip cutoffs");
2350 }
2351 return Reg;
2352}
2353
2354/// calcSpillCost - Compute how expensive it would be to spill the live range in
2355/// LI into memory.
2356BlockFrequency RAGreedy::calcSpillCost(const LiveInterval &LI) {
2357 uint64_t SpillCost = 0;
2358 SmallPtrSet<MachineInstr *, 8> Visited;
2359
2360 for (MachineRegisterInfo::reg_instr_nodbg_iterator
2361 I = MRI->reg_instr_nodbg_begin(RegNo: LI.reg()),
2362 E = MRI->reg_instr_nodbg_end();
2363 I != E;) {
2364 MachineInstr *MI = &*(I++);
2365 if (MI->isMetaInstruction())
2366 continue;
2367 if (!Visited.insert(Ptr: MI).second)
2368 continue;
2369
2370 auto [Reads, Writes] = MI->readsWritesVirtualRegister(Reg: LI.reg());
2371 auto MBBFreq = SpillPlacer->getBlockFrequency(Number: MI->getParent()->getNumber());
2372 SpillCost += (Reads + Writes) * MBBFreq.getFrequency();
2373 }
2374
2375 return BlockFrequency(SpillCost);
2376}
2377
2378/// Using a CSR for the first time has a cost because it causes push|pop
2379/// to be added to prologue|epilogue. Splitting a cold section of the live
2380/// range can have lower cost than using the CSR for the first time;
2381/// Spilling a live range in the cold path can have lower cost than using
2382/// the CSR for the first time. Returns the physical register if we decide
2383/// to use the CSR; otherwise return MCRegister().
2384MCRegister RAGreedy::tryAssignCSRFirstTime(
2385 const LiveInterval &VirtReg, AllocationOrder &Order, MCRegister PhysReg,
2386 uint8_t &CostPerUseLimit, SmallVectorImpl<Register> &NewVRegs) {
2387 if (ExtraInfo->getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2388 // We choose spill over using the CSR for the first time if the spill cost
2389 // is lower than CSRCost.
2390 SA->analyze(li: &VirtReg);
2391 if (calcSpillCost(LI: VirtReg) >= CSRCost)
2392 return PhysReg;
2393
2394 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2395 // we will not use a callee-saved register in tryEvict.
2396 CostPerUseLimit = 1;
2397 return MCRegister();
2398 }
2399 if (ExtraInfo->getStage(VirtReg) < RS_Split) {
2400 // We choose pre-splitting over using the CSR for the first time if
2401 // the cost of splitting is lower than CSRCost.
2402 SA->analyze(li: &VirtReg);
2403 unsigned NumCands = 0;
2404 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2405 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2406 NumCands, IgnoreCSR: true /*IgnoreCSR*/);
2407 if (BestCand == NoCand)
2408 // Use the CSR if we can't find a region split below CSRCost.
2409 return PhysReg;
2410
2411 // Perform the actual pre-splitting.
2412 doRegionSplit(VirtReg, BestCand, HasCompact: false/*HasCompact*/, NewVRegs);
2413 return MCRegister();
2414 }
2415 return PhysReg;
2416}
2417
2418void RAGreedy::aboutToRemoveInterval(const LiveInterval &LI) {
2419 // Do not keep invalid information around.
2420 SetOfBrokenHints.remove(X: &LI);
2421}
2422
2423void RAGreedy::initializeCSRCost() {
2424 if (!CSRCostScale.getNumOccurrences() &&
2425 (CSRFirstTimeCost.getNumOccurrences() || TRI->getCSRCost())) {
2426 // We should deprecate the usage of CSRFirstTimeCost!
2427 // We use the command-line option if it is explicitly set, otherwise use the
2428 // larger one out of the command-line option and the value reported by TRI.
2429 CSRCost = BlockFrequency(
2430 CSRFirstTimeCost.getNumOccurrences()
2431 ? CSRFirstTimeCost
2432 : std::max(a: (unsigned)CSRFirstTimeCost, b: TRI->getCSRCost()));
2433 if (!CSRCost.getFrequency())
2434 return;
2435
2436 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2437 uint64_t ActualEntry = MBFI->getEntryFreq().getFrequency();
2438 if (!ActualEntry) {
2439 CSRCost = BlockFrequency(0);
2440 return;
2441 }
2442 uint64_t FixedEntry = 1 << 14;
2443 if (ActualEntry < FixedEntry) {
2444 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2445 } else if (ActualEntry <= UINT32_MAX) {
2446 // Invert the fraction and divide.
2447 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2448 } else {
2449 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2450 CSRCost =
2451 BlockFrequency(CSRCost.getFrequency() * (ActualEntry / FixedEntry));
2452 }
2453 } else {
2454 uint64_t EntryFreq = MBFI->getEntryFreq().getFrequency();
2455 CSRCost = BlockFrequency(TRI->getCSRFirstUseCost(MF: *MF) * EntryFreq);
2456 unsigned Scale = TRI->getCSRCostScale(MF: *MF);
2457 // Command line specified CSRCostScale can override target's default value.
2458 if (CSRCostScale.getNumOccurrences())
2459 Scale = CSRCostScale;
2460
2461 if (Scale < 100)
2462 CSRCost *= BranchProbability(Scale, 100);
2463 else
2464 CSRCost /= BranchProbability(100, Scale);
2465 }
2466}
2467
2468/// Collect the hint info for \p Reg.
2469/// The results are stored into \p Out.
2470/// \p Out is not cleared before being populated.
2471void RAGreedy::collectHintInfo(Register Reg, HintsInfo &Out) {
2472 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
2473
2474 for (const MachineOperand &Opnd : MRI->reg_nodbg_operands(Reg)) {
2475 const MachineInstr &Instr = *Opnd.getParent();
2476 if (!Instr.isCopy() || Opnd.isImplicit())
2477 continue;
2478
2479 // Look for the other end of the copy.
2480 const MachineOperand &OtherOpnd = Instr.getOperand(i: Opnd.isDef());
2481 Register OtherReg = OtherOpnd.getReg();
2482 if (OtherReg == Reg)
2483 continue;
2484 unsigned OtherSubReg = OtherOpnd.getSubReg();
2485 unsigned SubReg = Opnd.getSubReg();
2486
2487 // Get the current assignment.
2488 MCRegister OtherPhysReg;
2489 if (OtherReg.isPhysical()) {
2490 if (OtherSubReg)
2491 OtherPhysReg = TRI->getMatchingSuperReg(Reg: OtherReg, SubIdx: OtherSubReg, RC);
2492 else if (SubReg)
2493 OtherPhysReg = TRI->getMatchingSuperReg(Reg: OtherReg, SubIdx: SubReg, RC);
2494 else
2495 OtherPhysReg = OtherReg;
2496 } else {
2497 OtherPhysReg = VRM->getPhys(virtReg: OtherReg);
2498 // TODO: Should find matching superregister, but applying this in the
2499 // non-hint case currently causes regressions
2500
2501 if (SubReg && OtherSubReg && SubReg != OtherSubReg)
2502 continue;
2503 }
2504
2505 // Push the collected information.
2506 if (OtherPhysReg) {
2507 Out.push_back(Elt: HintInfo(MBFI->getBlockFreq(MBB: Instr.getParent()), OtherReg,
2508 OtherPhysReg));
2509 }
2510 }
2511}
2512
2513/// Using the given \p List, compute the cost of the broken hints if
2514/// \p PhysReg was used.
2515/// \return The cost of \p List for \p PhysReg.
2516BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2517 MCRegister PhysReg) {
2518 BlockFrequency Cost = BlockFrequency(0);
2519 for (const HintInfo &Info : List) {
2520 if (Info.PhysReg != PhysReg)
2521 Cost += Info.Freq;
2522 }
2523 return Cost;
2524}
2525
2526/// Using the register assigned to \p VirtReg, try to recolor
2527/// all the live ranges that are copy-related with \p VirtReg.
2528/// The recoloring is then propagated to all the live-ranges that have
2529/// been recolored and so on, until no more copies can be coalesced or
2530/// it is not profitable.
2531/// For a given live range, profitability is determined by the sum of the
2532/// frequencies of the non-identity copies it would introduce with the old
2533/// and new register.
2534void RAGreedy::tryHintRecoloring(const LiveInterval &VirtReg) {
2535 // We have a broken hint, check if it is possible to fix it by
2536 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2537 // some register and PhysReg may be available for the other live-ranges.
2538 HintsInfo Info;
2539 Register Reg = VirtReg.reg();
2540 MCRegister PhysReg = VRM->getPhys(virtReg: Reg);
2541 // Start the recoloring algorithm from the input live-interval, then
2542 // it will propagate to the ones that are copy-related with it.
2543 SmallSet<Register, 4> Visited = {Reg};
2544 SmallVector<Register, 2> RecoloringCandidates = {Reg};
2545
2546 LLVM_DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI)
2547 << '(' << printReg(PhysReg, TRI) << ")\n");
2548
2549 do {
2550 Reg = RecoloringCandidates.pop_back_val();
2551
2552 MCRegister CurrPhys = VRM->getPhys(virtReg: Reg);
2553
2554 // This may be a skipped register.
2555 if (!CurrPhys) {
2556 assert(!shouldAllocateRegister(Reg) &&
2557 "We have an unallocated variable which should have been handled");
2558 continue;
2559 }
2560
2561 // Get the live interval mapped with this virtual register to be able
2562 // to check for the interference with the new color.
2563 LiveInterval &LI = LIS->getInterval(Reg);
2564 // Check that the new color matches the register class constraints and
2565 // that it is free for this live range.
2566 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(Reg: PhysReg) ||
2567 Matrix->checkInterference(VirtReg: LI, PhysReg)))
2568 continue;
2569
2570 LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI)
2571 << ") is recolorable.\n");
2572
2573 // Gather the hint info.
2574 Info.clear();
2575 collectHintInfo(Reg, Out&: Info);
2576 // Check if recoloring the live-range will increase the cost of the
2577 // non-identity copies.
2578 if (CurrPhys != PhysReg) {
2579 LLVM_DEBUG(dbgs() << "Checking profitability:\n");
2580 BlockFrequency OldCopiesCost = getBrokenHintFreq(List: Info, PhysReg: CurrPhys);
2581 BlockFrequency NewCopiesCost = getBrokenHintFreq(List: Info, PhysReg);
2582 LLVM_DEBUG(dbgs() << "Old Cost: " << printBlockFreq(*MBFI, OldCopiesCost)
2583 << "\nNew Cost: "
2584 << printBlockFreq(*MBFI, NewCopiesCost) << '\n');
2585 if (OldCopiesCost < NewCopiesCost) {
2586 LLVM_DEBUG(dbgs() << "=> Not profitable.\n");
2587 continue;
2588 }
2589 // At this point, the cost is either cheaper or equal. If it is
2590 // equal, we consider this is profitable because it may expose
2591 // more recoloring opportunities.
2592 LLVM_DEBUG(dbgs() << "=> Profitable.\n");
2593 // Recolor the live-range.
2594 Matrix->unassign(VirtReg: LI);
2595 Matrix->assign(VirtReg: LI, PhysReg);
2596 }
2597 // Push all copy-related live-ranges to keep reconciling the broken
2598 // hints.
2599 for (const HintInfo &HI : Info) {
2600 // We cannot recolor physical register.
2601 if (HI.Reg.isVirtual() && Visited.insert(V: HI.Reg).second)
2602 RecoloringCandidates.push_back(Elt: HI.Reg);
2603 }
2604 } while (!RecoloringCandidates.empty());
2605}
2606
2607/// Try to recolor broken hints.
2608/// Broken hints may be repaired by recoloring when an evicted variable
2609/// freed up a register for a larger live-range.
2610/// Consider the following example:
2611/// BB1:
2612/// a =
2613/// b =
2614/// BB2:
2615/// ...
2616/// = b
2617/// = a
2618/// Let us assume b gets split:
2619/// BB1:
2620/// a =
2621/// b =
2622/// BB2:
2623/// c = b
2624/// ...
2625/// d = c
2626/// = d
2627/// = a
2628/// Because of how the allocation work, b, c, and d may be assigned different
2629/// colors. Now, if a gets evicted later:
2630/// BB1:
2631/// a =
2632/// st a, SpillSlot
2633/// b =
2634/// BB2:
2635/// c = b
2636/// ...
2637/// d = c
2638/// = d
2639/// e = ld SpillSlot
2640/// = e
2641/// This is likely that we can assign the same register for b, c, and d,
2642/// getting rid of 2 copies.
2643void RAGreedy::tryHintsRecoloring() {
2644 for (const LiveInterval *LI : SetOfBrokenHints) {
2645 assert(LI->reg().isVirtual() &&
2646 "Recoloring is possible only for virtual registers");
2647 // Some dead defs may be around (e.g., because of debug uses).
2648 // Ignore those.
2649 if (!VRM->hasPhys(virtReg: LI->reg()))
2650 continue;
2651 tryHintRecoloring(VirtReg: *LI);
2652 }
2653}
2654
2655MCRegister RAGreedy::selectOrSplitImpl(const LiveInterval &VirtReg,
2656 SmallVectorImpl<Register> &NewVRegs,
2657 SmallVirtRegSet &FixedRegisters,
2658 RecoloringStack &RecolorStack,
2659 unsigned Depth) {
2660 uint8_t CostPerUseLimit = uint8_t(~0u);
2661 // First try assigning a free register.
2662 auto Order =
2663 AllocationOrder::create(VirtReg: VirtReg.reg(), VRM: *VRM, RegClassInfo, Matrix);
2664 if (MCRegister PhysReg =
2665 tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) {
2666 // When NewVRegs is not empty, we may have made decisions such as evicting
2667 // a virtual register, go with the earlier decisions and use the physical
2668 // register.
2669 if (CSRCost.getFrequency() &&
2670 EvictAdvisor->isUnusedCalleeSavedReg(PhysReg) && NewVRegs.empty()) {
2671 MCRegister CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2672 CostPerUseLimit, NewVRegs);
2673 if (CSRReg || !NewVRegs.empty())
2674 // Return now if we decide to use a CSR or create new vregs due to
2675 // pre-splitting.
2676 return CSRReg;
2677 } else
2678 return PhysReg;
2679 }
2680 // Non empty NewVRegs means VirtReg has been split.
2681 if (!NewVRegs.empty())
2682 return MCRegister();
2683
2684 LiveRangeStage Stage = ExtraInfo->getStage(VirtReg);
2685 LLVM_DEBUG(dbgs() << StageName[Stage] << " Cascade "
2686 << ExtraInfo->getCascade(VirtReg.reg()) << '\n');
2687
2688 // Try to evict a less worthy live range, but only for ranges from the primary
2689 // queue. The RS_Split ranges already failed to do this, and they should not
2690 // get a second chance until they have been split.
2691 if (Stage != RS_Split) {
2692 if (MCRegister PhysReg =
2693 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit,
2694 FixedRegisters)) {
2695 Register Hint = MRI->getSimpleHint(VReg: VirtReg.reg());
2696 // If VirtReg has a hint and that hint is broken record this
2697 // virtual register as a recoloring candidate for broken hint.
2698 // Indeed, since we evicted a variable in its neighborhood it is
2699 // likely we can at least partially recolor some of the
2700 // copy-related live-ranges.
2701 if (Hint && Hint != PhysReg)
2702 SetOfBrokenHints.insert(X: &VirtReg);
2703 return PhysReg;
2704 }
2705 }
2706
2707 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
2708
2709 // The first time we see a live range, don't try to split or spill.
2710 // Wait until the second time, when all smaller ranges have been allocated.
2711 // This gives a better picture of the interference to split around.
2712 if (Stage < RS_Split) {
2713 ExtraInfo->setStage(VirtReg, Stage: RS_Split);
2714 LLVM_DEBUG(dbgs() << "wait for second round\n");
2715 NewVRegs.push_back(Elt: VirtReg.reg());
2716 return MCRegister();
2717 }
2718
2719 if (Stage < RS_Spill && !VirtReg.empty()) {
2720 // Try splitting VirtReg or interferences.
2721 unsigned NewVRegSizeBefore = NewVRegs.size();
2722 MCRegister PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters);
2723 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore))
2724 return PhysReg;
2725 }
2726
2727 // If we couldn't allocate a register from spilling, there is probably some
2728 // invalid inline assembly. The base class will report it.
2729 if (Stage >= RS_Done || !VirtReg.isSpillable()) {
2730 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2731 RecolorStack, Depth);
2732 }
2733
2734 // Finally spill VirtReg itself.
2735 NamedRegionTimer T("spill", "Spiller", TimerGroupName,
2736 TimerGroupDescription, TimePassesIsEnabled);
2737 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2738 spiller().spill(LRE, Order: &Order);
2739 ExtraInfo->setStage(Begin: NewVRegs.begin(), End: NewVRegs.end(), NewStage: RS_Done);
2740
2741 // Tell LiveDebugVariables about the new ranges. Ranges not being covered by
2742 // the new regs are kept in LDV (still mapping to the old register), until
2743 // we rewrite spilled locations in LDV at a later stage.
2744 for (Register r : spiller().getSpilledRegs())
2745 DebugVars->splitRegister(OldReg: r, NewRegs: LRE.regs(), LIS&: *LIS);
2746 for (Register r : spiller().getReplacedRegs())
2747 DebugVars->splitRegister(OldReg: r, NewRegs: LRE.regs(), LIS&: *LIS);
2748
2749 if (VerifyEnabled)
2750 MF->verify(LiveInts: LIS, Indexes, Banner: "After spilling", OS: &errs());
2751
2752 // The live virtual register requesting allocation was spilled, so tell
2753 // the caller not to allocate anything during this round.
2754 return MCRegister();
2755}
2756
2757void RAGreedy::RAGreedyStats::report(MachineOptimizationRemarkMissed &R) {
2758 using namespace ore;
2759 if (Spills) {
2760 R << NV("NumSpills", Spills) << " spills ";
2761 R << NV("TotalSpillsCost", SpillsCost) << " total spills cost ";
2762 }
2763 if (FoldedSpills) {
2764 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
2765 R << NV("TotalFoldedSpillsCost", FoldedSpillsCost)
2766 << " total folded spills cost ";
2767 }
2768 if (Reloads) {
2769 R << NV("NumReloads", Reloads) << " reloads ";
2770 R << NV("TotalReloadsCost", ReloadsCost) << " total reloads cost ";
2771 }
2772 if (FoldedReloads) {
2773 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
2774 R << NV("TotalFoldedReloadsCost", FoldedReloadsCost)
2775 << " total folded reloads cost ";
2776 }
2777 if (ZeroCostFoldedReloads)
2778 R << NV("NumZeroCostFoldedReloads", ZeroCostFoldedReloads)
2779 << " zero cost folded reloads ";
2780 if (Copies) {
2781 R << NV("NumVRCopies", Copies) << " virtual registers copies ";
2782 R << NV("TotalCopiesCost", CopiesCost) << " total copies cost ";
2783 }
2784}
2785
2786RAGreedy::RAGreedyStats RAGreedy::computeStats(MachineBasicBlock &MBB) {
2787 RAGreedyStats Stats;
2788 const MachineFrameInfo &MFI = MF->getFrameInfo();
2789 int FI;
2790
2791 auto isSpillSlotAccess = [&MFI](const MachineMemOperand *A) {
2792 return MFI.isSpillSlotObjectIndex(ObjectIdx: cast<FixedStackPseudoSourceValue>(
2793 Val: A->getPseudoValue())->getFrameIndex());
2794 };
2795 auto isPatchpointInstr = [](const MachineInstr &MI) {
2796 return MI.getOpcode() == TargetOpcode::PATCHPOINT ||
2797 MI.getOpcode() == TargetOpcode::STACKMAP ||
2798 MI.getOpcode() == TargetOpcode::STATEPOINT;
2799 };
2800 for (MachineInstr &MI : MBB) {
2801 auto DestSrc = TII->isCopyInstr(MI);
2802 if (DestSrc) {
2803 const MachineOperand &Dest = *DestSrc->Destination;
2804 const MachineOperand &Src = *DestSrc->Source;
2805 Register SrcReg = Src.getReg();
2806 Register DestReg = Dest.getReg();
2807 // Only count `COPY`s with a virtual register as source or destination.
2808 if (SrcReg.isVirtual() || DestReg.isVirtual()) {
2809 if (SrcReg.isVirtual()) {
2810 SrcReg = VRM->getPhys(virtReg: SrcReg);
2811 if (SrcReg && Src.getSubReg())
2812 SrcReg = TRI->getSubReg(Reg: SrcReg, Idx: Src.getSubReg());
2813 }
2814 if (DestReg.isVirtual()) {
2815 DestReg = VRM->getPhys(virtReg: DestReg);
2816 if (DestReg && Dest.getSubReg())
2817 DestReg = TRI->getSubReg(Reg: DestReg, Idx: Dest.getSubReg());
2818 }
2819 if (SrcReg != DestReg)
2820 ++Stats.Copies;
2821 }
2822 continue;
2823 }
2824
2825 SmallVector<const MachineMemOperand *, 2> Accesses;
2826 if (TII->isLoadFromStackSlot(MI, FrameIndex&: FI) && MFI.isSpillSlotObjectIndex(ObjectIdx: FI)) {
2827 ++Stats.Reloads;
2828 continue;
2829 }
2830 if (TII->isStoreToStackSlot(MI, FrameIndex&: FI) && MFI.isSpillSlotObjectIndex(ObjectIdx: FI)) {
2831 ++Stats.Spills;
2832 continue;
2833 }
2834 if (TII->hasLoadFromStackSlot(MI, Accesses) &&
2835 llvm::any_of(Range&: Accesses, P: isSpillSlotAccess)) {
2836 if (!isPatchpointInstr(MI)) {
2837 Stats.FoldedReloads += Accesses.size();
2838 continue;
2839 }
2840 // For statepoint there may be folded and zero cost folded stack reloads.
2841 std::pair<unsigned, unsigned> NonZeroCostRange =
2842 TII->getPatchpointUnfoldableRange(MI);
2843 SmallSet<unsigned, 16> FoldedReloads;
2844 SmallSet<unsigned, 16> ZeroCostFoldedReloads;
2845 for (unsigned Idx = 0, E = MI.getNumOperands(); Idx < E; ++Idx) {
2846 MachineOperand &MO = MI.getOperand(i: Idx);
2847 if (!MO.isFI() || !MFI.isSpillSlotObjectIndex(ObjectIdx: MO.getIndex()))
2848 continue;
2849 if (Idx >= NonZeroCostRange.first && Idx < NonZeroCostRange.second)
2850 FoldedReloads.insert(V: MO.getIndex());
2851 else
2852 ZeroCostFoldedReloads.insert(V: MO.getIndex());
2853 }
2854 // If stack slot is used in folded reload it is not zero cost then.
2855 for (unsigned Slot : FoldedReloads)
2856 ZeroCostFoldedReloads.erase(V: Slot);
2857 Stats.FoldedReloads += FoldedReloads.size();
2858 Stats.ZeroCostFoldedReloads += ZeroCostFoldedReloads.size();
2859 continue;
2860 }
2861 Accesses.clear();
2862 if (TII->hasStoreToStackSlot(MI, Accesses) &&
2863 llvm::any_of(Range&: Accesses, P: isSpillSlotAccess)) {
2864 Stats.FoldedSpills += Accesses.size();
2865 }
2866 }
2867 // Set cost of collected statistic by multiplication to relative frequency of
2868 // this basic block.
2869 float RelFreq = MBFI->getBlockFreqRelativeToEntryBlock(MBB: &MBB);
2870 Stats.ReloadsCost = RelFreq * Stats.Reloads;
2871 Stats.FoldedReloadsCost = RelFreq * Stats.FoldedReloads;
2872 Stats.SpillsCost = RelFreq * Stats.Spills;
2873 Stats.FoldedSpillsCost = RelFreq * Stats.FoldedSpills;
2874 Stats.CopiesCost = RelFreq * Stats.Copies;
2875 return Stats;
2876}
2877
2878RAGreedy::RAGreedyStats RAGreedy::reportStats(MachineLoop *L) {
2879 RAGreedyStats Stats;
2880
2881 // Sum up the spill and reloads in subloops.
2882 for (MachineLoop *SubLoop : *L)
2883 Stats.add(other: reportStats(L: SubLoop));
2884
2885 for (MachineBasicBlock *MBB : L->getBlocks())
2886 // Handle blocks that were not included in subloops.
2887 if (Loops->getLoopFor(BB: MBB) == L)
2888 Stats.add(other: computeStats(MBB&: *MBB));
2889
2890 if (!Stats.isEmpty()) {
2891 using namespace ore;
2892
2893 ORE->emit(RemarkBuilder: [&]() {
2894 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReloadCopies",
2895 L->getStartLoc(), L->getHeader());
2896 Stats.report(R);
2897 R << "generated in loop";
2898 return R;
2899 });
2900 }
2901 return Stats;
2902}
2903
2904void RAGreedy::reportStats() {
2905 if (!ORE->allowExtraAnalysis(DEBUG_TYPE))
2906 return;
2907 RAGreedyStats Stats;
2908 for (MachineLoop *L : *Loops)
2909 Stats.add(other: reportStats(L));
2910 // Process non-loop blocks.
2911 for (MachineBasicBlock &MBB : *MF)
2912 if (!Loops->getLoopFor(BB: &MBB))
2913 Stats.add(other: computeStats(MBB));
2914 if (!Stats.isEmpty()) {
2915 using namespace ore;
2916
2917 ORE->emit(RemarkBuilder: [&]() {
2918 DebugLoc Loc;
2919 if (auto *SP = MF->getFunction().getSubprogram())
2920 Loc = DILocation::get(Context&: SP->getContext(), Line: SP->getLine(), Column: 1, Scope: SP);
2921 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "SpillReloadCopies", Loc,
2922 &MF->front());
2923 Stats.report(R);
2924 R << "generated in function";
2925 return R;
2926 });
2927 }
2928}
2929
2930bool RAGreedy::hasVirtRegAlloc() {
2931 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
2932 Register Reg = Register::index2VirtReg(Index: I);
2933 if (MRI->reg_nodbg_empty(RegNo: Reg))
2934 continue;
2935 if (shouldAllocateRegister(Reg))
2936 return true;
2937 }
2938
2939 return false;
2940}
2941
2942bool RAGreedy::run(MachineFunction &mf) {
2943 LLVM_DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
2944 << "********** Function: " << mf.getName() << '\n');
2945
2946 MF = &mf;
2947 TII = MF->getSubtarget().getInstrInfo();
2948
2949 if (VerifyEnabled)
2950 MF->verify(LiveInts: LIS, Indexes, Banner: "Before greedy register allocator", OS: &errs());
2951
2952 RegAllocBase::init(vrm&: *this->VRM, lis&: *this->LIS, mat&: *this->Matrix);
2953
2954 // Early return if there is no virtual register to be allocated to a
2955 // physical register.
2956 if (!hasVirtRegAlloc())
2957 return false;
2958
2959 // Renumber to get accurate and consistent results from
2960 // SlotIndexes::getApproxInstrDistance.
2961 Indexes->packIndexes();
2962
2963 initializeCSRCost();
2964
2965 RegCosts = TRI->getRegisterCosts(MF: *MF);
2966 RegClassPriorityTrumpsGlobalness =
2967 GreedyRegClassPriorityTrumpsGlobalness.getNumOccurrences()
2968 ? GreedyRegClassPriorityTrumpsGlobalness
2969 : TRI->regClassPriorityTrumpsGlobalness(MF: *MF);
2970
2971 ReverseLocalAssignment = GreedyReverseLocalAssignment.getNumOccurrences()
2972 ? GreedyReverseLocalAssignment
2973 : TRI->reverseLocalAssignment();
2974
2975 ExtraInfo.emplace();
2976
2977 EvictAdvisor = EvictProvider->getAdvisor(MF: *MF, RA: *this, MBFI, Loops);
2978 PriorityAdvisor = PriorityProvider->getAdvisor(MF: *MF, RA: *this, SI&: *Indexes);
2979
2980 VRAI = std::make_unique<VirtRegAuxInfo>(args&: *MF, args&: *LIS, args&: *VRM, args&: *Loops, args&: *MBFI);
2981 SpillerInstance.reset(p: createInlineSpiller(Analyses: {.LIS: *LIS, .LSS: *LSS, .MDT: *DomTree, .MBFI: *MBFI}, MF&: *MF,
2982 VRM&: *VRM, VRAI&: *VRAI, Matrix));
2983
2984 VRAI->calculateSpillWeightsAndHints();
2985
2986 LLVM_DEBUG(LIS->dump());
2987
2988 SA.reset(p: new SplitAnalysis(*VRM, *LIS, *Loops));
2989 SE.reset(p: new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI, *VRAI));
2990
2991 IntfCache.init(mf: MF, liuarray: Matrix->getLiveUnions(), indexes: Indexes, lis: LIS, tri: TRI);
2992 GlobalCand.resize(N: 32); // This will grow as needed.
2993 SetOfBrokenHints.clear();
2994
2995 allocatePhysRegs();
2996 tryHintsRecoloring();
2997
2998 if (VerifyEnabled)
2999 MF->verify(LiveInts: LIS, Indexes, Banner: "Before post optimization", OS: &errs());
3000 postOptimization();
3001 reportStats();
3002
3003 releaseMemory();
3004 return true;
3005}
3006