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
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 /// 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 *llvm::createRegAllocScoringPass() {
96   return new RegAllocScoring();
97 }
98 
99 INITIALIZE_PASS(RegAllocScoring, "regallocscoringpass",
100                 "Register Allocation Scoring Pass", false, false)
101 } // namespace llvm
102 
103 // ===================================
104 // Common ML Advisor declarations
105 // ===================================
106 #if defined(LLVM_HAVE_TF_AOT) || defined(LLVM_HAVE_TF_API)
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 const char *const 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 using CandidateRegList =
224     std::array<std::pair<MCRegister, bool>, NumberOfInterferences>;
225 using FeaturesListNormalizer = std::array<float, FeatureIDs::FeatureCount>;
226 
227 /// The ML evictor (commonalities between release and development mode)
228 class MLEvictAdvisor : public RegAllocEvictionAdvisor {
229 public:
230   MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
231                  MLModelRunner *Runner, const MachineBlockFrequencyInfo &MBFI,
232                  const MachineLoopInfo &Loops);
233 
234 protected:
235   const RegAllocEvictionAdvisor &getDefaultAdvisor() const {
236     return static_cast<const RegAllocEvictionAdvisor &>(DefaultAdvisor);
237   }
238 
239   // The assumption is that if the Runner could not be constructed, we emit-ed
240   // error, and we shouldn't be asking for it here.
241   const MLModelRunner &getRunner() const { return *Runner; }
242 
243   /// This just calls Evaluate on the Runner, but in the development mode case,
244   /// if we're just capturing the log of the default advisor, it needs to call
245   /// the latter instead, so we need to pass all the necessary parameters for
246   /// it. In the development case, it will also log.
247   virtual int64_t tryFindEvictionCandidatePosition(
248       LiveInterval &VirtReg, const AllocationOrder &Order, unsigned OrderLimit,
249       uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const;
250 
251   /// Load the features of the given VirtReg (allocated or not) at column Pos,
252   /// but if  that can't be evicted, return false instead.
253   bool
254   loadInterferenceFeatures(LiveInterval &VirtReg, MCRegister PhysReg,
255                            bool IsHint, const SmallVirtRegSet &FixedRegisters,
256                            std::array<float, FeatureIDs::FeatureCount> &Largest,
257                            size_t Pos) const;
258 
259 private:
260   static float getInitialQueueSize(const MachineFunction &MF);
261 
262   MCRegister tryFindEvictionCandidate(
263       LiveInterval &VirtReg, const AllocationOrder &Order,
264       uint8_t CostPerUseLimit,
265       const SmallVirtRegSet &FixedRegisters) const override;
266 
267   void extractFeatures(const SmallVectorImpl<LiveInterval *> &Intervals,
268                        std::array<float, FeatureIDs::FeatureCount> &Largest,
269                        size_t Pos, int64_t IsHint, int64_t LocalIntfsCount,
270                        float NrUrgent) const;
271 
272   // Point-in-time: we didn't learn this, so we always delegate to the default.
273   bool canEvictHintInterference(
274       LiveInterval &VirtReg, MCRegister PhysReg,
275       const SmallVirtRegSet &FixedRegisters) const override {
276     return getDefaultAdvisor().canEvictHintInterference(VirtReg, PhysReg,
277                                                         FixedRegisters);
278   }
279 
280   // Hold on to a default advisor for:
281   // 1) the implementation of canEvictHintInterference, because we didn't learn
282   // that nuance yet;
283   // 2) for bootstrapping (logging) in the development mode case.
284   const DefaultEvictionAdvisor DefaultAdvisor;
285   MLModelRunner *const Runner;
286   const MachineBlockFrequencyInfo &MBFI;
287   const MachineLoopInfo &Loops;
288 
289   // Indices of those features we don't want to normalize.
290   // This could be static and shared, but its initialization is non-trivial.
291   std::bitset<FeatureIDs::FeatureCount> DoNotNormalize;
292   const float InitialQSize;
293 };
294 
295 // ===================================
296 // Release (AOT) - specifics
297 // ===================================
298 #ifdef LLVM_HAVE_TF_AOT
299 const std::array<std::string, FeatureIDs::FeatureCount> FeatureNames{
300 #define _GETNAME(_, NAME, __, ___) #NAME,
301     RA_EVICT_FEATURES_LIST(_GETNAME)
302 #undef _GETNAME
303 };
304 
305 class ReleaseModeEvictionAdvisorAnalysis final
306     : public RegAllocEvictionAdvisorAnalysis {
307 public:
308   ReleaseModeEvictionAdvisorAnalysis()
309       : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Release) {}
310   // support for isa<> and dyn_cast.
311   static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
312     return R->getAdvisorMode() == AdvisorMode::Release;
313   }
314 
315 private:
316   void getAnalysisUsage(AnalysisUsage &AU) const override {
317     AU.addRequired<MachineBlockFrequencyInfo>();
318     AU.addRequired<MachineLoopInfo>();
319     RegAllocEvictionAdvisorAnalysis::getAnalysisUsage(AU);
320   }
321 
322   std::unique_ptr<RegAllocEvictionAdvisor>
323   getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
324     if (!Runner)
325       Runner = std::make_unique<ReleaseModeModelRunner<RegallocEvictModel>>(
326           MF.getFunction().getContext(), FeatureNames, DecisionName);
327     return std::make_unique<MLEvictAdvisor>(
328         MF, RA, Runner.get(), getAnalysis<MachineBlockFrequencyInfo>(),
329         getAnalysis<MachineLoopInfo>());
330   }
331   std::unique_ptr<ReleaseModeModelRunner<RegallocEvictModel>> Runner;
332 };
333 #endif // LLVM_HAVE_TF_AOT
334 
335 // ===================================
336 // Development mode-specifics
337 // ===================================
338 //
339 // Features we log
340 #ifdef LLVM_HAVE_TF_API
341 #define _DECL_FEATURES(type, name, shape, _)                                   \
342   TensorSpec::createSpec<type>(#name, shape),
343 
344 static const std::vector<TensorSpec> InputFeatures{
345     {RA_EVICT_FEATURES_LIST(_DECL_FEATURES)},
346 };
347 #undef _DECL_FEATURES
348 static const TensorSpec Output =
349     TensorSpec::createSpec<int64_t>(DecisionName, {1});
350 static const TensorSpec Reward = TensorSpec::createSpec<float>("reward", {1});
351 
352 // Features we bind on the model. The tensor names have a prefix, and we also
353 // need to include some tensors that are expected to be present by the training
354 // algo.
355 // TODO: can we just get rid of these?
356 #define _DECL_TRAIN_FEATURES(type, name, shape, _)                             \
357   TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
358 
359 static const std::vector<TensorSpec> TrainingInputFeatures{
360     {RA_EVICT_FEATURES_LIST(_DECL_TRAIN_FEATURES)
361          TensorSpec::createSpec<float>("action_discount", {1}),
362      TensorSpec::createSpec<int32_t>("action_step_type", {1}),
363      TensorSpec::createSpec<float>("action_reward", {1})}};
364 #undef _DECL_TRAIN_FEATURES
365 
366 class DevelopmentModeEvictAdvisor : public MLEvictAdvisor {
367 public:
368   DevelopmentModeEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
369                               MLModelRunner *Runner,
370                               const MachineBlockFrequencyInfo &MBFI,
371                               const MachineLoopInfo &Loops, Logger *Log)
372       : MLEvictAdvisor(MF, RA, Runner, MBFI, Loops), Log(Log) {}
373 
374 private:
375   int64_t tryFindEvictionCandidatePosition(
376       LiveInterval &VirtReg, const AllocationOrder &Order, unsigned OrderLimit,
377       uint8_t CostPerUseLimit,
378       const SmallVirtRegSet &FixedRegisters) const override;
379 
380   Logger *const Log;
381 };
382 
383 class DevelopmentModeEvictionAdvisorAnalysis final
384     : public RegAllocEvictionAdvisorAnalysis {
385 public:
386   DevelopmentModeEvictionAdvisorAnalysis()
387       : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Development) {}
388   // support for isa<> and dyn_cast.
389   static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
390     return R->getAdvisorMode() == AdvisorMode::Development;
391   }
392 
393   /// get the logger for the given function, or nullptr if we didn't collect
394   /// one. This is used to inject the score by the RegAllocScoring pass.
395   Logger *getLogger(const MachineFunction &MF) const {
396     auto I = LogMap.find(MF.getName());
397     if (I == LogMap.end())
398       return nullptr;
399     return I->second.get();
400   }
401 
402 private:
403   void getAnalysisUsage(AnalysisUsage &AU) const override {
404     AU.addRequired<MachineBlockFrequencyInfo>();
405     AU.addRequired<MachineLoopInfo>();
406     RegAllocEvictionAdvisorAnalysis::getAnalysisUsage(AU);
407   }
408 
409   // Save all the logs (when requested).
410   bool doFinalization(Module &M) override {
411     if (TrainingLog.empty())
412       return false;
413     std::error_code EC;
414     auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
415     if (EC) {
416       M.getContext().emitError(EC.message() + ":" + TrainingLog);
417       return false;
418     }
419     Logger::flushLogs(*OS, LogMap);
420     return false;
421   }
422 
423   std::unique_ptr<RegAllocEvictionAdvisor>
424   getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
425     LLVMContext &Ctx = MF.getFunction().getContext();
426     if (ModelUnderTraining.empty() && TrainingLog.empty()) {
427       Ctx.emitError("Regalloc development mode should be requested with at "
428                     "least logging enabled and/or a training model");
429       return nullptr;
430     }
431     if (!Runner) {
432       if (ModelUnderTraining.empty())
433         Runner = std::make_unique<NoInferenceModelRunner>(Ctx, InputFeatures);
434       else
435         Runner = ModelUnderTrainingRunner::createAndEnsureValid(
436             Ctx, ModelUnderTraining, DecisionName, TrainingInputFeatures);
437       if (!Runner) {
438         Ctx.emitError("Regalloc: could not set up the model runner");
439         return nullptr;
440       }
441     }
442 
443     Logger *Log = nullptr;
444     if (!TrainingLog.empty()) {
445       std::vector<LoggedFeatureSpec> LFS;
446       for (const auto &FS : InputFeatures)
447         LFS.push_back({FS, None});
448       if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(Runner.get()))
449         if (MUTR->outputLoggedFeatureSpecs().size() > 1)
450           append_range(LFS, drop_begin(MUTR->outputLoggedFeatureSpecs()));
451       // We always log the output; in particular, if we're not evaluating, we
452       // don't have an output spec json file. That's why we handle the
453       // 'normal' output separately.
454       LFS.push_back({Output, None});
455       auto I = LogMap.insert(std::make_pair(
456           MF.getFunction().getName(),
457           std::make_unique<Logger>(LFS, Reward, /*IncludeReward*/ true)));
458       assert(I.second);
459       Log = I.first->second.get();
460     }
461     return std::make_unique<DevelopmentModeEvictAdvisor>(
462         MF, RA, Runner.get(), getAnalysis<MachineBlockFrequencyInfo>(),
463         getAnalysis<MachineLoopInfo>(), Log);
464   }
465 
466   std::unique_ptr<MLModelRunner> Runner;
467   StringMap<std::unique_ptr<Logger>> LogMap;
468 };
469 #endif //#ifdef LLVM_HAVE_TF_API
470 } // namespace
471 
472 float MLEvictAdvisor::getInitialQueueSize(const MachineFunction &MF) {
473   auto &MRI = MF.getRegInfo();
474   float Ret = 0.0;
475   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
476     Register Reg = Register::index2VirtReg(I);
477     if (MRI.reg_nodbg_empty(Reg))
478       continue;
479     ++Ret;
480   }
481   return Ret;
482 }
483 
484 MLEvictAdvisor::MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
485                                MLModelRunner *Runner,
486                                const MachineBlockFrequencyInfo &MBFI,
487                                const MachineLoopInfo &Loops)
488     : RegAllocEvictionAdvisor(MF, RA), DefaultAdvisor(MF, RA),
489       Runner(std::move(Runner)), MBFI(MBFI), Loops(Loops),
490       InitialQSize(MLEvictAdvisor::getInitialQueueSize(MF)) {
491   assert(this->Runner);
492   DoNotNormalize.set(FeatureIDs::mask);
493   DoNotNormalize.set(FeatureIDs::is_free);
494   DoNotNormalize.set(FeatureIDs::is_hint);
495   DoNotNormalize.set(FeatureIDs::is_local);
496   DoNotNormalize.set(FeatureIDs::min_stage);
497   DoNotNormalize.set(FeatureIDs::max_stage);
498   DoNotNormalize.set(FeatureIDs::progress);
499 }
500 
501 int64_t MLEvictAdvisor::tryFindEvictionCandidatePosition(
502     LiveInterval &, const AllocationOrder &, unsigned, uint8_t,
503     const SmallVirtRegSet &) const {
504   int64_t Ret = Runner->evaluate<int64_t>();
505   assert(Ret >= 0);
506   assert(Ret <= CandidateVirtRegPos);
507   return Ret;
508 }
509 
510 bool MLEvictAdvisor::loadInterferenceFeatures(
511     LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint,
512     const SmallVirtRegSet &FixedRegisters, FeaturesListNormalizer &Largest,
513     size_t Pos) const {
514   // It is only possible to evict virtual register interference.
515   if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg) {
516     // leave unavailable
517     return false;
518   }
519 
520   const bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
521   int64_t LocalIntfs = 0;
522   float NrUrgent = 0.0f;
523 
524   // The cascade tracking is the same as in the default advisor
525   unsigned Cascade = RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.reg());
526 
527   SmallVector<LiveInterval *, MaxInterferences> InterferingIntervals;
528   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
529     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
530     // Different from the default heuristic, we don't make any assumptions about
531     // what having more than 10 results in the query may mean.
532     const auto &IFIntervals = Q.interferingVRegs();
533     if (IFIntervals.empty() && InterferingIntervals.empty())
534       continue;
535     InterferingIntervals.append(IFIntervals.begin(), IFIntervals.end());
536     for (LiveInterval *Intf : reverse(IFIntervals)) {
537       assert(Register::isVirtualRegister(Intf->reg()) &&
538              "Only expecting virtual register interference from query");
539       // This is the same set of legality checks as in the default case: don't
540       // try to evict fixed regs or 'done' ones. Also don't break cascades,
541       // except in the urgent case, with the same nuances used in the default
542       // heuristic.
543       // We could try sharing this between the advisors, but it may end up
544       // more complex than it is right now.
545       if (FixedRegisters.count(Intf->reg()))
546         return false;
547       if (RA.getExtraInfo().getStage(*Intf) == RS_Done)
548         return false;
549       bool Urgent =
550           !VirtReg.isSpillable() &&
551           (Intf->isSpillable() ||
552            RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg())) <
553                RegClassInfo.getNumAllocatableRegs(
554                    MRI->getRegClass(Intf->reg())));
555       // Only evict older cascades or live ranges without a cascade.
556       unsigned IntfCascade = RA.getExtraInfo().getCascade(Intf->reg());
557       if (Cascade <= IntfCascade) {
558         if (!Urgent)
559           return false;
560         ++NrUrgent;
561       }
562 
563       LocalIntfs += (IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
564                      (!EnableLocalReassign || !canReassign(*Intf, PhysReg)));
565     }
566   }
567   // OK, so if we made it this far, this LR is an eviction candidate, load its
568   // features.
569   extractFeatures(InterferingIntervals, Largest, Pos, IsHint, LocalIntfs,
570                   NrUrgent);
571   return true;
572 }
573 
574 MCRegister MLEvictAdvisor::tryFindEvictionCandidate(
575     LiveInterval &VirtReg, const AllocationOrder &Order,
576     uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
577   auto MaybeOrderLimit = getOrderLimit(VirtReg, Order, CostPerUseLimit);
578   if (!MaybeOrderLimit)
579     return MCRegister::NoRegister;
580   unsigned OrderLimit = *MaybeOrderLimit;
581 
582   // The heuristic sets initial costs such as, if CostPerUseLimit is
583   // max<uint8_t>, then any of the costs of the legally-evictable intervals
584   // would be lower. When that happens, one of those will be selected.
585   // Therefore, we allow the candidate be selected, unless the candidate is
586   // unspillable, in which case it would be incorrect to not find a register for
587   // it.
588   const bool MustFindEviction =
589       (!VirtReg.isSpillable() && CostPerUseLimit == static_cast<uint8_t>(~0u));
590   // Number of available candidates - if 0, no need to continue.
591   size_t Available = 0;
592   // Make sure we don't have leftover partial state from an attempt where we had
593   // no available candidates and bailed out early.
594   resetInputs(*Runner);
595 
596   // Track the index->register mapping because AllocationOrder doesn't do that
597   // and we'd have to scan it.
598   // Also track their mask, to write asserts/debug.
599   CandidateRegList Regs;
600   Regs.fill({0, false});
601 
602   // Track the largest value of features seen during this eviction session. We
603   // only normalize (some of) the float features, but it's just simpler to
604   // dimension 'Largest' to all the features, especially since we have the
605   // 'DoNotNormalize' list.
606   FeaturesListNormalizer Largest;
607   Largest.fill(0.0);
608 
609   // Same overal idea as in the default eviction policy - we visit the values of
610   // AllocationOrder one at a time. If it's not legally available, we mask off
611   // the corresponding feature column (==do nothing because we already reset all
612   // the features to 0)
613   // Use Pos to capture the column we load features at - in AllocationOrder
614   // order.
615   size_t Pos = 0;
616   for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit); I != E;
617        ++I, ++Pos) {
618     MCRegister PhysReg = *I;
619     Regs[Pos] = std::make_pair(PhysReg, true);
620     assert(PhysReg);
621     if (!canAllocatePhysReg(CostPerUseLimit, PhysReg)) {
622       Regs[Pos].second = false;
623       continue;
624     }
625     if (loadInterferenceFeatures(VirtReg, PhysReg, I.isHint(), FixedRegisters,
626                                  Largest, Pos)) {
627       ++Available;
628       Regs[Pos].second = true;
629     }
630   }
631   if (Available == 0) {
632     // Nothing to decide, nothing to learn.
633     assert(!MustFindEviction);
634     return MCRegister::NoRegister;
635   }
636   // If we must find eviction, the candidate should be masked out of the
637   // decision making process.
638   Regs[CandidateVirtRegPos].second = !MustFindEviction;
639   if (!MustFindEviction)
640     extractFeatures(SmallVector<LiveInterval *, 1>(1, &VirtReg), Largest,
641                     CandidateVirtRegPos, /*IsHint*/ 0, /*LocalIntfsCount*/ 0,
642                     /*NrUrgent*/ 0.0);
643   assert(InitialQSize > 0.0 && "We couldn't have gotten here if we had "
644                                "nothing to allocate initially.");
645   // Normalize the features.
646   for (auto &V : Largest)
647     V = V ? V : 1.0;
648   for (size_t FeatureIndex = 0; FeatureIndex < FeatureIDs::FeatureCount;
649        ++FeatureIndex) {
650     if (DoNotNormalize.test(FeatureIndex))
651       continue;
652     for (size_t Pos = 0; Pos < NumberOfInterferences; ++Pos) {
653       Runner->getTensor<float>(FeatureIndex)[Pos] /= Largest[FeatureIndex];
654     }
655   }
656   *Runner->getTensor<float>(FeatureIDs::progress) =
657       static_cast<float>(RA.getQueueSize()) / InitialQSize;
658 
659   // Get a decision.
660   size_t CandidatePos = tryFindEvictionCandidatePosition(
661       VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
662   // The contract with the ML side is that CandidatePos is mask == 1 (i.e.
663   // Regs[CandidatePos].second)
664   assert(Regs[CandidatePos].second);
665   if (CandidatePos == CandidateVirtRegPos) {
666     assert(!MustFindEviction);
667     return MCRegister::NoRegister;
668   }
669   return Regs[CandidatePos].first;
670 }
671 
672 // Overall, this currently mimics what we do for weight calculation, but instead
673 // of accummulating the various features, we keep them separate.
674 void MLEvictAdvisor::extractFeatures(
675     const SmallVectorImpl<LiveInterval *> &Intervals,
676     std::array<float, FeatureIDs::FeatureCount> &Largest, size_t Pos,
677     int64_t IsHint, int64_t LocalIntfsCount, float NrUrgent) const {
678   int64_t NrDefsAndUses = 0;
679   int64_t NrBrokenHints = 0;
680   float R = 0;
681   float W = 0;
682   float RW = 0;
683   float IndVarUpdates = 0;
684   float HintWeights = 0.0;
685   float StartBBFreq = 0.0;
686   float EndBBFreq = 0.0;
687   float HottestBlockFreq = 0.0;
688   int32_t NrRematerializable = 0;
689   float TotalWeight = 0.0;
690 
691   SlotIndex EndSI = LIS->getSlotIndexes()->getZeroIndex();
692   SlotIndex StartSI = LIS->getSlotIndexes()->getLastIndex();
693   int64_t MaxStage = 0;
694   int64_t MinStage =
695       Intervals.empty() ? 0 : std::numeric_limits<int64_t>::max();
696 
697   for (const auto *L : Intervals) {
698     const LiveInterval &LI = *L;
699     MaxStage = std::max<int64_t>(
700         MaxStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
701     MinStage = std::min<int64_t>(
702         MinStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
703 
704     TotalWeight = std::max(TotalWeight, LI.weight());
705 
706     if (LI.beginIndex() < StartSI)
707       StartSI = LI.beginIndex();
708 
709     if (LI.endIndex() > EndSI)
710       EndSI = LI.endIndex();
711 
712     SmallPtrSet<MachineInstr *, 8> Visited;
713     const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
714     NrBrokenHints += VRM->hasPreferredPhys(LI.reg());
715 
716     for (MachineRegisterInfo::reg_instr_nodbg_iterator
717              I = MRI->reg_instr_nodbg_begin(LI.reg()),
718              E = MRI->reg_instr_nodbg_end();
719          I != E;) {
720       MachineInstr *MI = &*(I++);
721 
722       ++NrDefsAndUses;
723       if (!Visited.insert(MI).second)
724         continue;
725 
726       if (MI->isIdentityCopy() || MI->isImplicitDef())
727         continue;
728 
729       bool Reads, Writes;
730       std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
731 
732       float Freq = MBFI.getBlockFreqRelativeToEntryBlock(MI->getParent());
733       if (Freq > HottestBlockFreq)
734         HottestBlockFreq = Freq;
735       R += (Reads && !Writes) * Freq;
736       W += (!Reads && Writes) * Freq;
737       RW += (Reads && Writes) * Freq;
738 
739       auto *MBB = MI->getParent();
740       auto *Loop = Loops.getLoopFor(MBB);
741       bool IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
742 
743       if (Writes && IsExiting && LIS->isLiveOutOfMBB(LI, MBB))
744         IndVarUpdates += Freq;
745 
746       if (MI->isCopy() && VirtRegAuxInfo::copyHint(MI, LI.reg(), TRI, *MRI))
747         HintWeights += Freq;
748     }
749     NrRematerializable += VirtRegAuxInfo::isRematerializable(
750         LI, *LIS, *VRM, *MF.getSubtarget().getInstrInfo());
751   }
752   size_t Size = 0;
753   if (!Intervals.empty()) {
754     StartBBFreq =
755         MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(StartSI));
756     if (EndSI >= LIS->getSlotIndexes()->getLastIndex())
757       EndSI = LIS->getSlotIndexes()->getLastIndex().getPrevIndex();
758     EndBBFreq =
759         MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(EndSI));
760     Size = StartSI.distance(EndSI);
761   }
762   // Set the features at the column 'Pos'.
763 #define SET(ID, TYPE, VAL)                                                     \
764   do {                                                                         \
765     Runner->getTensor<TYPE>(FeatureIDs::ID)[Pos] = static_cast<TYPE>(VAL);     \
766     if (!DoNotNormalize.test(FeatureIDs::ID))                                  \
767       Largest[FeatureIDs::ID] =                                                \
768           std::max(Largest[FeatureIDs::ID], static_cast<float>(VAL));          \
769   } while (false)
770   SET(mask, int64_t, 1);
771   SET(is_free, int64_t, Intervals.empty());
772   SET(nr_urgent, float, NrUrgent);
773   SET(nr_broken_hints, float, NrBrokenHints);
774   SET(is_hint, int64_t, IsHint);
775   SET(is_local, int64_t, LocalIntfsCount);
776   SET(nr_rematerializable, float, NrRematerializable);
777   SET(nr_defs_and_uses, float, NrDefsAndUses);
778   SET(weighed_reads_by_max, float, R);
779   SET(weighed_writes_by_max, float, W);
780   SET(weighed_read_writes_by_max, float, RW);
781   SET(weighed_indvars_by_max, float, IndVarUpdates);
782   SET(hint_weights_by_max, float, HintWeights);
783   SET(start_bb_freq_by_max, float, StartBBFreq);
784   SET(end_bb_freq_by_max, float, EndBBFreq);
785   SET(hottest_bb_freq_by_max, float, HottestBlockFreq);
786   SET(liverange_size, float, Size);
787   SET(use_def_density, float, TotalWeight);
788   SET(max_stage, int64_t, MaxStage);
789   SET(min_stage, int64_t, MinStage);
790 #undef SET
791 }
792 
793 // Development mode-specific implementations
794 #ifdef LLVM_HAVE_TF_API
795 RegAllocEvictionAdvisorAnalysis *llvm::createDevelopmentModeAdvisor() {
796   return new DevelopmentModeEvictionAdvisorAnalysis();
797 }
798 
799 int64_t DevelopmentModeEvictAdvisor::tryFindEvictionCandidatePosition(
800     LiveInterval &VirtReg, const AllocationOrder &Order, unsigned OrderLimit,
801     uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
802   int64_t Ret = 0;
803   if (isa<ModelUnderTrainingRunner>(getRunner())) {
804     Ret = MLEvictAdvisor::tryFindEvictionCandidatePosition(
805         VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
806   } else {
807     MCRegister PhysReg = getDefaultAdvisor().tryFindEvictionCandidate(
808         VirtReg, Order, CostPerUseLimit, FixedRegisters);
809     // Find the index of the selected PhysReg. We need it for logging, otherwise
810     // this is wasted cycles (but so would starting development mode without a
811     // model nor logging)
812     if (!PhysReg)
813       Ret = CandidateVirtRegPos;
814     else
815       for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit);
816            I != E; ++I, ++Ret)
817         if (*I == PhysReg)
818           break;
819   }
820   if (TrainingLog.empty())
821     return Ret;
822   size_t CurrentFeature = 0;
823   for (; CurrentFeature < FeatureIDs::FeatureCount; ++CurrentFeature) {
824     Log->logSpecifiedTensorValue(
825         CurrentFeature, reinterpret_cast<const char *>(
826                             getRunner().getTensorUntyped(CurrentFeature)));
827   }
828   if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(&getRunner()))
829     for (size_t I = 1; I < MUTR->outputLoggedFeatureSpecs().size();
830          ++I, ++CurrentFeature)
831       Log->logSpecifiedTensorValue(
832           CurrentFeature,
833           reinterpret_cast<const char *>(
834               MUTR->lastEvaluationResult()->getUntypedTensorValue(I)));
835   // The output is right after the features and the extra outputs
836   Log->logInt64Value(CurrentFeature, &Ret);
837   return Ret;
838 }
839 
840 bool RegAllocScoring::runOnMachineFunction(MachineFunction &MF) {
841   if (auto *DevModeAnalysis = dyn_cast<DevelopmentModeEvictionAdvisorAnalysis>(
842           &getAnalysis<RegAllocEvictionAdvisorAnalysis>()))
843     if (auto *Log = DevModeAnalysis->getLogger(MF))
844       Log->logFloatFinalReward(static_cast<float>(
845           calculateRegAllocScore(
846               MF, getAnalysis<MachineBlockFrequencyInfo>(),
847               getAnalysis<AAResultsWrapperPass>().getAAResults())
848               .getScore()));
849 
850   return false;
851 }
852 #endif // #ifdef LLVM_HAVE_TF_API
853 
854 // Release mode specific implementations
855 #if defined LLVM_HAVE_TF_AOT
856 RegAllocEvictionAdvisorAnalysis *llvm::createReleaseModeAdvisor() {
857   return new ReleaseModeEvictionAdvisorAnalysis();
858 }
859 #endif // defined(LLVM_HAVE_TF_AOT)
860 #endif // defined(LLVM_HAVE_TF_AOT) || defined(LLVM_HAVE_TF_API)
861 
862 // In all cases except development mode, we don't need scoring.
863 #if !defined(LLVM_HAVE_TF_API)
864 bool RegAllocScoring::runOnMachineFunction(MachineFunction &) { return false; }
865 #endif
866