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