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