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