1 //==- RegAllocGreedy.h ------- greedy register allocator  ----------*-C++-*-==//
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 // This file defines the RAGreedy function pass for register allocation in
9 // optimized builds.
10 //===----------------------------------------------------------------------===//
11 
12 #ifndef LLVM_CODEGEN_REGALLOCGREEDY_H_
13 #define LLVM_CODEGEN_REGALLOCGREEDY_H_
14 
15 #include "InterferenceCache.h"
16 #include "RegAllocBase.h"
17 #include "RegAllocEvictionAdvisor.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/SetVector.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/CodeGen/CalcSpillWeights.h"
30 #include "llvm/CodeGen/LiveInterval.h"
31 #include "llvm/CodeGen/LiveRangeEdit.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/RegisterClassInfo.h"
35 #include "llvm/CodeGen/Spiller.h"
36 #include "llvm/CodeGen/TargetRegisterInfo.h"
37 #include <algorithm>
38 #include <cstdint>
39 #include <memory>
40 #include <queue>
41 #include <utility>
42 
43 namespace llvm {
44 class AllocationOrder;
45 class AnalysisUsage;
46 class EdgeBundles;
47 class LiveDebugVariables;
48 class LiveIntervals;
49 class LiveRegMatrix;
50 class MachineBasicBlock;
51 class MachineBlockFrequencyInfo;
52 class MachineDominatorTree;
53 class MachineLoop;
54 class MachineLoopInfo;
55 class MachineOptimizationRemarkEmitter;
56 class MachineOptimizationRemarkMissed;
57 class SlotIndex;
58 class SlotIndexes;
59 class TargetInstrInfo;
60 class VirtRegMap;
61 
62 class LLVM_LIBRARY_VISIBILITY RAGreedy : public MachineFunctionPass,
63                                          public RegAllocBase,
64                                          private LiveRangeEdit::Delegate {
65   // Interface to eviction advisers
66 public:
67   /// Track allocation stage and eviction loop prevention during allocation.
68   class ExtraRegInfo final {
69     // RegInfo - Keep additional information about each live range.
70     struct RegInfo {
71       LiveRangeStage Stage = RS_New;
72 
73       // Cascade - Eviction loop prevention. See
74       // canEvictInterferenceBasedOnCost().
75       unsigned Cascade = 0;
76 
77       RegInfo() = default;
78     };
79 
80     IndexedMap<RegInfo, VirtReg2IndexFunctor> Info;
81     unsigned NextCascade = 1;
82 
83   public:
84     ExtraRegInfo() = default;
85     ExtraRegInfo(const ExtraRegInfo &) = delete;
86 
87     LiveRangeStage getStage(Register Reg) const { return Info[Reg].Stage; }
88 
89     LiveRangeStage getStage(const LiveInterval &VirtReg) const {
90       return getStage(VirtReg.reg());
91     }
92 
93     void setStage(Register Reg, LiveRangeStage Stage) {
94       Info.grow(Reg.id());
95       Info[Reg].Stage = Stage;
96     }
97 
98     void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
99       setStage(VirtReg.reg(), Stage);
100     }
101 
102     /// Return the current stage of the register, if present, otherwise
103     /// initialize it and return that.
104     LiveRangeStage getOrInitStage(Register Reg) {
105       Info.grow(Reg.id());
106       return getStage(Reg);
107     }
108 
109     unsigned getCascade(Register Reg) const { return Info[Reg].Cascade; }
110 
111     void setCascade(Register Reg, unsigned Cascade) {
112       Info.grow(Reg.id());
113       Info[Reg].Cascade = Cascade;
114     }
115 
116     unsigned getOrAssignNewCascade(Register Reg) {
117       unsigned Cascade = getCascade(Reg);
118       if (!Cascade) {
119         Cascade = NextCascade++;
120         setCascade(Reg, Cascade);
121       }
122       return Cascade;
123     }
124 
125     unsigned getCascadeOrCurrentNext(Register Reg) const {
126       unsigned Cascade = getCascade(Reg);
127       if (!Cascade)
128         Cascade = NextCascade;
129       return Cascade;
130     }
131 
132     template <typename Iterator>
133     void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
134       for (; Begin != End; ++Begin) {
135         Register Reg = *Begin;
136         Info.grow(Reg.id());
137         if (Info[Reg].Stage == RS_New)
138           Info[Reg].Stage = NewStage;
139       }
140     }
141     void LRE_DidCloneVirtReg(Register New, Register Old);
142   };
143 
144   LiveRegMatrix *getInterferenceMatrix() const { return Matrix; }
145   LiveIntervals *getLiveIntervals() const { return LIS; }
146   VirtRegMap *getVirtRegMap() const { return VRM; }
147   const RegisterClassInfo &getRegClassInfo() const { return RegClassInfo; }
148   const ExtraRegInfo &getExtraInfo() const { return *ExtraInfo; }
149   size_t getQueueSize() const { return Queue.size(); }
150   // end (interface to eviction advisers)
151 
152 private:
153   // Convenient shortcuts.
154   using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
155   using SmallLISet = SmallPtrSet<const LiveInterval *, 4>;
156 
157   // We need to track all tentative recolorings so we can roll back any
158   // successful and unsuccessful recoloring attempts.
159   using RecoloringStack =
160       SmallVector<std::pair<const LiveInterval *, MCRegister>, 8>;
161 
162   // context
163   MachineFunction *MF;
164 
165   // Shortcuts to some useful interface.
166   const TargetInstrInfo *TII;
167   const TargetRegisterInfo *TRI;
168   RegisterClassInfo RCI;
169 
170   // analyses
171   SlotIndexes *Indexes;
172   MachineBlockFrequencyInfo *MBFI;
173   MachineDominatorTree *DomTree;
174   MachineLoopInfo *Loops;
175   MachineOptimizationRemarkEmitter *ORE;
176   EdgeBundles *Bundles;
177   SpillPlacement *SpillPlacer;
178   LiveDebugVariables *DebugVars;
179   AliasAnalysis *AA;
180 
181   // state
182   std::unique_ptr<Spiller> SpillerInstance;
183   PQueue Queue;
184   std::unique_ptr<VirtRegAuxInfo> VRAI;
185   Optional<ExtraRegInfo> ExtraInfo;
186   std::unique_ptr<RegAllocEvictionAdvisor> EvictAdvisor;
187 
188   // Enum CutOffStage to keep a track whether the register allocation failed
189   // because of the cutoffs encountered in last chance recoloring.
190   // Note: This is used as bitmask. New value should be next power of 2.
191   enum CutOffStage {
192     // No cutoffs encountered
193     CO_None = 0,
194 
195     // lcr-max-depth cutoff encountered
196     CO_Depth = 1,
197 
198     // lcr-max-interf cutoff encountered
199     CO_Interf = 2
200   };
201 
202   uint8_t CutOffInfo;
203 
204 #ifndef NDEBUG
205   static const char *const StageName[];
206 #endif
207 
208   /// EvictionTrack - Keeps track of past evictions in order to optimize region
209   /// split decision.
210   class EvictionTrack {
211 
212   public:
213     using EvictorInfo =
214         std::pair<Register /* evictor */, MCRegister /* physreg */>;
215     using EvicteeInfo = llvm::DenseMap<Register /* evictee */, EvictorInfo>;
216 
217   private:
218     /// Each Vreg that has been evicted in the last stage of selectOrSplit will
219     /// be mapped to the evictor Vreg and the PhysReg it was evicted from.
220     EvicteeInfo Evictees;
221 
222   public:
223     /// Clear all eviction information.
224     void clear() { Evictees.clear(); }
225 
226     ///  Clear eviction information for the given evictee Vreg.
227     /// E.g. when Vreg get's a new allocation, the old eviction info is no
228     /// longer relevant.
229     /// \param Evictee The evictee Vreg for whom we want to clear collected
230     /// eviction info.
231     void clearEvicteeInfo(Register Evictee) { Evictees.erase(Evictee); }
232 
233     /// Track new eviction.
234     /// The Evictor vreg has evicted the Evictee vreg from Physreg.
235     /// \param PhysReg The physical register Evictee was evicted from.
236     /// \param Evictor The evictor Vreg that evicted Evictee.
237     /// \param Evictee The evictee Vreg.
238     void addEviction(MCRegister PhysReg, Register Evictor, Register Evictee) {
239       Evictees[Evictee].first = Evictor;
240       Evictees[Evictee].second = PhysReg;
241     }
242 
243     /// Return the Evictor Vreg which evicted Evictee Vreg from PhysReg.
244     /// \param Evictee The evictee vreg.
245     /// \return The Evictor vreg which evicted Evictee vreg from PhysReg. 0 if
246     /// nobody has evicted Evictee from PhysReg.
247     EvictorInfo getEvictor(Register Evictee) {
248       if (Evictees.count(Evictee)) {
249         return Evictees[Evictee];
250       }
251 
252       return EvictorInfo(0, 0);
253     }
254   };
255 
256   // Keeps track of past evictions in order to optimize region split decision.
257   EvictionTrack LastEvicted;
258 
259   // splitting state.
260   std::unique_ptr<SplitAnalysis> SA;
261   std::unique_ptr<SplitEditor> SE;
262 
263   /// Cached per-block interference maps
264   InterferenceCache IntfCache;
265 
266   /// All basic blocks where the current register has uses.
267   SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
268 
269   /// Global live range splitting candidate info.
270   struct GlobalSplitCandidate {
271     // Register intended for assignment, or 0.
272     MCRegister PhysReg;
273 
274     // SplitKit interval index for this candidate.
275     unsigned IntvIdx;
276 
277     // Interference for PhysReg.
278     InterferenceCache::Cursor Intf;
279 
280     // Bundles where this candidate should be live.
281     BitVector LiveBundles;
282     SmallVector<unsigned, 8> ActiveBlocks;
283 
284     void reset(InterferenceCache &Cache, MCRegister Reg) {
285       PhysReg = Reg;
286       IntvIdx = 0;
287       Intf.setPhysReg(Cache, Reg);
288       LiveBundles.clear();
289       ActiveBlocks.clear();
290     }
291 
292     // Set B[I] = C for every live bundle where B[I] was NoCand.
293     unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
294       unsigned Count = 0;
295       for (unsigned I : LiveBundles.set_bits())
296         if (B[I] == NoCand) {
297           B[I] = C;
298           Count++;
299         }
300       return Count;
301     }
302   };
303 
304   /// Candidate info for each PhysReg in AllocationOrder.
305   /// This vector never shrinks, but grows to the size of the largest register
306   /// class.
307   SmallVector<GlobalSplitCandidate, 32> GlobalCand;
308 
309   enum : unsigned { NoCand = ~0u };
310 
311   /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
312   /// NoCand which indicates the stack interval.
313   SmallVector<unsigned, 32> BundleCand;
314 
315   /// Callee-save register cost, calculated once per machine function.
316   BlockFrequency CSRCost;
317 
318   /// Set of broken hints that may be reconciled later because of eviction.
319   SmallSetVector<const LiveInterval *, 8> SetOfBrokenHints;
320 
321   /// The register cost values. This list will be recreated for each Machine
322   /// Function
323   ArrayRef<uint8_t> RegCosts;
324 
325 public:
326   RAGreedy(const RegClassFilterFunc F = allocateAllRegClasses);
327 
328   /// Return the pass name.
329   StringRef getPassName() const override { return "Greedy Register Allocator"; }
330 
331   /// RAGreedy analysis usage.
332   void getAnalysisUsage(AnalysisUsage &AU) const override;
333   void releaseMemory() override;
334   Spiller &spiller() override { return *SpillerInstance; }
335   void enqueueImpl(const LiveInterval *LI) override;
336   const LiveInterval *dequeue() override;
337   MCRegister selectOrSplit(const LiveInterval &,
338                            SmallVectorImpl<Register> &) override;
339   void aboutToRemoveInterval(const LiveInterval &) override;
340 
341   /// Perform register allocation.
342   bool runOnMachineFunction(MachineFunction &mf) override;
343 
344   MachineFunctionProperties getRequiredProperties() const override {
345     return MachineFunctionProperties().set(
346         MachineFunctionProperties::Property::NoPHIs);
347   }
348 
349   MachineFunctionProperties getClearedProperties() const override {
350     return MachineFunctionProperties().set(
351         MachineFunctionProperties::Property::IsSSA);
352   }
353 
354   static char ID;
355 
356 private:
357   MCRegister selectOrSplitImpl(const LiveInterval &,
358                                SmallVectorImpl<Register> &, SmallVirtRegSet &,
359                                RecoloringStack &, unsigned = 0);
360 
361   bool LRE_CanEraseVirtReg(Register) override;
362   void LRE_WillShrinkVirtReg(Register) override;
363   void LRE_DidCloneVirtReg(Register, Register) override;
364   void enqueue(PQueue &CurQueue, const LiveInterval *LI);
365   const LiveInterval *dequeue(PQueue &CurQueue);
366 
367   BlockFrequency calcSpillCost();
368   bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency &);
369   bool addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
370   bool growRegion(GlobalSplitCandidate &Cand);
371   bool splitCanCauseEvictionChain(Register Evictee, GlobalSplitCandidate &Cand,
372                                   unsigned BBNumber,
373                                   const AllocationOrder &Order);
374   BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate &,
375                                      const AllocationOrder &Order);
376   bool calcCompactRegion(GlobalSplitCandidate &);
377   void splitAroundRegion(LiveRangeEdit &, ArrayRef<unsigned>);
378   void calcGapWeights(MCRegister, SmallVectorImpl<float> &);
379   bool canEvictInterferenceInRange(const LiveInterval &VirtReg,
380                                    MCRegister PhysReg, SlotIndex Start,
381                                    SlotIndex End, EvictionCost &MaxCost) const;
382   MCRegister getCheapestEvicteeWeight(const AllocationOrder &Order,
383                                       const LiveInterval &VirtReg,
384                                       SlotIndex Start, SlotIndex End,
385                                       float *BestEvictWeight) const;
386   void evictInterference(const LiveInterval &, MCRegister,
387                          SmallVectorImpl<Register> &);
388   bool mayRecolorAllInterferences(MCRegister PhysReg,
389                                   const LiveInterval &VirtReg,
390                                   SmallLISet &RecoloringCandidates,
391                                   const SmallVirtRegSet &FixedRegisters);
392 
393   MCRegister tryAssign(const LiveInterval &, AllocationOrder &,
394                        SmallVectorImpl<Register> &, const SmallVirtRegSet &);
395   MCRegister tryEvict(const LiveInterval &, AllocationOrder &,
396                       SmallVectorImpl<Register> &, uint8_t,
397                       const SmallVirtRegSet &);
398   MCRegister tryRegionSplit(const LiveInterval &, AllocationOrder &,
399                             SmallVectorImpl<Register> &);
400   /// Calculate cost of region splitting.
401   unsigned calculateRegionSplitCost(const LiveInterval &VirtReg,
402                                     AllocationOrder &Order,
403                                     BlockFrequency &BestCost,
404                                     unsigned &NumCands, bool IgnoreCSR);
405   /// Perform region splitting.
406   unsigned doRegionSplit(const LiveInterval &VirtReg, unsigned BestCand,
407                          bool HasCompact, SmallVectorImpl<Register> &NewVRegs);
408   /// Check other options before using a callee-saved register for the first
409   /// time.
410   MCRegister tryAssignCSRFirstTime(const LiveInterval &VirtReg,
411                                    AllocationOrder &Order, MCRegister PhysReg,
412                                    uint8_t &CostPerUseLimit,
413                                    SmallVectorImpl<Register> &NewVRegs);
414   void initializeCSRCost();
415   unsigned tryBlockSplit(const LiveInterval &, AllocationOrder &,
416                          SmallVectorImpl<Register> &);
417   unsigned tryInstructionSplit(const LiveInterval &, AllocationOrder &,
418                                SmallVectorImpl<Register> &);
419   unsigned tryLocalSplit(const LiveInterval &, AllocationOrder &,
420                          SmallVectorImpl<Register> &);
421   unsigned trySplit(const LiveInterval &, AllocationOrder &,
422                     SmallVectorImpl<Register> &, const SmallVirtRegSet &);
423   unsigned tryLastChanceRecoloring(const LiveInterval &, AllocationOrder &,
424                                    SmallVectorImpl<Register> &,
425                                    SmallVirtRegSet &, RecoloringStack &,
426                                    unsigned);
427   bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<Register> &,
428                                SmallVirtRegSet &, RecoloringStack &, unsigned);
429   void tryHintRecoloring(const LiveInterval &);
430   void tryHintsRecoloring();
431 
432   /// Model the information carried by one end of a copy.
433   struct HintInfo {
434     /// The frequency of the copy.
435     BlockFrequency Freq;
436     /// The virtual register or physical register.
437     Register Reg;
438     /// Its currently assigned register.
439     /// In case of a physical register Reg == PhysReg.
440     MCRegister PhysReg;
441 
442     HintInfo(BlockFrequency Freq, Register Reg, MCRegister PhysReg)
443         : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
444   };
445   using HintsInfo = SmallVector<HintInfo, 4>;
446 
447   BlockFrequency getBrokenHintFreq(const HintsInfo &, MCRegister);
448   void collectHintInfo(Register, HintsInfo &);
449 
450   /// Greedy RA statistic to remark.
451   struct RAGreedyStats {
452     unsigned Reloads = 0;
453     unsigned FoldedReloads = 0;
454     unsigned ZeroCostFoldedReloads = 0;
455     unsigned Spills = 0;
456     unsigned FoldedSpills = 0;
457     unsigned Copies = 0;
458     float ReloadsCost = 0.0f;
459     float FoldedReloadsCost = 0.0f;
460     float SpillsCost = 0.0f;
461     float FoldedSpillsCost = 0.0f;
462     float CopiesCost = 0.0f;
463 
464     bool isEmpty() {
465       return !(Reloads || FoldedReloads || Spills || FoldedSpills ||
466                ZeroCostFoldedReloads || Copies);
467     }
468 
469     void add(RAGreedyStats other) {
470       Reloads += other.Reloads;
471       FoldedReloads += other.FoldedReloads;
472       ZeroCostFoldedReloads += other.ZeroCostFoldedReloads;
473       Spills += other.Spills;
474       FoldedSpills += other.FoldedSpills;
475       Copies += other.Copies;
476       ReloadsCost += other.ReloadsCost;
477       FoldedReloadsCost += other.FoldedReloadsCost;
478       SpillsCost += other.SpillsCost;
479       FoldedSpillsCost += other.FoldedSpillsCost;
480       CopiesCost += other.CopiesCost;
481     }
482 
483     void report(MachineOptimizationRemarkMissed &R);
484   };
485 
486   /// Compute statistic for a basic block.
487   RAGreedyStats computeStats(MachineBasicBlock &MBB);
488 
489   /// Compute and report statistic through a remark.
490   RAGreedyStats reportStats(MachineLoop *L);
491 
492   /// Report the statistic for each loop.
493   void reportStats();
494 };
495 } // namespace llvm
496 #endif // #ifndef LLVM_CODEGEN_REGALLOCGREEDY_H_
497