1 //===- MLRegAllocEvictAdvisor.cpp - ML eviction advisor -------------------===//
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 // Implementation of the ML eviction advisor and reward injection pass
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RegAllocEvictionAdvisor.h"
14 #include "RegAllocGreedy.h"
15 #include "RegAllocScore.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/MLModelRunner.h"
18 #include "llvm/Analysis/ModelUnderTrainingRunner.h"
19 #include "llvm/Analysis/NoInferenceModelRunner.h"
20 #include "llvm/Analysis/ReleaseModeModelRunner.h"
21 #include "llvm/Analysis/Utils/TFUtils.h"
22 #include "llvm/CodeGen/CalcSpillWeights.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegisterClassInfo.h"
30 #include "llvm/CodeGen/VirtRegMap.h"
31 #include "llvm/Config/config.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/Pass.h"
34 #include "llvm/PassRegistry.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Target/TargetMachine.h"
38 
39 #include <array>
40 #include <memory>
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "ml-regalloc"
45 
46 // Generated header in release (AOT) mode
47 #if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL)
48 #include "RegallocEvictModel.h"
49 #endif
50 
51 // Options that only make sense in development mode
52 #ifdef LLVM_HAVE_TF_API
53 static cl::opt<std::string> TrainingLog(
54     "regalloc-training-log", cl::Hidden,
55     cl::desc("Training log for the register allocator eviction model"));
56 
57 static cl::opt<std::string> ModelUnderTraining(
58     "regalloc-model", cl::Hidden,
59     cl::desc("The model being trained for register allocation eviction"));
60 
61 #endif // #ifdef LLVM_HAVE_TF_API
62 
63 extern cl::opt<unsigned> EvictInterferenceCutoff;
64 
65 /// The score injection pass.
66 /// This pass calculates the score for a function and inserts it in the log, but
67 /// this happens only in development mode. It's a no-op otherwise.
68 namespace llvm {
69 class RegAllocScoring : public MachineFunctionPass {
70 public:
71   static char ID;
72 
73   RegAllocScoring() : MachineFunctionPass(ID) {
74     initializeRegAllocScoringPass(*PassRegistry::getPassRegistry());
75   }
76 
77   ~RegAllocScoring() override = default;
78 
79   StringRef getPassName() const override {
80     return "Register Allocation Pass Scoring";
81   }
82 
83   /// RegAllocReward analysis usage.
84   void getAnalysisUsage(AnalysisUsage &AU) const override {
85     AU.setPreservesAll();
86     AU.addRequired<RegAllocEvictionAdvisorAnalysis>();
87     AU.addRequired<MachineBlockFrequencyInfo>();
88     AU.addRequired<AAResultsWrapperPass>();
89     MachineFunctionPass::getAnalysisUsage(AU);
90   }
91 
92   /// Performs this pass
93   bool runOnMachineFunction(MachineFunction &) override;
94 };
95 
96 char RegAllocScoring::ID = 0;
97 FunctionPass *createRegAllocScoringPass() { return new RegAllocScoring(); }
98 
99 } // namespace llvm
100 
101 INITIALIZE_PASS(RegAllocScoring, "regallocscoringpass",
102                 "Register Allocation Scoring Pass", false, false)
103 
104 // ===================================
105 // Common ML Advisor declarations
106 // ===================================
107 namespace {
108 // This is the maximum number of interfererring ranges. That's the number of
109 // distinct AllocationOrder values, which comes from MCRegisterClass::RegsSize.
110 // For X86, that's 32.
111 // TODO: find a way to get this, statically, in a programmatic way.
112 static const int64_t MaxInterferences = 32;
113 
114 // Logically, we can think of the feature set given to the evaluator as a 2D
115 // matrix. The rows are the features (see next). The columns correspond to the
116 // interferences. We treat the candidate virt reg as an 'interference', too, as
117 // its feature set is the same as that of the interferring ranges. So we'll have
118 // MaxInterferences + 1 columns and by convention, we will use the last column
119 // for the virt reg seeking allocation.
120 static const int64_t CandidateVirtRegPos = MaxInterferences;
121 static const int64_t NumberOfInterferences = CandidateVirtRegPos + 1;
122 
123 // Most features are as described above, so we'll reuse this vector in defining
124 // them.
125 static const std::vector<int64_t> PerLiveRangeShape{1, NumberOfInterferences};
126 
127 // --------------
128 // Features table
129 // --------------
130 // For each interfering live range (incl. the candidate) we collect a number of
131 // features. However, because the features are of different types (and because
132 // of ML best practices), we organize the tensors per feature, not per
133 // candidate. Each such tensor has a scalar value corresponding to the
134 // interferring live range at that position, in the order in AllocationOrder.
135 // The last position corresponds to the virt reg seeking allocation.
136 // Exception to all that is the progression feature, which is just a scalar (see
137 // its documentation for details).
138 // Note on naming: the "_by_max" are normalized using the largest value of that
139 // tensor, as observed in the current decision making stage (i.e. for the
140 // current call to the advisor's tryFindEvictionCandidate)
141 //
142 // The feature list format: type, name, shape, documentation.
143 // Note: we can really just use int64 and float, hence the modeling of some
144 // bools as int64 values.
145 #define RA_EVICT_FEATURES_LIST(M)                                              \
146   M(int64_t, mask, PerLiveRangeShape,                                          \
147     "boolean values, 0 for unavailable candidates (i.e. if a position is 0, "  \
148     "it "                                                                      \
149     "can't be evicted)")                                                       \
150   M(int64_t, is_free, PerLiveRangeShape,                                       \
151     "boolean values, 1 if this phys reg is actually free (no interferences)")  \
152   M(float, nr_urgent, PerLiveRangeShape,                                       \
153     "number of 'urgent' intervals, normalized. Urgent are those that are OK "  \
154     "to break cascades")                                                       \
155   M(float, nr_broken_hints, PerLiveRangeShape,                                 \
156     "if this position were evicted, how many broken hints would there be")     \
157   M(int64_t, is_hint, PerLiveRangeShape,                                       \
158     "is this a preferred phys reg for the candidate")                          \
159   M(int64_t, is_local, PerLiveRangeShape,                                      \
160     "is this live range local to a basic block")                               \
161   M(float, nr_rematerializable, PerLiveRangeShape,                             \
162     "nr rematerializable ranges")                                              \
163   M(float, nr_defs_and_uses, PerLiveRangeShape,                                \
164     "bb freq - weighed nr defs and uses")                                      \
165   M(float, weighed_reads_by_max, PerLiveRangeShape,                            \
166     "bb freq - weighed nr of reads, normalized")                               \
167   M(float, weighed_writes_by_max, PerLiveRangeShape,                           \
168     "bb feq - weighed nr of writes, normalized")                               \
169   M(float, weighed_read_writes_by_max, PerLiveRangeShape,                      \
170     "bb freq - weighed nr of uses that are both read and writes, normalized")  \
171   M(float, weighed_indvars_by_max, PerLiveRangeShape,                          \
172     "bb freq - weighed nr of uses that are indvars, normalized")               \
173   M(float, hint_weights_by_max, PerLiveRangeShape,                             \
174     "bb freq - weighed nr of uses that are hints, normalized")                 \
175   M(float, start_bb_freq_by_max, PerLiveRangeShape,                            \
176     "the freq in the start block, normalized")                                 \
177   M(float, end_bb_freq_by_max, PerLiveRangeShape,                              \
178     "freq of end block, normalized")                                           \
179   M(float, hottest_bb_freq_by_max, PerLiveRangeShape,                          \
180     "hottest BB freq, normalized")                                             \
181   M(float, liverange_size, PerLiveRangeShape,                                  \
182     "size (instr index diff) of the LR")                                       \
183   M(float, use_def_density, PerLiveRangeShape,                                 \
184     "the max weight, as computed by the manual heuristic")                     \
185   M(int64_t, max_stage, PerLiveRangeShape,                                     \
186     "largest stage of an interval in this LR")                                 \
187   M(int64_t, min_stage, PerLiveRangeShape,                                     \
188     "lowest stage of an interval in this LR")                                  \
189   M(float, progress, {1}, "ratio of current queue size to initial size")
190 
191 // The model learns to pick one of the mask == 1 interferences. This is the name
192 // of the output tensor.
193 // The contract with the model is that the output will be guaranteed to be to a
194 // mask == 1 position.
195 // Using a macro here to avoid 'not used' warnings (and keep cond compilation to
196 // a minimum)
197 #define DecisionName "index_to_evict"
198 
199 // Named features index.
200 enum FeatureIDs {
201 #define _FEATURE_IDX(_, name, __, ___) name,
202   RA_EVICT_FEATURES_LIST(_FEATURE_IDX)
203 #undef _FEATURE_IDX
204       FeatureCount
205 };
206 
207 // The ML advisor will typically have a sparse input to the evaluator, because
208 // various phys regs won't be available. It's easier (maintenance-wise) to
209 // bulk-reset the state of the evaluator each time we are about to use it again.
210 template <typename T> size_t getTotalSize(const std::vector<int64_t> &Shape) {
211   size_t Ret = sizeof(T);
212   for (const auto V : Shape)
213     Ret *= V;
214   return Ret;
215 }
216 
217 void resetInputs(MLModelRunner &Runner) {
218 #define _RESET(TYPE, NAME, SHAPE, __)                                          \
219   std::memset(Runner.getTensorUntyped(FeatureIDs::NAME), 0,                    \
220               getTotalSize<TYPE>(SHAPE));
221   RA_EVICT_FEATURES_LIST(_RESET)
222 #undef _RESET
223 }
224 
225 // Per-live interval components that get aggregated into the feature values that
226 // will be passed to the evaluator.
227 struct LIFeatureComponents {
228   double R = 0;
229   double W = 0;
230   double RW = 0;
231   double IndVarUpdates = 0;
232   double HintWeights = 0.0;
233   int64_t NrDefsAndUses = 0;
234   float HottestBlockFreq = 0.0;
235   bool IsRemat = false;
236 };
237 
238 using CandidateRegList =
239     std::array<std::pair<MCRegister, bool>, NumberOfInterferences>;
240 using FeaturesListNormalizer = std::array<float, FeatureIDs::FeatureCount>;
241 
242 /// The ML evictor (commonalities between release and development mode)
243 class MLEvictAdvisor : public RegAllocEvictionAdvisor {
244 public:
245   MLEvictAdvisor(MachineFunction &MF, const RAGreedy &RA, MLModelRunner *Runner,
246                  const MachineBlockFrequencyInfo &MBFI,
247                  const MachineLoopInfo &Loops);
248 
249 protected:
250   const RegAllocEvictionAdvisor &getDefaultAdvisor() const {
251     return static_cast<const RegAllocEvictionAdvisor &>(DefaultAdvisor);
252   }
253 
254   // The assumption is that if the Runner could not be constructed, we emit-ed
255   // error, and we shouldn't be asking for it here.
256   const MLModelRunner &getRunner() const { return *Runner; }
257 
258   /// This just calls Evaluate on the Runner, but in the development mode case,
259   /// if we're just capturing the log of the default advisor, it needs to call
260   /// the latter instead, so we need to pass all the necessary parameters for
261   /// it. In the development case, it will also log.
262   virtual int64_t tryFindEvictionCandidatePosition(
263       LiveInterval &VirtReg, const AllocationOrder &Order, unsigned OrderLimit,
264       uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const;
265 
266   /// Load the features of the given VirtReg (allocated or not) at column Pos,
267   /// but if  that can't be evicted, return false instead.
268   bool
269   loadInterferenceFeatures(LiveInterval &VirtReg, MCRegister PhysReg,
270                            bool IsHint, const SmallVirtRegSet &FixedRegisters,
271                            std::array<float, FeatureIDs::FeatureCount> &Largest,
272                            size_t Pos) const;
273 
274 private:
275   static float getInitialQueueSize(const MachineFunction &MF);
276 
277   MCRegister tryFindEvictionCandidate(
278       LiveInterval &VirtReg, const AllocationOrder &Order,
279       uint8_t CostPerUseLimit,
280       const SmallVirtRegSet &FixedRegisters) const override;
281 
282   void extractFeatures(const SmallVectorImpl<LiveInterval *> &Intervals,
283                        std::array<float, FeatureIDs::FeatureCount> &Largest,
284                        size_t Pos, int64_t IsHint, int64_t LocalIntfsCount,
285                        float NrUrgent) const;
286 
287   // Point-in-time: we didn't learn this, so we always delegate to the default.
288   bool canEvictHintInterference(
289       LiveInterval &VirtReg, MCRegister PhysReg,
290       const SmallVirtRegSet &FixedRegisters) const override {
291     return getDefaultAdvisor().canEvictHintInterference(VirtReg, PhysReg,
292                                                         FixedRegisters);
293   }
294 
295   const LIFeatureComponents
296   getLIFeatureComponents(const LiveInterval &LI) const;
297 
298   // Hold on to a default advisor for:
299   // 1) the implementation of canEvictHintInterference, because we didn't learn
300   // that nuance yet;
301   // 2) for bootstrapping (logging) in the development mode case.
302   const DefaultEvictionAdvisor DefaultAdvisor;
303   MLModelRunner *const Runner;
304   const MachineBlockFrequencyInfo &MBFI;
305   const MachineLoopInfo &Loops;
306 
307   // Indices of those features we don't want to normalize.
308   // This could be static and shared, but its initialization is non-trivial.
309   std::bitset<FeatureIDs::FeatureCount> DoNotNormalize;
310   const float InitialQSize;
311 };
312 
313 // ===================================
314 // Release (AOT) - specifics
315 // ===================================
316 #if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL)
317 const std::array<std::string, FeatureIDs::FeatureCount> FeatureNames{
318 #define _GETNAME(_, NAME, __, ___) #NAME,
319     RA_EVICT_FEATURES_LIST(_GETNAME)
320 #undef _GETNAME
321 };
322 class ReleaseModeEvictionAdvisorAnalysis final
323     : public RegAllocEvictionAdvisorAnalysis {
324 public:
325   ReleaseModeEvictionAdvisorAnalysis()
326       : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Release) {}
327   // support for isa<> and dyn_cast.
328   static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
329     return R->getAdvisorMode() == AdvisorMode::Release;
330   }
331 
332 private:
333   void getAnalysisUsage(AnalysisUsage &AU) const override {
334     AU.addRequired<MachineBlockFrequencyInfo>();
335     AU.addRequired<MachineLoopInfo>();
336     RegAllocEvictionAdvisorAnalysis::getAnalysisUsage(AU);
337   }
338 
339   std::unique_ptr<RegAllocEvictionAdvisor>
340   getAdvisor(MachineFunction &MF, const RAGreedy &RA) override {
341     if (!Runner)
342       Runner = std::make_unique<ReleaseModeModelRunner<RegallocEvictModel>>(
343           MF.getFunction().getContext(), FeatureNames, DecisionName);
344     return std::make_unique<MLEvictAdvisor>(
345         MF, RA, Runner.get(), getAnalysis<MachineBlockFrequencyInfo>(),
346         getAnalysis<MachineLoopInfo>());
347   }
348   std::unique_ptr<ReleaseModeModelRunner<RegallocEvictModel>> Runner;
349 };
350 #endif
351 
352 // ===================================
353 // Development mode-specifics
354 // ===================================
355 //
356 // Features we log
357 #ifdef LLVM_HAVE_TF_API
358 #define _DECL_FEATURES(type, name, shape, _)                                   \
359   TensorSpec::createSpec<type>(#name, shape),
360 
361 static const std::vector<TensorSpec> InputFeatures{
362     {RA_EVICT_FEATURES_LIST(_DECL_FEATURES)},
363 };
364 #undef _DECL_FEATURES
365 static const TensorSpec Output =
366     TensorSpec::createSpec<int64_t>(DecisionName, {1});
367 static const TensorSpec Reward = TensorSpec::createSpec<float>("reward", {1});
368 
369 // Features we bind on the model. The tensor names have a prefix, and we also
370 // need to include some tensors that are expected to be present by the training
371 // algo.
372 // TODO: can we just get rid of these?
373 #define _DECL_TRAIN_FEATURES(type, name, shape, _)                             \
374   TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
375 
376 static const std::vector<TensorSpec> TrainingInputFeatures{
377     {RA_EVICT_FEATURES_LIST(_DECL_TRAIN_FEATURES)
378          TensorSpec::createSpec<float>("action_discount", {1}),
379      TensorSpec::createSpec<int32_t>("action_step_type", {1}),
380      TensorSpec::createSpec<float>("action_reward", {1})}};
381 #undef _DECL_TRAIN_FEATURES
382 
383 class DevelopmentModeEvictAdvisor : public MLEvictAdvisor {
384 public:
385   DevelopmentModeEvictAdvisor(MachineFunction &MF, const RAGreedy &RA,
386                               MLModelRunner *Runner,
387                               const MachineBlockFrequencyInfo &MBFI,
388                               const MachineLoopInfo &Loops, Logger *Log)
389       : MLEvictAdvisor(MF, RA, Runner, MBFI, Loops), Log(Log) {}
390 
391 private:
392   int64_t tryFindEvictionCandidatePosition(
393       LiveInterval &VirtReg, const AllocationOrder &Order, unsigned OrderLimit,
394       uint8_t CostPerUseLimit,
395       const SmallVirtRegSet &FixedRegisters) const override;
396 
397   Logger *const Log;
398 };
399 
400 class DevelopmentModeEvictionAdvisorAnalysis final
401     : public RegAllocEvictionAdvisorAnalysis {
402 public:
403   DevelopmentModeEvictionAdvisorAnalysis()
404       : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Development) {}
405   // support for isa<> and dyn_cast.
406   static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
407     return R->getAdvisorMode() == AdvisorMode::Development;
408   }
409 
410   /// get the logger for the given function, or nullptr if we didn't collect
411   /// one. This is used to inject the score by the RegAllocScoring pass.
412   Logger *getLogger(const MachineFunction &MF) const {
413     auto I = LogMap.find(MF.getName());
414     if (I == LogMap.end())
415       return nullptr;
416     return I->second.get();
417   }
418 
419 private:
420   void getAnalysisUsage(AnalysisUsage &AU) const override {
421     AU.addRequired<MachineBlockFrequencyInfo>();
422     AU.addRequired<MachineLoopInfo>();
423     RegAllocEvictionAdvisorAnalysis::getAnalysisUsage(AU);
424   }
425 
426   // Save all the logs (when requested).
427   bool doFinalization(Module &M) override {
428     if (TrainingLog.empty())
429       return false;
430     std::error_code EC;
431     auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
432     if (EC) {
433       M.getContext().emitError(EC.message() + ":" + TrainingLog);
434       return false;
435     }
436     Logger::flushLogs(*OS, LogMap);
437     return false;
438   }
439 
440   std::unique_ptr<RegAllocEvictionAdvisor>
441   getAdvisor(MachineFunction &MF, const RAGreedy &RA) override {
442     LLVMContext &Ctx = MF.getFunction().getContext();
443     if (ModelUnderTraining.empty() && TrainingLog.empty()) {
444       Ctx.emitError("Regalloc development mode should be requested with at "
445                     "least logging enabled and/or a training model");
446       return nullptr;
447     }
448     if (!Runner) {
449       if (ModelUnderTraining.empty())
450         Runner = std::make_unique<NoInferenceModelRunner>(Ctx, InputFeatures);
451       else
452         Runner = ModelUnderTrainingRunner::createAndEnsureValid(
453             Ctx, ModelUnderTraining, DecisionName, TrainingInputFeatures);
454       if (!Runner) {
455         Ctx.emitError("Regalloc: could not set up the model runner");
456         return nullptr;
457       }
458     }
459 
460     Logger *Log = nullptr;
461     if (!TrainingLog.empty()) {
462       std::vector<LoggedFeatureSpec> LFS;
463       for (const auto &FS : InputFeatures)
464         LFS.push_back({FS, None});
465       if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(Runner.get()))
466         if (MUTR->outputLoggedFeatureSpecs().size() > 1)
467           append_range(LFS, drop_begin(MUTR->outputLoggedFeatureSpecs()));
468       // We always log the output; in particular, if we're not evaluating, we
469       // don't have an output spec json file. That's why we handle the
470       // 'normal' output separately.
471       LFS.push_back({Output, None});
472       auto I = LogMap.insert(std::make_pair(
473           MF.getFunction().getName(),
474           std::make_unique<Logger>(LFS, Reward, /*IncludeReward*/ true)));
475       assert(I.second);
476       Log = I.first->second.get();
477     }
478     return std::make_unique<DevelopmentModeEvictAdvisor>(
479         MF, RA, Runner.get(), getAnalysis<MachineBlockFrequencyInfo>(),
480         getAnalysis<MachineLoopInfo>(), Log);
481   }
482 
483   std::unique_ptr<MLModelRunner> Runner;
484   StringMap<std::unique_ptr<Logger>> LogMap;
485 };
486 #endif //#ifdef LLVM_HAVE_TF_API
487 } // namespace
488 
489 float MLEvictAdvisor::getInitialQueueSize(const MachineFunction &MF) {
490   auto &MRI = MF.getRegInfo();
491   float Ret = 0.0;
492   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
493     Register Reg = Register::index2VirtReg(I);
494     if (MRI.reg_nodbg_empty(Reg))
495       continue;
496     ++Ret;
497   }
498   return Ret;
499 }
500 
501 MLEvictAdvisor::MLEvictAdvisor(MachineFunction &MF, const RAGreedy &RA,
502                                MLModelRunner *Runner,
503                                const MachineBlockFrequencyInfo &MBFI,
504                                const MachineLoopInfo &Loops)
505     : RegAllocEvictionAdvisor(MF, RA), DefaultAdvisor(MF, RA),
506       Runner(std::move(Runner)), MBFI(MBFI), Loops(Loops),
507       InitialQSize(MLEvictAdvisor::getInitialQueueSize(MF)) {
508   assert(this->Runner);
509   DoNotNormalize.set(FeatureIDs::mask);
510   DoNotNormalize.set(FeatureIDs::is_free);
511   DoNotNormalize.set(FeatureIDs::is_hint);
512   DoNotNormalize.set(FeatureIDs::is_local);
513   DoNotNormalize.set(FeatureIDs::min_stage);
514   DoNotNormalize.set(FeatureIDs::max_stage);
515   DoNotNormalize.set(FeatureIDs::progress);
516 }
517 
518 int64_t MLEvictAdvisor::tryFindEvictionCandidatePosition(
519     LiveInterval &, const AllocationOrder &, unsigned, uint8_t,
520     const SmallVirtRegSet &) const {
521   int64_t Ret = Runner->evaluate<int64_t>();
522   assert(Ret >= 0);
523   assert(Ret <= CandidateVirtRegPos);
524   return Ret;
525 }
526 
527 bool MLEvictAdvisor::loadInterferenceFeatures(
528     LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint,
529     const SmallVirtRegSet &FixedRegisters, FeaturesListNormalizer &Largest,
530     size_t Pos) const {
531   // It is only possible to evict virtual register interference.
532   if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg) {
533     // leave unavailable
534     return false;
535   }
536 
537   const bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
538   int64_t LocalIntfs = 0;
539   float NrUrgent = 0.0f;
540 
541   // The cascade tracking is the same as in the default advisor
542   unsigned Cascade = RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.reg());
543 
544   SmallVector<LiveInterval *, MaxInterferences> InterferingIntervals;
545   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
546     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
547     // Different from the default heuristic, we don't make any assumptions about
548     // what having more than 10 results in the query may mean.
549     const auto &IFIntervals = Q.interferingVRegs(EvictInterferenceCutoff);
550     if (IFIntervals.empty() && InterferingIntervals.empty())
551       continue;
552     if (IFIntervals.size() >= EvictInterferenceCutoff)
553       return false;
554     InterferingIntervals.append(IFIntervals.begin(), IFIntervals.end());
555     for (LiveInterval *Intf : reverse(IFIntervals)) {
556       assert(Register::isVirtualRegister(Intf->reg()) &&
557              "Only expecting virtual register interference from query");
558       // This is the same set of legality checks as in the default case: don't
559       // try to evict fixed regs or 'done' ones. Also don't break cascades,
560       // except in the urgent case, with the same nuances used in the default
561       // heuristic.
562       // We could try sharing this between the advisors, but it may end up
563       // more complex than it is right now.
564       if (FixedRegisters.count(Intf->reg()))
565         return false;
566       if (RA.getExtraInfo().getStage(*Intf) == RS_Done)
567         return false;
568       bool Urgent =
569           !VirtReg.isSpillable() &&
570           (Intf->isSpillable() ||
571            RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg())) <
572                RegClassInfo.getNumAllocatableRegs(
573                    MRI->getRegClass(Intf->reg())));
574       // Only evict older cascades or live ranges without a cascade.
575       unsigned IntfCascade = RA.getExtraInfo().getCascade(Intf->reg());
576       if (Cascade <= IntfCascade) {
577         if (!Urgent)
578           return false;
579         ++NrUrgent;
580       }
581 
582       LocalIntfs += (IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
583                      (!EnableLocalReassign || !canReassign(*Intf, PhysReg)));
584     }
585   }
586   // OK, so if we made it this far, this LR is an eviction candidate, load its
587   // features.
588   extractFeatures(InterferingIntervals, Largest, Pos, IsHint, LocalIntfs,
589                   NrUrgent);
590   return true;
591 }
592 
593 MCRegister MLEvictAdvisor::tryFindEvictionCandidate(
594     LiveInterval &VirtReg, const AllocationOrder &Order,
595     uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
596   auto MaybeOrderLimit = getOrderLimit(VirtReg, Order, CostPerUseLimit);
597   if (!MaybeOrderLimit)
598     return MCRegister::NoRegister;
599   unsigned OrderLimit = *MaybeOrderLimit;
600 
601   // The heuristic sets initial costs such as, if CostPerUseLimit is
602   // max<uint8_t>, then any of the costs of the legally-evictable intervals
603   // would be lower. When that happens, one of those will be selected.
604   // Therefore, we allow the candidate be selected, unless the candidate is
605   // unspillable, in which case it would be incorrect to not find a register for
606   // it.
607   const bool MustFindEviction =
608       (!VirtReg.isSpillable() && CostPerUseLimit == static_cast<uint8_t>(~0u));
609   // Number of available candidates - if 0, no need to continue.
610   size_t Available = 0;
611   // Make sure we don't have leftover partial state from an attempt where we had
612   // no available candidates and bailed out early.
613   resetInputs(*Runner);
614 
615   // Track the index->register mapping because AllocationOrder doesn't do that
616   // and we'd have to scan it.
617   // Also track their mask, to write asserts/debug.
618   CandidateRegList Regs;
619   Regs.fill({0, false});
620 
621   // Track the largest value of features seen during this eviction session. We
622   // only normalize (some of) the float features, but it's just simpler to
623   // dimension 'Largest' to all the features, especially since we have the
624   // 'DoNotNormalize' list.
625   FeaturesListNormalizer Largest;
626   Largest.fill(0.0);
627 
628   // Same overal idea as in the default eviction policy - we visit the values of
629   // AllocationOrder one at a time. If it's not legally available, we mask off
630   // the corresponding feature column (==do nothing because we already reset all
631   // the features to 0)
632   // Use Pos to capture the column we load features at - in AllocationOrder
633   // order.
634   size_t Pos = 0;
635   for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit); I != E;
636        ++I, ++Pos) {
637     MCRegister PhysReg = *I;
638     assert(!Regs[Pos].second);
639     assert(PhysReg);
640     if (!canAllocatePhysReg(CostPerUseLimit, PhysReg)) {
641       continue;
642     }
643     if (loadInterferenceFeatures(VirtReg, PhysReg, I.isHint(), FixedRegisters,
644                                  Largest, Pos)) {
645       ++Available;
646       Regs[Pos] = std::make_pair(PhysReg, true);
647     }
648   }
649   if (Available == 0) {
650     // Nothing to decide, nothing to learn.
651     assert(!MustFindEviction);
652     return MCRegister::NoRegister;
653   }
654   const size_t ValidPosLimit = Pos;
655   // If we must find eviction, the candidate should be masked out of the
656   // decision making process.
657   Regs[CandidateVirtRegPos].second = !MustFindEviction;
658   if (!MustFindEviction)
659     extractFeatures(SmallVector<LiveInterval *, 1>(1, &VirtReg), Largest,
660                     CandidateVirtRegPos, /*IsHint*/ 0, /*LocalIntfsCount*/ 0,
661                     /*NrUrgent*/ 0.0);
662   assert(InitialQSize > 0.0 && "We couldn't have gotten here if we had "
663                                "nothing to allocate initially.");
664   // Normalize the features.
665   for (auto &V : Largest)
666     V = V ? V : 1.0;
667   for (size_t FeatureIndex = 0; FeatureIndex < FeatureIDs::FeatureCount;
668        ++FeatureIndex) {
669     if (DoNotNormalize.test(FeatureIndex))
670       continue;
671     for (size_t Pos = 0; Pos < NumberOfInterferences; ++Pos) {
672       Runner->getTensor<float>(FeatureIndex)[Pos] /= Largest[FeatureIndex];
673     }
674   }
675   *Runner->getTensor<float>(FeatureIDs::progress) =
676       static_cast<float>(RA.getQueueSize()) / InitialQSize;
677 
678   // Get a decision.
679   size_t CandidatePos = tryFindEvictionCandidatePosition(
680       VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
681   // The contract with the ML side is that CandidatePos is mask == 1 (i.e.
682   // Regs[CandidatePos].second)
683   assert(Regs[CandidatePos].second);
684   if (CandidatePos == CandidateVirtRegPos) {
685     assert(!MustFindEviction);
686     return MCRegister::NoRegister;
687   }
688   assert(CandidatePos < ValidPosLimit);
689   (void)ValidPosLimit;
690   return Regs[CandidatePos].first;
691 }
692 
693 const LIFeatureComponents
694 MLEvictAdvisor::getLIFeatureComponents(const LiveInterval &LI) const {
695   LIFeatureComponents Ret;
696   SmallPtrSet<MachineInstr *, 8> Visited;
697   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
698 
699   for (MachineRegisterInfo::reg_instr_nodbg_iterator
700            I = MRI->reg_instr_nodbg_begin(LI.reg()),
701            E = MRI->reg_instr_nodbg_end();
702        I != E;) {
703     MachineInstr *MI = &*(I++);
704 
705     ++Ret.NrDefsAndUses;
706     if (!Visited.insert(MI).second)
707       continue;
708 
709     if (MI->isIdentityCopy() || MI->isImplicitDef())
710       continue;
711 
712     bool Reads, Writes;
713     std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
714 
715     float Freq = MBFI.getBlockFreqRelativeToEntryBlock(MI->getParent());
716     Ret.HottestBlockFreq = std::max(Freq, Ret.HottestBlockFreq);
717 
718     Ret.R += (Reads && !Writes) * Freq;
719     Ret.W += (!Reads && Writes) * Freq;
720     Ret.RW += (Reads && Writes) * Freq;
721 
722     auto *MBB = MI->getParent();
723     auto *Loop = Loops.getLoopFor(MBB);
724     bool IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
725 
726     if (Writes && IsExiting && LIS->isLiveOutOfMBB(LI, MBB))
727       Ret.IndVarUpdates += Freq;
728 
729     if (MI->isCopy() && VirtRegAuxInfo::copyHint(MI, LI.reg(), TRI, *MRI))
730       Ret.HintWeights += Freq;
731   }
732   Ret.IsRemat = VirtRegAuxInfo::isRematerializable(
733       LI, *LIS, *VRM, *MF.getSubtarget().getInstrInfo());
734   return Ret;
735 }
736 
737 // Overall, this currently mimics what we do for weight calculation, but instead
738 // of accummulating the various features, we keep them separate.
739 void MLEvictAdvisor::extractFeatures(
740     const SmallVectorImpl<LiveInterval *> &Intervals,
741     std::array<float, FeatureIDs::FeatureCount> &Largest, size_t Pos,
742     int64_t IsHint, int64_t LocalIntfsCount, float NrUrgent) const {
743   int64_t NrDefsAndUses = 0;
744   int64_t NrBrokenHints = 0;
745   double R = 0.0;
746   double W = 0.0;
747   double RW = 0.0;
748   double IndVarUpdates = 0.0;
749   double HintWeights = 0.0;
750   float StartBBFreq = 0.0;
751   float EndBBFreq = 0.0;
752   float HottestBlockFreq = 0.0;
753   int32_t NrRematerializable = 0;
754   float TotalWeight = 0.0;
755 
756   SlotIndex EndSI = LIS->getSlotIndexes()->getZeroIndex();
757   SlotIndex StartSI = LIS->getSlotIndexes()->getLastIndex();
758   int64_t MaxStage = 0;
759   int64_t MinStage =
760       Intervals.empty() ? 0 : std::numeric_limits<int64_t>::max();
761 
762   for (const auto *L : Intervals) {
763     const LiveInterval &LI = *L;
764     MaxStage = std::max<int64_t>(
765         MaxStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
766     MinStage = std::min<int64_t>(
767         MinStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
768 
769     TotalWeight = std::max(TotalWeight, LI.weight());
770 
771     if (LI.beginIndex() < StartSI)
772       StartSI = LI.beginIndex();
773 
774     if (LI.endIndex() > EndSI)
775       EndSI = LI.endIndex();
776     const LIFeatureComponents LIFC = getLIFeatureComponents(LI);
777     NrBrokenHints += VRM->hasPreferredPhys(LI.reg());
778 
779     NrDefsAndUses += LIFC.NrDefsAndUses;
780     HottestBlockFreq = std::max(HottestBlockFreq, LIFC.HottestBlockFreq);
781     R += LIFC.R;
782     W += LIFC.W;
783     RW += LIFC.RW;
784 
785     IndVarUpdates += LIFC.IndVarUpdates;
786 
787     HintWeights += LIFC.HintWeights;
788     NrRematerializable += LIFC.IsRemat;
789   }
790   size_t Size = 0;
791   if (!Intervals.empty()) {
792     StartBBFreq =
793         MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(StartSI));
794     if (EndSI >= LIS->getSlotIndexes()->getLastIndex())
795       EndSI = LIS->getSlotIndexes()->getLastIndex().getPrevIndex();
796     EndBBFreq =
797         MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(EndSI));
798     Size = StartSI.distance(EndSI);
799   }
800   // Set the features at the column 'Pos'.
801 #define SET(ID, TYPE, VAL)                                                     \
802   do {                                                                         \
803     Runner->getTensor<TYPE>(FeatureIDs::ID)[Pos] = static_cast<TYPE>(VAL);     \
804     if (!DoNotNormalize.test(FeatureIDs::ID))                                  \
805       Largest[FeatureIDs::ID] =                                                \
806           std::max(Largest[FeatureIDs::ID], static_cast<float>(VAL));          \
807   } while (false)
808   SET(mask, int64_t, 1);
809   SET(is_free, int64_t, Intervals.empty());
810   SET(nr_urgent, float, NrUrgent);
811   SET(nr_broken_hints, float, NrBrokenHints);
812   SET(is_hint, int64_t, IsHint);
813   SET(is_local, int64_t, LocalIntfsCount);
814   SET(nr_rematerializable, float, NrRematerializable);
815   SET(nr_defs_and_uses, float, NrDefsAndUses);
816   SET(weighed_reads_by_max, float, R);
817   SET(weighed_writes_by_max, float, W);
818   SET(weighed_read_writes_by_max, float, RW);
819   SET(weighed_indvars_by_max, float, IndVarUpdates);
820   SET(hint_weights_by_max, float, HintWeights);
821   SET(start_bb_freq_by_max, float, StartBBFreq);
822   SET(end_bb_freq_by_max, float, EndBBFreq);
823   SET(hottest_bb_freq_by_max, float, HottestBlockFreq);
824   SET(liverange_size, float, Size);
825   SET(use_def_density, float, TotalWeight);
826   SET(max_stage, int64_t, MaxStage);
827   SET(min_stage, int64_t, MinStage);
828 #undef SET
829 }
830 
831 // Development mode-specific implementations
832 #ifdef LLVM_HAVE_TF_API
833 RegAllocEvictionAdvisorAnalysis *llvm::createDevelopmentModeAdvisor() {
834   return new DevelopmentModeEvictionAdvisorAnalysis();
835 }
836 
837 int64_t DevelopmentModeEvictAdvisor::tryFindEvictionCandidatePosition(
838     LiveInterval &VirtReg, const AllocationOrder &Order, unsigned OrderLimit,
839     uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
840   int64_t Ret = 0;
841   if (isa<ModelUnderTrainingRunner>(getRunner())) {
842     Ret = MLEvictAdvisor::tryFindEvictionCandidatePosition(
843         VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
844   } else {
845     MCRegister PhysReg = getDefaultAdvisor().tryFindEvictionCandidate(
846         VirtReg, Order, CostPerUseLimit, FixedRegisters);
847     // Find the index of the selected PhysReg. We need it for logging, otherwise
848     // this is wasted cycles (but so would starting development mode without a
849     // model nor logging)
850     if (!PhysReg)
851       Ret = CandidateVirtRegPos;
852     else
853       for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit);
854            I != E; ++I, ++Ret)
855         if (*I == PhysReg)
856           break;
857   }
858   if (TrainingLog.empty())
859     return Ret;
860   size_t CurrentFeature = 0;
861   for (; CurrentFeature < FeatureIDs::FeatureCount; ++CurrentFeature) {
862     Log->logSpecifiedTensorValue(
863         CurrentFeature, reinterpret_cast<const char *>(
864                             getRunner().getTensorUntyped(CurrentFeature)));
865   }
866   if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(&getRunner()))
867     for (size_t I = 1; I < MUTR->outputLoggedFeatureSpecs().size();
868          ++I, ++CurrentFeature)
869       Log->logSpecifiedTensorValue(
870           CurrentFeature,
871           reinterpret_cast<const char *>(
872               MUTR->lastEvaluationResult()->getUntypedTensorValue(I)));
873   // The output is right after the features and the extra outputs
874   Log->logInt64Value(CurrentFeature, &Ret);
875   return Ret;
876 }
877 
878 bool RegAllocScoring::runOnMachineFunction(MachineFunction &MF) {
879   if (auto *DevModeAnalysis = dyn_cast<DevelopmentModeEvictionAdvisorAnalysis>(
880           &getAnalysis<RegAllocEvictionAdvisorAnalysis>()))
881     if (auto *Log = DevModeAnalysis->getLogger(MF))
882       Log->logFloatFinalReward(static_cast<float>(
883           calculateRegAllocScore(
884               MF, getAnalysis<MachineBlockFrequencyInfo>(),
885               getAnalysis<AAResultsWrapperPass>().getAAResults())
886               .getScore()));
887 
888   return false;
889 }
890 #endif // #ifdef LLVM_HAVE_TF_API
891 
892 #if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL)
893 RegAllocEvictionAdvisorAnalysis *llvm::createReleaseModeAdvisor() {
894   return new ReleaseModeEvictionAdvisorAnalysis();
895 }
896 #endif
897 
898 // In all cases except development mode, we don't need scoring.
899 #if !defined(LLVM_HAVE_TF_API)
900 bool RegAllocScoring::runOnMachineFunction(MachineFunction &) { return false; }
901 #endif
902