18#if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL) || defined(LLVM_HAVE_TFLITE)
47#define DEBUG_TYPE "ml-regalloc"
50#if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL)
51#include "RegAllocEvictModel.h"
58#include "llvm/CodeGen/RegAllocEvictModels.h"
62#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) CLASS_NAME,
63#include "llvm/CodeGen/RegAllocEvictModels.def"
67 "regalloc-mlgo-model",
68 llvm::cl::desc(
"Select the MLGO model to execute for register allocation:"),
71 "Use standard heuristic")
73 ,
clEnumValN(MLGORegAllocModelChoice::CLASS_NAME, CLI_FLAG, \
74 "Use the " CLI_FLAG
" MLGO model")
75#include
"llvm/CodeGen/RegAllocEvictModels.def"
78static std::unique_ptr<MLModelRunner>
84#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) \
85 case MLGORegAllocModelChoice::CLASS_NAME: \
86 return EmitCModelRunner<CLASS_NAME>::createAndEnsureValid(Ctx, \
88#include "llvm/CodeGen/RegAllocEvictModels.def"
94 "regalloc-evict-interactive-channel-base",
cl::Hidden,
96 "Base file path for the interactive mode. The incoming filename should "
97 "have the name <regalloc-evict-interactive-channel-base>.in, while the "
98 "outgoing name should be "
99 "<regalloc-evict-interactive-channel-base>.out"));
103 cl::desc(
"The maximum number of times a live range can be "
104 "evicted before preventing it from being evicted"),
108 "mlregalloc-num-allocatable-regs",
cl::Hidden,
109 cl::desc(
"The number of eviction candidates the model sees. The model has "
110 "one more column, for the live range seeking allocation"),
114#ifdef LLVM_HAVE_TFLITE
120 cl::desc(
"Training log for the register allocator eviction model"));
124 cl::desc(
"The model being trained for register allocation eviction"));
140 RegAllocScoring() : MachineFunctionPass(ID) {}
142 ~RegAllocScoring()
override =
default;
144 StringRef getPassName()
const override {
145 return "Register Allocation Pass Scoring";
149 void getAnalysisUsage(AnalysisUsage &AU)
const override {
151 AU.
addRequired<RegAllocEvictionAdvisorAnalysisLegacy>();
152 AU.
addRequired<RegAllocPriorityAdvisorAnalysisLegacy>();
153 AU.
addRequired<MachineBlockFrequencyInfoWrapperPass>();
162char RegAllocScoring::ID = 0;
164 return new RegAllocScoring();
168 "Register Allocation Scoring Pass",
false,
false)
192#define RA_EVICT_FEATURES_LIST(M) \
193 M(int64_t, mask, PerLiveRangeShape, \
194 "boolean values, 0 for unavailable candidates (i.e. if a position is 0, " \
196 "can't be evicted)") \
197 M(int64_t, is_free, PerLiveRangeShape, \
198 "boolean values, 1 if this phys reg is actually free (no interferences)") \
199 M(float, nr_urgent, PerLiveRangeShape, \
200 "number of 'urgent' intervals, normalized. Urgent are those that are OK " \
201 "to break cascades") \
202 M(float, nr_broken_hints, PerLiveRangeShape, \
203 "if this position were evicted, how many broken hints would there be") \
204 M(int64_t, is_hint, PerLiveRangeShape, \
205 "is this a preferred phys reg for the candidate") \
206 M(int64_t, is_local, PerLiveRangeShape, \
207 "is this live range local to a basic block") \
208 M(float, nr_rematerializable, PerLiveRangeShape, \
209 "nr rematerializable ranges") \
210 M(float, nr_defs_and_uses, PerLiveRangeShape, \
211 "bb freq - weighed nr defs and uses") \
212 M(float, weighed_reads_by_max, PerLiveRangeShape, \
213 "bb freq - weighed nr of reads, normalized") \
214 M(float, weighed_writes_by_max, PerLiveRangeShape, \
215 "bb feq - weighed nr of writes, normalized") \
216 M(float, weighed_read_writes_by_max, PerLiveRangeShape, \
217 "bb freq - weighed nr of uses that are both read and writes, normalized") \
218 M(float, weighed_indvars_by_max, PerLiveRangeShape, \
219 "bb freq - weighed nr of uses that are indvars, normalized") \
220 M(float, hint_weights_by_max, PerLiveRangeShape, \
221 "bb freq - weighed nr of uses that are hints, normalized") \
222 M(float, start_bb_freq_by_max, PerLiveRangeShape, \
223 "the freq in the start block, normalized") \
224 M(float, end_bb_freq_by_max, PerLiveRangeShape, \
225 "freq of end block, normalized") \
226 M(float, hottest_bb_freq_by_max, PerLiveRangeShape, \
227 "hottest BB freq, normalized") \
228 M(float, liverange_size, PerLiveRangeShape, \
229 "size (instr index diff) of the LR") \
230 M(float, use_def_density, PerLiveRangeShape, \
231 "the max weight, as computed by the manual heuristic") \
232 M(int64_t, max_stage, PerLiveRangeShape, \
233 "largest stage of an interval in this LR") \
234 M(int64_t, min_stage, PerLiveRangeShape, \
235 "lowest stage of an interval in this LR") \
236 M(float, progress, {1}, "ratio of current queue size to initial size")
242#define DecisionName "index_to_evict"
248#define _FEATURE_IDX_SIMPLE(_, name, __, ___) name
249#define _FEATURE_IDX(A, B, C, D) _FEATURE_IDX_SIMPLE(A, B, C, D),
252#undef _FEATURE_IDX_SIMPLE
266struct LIFeatureComponents {
270 double IndVarUpdates = 0;
271 double HintWeights = 0.0;
272 int64_t NumDefsAndUses = 0;
273 float HottestBlockFreq = 0.0;
274 bool IsRemat =
false;
278static constexpr unsigned MaxColumnsCapacityHint = 40;
280using CandidateRegList =
282using FeaturesListNormalizer =
300 const size_t NumColumns;
301 const size_t CandidateVirtRegPos = NumColumns - 1;
312 tryFindEvictionCandidatePosition(
const LiveInterval &VirtReg,
314 unsigned OrderLimit,
uint8_t CostPerUseLimit,
335 int64_t IsHint, int64_t LocalIntfsCount,
float NumUrgent,
343 return getDefaultAdvisor().canEvictHintInterference(VirtReg, PhysReg,
347 const LIFeatureComponents &
361 std::bitset<FeatureIDs::FeatureCount> DoNotNormalize;
362 const float InitialQSize;
369 void onEviction(
Register RegBeingEvicted)
const {
373 ++VirtRegEvictionCounts[RegBeingEvicted.
id()];
377 auto EvictionCountIt = VirtRegEvictionCounts.
find(
Reg.id());
378 if (EvictionCountIt != VirtRegEvictionCounts.
end())
379 return EvictionCountIt->second;
384#define _DECL_FEATURES(type, name, shape, _) \
385 TensorSpec::createSpec<type>(#name, shape),
391class ReleaseModeEvictionAdvisorProvider final
394 ReleaseModeEvictionAdvisorProvider(
LLVMContext &Ctx)
404 return R->getAdvisorMode() == AdvisorMode::Release;
407 std::unique_ptr<RegAllocEvictionAdvisor>
411 "Invalid provider state: must have analysis available");
413 return std::make_unique<DefaultEvictionAdvisor>(MF,
RA);
414 return std::make_unique<MLEvictAdvisor>(MF,
RA, Runner.get(),
InputFeatures,
420 std::unique_ptr<MLModelRunner> Runner;
423class ReleaseModeEvictionAdvisorAnalysisLegacy final
426 ReleaseModeEvictionAdvisorAnalysisLegacy()
436 std::make_unique<ReleaseModeEvictionAdvisorProvider>(M.getContext());
441 return R->getAdvisorMode() == AdvisorMode::Release;
455#ifdef LLVM_HAVE_TFLITE
462#define _DECL_TRAIN_FEATURES(type, name, shape, _) \
463 TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
465class DevelopmentModeEvictAdvisor :
public MLEvictAdvisor {
475 int64_t tryFindEvictionCandidatePosition(
477 unsigned OrderLimit,
uint8_t CostPerUseLimit,
483class DevelopmentModeEvictionAdvisorProvider final
486 DevelopmentModeEvictionAdvisorProvider(
LLVMContext &Ctx)
491 TrainingInputFeatures = {
496 if (ModelUnderTraining.empty() && TrainingLog.empty()) {
497 Ctx.emitError(
"Regalloc development mode should be requested with at "
498 "least logging enabled and/or a training model");
501 if (ModelUnderTraining.empty())
502 Runner = std::make_unique<NoInferenceModelRunner>(Ctx,
InputFeatures);
504 Runner = ModelUnderTrainingRunner::createAndEnsureValid(
505 Ctx, ModelUnderTraining,
DecisionName, TrainingInputFeatures);
507 Ctx.emitError(
"Regalloc: could not set up the model runner");
510 if (TrainingLog.empty())
513 auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
515 Ctx.emitError(EC.message() +
":" + TrainingLog);
526 Log = std::make_unique<Logger>(std::move(OS), LFS, Reward,
533 return R->getAdvisorMode() == AdvisorMode::Development;
540 std::string Ctx = getContextName(MF);
541 if (!Log->hasAnyObservationForContext(Ctx))
547 if (Log->currentContext() != Ctx) {
549 "The training log context shouldn't have had changed.");
551 if (Log->hasObservationInProgress())
552 Log->logReward<
float>(GetReward());
555 std::unique_ptr<RegAllocEvictionAdvisor>
559 return std::make_unique<DefaultEvictionAdvisor>(MF,
RA);
562 Log->switchContext(getContextName(MF));
565 "Invalid provider state: must have analysis available");
566 return std::make_unique<DevelopmentModeEvictAdvisor>(
572 std::vector<TensorSpec> TrainingInputFeatures;
574 std::unique_ptr<MLModelRunner> Runner;
575 std::unique_ptr<Logger> Log;
576 std::optional<unsigned> LastFunctionNumber;
583class DevelopmentModeEvictionAdvisorAnalysisLegacy final
586 DevelopmentModeEvictionAdvisorAnalysisLegacy()
590 Provider = std::make_unique<DevelopmentModeEvictionAdvisorProvider>(
597 Provider->logRewardIfNeeded(MF, GetReward);
602 return R->getAdvisorMode() == AdvisorMode::Development;
616 unsigned NumUsedRegs = 0;
617 for (
unsigned I = 0,
E =
MRI.getNumVirtRegs();
I !=
E; ++
I) {
619 if (!
MRI.reg_nodbg_empty(
Reg))
622 return static_cast<float>(NumUsedRegs);
631 for (
unsigned I = 0,
E =
MRI.getNumVirtRegs();
I !=
E; ++
I) {
633 if (
MRI.reg_nodbg_empty(
Reg))
651 InitialQSize(MLEvictAdvisor::getInitialQueueSize(MF)) {
657 " needs -mlregalloc-num-allocatable-regs=" +
Twine(MaxOrder) +
660 DoNotNormalize.set(FeatureIDs::mask);
661 DoNotNormalize.set(FeatureIDs::is_free);
662 DoNotNormalize.set(FeatureIDs::is_hint);
663 DoNotNormalize.set(FeatureIDs::is_local);
664 DoNotNormalize.set(FeatureIDs::min_stage);
665 DoNotNormalize.set(FeatureIDs::max_stage);
666 DoNotNormalize.set(FeatureIDs::progress);
669int64_t MLEvictAdvisor::tryFindEvictionCandidatePosition(
672 int64_t Ret = Runner->
evaluate<int64_t>();
674 assert(
static_cast<size_t>(Ret) <= CandidateVirtRegPos);
678bool MLEvictAdvisor::loadInterferenceFeatures(
689 const bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
690 int64_t LocalIntfs = 0;
691 float NumUrgent = 0.0f;
694 unsigned Cascade =
RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.
reg());
697 InterferingIntervals;
698 for (MCRegUnit Unit :
TRI->regunits(PhysReg)) {
703 if (IFIntervals.empty() && InterferingIntervals.
empty())
707 InterferingIntervals.
append(IFIntervals.begin(), IFIntervals.end());
709 assert(Intf->reg().isVirtual() &&
710 "Only expecting virtual register interference from query");
717 if (FixedRegisters.
count(Intf->reg()))
719 if (
RA.getExtraInfo().getStage(*Intf) ==
RS_Done)
721 bool Urgent = isUrgentEviction(VirtReg, *Intf);
723 unsigned IntfCascade =
RA.getExtraInfo().getCascade(Intf->reg());
737 if (Cascade <= IntfCascade) {
738 bool CanBreakCascade = (Cascade < IntfCascade && Urgent) ||
740 if (!CanBreakCascade)
745 LocalIntfs += (IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
746 (!EnableLocalReassign || !canReassign(*Intf, PhysReg)));
751 extractFeatures(InterferingIntervals, Largest, Pos, IsHint, LocalIntfs,
752 NumUrgent, LRPosInfo);
756MCRegister MLEvictAdvisor::tryFindEvictionCandidate(
759 auto MaybeOrderLimit = getOrderLimit(VirtReg, Order, CostPerUseLimit);
760 if (!MaybeOrderLimit)
762 unsigned OrderLimit = *MaybeOrderLimit;
770 const bool MustFindEviction =
781 CandidateRegList Regs(NumColumns, {0,
false});
798 if (Pos == CandidateVirtRegPos)
800 "-mlregalloc-num-allocatable-regs=" +
803 assert(!Regs[Pos].second);
805 if (!canAllocatePhysReg(VirtReg, CostPerUseLimit, PhysReg)) {
808 if (loadInterferenceFeatures(VirtReg, PhysReg,
I.isHint(), FixedRegisters,
809 Largest, Pos, LRPosInfo)) {
811 Regs[Pos] = std::make_pair(PhysReg,
true);
818 const size_t ValidPosLimit = Pos;
821 Regs[CandidateVirtRegPos].second = !MustFindEviction;
822 if (!MustFindEviction)
824 CandidateVirtRegPos, 0,
827 assert(InitialQSize > 0.0 &&
"We couldn't have gotten here if we had "
828 "nothing to allocate initially.");
830 for (
auto &
V : Largest)
836 for (
size_t Pos = 0; Pos < NumColumns; ++Pos) {
841 *Runner->
getTensor<
float>(FeatureIDs::progress) =
842 static_cast<float>(
RA.getQueueSize()) / InitialQSize;
845 size_t CandidatePos = tryFindEvictionCandidatePosition(
846 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
849 assert(Regs[CandidatePos].second);
850 if (CandidatePos == CandidateVirtRegPos) {
851 onEviction(VirtReg.
reg());
852 assert(!MustFindEviction);
855 assert(CandidatePos < ValidPosLimit);
861 for (MCRegUnit Unit :
TRI->regunits(Regs[CandidatePos].first)) {
865 onEviction(Intf->reg());
869 return Regs[CandidatePos].first;
872const LIFeatureComponents &
873MLEvictAdvisor::getLIFeatureComponents(
const LiveInterval &LI)
const {
874 RegID ID = LI.
reg().
id();
875 LIFeatureComponents
Empty;
876 auto I = CachedFeatures.insert(std::make_pair(ID,
Empty));
877 LIFeatureComponents &Ret =
I.first->getSecond();
885 I =
MRI->reg_instr_nodbg_begin(LI.
reg()),
886 E =
MRI->reg_instr_nodbg_end();
890 ++Ret.NumDefsAndUses;
894 if (
MI->isIdentityCopy() ||
MI->isImplicitDef())
898 std::tie(Reads, Writes) =
MI->readsWritesVirtualRegister(LI.
reg());
901 Ret.HottestBlockFreq = std::max(Freq, Ret.HottestBlockFreq);
903 Ret.R += (Reads && !Writes) * Freq;
904 Ret.W += (!Reads && Writes) * Freq;
905 Ret.RW += (Reads && Writes) * Freq;
907 auto *
MBB =
MI->getParent();
911 if (Writes && IsExiting && LIS->isLiveOutOfMBB(LI,
MBB))
912 Ret.IndVarUpdates += Freq;
915 Ret.HintWeights += Freq;
924void MLEvictAdvisor::extractFeatures(
927 int64_t LocalIntfsCount,
float NumUrgent,
929 int64_t NumDefsAndUses = 0;
930 int64_t NumBrokenHints = 0;
934 double IndVarUpdates = 0.0;
935 double HintWeights = 0.0;
936 float StartBBFreq = 0.0;
937 float EndBBFreq = 0.0;
938 float HottestBlockFreq = 0.0;
939 int32_t NumRematerializable = 0;
940 float TotalWeight = 0.0;
942 SlotIndex EndSI = LIS->getSlotIndexes()->getZeroIndex();
943 SlotIndex StartSI = LIS->getSlotIndexes()->getLastIndex();
944 int64_t MaxStage = 0;
946 Intervals.
empty() ? 0 : std::numeric_limits<int64_t>::max();
948 for (
const auto *L : Intervals) {
950 MaxStage = std::max<int64_t>(
951 MaxStage,
static_cast<int64_t
>(
RA.getExtraInfo().getStage(LI)));
952 MinStage = std::min<int64_t>(
953 MinStage,
static_cast<int64_t
>(
RA.getExtraInfo().getStage(LI)));
955 TotalWeight = std::max(TotalWeight, LI.
weight());
962 const LIFeatureComponents &LIFC = getLIFeatureComponents(LI);
963 NumBrokenHints += VRM->hasPreferredPhys(LI.
reg());
965 NumDefsAndUses += LIFC.NumDefsAndUses;
966 HottestBlockFreq = std::max(HottestBlockFreq, LIFC.HottestBlockFreq);
971 IndVarUpdates += LIFC.IndVarUpdates;
973 HintWeights += LIFC.HintWeights;
974 NumRematerializable += LIFC.IsRemat;
977 if (!Intervals.empty()) {
980 if (EndSI >= LIS->getSlotIndexes()->getLastIndex())
981 EndSI = LIS->getSlotIndexes()->getLastIndex().
getPrevIndex();
987#define SET(ID, TYPE, VAL) \
989 Runner->getTensor<TYPE>(FeatureIDs::ID)[Pos] = static_cast<TYPE>(VAL); \
990 float F = static_cast<float>(VAL); \
991 if (!DoNotNormalize.test(FeatureIDs::ID) && !std::isinf(F)) \
992 Largest[FeatureIDs::ID] = std::max(Largest[FeatureIDs::ID], F); \
995 SET(is_free, int64_t, Intervals.empty());
996 SET(nr_urgent,
float, NumUrgent);
997 SET(nr_broken_hints,
float, NumBrokenHints);
998 SET(is_hint, int64_t, IsHint);
999 SET(is_local, int64_t, LocalIntfsCount);
1000 SET(nr_rematerializable,
float, NumRematerializable);
1001 SET(nr_defs_and_uses,
float, NumDefsAndUses);
1002 SET(weighed_reads_by_max,
float, R);
1003 SET(weighed_writes_by_max,
float, W);
1004 SET(weighed_read_writes_by_max,
float, RW);
1005 SET(weighed_indvars_by_max,
float, IndVarUpdates);
1006 SET(hint_weights_by_max,
float, HintWeights);
1007 SET(start_bb_freq_by_max,
float, StartBBFreq);
1008 SET(end_bb_freq_by_max,
float, EndBBFreq);
1009 SET(hottest_bb_freq_by_max,
float, HottestBlockFreq);
1010 SET(liverange_size,
float,
Size);
1011 SET(use_def_density,
float, TotalWeight);
1012 SET(max_stage, int64_t, MaxStage);
1013 SET(min_stage, int64_t, MinStage);
1018#ifdef LLVM_HAVE_TFLITE
1022 return new DevelopmentModeEvictionAdvisorAnalysisLegacy();
1025int64_t DevelopmentModeEvictAdvisor::tryFindEvictionCandidatePosition(
1027 unsigned OrderLimit,
uint8_t CostPerUseLimit,
1031 Ret = MLEvictAdvisor::tryFindEvictionCandidatePosition(
1032 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
1034 MCRegister PhysReg = getDefaultAdvisor().tryFindEvictionCandidate(
1035 VirtReg, Order, CostPerUseLimit, FixedRegisters);
1040 Ret = CandidateVirtRegPos;
1052 if (
Log->hasObservationInProgress())
1053 Log->logReward<
float>(0.0);
1055 Log->startObservation();
1056 size_t CurrentFeature = 0;
1058 for (; CurrentFeature <
FeatureCount; ++CurrentFeature) {
1059 Log->logTensorValue(CurrentFeature,
1060 reinterpret_cast<const char *
>(
1061 getRunner().getTensorUntyped(CurrentFeature)));
1064 for (
size_t I = 0;
I < MUTR->extraOutputsForLoggingSpecs().
size();
1065 ++
I, ++CurrentFeature)
1066 Log->logTensorValue(
1068 reinterpret_cast<const char *
>(MUTR->getUntypedExtraOutputValue(
I)));
1070 Log->logTensorValue(CurrentFeature,
reinterpret_cast<const char *
>(&Ret));
1071 Log->endObservation();
1076 std::optional<float> CachedReward;
1077 auto GetReward = [&]() {
1079 CachedReward =
static_cast<float>(
1081 MF, getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI())
1083 return *CachedReward;
1086 getAnalysis<RegAllocEvictionAdvisorAnalysisLegacy>().logRewardIfNeeded(
1088 getAnalysis<RegAllocPriorityAdvisorAnalysisLegacy>().logRewardIfNeeded(
1094RegAllocEvictionAdvisorProvider *
1098 ?
new ReleaseModeEvictionAdvisorProvider(Ctx)
1104#if defined(LLVM_HAVE_TFLITE)
1105 return new DevelopmentModeEvictionAdvisorProvider(Ctx);
1114 ?
new ReleaseModeEvictionAdvisorAnalysisLegacy()
1119#if !defined(LLVM_HAVE_TFLITE)
1120bool RegAllocScoring::runOnMachineFunction(
MachineFunction &) {
return false; }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static constexpr unsigned long long mask(BlockVerifier::State S)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file implements a model runner wrapping an EmitC compiled ML model.
@ Available
We know the block is fully available. This is a fixpoint.
Module.h This file contains the declarations for the Module class.
This file provides helper functions for creating MLModelRunners and checking model validity in releas...
NoopSavedModelImpl CompiledModelType
static llvm::cl::opt< MLGORegAllocModelChoice > SelectedMLGORegAllocModel("regalloc-mlgo-model", llvm::cl::desc("Select the MLGO model to execute for register allocation:"), llvm::cl::init(MLGORegAllocModelChoice::Default), llvm::cl::values(clEnumValN(MLGORegAllocModelChoice::Default, "default", "Use standard heuristic") #define MLGO_MODEL(CLASS_NAME, CLI_FLAG) \ \))
static std::unique_ptr< MLModelRunner > createMLGORegAllocModelRunner(LLVMContext &Ctx, const std::vector< TensorSpec > &InputFeatures)
#define MLGO_MODEL(CLASS_NAME, CLI_FLAG)
static cl::opt< unsigned > MaxEvictionCount("mlregalloc-max-eviction-count", cl::Hidden, cl::desc("The maximum number of times a live range can be " "evicted before preventing it from being evicted"), cl::init(100))
#define RA_EVICT_FEATURES_LIST(M)
#define SET(ID, TYPE, VAL)
static cl::opt< std::string > InteractiveChannelBaseName("regalloc-evict-interactive-channel-base", cl::Hidden, cl::desc("Base file path for the interactive mode. The incoming filename should " "have the name <regalloc-evict-interactive-channel-base>.in, while the " "outgoing name should be " "<regalloc-evict-interactive-channel-base>.out"))
static cl::opt< unsigned > NumAllocatableRegs("mlregalloc-num-allocatable-regs", cl::Hidden, cl::desc("The number of eviction candidates the model sees. The model has " "one more column, for the live range seeking allocation"), cl::init(32))
#define _FEATURE_IDX(A, B, C, D)
#define _DECL_FEATURES(type, name, shape, _)
static unsigned getMaxAllocationOrderLength(const MachineFunction &MF, const RegisterClassInfo &RCI)
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
MachineRegisterInfo & MRI
SI optimize exec mask operations pre RA
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Iterator getOrderLimitEnd(unsigned OrderLimit) const
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
iterator find(const_arg_type_t< KeyT > Val)
FunctionPass class - This class is used to implement most global optimizations.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
This is an important class for using LLVM in a threaded context.
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.
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.
Wrapper class representing physical registers and target specific virtual registers.
static constexpr unsigned NoRegister
MLModelRunner interface: abstraction of a mechanism for evaluating a ML model.
virtual void switchContext(StringRef Name)
void * getTensorUntyped(size_t Index)
T * getTensor(I FeatureID)
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
double getBlockFreqRelativeToEntryBlock(const MachineBasicBlock *MBB) const
Compute the frequency of the block, relative to the entry block.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
defusechain_instr_iterator< true, true, true, true > reg_instr_nodbg_iterator
reg_instr_nodbg_iterator/reg_instr_nodbg_begin/reg_instr_nodbg_end - Walk all defs and uses of the sp...
A Module instance is used to store all the information related to an LLVM module.
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 ...
ImmutableAnalysis abstraction for fetching the Eviction Advisor.
virtual void logRewardIfNeeded(const MachineFunction &MF, function_ref< float()> GetReward)
RegAllocEvictionAdvisorAnalysisLegacy(AdvisorMode Mode)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Common provider for legacy and new pass managers.
virtual std::unique_ptr< RegAllocEvictionAdvisor > getAdvisor(const MachineFunction &MF, const RAGreedy &RA, MachineBlockFrequencyInfo *MBFI, MachineLoopInfo *Loops)=0
virtual void logRewardIfNeeded(const MachineFunction &MF, llvm::function_ref< float()> GetReward)
RegAllocEvictionAdvisorProvider(AdvisorMode Mode, LLVMContext &Ctx)
virtual bool canEvictHintInterference(const LiveInterval &VirtReg, MCRegister PhysReg, const SmallVirtRegSet &FixedRegisters) const =0
Find out if we can evict the live ranges occupying the given PhysReg, which is a hint (preferred regi...
virtual MCRegister tryFindEvictionCandidate(const LiveInterval &VirtReg, const AllocationOrder &Order, uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const =0
Find a physical register that can be freed by evicting the FixedRegisters, or return NoRegister.
LLVM_ABI_FOR_TEST double getScore() const
unsigned getNumAllocatableRegs(const TargetRegisterClass *RC) const
getNumAllocatableRegs - Returns the number of actually allocatable registers in RC in the current fun...
Wrapper class representing virtual and physical registers.
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
constexpr unsigned id() const
SlotIndex - An opaque wrapper around machine indexes.
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.
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)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static LLVM_ABI bool isRematerializable(const LiveInterval &LI, const LiveIntervals &LIS, const VirtRegMap &VRM, const MachineRegisterInfo &MRI, const TargetInstrInfo &TII)
Determine if all values in LI are rematerializable.
static LLVM_ABI Register copyHint(const MachineInstr *MI, Register Reg, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI)
Return the preferred allocation register for reg, given a COPY instruction.
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
SmallSet< Register, 16 > SmallVirtRegSet
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
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.
static const TensorSpec DecisionSpec
RegAllocScore calculateRegAllocScore(const MachineFunction &MF, const MachineBlockFrequencyInfo &MBFI)
Calculate a score.
bool isReleaseModelValid(StringRef InteractiveChannelBaseName, const cl::opt< EnumType, ExternalStorage, ParserClass > &SelectedModel, EnumType DefaultModelVal=EnumType::Default)
Helper to check if a release-mode ML advisor has a valid model to execute.
LLVM_ABI RegAllocEvictionAdvisorAnalysisLegacy * createDevelopmentModeAdvisorAnalysisLegacy()
auto reverse(ContainerTy &&C)
std::unique_ptr< MLModelRunner > createReleaseModeModelRunner(LLVMContext &Ctx, const std::vector< TensorSpec > &InputFeatures, StringRef DecisionName, const std::string &InteractiveChannelBaseName, const TensorSpec &InteractiveDecisionSpec, CreateEmitCFunc &&CreateEmitCModelRunner, const EmbeddedModelRunnerOptions &Options={})
Helper to construct the appropriate MLModelRunner in release mode:
static const std::vector< TensorSpec > InputFeatures
@ RS_Done
There is nothing more we can do to this live range.
std::string getLoggerContextName(StringRef Name, unsigned Number)
Context name for Name.
LLVM_ABI FunctionPass * createRegAllocScoringPass()
When learning an eviction policy, extract score(reward) information, otherwise this does nothing.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
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.
LLVM_ABI RegAllocEvictionAdvisorProvider * createReleaseModeAdvisorProvider(LLVMContext &Ctx)
static const std::vector< int64_t > PerLiveRangeShape
MCRegisterClass TargetRegisterClass
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Implement std::hash so that hash_code can be used in STL containers.