LLVM 24.0.0git
MLRegAllocEvictAdvisor.cpp
Go to the documentation of this file.
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 "RegAllocGreedy.h"
18#if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL) || defined(LLVM_HAVE_TFLITE)
21#endif
32#include "llvm/CodeGen/Passes.h"
35#include "llvm/IR/Module.h"
37#include "llvm/Pass.h"
40
41#include <bitset>
42#include <cmath>
43#include <memory>
44
45using namespace llvm;
46
47#define DEBUG_TYPE "ml-regalloc"
48
49// Generated header in release (AOT) mode
50#if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL)
51#include "RegAllocEvictModel.h"
52using CompiledModelType = RegAllocEvictModel;
53#else
55#endif
56
58#include "llvm/CodeGen/RegAllocEvictModels.h"
59
62#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) CLASS_NAME,
63#include "llvm/CodeGen/RegAllocEvictModels.def"
64};
65
67 "regalloc-mlgo-model",
68 llvm::cl::desc("Select the MLGO model to execute for register allocation:"),
71 "Use standard heuristic")
72#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) \
73 , clEnumValN(MLGORegAllocModelChoice::CLASS_NAME, CLI_FLAG, \
74 "Use the " CLI_FLAG " MLGO model")
75#include "llvm/CodeGen/RegAllocEvictModels.def"
76 ));
77
78static std::unique_ptr<MLModelRunner>
80 const std::vector<TensorSpec> &InputFeatures) {
83 return nullptr;
84#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) \
85 case MLGORegAllocModelChoice::CLASS_NAME: \
86 return EmitCModelRunner<CLASS_NAME>::createAndEnsureValid(Ctx, \
87 InputFeatures);
88#include "llvm/CodeGen/RegAllocEvictModels.def"
89 }
90 llvm_unreachable("Unknown MLGO model type!");
91}
92
94 "regalloc-evict-interactive-channel-base", cl::Hidden,
96 "Base file path for the interactive mode. The incoming filename should "
97 "have the name <regalloc-evict-interactive-channel-base>.in, while the "
98 "outgoing name should be "
99 "<regalloc-evict-interactive-channel-base>.out"));
100
102 "mlregalloc-max-eviction-count", cl::Hidden,
103 cl::desc("The maximum number of times a live range can be "
104 "evicted before preventing it from being evicted"),
105 cl::init(100));
106
108 "mlregalloc-num-allocatable-regs", cl::Hidden,
109 cl::desc("The number of eviction candidates the model sees. The model has "
110 "one more column, for the live range seeking allocation"),
111 cl::init(32));
112
113// Options that only make sense in development mode
114#ifdef LLVM_HAVE_TFLITE
115#include "RegAllocScore.h"
117
118static cl::opt<std::string> TrainingLog(
119 "regalloc-training-log", cl::Hidden,
120 cl::desc("Training log for the register allocator eviction model"));
121
122static cl::opt<std::string> ModelUnderTraining(
123 "regalloc-model", cl::Hidden,
124 cl::desc("The model being trained for register allocation eviction"));
125
126#endif // #ifdef LLVM_HAVE_TFLITE
127
128/// The score injection pass.
129/// This pass calculates the score for a function and inserts it in the log, but
130/// this happens only in development mode. It's a no-op otherwise.
131namespace llvm {
133} // namespace llvm
134
135namespace {
136class RegAllocScoring : public MachineFunctionPass {
137public:
138 static char ID;
139
140 RegAllocScoring() : MachineFunctionPass(ID) {}
141
142 ~RegAllocScoring() override = default;
143
144 StringRef getPassName() const override {
145 return "Register Allocation Pass Scoring";
146 }
147
148 /// RegAllocReward analysis usage.
149 void getAnalysisUsage(AnalysisUsage &AU) const override {
150 AU.setPreservesAll();
151 AU.addRequired<RegAllocEvictionAdvisorAnalysisLegacy>();
152 AU.addRequired<RegAllocPriorityAdvisorAnalysisLegacy>();
153 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
155 }
156
157 /// Performs this pass
158 bool runOnMachineFunction(MachineFunction &) override;
159};
160} // namespace
161
162char RegAllocScoring::ID = 0;
164 return new RegAllocScoring();
165}
166
167INITIALIZE_PASS(RegAllocScoring, "regallocscoringpass",
168 "Register Allocation Scoring Pass", false, false)
169
170// ===================================
171// Common ML Advisor declarations
172// ===================================
173namespace {
174// --------------
175// Features table
176// --------------
177// For each interfering live range (incl. the candidate) we collect a number of
178// features. However, because the features are of different types (and because
179// of ML best practices), we organize the tensors per feature, not per
180// candidate. Each such tensor has a scalar value corresponding to the
181// interferring live range at that position, in the order in AllocationOrder.
182// The last position corresponds to the virt reg seeking allocation.
183// Exception to all that is the progression feature, which is just a scalar (see
184// its documentation for details).
185// Note on naming: the "_by_max" are normalized using the largest value of that
186// tensor, as observed in the current decision making stage (i.e. for the
187// current call to the advisor's tryFindEvictionCandidate)
188//
189// The feature list format: type, name, shape, documentation.
190// Note: we can really just use int64 and float, hence the modeling of some
191// bools as int64 values.
192#define RA_EVICT_FEATURES_LIST(M) \
193 M(int64_t, mask, PerLiveRangeShape, \
194 "boolean values, 0 for unavailable candidates (i.e. if a position is 0, " \
195 "it " \
196 "can't be evicted)") \
197 M(int64_t, is_free, PerLiveRangeShape, \
198 "boolean values, 1 if this phys reg is actually free (no interferences)") \
199 M(float, nr_urgent, PerLiveRangeShape, \
200 "number of 'urgent' intervals, normalized. Urgent are those that are OK " \
201 "to break cascades") \
202 M(float, nr_broken_hints, PerLiveRangeShape, \
203 "if this position were evicted, how many broken hints would there be") \
204 M(int64_t, is_hint, PerLiveRangeShape, \
205 "is this a preferred phys reg for the candidate") \
206 M(int64_t, is_local, PerLiveRangeShape, \
207 "is this live range local to a basic block") \
208 M(float, nr_rematerializable, PerLiveRangeShape, \
209 "nr rematerializable ranges") \
210 M(float, nr_defs_and_uses, PerLiveRangeShape, \
211 "bb freq - weighed nr defs and uses") \
212 M(float, weighed_reads_by_max, PerLiveRangeShape, \
213 "bb freq - weighed nr of reads, normalized") \
214 M(float, weighed_writes_by_max, PerLiveRangeShape, \
215 "bb feq - weighed nr of writes, normalized") \
216 M(float, weighed_read_writes_by_max, PerLiveRangeShape, \
217 "bb freq - weighed nr of uses that are both read and writes, normalized") \
218 M(float, weighed_indvars_by_max, PerLiveRangeShape, \
219 "bb freq - weighed nr of uses that are indvars, normalized") \
220 M(float, hint_weights_by_max, PerLiveRangeShape, \
221 "bb freq - weighed nr of uses that are hints, normalized") \
222 M(float, start_bb_freq_by_max, PerLiveRangeShape, \
223 "the freq in the start block, normalized") \
224 M(float, end_bb_freq_by_max, PerLiveRangeShape, \
225 "freq of end block, normalized") \
226 M(float, hottest_bb_freq_by_max, PerLiveRangeShape, \
227 "hottest BB freq, normalized") \
228 M(float, liverange_size, PerLiveRangeShape, \
229 "size (instr index diff) of the LR") \
230 M(float, use_def_density, PerLiveRangeShape, \
231 "the max weight, as computed by the manual heuristic") \
232 M(int64_t, max_stage, PerLiveRangeShape, \
233 "largest stage of an interval in this LR") \
234 M(int64_t, min_stage, PerLiveRangeShape, \
235 "lowest stage of an interval in this LR") \
236 M(float, progress, {1}, "ratio of current queue size to initial size")
237
238// The model learns to pick one of the mask == 1 interferences. This is the
239// name of the output tensor. The contract with the model is that the output
240// will be guaranteed to be to a mask == 1 position. Using a macro here to
241// avoid 'not used' warnings (and keep cond compilation to a minimum)
242#define DecisionName "index_to_evict"
243static const TensorSpec DecisionSpec =
245
246// Named features index.
247enum FeatureIDs {
248#define _FEATURE_IDX_SIMPLE(_, name, __, ___) name
249#define _FEATURE_IDX(A, B, C, D) _FEATURE_IDX_SIMPLE(A, B, C, D),
251#undef _FEATURE_IDX
252#undef _FEATURE_IDX_SIMPLE
253};
254
255// The ML advisor will typically have a sparse input to the evaluator, because
256// various phys regs won't be available. It's easier (maintenance-wise) to
257// bulk-reset the state of the evaluator each time we are about to use it
258// again.
259void resetInputs(MLModelRunner &Runner, ArrayRef<TensorSpec> InputFeatures) {
260 for (auto [I, Spec] : enumerate(InputFeatures))
261 std::memset(Runner.getTensorUntyped(I), 0, Spec.getTotalTensorBufferSize());
262}
263
264// Per-live interval components that get aggregated into the feature values
265// that will be passed to the evaluator.
266struct LIFeatureComponents {
267 double R = 0;
268 double W = 0;
269 double RW = 0;
270 double IndVarUpdates = 0;
271 double HintWeights = 0.0;
272 int64_t NumDefsAndUses = 0;
273 float HottestBlockFreq = 0.0;
274 bool IsRemat = false;
275};
276
277// Inline capacity hint only, the real width comes from NumAllocatableRegs.
278static constexpr unsigned MaxColumnsCapacityHint = 40;
279
280using CandidateRegList =
281 SmallVector<std::pair<MCRegister, bool>, MaxColumnsCapacityHint>;
282using FeaturesListNormalizer =
284
285/// The ML evictor (commonalities between release and development mode)
286class MLEvictAdvisor : public RegAllocEvictionAdvisor {
287public:
288 MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
290 const MachineBlockFrequencyInfo &MBFI,
291 const MachineLoopInfo &Loops);
292
293protected:
294 const RegAllocEvictionAdvisor &getDefaultAdvisor() const {
295 return static_cast<const RegAllocEvictionAdvisor &>(DefaultAdvisor);
296 }
297
298 // By convention the last column holds the virt reg seeking allocation.
300 const size_t NumColumns;
301 const size_t CandidateVirtRegPos = NumColumns - 1;
302
303 // The assumption is that if the Runner could not be constructed, we emit-ed
304 // error, and we shouldn't be asking for it here.
305 const MLModelRunner &getRunner() const { return *Runner; }
306
307 /// This just calls Evaluate on the Runner, but in the development mode
308 /// case, if we're just capturing the log of the default advisor, it needs
309 /// to call the latter instead, so we need to pass all the necessary
310 /// parameters for it. In the development case, it will also log.
311 virtual int64_t
312 tryFindEvictionCandidatePosition(const LiveInterval &VirtReg,
313 const AllocationOrder &Order,
314 unsigned OrderLimit, uint8_t CostPerUseLimit,
315 const SmallVirtRegSet &FixedRegisters) const;
316
317 /// Load the features of the given VirtReg (allocated or not) at column Pos,
318 /// but if that can't be evicted, return false instead.
319 bool
320 loadInterferenceFeatures(const LiveInterval &VirtReg, MCRegister PhysReg,
321 bool IsHint, const SmallVirtRegSet &FixedRegisters,
322 llvm::SmallVectorImpl<float> &Largest, size_t Pos,
323 SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const;
324
325private:
326 static float getInitialQueueSize(const MachineFunction &MF);
327
329 const LiveInterval &VirtReg, const AllocationOrder &Order,
330 uint8_t CostPerUseLimit,
331 const SmallVirtRegSet &FixedRegisters) const override;
332
333 void extractFeatures(const SmallVectorImpl<const LiveInterval *> &Intervals,
334 llvm::SmallVectorImpl<float> &Largest, size_t Pos,
335 int64_t IsHint, int64_t LocalIntfsCount, float NumUrgent,
336 SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const;
337
338 // Point-in-time: we didn't learn this, so we always delegate to the
339 // default.
341 const LiveInterval &VirtReg, MCRegister PhysReg,
342 const SmallVirtRegSet &FixedRegisters) const override {
343 return getDefaultAdvisor().canEvictHintInterference(VirtReg, PhysReg,
344 FixedRegisters);
345 }
346
347 const LIFeatureComponents &
348 getLIFeatureComponents(const LiveInterval &LI) const;
349
350 // Hold on to a default advisor for:
351 // 1) the implementation of canEvictHintInterference, because we didn't
352 // learn that nuance yet; 2) for bootstrapping (logging) in the development
353 // mode case.
354 const DefaultEvictionAdvisor DefaultAdvisor;
355 MLModelRunner *const Runner;
356 const MachineBlockFrequencyInfo &MBFI;
357 const MachineLoopInfo &Loops;
358
359 // Indices of those features we don't want to normalize.
360 // This could be static and shared, but its initialization is non-trivial.
361 std::bitset<FeatureIDs::FeatureCount> DoNotNormalize;
362 const float InitialQSize;
363
364 using RegID = unsigned;
365 mutable DenseMap<RegID, LIFeatureComponents> CachedFeatures;
366
367 mutable DenseMap<unsigned, unsigned> VirtRegEvictionCounts;
368
369 void onEviction(Register RegBeingEvicted) const {
370 // If we cannot find the virtual register in the map, we just assume it has
371 // not been evicted before and thus has a value of zero (which is what the
372 // subscript operator returns by default).
373 ++VirtRegEvictionCounts[RegBeingEvicted.id()];
374 }
375
376 unsigned getEvictionCount(Register Reg) const {
377 auto EvictionCountIt = VirtRegEvictionCounts.find(Reg.id());
378 if (EvictionCountIt != VirtRegEvictionCounts.end())
379 return EvictionCountIt->second;
380 return 0;
381 }
382};
383
384#define _DECL_FEATURES(type, name, shape, _) \
385 TensorSpec::createSpec<type>(#name, shape),
386
387// ===================================
388// Release (AOT) - specifics
389// ===================================
390/// Common provider for legacy and new pass managers.
391class ReleaseModeEvictionAdvisorProvider final
393public:
394 ReleaseModeEvictionAdvisorProvider(LLVMContext &Ctx)
395 : RegAllocEvictionAdvisorProvider(AdvisorMode::Release, Ctx) {
396 const std::vector<int64_t> PerLiveRangeShape{1, NumAllocatableRegs + 1};
401 }
402 // support for isa<> and dyn_cast.
403 static bool classof(const RegAllocEvictionAdvisorProvider *R) {
404 return R->getAdvisorMode() == AdvisorMode::Release;
405 }
406
407 std::unique_ptr<RegAllocEvictionAdvisor>
408 getAdvisor(const MachineFunction &MF, const RAGreedy &RA,
410 assert(MBFI && Loops &&
411 "Invalid provider state: must have analysis available");
412 if (!Runner)
413 return std::make_unique<DefaultEvictionAdvisor>(MF, RA);
414 return std::make_unique<MLEvictAdvisor>(MF, RA, Runner.get(), InputFeatures,
415 *MBFI, *Loops);
416 }
417
418private:
419 std::vector<TensorSpec> InputFeatures;
420 std::unique_ptr<MLModelRunner> Runner;
421};
422
423class ReleaseModeEvictionAdvisorAnalysisLegacy final
425public:
426 ReleaseModeEvictionAdvisorAnalysisLegacy()
427 : RegAllocEvictionAdvisorAnalysisLegacy(AdvisorMode::Release) {}
428
429 void logRewardIfNeeded(const MachineFunction &MF,
430 llvm::function_ref<float()> GetReward) override {
431 // No-op in release mode
432 }
433
434 bool doInitialization(Module &M) override {
435 Provider =
436 std::make_unique<ReleaseModeEvictionAdvisorProvider>(M.getContext());
437 return false;
438 }
439
440 static bool classof(const RegAllocEvictionAdvisorAnalysisLegacy *R) {
441 return R->getAdvisorMode() == AdvisorMode::Release;
442 }
443
444 void getAnalysisUsage(AnalysisUsage &AU) const override {
447 }
448};
449
450// ===================================
451// Development mode-specifics
452// ===================================
453//
454// Features we log
455#ifdef LLVM_HAVE_TFLITE
456static const TensorSpec Reward = TensorSpec::createSpec<float>("reward", {1});
457
458// Features we bind on the model. The tensor names have a prefix, and we also
459// need to include some tensors that are expected to be present by the
460// training algo.
461// TODO: can we just get rid of these?
462#define _DECL_TRAIN_FEATURES(type, name, shape, _) \
463 TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
464
465class DevelopmentModeEvictAdvisor : public MLEvictAdvisor {
466public:
467 DevelopmentModeEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
468 MLModelRunner *Runner,
470 const MachineBlockFrequencyInfo &MBFI,
471 const MachineLoopInfo &Loops, Logger *Log)
472 : MLEvictAdvisor(MF, RA, Runner, InputFeatures, MBFI, Loops), Log(Log) {}
473
474private:
475 int64_t tryFindEvictionCandidatePosition(
476 const LiveInterval &VirtReg, const AllocationOrder &Order,
477 unsigned OrderLimit, uint8_t CostPerUseLimit,
478 const SmallVirtRegSet &FixedRegisters) const override;
479
480 Logger *const Log;
481};
482
483class DevelopmentModeEvictionAdvisorProvider final
485public:
486 DevelopmentModeEvictionAdvisorProvider(LLVMContext &Ctx)
487 : RegAllocEvictionAdvisorProvider(AdvisorMode::Development, Ctx) {
488 // Picked up by RA_EVICT_FEATURES_LIST.
489 const std::vector<int64_t> PerLiveRangeShape{1, NumAllocatableRegs + 1};
491 TrainingInputFeatures = {
492 RA_EVICT_FEATURES_LIST(_DECL_TRAIN_FEATURES)
493 TensorSpec::createSpec<float>("action_discount", {1}),
494 TensorSpec::createSpec<int32_t>("action_step_type", {1}),
495 TensorSpec::createSpec<float>("action_reward", {1})};
496 if (ModelUnderTraining.empty() && TrainingLog.empty()) {
497 Ctx.emitError("Regalloc development mode should be requested with at "
498 "least logging enabled and/or a training model");
499 return;
500 }
501 if (ModelUnderTraining.empty())
502 Runner = std::make_unique<NoInferenceModelRunner>(Ctx, InputFeatures);
503 else
504 Runner = ModelUnderTrainingRunner::createAndEnsureValid(
505 Ctx, ModelUnderTraining, DecisionName, TrainingInputFeatures);
506 if (!Runner) {
507 Ctx.emitError("Regalloc: could not set up the model runner");
508 return;
509 }
510 if (TrainingLog.empty())
511 return;
512 std::error_code EC;
513 auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
514 if (EC) {
515 Ctx.emitError(EC.message() + ":" + TrainingLog);
516 return;
517 }
518 std::vector<TensorSpec> LFS = InputFeatures;
519 if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(Runner.get()))
520 append_range(LFS, MUTR->extraOutputsForLoggingSpecs());
521 // We always log the output; in particular, if we're not evaluating, we
522 // don't have an output spec json file. That's why we handle the
523 // 'normal' output separately.
524 LFS.push_back(DecisionSpec);
525
526 Log = std::make_unique<Logger>(std::move(OS), LFS, Reward,
527 /*IncludeReward*/ true);
528 return;
529 }
530
531 // support for isa<> and dyn_cast.
532 static bool classof(const RegAllocEvictionAdvisorProvider *R) {
533 return R->getAdvisorMode() == AdvisorMode::Development;
534 }
535
536 void logRewardIfNeeded(const MachineFunction &MF,
537 llvm::function_ref<float()> GetReward) override {
538 if (!Log)
539 return;
540 std::string Ctx = getContextName(MF);
541 if (!Log->hasAnyObservationForContext(Ctx))
542 return;
543 // The function pass manager would run all the function passes for a
544 // function, so we assume the last context belongs to this function. If
545 // this invariant ever changes, we can implement at that time switching
546 // contexts. At this point, it'd be an error
547 if (Log->currentContext() != Ctx) {
549 "The training log context shouldn't have had changed.");
550 }
551 if (Log->hasObservationInProgress())
552 Log->logReward<float>(GetReward());
553 }
554
555 std::unique_ptr<RegAllocEvictionAdvisor>
556 getAdvisor(const MachineFunction &MF, const RAGreedy &RA,
558 if (!Runner)
559 return std::make_unique<DefaultEvictionAdvisor>(MF, RA);
560 if (Log && LastFunctionNumber != MF.getFunctionNumber()) {
561 LastFunctionNumber = MF.getFunctionNumber();
562 Log->switchContext(getContextName(MF));
563 }
564 assert(MBFI && Loops &&
565 "Invalid provider state: must have analysis available");
566 return std::make_unique<DevelopmentModeEvictAdvisor>(
567 MF, RA, Runner.get(), InputFeatures, *MBFI, *Loops, Log.get());
568 }
569
570private:
571 std::vector<TensorSpec> InputFeatures;
572 std::vector<TensorSpec> TrainingInputFeatures;
573
574 std::unique_ptr<MLModelRunner> Runner;
575 std::unique_ptr<Logger> Log;
576 std::optional<unsigned> LastFunctionNumber;
577
578 static std::string getContextName(const MachineFunction &MF) {
580 }
581};
582
583class DevelopmentModeEvictionAdvisorAnalysisLegacy final
585public:
586 DevelopmentModeEvictionAdvisorAnalysisLegacy()
587 : RegAllocEvictionAdvisorAnalysisLegacy(AdvisorMode::Development) {}
588
589 bool doInitialization(Module &M) override {
590 Provider = std::make_unique<DevelopmentModeEvictionAdvisorProvider>(
591 M.getContext());
592 return false;
593 }
594
595 void logRewardIfNeeded(const MachineFunction &MF,
596 llvm::function_ref<float()> GetReward) override {
597 Provider->logRewardIfNeeded(MF, GetReward);
598 }
599
600 // support for isa<> and dyn_cast.
601 static bool classof(const RegAllocEvictionAdvisorAnalysisLegacy *R) {
602 return R->getAdvisorMode() == AdvisorMode::Development;
603 }
604
605 void getAnalysisUsage(AnalysisUsage &AU) const override {
608 }
609};
610
611#endif // #ifdef LLVM_HAVE_TFLITE
612} // namespace
613
614float MLEvictAdvisor::getInitialQueueSize(const MachineFunction &MF) {
615 auto &MRI = MF.getRegInfo();
616 unsigned NumUsedRegs = 0;
617 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
619 if (!MRI.reg_nodbg_empty(Reg))
620 ++NumUsedRegs;
621 }
622 return static_cast<float>(NumUsedRegs);
623}
624
625// Counts the super class because inflation can widen a class up to it.
627 const RegisterClassInfo &RCI) {
628 const MachineRegisterInfo &MRI = MF.getRegInfo();
630 unsigned Max = 0;
631 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
633 if (MRI.reg_nodbg_empty(Reg))
634 continue;
635 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
636 Max = std::max(
637 {Max, RCI.getNumAllocatableRegs(RC),
638 RCI.getNumAllocatableRegs(TRI.getLargestLegalSuperClass(RC, MF))});
639 }
640 return Max;
641}
642
643MLEvictAdvisor::MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
644 MLModelRunner *Runner,
646 const MachineBlockFrequencyInfo &MBFI,
647 const MachineLoopInfo &Loops)
649 NumColumns(NumAllocatableRegs + 1), DefaultAdvisor(MF, RA),
650 Runner(std::move(Runner)), MBFI(MBFI), Loops(Loops),
651 InitialQSize(MLEvictAdvisor::getInitialQueueSize(MF)) {
652 assert(this->Runner);
653 unsigned MaxOrder = getMaxAllocationOrderLength(MF, RegClassInfo);
654 if (MaxOrder > NumAllocatableRegs)
656 "Regalloc: " + MF.getName() +
657 " needs -mlregalloc-num-allocatable-regs=" + Twine(MaxOrder) +
658 " or more, got " + Twine(NumAllocatableRegs));
659 Runner->switchContext(MF.getName());
660 DoNotNormalize.set(FeatureIDs::mask);
661 DoNotNormalize.set(FeatureIDs::is_free);
662 DoNotNormalize.set(FeatureIDs::is_hint);
663 DoNotNormalize.set(FeatureIDs::is_local);
664 DoNotNormalize.set(FeatureIDs::min_stage);
665 DoNotNormalize.set(FeatureIDs::max_stage);
666 DoNotNormalize.set(FeatureIDs::progress);
667}
668
669int64_t MLEvictAdvisor::tryFindEvictionCandidatePosition(
670 const LiveInterval &, const AllocationOrder &, unsigned, uint8_t,
671 const SmallVirtRegSet &) const {
672 int64_t Ret = Runner->evaluate<int64_t>();
673 assert(Ret >= 0);
674 assert(static_cast<size_t>(Ret) <= CandidateVirtRegPos);
675 return Ret;
676}
677
678bool MLEvictAdvisor::loadInterferenceFeatures(
679 const LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint,
680 const SmallVirtRegSet &FixedRegisters,
681 llvm::SmallVectorImpl<float> &Largest, size_t Pos,
682 llvm::SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const {
683 // It is only possible to evict virtual register interference.
684 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg) {
685 // leave unavailable
686 return false;
687 }
688
689 const bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
690 int64_t LocalIntfs = 0;
691 float NumUrgent = 0.0f;
692
693 // The cascade tracking is the same as in the default advisor
694 unsigned Cascade = RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.reg());
695
697 InterferingIntervals;
698 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
699 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
700 // Different from the default heuristic, we don't make any assumptions
701 // about what having more than 10 results in the query may mean.
702 const auto &IFIntervals = Q.interferingVRegs(EvictInterferenceCutoff);
703 if (IFIntervals.empty() && InterferingIntervals.empty())
704 continue;
705 if (IFIntervals.size() >= EvictInterferenceCutoff)
706 return false;
707 InterferingIntervals.append(IFIntervals.begin(), IFIntervals.end());
708 for (const LiveInterval *Intf : reverse(IFIntervals)) {
709 assert(Intf->reg().isVirtual() &&
710 "Only expecting virtual register interference from query");
711 // This is the same set of legality checks as in the default case: don't
712 // try to evict fixed regs or 'done' ones. Also don't break cascades,
713 // except in the urgent case, with the same nuances used in the default
714 // heuristic.
715 // We could try sharing this between the advisors, but it may end up
716 // more complex than it is right now.
717 if (FixedRegisters.count(Intf->reg()))
718 return false;
719 if (RA.getExtraInfo().getStage(*Intf) == RS_Done)
720 return false;
721 bool Urgent = isUrgentEviction(VirtReg, *Intf);
722
723 unsigned IntfCascade = RA.getExtraInfo().getCascade(Intf->reg());
724 // There is a potential that the model could be adversarial and
725 // continually evict live ranges over and over again, leading to a
726 // large amount of compile time being spent in regalloc. If we hit the
727 // threshold, prevent the range from being evicted. We still let the
728 // range through if it is urgent as we are required to produce an
729 // eviction if the candidate is not spillable.
730 // The cap should not apply when the default advisor decides.
731 if (!isa<NoInferenceModelRunner>(Runner) &&
732 getEvictionCount(Intf->reg()) > MaxEvictionCount && !Urgent)
733 return false;
734
735 // Only evict older cascades or live ranges without a cascade, except when
736 // breaking a cascade is legal in RAGreedy::evictInterference.
737 if (Cascade <= IntfCascade) {
738 bool CanBreakCascade = (Cascade < IntfCascade && Urgent) ||
739 (!VirtReg.isSpillable() && Intf->isSpillable());
740 if (!CanBreakCascade)
741 return false;
742 ++NumUrgent;
743 }
744
745 LocalIntfs += (IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
746 (!EnableLocalReassign || !canReassign(*Intf, PhysReg)));
747 }
748 }
749 // OK, so if we made it this far, this LR is an eviction candidate, load its
750 // features.
751 extractFeatures(InterferingIntervals, Largest, Pos, IsHint, LocalIntfs,
752 NumUrgent, LRPosInfo);
753 return true;
754}
755
756MCRegister MLEvictAdvisor::tryFindEvictionCandidate(
757 const LiveInterval &VirtReg, const AllocationOrder &Order,
758 uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
759 auto MaybeOrderLimit = getOrderLimit(VirtReg, Order, CostPerUseLimit);
760 if (!MaybeOrderLimit)
762 unsigned OrderLimit = *MaybeOrderLimit;
763
764 // The heuristic sets initial costs such as, if CostPerUseLimit is
765 // max<uint8_t>, then any of the costs of the legally-evictable intervals
766 // would be lower. When that happens, one of those will be selected.
767 // Therefore, we allow the candidate be selected, unless the candidate is
768 // unspillable, in which case it would be incorrect to not find a register
769 // for it.
770 const bool MustFindEviction =
771 (!VirtReg.isSpillable() && CostPerUseLimit == static_cast<uint8_t>(~0u));
772 // Number of available candidates - if 0, no need to continue.
773 size_t Available = 0;
774 // Make sure we don't have leftover partial state from an attempt where we
775 // had no available candidates and bailed out early.
776 resetInputs(*Runner, InputFeatures);
777
778 // Track the index->register mapping because AllocationOrder doesn't do that
779 // and we'd have to scan it.
780 // Also track their mask, to write asserts/debug.
781 CandidateRegList Regs(NumColumns, {0, false});
782
783 // Track the largest value of features seen during this eviction session. We
784 // only normalize (some of) the float features, but it's just simpler to
785 // dimension 'Largest' to all the features, especially since we have the
786 // 'DoNotNormalize' list.
787 FeaturesListNormalizer Largest(FeatureIDs::FeatureCount, 0.0);
788
789 // Same overal idea as in the default eviction policy - we visit the values
790 // of AllocationOrder one at a time. If it's not legally available, we mask
791 // off the corresponding feature column (==do nothing because we already
792 // reset all the features to 0) Use Pos to capture the column we load
793 // features at - in AllocationOrder order.
794 size_t Pos = 0;
796 for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit); I != E;
797 ++I, ++Pos) {
798 if (Pos == CandidateVirtRegPos)
799 reportFatalUsageError("Regalloc: the allocation order is longer than "
800 "-mlregalloc-num-allocatable-regs=" +
802 MCRegister PhysReg = *I;
803 assert(!Regs[Pos].second);
804 assert(PhysReg);
805 if (!canAllocatePhysReg(VirtReg, CostPerUseLimit, PhysReg)) {
806 continue;
807 }
808 if (loadInterferenceFeatures(VirtReg, PhysReg, I.isHint(), FixedRegisters,
809 Largest, Pos, LRPosInfo)) {
810 ++Available;
811 Regs[Pos] = std::make_pair(PhysReg, true);
812 }
813 }
814 if (Available == 0) {
815 // Nothing to decide, nothing to learn.
817 }
818 const size_t ValidPosLimit = Pos;
819 // If we must find eviction, the candidate should be masked out of the
820 // decision making process.
821 Regs[CandidateVirtRegPos].second = !MustFindEviction;
822 if (!MustFindEviction)
823 extractFeatures(SmallVector<const LiveInterval *, 1>(1, &VirtReg), Largest,
824 CandidateVirtRegPos, /*IsHint*/ 0,
825 /*LocalIntfsCount*/ 0,
826 /*NumUrgent*/ 0.0, LRPosInfo);
827 assert(InitialQSize > 0.0 && "We couldn't have gotten here if we had "
828 "nothing to allocate initially.");
829 // Normalize the features.
830 for (auto &V : Largest)
831 V = V ? V : 1.0;
833 ++FeatureIndex) {
834 if (DoNotNormalize.test(FeatureIndex))
835 continue;
836 for (size_t Pos = 0; Pos < NumColumns; ++Pos) {
837 float &V = Runner->getTensor<float>(FeatureIndex)[Pos];
838 V = std::isinf(V) ? 1.0f : V / Largest[FeatureIndex];
839 }
840 }
841 *Runner->getTensor<float>(FeatureIDs::progress) =
842 static_cast<float>(RA.getQueueSize()) / InitialQSize;
843
844 // Get a decision.
845 size_t CandidatePos = tryFindEvictionCandidatePosition(
846 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
847 // The contract with the ML side is that CandidatePos is mask == 1 (i.e.
848 // Regs[CandidatePos].second)
849 assert(Regs[CandidatePos].second);
850 if (CandidatePos == CandidateVirtRegPos) {
851 onEviction(VirtReg.reg());
852 assert(!MustFindEviction);
854 }
855 assert(CandidatePos < ValidPosLimit);
856 (void)ValidPosLimit;
857
858 // Update information about how many times the virtual registers being
859 // evicted have been evicted so that we can prevent the model from evicting
860 // the same ranges continually and eating compile time.
861 for (MCRegUnit Unit : TRI->regunits(Regs[CandidatePos].first)) {
862 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
863 const auto &IFIntervals = Q.interferingVRegs(EvictInterferenceCutoff);
864 for (const LiveInterval *Intf : reverse(IFIntervals)) {
865 onEviction(Intf->reg());
866 }
867 }
868
869 return Regs[CandidatePos].first;
870}
871
872const LIFeatureComponents &
873MLEvictAdvisor::getLIFeatureComponents(const LiveInterval &LI) const {
874 RegID ID = LI.reg().id();
875 LIFeatureComponents Empty;
876 auto I = CachedFeatures.insert(std::make_pair(ID, Empty));
877 LIFeatureComponents &Ret = I.first->getSecond();
878 if (!I.second)
879 return Ret;
880
883
885 I = MRI->reg_instr_nodbg_begin(LI.reg()),
886 E = MRI->reg_instr_nodbg_end();
887 I != E;) {
888 MachineInstr *MI = &*(I++);
889
890 ++Ret.NumDefsAndUses;
891 if (!Visited.insert(MI).second)
892 continue;
893
894 if (MI->isIdentityCopy() || MI->isImplicitDef())
895 continue;
896
897 bool Reads, Writes;
898 std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
899
900 float Freq = MBFI.getBlockFreqRelativeToEntryBlock(MI->getParent());
901 Ret.HottestBlockFreq = std::max(Freq, Ret.HottestBlockFreq);
902
903 Ret.R += (Reads && !Writes) * Freq;
904 Ret.W += (!Reads && Writes) * Freq;
905 Ret.RW += (Reads && Writes) * Freq;
906
907 auto *MBB = MI->getParent();
908 auto *Loop = Loops.getLoopFor(MBB);
909 bool IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
910
911 if (Writes && IsExiting && LIS->isLiveOutOfMBB(LI, MBB))
912 Ret.IndVarUpdates += Freq;
913
914 if (MI->isCopy() && VirtRegAuxInfo::copyHint(MI, LI.reg(), TRI, *MRI))
915 Ret.HintWeights += Freq;
916 }
918 LI, *LIS, *VRM, *MRI, *MF.getSubtarget().getInstrInfo());
919 return Ret;
920}
921
922// Overall, this currently mimics what we do for weight calculation, but instead
923// of accummulating the various features, we keep them separate.
924void MLEvictAdvisor::extractFeatures(
926 llvm::SmallVectorImpl<float> &Largest, size_t Pos, int64_t IsHint,
927 int64_t LocalIntfsCount, float NumUrgent,
928 SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const {
929 int64_t NumDefsAndUses = 0;
930 int64_t NumBrokenHints = 0;
931 double R = 0.0;
932 double W = 0.0;
933 double RW = 0.0;
934 double IndVarUpdates = 0.0;
935 double HintWeights = 0.0;
936 float StartBBFreq = 0.0;
937 float EndBBFreq = 0.0;
938 float HottestBlockFreq = 0.0;
939 int32_t NumRematerializable = 0;
940 float TotalWeight = 0.0;
941
942 SlotIndex EndSI = LIS->getSlotIndexes()->getZeroIndex();
943 SlotIndex StartSI = LIS->getSlotIndexes()->getLastIndex();
944 int64_t MaxStage = 0;
945 int64_t MinStage =
946 Intervals.empty() ? 0 : std::numeric_limits<int64_t>::max();
947
948 for (const auto *L : Intervals) {
949 const LiveInterval &LI = *L;
950 MaxStage = std::max<int64_t>(
951 MaxStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
952 MinStage = std::min<int64_t>(
953 MinStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
954
955 TotalWeight = std::max(TotalWeight, LI.weight());
956
957 if (LI.beginIndex() < StartSI)
958 StartSI = LI.beginIndex();
959
960 if (LI.endIndex() > EndSI)
961 EndSI = LI.endIndex();
962 const LIFeatureComponents &LIFC = getLIFeatureComponents(LI);
963 NumBrokenHints += VRM->hasPreferredPhys(LI.reg());
964
965 NumDefsAndUses += LIFC.NumDefsAndUses;
966 HottestBlockFreq = std::max(HottestBlockFreq, LIFC.HottestBlockFreq);
967 R += LIFC.R;
968 W += LIFC.W;
969 RW += LIFC.RW;
970
971 IndVarUpdates += LIFC.IndVarUpdates;
972
973 HintWeights += LIFC.HintWeights;
974 NumRematerializable += LIFC.IsRemat;
975 }
976 size_t Size = 0;
977 if (!Intervals.empty()) {
978 StartBBFreq =
979 MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(StartSI));
980 if (EndSI >= LIS->getSlotIndexes()->getLastIndex())
981 EndSI = LIS->getSlotIndexes()->getLastIndex().getPrevIndex();
982 EndBBFreq =
983 MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(EndSI));
984 Size = StartSI.distance(EndSI);
985 }
986 // Set the features at the column 'Pos'.
987#define SET(ID, TYPE, VAL) \
988 do { \
989 Runner->getTensor<TYPE>(FeatureIDs::ID)[Pos] = static_cast<TYPE>(VAL); \
990 float F = static_cast<float>(VAL); \
991 if (!DoNotNormalize.test(FeatureIDs::ID) && !std::isinf(F)) \
992 Largest[FeatureIDs::ID] = std::max(Largest[FeatureIDs::ID], F); \
993 } while (false)
994 SET(mask, int64_t, 1);
995 SET(is_free, int64_t, Intervals.empty());
996 SET(nr_urgent, float, NumUrgent);
997 SET(nr_broken_hints, float, NumBrokenHints);
998 SET(is_hint, int64_t, IsHint);
999 SET(is_local, int64_t, LocalIntfsCount);
1000 SET(nr_rematerializable, float, NumRematerializable);
1001 SET(nr_defs_and_uses, float, NumDefsAndUses);
1002 SET(weighed_reads_by_max, float, R);
1003 SET(weighed_writes_by_max, float, W);
1004 SET(weighed_read_writes_by_max, float, RW);
1005 SET(weighed_indvars_by_max, float, IndVarUpdates);
1006 SET(hint_weights_by_max, float, HintWeights);
1007 SET(start_bb_freq_by_max, float, StartBBFreq);
1008 SET(end_bb_freq_by_max, float, EndBBFreq);
1009 SET(hottest_bb_freq_by_max, float, HottestBlockFreq);
1010 SET(liverange_size, float, Size);
1011 SET(use_def_density, float, TotalWeight);
1012 SET(max_stage, int64_t, MaxStage);
1013 SET(min_stage, int64_t, MinStage);
1014#undef SET
1015}
1016
1017// Development mode-specific implementations
1018#ifdef LLVM_HAVE_TFLITE
1019
1022 return new DevelopmentModeEvictionAdvisorAnalysisLegacy();
1023}
1024
1025int64_t DevelopmentModeEvictAdvisor::tryFindEvictionCandidatePosition(
1026 const LiveInterval &VirtReg, const AllocationOrder &Order,
1027 unsigned OrderLimit, uint8_t CostPerUseLimit,
1028 const SmallVirtRegSet &FixedRegisters) const {
1029 int64_t Ret = 0;
1030 if (isa<ModelUnderTrainingRunner>(getRunner())) {
1031 Ret = MLEvictAdvisor::tryFindEvictionCandidatePosition(
1032 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
1033 } else {
1034 MCRegister PhysReg = getDefaultAdvisor().tryFindEvictionCandidate(
1035 VirtReg, Order, CostPerUseLimit, FixedRegisters);
1036 // Find the index of the selected PhysReg. We need it for logging,
1037 // otherwise this is wasted cycles (but so would starting development mode
1038 // without a model nor logging)
1039 if (!PhysReg)
1040 Ret = CandidateVirtRegPos;
1041 else
1042 for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit);
1043 I != E; ++I, ++Ret)
1044 if (*I == PhysReg)
1045 break;
1046 }
1047 if (!Log)
1048 return Ret;
1049 // TODO(mtrofin): when we support optional rewards, this can go away. In the
1050 // meantime, we log the "pretend" reward (0) for the previous observation
1051 // before starting a new one.
1052 if (Log->hasObservationInProgress())
1053 Log->logReward<float>(0.0);
1054
1055 Log->startObservation();
1056 size_t CurrentFeature = 0;
1058 for (; CurrentFeature < FeatureCount; ++CurrentFeature) {
1059 Log->logTensorValue(CurrentFeature,
1060 reinterpret_cast<const char *>(
1061 getRunner().getTensorUntyped(CurrentFeature)));
1062 }
1063 if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(&getRunner()))
1064 for (size_t I = 0; I < MUTR->extraOutputsForLoggingSpecs().size();
1065 ++I, ++CurrentFeature)
1066 Log->logTensorValue(
1067 CurrentFeature,
1068 reinterpret_cast<const char *>(MUTR->getUntypedExtraOutputValue(I)));
1069 // The output is right after the features and the extra outputs
1070 Log->logTensorValue(CurrentFeature, reinterpret_cast<const char *>(&Ret));
1071 Log->endObservation();
1072 return Ret;
1073}
1074
1075bool RegAllocScoring::runOnMachineFunction(MachineFunction &MF) {
1076 std::optional<float> CachedReward;
1077 auto GetReward = [&]() {
1078 if (!CachedReward)
1079 CachedReward = static_cast<float>(
1081 MF, getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI())
1082 .getScore());
1083 return *CachedReward;
1084 };
1085
1086 getAnalysis<RegAllocEvictionAdvisorAnalysisLegacy>().logRewardIfNeeded(
1087 MF, GetReward);
1088 getAnalysis<RegAllocPriorityAdvisorAnalysisLegacy>().logRewardIfNeeded(
1089 MF, GetReward);
1090 return false;
1091}
1092#endif // #ifdef LLVM_HAVE_TFLITE
1093
1094RegAllocEvictionAdvisorProvider *
1098 ? new ReleaseModeEvictionAdvisorProvider(Ctx)
1099 : nullptr;
1100}
1101
1104#if defined(LLVM_HAVE_TFLITE)
1105 return new DevelopmentModeEvictionAdvisorProvider(Ctx);
1106#endif
1107 return nullptr;
1108}
1109
1114 ? new ReleaseModeEvictionAdvisorAnalysisLegacy()
1115 : nullptr;
1116}
1117
1118// In all cases except development mode, we don't need scoring.
1119#if !defined(LLVM_HAVE_TFLITE)
1120bool RegAllocScoring::runOnMachineFunction(MachineFunction &) { return false; }
1121#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static constexpr unsigned long long mask(BlockVerifier::State S)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
@ Default
This file implements a model runner wrapping an EmitC compiled ML model.
@ Available
We know the block is fully available. This is a fixpoint.
Definition GVN.cpp:1242
Hexagon Hardware Loops
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
Live Register Matrix
#define I(x, y, z)
Definition MD5.cpp:57
This file provides helper functions for creating MLModelRunners and checking model validity in releas...
NoopSavedModelImpl CompiledModelType
static llvm::cl::opt< MLGORegAllocModelChoice > SelectedMLGORegAllocModel("regalloc-mlgo-model", llvm::cl::desc("Select the MLGO model to execute for register allocation:"), llvm::cl::init(MLGORegAllocModelChoice::Default), llvm::cl::values(clEnumValN(MLGORegAllocModelChoice::Default, "default", "Use standard heuristic") #define MLGO_MODEL(CLASS_NAME, CLI_FLAG) \ \‍))
static std::unique_ptr< MLModelRunner > createMLGORegAllocModelRunner(LLVMContext &Ctx, const std::vector< TensorSpec > &InputFeatures)
#define MLGO_MODEL(CLASS_NAME, CLI_FLAG)
static cl::opt< unsigned > MaxEvictionCount("mlregalloc-max-eviction-count", cl::Hidden, cl::desc("The maximum number of times a live range can be " "evicted before preventing it from being evicted"), cl::init(100))
#define RA_EVICT_FEATURES_LIST(M)
#define SET(ID, TYPE, VAL)
static cl::opt< std::string > InteractiveChannelBaseName("regalloc-evict-interactive-channel-base", cl::Hidden, cl::desc("Base file path for the interactive mode. The incoming filename should " "have the name <regalloc-evict-interactive-channel-base>.in, while the " "outgoing name should be " "<regalloc-evict-interactive-channel-base>.out"))
static cl::opt< unsigned > NumAllocatableRegs("mlregalloc-num-allocatable-regs", cl::Hidden, cl::desc("The number of eviction candidates the model sees. The model has " "one more column, for the live range seeking allocation"), cl::init(32))
#define _FEATURE_IDX(A, B, C, D)
#define _DECL_FEATURES(type, name, shape, _)
#define DecisionName
static unsigned getMaxAllocationOrderLength(const MachineFunction &MF, const RegisterClassInfo &RCI)
Register Reg
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
SI optimize exec mask operations pre RA
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Iterator getOrderLimitEnd(unsigned OrderLimit) const
Iterator begin() const
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Query interferences between a single live virtual register and a live interval union.
const SmallVectorImpl< const LiveInterval * > & interferingVRegs(unsigned MaxInterferingRegs=std::numeric_limits< unsigned >::max())
LiveInterval - This class represents the liveness of a register, or stack slot.
float weight() const
Register reg() const
bool isSpillable() const
isSpillable - Can this interval be spilled?
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
@ IK_VirtReg
Virtual register interference.
Logging utility - given an ordered specification of features, and assuming a scalar reward,...
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
static constexpr unsigned NoRegister
Definition MCRegister.h:62
MLModelRunner interface: abstraction of a mechanism for evaluating a ML model.
virtual void switchContext(StringRef Name)
void * getTensorUntyped(size_t Index)
T * getTensor(I FeatureID)
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
double getBlockFreqRelativeToEntryBlock(const MachineBasicBlock *MBB) const
Compute the frequency of the block, relative to the entry block.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
defusechain_instr_iterator< true, true, true, true > reg_instr_nodbg_iterator
reg_instr_nodbg_iterator/reg_instr_nodbg_begin/reg_instr_nodbg_end - Walk all defs and uses of the sp...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A mock class satisfying the interface expected by ReleaseModeModelRunner for its TGen parameter.
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
Definition Pass.h:126
ImmutableAnalysis abstraction for fetching the Eviction Advisor.
virtual void logRewardIfNeeded(const MachineFunction &MF, function_ref< float()> GetReward)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Common provider for legacy and new pass managers.
virtual std::unique_ptr< RegAllocEvictionAdvisor > getAdvisor(const MachineFunction &MF, const RAGreedy &RA, MachineBlockFrequencyInfo *MBFI, MachineLoopInfo *Loops)=0
virtual void logRewardIfNeeded(const MachineFunction &MF, llvm::function_ref< float()> GetReward)
RegAllocEvictionAdvisorProvider(AdvisorMode Mode, LLVMContext &Ctx)
virtual bool canEvictHintInterference(const LiveInterval &VirtReg, MCRegister PhysReg, const SmallVirtRegSet &FixedRegisters) const =0
Find out if we can evict the live ranges occupying the given PhysReg, which is a hint (preferred regi...
virtual MCRegister tryFindEvictionCandidate(const LiveInterval &VirtReg, const AllocationOrder &Order, uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const =0
Find a physical register that can be freed by evicting the FixedRegisters, or return NoRegister.
LLVM_ABI_FOR_TEST double getScore() const
unsigned getNumAllocatableRegs(const TargetRegisterClass *RC) const
getNumAllocatableRegs - Returns the number of actually allocatable registers in RC in the current fun...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
constexpr unsigned id() const
Definition Register.h:100
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
int distance(SlotIndex other) const
Return the distance from this index to the given one.
SlotIndex getPrevIndex() const
Returns the previous index.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
static TensorSpec createSpec(const std::string &Name, const std::vector< int64_t > &Shape, int Port=0)
Definition TensorSpec.h:65
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI bool isRematerializable(const LiveInterval &LI, const LiveIntervals &LIS, const VirtRegMap &VRM, const MachineRegisterInfo &MRI, const TargetInstrInfo &TII)
Determine if all values in LI are rematerializable.
static LLVM_ABI Register copyHint(const MachineInstr *MI, Register Reg, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI)
Return the preferred allocation register for reg, given a COPY instruction.
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
SmallSet< Register, 16 > SmallVirtRegSet
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI RegAllocEvictionAdvisorAnalysisLegacy * createReleaseModeAdvisorAnalysisLegacy()
LLVM_ABI RegAllocEvictionAdvisorProvider * createDevelopmentModeAdvisorProvider(LLVMContext &Ctx)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
static const TensorSpec DecisionSpec
RegAllocScore calculateRegAllocScore(const MachineFunction &MF, const MachineBlockFrequencyInfo &MBFI)
Calculate a score.
bool isReleaseModelValid(StringRef InteractiveChannelBaseName, const cl::opt< EnumType, ExternalStorage, ParserClass > &SelectedModel, EnumType DefaultModelVal=EnumType::Default)
Helper to check if a release-mode ML advisor has a valid model to execute.
Definition MLGOUtils.h:35
LLVM_ABI RegAllocEvictionAdvisorAnalysisLegacy * createDevelopmentModeAdvisorAnalysisLegacy()
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
std::unique_ptr< MLModelRunner > createReleaseModeModelRunner(LLVMContext &Ctx, const std::vector< TensorSpec > &InputFeatures, StringRef DecisionName, const std::string &InteractiveChannelBaseName, const TensorSpec &InteractiveDecisionSpec, CreateEmitCFunc &&CreateEmitCModelRunner, const EmbeddedModelRunnerOptions &Options={})
Helper to construct the appropriate MLModelRunner in release mode:
Definition MLGOUtils.h:61
static const std::vector< TensorSpec > InputFeatures
@ RS_Done
There is nothing more we can do to this live range.
std::string getLoggerContextName(StringRef Name, unsigned Number)
Context name for Name.
LLVM_ABI FunctionPass * createRegAllocScoringPass()
When learning an eviction policy, extract score(reward) information, otherwise this does nothing.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
cl::opt< unsigned > EvictInterferenceCutoff
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI RegAllocEvictionAdvisorProvider * createReleaseModeAdvisorProvider(LLVMContext &Ctx)
static const std::vector< int64_t > PerLiveRangeShape
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879