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