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"
57#if defined(LLVM_HAVE_MLIR_LOWERING_REGALLOC)
60#include "llvm/CodeGen/RegAllocEvictModels.h"
64#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) CLASS_NAME,
65#include "llvm/CodeGen/RegAllocEvictModels.def"
69 "regalloc-mlgo-model",
70 llvm::cl::desc(
"Select the MLGO model to execute for register allocation:"),
73 "Use standard heuristic")
74#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) \
75 ,
clEnumValN(MLGORegAllocModelChoice::CLASS_NAME, CLI_FLAG, \
76 "Use the " CLI_FLAG
" MLGO model")
77#include
"llvm/CodeGen/RegAllocEvictModels.def"
80static std::unique_ptr<MLModelRunner>
86#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) \
87 case MLGORegAllocModelChoice::CLASS_NAME: \
88 return std::make_unique<EmitCModelRunner<CLASS_NAME>>(Ctx, InputFeatures);
89#include "llvm/CodeGen/RegAllocEvictModels.def"
98static inline std::unique_ptr<MLModelRunner>
105 "regalloc-evict-interactive-channel-base",
cl::Hidden,
107 "Base file path for the interactive mode. The incoming filename should "
108 "have the name <regalloc-evict-interactive-channel-base>.in, while the "
109 "outgoing name should be "
110 "<regalloc-evict-interactive-channel-base>.out"));
114 cl::desc(
"The maximum number of times a live range can be "
115 "evicted before preventing it from being evicted"),
119#ifdef LLVM_HAVE_TFLITE
125 cl::desc(
"Training log for the register allocator eviction model"));
129 cl::desc(
"The model being trained for register allocation eviction"));
145 RegAllocScoring() : MachineFunctionPass(ID) {}
147 ~RegAllocScoring()
override =
default;
149 StringRef getPassName()
const override {
150 return "Register Allocation Pass Scoring";
154 void getAnalysisUsage(AnalysisUsage &AU)
const override {
156 AU.
addRequired<RegAllocEvictionAdvisorAnalysisLegacy>();
157 AU.
addRequired<RegAllocPriorityAdvisorAnalysisLegacy>();
158 AU.
addRequired<MachineBlockFrequencyInfoWrapperPass>();
167char RegAllocScoring::ID = 0;
169 return new RegAllocScoring();
173 "Register Allocation Scoring Pass",
false,
false)
201#define RA_EVICT_FEATURES_LIST(M) \
202 M(int64_t, mask, PerLiveRangeShape, \
203 "boolean values, 0 for unavailable candidates (i.e. if a position is 0, " \
205 "can't be evicted)") \
206 M(int64_t, is_free, PerLiveRangeShape, \
207 "boolean values, 1 if this phys reg is actually free (no interferences)") \
208 M(float, nr_urgent, PerLiveRangeShape, \
209 "number of 'urgent' intervals, normalized. Urgent are those that are OK " \
210 "to break cascades") \
211 M(float, nr_broken_hints, PerLiveRangeShape, \
212 "if this position were evicted, how many broken hints would there be") \
213 M(int64_t, is_hint, PerLiveRangeShape, \
214 "is this a preferred phys reg for the candidate") \
215 M(int64_t, is_local, PerLiveRangeShape, \
216 "is this live range local to a basic block") \
217 M(float, nr_rematerializable, PerLiveRangeShape, \
218 "nr rematerializable ranges") \
219 M(float, nr_defs_and_uses, PerLiveRangeShape, \
220 "bb freq - weighed nr defs and uses") \
221 M(float, weighed_reads_by_max, PerLiveRangeShape, \
222 "bb freq - weighed nr of reads, normalized") \
223 M(float, weighed_writes_by_max, PerLiveRangeShape, \
224 "bb feq - weighed nr of writes, normalized") \
225 M(float, weighed_read_writes_by_max, PerLiveRangeShape, \
226 "bb freq - weighed nr of uses that are both read and writes, normalized") \
227 M(float, weighed_indvars_by_max, PerLiveRangeShape, \
228 "bb freq - weighed nr of uses that are indvars, normalized") \
229 M(float, hint_weights_by_max, PerLiveRangeShape, \
230 "bb freq - weighed nr of uses that are hints, normalized") \
231 M(float, start_bb_freq_by_max, PerLiveRangeShape, \
232 "the freq in the start block, normalized") \
233 M(float, end_bb_freq_by_max, PerLiveRangeShape, \
234 "freq of end block, normalized") \
235 M(float, hottest_bb_freq_by_max, PerLiveRangeShape, \
236 "hottest BB freq, normalized") \
237 M(float, liverange_size, PerLiveRangeShape, \
238 "size (instr index diff) of the LR") \
239 M(float, use_def_density, PerLiveRangeShape, \
240 "the max weight, as computed by the manual heuristic") \
241 M(int64_t, max_stage, PerLiveRangeShape, \
242 "largest stage of an interval in this LR") \
243 M(int64_t, min_stage, PerLiveRangeShape, \
244 "lowest stage of an interval in this LR") \
245 M(float, progress, {1}, "ratio of current queue size to initial size")
251#define DecisionName "index_to_evict"
257#define _FEATURE_IDX_SIMPLE(_, name, __, ___) name
258#define _FEATURE_IDX(A, B, C, D) _FEATURE_IDX_SIMPLE(A, B, C, D),
261#undef _FEATURE_IDX_SIMPLE
268template <
typename T>
size_t getTotalSize(
const std::vector<int64_t> &Shape) {
269 size_t Ret =
sizeof(
T);
270 for (
const auto V : Shape)
276#define _RESET(TYPE, NAME, SHAPE, __) \
277 std::memset(Runner.getTensorUntyped(FeatureIDs::NAME), 0, \
278 getTotalSize<TYPE>(SHAPE));
285struct LIFeatureComponents {
289 double IndVarUpdates = 0;
290 double HintWeights = 0.0;
291 int64_t NumDefsAndUses = 0;
292 float HottestBlockFreq = 0.0;
293 bool IsRemat =
false;
296using CandidateRegList =
298using FeaturesListNormalizer =
322 tryFindEvictionCandidatePosition(
const LiveInterval &VirtReg,
324 unsigned OrderLimit,
uint8_t CostPerUseLimit,
345 int64_t IsHint, int64_t LocalIntfsCount,
float NumUrgent,
353 return getDefaultAdvisor().canEvictHintInterference(VirtReg, PhysReg,
357 const LIFeatureComponents &
371 std::bitset<FeatureIDs::FeatureCount> DoNotNormalize;
372 const float InitialQSize;
379 void onEviction(
Register RegBeingEvicted)
const {
383 ++VirtRegEvictionCounts[RegBeingEvicted.
id()];
387 auto EvictionCountIt = VirtRegEvictionCounts.
find(
Reg.id());
388 if (EvictionCountIt != VirtRegEvictionCounts.
end())
389 return EvictionCountIt->second;
394#define _DECL_FEATURES(type, name, shape, _) \
395 TensorSpec::createSpec<type>(#name, shape),
401class ReleaseModeEvictionAdvisorProvider final
404 ReleaseModeEvictionAdvisorProvider(
LLVMContext &Ctx)
410 return R->getAdvisorMode() == AdvisorMode::Release;
413 std::unique_ptr<RegAllocEvictionAdvisor>
424 "Invalid provider state: must have analysis available");
425 return std::make_unique<MLEvictAdvisor>(MF,
RA, Runner.get(), *MBFI,
431 std::unique_ptr<MLModelRunner> Runner;
434class ReleaseModeEvictionAdvisorAnalysisLegacy final
437 ReleaseModeEvictionAdvisorAnalysisLegacy()
447 std::make_unique<ReleaseModeEvictionAdvisorProvider>(M.getContext());
452 return R->getAdvisorMode() == AdvisorMode::Release;
466#ifdef LLVM_HAVE_TFLITE
473#define _DECL_TRAIN_FEATURES(type, name, shape, _) \
474 TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
476class DevelopmentModeEvictAdvisor :
public MLEvictAdvisor {
482 : MLEvictAdvisor(MF,
RA, Runner, MBFI,
Loops), Log(Log) {}
485 int64_t tryFindEvictionCandidatePosition(
487 unsigned OrderLimit,
uint8_t CostPerUseLimit,
493class DevelopmentModeEvictionAdvisorProvider final
496 DevelopmentModeEvictionAdvisorProvider(
LLVMContext &Ctx)
499 TrainingInputFeatures = {
504 if (ModelUnderTraining.empty() && TrainingLog.empty()) {
505 Ctx.emitError(
"Regalloc development mode should be requested with at "
506 "least logging enabled and/or a training model");
509 if (ModelUnderTraining.empty())
510 Runner = std::make_unique<NoInferenceModelRunner>(Ctx,
InputFeatures);
512 Runner = ModelUnderTrainingRunner::createAndEnsureValid(
513 Ctx, ModelUnderTraining,
DecisionName, TrainingInputFeatures);
515 Ctx.emitError(
"Regalloc: could not set up the model runner");
518 if (TrainingLog.empty())
521 auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
523 Ctx.emitError(EC.message() +
":" + TrainingLog);
534 Log = std::make_unique<Logger>(std::move(OS), LFS, Reward,
541 return R->getAdvisorMode() == AdvisorMode::Development;
546 if (!Log || !Log->hasAnyObservationForContext(MF.
getName()))
552 if (Log->currentContext() != MF.
getName()) {
554 "The training log context shouldn't have had changed.");
556 if (Log->hasObservationInProgress())
557 Log->logReward<
float>(GetReward());
560 std::unique_ptr<RegAllocEvictionAdvisor>
566 Log->switchContext(MF.
getName());
568 "Invalid provider state: must have analysis available");
569 return std::make_unique<DevelopmentModeEvictAdvisor>(
570 MF,
RA, Runner.get(), *MBFI, *
Loops, Log.get());
575 std::vector<TensorSpec> TrainingInputFeatures;
577 std::unique_ptr<MLModelRunner> Runner;
578 std::unique_ptr<Logger> Log;
581class DevelopmentModeEvictionAdvisorAnalysisLegacy final
584 DevelopmentModeEvictionAdvisorAnalysisLegacy()
588 Provider = std::make_unique<DevelopmentModeEvictionAdvisorProvider>(
595 Provider->logRewardIfNeeded(MF, GetReward);
600 return R->getAdvisorMode() == AdvisorMode::Development;
614 unsigned NumUsedRegs = 0;
615 for (
unsigned I = 0,
E = MRI.getNumVirtRegs();
I !=
E; ++
I) {
617 if (!MRI.reg_nodbg_empty(
Reg))
620 return static_cast<float>(NumUsedRegs);
629 InitialQSize(MLEvictAdvisor::getInitialQueueSize(MF)) {
632 DoNotNormalize.set(FeatureIDs::mask);
633 DoNotNormalize.set(FeatureIDs::is_free);
634 DoNotNormalize.set(FeatureIDs::is_hint);
635 DoNotNormalize.set(FeatureIDs::is_local);
636 DoNotNormalize.set(FeatureIDs::min_stage);
637 DoNotNormalize.set(FeatureIDs::max_stage);
638 DoNotNormalize.set(FeatureIDs::progress);
641int64_t MLEvictAdvisor::tryFindEvictionCandidatePosition(
644 int64_t Ret = Runner->
evaluate<int64_t>();
650bool MLEvictAdvisor::loadInterferenceFeatures(
661 const bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
662 int64_t LocalIntfs = 0;
663 float NumUrgent = 0.0f;
666 unsigned Cascade =
RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.
reg());
669 for (MCRegUnit Unit :
TRI->regunits(PhysReg)) {
674 if (IFIntervals.empty() && InterferingIntervals.
empty())
678 InterferingIntervals.
append(IFIntervals.begin(), IFIntervals.end());
680 assert(Intf->reg().isVirtual() &&
681 "Only expecting virtual register interference from query");
688 if (FixedRegisters.
count(Intf->reg()))
690 if (
RA.getExtraInfo().getStage(*Intf) ==
RS_Done)
694 (Intf->isSpillable() ||
695 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.
reg())) <
696 RegClassInfo.getNumAllocatableRegs(
697 MRI->getRegClass(Intf->reg())));
699 unsigned IntfCascade =
RA.getExtraInfo().getCascade(Intf->reg());
710 if (Cascade <= IntfCascade) {
716 LocalIntfs += (IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
717 (!EnableLocalReassign || !canReassign(*Intf, PhysReg)));
722 extractFeatures(InterferingIntervals, Largest, Pos, IsHint, LocalIntfs,
723 NumUrgent, LRPosInfo);
727MCRegister MLEvictAdvisor::tryFindEvictionCandidate(
730 auto MaybeOrderLimit = getOrderLimit(VirtReg, Order, CostPerUseLimit);
731 if (!MaybeOrderLimit)
733 unsigned OrderLimit = *MaybeOrderLimit;
741 const bool MustFindEviction =
747 resetInputs(*Runner);
752 CandidateRegList Regs;
753 Regs.fill({0,
false});
771 assert(!Regs[Pos].second);
773 if (!canAllocatePhysReg(CostPerUseLimit, PhysReg)) {
776 if (loadInterferenceFeatures(VirtReg, PhysReg,
I.isHint(), FixedRegisters,
777 Largest, Pos, LRPosInfo)) {
779 Regs[Pos] = std::make_pair(PhysReg,
true);
784 assert(!MustFindEviction);
787 const size_t ValidPosLimit = Pos;
791 if (!MustFindEviction)
796 assert(InitialQSize > 0.0 &&
"We couldn't have gotten here if we had "
797 "nothing to allocate initially.");
799 for (
auto &V : Largest)
809 *Runner->
getTensor<
float>(FeatureIDs::progress) =
810 static_cast<float>(
RA.getQueueSize()) / InitialQSize;
813 size_t CandidatePos = tryFindEvictionCandidatePosition(
814 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
817 assert(Regs[CandidatePos].second);
819 onEviction(VirtReg.
reg());
820 assert(!MustFindEviction);
823 assert(CandidatePos < ValidPosLimit);
829 for (MCRegUnit Unit :
TRI->regunits(Regs[CandidatePos].first)) {
833 onEviction(Intf->reg());
837 return Regs[CandidatePos].first;
840const LIFeatureComponents &
841MLEvictAdvisor::getLIFeatureComponents(
const LiveInterval &LI)
const {
842 RegID ID = LI.
reg().
id();
843 LIFeatureComponents
Empty;
844 auto I = CachedFeatures.insert(std::make_pair(ID,
Empty));
845 LIFeatureComponents &Ret =
I.first->getSecond();
853 I = MRI->reg_instr_nodbg_begin(LI.
reg()),
854 E = MRI->reg_instr_nodbg_end();
858 ++Ret.NumDefsAndUses;
862 if (
MI->isIdentityCopy() ||
MI->isImplicitDef())
866 std::tie(Reads, Writes) =
MI->readsWritesVirtualRegister(LI.
reg());
869 Ret.HottestBlockFreq = std::max(Freq, Ret.HottestBlockFreq);
871 Ret.R += (Reads && !Writes) * Freq;
872 Ret.W += (!Reads && Writes) * Freq;
873 Ret.RW += (Reads && Writes) * Freq;
875 auto *
MBB =
MI->getParent();
879 if (Writes && IsExiting && LIS->isLiveOutOfMBB(LI,
MBB))
880 Ret.IndVarUpdates += Freq;
883 Ret.HintWeights += Freq;
892void MLEvictAdvisor::extractFeatures(
895 int64_t LocalIntfsCount,
float NumUrgent,
897 int64_t NumDefsAndUses = 0;
898 int64_t NumBrokenHints = 0;
902 double IndVarUpdates = 0.0;
903 double HintWeights = 0.0;
904 float StartBBFreq = 0.0;
905 float EndBBFreq = 0.0;
906 float HottestBlockFreq = 0.0;
907 int32_t NumRematerializable = 0;
908 float TotalWeight = 0.0;
910 SlotIndex EndSI = LIS->getSlotIndexes()->getZeroIndex();
911 SlotIndex StartSI = LIS->getSlotIndexes()->getLastIndex();
912 int64_t MaxStage = 0;
914 Intervals.
empty() ? 0 : std::numeric_limits<int64_t>::max();
916 for (
const auto *L : Intervals) {
918 MaxStage = std::max<int64_t>(
919 MaxStage,
static_cast<int64_t
>(
RA.getExtraInfo().getStage(LI)));
920 MinStage = std::min<int64_t>(
921 MinStage,
static_cast<int64_t
>(
RA.getExtraInfo().getStage(LI)));
923 TotalWeight = std::max(TotalWeight, LI.
weight());
930 const LIFeatureComponents &LIFC = getLIFeatureComponents(LI);
931 NumBrokenHints += VRM->hasPreferredPhys(LI.
reg());
933 NumDefsAndUses += LIFC.NumDefsAndUses;
934 HottestBlockFreq = std::max(HottestBlockFreq, LIFC.HottestBlockFreq);
939 IndVarUpdates += LIFC.IndVarUpdates;
941 HintWeights += LIFC.HintWeights;
942 NumRematerializable += LIFC.IsRemat;
945 if (!Intervals.empty()) {
948 if (EndSI >= LIS->getSlotIndexes()->getLastIndex())
949 EndSI = LIS->getSlotIndexes()->getLastIndex().
getPrevIndex();
955#define SET(ID, TYPE, VAL) \
957 Runner->getTensor<TYPE>(FeatureIDs::ID)[Pos] = static_cast<TYPE>(VAL); \
958 if (!DoNotNormalize.test(FeatureIDs::ID)) \
959 Largest[FeatureIDs::ID] = \
960 std::max(Largest[FeatureIDs::ID], static_cast<float>(VAL)); \
963 SET(is_free, int64_t, Intervals.empty());
964 SET(nr_urgent,
float, NumUrgent);
965 SET(nr_broken_hints,
float, NumBrokenHints);
966 SET(is_hint, int64_t, IsHint);
967 SET(is_local, int64_t, LocalIntfsCount);
968 SET(nr_rematerializable,
float, NumRematerializable);
969 SET(nr_defs_and_uses,
float, NumDefsAndUses);
970 SET(weighed_reads_by_max,
float, R);
971 SET(weighed_writes_by_max,
float, W);
972 SET(weighed_read_writes_by_max,
float, RW);
973 SET(weighed_indvars_by_max,
float, IndVarUpdates);
974 SET(hint_weights_by_max,
float, HintWeights);
975 SET(start_bb_freq_by_max,
float, StartBBFreq);
976 SET(end_bb_freq_by_max,
float, EndBBFreq);
977 SET(hottest_bb_freq_by_max,
float, HottestBlockFreq);
978 SET(liverange_size,
float,
Size);
979 SET(use_def_density,
float, TotalWeight);
980 SET(max_stage, int64_t, MaxStage);
981 SET(min_stage, int64_t, MinStage);
986#ifdef LLVM_HAVE_TFLITE
990 return new DevelopmentModeEvictionAdvisorAnalysisLegacy();
993int64_t DevelopmentModeEvictAdvisor::tryFindEvictionCandidatePosition(
995 unsigned OrderLimit,
uint8_t CostPerUseLimit,
999 Ret = MLEvictAdvisor::tryFindEvictionCandidatePosition(
1000 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
1002 MCRegister PhysReg = getDefaultAdvisor().tryFindEvictionCandidate(
1003 VirtReg, Order, CostPerUseLimit, FixedRegisters);
1015 if (TrainingLog.empty())
1020 if (
Log->hasObservationInProgress())
1021 Log->logReward<
float>(0.0);
1023 Log->startObservation();
1024 size_t CurrentFeature = 0;
1026 for (; CurrentFeature <
FeatureCount; ++CurrentFeature) {
1027 Log->logTensorValue(CurrentFeature,
1028 reinterpret_cast<const char *
>(
1029 getRunner().getTensorUntyped(CurrentFeature)));
1032 for (
size_t I = 0;
I < MUTR->extraOutputsForLoggingSpecs().
size();
1033 ++
I, ++CurrentFeature)
1034 Log->logTensorValue(
1036 reinterpret_cast<const char *
>(MUTR->getUntypedExtraOutputValue(
I)));
1038 Log->logTensorValue(CurrentFeature,
reinterpret_cast<const char *
>(&Ret));
1039 Log->endObservation();
1044 std::optional<float> CachedReward;
1045 auto GetReward = [&]() {
1047 CachedReward =
static_cast<float>(
1049 MF, getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI())
1051 return *CachedReward;
1054 getAnalysis<RegAllocEvictionAdvisorAnalysisLegacy>().logRewardIfNeeded(
1056 getAnalysis<RegAllocPriorityAdvisorAnalysisLegacy>().logRewardIfNeeded(
1062RegAllocEvictionAdvisorProvider *
1066 ?
new ReleaseModeEvictionAdvisorProvider(Ctx)
1072#if defined(LLVM_HAVE_TFLITE)
1073 return new DevelopmentModeEvictionAdvisorProvider(Ctx);
1082 ?
new ReleaseModeEvictionAdvisorAnalysisLegacy()
1087#if !defined(LLVM_HAVE_TFLITE)
1088bool 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 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))
static std::unique_ptr< MLModelRunner > createMLGORegAllocModelRunner(LLVMContext &, const std::vector< TensorSpec > &)
static const MLGORegAllocModelChoice SelectedMLGORegAllocModel
#define RA_EVICT_FEATURES_LIST(M)
constexpr bool HaveMLIRLoweringRegAlloc
#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, _)
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
SI optimize exec mask operations pre RA
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
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.
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. Should be passed by value.
static constexpr unsigned NoRegister
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.
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
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)
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
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)
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...
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_ATTRIBUTE_RETURNS_NONNULL LLVM_ABI RegAllocEvictionAdvisorProvider * createReleaseModeAdvisorProvider(LLVMContext &Ctx)
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 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.