LLVM 19.0.0git
MLRegAllocPriorityAdvisor.cpp
Go to the documentation of this file.
1//===- MLRegAllocPriorityAdvisor.cpp - ML priority 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 priority advisor and reward injection pass
10//
11//===----------------------------------------------------------------------===//
12
13#include "AllocationOrder.h"
14#include "RegAllocGreedy.h"
27#include "llvm/CodeGen/Passes.h"
32#include "llvm/Pass.h"
33#include "llvm/PassRegistry.h"
35
36#if defined(LLVM_HAVE_TFLITE)
40#endif
41
42using namespace llvm;
43
45 "regalloc-priority-interactive-channel-base", cl::Hidden,
47 "Base file path for the interactive mode. The incoming filename should "
48 "have the name <regalloc-priority-interactive-channel-base>.in, while "
49 "the outgoing name should be "
50 "<regalloc-priority-interactive-channel-base>.out"));
51
53
54// Options that only make sense in development mode
55#ifdef LLVM_HAVE_TFLITE
56#include "RegAllocScore.h"
58
59static cl::opt<std::string> TrainingLog(
60 "regalloc-priority-training-log", cl::Hidden,
61 cl::desc("Training log for the register allocator priority model"));
62
63static cl::opt<std::string> ModelUnderTraining(
64 "regalloc-priority-model", cl::Hidden,
65 cl::desc("The model being trained for register allocation priority"));
66
67#endif // #ifdef LLVM_HAVE_TFLITE
68
69namespace llvm {
70
71static const std::vector<int64_t> PerLiveRangeShape{1};
72
73#define RA_PRIORITY_FEATURES_LIST(M) \
74 M(int64_t, li_size, PerLiveRangeShape, "size") \
75 M(int64_t, stage, PerLiveRangeShape, "stage") \
76 M(float, weight, PerLiveRangeShape, "weight")
77
78#define DecisionName "priority"
80 TensorSpec::createSpec<float>(DecisionName, {1});
81
82
83// Named features index.
85#define _FEATURE_IDX(_, name, __, ___) name,
87#undef _FEATURE_IDX
89};
90
92public:
94 SlotIndexes *const Indexes, MLModelRunner *Runner);
95
96protected:
98 return static_cast<const RegAllocPriorityAdvisor &>(DefaultAdvisor);
99 }
100
101 // The assumption is that if the Runner could not be constructed, we emit-ed
102 // error, and we shouldn't be asking for it here.
103 const MLModelRunner &getRunner() const { return *Runner; }
104 float getPriorityImpl(const LiveInterval &LI) const;
105 unsigned getPriority(const LiveInterval &LI) const override;
106
107private:
108 const DefaultPriorityAdvisor DefaultAdvisor;
109 MLModelRunner *const Runner;
110};
111
112#define _DECL_FEATURES(type, name, shape, _) \
113 TensorSpec::createSpec<type>(#name, shape),
114
115static const std::vector<TensorSpec> InputFeatures{
117};
118#undef _DECL_FEATURES
119
120// ===================================
121// Release (AOT) - specifics
122// ===================================
125public:
128 // support for isa<> and dyn_cast.
130 return R->getAdvisorMode() == AdvisorMode::Release;
131 }
132
133private:
134 void getAnalysisUsage(AnalysisUsage &AU) const override {
135 AU.setPreservesAll();
138 }
139
140 std::unique_ptr<RegAllocPriorityAdvisor>
141 getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
142 if (!Runner) {
143 if (InteractiveChannelBaseName.empty())
144 Runner = std::make_unique<ReleaseModeModelRunner<CompiledModelType>>(
146 else
147 Runner = std::make_unique<InteractiveModelRunner>(
151 }
152 return std::make_unique<MLPriorityAdvisor>(
153 MF, RA, &getAnalysis<SlotIndexes>(), Runner.get());
154 }
155 std::unique_ptr<MLModelRunner> Runner;
156};
157
158// ===================================
159// Development mode-specifics
160// ===================================
161//
162// Features we log
163#ifdef LLVM_HAVE_TFLITE
164static const TensorSpec Reward = TensorSpec::createSpec<float>("reward", {1});
165
166#define _DECL_TRAIN_FEATURES(type, name, shape, _) \
167 TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
168
169static const std::vector<TensorSpec> TrainingInputFeatures{
170 {RA_PRIORITY_FEATURES_LIST(_DECL_TRAIN_FEATURES)
171 TensorSpec::createSpec<float>("action_discount", {1}),
172 TensorSpec::createSpec<int32_t>("action_step_type", {1}),
173 TensorSpec::createSpec<float>("action_reward", {1})}};
174#undef _DECL_TRAIN_FEATURES
175
176class DevelopmentModePriorityAdvisor : public MLPriorityAdvisor {
177public:
178 DevelopmentModePriorityAdvisor(const MachineFunction &MF, const RAGreedy &RA,
179 SlotIndexes *const Indexes,
180 MLModelRunner *Runner, Logger *Log)
181 : MLPriorityAdvisor(MF, RA, Indexes, Runner), Log(Log) {}
182
183private:
184 unsigned getPriority(const LiveInterval &LI) const override;
185 Logger *const Log;
186};
187
188class DevelopmentModePriorityAdvisorAnalysis final
190public:
191 DevelopmentModePriorityAdvisorAnalysis()
193 // support for isa<> and dyn_cast.
194 static bool classof(const RegAllocPriorityAdvisorAnalysis *R) {
195 return R->getAdvisorMode() == AdvisorMode::Development;
196 }
197
198 void logRewardIfNeeded(const MachineFunction &MF,
199 llvm::function_ref<float()> GetReward) override {
200 if (!Log || !Log->hasAnyObservationForContext(MF.getName()))
201 return;
202 // The function pass manager would run all the function passes for a
203 // function, so we assume the last context belongs to this function. If
204 // this invariant ever changes, we can implement at that time switching
205 // contexts. At this point, it'd be an error
206 if (Log->currentContext() != MF.getName()) {
208 "The training log context shouldn't have had changed.");
209 }
210 if (Log->hasObservationInProgress())
211 Log->logReward<float>(GetReward());
212 }
213
214private:
215 void getAnalysisUsage(AnalysisUsage &AU) const override {
216 AU.setPreservesAll();
219 }
220
221 // Save all the logs (when requested).
222 bool doInitialization(Module &M) override {
223 LLVMContext &Ctx = M.getContext();
224 if (ModelUnderTraining.empty() && TrainingLog.empty()) {
225 Ctx.emitError("Regalloc development mode should be requested with at "
226 "least logging enabled and/or a training model");
227 return false;
228 }
229 if (ModelUnderTraining.empty())
230 Runner = std::make_unique<NoInferenceModelRunner>(Ctx, InputFeatures);
231 else
232 Runner = ModelUnderTrainingRunner::createAndEnsureValid(
233 Ctx, ModelUnderTraining, DecisionName, TrainingInputFeatures);
234 if (!Runner) {
235 Ctx.emitError("Regalloc: could not set up the model runner");
236 return false;
237 }
238 if (TrainingLog.empty())
239 return false;
240 std::error_code EC;
241 auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
242 if (EC) {
243 M.getContext().emitError(EC.message() + ":" + TrainingLog);
244 return false;
245 }
246 std::vector<TensorSpec> LFS = InputFeatures;
247 if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(Runner.get()))
248 append_range(LFS, MUTR->extraOutputsForLoggingSpecs());
249 // We always log the output; in particular, if we're not evaluating, we
250 // don't have an output spec json file. That's why we handle the
251 // 'normal' output separately.
252 LFS.push_back(DecisionSpec);
253
254 Log = std::make_unique<Logger>(std::move(OS), LFS, Reward,
255 /*IncludeReward*/ true);
256 return false;
257 }
258
259 std::unique_ptr<RegAllocPriorityAdvisor>
260 getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
261 if (!Runner)
262 return nullptr;
263 if (Log) {
264 Log->switchContext(MF.getName());
265 }
266
267 return std::make_unique<DevelopmentModePriorityAdvisor>(
268 MF, RA, &getAnalysis<SlotIndexes>(), Runner.get(), Log.get());
269 }
270
271 std::unique_ptr<MLModelRunner> Runner;
272 std::unique_ptr<Logger> Log;
273};
274#endif //#ifdef LLVM_HAVE_TFLITE
275
276} // namespace llvm
277
279 return llvm::isEmbeddedModelEvaluatorValid<CompiledModelType>() ||
282 : nullptr;
283}
284
286 const RAGreedy &RA,
287 SlotIndexes *const Indexes,
288 MLModelRunner *Runner)
289 : RegAllocPriorityAdvisor(MF, RA, Indexes), DefaultAdvisor(MF, RA, Indexes),
290 Runner(std::move(Runner)) {
291 assert(this->Runner);
292 Runner->switchContext(MF.getName());
293}
294
296 const unsigned Size = LI.getSize();
298
299 *Runner->getTensor<int64_t>(0) = static_cast<int64_t>(Size);
300 *Runner->getTensor<int64_t>(1) = static_cast<int64_t>(Stage);
301 *Runner->getTensor<float>(2) = static_cast<float>(LI.weight());
302
303 return Runner->evaluate<float>();
304}
305
307 return static_cast<unsigned>(getPriorityImpl(LI));
308}
309
310#ifdef LLVM_HAVE_TFLITE
312 return new DevelopmentModePriorityAdvisorAnalysis();
313}
314
315unsigned
316DevelopmentModePriorityAdvisor::getPriority(const LiveInterval &LI) const {
317 double Prio = 0;
318
319 if (isa<ModelUnderTrainingRunner>(getRunner())) {
321 } else {
322 Prio = getDefaultAdvisor().getPriority(LI);
323 }
324
325 if (TrainingLog.empty())
326 return Prio;
327
328 // TODO(mtrofin): when we support optional rewards, this can go away. In the
329 // meantime, we log the "pretend" reward (0) for the previous observation
330 // before starting a new one.
331 if (Log->hasObservationInProgress())
332 Log->logReward<float>(0.0);
333
334 Log->startObservation();
335 size_t CurrentFeature = 0;
336 for (; CurrentFeature < InputFeatures.size(); ++CurrentFeature) {
337 Log->logTensorValue(CurrentFeature,
338 reinterpret_cast<const char *>(
339 getRunner().getTensorUntyped(CurrentFeature)));
340 }
341
342 if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(&getRunner())) {
343 for (size_t I = 0; I < MUTR->extraOutputsForLoggingSpecs().size();
344 ++I, ++CurrentFeature)
345 Log->logTensorValue(
346 CurrentFeature,
347 reinterpret_cast<const char *>(MUTR->getUntypedExtraOutputValue(I)));
348 }
349
350 float Ret = static_cast<float>(Prio);
351 Log->logTensorValue(CurrentFeature, reinterpret_cast<const char *>(&Ret));
352 Log->endObservation();
353
354 return static_cast<unsigned>(Prio);
355}
356
357#endif // #ifdef LLVM_HAVE_TFLITE
uint64_t Size
#define I(x, y, z)
Definition: MD5.cpp:58
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"))
#define _FEATURE_IDX(A, B, C, D)
#define _DECL_FEATURES(type, name, shape, _)
#define DecisionName
static cl::opt< std::string > InteractiveChannelBaseName("regalloc-priority-interactive-channel-base", cl::Hidden, cl::desc("Base file path for the interactive mode. The incoming filename should " "have the name <regalloc-priority-interactive-channel-base>.in, while " "the outgoing name should be " "<regalloc-priority-interactive-channel-base>.out"))
#define RA_PRIORITY_FEATURES_LIST(M)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SI optimize exec mask operations pre RA
raw_pwrite_stream & OS
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:356
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void emitError(uint64_t LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:687
float weight() const
Definition: LiveInterval.h:719
unsigned getSize() const
getSize - Returns the sum of sizes of all the LiveRange's.
Logging utility - given an ordered specification of features, and assuming a scalar reward,...
MLModelRunner interface: abstraction of a mechanism for evaluating a ML model.
Definition: MLModelRunner.h:26
virtual void switchContext(StringRef Name)
Definition: MLModelRunner.h:54
T * getTensor(I FeatureID)
Definition: MLModelRunner.h:37
const MLModelRunner & getRunner() const
MLPriorityAdvisor(const MachineFunction &MF, const RAGreedy &RA, SlotIndexes *const Indexes, MLModelRunner *Runner)
const RegAllocPriorityAdvisor & getDefaultAdvisor() const
unsigned getPriority(const LiveInterval &LI) const override
Find the priority value for a live range.
float getPriorityImpl(const LiveInterval &LI) const
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Function & getFunction()
Return the LLVM function that this machine code represents.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A mock class satisfying the interface expected by ReleaseModeModelRunner for its TGen parameter.
LiveRangeStage getStage(Register Reg) const
const ExtraRegInfo & getExtraInfo() const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Interface to the priority advisor, which is responsible for prioritizing live ranges.
static bool classof(const RegAllocPriorityAdvisorAnalysis *R)
SlotIndexes pass.
Definition: SlotIndexes.h:300
An efficient, type-erasing, non-owning reference to a callable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
RegAllocPriorityAdvisorAnalysis * createReleaseModePriorityAdvisor()
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2073
static const TensorSpec DecisionSpec
const char *const DecisionName
static const std::vector< TensorSpec > InputFeatures
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:1849
RegAllocPriorityAdvisorAnalysis * createDevelopmentModePriorityAdvisor()
static const std::vector< int64_t > PerLiveRangeShape
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858