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