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