LLVM 22.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"
19#if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL) || defined(LLVM_HAVE_TFLITE)
23#endif
32#include "llvm/CodeGen/Passes.h"
35#include "llvm/IR/Module.h"
37#include "llvm/Pass.h"
38#include "llvm/PassRegistry.h"
41
42#include <array>
43#include <bitset>
44#include <memory>
45#include <unordered_map>
46
47using namespace llvm;
48
49#define DEBUG_TYPE "ml-regalloc"
50
51// Generated header in release (AOT) mode
52#if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL)
53#include "RegAllocEvictModel.h"
54using CompiledModelType = RegAllocEvictModel;
55#else
57#endif
58
60 "regalloc-evict-interactive-channel-base", cl::Hidden,
62 "Base file path for the interactive mode. The incoming filename should "
63 "have the name <regalloc-evict-interactive-channel-base>.in, while the "
64 "outgoing name should be "
65 "<regalloc-evict-interactive-channel-base>.out"));
66
68 "mlregalloc-max-eviction-count", cl::Hidden,
69 cl::desc("The maximum number of times a live range can be "
70 "evicted before preventing it from being evicted"),
71 cl::init(100));
72
73// Options that only make sense in development mode
74#ifdef LLVM_HAVE_TFLITE
75#include "RegAllocScore.h"
77
78static cl::opt<std::string> TrainingLog(
79 "regalloc-training-log", cl::Hidden,
80 cl::desc("Training log for the register allocator eviction model"));
81
82static cl::opt<std::string> ModelUnderTraining(
83 "regalloc-model", cl::Hidden,
84 cl::desc("The model being trained for register allocation eviction"));
85
86#endif // #ifdef LLVM_HAVE_TFLITE
87
88/// The score injection pass.
89/// This pass calculates the score for a function and inserts it in the log, but
90/// this happens only in development mode. It's a no-op otherwise.
91namespace llvm {
93} // namespace llvm
94
95namespace {
96class RegAllocScoring : public MachineFunctionPass {
97public:
98 static char ID;
99
100 RegAllocScoring() : MachineFunctionPass(ID) {
102 }
103
104 ~RegAllocScoring() override = default;
105
106 StringRef getPassName() const override {
107 return "Register Allocation Pass Scoring";
108 }
109
110 /// RegAllocReward analysis usage.
111 void getAnalysisUsage(AnalysisUsage &AU) const override {
112 AU.setPreservesAll();
113 AU.addRequired<RegAllocEvictionAdvisorAnalysisLegacy>();
114 AU.addRequired<RegAllocPriorityAdvisorAnalysisLegacy>();
115 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
117 }
118
119 /// Performs this pass
120 bool runOnMachineFunction(MachineFunction &) override;
121};
122} // namespace
123
124char RegAllocScoring::ID = 0;
126 return new RegAllocScoring();
127}
128
129INITIALIZE_PASS(RegAllocScoring, "regallocscoringpass",
130 "Register Allocation Scoring Pass", false, false)
131
132// ===================================
133// Common ML Advisor declarations
134// ===================================
135namespace {
136// The model can only accept a specified number of opcodes and will error it if
137// fed an opcode it hasn't seen before. This constant sets the current cutoff.
138static const int OpcodeValueCutoff = 17716;
139
140// Most features are as described above, so we'll reuse this vector in defining
141// them.
142static const std::vector<int64_t> PerLiveRangeShape{1, NumberOfInterferences};
143
144// --------------
145// Features table
146// --------------
147// For each interfering live range (incl. the candidate) we collect a number of
148// features. However, because the features are of different types (and because
149// of ML best practices), we organize the tensors per feature, not per
150// candidate. Each such tensor has a scalar value corresponding to the
151// interferring live range at that position, in the order in AllocationOrder.
152// The last position corresponds to the virt reg seeking allocation.
153// Exception to all that is the progression feature, which is just a scalar (see
154// its documentation for details).
155// Note on naming: the "_by_max" are normalized using the largest value of that
156// tensor, as observed in the current decision making stage (i.e. for the
157// current call to the advisor's tryFindEvictionCandidate)
158//
159// The feature list format: type, name, shape, documentation.
160// Note: we can really just use int64 and float, hence the modeling of some
161// bools as int64 values.
162#define RA_EVICT_FEATURES_LIST(M) \
163 M(int64_t, mask, PerLiveRangeShape, \
164 "boolean values, 0 for unavailable candidates (i.e. if a position is 0, " \
165 "it " \
166 "can't be evicted)") \
167 M(int64_t, is_free, PerLiveRangeShape, \
168 "boolean values, 1 if this phys reg is actually free (no interferences)") \
169 M(float, nr_urgent, PerLiveRangeShape, \
170 "number of 'urgent' intervals, normalized. Urgent are those that are OK " \
171 "to break cascades") \
172 M(float, nr_broken_hints, PerLiveRangeShape, \
173 "if this position were evicted, how many broken hints would there be") \
174 M(int64_t, is_hint, PerLiveRangeShape, \
175 "is this a preferred phys reg for the candidate") \
176 M(int64_t, is_local, PerLiveRangeShape, \
177 "is this live range local to a basic block") \
178 M(float, nr_rematerializable, PerLiveRangeShape, \
179 "nr rematerializable ranges") \
180 M(float, nr_defs_and_uses, PerLiveRangeShape, \
181 "bb freq - weighed nr defs and uses") \
182 M(float, weighed_reads_by_max, PerLiveRangeShape, \
183 "bb freq - weighed nr of reads, normalized") \
184 M(float, weighed_writes_by_max, PerLiveRangeShape, \
185 "bb feq - weighed nr of writes, normalized") \
186 M(float, weighed_read_writes_by_max, PerLiveRangeShape, \
187 "bb freq - weighed nr of uses that are both read and writes, normalized") \
188 M(float, weighed_indvars_by_max, PerLiveRangeShape, \
189 "bb freq - weighed nr of uses that are indvars, normalized") \
190 M(float, hint_weights_by_max, PerLiveRangeShape, \
191 "bb freq - weighed nr of uses that are hints, normalized") \
192 M(float, start_bb_freq_by_max, PerLiveRangeShape, \
193 "the freq in the start block, normalized") \
194 M(float, end_bb_freq_by_max, PerLiveRangeShape, \
195 "freq of end block, normalized") \
196 M(float, hottest_bb_freq_by_max, PerLiveRangeShape, \
197 "hottest BB freq, normalized") \
198 M(float, liverange_size, PerLiveRangeShape, \
199 "size (instr index diff) of the LR") \
200 M(float, use_def_density, PerLiveRangeShape, \
201 "the max weight, as computed by the manual heuristic") \
202 M(int64_t, max_stage, PerLiveRangeShape, \
203 "largest stage of an interval in this LR") \
204 M(int64_t, min_stage, PerLiveRangeShape, \
205 "lowest stage of an interval in this LR") \
206 M(float, progress, {1}, "ratio of current queue size to initial size")
207
208// The model learns to pick one of the mask == 1 interferences. This is the
209// name of the output tensor. The contract with the model is that the output
210// will be guaranteed to be to a mask == 1 position. Using a macro here to
211// avoid 'not used' warnings (and keep cond compilation to a minimum)
212#define DecisionName "index_to_evict"
213static const TensorSpec DecisionSpec =
215
216// Named features index.
217enum FeatureIDs {
218#define _FEATURE_IDX_SIMPLE(_, name, __, ___) name
219#define _FEATURE_IDX(A, B, C, D) _FEATURE_IDX_SIMPLE(A, B, C, D),
221#undef _FEATURE_IDX
222#undef _FEATURE_IDX_SIMPLE
223};
224
225// The ML advisor will typically have a sparse input to the evaluator, because
226// various phys regs won't be available. It's easier (maintenance-wise) to
227// bulk-reset the state of the evaluator each time we are about to use it
228// again.
229template <typename T> size_t getTotalSize(const std::vector<int64_t> &Shape) {
230 size_t Ret = sizeof(T);
231 for (const auto V : Shape)
232 Ret *= V;
233 return Ret;
234}
235
236void resetInputs(MLModelRunner &Runner) {
237#define _RESET(TYPE, NAME, SHAPE, __) \
238 std::memset(Runner.getTensorUntyped(FeatureIDs::NAME), 0, \
239 getTotalSize<TYPE>(SHAPE));
241#undef _RESET
242}
243
244// Per-live interval components that get aggregated into the feature values
245// that will be passed to the evaluator.
246struct LIFeatureComponents {
247 double R = 0;
248 double W = 0;
249 double RW = 0;
250 double IndVarUpdates = 0;
251 double HintWeights = 0.0;
252 int64_t NumDefsAndUses = 0;
253 float HottestBlockFreq = 0.0;
254 bool IsRemat = false;
255};
256
257using CandidateRegList =
258 std::array<std::pair<MCRegister, bool>, NumberOfInterferences>;
259using FeaturesListNormalizer =
261
262/// The ML evictor (commonalities between release and development mode)
263class MLEvictAdvisor : public RegAllocEvictionAdvisor {
264public:
265 MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
266 MLModelRunner *Runner, const MachineBlockFrequencyInfo &MBFI,
267 const MachineLoopInfo &Loops);
268
269protected:
270 const RegAllocEvictionAdvisor &getDefaultAdvisor() const {
271 return static_cast<const RegAllocEvictionAdvisor &>(DefaultAdvisor);
272 }
273
274 // The assumption is that if the Runner could not be constructed, we emit-ed
275 // error, and we shouldn't be asking for it here.
276 const MLModelRunner &getRunner() const { return *Runner; }
277
278 /// This just calls Evaluate on the Runner, but in the development mode
279 /// case, if we're just capturing the log of the default advisor, it needs
280 /// to call the latter instead, so we need to pass all the necessary
281 /// parameters for it. In the development case, it will also log.
282 virtual int64_t
283 tryFindEvictionCandidatePosition(const LiveInterval &VirtReg,
284 const AllocationOrder &Order,
285 unsigned OrderLimit, uint8_t CostPerUseLimit,
286 const SmallVirtRegSet &FixedRegisters) const;
287
288 /// Load the features of the given VirtReg (allocated or not) at column Pos,
289 /// but if that can't be evicted, return false instead.
290 bool
291 loadInterferenceFeatures(const LiveInterval &VirtReg, MCRegister PhysReg,
292 bool IsHint, const SmallVirtRegSet &FixedRegisters,
293 llvm::SmallVectorImpl<float> &Largest, size_t Pos,
294 SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const;
295
296private:
297 static float getInitialQueueSize(const MachineFunction &MF);
298
300 const LiveInterval &VirtReg, const AllocationOrder &Order,
301 uint8_t CostPerUseLimit,
302 const SmallVirtRegSet &FixedRegisters) const override;
303
304 void extractFeatures(const SmallVectorImpl<const LiveInterval *> &Intervals,
305 llvm::SmallVectorImpl<float> &Largest, size_t Pos,
306 int64_t IsHint, int64_t LocalIntfsCount, float NumUrgent,
307 SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const;
308
309 // Point-in-time: we didn't learn this, so we always delegate to the
310 // default.
312 const LiveInterval &VirtReg, MCRegister PhysReg,
313 const SmallVirtRegSet &FixedRegisters) const override {
314 return getDefaultAdvisor().canEvictHintInterference(VirtReg, PhysReg,
315 FixedRegisters);
316 }
317
318 const LIFeatureComponents &
319 getLIFeatureComponents(const LiveInterval &LI) const;
320
321 // Hold on to a default advisor for:
322 // 1) the implementation of canEvictHintInterference, because we didn't
323 // learn that nuance yet; 2) for bootstrapping (logging) in the development
324 // mode case.
325 const DefaultEvictionAdvisor DefaultAdvisor;
326 MLModelRunner *const Runner;
327 const MachineBlockFrequencyInfo &MBFI;
328 const MachineLoopInfo &Loops;
329
330 // Indices of those features we don't want to normalize.
331 // This could be static and shared, but its initialization is non-trivial.
332 std::bitset<FeatureIDs::FeatureCount> DoNotNormalize;
333 const float InitialQSize;
334
335 using RegID = unsigned;
336 mutable DenseMap<RegID, LIFeatureComponents> CachedFeatures;
337
338 mutable std::unordered_map<unsigned, unsigned> VirtRegEvictionCounts;
339
340 void onEviction(Register RegBeingEvicted) const {
341 // If we cannot find the virtual register in the map, we just assume it has
342 // not been evicted before and thus has a value of zero (which is what the
343 // subscript operator returns by default).
344 ++VirtRegEvictionCounts[RegBeingEvicted.id()];
345 }
346
347 unsigned getEvictionCount(Register Reg) const {
348 auto EvictionCountIt = VirtRegEvictionCounts.find(Reg.id());
349 if (EvictionCountIt != VirtRegEvictionCounts.end())
350 return EvictionCountIt->second;
351 return 0;
352 }
353};
354
355#define _DECL_FEATURES(type, name, shape, _) \
356 TensorSpec::createSpec<type>(#name, shape),
357
358// ===================================
359// Release (AOT) - specifics
360// ===================================
361/// Common provider for legacy and new pass managers.
362class ReleaseModeEvictionAdvisorProvider final
364public:
365 ReleaseModeEvictionAdvisorProvider(LLVMContext &Ctx)
366 : RegAllocEvictionAdvisorProvider(AdvisorMode::Release, Ctx) {
368 }
369 // support for isa<> and dyn_cast.
370 static bool classof(const RegAllocEvictionAdvisorProvider *R) {
371 return R->getAdvisorMode() == AdvisorMode::Release;
372 }
373
374 std::unique_ptr<RegAllocEvictionAdvisor>
375 getAdvisor(const MachineFunction &MF, const RAGreedy &RA,
377 if (!Runner) {
378 if (InteractiveChannelBaseName.empty())
379 Runner = std::make_unique<ReleaseModeModelRunner<CompiledModelType>>(
380 MF.getFunction().getContext(), InputFeatures, DecisionName);
381 else
382 Runner = std::make_unique<InteractiveModelRunner>(
386 }
387 assert(MBFI && Loops &&
388 "Invalid provider state: must have analysis available");
389 return std::make_unique<MLEvictAdvisor>(MF, RA, Runner.get(), *MBFI,
390 *Loops);
391 }
392
393private:
394 std::vector<TensorSpec> InputFeatures;
395 std::unique_ptr<MLModelRunner> Runner;
396};
397
398class ReleaseModeEvictionAdvisorAnalysisLegacy final
400public:
401 ReleaseModeEvictionAdvisorAnalysisLegacy()
402 : RegAllocEvictionAdvisorAnalysisLegacy(AdvisorMode::Release) {}
403
404 void logRewardIfNeeded(const MachineFunction &MF,
405 llvm::function_ref<float()> GetReward) override {
406 // No-op in release mode
407 }
408
409 bool doInitialization(Module &M) override {
410 Provider =
411 std::make_unique<ReleaseModeEvictionAdvisorProvider>(M.getContext());
412 return false;
413 }
414
415 static bool classof(const RegAllocEvictionAdvisorAnalysisLegacy *R) {
416 return R->getAdvisorMode() == AdvisorMode::Release;
417 }
418
419 void getAnalysisUsage(AnalysisUsage &AU) const override {
423 }
424};
425
426// ===================================
427// Development mode-specifics
428// ===================================
429//
430// Features we log
431#ifdef LLVM_HAVE_TFLITE
432static const TensorSpec Reward = TensorSpec::createSpec<float>("reward", {1});
433
434// Features we bind on the model. The tensor names have a prefix, and we also
435// need to include some tensors that are expected to be present by the
436// training algo.
437// TODO: can we just get rid of these?
438#define _DECL_TRAIN_FEATURES(type, name, shape, _) \
439 TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
440
441class DevelopmentModeEvictAdvisor : public MLEvictAdvisor {
442public:
443 DevelopmentModeEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
444 MLModelRunner *Runner,
445 const MachineBlockFrequencyInfo &MBFI,
446 const MachineLoopInfo &Loops, Logger *Log)
447 : MLEvictAdvisor(MF, RA, Runner, MBFI, Loops), Log(Log) {}
448
449private:
450 int64_t tryFindEvictionCandidatePosition(
451 const LiveInterval &VirtReg, const AllocationOrder &Order,
452 unsigned OrderLimit, uint8_t CostPerUseLimit,
453 const SmallVirtRegSet &FixedRegisters) const override;
454
455 Logger *const Log;
456};
457
458class DevelopmentModeEvictionAdvisorProvider final
460public:
461 DevelopmentModeEvictionAdvisorProvider(LLVMContext &Ctx)
462 : RegAllocEvictionAdvisorProvider(AdvisorMode::Development, Ctx) {
464 TrainingInputFeatures = {
465 RA_EVICT_FEATURES_LIST(_DECL_TRAIN_FEATURES)
466 TensorSpec::createSpec<float>("action_discount", {1}),
467 TensorSpec::createSpec<int32_t>("action_step_type", {1}),
468 TensorSpec::createSpec<float>("action_reward", {1})};
469 if (ModelUnderTraining.empty() && TrainingLog.empty()) {
470 Ctx.emitError("Regalloc development mode should be requested with at "
471 "least logging enabled and/or a training model");
472 return;
473 }
474 if (ModelUnderTraining.empty())
475 Runner = std::make_unique<NoInferenceModelRunner>(Ctx, InputFeatures);
476 else
477 Runner = ModelUnderTrainingRunner::createAndEnsureValid(
478 Ctx, ModelUnderTraining, DecisionName, TrainingInputFeatures);
479 if (!Runner) {
480 Ctx.emitError("Regalloc: could not set up the model runner");
481 return;
482 }
483 if (TrainingLog.empty())
484 return;
485 std::error_code EC;
486 auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
487 if (EC) {
488 Ctx.emitError(EC.message() + ":" + TrainingLog);
489 return;
490 }
491 std::vector<TensorSpec> LFS = InputFeatures;
492 if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(Runner.get()))
493 append_range(LFS, MUTR->extraOutputsForLoggingSpecs());
494 // We always log the output; in particular, if we're not evaluating, we
495 // don't have an output spec json file. That's why we handle the
496 // 'normal' output separately.
497 LFS.push_back(DecisionSpec);
498
499 Log = std::make_unique<Logger>(std::move(OS), LFS, Reward,
500 /*IncludeReward*/ true);
501 return;
502 }
503
504 // support for isa<> and dyn_cast.
505 static bool classof(const RegAllocEvictionAdvisorProvider *R) {
506 return R->getAdvisorMode() == AdvisorMode::Development;
507 }
508
509 void logRewardIfNeeded(const MachineFunction &MF,
510 llvm::function_ref<float()> GetReward) override {
511 if (!Log || !Log->hasAnyObservationForContext(MF.getName()))
512 return;
513 // The function pass manager would run all the function passes for a
514 // function, so we assume the last context belongs to this function. If
515 // this invariant ever changes, we can implement at that time switching
516 // contexts. At this point, it'd be an error
517 if (Log->currentContext() != MF.getName()) {
519 "The training log context shouldn't have had changed.");
520 }
521 if (Log->hasObservationInProgress())
522 Log->logReward<float>(GetReward());
523 }
524
525 std::unique_ptr<RegAllocEvictionAdvisor>
526 getAdvisor(const MachineFunction &MF, const RAGreedy &RA,
528 if (!Runner)
529 return nullptr;
530 if (Log)
531 Log->switchContext(MF.getName());
532 assert(MBFI && Loops &&
533 "Invalid provider state: must have analysis available");
534 return std::make_unique<DevelopmentModeEvictAdvisor>(
535 MF, RA, Runner.get(), *MBFI, *Loops, Log.get());
536 }
537
538private:
539 std::vector<TensorSpec> InputFeatures;
540 std::vector<TensorSpec> TrainingInputFeatures;
541
542 std::unique_ptr<MLModelRunner> Runner;
543 std::unique_ptr<Logger> Log;
544};
545
546class DevelopmentModeEvictionAdvisorAnalysisLegacy final
548public:
549 DevelopmentModeEvictionAdvisorAnalysisLegacy()
550 : RegAllocEvictionAdvisorAnalysisLegacy(AdvisorMode::Development) {}
551
552 bool doInitialization(Module &M) override {
553 Provider = std::make_unique<DevelopmentModeEvictionAdvisorProvider>(
554 M.getContext());
555 return false;
556 }
557
558 void logRewardIfNeeded(const MachineFunction &MF,
559 llvm::function_ref<float()> GetReward) override {
560 Provider->logRewardIfNeeded(MF, GetReward);
561 }
562
563 // support for isa<> and dyn_cast.
564 static bool classof(const RegAllocEvictionAdvisorAnalysisLegacy *R) {
565 return R->getAdvisorMode() == AdvisorMode::Development;
566 }
567
568 void getAnalysisUsage(AnalysisUsage &AU) const override {
572 }
573};
574
575#endif // #ifdef LLVM_HAVE_TFLITE
576} // namespace
577
578float MLEvictAdvisor::getInitialQueueSize(const MachineFunction &MF) {
579 auto &MRI = MF.getRegInfo();
580 unsigned NumUsedRegs = 0;
581 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
583 if (!MRI.reg_nodbg_empty(Reg))
584 ++NumUsedRegs;
585 }
586 return static_cast<float>(NumUsedRegs);
587}
588
589MLEvictAdvisor::MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
590 MLModelRunner *Runner,
591 const MachineBlockFrequencyInfo &MBFI,
592 const MachineLoopInfo &Loops)
593 : RegAllocEvictionAdvisor(MF, RA), DefaultAdvisor(MF, RA),
594 Runner(std::move(Runner)), MBFI(MBFI), Loops(Loops),
595 InitialQSize(MLEvictAdvisor::getInitialQueueSize(MF)) {
596 assert(this->Runner);
597 Runner->switchContext(MF.getName());
598 DoNotNormalize.set(FeatureIDs::mask);
599 DoNotNormalize.set(FeatureIDs::is_free);
600 DoNotNormalize.set(FeatureIDs::is_hint);
601 DoNotNormalize.set(FeatureIDs::is_local);
602 DoNotNormalize.set(FeatureIDs::min_stage);
603 DoNotNormalize.set(FeatureIDs::max_stage);
604 DoNotNormalize.set(FeatureIDs::progress);
605}
606
607int64_t MLEvictAdvisor::tryFindEvictionCandidatePosition(
608 const LiveInterval &, const AllocationOrder &, unsigned, uint8_t,
609 const SmallVirtRegSet &) const {
610 int64_t Ret = Runner->evaluate<int64_t>();
611 assert(Ret >= 0);
613 return Ret;
614}
615
616bool MLEvictAdvisor::loadInterferenceFeatures(
617 const LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint,
618 const SmallVirtRegSet &FixedRegisters,
619 llvm::SmallVectorImpl<float> &Largest, size_t Pos,
620 llvm::SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const {
621 // It is only possible to evict virtual register interference.
622 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg) {
623 // leave unavailable
624 return false;
625 }
626
627 const bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
628 int64_t LocalIntfs = 0;
629 float NumUrgent = 0.0f;
630
631 // The cascade tracking is the same as in the default advisor
632 unsigned Cascade = RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.reg());
633
635 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
636 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
637 // Different from the default heuristic, we don't make any assumptions
638 // about what having more than 10 results in the query may mean.
639 const auto &IFIntervals = Q.interferingVRegs(EvictInterferenceCutoff);
640 if (IFIntervals.empty() && InterferingIntervals.empty())
641 continue;
642 if (IFIntervals.size() >= EvictInterferenceCutoff)
643 return false;
644 InterferingIntervals.append(IFIntervals.begin(), IFIntervals.end());
645 for (const LiveInterval *Intf : reverse(IFIntervals)) {
646 assert(Intf->reg().isVirtual() &&
647 "Only expecting virtual register interference from query");
648 // This is the same set of legality checks as in the default case: don't
649 // try to evict fixed regs or 'done' ones. Also don't break cascades,
650 // except in the urgent case, with the same nuances used in the default
651 // heuristic.
652 // We could try sharing this between the advisors, but it may end up
653 // more complex than it is right now.
654 if (FixedRegisters.count(Intf->reg()))
655 return false;
656 if (RA.getExtraInfo().getStage(*Intf) == RS_Done)
657 return false;
658 bool Urgent =
659 !VirtReg.isSpillable() &&
660 (Intf->isSpillable() ||
661 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg())) <
662 RegClassInfo.getNumAllocatableRegs(
663 MRI->getRegClass(Intf->reg())));
664
665 unsigned IntfCascade = RA.getExtraInfo().getCascade(Intf->reg());
666 // There is a potential that the model could be adversarial and
667 // continually evict live ranges over and over again, leading to a
668 // large amount of compile time being spent in regalloc. If we hit the
669 // threshold, prevent the range from being evicted. We still let the
670 // range through if it is urgent as we are required to produce an
671 // eviction if the candidate is not spillable.
672 if (getEvictionCount(Intf->reg()) > MaxEvictionCount && !Urgent)
673 return false;
674
675 // Only evict older cascades or live ranges without a cascade.
676 if (Cascade <= IntfCascade) {
677 if (!Urgent)
678 return false;
679 ++NumUrgent;
680 }
681
682 LocalIntfs += (IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
683 (!EnableLocalReassign || !canReassign(*Intf, PhysReg)));
684 }
685 }
686 // OK, so if we made it this far, this LR is an eviction candidate, load its
687 // features.
688 extractFeatures(InterferingIntervals, Largest, Pos, IsHint, LocalIntfs,
689 NumUrgent, LRPosInfo);
690 return true;
691}
692
693MCRegister MLEvictAdvisor::tryFindEvictionCandidate(
694 const LiveInterval &VirtReg, const AllocationOrder &Order,
695 uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
696 auto MaybeOrderLimit = getOrderLimit(VirtReg, Order, CostPerUseLimit);
697 if (!MaybeOrderLimit)
699 unsigned OrderLimit = *MaybeOrderLimit;
700
701 // The heuristic sets initial costs such as, if CostPerUseLimit is
702 // max<uint8_t>, then any of the costs of the legally-evictable intervals
703 // would be lower. When that happens, one of those will be selected.
704 // Therefore, we allow the candidate be selected, unless the candidate is
705 // unspillable, in which case it would be incorrect to not find a register
706 // for it.
707 const bool MustFindEviction =
708 (!VirtReg.isSpillable() && CostPerUseLimit == static_cast<uint8_t>(~0u));
709 // Number of available candidates - if 0, no need to continue.
710 size_t Available = 0;
711 // Make sure we don't have leftover partial state from an attempt where we
712 // had no available candidates and bailed out early.
713 resetInputs(*Runner);
714
715 // Track the index->register mapping because AllocationOrder doesn't do that
716 // and we'd have to scan it.
717 // Also track their mask, to write asserts/debug.
718 CandidateRegList Regs;
719 Regs.fill({0, false});
720
721 // Track the largest value of features seen during this eviction session. We
722 // only normalize (some of) the float features, but it's just simpler to
723 // dimension 'Largest' to all the features, especially since we have the
724 // 'DoNotNormalize' list.
725 FeaturesListNormalizer Largest(FeatureIDs::FeatureCount, 0.0);
726
727 // Same overal idea as in the default eviction policy - we visit the values
728 // of AllocationOrder one at a time. If it's not legally available, we mask
729 // off the corresponding feature column (==do nothing because we already
730 // reset all the features to 0) Use Pos to capture the column we load
731 // features at - in AllocationOrder order.
732 size_t Pos = 0;
734 for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit); I != E;
735 ++I, ++Pos) {
736 MCRegister PhysReg = *I;
737 assert(!Regs[Pos].second);
738 assert(PhysReg);
739 if (!canAllocatePhysReg(CostPerUseLimit, PhysReg)) {
740 continue;
741 }
742 if (loadInterferenceFeatures(VirtReg, PhysReg, I.isHint(), FixedRegisters,
743 Largest, Pos, LRPosInfo)) {
744 ++Available;
745 Regs[Pos] = std::make_pair(PhysReg, true);
746 }
747 }
748 if (Available == 0) {
749 // Nothing to decide, nothing to learn.
750 assert(!MustFindEviction);
752 }
753 const size_t ValidPosLimit = Pos;
754 // If we must find eviction, the candidate should be masked out of the
755 // decision making process.
756 Regs[CandidateVirtRegPos].second = !MustFindEviction;
757 if (!MustFindEviction)
758 extractFeatures(SmallVector<const LiveInterval *, 1>(1, &VirtReg), Largest,
759 CandidateVirtRegPos, /*IsHint*/ 0,
760 /*LocalIntfsCount*/ 0,
761 /*NumUrgent*/ 0.0, LRPosInfo);
762 assert(InitialQSize > 0.0 && "We couldn't have gotten here if we had "
763 "nothing to allocate initially.");
764 // Normalize the features.
765 for (auto &V : Largest)
766 V = V ? V : 1.0;
768 ++FeatureIndex) {
769 if (DoNotNormalize.test(FeatureIndex))
770 continue;
771 for (size_t Pos = 0; Pos < NumberOfInterferences; ++Pos) {
772 Runner->getTensor<float>(FeatureIndex)[Pos] /= Largest[FeatureIndex];
773 }
774 }
775 *Runner->getTensor<float>(FeatureIDs::progress) =
776 static_cast<float>(RA.getQueueSize()) / InitialQSize;
777
778 // Get a decision.
779 size_t CandidatePos = tryFindEvictionCandidatePosition(
780 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
781 // The contract with the ML side is that CandidatePos is mask == 1 (i.e.
782 // Regs[CandidatePos].second)
783 assert(Regs[CandidatePos].second);
784 if (CandidatePos == CandidateVirtRegPos) {
785 onEviction(VirtReg.reg());
786 assert(!MustFindEviction);
788 }
789 assert(CandidatePos < ValidPosLimit);
790 (void)ValidPosLimit;
791
792 // Update information about how many times the virtual registers being
793 // evicted have been evicted so that we can prevent the model from evicting
794 // the same ranges continually and eating compile time.
795 for (MCRegUnit Unit : TRI->regunits(Regs[CandidatePos].first)) {
796 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
797 const auto &IFIntervals = Q.interferingVRegs(EvictInterferenceCutoff);
798 for (const LiveInterval *Intf : reverse(IFIntervals)) {
799 onEviction(Intf->reg());
800 }
801 }
802
803 return Regs[CandidatePos].first;
804}
805
806const LIFeatureComponents &
807MLEvictAdvisor::getLIFeatureComponents(const LiveInterval &LI) const {
808 RegID ID = LI.reg().id();
809 LIFeatureComponents Empty;
810 auto I = CachedFeatures.insert(std::make_pair(ID, Empty));
811 LIFeatureComponents &Ret = I.first->getSecond();
812 if (!I.second)
813 return Ret;
814
817
819 I = MRI->reg_instr_nodbg_begin(LI.reg()),
820 E = MRI->reg_instr_nodbg_end();
821 I != E;) {
822 MachineInstr *MI = &*(I++);
823
824 ++Ret.NumDefsAndUses;
825 if (!Visited.insert(MI).second)
826 continue;
827
828 if (MI->isIdentityCopy() || MI->isImplicitDef())
829 continue;
830
831 bool Reads, Writes;
832 std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
833
834 float Freq = MBFI.getBlockFreqRelativeToEntryBlock(MI->getParent());
835 Ret.HottestBlockFreq = std::max(Freq, Ret.HottestBlockFreq);
836
837 Ret.R += (Reads && !Writes) * Freq;
838 Ret.W += (!Reads && Writes) * Freq;
839 Ret.RW += (Reads && Writes) * Freq;
840
841 auto *MBB = MI->getParent();
842 auto *Loop = Loops.getLoopFor(MBB);
843 bool IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
844
845 if (Writes && IsExiting && LIS->isLiveOutOfMBB(LI, MBB))
846 Ret.IndVarUpdates += Freq;
847
848 if (MI->isCopy() && VirtRegAuxInfo::copyHint(MI, LI.reg(), TRI, *MRI))
849 Ret.HintWeights += Freq;
850 }
852 LI, *LIS, *VRM, *MRI, *MF.getSubtarget().getInstrInfo());
853 return Ret;
854}
855
856// Overall, this currently mimics what we do for weight calculation, but instead
857// of accummulating the various features, we keep them separate.
858void MLEvictAdvisor::extractFeatures(
860 llvm::SmallVectorImpl<float> &Largest, size_t Pos, int64_t IsHint,
861 int64_t LocalIntfsCount, float NumUrgent,
862 SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const {
863 int64_t NumDefsAndUses = 0;
864 int64_t NumBrokenHints = 0;
865 double R = 0.0;
866 double W = 0.0;
867 double RW = 0.0;
868 double IndVarUpdates = 0.0;
869 double HintWeights = 0.0;
870 float StartBBFreq = 0.0;
871 float EndBBFreq = 0.0;
872 float HottestBlockFreq = 0.0;
873 int32_t NumRematerializable = 0;
874 float TotalWeight = 0.0;
875
876 SlotIndex EndSI = LIS->getSlotIndexes()->getZeroIndex();
877 SlotIndex StartSI = LIS->getSlotIndexes()->getLastIndex();
878 int64_t MaxStage = 0;
879 int64_t MinStage =
880 Intervals.empty() ? 0 : std::numeric_limits<int64_t>::max();
881
882 for (const auto *L : Intervals) {
883 const LiveInterval &LI = *L;
884 MaxStage = std::max<int64_t>(
885 MaxStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
886 MinStage = std::min<int64_t>(
887 MinStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
888
889 TotalWeight = std::max(TotalWeight, LI.weight());
890
891 if (LI.beginIndex() < StartSI)
892 StartSI = LI.beginIndex();
893
894 if (LI.endIndex() > EndSI)
895 EndSI = LI.endIndex();
896 const LIFeatureComponents &LIFC = getLIFeatureComponents(LI);
897 NumBrokenHints += VRM->hasPreferredPhys(LI.reg());
898
899 NumDefsAndUses += LIFC.NumDefsAndUses;
900 HottestBlockFreq = std::max(HottestBlockFreq, LIFC.HottestBlockFreq);
901 R += LIFC.R;
902 W += LIFC.W;
903 RW += LIFC.RW;
904
905 IndVarUpdates += LIFC.IndVarUpdates;
906
907 HintWeights += LIFC.HintWeights;
908 NumRematerializable += LIFC.IsRemat;
909 }
910 size_t Size = 0;
911 if (!Intervals.empty()) {
912 StartBBFreq =
913 MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(StartSI));
914 if (EndSI >= LIS->getSlotIndexes()->getLastIndex())
915 EndSI = LIS->getSlotIndexes()->getLastIndex().getPrevIndex();
916 EndBBFreq =
917 MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(EndSI));
918 Size = StartSI.distance(EndSI);
919 }
920 // Set the features at the column 'Pos'.
921#define SET(ID, TYPE, VAL) \
922 do { \
923 Runner->getTensor<TYPE>(FeatureIDs::ID)[Pos] = static_cast<TYPE>(VAL); \
924 if (!DoNotNormalize.test(FeatureIDs::ID)) \
925 Largest[FeatureIDs::ID] = \
926 std::max(Largest[FeatureIDs::ID], static_cast<float>(VAL)); \
927 } while (false)
928 SET(mask, int64_t, 1);
929 SET(is_free, int64_t, Intervals.empty());
930 SET(nr_urgent, float, NumUrgent);
931 SET(nr_broken_hints, float, NumBrokenHints);
932 SET(is_hint, int64_t, IsHint);
933 SET(is_local, int64_t, LocalIntfsCount);
934 SET(nr_rematerializable, float, NumRematerializable);
935 SET(nr_defs_and_uses, float, NumDefsAndUses);
936 SET(weighed_reads_by_max, float, R);
937 SET(weighed_writes_by_max, float, W);
938 SET(weighed_read_writes_by_max, float, RW);
939 SET(weighed_indvars_by_max, float, IndVarUpdates);
940 SET(hint_weights_by_max, float, HintWeights);
941 SET(start_bb_freq_by_max, float, StartBBFreq);
942 SET(end_bb_freq_by_max, float, EndBBFreq);
943 SET(hottest_bb_freq_by_max, float, HottestBlockFreq);
944 SET(liverange_size, float, Size);
945 SET(use_def_density, float, TotalWeight);
946 SET(max_stage, int64_t, MaxStage);
947 SET(min_stage, int64_t, MinStage);
948#undef SET
949}
950
952 SmallVectorImpl<LRStartEndInfo> &LRPosInfo, MLModelRunner *RegallocRunner,
953 function_ref<int(SlotIndex)> GetOpcode,
954 function_ref<float(SlotIndex)> GetMBBFreq,
955 function_ref<MachineBasicBlock *(SlotIndex)> GetMBBReference,
956 const int InstructionsIndex, const int InstructionsMappingIndex,
957 const int MBBFreqIndex, const int MBBMappingIndex,
958 const SlotIndex LastIndex) {
959 // This function extracts instruction based features relevant to the eviction
960 // problem currently being solved. This function ends up extracting two
961 // tensors.
962 // 1 - A vector of size max instruction count. It contains the opcodes of the
963 // instructions spanned by all the intervals in the current instance of the
964 // eviction problem.
965 // 2 - A binary mapping matrix of size (LR count * max
966 // instruction count) which maps where the LRs are live to the actual opcodes
967 // for which they are live.
968 // 3 - A vector of size max supported MBB count storing MBB frequencies,
969 // encompassing all of the MBBs covered by the eviction problem.
970 // 4 - A vector of size max instruction count of indices to members of the MBB
971 // frequency vector, mapping each instruction to its associated MBB.
972
973 // Start off by sorting the segments based on the beginning slot index.
974 std::sort(
975 LRPosInfo.begin(), LRPosInfo.end(),
976 [](LRStartEndInfo A, LRStartEndInfo B) { return A.Begin < B.Begin; });
977 size_t InstructionIndex = 0;
978 size_t CurrentSegmentIndex = 0;
979 SlotIndex CurrentIndex = LRPosInfo[0].Begin;
980 std::map<MachineBasicBlock *, size_t> VisitedMBBs;
981 size_t CurrentMBBIndex = 0;
982 // This loop processes all the segments sequentially by starting at the
983 // beginning slot index of the first segment, iterating through all the slot
984 // indices before the end slot index of that segment (while checking for
985 // overlaps with segments that start at greater slot indices). After hitting
986 // that end index, the current segment being processed gets bumped until they
987 // are all processed or the max instruction count is hit, where everything is
988 // just truncated.
989 while (true) {
990 // If the index that we are currently at is within the current segment and
991 // we haven't hit the max instruction count, continue processing the current
992 // segment.
993 while (CurrentIndex <= LRPosInfo[CurrentSegmentIndex].End &&
994 InstructionIndex < ModelMaxSupportedInstructionCount) {
995 int CurrentOpcode = GetOpcode(CurrentIndex);
996 // If the current machine instruction is null, skip it
997 if (CurrentOpcode == -1) {
998 // If we're currently at the last index in the SlotIndex analysis,
999 // we can't go any further, so return from the function
1000 if (CurrentIndex >= LastIndex) {
1001 return;
1002 }
1003 CurrentIndex = CurrentIndex.getNextIndex();
1004 continue;
1005 }
1006 MachineBasicBlock *CurrentMBBReference = GetMBBReference(CurrentIndex);
1007 if (VisitedMBBs.count(CurrentMBBReference) == 0) {
1008 VisitedMBBs[CurrentMBBReference] = CurrentMBBIndex;
1009 ++CurrentMBBIndex;
1010 }
1011 extractMBBFrequency(CurrentIndex, InstructionIndex, VisitedMBBs,
1012 GetMBBFreq, CurrentMBBReference, RegallocRunner,
1013 MBBFreqIndex, MBBMappingIndex);
1014 // Current code assumes we're not going to get any disjointed segments
1015 assert(LRPosInfo[CurrentSegmentIndex].Begin <= CurrentIndex);
1016 RegallocRunner->getTensor<int64_t>(InstructionsIndex)[InstructionIndex] =
1017 CurrentOpcode < OpcodeValueCutoff ? CurrentOpcode : 0;
1018 // set value in the binary mapping matrix for the current instruction
1019 auto CurrentSegmentPosition = LRPosInfo[CurrentSegmentIndex].Pos;
1020 RegallocRunner->getTensor<int64_t>(
1021 InstructionsMappingIndex)[CurrentSegmentPosition *
1023 InstructionIndex] = 1;
1024 // All of the segments are sorted based on the beginning slot index, but
1025 // this doesn't mean that the beginning slot index of the next segment is
1026 // after the end segment of the one being currently processed. This while
1027 // loop checks for overlapping segments and modifies the portion of the
1028 // column in the mapping matrix for the currently processed instruction
1029 // for the LR it is checking. Also make sure that the beginning of the
1030 // current segment we're checking for overlap in is less than the current
1031 // index, otherwise we're done checking overlaps.
1032 size_t OverlapCheckCurrentSegment = CurrentSegmentIndex + 1;
1033 while (OverlapCheckCurrentSegment < LRPosInfo.size() &&
1034 LRPosInfo[OverlapCheckCurrentSegment].Begin <= CurrentIndex) {
1035 auto OverlapCurrentSegmentPosition =
1036 LRPosInfo[OverlapCheckCurrentSegment].Pos;
1037 if (LRPosInfo[OverlapCheckCurrentSegment].End >= CurrentIndex) {
1038 RegallocRunner->getTensor<int64_t>(
1039 InstructionsMappingIndex)[OverlapCurrentSegmentPosition *
1041 InstructionIndex] = 1;
1042 }
1043 ++OverlapCheckCurrentSegment;
1044 }
1045 ++InstructionIndex;
1046 if (CurrentIndex >= LastIndex) {
1047 return;
1048 }
1049 CurrentIndex = CurrentIndex.getNextIndex();
1050 }
1051 // if we've just finished processing through the last segment or if we've
1052 // hit the maximum number of instructions, break out of the loop.
1053 if (CurrentSegmentIndex == LRPosInfo.size() - 1 ||
1054 InstructionIndex >= ModelMaxSupportedInstructionCount) {
1055 break;
1056 }
1057 // If the segments are not overlapping, we need to move to the beginning
1058 // index of the next segment to avoid having instructions not attached to
1059 // any register.
1060 if (LRPosInfo[CurrentSegmentIndex + 1].Begin >
1061 LRPosInfo[CurrentSegmentIndex].End) {
1062 CurrentIndex = LRPosInfo[CurrentSegmentIndex + 1].Begin;
1063 }
1064 ++CurrentSegmentIndex;
1065 }
1066}
1067
1069 const SlotIndex CurrentIndex, const size_t CurrentInstructionIndex,
1070 std::map<MachineBasicBlock *, size_t> &VisitedMBBs,
1071 function_ref<float(SlotIndex)> GetMBBFreq,
1072 MachineBasicBlock *CurrentMBBReference, MLModelRunner *RegallocRunner,
1073 const int MBBFreqIndex, const int MBBMappingIndex) {
1074 size_t CurrentMBBIndex = VisitedMBBs[CurrentMBBReference];
1075 float CurrentMBBFreq = GetMBBFreq(CurrentIndex);
1076 if (CurrentMBBIndex < ModelMaxSupportedMBBCount) {
1077 RegallocRunner->getTensor<float>(MBBFreqIndex)[CurrentMBBIndex] =
1078 CurrentMBBFreq;
1079 RegallocRunner->getTensor<int64_t>(
1080 MBBMappingIndex)[CurrentInstructionIndex] = CurrentMBBIndex;
1081 }
1082}
1083
1084// Development mode-specific implementations
1085#ifdef LLVM_HAVE_TFLITE
1086
1089 return new DevelopmentModeEvictionAdvisorAnalysisLegacy();
1090}
1091
1092int64_t DevelopmentModeEvictAdvisor::tryFindEvictionCandidatePosition(
1093 const LiveInterval &VirtReg, const AllocationOrder &Order,
1094 unsigned OrderLimit, uint8_t CostPerUseLimit,
1095 const SmallVirtRegSet &FixedRegisters) const {
1096 int64_t Ret = 0;
1097 if (isa<ModelUnderTrainingRunner>(getRunner())) {
1098 Ret = MLEvictAdvisor::tryFindEvictionCandidatePosition(
1099 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
1100 } else {
1101 MCRegister PhysReg = getDefaultAdvisor().tryFindEvictionCandidate(
1102 VirtReg, Order, CostPerUseLimit, FixedRegisters);
1103 // Find the index of the selected PhysReg. We need it for logging,
1104 // otherwise this is wasted cycles (but so would starting development mode
1105 // without a model nor logging)
1106 if (!PhysReg)
1108 else
1109 for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit);
1110 I != E; ++I, ++Ret)
1111 if (*I == PhysReg)
1112 break;
1113 }
1114 if (TrainingLog.empty())
1115 return Ret;
1116 // TODO(mtrofin): when we support optional rewards, this can go away. In the
1117 // meantime, we log the "pretend" reward (0) for the previous observation
1118 // before starting a new one.
1119 if (Log->hasObservationInProgress())
1120 Log->logReward<float>(0.0);
1121
1122 Log->startObservation();
1123 size_t CurrentFeature = 0;
1125 for (; CurrentFeature < FeatureCount; ++CurrentFeature) {
1126 Log->logTensorValue(CurrentFeature,
1127 reinterpret_cast<const char *>(
1128 getRunner().getTensorUntyped(CurrentFeature)));
1129 }
1130 if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(&getRunner()))
1131 for (size_t I = 0; I < MUTR->extraOutputsForLoggingSpecs().size();
1132 ++I, ++CurrentFeature)
1133 Log->logTensorValue(
1134 CurrentFeature,
1135 reinterpret_cast<const char *>(MUTR->getUntypedExtraOutputValue(I)));
1136 // The output is right after the features and the extra outputs
1137 Log->logTensorValue(CurrentFeature, reinterpret_cast<const char *>(&Ret));
1138 Log->endObservation();
1139 return Ret;
1140}
1141
1142bool RegAllocScoring::runOnMachineFunction(MachineFunction &MF) {
1143 std::optional<float> CachedReward;
1144 auto GetReward = [&]() {
1145 if (!CachedReward)
1146 CachedReward = static_cast<float>(
1148 MF, getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI())
1149 .getScore());
1150 return *CachedReward;
1151 };
1152
1153 getAnalysis<RegAllocEvictionAdvisorAnalysisLegacy>().logRewardIfNeeded(
1154 MF, GetReward);
1155 getAnalysis<RegAllocPriorityAdvisorAnalysisLegacy>().logRewardIfNeeded(
1156 MF, GetReward);
1157 return false;
1158}
1159#endif // #ifdef LLVM_HAVE_TFLITE
1160
1161RegAllocEvictionAdvisorProvider *
1163 return new ReleaseModeEvictionAdvisorProvider(Ctx);
1164}
1165
1168#if defined(LLVM_HAVE_TFLITE)
1169 return new DevelopmentModeEvictionAdvisorProvider(Ctx);
1170#endif
1171 return nullptr;
1172}
1173
1178 ? new ReleaseModeEvictionAdvisorAnalysisLegacy()
1179 : nullptr;
1180}
1181
1182// In all cases except development mode, we don't need scoring.
1183#if !defined(LLVM_HAVE_TFLITE)
1184bool RegAllocScoring::runOnMachineFunction(MachineFunction &) { return false; }
1185#endif
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static constexpr unsigned long long mask(BlockVerifier::State S)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
@ Available
We know the block is fully available. This is a fixpoint.
Definition GVN.cpp:951
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
NoopSavedModelImpl CompiledModelType
static cl::opt< std::string > InteractiveChannelBaseName("inliner-interactive-channel-base", cl::Hidden, cl::desc("Base file path for the interactive mode. The incoming filename should " "have the name <inliner-interactive-channel-base>.in, while the " "outgoing name should be <inliner-interactive-channel-base>.out"))
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)
#define _RESET(TYPE, NAME, SHAPE, __)
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"))
#define _FEATURE_IDX(A, B, C, D)
#define _DECL_FEATURES(type, name, shape, _)
#define DecisionName
Register Reg
Register const TargetRegisterInfo * TRI
#define T
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
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.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:359
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
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. Should be passed by value.
Definition MCRegister.h:33
static constexpr unsigned NoRegister
Definition MCRegister.h:52
MLModelRunner interface: abstraction of a mechanism for evaluating a ML model.
virtual void switchContext(StringRef Name)
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.
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.
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:67
A mock class satisfying the interface expected by ReleaseModeModelRunner for its TGen parameter.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
Definition Pass.h:128
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
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:66
SlotIndex getNextIndex() const
Returns the next index.
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:175
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
static 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 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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
bool isEmbeddedModelEvaluatorValid()
static const int ModelMaxSupportedInstructionCount
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:1655
SmallSet< Register, 16 > SmallVirtRegSet
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RegAllocEvictionAdvisorAnalysisLegacy * createReleaseModeAdvisorAnalysisLegacy()
static const int64_t ModelMaxSupportedMBBCount
RegAllocEvictionAdvisorProvider * createDevelopmentModeAdvisorProvider(LLVMContext &Ctx)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2136
LLVM_ABI_FOR_TEST void extractInstructionFeatures(llvm::SmallVectorImpl< LRStartEndInfo > &LRPosInfo, MLModelRunner *RegallocRunner, function_ref< int(SlotIndex)> GetOpcode, function_ref< float(SlotIndex)> GetMBBFreq, function_ref< MachineBasicBlock *(SlotIndex)> GetMBBReference, const int InstructionsIndex, const int InstructionsMappingIndex, const int MBBFreqIndex, const int MBBMappingIndex, const SlotIndex LastIndex)
static const TensorSpec DecisionSpec
RegAllocScore calculateRegAllocScore(const MachineFunction &MF, const MachineBlockFrequencyInfo &MBFI)
Calculate a score.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
LLVM_ABI void initializeRegAllocScoringPass(PassRegistry &)
static const std::vector< TensorSpec > InputFeatures
@ RS_Done
There is nothing more we can do to this live range.
unsigned MCRegUnit
Register units are used to compute register aliasing.
Definition MCRegister.h:30
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:1867
LLVM_ATTRIBUTE_RETURNS_NONNULL RegAllocEvictionAdvisorProvider * createReleaseModeAdvisorProvider(LLVMContext &Ctx)
LLVM_ABI_FOR_TEST void extractMBBFrequency(const SlotIndex CurrentIndex, const size_t CurrentInstructionIndex, std::map< MachineBasicBlock *, size_t > &VisitedMBBs, function_ref< float(SlotIndex)> GetMBBFreq, MachineBasicBlock *CurrentMBBReference, MLModelRunner *RegallocRunner, const int MBBFreqIndex, const int MBBMappingIndex)
static const int64_t NumberOfInterferences
static const std::vector< int64_t > PerLiveRangeShape
RegAllocEvictionAdvisorAnalysisLegacy * createDevelopmentModeAdvisorAnalysisLegacy()
static const int64_t CandidateVirtRegPos
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867