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/DenseMap.h"
25 #include "llvm/ADT/IndexedMap.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
34 #include "llvm/CodeGen/CalcSpillWeights.h"
35 #include "llvm/CodeGen/EdgeBundles.h"
36 #include "llvm/CodeGen/LiveInterval.h"
37 #include "llvm/CodeGen/LiveIntervalUnion.h"
38 #include "llvm/CodeGen/LiveIntervals.h"
39 #include "llvm/CodeGen/LiveRangeEdit.h"
40 #include "llvm/CodeGen/LiveRegMatrix.h"
41 #include "llvm/CodeGen/LiveStacks.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
44 #include "llvm/CodeGen/MachineDominators.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineFunctionPass.h"
48 #include "llvm/CodeGen/MachineInstr.h"
49 #include "llvm/CodeGen/MachineLoopInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/RegAllocRegistry.h"
54 #include "llvm/CodeGen/RegisterClassInfo.h"
55 #include "llvm/CodeGen/SlotIndexes.h"
56 #include "llvm/CodeGen/Spiller.h"
57 #include "llvm/CodeGen/TargetInstrInfo.h"
58 #include "llvm/CodeGen/TargetRegisterInfo.h"
59 #include "llvm/CodeGen/TargetSubtargetInfo.h"
60 #include "llvm/CodeGen/VirtRegMap.h"
61 #include "llvm/IR/DebugInfoMetadata.h"
62 #include "llvm/IR/Function.h"
63 #include "llvm/IR/LLVMContext.h"
64 #include "llvm/InitializePasses.h"
65 #include "llvm/MC/MCRegisterInfo.h"
66 #include "llvm/Pass.h"
67 #include "llvm/Support/BlockFrequency.h"
68 #include "llvm/Support/BranchProbability.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/Timer.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include <algorithm>
75 #include <cassert>
76 #include <cstdint>
77 #include <utility>
78 
79 using namespace llvm;
80 
81 #define DEBUG_TYPE "regalloc"
82 
83 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
84 STATISTIC(NumLocalSplits,  "Number of split local live ranges");
85 STATISTIC(NumEvicted,      "Number of interferences evicted");
86 
87 static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
88     "split-spill-mode", cl::Hidden,
89     cl::desc("Spill mode for splitting live ranges"),
90     cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
91                clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
92                clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
93     cl::init(SplitEditor::SM_Speed));
94 
95 static cl::opt<unsigned>
96 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
97                              cl::desc("Last chance recoloring max depth"),
98                              cl::init(5));
99 
100 static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
101     "lcr-max-interf", cl::Hidden,
102     cl::desc("Last chance recoloring maximum number of considered"
103              " interference at a time"),
104     cl::init(8));
105 
106 static cl::opt<bool> ExhaustiveSearch(
107     "exhaustive-register-search", cl::NotHidden,
108     cl::desc("Exhaustive Search for registers bypassing the depth "
109              "and interference cutoffs of last chance recoloring"),
110     cl::Hidden);
111 
112 static cl::opt<bool> EnableDeferredSpilling(
113     "enable-deferred-spilling", cl::Hidden,
114     cl::desc("Instead of spilling a variable right away, defer the actual "
115              "code insertion to the end of the allocation. That way the "
116              "allocator might still find a suitable coloring for this "
117              "variable because of other evicted variables."),
118     cl::init(false));
119 
120 // FIXME: Find a good default for this flag and remove the flag.
121 static cl::opt<unsigned>
122 CSRFirstTimeCost("regalloc-csr-first-time-cost",
123               cl::desc("Cost for first time use of callee-saved register."),
124               cl::init(0), cl::Hidden);
125 
126 static cl::opt<long> GrowRegionComplexityBudget(
127     "grow-region-complexity-budget",
128     cl::desc("growRegion() does not scale with the number of BB edges, so "
129              "limit its budget and bail out once we reach the limit."),
130     cl::init(10000), cl::Hidden);
131 
132 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
133                                        createGreedyRegisterAllocator);
134 
135 char RAGreedy::ID = 0;
136 char &llvm::RAGreedyID = RAGreedy::ID;
137 
138 INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
139                 "Greedy Register Allocator", false, false)
140 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
141 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
142 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
143 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
144 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
145 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
146 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
147 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
148 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
149 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
150 INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
151 INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
152 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
153 INITIALIZE_PASS_DEPENDENCY(RegAllocEvictionAdvisorAnalysis)
154 INITIALIZE_PASS_END(RAGreedy, "greedy",
155                 "Greedy Register Allocator", false, false)
156 
157 #ifndef NDEBUG
158 const char *const RAGreedy::StageName[] = {
159     "RS_New",
160     "RS_Assign",
161     "RS_Split",
162     "RS_Split2",
163     "RS_Spill",
164     "RS_Memory",
165     "RS_Done"
166 };
167 #endif
168 
169 // Hysteresis to use when comparing floats.
170 // This helps stabilize decisions based on float comparisons.
171 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
172 
173 FunctionPass* llvm::createGreedyRegisterAllocator() {
174   return new RAGreedy();
175 }
176 
177 namespace llvm {
178 FunctionPass* createGreedyRegisterAllocator(
179   std::function<bool(const TargetRegisterInfo &TRI,
180                      const TargetRegisterClass &RC)> Ftor);
181 
182 }
183 
184 FunctionPass* llvm::createGreedyRegisterAllocator(
185   std::function<bool(const TargetRegisterInfo &TRI,
186                      const TargetRegisterClass &RC)> Ftor) {
187   return new RAGreedy(Ftor);
188 }
189 
190 RAGreedy::RAGreedy(RegClassFilterFunc F):
191   MachineFunctionPass(ID),
192   RegAllocBase(F) {
193 }
194 
195 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
196   AU.setPreservesCFG();
197   AU.addRequired<MachineBlockFrequencyInfo>();
198   AU.addPreserved<MachineBlockFrequencyInfo>();
199   AU.addRequired<AAResultsWrapperPass>();
200   AU.addPreserved<AAResultsWrapperPass>();
201   AU.addRequired<LiveIntervals>();
202   AU.addPreserved<LiveIntervals>();
203   AU.addRequired<SlotIndexes>();
204   AU.addPreserved<SlotIndexes>();
205   AU.addRequired<LiveDebugVariables>();
206   AU.addPreserved<LiveDebugVariables>();
207   AU.addRequired<LiveStacks>();
208   AU.addPreserved<LiveStacks>();
209   AU.addRequired<MachineDominatorTree>();
210   AU.addPreserved<MachineDominatorTree>();
211   AU.addRequired<MachineLoopInfo>();
212   AU.addPreserved<MachineLoopInfo>();
213   AU.addRequired<VirtRegMap>();
214   AU.addPreserved<VirtRegMap>();
215   AU.addRequired<LiveRegMatrix>();
216   AU.addPreserved<LiveRegMatrix>();
217   AU.addRequired<EdgeBundles>();
218   AU.addRequired<SpillPlacement>();
219   AU.addRequired<MachineOptimizationRemarkEmitterPass>();
220   AU.addRequired<RegAllocEvictionAdvisorAnalysis>();
221   MachineFunctionPass::getAnalysisUsage(AU);
222 }
223 
224 //===----------------------------------------------------------------------===//
225 //                     LiveRangeEdit delegate methods
226 //===----------------------------------------------------------------------===//
227 
228 bool RAGreedy::LRE_CanEraseVirtReg(Register VirtReg) {
229   LiveInterval &LI = LIS->getInterval(VirtReg);
230   if (VRM->hasPhys(VirtReg)) {
231     Matrix->unassign(LI);
232     aboutToRemoveInterval(LI);
233     return true;
234   }
235   // Unassigned virtreg is probably in the priority queue.
236   // RegAllocBase will erase it after dequeueing.
237   // Nonetheless, clear the live-range so that the debug
238   // dump will show the right state for that VirtReg.
239   LI.clear();
240   return false;
241 }
242 
243 void RAGreedy::LRE_WillShrinkVirtReg(Register VirtReg) {
244   if (!VRM->hasPhys(VirtReg))
245     return;
246 
247   // Register is assigned, put it back on the queue for reassignment.
248   LiveInterval &LI = LIS->getInterval(VirtReg);
249   Matrix->unassign(LI);
250   RegAllocBase::enqueue(&LI);
251 }
252 
253 void RAGreedy::LRE_DidCloneVirtReg(Register New, Register Old) {
254   ExtraInfo->LRE_DidCloneVirtReg(New, Old);
255 }
256 
257 void RAGreedy::ExtraRegInfo::LRE_DidCloneVirtReg(Register New, Register Old) {
258   // Cloning a register we haven't even heard about yet?  Just ignore it.
259   if (!Info.inBounds(Old))
260     return;
261 
262   // LRE may clone a virtual register because dead code elimination causes it to
263   // be split into connected components. The new components are much smaller
264   // than the original, so they should get a new chance at being assigned.
265   // same stage as the parent.
266   Info[Old].Stage = RS_Assign;
267   Info.grow(New.id());
268   Info[New] = Info[Old];
269 }
270 
271 void RAGreedy::releaseMemory() {
272   SpillerInstance.reset();
273   GlobalCand.clear();
274 }
275 
276 void RAGreedy::enqueueImpl(const LiveInterval *LI) { enqueue(Queue, LI); }
277 
278 void RAGreedy::enqueue(PQueue &CurQueue, const LiveInterval *LI) {
279   // Prioritize live ranges by size, assigning larger ranges first.
280   // The queue holds (size, reg) pairs.
281   const unsigned Size = LI->getSize();
282   const Register Reg = LI->reg();
283   assert(Reg.isVirtual() && "Can only enqueue virtual registers");
284   unsigned Prio;
285 
286   auto Stage = ExtraInfo->getOrInitStage(Reg);
287   if (Stage == RS_New) {
288     Stage = RS_Assign;
289     ExtraInfo->setStage(Reg, Stage);
290   }
291   if (Stage == RS_Split) {
292     // Unsplit ranges that couldn't be allocated immediately are deferred until
293     // everything else has been allocated.
294     Prio = Size;
295   } else if (Stage == RS_Memory) {
296     // Memory operand should be considered last.
297     // Change the priority such that Memory operand are assigned in
298     // the reverse order that they came in.
299     // TODO: Make this a member variable and probably do something about hints.
300     static unsigned MemOp = 0;
301     Prio = MemOp++;
302   } else {
303     // Giant live ranges fall back to the global assignment heuristic, which
304     // prevents excessive spilling in pathological cases.
305     bool ReverseLocal = TRI->reverseLocalAssignment();
306     const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
307     bool ForceGlobal = !ReverseLocal &&
308       (Size / SlotIndex::InstrDist) > (2 * RCI.getNumAllocatableRegs(&RC));
309 
310     if (Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
311         LIS->intervalIsInOneMBB(*LI)) {
312       // Allocate original local ranges in linear instruction order. Since they
313       // are singly defined, this produces optimal coloring in the absence of
314       // global interference and other constraints.
315       if (!ReverseLocal)
316         Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
317       else {
318         // Allocating bottom up may allow many short LRGs to be assigned first
319         // to one of the cheap registers. This could be much faster for very
320         // large blocks on targets with many physical registers.
321         Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
322       }
323       Prio |= RC.AllocationPriority << 24;
324     } else {
325       // Allocate global and split ranges in long->short order. Long ranges that
326       // don't fit should be spilled (or split) ASAP so they don't create
327       // interference.  Mark a bit to prioritize global above local ranges.
328       Prio = (1u << 29) + Size;
329 
330       Prio |= RC.AllocationPriority << 24;
331     }
332     // Mark a higher bit to prioritize global and local above RS_Split.
333     Prio |= (1u << 31);
334 
335     // Boost ranges that have a physical register hint.
336     if (VRM->hasKnownPreference(Reg))
337       Prio |= (1u << 30);
338   }
339   // The virtual register number is a tie breaker for same-sized ranges.
340   // Give lower vreg numbers higher priority to assign them first.
341   CurQueue.push(std::make_pair(Prio, ~Reg));
342 }
343 
344 const LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
345 
346 const LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
347   if (CurQueue.empty())
348     return nullptr;
349   LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
350   CurQueue.pop();
351   return LI;
352 }
353 
354 //===----------------------------------------------------------------------===//
355 //                            Direct Assignment
356 //===----------------------------------------------------------------------===//
357 
358 /// tryAssign - Try to assign VirtReg to an available register.
359 MCRegister RAGreedy::tryAssign(const LiveInterval &VirtReg,
360                                AllocationOrder &Order,
361                                SmallVectorImpl<Register> &NewVRegs,
362                                const SmallVirtRegSet &FixedRegisters) {
363   MCRegister PhysReg;
364   for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) {
365     assert(*I);
366     if (!Matrix->checkInterference(VirtReg, *I)) {
367       if (I.isHint())
368         return *I;
369       else
370         PhysReg = *I;
371     }
372   }
373   if (!PhysReg.isValid())
374     return PhysReg;
375 
376   // PhysReg is available, but there may be a better choice.
377 
378   // If we missed a simple hint, try to cheaply evict interference from the
379   // preferred register.
380   if (Register Hint = MRI->getSimpleHint(VirtReg.reg()))
381     if (Order.isHint(Hint)) {
382       MCRegister PhysHint = Hint.asMCReg();
383       LLVM_DEBUG(dbgs() << "missed hint " << printReg(PhysHint, TRI) << '\n');
384 
385       if (EvictAdvisor->canEvictHintInterference(VirtReg, PhysHint,
386                                                  FixedRegisters)) {
387         evictInterference(VirtReg, PhysHint, NewVRegs);
388         return PhysHint;
389       }
390       // Record the missed hint, we may be able to recover
391       // at the end if the surrounding allocation changed.
392       SetOfBrokenHints.insert(&VirtReg);
393     }
394 
395   // Try to evict interference from a cheaper alternative.
396   uint8_t Cost = RegCosts[PhysReg];
397 
398   // Most registers have 0 additional cost.
399   if (!Cost)
400     return PhysReg;
401 
402   LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost "
403                     << (unsigned)Cost << '\n');
404   MCRegister CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost, FixedRegisters);
405   return CheapReg ? CheapReg : PhysReg;
406 }
407 
408 //===----------------------------------------------------------------------===//
409 //                         Interference eviction
410 //===----------------------------------------------------------------------===//
411 
412 Register RegAllocEvictionAdvisor::canReassign(const LiveInterval &VirtReg,
413                                               Register PrevReg) const {
414   auto Order =
415       AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
416   MCRegister PhysReg;
417   for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) {
418     if ((*I).id() == PrevReg.id())
419       continue;
420 
421     MCRegUnitIterator Units(*I, TRI);
422     for (; Units.isValid(); ++Units) {
423       // Instantiate a "subquery", not to be confused with the Queries array.
424       LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
425       if (subQ.checkInterference())
426         break;
427     }
428     // If no units have interference, break out with the current PhysReg.
429     if (!Units.isValid())
430       PhysReg = *I;
431   }
432   if (PhysReg)
433     LLVM_DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
434                       << printReg(PrevReg, TRI) << " to "
435                       << printReg(PhysReg, TRI) << '\n');
436   return PhysReg;
437 }
438 
439 /// Return true if all interferences between VirtReg and PhysReg between
440 /// Start and End can be evicted.
441 ///
442 /// \param VirtReg Live range that is about to be assigned.
443 /// \param PhysReg Desired register for assignment.
444 /// \param Start   Start of range to look for interferences.
445 /// \param End     End of range to look for interferences.
446 /// \param MaxCost Only look for cheaper candidates and update with new cost
447 ///                when returning true.
448 /// \return True when interference can be evicted cheaper than MaxCost.
449 bool RAGreedy::canEvictInterferenceInRange(const LiveInterval &VirtReg,
450                                            MCRegister PhysReg, SlotIndex Start,
451                                            SlotIndex End,
452                                            EvictionCost &MaxCost) const {
453   EvictionCost Cost;
454 
455   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
456     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
457 
458     // Check if any interfering live range is heavier than MaxWeight.
459     for (const LiveInterval *Intf : reverse(Q.interferingVRegs())) {
460       // Check if interference overlast the segment in interest.
461       if (!Intf->overlaps(Start, End))
462         continue;
463 
464       // Cannot evict non virtual reg interference.
465       if (!Register::isVirtualRegister(Intf->reg()))
466         return false;
467       // Never evict spill products. They cannot split or spill.
468       if (ExtraInfo->getStage(*Intf) == RS_Done)
469         return false;
470 
471       // Would this break a satisfied hint?
472       bool BreaksHint = VRM->hasPreferredPhys(Intf->reg());
473       // Update eviction cost.
474       Cost.BrokenHints += BreaksHint;
475       Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight());
476       // Abort if this would be too expensive.
477       if (!(Cost < MaxCost))
478         return false;
479     }
480   }
481 
482   if (Cost.MaxWeight == 0)
483     return false;
484 
485   MaxCost = Cost;
486   return true;
487 }
488 
489 /// Return the physical register that will be best
490 /// candidate for eviction by a local split interval that will be created
491 /// between Start and End.
492 ///
493 /// \param Order            The allocation order
494 /// \param VirtReg          Live range that is about to be assigned.
495 /// \param Start            Start of range to look for interferences
496 /// \param End              End of range to look for interferences
497 /// \param BestEvictweight  The eviction cost of that eviction
498 /// \return The PhysReg which is the best candidate for eviction and the
499 /// eviction cost in BestEvictweight
500 MCRegister RAGreedy::getCheapestEvicteeWeight(const AllocationOrder &Order,
501                                               const LiveInterval &VirtReg,
502                                               SlotIndex Start, SlotIndex End,
503                                               float *BestEvictweight) const {
504   EvictionCost BestEvictCost;
505   BestEvictCost.setMax();
506   BestEvictCost.MaxWeight = VirtReg.weight();
507   MCRegister BestEvicteePhys;
508 
509   // Go over all physical registers and find the best candidate for eviction
510   for (MCRegister PhysReg : Order.getOrder()) {
511 
512     if (!canEvictInterferenceInRange(VirtReg, PhysReg, Start, End,
513                                      BestEvictCost))
514       continue;
515 
516     // Best so far.
517     BestEvicteePhys = PhysReg;
518   }
519   *BestEvictweight = BestEvictCost.MaxWeight;
520   return BestEvicteePhys;
521 }
522 
523 /// evictInterference - Evict any interferring registers that prevent VirtReg
524 /// from being assigned to Physreg. This assumes that canEvictInterference
525 /// returned true.
526 void RAGreedy::evictInterference(const LiveInterval &VirtReg,
527                                  MCRegister PhysReg,
528                                  SmallVectorImpl<Register> &NewVRegs) {
529   // Make sure that VirtReg has a cascade number, and assign that cascade
530   // number to every evicted register. These live ranges than then only be
531   // evicted by a newer cascade, preventing infinite loops.
532   unsigned Cascade = ExtraInfo->getOrAssignNewCascade(VirtReg.reg());
533 
534   LLVM_DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI)
535                     << " interference: Cascade " << Cascade << '\n');
536 
537   // Collect all interfering virtregs first.
538   SmallVector<const LiveInterval *, 8> Intfs;
539   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
540     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
541     // We usually have the interfering VRegs cached so collectInterferingVRegs()
542     // should be fast, we may need to recalculate if when different physregs
543     // overlap the same register unit so we had different SubRanges queried
544     // against it.
545     ArrayRef<const LiveInterval *> IVR = Q.interferingVRegs();
546     Intfs.append(IVR.begin(), IVR.end());
547   }
548 
549   // Evict them second. This will invalidate the queries.
550   for (const LiveInterval *Intf : Intfs) {
551     // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
552     if (!VRM->hasPhys(Intf->reg()))
553       continue;
554 
555     LastEvicted.addEviction(PhysReg, VirtReg.reg(), Intf->reg());
556 
557     Matrix->unassign(*Intf);
558     assert((ExtraInfo->getCascade(Intf->reg()) < Cascade ||
559             VirtReg.isSpillable() < Intf->isSpillable()) &&
560            "Cannot decrease cascade number, illegal eviction");
561     ExtraInfo->setCascade(Intf->reg(), Cascade);
562     ++NumEvicted;
563     NewVRegs.push_back(Intf->reg());
564   }
565 }
566 
567 /// Returns true if the given \p PhysReg is a callee saved register and has not
568 /// been used for allocation yet.
569 bool RegAllocEvictionAdvisor::isUnusedCalleeSavedReg(MCRegister PhysReg) const {
570   MCRegister CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
571   if (!CSR)
572     return false;
573 
574   return !Matrix->isPhysRegUsed(PhysReg);
575 }
576 
577 Optional<unsigned>
578 RegAllocEvictionAdvisor::getOrderLimit(const LiveInterval &VirtReg,
579                                        const AllocationOrder &Order,
580                                        unsigned CostPerUseLimit) const {
581   unsigned OrderLimit = Order.getOrder().size();
582 
583   if (CostPerUseLimit < uint8_t(~0u)) {
584     // Check of any registers in RC are below CostPerUseLimit.
585     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg());
586     uint8_t MinCost = RegClassInfo.getMinCost(RC);
587     if (MinCost >= CostPerUseLimit) {
588       LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = "
589                         << MinCost << ", no cheaper registers to be found.\n");
590       return None;
591     }
592 
593     // It is normal for register classes to have a long tail of registers with
594     // the same cost. We don't need to look at them if they're too expensive.
595     if (RegCosts[Order.getOrder().back()] >= CostPerUseLimit) {
596       OrderLimit = RegClassInfo.getLastCostChange(RC);
597       LLVM_DEBUG(dbgs() << "Only trying the first " << OrderLimit
598                         << " regs.\n");
599     }
600   }
601   return OrderLimit;
602 }
603 
604 bool RegAllocEvictionAdvisor::canAllocatePhysReg(unsigned CostPerUseLimit,
605                                                  MCRegister PhysReg) const {
606   if (RegCosts[PhysReg] >= CostPerUseLimit)
607     return false;
608   // The first use of a callee-saved register in a function has cost 1.
609   // Don't start using a CSR when the CostPerUseLimit is low.
610   if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
611     LLVM_DEBUG(
612         dbgs() << printReg(PhysReg, TRI) << " would clobber CSR "
613                << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
614                << '\n');
615     return false;
616   }
617   return true;
618 }
619 
620 /// tryEvict - Try to evict all interferences for a physreg.
621 /// @param  VirtReg Currently unassigned virtual register.
622 /// @param  Order   Physregs to try.
623 /// @return         Physreg to assign VirtReg, or 0.
624 MCRegister RAGreedy::tryEvict(const LiveInterval &VirtReg,
625                               AllocationOrder &Order,
626                               SmallVectorImpl<Register> &NewVRegs,
627                               uint8_t CostPerUseLimit,
628                               const SmallVirtRegSet &FixedRegisters) {
629   NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
630                      TimePassesIsEnabled);
631 
632   MCRegister BestPhys = EvictAdvisor->tryFindEvictionCandidate(
633       VirtReg, Order, CostPerUseLimit, FixedRegisters);
634   if (BestPhys.isValid())
635     evictInterference(VirtReg, BestPhys, NewVRegs);
636   return BestPhys;
637 }
638 
639 //===----------------------------------------------------------------------===//
640 //                              Region Splitting
641 //===----------------------------------------------------------------------===//
642 
643 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
644 /// interference pattern in Physreg and its aliases. Add the constraints to
645 /// SpillPlacement and return the static cost of this split in Cost, assuming
646 /// that all preferences in SplitConstraints are met.
647 /// Return false if there are no bundles with positive bias.
648 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
649                                    BlockFrequency &Cost) {
650   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
651 
652   // Reset interference dependent info.
653   SplitConstraints.resize(UseBlocks.size());
654   BlockFrequency StaticCost = 0;
655   for (unsigned I = 0; I != UseBlocks.size(); ++I) {
656     const SplitAnalysis::BlockInfo &BI = UseBlocks[I];
657     SpillPlacement::BlockConstraint &BC = SplitConstraints[I];
658 
659     BC.Number = BI.MBB->getNumber();
660     Intf.moveToBlock(BC.Number);
661     BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
662     BC.Exit = (BI.LiveOut &&
663                !LIS->getInstructionFromIndex(BI.LastInstr)->isImplicitDef())
664                   ? SpillPlacement::PrefReg
665                   : SpillPlacement::DontCare;
666     BC.ChangesValue = BI.FirstDef.isValid();
667 
668     if (!Intf.hasInterference())
669       continue;
670 
671     // Number of spill code instructions to insert.
672     unsigned Ins = 0;
673 
674     // Interference for the live-in value.
675     if (BI.LiveIn) {
676       if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
677         BC.Entry = SpillPlacement::MustSpill;
678         ++Ins;
679       } else if (Intf.first() < BI.FirstInstr) {
680         BC.Entry = SpillPlacement::PrefSpill;
681         ++Ins;
682       } else if (Intf.first() < BI.LastInstr) {
683         ++Ins;
684       }
685 
686       // Abort if the spill cannot be inserted at the MBB' start
687       if (((BC.Entry == SpillPlacement::MustSpill) ||
688            (BC.Entry == SpillPlacement::PrefSpill)) &&
689           SlotIndex::isEarlierInstr(BI.FirstInstr,
690                                     SA->getFirstSplitPoint(BC.Number)))
691         return false;
692     }
693 
694     // Interference for the live-out value.
695     if (BI.LiveOut) {
696       if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
697         BC.Exit = SpillPlacement::MustSpill;
698         ++Ins;
699       } else if (Intf.last() > BI.LastInstr) {
700         BC.Exit = SpillPlacement::PrefSpill;
701         ++Ins;
702       } else if (Intf.last() > BI.FirstInstr) {
703         ++Ins;
704       }
705     }
706 
707     // Accumulate the total frequency of inserted spill code.
708     while (Ins--)
709       StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
710   }
711   Cost = StaticCost;
712 
713   // Add constraints for use-blocks. Note that these are the only constraints
714   // that may add a positive bias, it is downhill from here.
715   SpillPlacer->addConstraints(SplitConstraints);
716   return SpillPlacer->scanActiveBundles();
717 }
718 
719 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
720 /// live-through blocks in Blocks.
721 bool RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
722                                      ArrayRef<unsigned> Blocks) {
723   const unsigned GroupSize = 8;
724   SpillPlacement::BlockConstraint BCS[GroupSize];
725   unsigned TBS[GroupSize];
726   unsigned B = 0, T = 0;
727 
728   for (unsigned Number : Blocks) {
729     Intf.moveToBlock(Number);
730 
731     if (!Intf.hasInterference()) {
732       assert(T < GroupSize && "Array overflow");
733       TBS[T] = Number;
734       if (++T == GroupSize) {
735         SpillPlacer->addLinks(makeArrayRef(TBS, T));
736         T = 0;
737       }
738       continue;
739     }
740 
741     assert(B < GroupSize && "Array overflow");
742     BCS[B].Number = Number;
743 
744     // Abort if the spill cannot be inserted at the MBB' start
745     MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
746     auto FirstNonDebugInstr = MBB->getFirstNonDebugInstr();
747     if (FirstNonDebugInstr != MBB->end() &&
748         SlotIndex::isEarlierInstr(LIS->getInstructionIndex(*FirstNonDebugInstr),
749                                   SA->getFirstSplitPoint(Number)))
750       return false;
751     // Interference for the live-in value.
752     if (Intf.first() <= Indexes->getMBBStartIdx(Number))
753       BCS[B].Entry = SpillPlacement::MustSpill;
754     else
755       BCS[B].Entry = SpillPlacement::PrefSpill;
756 
757     // Interference for the live-out value.
758     if (Intf.last() >= SA->getLastSplitPoint(Number))
759       BCS[B].Exit = SpillPlacement::MustSpill;
760     else
761       BCS[B].Exit = SpillPlacement::PrefSpill;
762 
763     if (++B == GroupSize) {
764       SpillPlacer->addConstraints(makeArrayRef(BCS, B));
765       B = 0;
766     }
767   }
768 
769   SpillPlacer->addConstraints(makeArrayRef(BCS, B));
770   SpillPlacer->addLinks(makeArrayRef(TBS, T));
771   return true;
772 }
773 
774 bool RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
775   // Keep track of through blocks that have not been added to SpillPlacer.
776   BitVector Todo = SA->getThroughBlocks();
777   SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
778   unsigned AddedTo = 0;
779 #ifndef NDEBUG
780   unsigned Visited = 0;
781 #endif
782 
783   long Budget = GrowRegionComplexityBudget;
784   while (true) {
785     ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
786     // Find new through blocks in the periphery of PrefRegBundles.
787     for (unsigned Bundle : NewBundles) {
788       // Look at all blocks connected to Bundle in the full graph.
789       ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
790       for (unsigned Block : Blocks) {
791         // Limit compilation time by bailing out after we use all our budget.
792         if (Budget-- == 0)
793           return false;
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       //
1869       // Also, don't try to evict a register which is assigned to an overlapping
1870       // super register.
1871       //
1872       // TODO: Can we evict an interfering subset of the subregisters?
1873       if (((ExtraInfo->getStage(*Intf) == RS_Done &&
1874             (MRI->getRegClass(Intf->reg()) == CurRC ||
1875              TRI->regsOverlap(VRM->getPhys(Intf->reg()), PhysReg))) &&
1876            !(hasTiedDef(MRI, VirtReg.reg()) &&
1877              !hasTiedDef(MRI, Intf->reg()))) ||
1878           FixedRegisters.count(Intf->reg())) {
1879         LLVM_DEBUG(
1880             dbgs() << "Early abort: the interference is not recolorable.\n");
1881         return false;
1882       }
1883       RecoloringCandidates.insert(Intf);
1884     }
1885   }
1886   return true;
1887 }
1888 
1889 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
1890 /// its interferences.
1891 /// Last chance recoloring chooses a color for \p VirtReg and recolors every
1892 /// virtual register that was using it. The recoloring process may recursively
1893 /// use the last chance recoloring. Therefore, when a virtual register has been
1894 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
1895 /// be last-chance-recolored again during this recoloring "session".
1896 /// E.g.,
1897 /// Let
1898 /// vA can use {R1, R2    }
1899 /// vB can use {    R2, R3}
1900 /// vC can use {R1        }
1901 /// Where vA, vB, and vC cannot be split anymore (they are reloads for
1902 /// instance) and they all interfere.
1903 ///
1904 /// vA is assigned R1
1905 /// vB is assigned R2
1906 /// vC tries to evict vA but vA is already done.
1907 /// Regular register allocation fails.
1908 ///
1909 /// Last chance recoloring kicks in:
1910 /// vC does as if vA was evicted => vC uses R1.
1911 /// vC is marked as fixed.
1912 /// vA needs to find a color.
1913 /// None are available.
1914 /// vA cannot evict vC: vC is a fixed virtual register now.
1915 /// vA does as if vB was evicted => vA uses R2.
1916 /// vB needs to find a color.
1917 /// R3 is available.
1918 /// Recoloring => vC = R1, vA = R2, vB = R3
1919 ///
1920 /// \p Order defines the preferred allocation order for \p VirtReg.
1921 /// \p NewRegs will contain any new virtual register that have been created
1922 /// (split, spill) during the process and that must be assigned.
1923 /// \p FixedRegisters contains all the virtual registers that cannot be
1924 /// recolored.
1925 /// \p Depth gives the current depth of the last chance recoloring.
1926 /// \return a physical register that can be used for VirtReg or ~0u if none
1927 /// exists.
1928 unsigned RAGreedy::tryLastChanceRecoloring(const LiveInterval &VirtReg,
1929                                            AllocationOrder &Order,
1930                                            SmallVectorImpl<Register> &NewVRegs,
1931                                            SmallVirtRegSet &FixedRegisters,
1932                                            unsigned Depth) {
1933   if (!TRI->shouldUseLastChanceRecoloringForVirtReg(*MF, VirtReg))
1934     return ~0u;
1935 
1936   LLVM_DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
1937   // Ranges must be Done.
1938   assert((ExtraInfo->getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
1939          "Last chance recoloring should really be last chance");
1940   // Set the max depth to LastChanceRecoloringMaxDepth.
1941   // We may want to reconsider that if we end up with a too large search space
1942   // for target with hundreds of registers.
1943   // Indeed, in that case we may want to cut the search space earlier.
1944   if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
1945     LLVM_DEBUG(dbgs() << "Abort because max depth has been reached.\n");
1946     CutOffInfo |= CO_Depth;
1947     return ~0u;
1948   }
1949 
1950   // Set of Live intervals that will need to be recolored.
1951   SmallLISet RecoloringCandidates;
1952   // Record the original mapping virtual register to physical register in case
1953   // the recoloring fails.
1954   DenseMap<Register, MCRegister> VirtRegToPhysReg;
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     VirtRegToPhysReg.clear();
1967     CurrentNewVRegs.clear();
1968 
1969     // It is only possible to recolor virtual register interference.
1970     if (Matrix->checkInterference(VirtReg, PhysReg) >
1971         LiveRegMatrix::IK_VirtReg) {
1972       LLVM_DEBUG(
1973           dbgs() << "Some interferences are not with virtual registers.\n");
1974 
1975       continue;
1976     }
1977 
1978     // Early give up on this PhysReg if it is obvious we cannot recolor all
1979     // the interferences.
1980     if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
1981                                     FixedRegisters)) {
1982       LLVM_DEBUG(dbgs() << "Some interferences cannot be recolored.\n");
1983       continue;
1984     }
1985 
1986     // RecoloringCandidates contains all the virtual registers that interfer
1987     // with VirtReg on PhysReg (or one of its aliases).
1988     // Enqueue them for recoloring and perform the actual recoloring.
1989     PQueue RecoloringQueue;
1990     for (const LiveInterval *RC : RecoloringCandidates) {
1991       Register ItVirtReg = RC->reg();
1992       enqueue(RecoloringQueue, RC);
1993       assert(VRM->hasPhys(ItVirtReg) &&
1994              "Interferences are supposed to be with allocated variables");
1995 
1996       // Record the current allocation.
1997       VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
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, 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     for (const LiveInterval *RC : RecoloringCandidates) {
2040       Register ItVirtReg = RC->reg();
2041       if (VRM->hasPhys(ItVirtReg))
2042         Matrix->unassign(*RC);
2043       MCRegister ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2044       Matrix->assign(*RC, ItPhysReg);
2045     }
2046   }
2047 
2048   // Last chance recoloring did not worked either, give up.
2049   return ~0u;
2050 }
2051 
2052 /// tryRecoloringCandidates - Try to assign a new color to every register
2053 /// in \RecoloringQueue.
2054 /// \p NewRegs will contain any new virtual register created during the
2055 /// recoloring process.
2056 /// \p FixedRegisters[in/out] contains all the registers that have been
2057 /// recolored.
2058 /// \return true if all virtual registers in RecoloringQueue were successfully
2059 /// recolored, false otherwise.
2060 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2061                                        SmallVectorImpl<Register> &NewVRegs,
2062                                        SmallVirtRegSet &FixedRegisters,
2063                                        unsigned Depth) {
2064   while (!RecoloringQueue.empty()) {
2065     const LiveInterval *LI = dequeue(RecoloringQueue);
2066     LLVM_DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2067     MCRegister PhysReg =
2068         selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2069     // When splitting happens, the live-range may actually be empty.
2070     // In that case, this is okay to continue the recoloring even
2071     // if we did not find an alternative color for it. Indeed,
2072     // there will not be anything to color for LI in the end.
2073     if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
2074       return false;
2075 
2076     if (!PhysReg) {
2077       assert(LI->empty() && "Only empty live-range do not require a register");
2078       LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2079                         << " succeeded. Empty LI.\n");
2080       continue;
2081     }
2082     LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2083                       << " succeeded with: " << printReg(PhysReg, TRI) << '\n');
2084 
2085     Matrix->assign(*LI, PhysReg);
2086     FixedRegisters.insert(LI->reg());
2087   }
2088   return true;
2089 }
2090 
2091 //===----------------------------------------------------------------------===//
2092 //                            Main Entry Point
2093 //===----------------------------------------------------------------------===//
2094 
2095 MCRegister RAGreedy::selectOrSplit(const LiveInterval &VirtReg,
2096                                    SmallVectorImpl<Register> &NewVRegs) {
2097   CutOffInfo = CO_None;
2098   LLVMContext &Ctx = MF->getFunction().getContext();
2099   SmallVirtRegSet FixedRegisters;
2100   MCRegister Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2101   if (Reg == ~0U && (CutOffInfo != CO_None)) {
2102     uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2103     if (CutOffEncountered == CO_Depth)
2104       Ctx.emitError("register allocation failed: maximum depth for recoloring "
2105                     "reached. Use -fexhaustive-register-search to skip "
2106                     "cutoffs");
2107     else if (CutOffEncountered == CO_Interf)
2108       Ctx.emitError("register allocation failed: maximum interference for "
2109                     "recoloring reached. Use -fexhaustive-register-search "
2110                     "to skip cutoffs");
2111     else if (CutOffEncountered == (CO_Depth | CO_Interf))
2112       Ctx.emitError("register allocation failed: maximum interference and "
2113                     "depth for recoloring reached. Use "
2114                     "-fexhaustive-register-search to skip cutoffs");
2115   }
2116   return Reg;
2117 }
2118 
2119 /// Using a CSR for the first time has a cost because it causes push|pop
2120 /// to be added to prologue|epilogue. Splitting a cold section of the live
2121 /// range can have lower cost than using the CSR for the first time;
2122 /// Spilling a live range in the cold path can have lower cost than using
2123 /// the CSR for the first time. Returns the physical register if we decide
2124 /// to use the CSR; otherwise return 0.
2125 MCRegister RAGreedy::tryAssignCSRFirstTime(
2126     const LiveInterval &VirtReg, AllocationOrder &Order, MCRegister PhysReg,
2127     uint8_t &CostPerUseLimit, SmallVectorImpl<Register> &NewVRegs) {
2128   if (ExtraInfo->getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2129     // We choose spill over using the CSR for the first time if the spill cost
2130     // is lower than CSRCost.
2131     SA->analyze(&VirtReg);
2132     if (calcSpillCost() >= CSRCost)
2133       return PhysReg;
2134 
2135     // We are going to spill, set CostPerUseLimit to 1 to make sure that
2136     // we will not use a callee-saved register in tryEvict.
2137     CostPerUseLimit = 1;
2138     return 0;
2139   }
2140   if (ExtraInfo->getStage(VirtReg) < RS_Split) {
2141     // We choose pre-splitting over using the CSR for the first time if
2142     // the cost of splitting is lower than CSRCost.
2143     SA->analyze(&VirtReg);
2144     unsigned NumCands = 0;
2145     BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2146     unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2147                                                  NumCands, true /*IgnoreCSR*/);
2148     if (BestCand == NoCand)
2149       // Use the CSR if we can't find a region split below CSRCost.
2150       return PhysReg;
2151 
2152     // Perform the actual pre-splitting.
2153     doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2154     return 0;
2155   }
2156   return PhysReg;
2157 }
2158 
2159 void RAGreedy::aboutToRemoveInterval(const LiveInterval &LI) {
2160   // Do not keep invalid information around.
2161   SetOfBrokenHints.remove(&LI);
2162 }
2163 
2164 void RAGreedy::initializeCSRCost() {
2165   // We use the larger one out of the command-line option and the value report
2166   // by TRI.
2167   CSRCost = BlockFrequency(
2168       std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2169   if (!CSRCost.getFrequency())
2170     return;
2171 
2172   // Raw cost is relative to Entry == 2^14; scale it appropriately.
2173   uint64_t ActualEntry = MBFI->getEntryFreq();
2174   if (!ActualEntry) {
2175     CSRCost = 0;
2176     return;
2177   }
2178   uint64_t FixedEntry = 1 << 14;
2179   if (ActualEntry < FixedEntry)
2180     CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2181   else if (ActualEntry <= UINT32_MAX)
2182     // Invert the fraction and divide.
2183     CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2184   else
2185     // Can't use BranchProbability in general, since it takes 32-bit numbers.
2186     CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2187 }
2188 
2189 /// Collect the hint info for \p Reg.
2190 /// The results are stored into \p Out.
2191 /// \p Out is not cleared before being populated.
2192 void RAGreedy::collectHintInfo(Register Reg, HintsInfo &Out) {
2193   for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2194     if (!Instr.isFullCopy())
2195       continue;
2196     // Look for the other end of the copy.
2197     Register OtherReg = Instr.getOperand(0).getReg();
2198     if (OtherReg == Reg) {
2199       OtherReg = Instr.getOperand(1).getReg();
2200       if (OtherReg == Reg)
2201         continue;
2202     }
2203     // Get the current assignment.
2204     MCRegister OtherPhysReg =
2205         OtherReg.isPhysical() ? OtherReg.asMCReg() : VRM->getPhys(OtherReg);
2206     // Push the collected information.
2207     Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2208                            OtherPhysReg));
2209   }
2210 }
2211 
2212 /// Using the given \p List, compute the cost of the broken hints if
2213 /// \p PhysReg was used.
2214 /// \return The cost of \p List for \p PhysReg.
2215 BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2216                                            MCRegister PhysReg) {
2217   BlockFrequency Cost = 0;
2218   for (const HintInfo &Info : List) {
2219     if (Info.PhysReg != PhysReg)
2220       Cost += Info.Freq;
2221   }
2222   return Cost;
2223 }
2224 
2225 /// Using the register assigned to \p VirtReg, try to recolor
2226 /// all the live ranges that are copy-related with \p VirtReg.
2227 /// The recoloring is then propagated to all the live-ranges that have
2228 /// been recolored and so on, until no more copies can be coalesced or
2229 /// it is not profitable.
2230 /// For a given live range, profitability is determined by the sum of the
2231 /// frequencies of the non-identity copies it would introduce with the old
2232 /// and new register.
2233 void RAGreedy::tryHintRecoloring(const LiveInterval &VirtReg) {
2234   // We have a broken hint, check if it is possible to fix it by
2235   // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2236   // some register and PhysReg may be available for the other live-ranges.
2237   SmallSet<Register, 4> Visited;
2238   SmallVector<unsigned, 2> RecoloringCandidates;
2239   HintsInfo Info;
2240   Register Reg = VirtReg.reg();
2241   MCRegister PhysReg = VRM->getPhys(Reg);
2242   // Start the recoloring algorithm from the input live-interval, then
2243   // it will propagate to the ones that are copy-related with it.
2244   Visited.insert(Reg);
2245   RecoloringCandidates.push_back(Reg);
2246 
2247   LLVM_DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI)
2248                     << '(' << printReg(PhysReg, TRI) << ")\n");
2249 
2250   do {
2251     Reg = RecoloringCandidates.pop_back_val();
2252 
2253     // We cannot recolor physical register.
2254     if (Register::isPhysicalRegister(Reg))
2255       continue;
2256 
2257     // This may be a skipped class
2258     if (!VRM->hasPhys(Reg)) {
2259       assert(!ShouldAllocateClass(*TRI, *MRI->getRegClass(Reg)) &&
2260              "We have an unallocated variable which should have been handled");
2261       continue;
2262     }
2263 
2264     // Get the live interval mapped with this virtual register to be able
2265     // to check for the interference with the new color.
2266     LiveInterval &LI = LIS->getInterval(Reg);
2267     MCRegister CurrPhys = VRM->getPhys(Reg);
2268     // Check that the new color matches the register class constraints and
2269     // that it is free for this live range.
2270     if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2271                                 Matrix->checkInterference(LI, PhysReg)))
2272       continue;
2273 
2274     LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI)
2275                       << ") is recolorable.\n");
2276 
2277     // Gather the hint info.
2278     Info.clear();
2279     collectHintInfo(Reg, Info);
2280     // Check if recoloring the live-range will increase the cost of the
2281     // non-identity copies.
2282     if (CurrPhys != PhysReg) {
2283       LLVM_DEBUG(dbgs() << "Checking profitability:\n");
2284       BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2285       BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
2286       LLVM_DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2287                         << "\nNew Cost: " << NewCopiesCost.getFrequency()
2288                         << '\n');
2289       if (OldCopiesCost < NewCopiesCost) {
2290         LLVM_DEBUG(dbgs() << "=> Not profitable.\n");
2291         continue;
2292       }
2293       // At this point, the cost is either cheaper or equal. If it is
2294       // equal, we consider this is profitable because it may expose
2295       // more recoloring opportunities.
2296       LLVM_DEBUG(dbgs() << "=> Profitable.\n");
2297       // Recolor the live-range.
2298       Matrix->unassign(LI);
2299       Matrix->assign(LI, PhysReg);
2300     }
2301     // Push all copy-related live-ranges to keep reconciling the broken
2302     // hints.
2303     for (const HintInfo &HI : Info) {
2304       if (Visited.insert(HI.Reg).second)
2305         RecoloringCandidates.push_back(HI.Reg);
2306     }
2307   } while (!RecoloringCandidates.empty());
2308 }
2309 
2310 /// Try to recolor broken hints.
2311 /// Broken hints may be repaired by recoloring when an evicted variable
2312 /// freed up a register for a larger live-range.
2313 /// Consider the following example:
2314 /// BB1:
2315 ///   a =
2316 ///   b =
2317 /// BB2:
2318 ///   ...
2319 ///   = b
2320 ///   = a
2321 /// Let us assume b gets split:
2322 /// BB1:
2323 ///   a =
2324 ///   b =
2325 /// BB2:
2326 ///   c = b
2327 ///   ...
2328 ///   d = c
2329 ///   = d
2330 ///   = a
2331 /// Because of how the allocation work, b, c, and d may be assigned different
2332 /// colors. Now, if a gets evicted later:
2333 /// BB1:
2334 ///   a =
2335 ///   st a, SpillSlot
2336 ///   b =
2337 /// BB2:
2338 ///   c = b
2339 ///   ...
2340 ///   d = c
2341 ///   = d
2342 ///   e = ld SpillSlot
2343 ///   = e
2344 /// This is likely that we can assign the same register for b, c, and d,
2345 /// getting rid of 2 copies.
2346 void RAGreedy::tryHintsRecoloring() {
2347   for (const LiveInterval *LI : SetOfBrokenHints) {
2348     assert(Register::isVirtualRegister(LI->reg()) &&
2349            "Recoloring is possible only for virtual registers");
2350     // Some dead defs may be around (e.g., because of debug uses).
2351     // Ignore those.
2352     if (!VRM->hasPhys(LI->reg()))
2353       continue;
2354     tryHintRecoloring(*LI);
2355   }
2356 }
2357 
2358 MCRegister RAGreedy::selectOrSplitImpl(const LiveInterval &VirtReg,
2359                                        SmallVectorImpl<Register> &NewVRegs,
2360                                        SmallVirtRegSet &FixedRegisters,
2361                                        unsigned Depth) {
2362   uint8_t CostPerUseLimit = uint8_t(~0u);
2363   // First try assigning a free register.
2364   auto Order =
2365       AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
2366   if (MCRegister PhysReg =
2367           tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) {
2368     // If VirtReg got an assignment, the eviction info is no longer relevant.
2369     LastEvicted.clearEvicteeInfo(VirtReg.reg());
2370     // When NewVRegs is not empty, we may have made decisions such as evicting
2371     // a virtual register, go with the earlier decisions and use the physical
2372     // register.
2373     if (CSRCost.getFrequency() &&
2374         EvictAdvisor->isUnusedCalleeSavedReg(PhysReg) && NewVRegs.empty()) {
2375       MCRegister CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2376                                                 CostPerUseLimit, NewVRegs);
2377       if (CSRReg || !NewVRegs.empty())
2378         // Return now if we decide to use a CSR or create new vregs due to
2379         // pre-splitting.
2380         return CSRReg;
2381     } else
2382       return PhysReg;
2383   }
2384 
2385   LiveRangeStage Stage = ExtraInfo->getStage(VirtReg);
2386   LLVM_DEBUG(dbgs() << StageName[Stage] << " Cascade "
2387                     << ExtraInfo->getCascade(VirtReg.reg()) << '\n');
2388 
2389   // Try to evict a less worthy live range, but only for ranges from the primary
2390   // queue. The RS_Split ranges already failed to do this, and they should not
2391   // get a second chance until they have been split.
2392   if (Stage != RS_Split)
2393     if (Register PhysReg =
2394             tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit,
2395                      FixedRegisters)) {
2396       Register Hint = MRI->getSimpleHint(VirtReg.reg());
2397       // If VirtReg has a hint and that hint is broken record this
2398       // virtual register as a recoloring candidate for broken hint.
2399       // Indeed, since we evicted a variable in its neighborhood it is
2400       // likely we can at least partially recolor some of the
2401       // copy-related live-ranges.
2402       if (Hint && Hint != PhysReg)
2403         SetOfBrokenHints.insert(&VirtReg);
2404       // If VirtReg eviction someone, the eviction info for it as an evictee is
2405       // no longer relevant.
2406       LastEvicted.clearEvicteeInfo(VirtReg.reg());
2407       return PhysReg;
2408     }
2409 
2410   assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
2411 
2412   // The first time we see a live range, don't try to split or spill.
2413   // Wait until the second time, when all smaller ranges have been allocated.
2414   // This gives a better picture of the interference to split around.
2415   if (Stage < RS_Split) {
2416     ExtraInfo->setStage(VirtReg, RS_Split);
2417     LLVM_DEBUG(dbgs() << "wait for second round\n");
2418     NewVRegs.push_back(VirtReg.reg());
2419     return 0;
2420   }
2421 
2422   if (Stage < RS_Spill) {
2423     // Try splitting VirtReg or interferences.
2424     unsigned NewVRegSizeBefore = NewVRegs.size();
2425     Register PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters);
2426     if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore)) {
2427       // If VirtReg got split, the eviction info is no longer relevant.
2428       LastEvicted.clearEvicteeInfo(VirtReg.reg());
2429       return PhysReg;
2430     }
2431   }
2432 
2433   // If we couldn't allocate a register from spilling, there is probably some
2434   // invalid inline assembly. The base class will report it.
2435   if (Stage >= RS_Done || !VirtReg.isSpillable())
2436     return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2437                                    Depth);
2438 
2439   // Finally spill VirtReg itself.
2440   if ((EnableDeferredSpilling ||
2441        TRI->shouldUseDeferredSpillingForVirtReg(*MF, VirtReg)) &&
2442       ExtraInfo->getStage(VirtReg) < RS_Memory) {
2443     // TODO: This is experimental and in particular, we do not model
2444     // the live range splitting done by spilling correctly.
2445     // We would need a deep integration with the spiller to do the
2446     // right thing here. Anyway, that is still good for early testing.
2447     ExtraInfo->setStage(VirtReg, RS_Memory);
2448     LLVM_DEBUG(dbgs() << "Do as if this register is in memory\n");
2449     NewVRegs.push_back(VirtReg.reg());
2450   } else {
2451     NamedRegionTimer T("spill", "Spiller", TimerGroupName,
2452                        TimerGroupDescription, TimePassesIsEnabled);
2453     LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2454     spiller().spill(LRE);
2455     ExtraInfo->setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
2456 
2457     // Tell LiveDebugVariables about the new ranges. Ranges not being covered by
2458     // the new regs are kept in LDV (still mapping to the old register), until
2459     // we rewrite spilled locations in LDV at a later stage.
2460     DebugVars->splitRegister(VirtReg.reg(), LRE.regs(), *LIS);
2461 
2462     if (VerifyEnabled)
2463       MF->verify(this, "After spilling");
2464   }
2465 
2466   // The live virtual register requesting allocation was spilled, so tell
2467   // the caller not to allocate anything during this round.
2468   return 0;
2469 }
2470 
2471 void RAGreedy::RAGreedyStats::report(MachineOptimizationRemarkMissed &R) {
2472   using namespace ore;
2473   if (Spills) {
2474     R << NV("NumSpills", Spills) << " spills ";
2475     R << NV("TotalSpillsCost", SpillsCost) << " total spills cost ";
2476   }
2477   if (FoldedSpills) {
2478     R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
2479     R << NV("TotalFoldedSpillsCost", FoldedSpillsCost)
2480       << " total folded spills cost ";
2481   }
2482   if (Reloads) {
2483     R << NV("NumReloads", Reloads) << " reloads ";
2484     R << NV("TotalReloadsCost", ReloadsCost) << " total reloads cost ";
2485   }
2486   if (FoldedReloads) {
2487     R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
2488     R << NV("TotalFoldedReloadsCost", FoldedReloadsCost)
2489       << " total folded reloads cost ";
2490   }
2491   if (ZeroCostFoldedReloads)
2492     R << NV("NumZeroCostFoldedReloads", ZeroCostFoldedReloads)
2493       << " zero cost folded reloads ";
2494   if (Copies) {
2495     R << NV("NumVRCopies", Copies) << " virtual registers copies ";
2496     R << NV("TotalCopiesCost", CopiesCost) << " total copies cost ";
2497   }
2498 }
2499 
2500 RAGreedy::RAGreedyStats RAGreedy::computeStats(MachineBasicBlock &MBB) {
2501   RAGreedyStats Stats;
2502   const MachineFrameInfo &MFI = MF->getFrameInfo();
2503   int FI;
2504 
2505   auto isSpillSlotAccess = [&MFI](const MachineMemOperand *A) {
2506     return MFI.isSpillSlotObjectIndex(cast<FixedStackPseudoSourceValue>(
2507         A->getPseudoValue())->getFrameIndex());
2508   };
2509   auto isPatchpointInstr = [](const MachineInstr &MI) {
2510     return MI.getOpcode() == TargetOpcode::PATCHPOINT ||
2511            MI.getOpcode() == TargetOpcode::STACKMAP ||
2512            MI.getOpcode() == TargetOpcode::STATEPOINT;
2513   };
2514   for (MachineInstr &MI : MBB) {
2515     if (MI.isCopy()) {
2516       MachineOperand &Dest = MI.getOperand(0);
2517       MachineOperand &Src = MI.getOperand(1);
2518       if (Dest.isReg() && Src.isReg() && Dest.getReg().isVirtual() &&
2519           Src.getReg().isVirtual())
2520         ++Stats.Copies;
2521       continue;
2522     }
2523 
2524     SmallVector<const MachineMemOperand *, 2> Accesses;
2525     if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) {
2526       ++Stats.Reloads;
2527       continue;
2528     }
2529     if (TII->isStoreToStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) {
2530       ++Stats.Spills;
2531       continue;
2532     }
2533     if (TII->hasLoadFromStackSlot(MI, Accesses) &&
2534         llvm::any_of(Accesses, isSpillSlotAccess)) {
2535       if (!isPatchpointInstr(MI)) {
2536         Stats.FoldedReloads += Accesses.size();
2537         continue;
2538       }
2539       // For statepoint there may be folded and zero cost folded stack reloads.
2540       std::pair<unsigned, unsigned> NonZeroCostRange =
2541           TII->getPatchpointUnfoldableRange(MI);
2542       SmallSet<unsigned, 16> FoldedReloads;
2543       SmallSet<unsigned, 16> ZeroCostFoldedReloads;
2544       for (unsigned Idx = 0, E = MI.getNumOperands(); Idx < E; ++Idx) {
2545         MachineOperand &MO = MI.getOperand(Idx);
2546         if (!MO.isFI() || !MFI.isSpillSlotObjectIndex(MO.getIndex()))
2547           continue;
2548         if (Idx >= NonZeroCostRange.first && Idx < NonZeroCostRange.second)
2549           FoldedReloads.insert(MO.getIndex());
2550         else
2551           ZeroCostFoldedReloads.insert(MO.getIndex());
2552       }
2553       // If stack slot is used in folded reload it is not zero cost then.
2554       for (unsigned Slot : FoldedReloads)
2555         ZeroCostFoldedReloads.erase(Slot);
2556       Stats.FoldedReloads += FoldedReloads.size();
2557       Stats.ZeroCostFoldedReloads += ZeroCostFoldedReloads.size();
2558       continue;
2559     }
2560     Accesses.clear();
2561     if (TII->hasStoreToStackSlot(MI, Accesses) &&
2562         llvm::any_of(Accesses, isSpillSlotAccess)) {
2563       Stats.FoldedSpills += Accesses.size();
2564     }
2565   }
2566   // Set cost of collected statistic by multiplication to relative frequency of
2567   // this basic block.
2568   float RelFreq = MBFI->getBlockFreqRelativeToEntryBlock(&MBB);
2569   Stats.ReloadsCost = RelFreq * Stats.Reloads;
2570   Stats.FoldedReloadsCost = RelFreq * Stats.FoldedReloads;
2571   Stats.SpillsCost = RelFreq * Stats.Spills;
2572   Stats.FoldedSpillsCost = RelFreq * Stats.FoldedSpills;
2573   Stats.CopiesCost = RelFreq * Stats.Copies;
2574   return Stats;
2575 }
2576 
2577 RAGreedy::RAGreedyStats RAGreedy::reportStats(MachineLoop *L) {
2578   RAGreedyStats Stats;
2579 
2580   // Sum up the spill and reloads in subloops.
2581   for (MachineLoop *SubLoop : *L)
2582     Stats.add(reportStats(SubLoop));
2583 
2584   for (MachineBasicBlock *MBB : L->getBlocks())
2585     // Handle blocks that were not included in subloops.
2586     if (Loops->getLoopFor(MBB) == L)
2587       Stats.add(computeStats(*MBB));
2588 
2589   if (!Stats.isEmpty()) {
2590     using namespace ore;
2591 
2592     ORE->emit([&]() {
2593       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReloadCopies",
2594                                         L->getStartLoc(), L->getHeader());
2595       Stats.report(R);
2596       R << "generated in loop";
2597       return R;
2598     });
2599   }
2600   return Stats;
2601 }
2602 
2603 void RAGreedy::reportStats() {
2604   if (!ORE->allowExtraAnalysis(DEBUG_TYPE))
2605     return;
2606   RAGreedyStats Stats;
2607   for (MachineLoop *L : *Loops)
2608     Stats.add(reportStats(L));
2609   // Process non-loop blocks.
2610   for (MachineBasicBlock &MBB : *MF)
2611     if (!Loops->getLoopFor(&MBB))
2612       Stats.add(computeStats(MBB));
2613   if (!Stats.isEmpty()) {
2614     using namespace ore;
2615 
2616     ORE->emit([&]() {
2617       DebugLoc Loc;
2618       if (auto *SP = MF->getFunction().getSubprogram())
2619         Loc = DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
2620       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "SpillReloadCopies", Loc,
2621                                         &MF->front());
2622       Stats.report(R);
2623       R << "generated in function";
2624       return R;
2625     });
2626   }
2627 }
2628 
2629 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2630   LLVM_DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
2631                     << "********** Function: " << mf.getName() << '\n');
2632 
2633   MF = &mf;
2634   TRI = MF->getSubtarget().getRegisterInfo();
2635   TII = MF->getSubtarget().getInstrInfo();
2636   RCI.runOnMachineFunction(mf);
2637 
2638   if (VerifyEnabled)
2639     MF->verify(this, "Before greedy register allocator");
2640 
2641   RegAllocBase::init(getAnalysis<VirtRegMap>(),
2642                      getAnalysis<LiveIntervals>(),
2643                      getAnalysis<LiveRegMatrix>());
2644   Indexes = &getAnalysis<SlotIndexes>();
2645   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2646   DomTree = &getAnalysis<MachineDominatorTree>();
2647   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2648   Loops = &getAnalysis<MachineLoopInfo>();
2649   Bundles = &getAnalysis<EdgeBundles>();
2650   SpillPlacer = &getAnalysis<SpillPlacement>();
2651   DebugVars = &getAnalysis<LiveDebugVariables>();
2652   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2653 
2654   initializeCSRCost();
2655 
2656   RegCosts = TRI->getRegisterCosts(*MF);
2657 
2658   ExtraInfo.emplace();
2659   EvictAdvisor =
2660       getAnalysis<RegAllocEvictionAdvisorAnalysis>().getAdvisor(*MF, *this);
2661 
2662   VRAI = std::make_unique<VirtRegAuxInfo>(*MF, *LIS, *VRM, *Loops, *MBFI);
2663   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, *VRAI));
2664 
2665   VRAI->calculateSpillWeightsAndHints();
2666 
2667   LLVM_DEBUG(LIS->dump());
2668 
2669   SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
2670   SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI, *VRAI));
2671 
2672   IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
2673   GlobalCand.resize(32);  // This will grow as needed.
2674   SetOfBrokenHints.clear();
2675   LastEvicted.clear();
2676 
2677   allocatePhysRegs();
2678   tryHintsRecoloring();
2679 
2680   if (VerifyEnabled)
2681     MF->verify(this, "Before post optimization");
2682   postOptimization();
2683   reportStats();
2684 
2685   releaseMemory();
2686   return true;
2687 }
2688