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