LLVM 24.0.0git
Scheduler.h
Go to the documentation of this file.
1//===- Scheduler.h ----------------------------------------------*- C++ -*-===//
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// This is the bottom-up list scheduler used by the vectorizer. It is used for
10// checking the legality of vectorization and for scheduling instructions in
11// such a way that makes vectorization possible, if legal.
12//
13// The legality check is performed by `trySchedule(Instrs)`, which will try to
14// schedule the IR until all instructions in `Instrs` can be scheduled together
15// back-to-back. If this fails then it is illegal to vectorize `Instrs`.
16//
17// Internally the scheduler uses the vectorizer-specific DependencyGraph class.
18//
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_TRANSFORMS_VECTORIZE_SANDBOXVECTORIZER_SCHEDULER_H
22#define LLVM_TRANSFORMS_VECTORIZE_SANDBOXVECTORIZER_SCHEDULER_H
23
27#include <queue>
28#include <variant>
29
30namespace llvm::sandboxir {
31
33public:
34 bool operator()(const DGNode *N1, const DGNode *N2) {
35 // Given that the DAG does not model dependencies such that PHIs are always
36 // at the top, or terminators always at the bottom, we need to force the
37 // priority here in the comparator of the ready list container.
38 auto *I1 = N1->getInstruction();
39 auto *I2 = N2->getInstruction();
40 bool IsTerm1 = I1->isTerminator();
41 bool IsTerm2 = I2->isTerminator();
42 if (IsTerm1 != IsTerm2)
43 // Terminators have the lowest priority.
44 return IsTerm1 > IsTerm2;
45 bool IsPHI1 = isa<PHINode>(I1);
46 bool IsPHI2 = isa<PHINode>(I2);
47 if (IsPHI1 != IsPHI2)
48 // PHIs have the highest priority.
49 return IsPHI1 < IsPHI2;
50 // Otherwise rely on the instruction order.
51 return I2->comesBefore(I1);
52 }
53};
54
55/// The list holding nodes that are ready to schedule. Used by the scheduler.
57 PriorityCmp Cmp;
58 /// Control/Other dependencies are not modeled by the DAG to save memory.
59 /// These have to be modeled in the ready list for correctness.
60 /// This means that the list will hold back nodes that need to meet such
61 /// unmodeled dependencies.
62 std::priority_queue<DGNode *, std::vector<DGNode *>, PriorityCmp> List;
63
64public:
65 ReadyListContainer() : List(Cmp) {}
66 void insert(DGNode *N) {
67#ifndef NDEBUG
68 assert(!N->scheduled() && "Don't insert a scheduled node!");
69 assert(!contains(N) && "Node already exists in ready list!");
70#endif
71 List.push(N);
72 }
74 auto *Back = List.top();
75 List.pop();
76 return Back;
77 }
78 bool empty() const { return List.empty(); }
79 void clear() { List = {}; }
80 bool contains(DGNode *N) const {
81 // TODO: We should update the data structure to make this O(1).
82 auto ListCopy = List;
83 while (!ListCopy.empty()) {
84 DGNode *Top = ListCopy.top();
85 if (Top == N)
86 return true;
87 ListCopy.pop();
88 }
89 return false;
90 }
91 /// \Removes \p N if found in the ready list.
92 void remove(DGNode *N) {
93 // TODO: Use a more efficient data-structure for the ready list because the
94 // priority queue does not support fast removals.
96 Keep.reserve(List.size());
97 while (!List.empty()) {
98 auto *Top = List.top();
99 List.pop();
100 if (Top == N)
101 break;
102 Keep.push_back(Top);
103 }
104 for (auto *KeepN : Keep)
105 List.push(KeepN);
106 }
107#ifndef NDEBUG
108 void dump(raw_ostream &OS) const;
109 LLVM_DUMP_METHOD void dump() const;
110#endif // NDEBUG
111};
112
113/// The nodes that need to be scheduled back-to-back in a single scheduling
114/// cycle form a SchedBundle.
116public:
118
119private:
120 ContainerTy Nodes;
121
122 /// Called by the DGNode destructor to avoid accessing freed memory.
123 void eraseFromBundle(DGNode *N) { llvm::erase(Nodes, N); }
124 friend void DGNode::setSchedBundle(SchedBundle &); // For eraseFromBunde().
125 friend DGNode::~DGNode(); // For eraseFromBundle().
126
127public:
128 SchedBundle() = default;
129 SchedBundle(ContainerTy &&Nodes) : Nodes(std::move(Nodes)) {
130 for (auto *N : this->Nodes)
131 N->setSchedBundle(*this);
132 }
133 /// Copy CTOR (unimplemented).
134 SchedBundle(const SchedBundle &Other) = delete;
135 /// Copy Assignment (unimplemented).
138 for (auto *N : this->Nodes)
139 N->clearSchedBundle();
140 }
141 bool empty() const { return Nodes.empty(); }
142 /// Singleton bundles are created when scheduling instructions temporarily to
143 /// fill in the schedule until we schedule the vector bundle. These are
144 /// non-vector bundles containing just a single instruction.
145 bool isSingleton() const { return Nodes.size() == 1u; }
146 DGNode *back() const { return Nodes.back(); }
149 iterator begin() { return Nodes.begin(); }
150 iterator end() { return Nodes.end(); }
151 const_iterator begin() const { return Nodes.begin(); }
152 const_iterator end() const { return Nodes.end(); }
153 /// \Returns the bundle node that comes before the others in program order.
154 LLVM_ABI DGNode *getTop() const;
155 /// \Returns the bundle node that comes after the others in program order.
156 LLVM_ABI DGNode *getBot() const;
157 /// Move all bundle instructions to \p Where back-to-back.
159 /// \Returns true if all nodes in the bundle are ready.
160 bool ready(SchedDirection Dir) const {
161 return all_of(Nodes, [](const auto *N) { return N->ready(); });
162 }
163#ifndef NDEBUG
164 void dump(raw_ostream &OS) const;
165 LLVM_DUMP_METHOD void dump() const;
166#endif
167};
168
169/// The scheduling point in the context of the Scheduler points to the
170/// top-of-schedule (i.e., the top-most instruction of the top bundle) during
171/// bottom-up scheduling or the bottom of the schedule (i.e., the bottom-most
172/// instruction of the bottom bundle) during top-down.
173///
174/// This class can be thought of as an extended BB::iterator, one that can
175/// not only point to after the last instruction in a BB (i.e., BB.end()), but
176/// also before the first instruction (i.e., something equivalent to
177/// prev(BB.begin()), which is not a legal BasicBlock::iterator).
178///
179/// This is needed for symmetric implementations of top-down and bottom-up
180/// scheduling. More specifically, if this is the first scheduling attempt we
181/// need the scheduling front to still point to a hypothetical last scheduling
182/// point. In bottom-up this can be at BB.end() but in top-down this can be
183/// before BB.begin(). This is why a BasicBlock::iterator is not suitable for
184/// this.
185class SchedulingPoint {
186 /// If Where contains a Block, then we are pointing before BB.begin(),
187 /// otherwise if it contains an iterator then we point to anywhere in the BB
188 /// or at BB.end().
189 std::variant<BasicBlock::iterator, BasicBlock *> Where;
190
191 /// Creates a scheduling point pointing before the beginning of BB.
192 SchedulingPoint(BasicBlock &BB) : Where(&BB) {}
193
194public:
195 /// Creates a scheduling point pointing at \p It, meaning any instruction in a
196 /// BB or BB.end().
198 /// Returns a SchedulingPoint that points to \p It.
199 static SchedulingPoint createAt(BasicBlock::iterator It) {
200 return SchedulingPoint(It);
201 }
202 /// Returns a SchedulingPoint that points to one element before \p It.
203 static SchedulingPoint createBefore(BasicBlock::iterator It) {
204 BasicBlock &BB = *It.getNodeParent();
205 if (It == BB.begin())
206 return SchedulingPoint(BB);
207 return SchedulingPoint(std::prev(It));
208 }
209 /// Returns a SchedulingPoint that points to one element after \p It.
210 static SchedulingPoint createAfter(BasicBlock::iterator It) {
211 assert(It != It.getNodeParent()->end() && "Already at end!");
212 return SchedulingPoint(std::next(It));
213 }
214
215 /// If the SchedulingPoint points to before the beginning of a BB, then this
216 /// returns that BB, else returns nullptr.
218 if (std::holds_alternative<BasicBlock::iterator>(Where))
219 return nullptr;
220 return std::get<BasicBlock *>(Where);
221 }
222 /// If the SchedulingPoint points after the last instruction in the BB then
223 /// this returns the corresponding BasicBlock, nullptr otherwise.
225 if (std::holds_alternative<BasicBlock *>(Where))
226 return nullptr;
227 auto It = std::get<BasicBlock::iterator>(Where);
228 return It == It.getNodeParent()->end() ? It.getNodeParent() : nullptr;
229 }
230 /// Returns the instruction pointed to by this SchedulingPoint or null if we
231 /// are before/after BB.
234 return nullptr;
235 return &*std::get<BasicBlock::iterator>(Where);
236 }
237 /// Cast to Instruction *. Asserts that we are pointing to an instruction and
238 /// not before/after the beginning/end of a BB.
239 operator Instruction *() const { return atInstrOrNull(); }
240 /// Returns the corresponding BB::iterator. Asserts that we are not pointing
241 /// before BB begin.
243 assert(!atBeforeBeginOrNull() && "Expected in/after BB!");
244 return std::get<BasicBlock::iterator>(Where);
245 }
246 operator BasicBlock::iterator() const { return getIterator(); }
247 /// Returns the SchedulingPoint pointing after this.
248 SchedulingPoint getNext() const {
249 assert(!atEndOrNull() && "Expected before/in BB!");
251 return BB->begin();
252 return std::next(getIterator());
253 }
254 /// Returns the SchedulingPoint pointing before this.
255 SchedulingPoint getPrev() const {
256 assert(!atBeforeBeginOrNull() && "Expected in/after BB!");
257 auto It = getIterator();
258 auto *BB = It.getNodeParent();
259 if (It == BB->begin())
260 return *BB;
261 return std::prev(It);
262 }
263 bool operator==(const SchedulingPoint &Other) const {
264 return Where == Other.Where;
265 }
266#ifndef NDEBUG
267 void print(raw_ostream &OS) const;
268 LLVM_DUMP_METHOD void dump() const;
269#endif
270};
271
272/// The list scheduler.
273class Scheduler {
274 /// This is a list-scheduler and this is the list containing the instructions
275 /// that are ready, meaning that all their dependency successors have already
276 /// been scheduled.
277 ReadyListContainer ReadyList;
278 /// The dependency graph is used by the scheduler to determine the legal
279 /// ordering of instructions.
280 DependencyGraph DAG;
281 friend class SchedulerInternalsAttorney; // For DAG.
282 Context &Ctx;
283 /// This is the top of the schedule during bottom-up scheduling and the bottom
284 /// of the schedule during top-down. It points to the position of the last
285 /// top-most/bottom-most instruction scheduled. It may get updated after every
286 /// trySchedule() attempt, regardless of whether scheduling succeeded or not.
287 /// It is nullopt if we have not scheduled before.
288 std::optional<SchedulingPoint> ScheduleTopItOpt;
289 // TODO: This is wasting memory in exchange for fast removal using a raw ptr.
291 /// The BB that we are currently scheduling.
292 BasicBlock *ScheduledBB = nullptr;
293 /// The ID of the callback we register with Sandbox IR.
294 std::optional<Context::CallbackID> CreateInstrCB;
295 /// Called by Sandbox IR's callback system, after \p I has been created.
296 /// NOTE: This should run after DAG's callback has run.
297 // TODO: Perhaps call DAG's notify function from within this one?
298 LLVM_ABI void notifyCreateInstr(Instruction *I);
299
300 /// \Returns a scheduling bundle containing \p Instrs.
301 SchedBundle *createBundle(ArrayRef<Instruction *> Instrs);
302 void eraseBundle(SchedBundle *SB);
303 /// Schedule nodes until we can schedule \p Instrs back-to-back.
304 bool tryScheduleUntil(ArrayRef<Instruction *> Instrs);
305 /// Schedules all nodes in \p Bndl, marks them as scheduled, updates the
306 /// UnscheduledSuccs counter of all dependency predecessors, and adds any of
307 /// them that become ready to the ready list.
308 void scheduleAndUpdateReadyList(SchedBundle &Bndl);
309 /// The scheduling state of the instructions in the bundle.
310 enum class BndlSchedState {
311 NoneScheduled, ///> No instruction in the bundle was previously scheduled.
312 AlreadyScheduled, ///> At least one instruction in the bundle belongs to a
313 /// different non-singleton scheduling bundle.
314 TemporarilyScheduled, ///> Instructions were temporarily scheduled as
315 /// singleton bundles or some of them were not
316 /// scheduled at all. None of them were in a vector
317 ///(non-singleton) bundle.
318 FullyScheduled, ///> All instrs in the bundle were previously scheduled and
319 /// were in the same SchedBundle.
320 };
321 /// \Returns whether none/some/all of \p Instrs have been scheduled.
322 LLVM_ABI BndlSchedState
323 getBndlSchedState(ArrayRef<Instruction *> Instrs) const;
324 /// Destroy the top-most part of the schedule that includes \p Instrs.
325 void trimSchedule(ArrayRef<Instruction *> Instrs);
326 /// Disable copies.
327 Scheduler(const Scheduler &) = delete;
328 Scheduler &operator=(const Scheduler &) = delete;
329
330private:
332
333public:
335 : DAG(Dir, AA, Ctx), Ctx(Ctx), Dir(Dir) {
336 // NOTE: The scheduler's callback depends on the DAG's callback running
337 // before it and updating the DAG accordingly.
338 CreateInstrCB = Ctx.registerCreateInstrCallback(
339 [this](Instruction *I) { notifyCreateInstr(I); });
340 }
342 if (CreateInstrCB)
343 Ctx.unregisterCreateInstrCallback(*CreateInstrCB);
344 }
345 /// Tries to build a schedule that includes all of \p Instrs scheduled at the
346 /// same scheduling cycle. This essentially checks that there are no
347 /// dependencies among \p Instrs. This function may involve scheduling
348 /// intermediate instructions or canceling and re-scheduling if needed.
349 /// \Returns true on success, false otherwise.
351 /// Clear the scheduler's state, including the DAG.
352 void clear() {
353 Bndls.clear();
354 // TODO: clear view once it lands.
355 DAG.clear();
356 ReadyList.clear();
357 ScheduleTopItOpt = std::nullopt;
358 ScheduledBB = nullptr;
359 assert(Bndls.empty() && DAG.empty() && ReadyList.empty() &&
360 !ScheduleTopItOpt && ScheduledBB == nullptr &&
361 "Expected empty state!");
362 }
363
364#ifndef NDEBUG
365 void dump(raw_ostream &OS) const;
366 LLVM_DUMP_METHOD void dump() const;
367#endif
368};
369
370/// A client-attorney class for accessing the Scheduler's internals (used for
371/// unit tests).
373public:
374 static DependencyGraph &getDAG(Scheduler &Sched) { return Sched.DAG; }
375 using BndlSchedState = Scheduler::BndlSchedState;
378 return Sched.getBndlSchedState(Instrs);
379 }
380};
381
382} // namespace llvm::sandboxir
383
384#endif // LLVM_TRANSFORMS_VECTORIZE_SANDBOXVECTORIZER_SCHEDULER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
#define I(x, y, z)
Definition MD5.cpp:57
PostRA Machine Instruction Scheduler
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A DependencyGraph Node that points to an Instruction and contains memory dependency edges.
void setSchedBundle(SchedBundle &SB)
Instruction * getInstruction() const
A sandboxir::User with operands, opcode and linked with previous/next instructions in an instruction ...
Definition Instruction.h:43
bool operator()(const DGNode *N1, const DGNode *N2)
Definition Scheduler.h:34
The list holding nodes that are ready to schedule. Used by the scheduler.
Definition Scheduler.h:56
LLVM_DUMP_METHOD void dump() const
Definition Scheduler.cpp:63
void remove(DGNode *N)
\Removes N if found in the ready list.
Definition Scheduler.h:92
bool contains(DGNode *N) const
Definition Scheduler.h:80
The nodes that need to be scheduled back-to-back in a single scheduling cycle form a SchedBundle.
Definition Scheduler.h:115
LLVM_ABI DGNode * getBot() const
\Returns the bundle node that comes after the others in program order.
Definition Scheduler.cpp:24
SchedBundle(ContainerTy &&Nodes)
Definition Scheduler.h:129
SchedBundle & operator=(const SchedBundle &Other)=delete
Copy Assignment (unimplemented).
LLVM_ABI DGNode * getTop() const
\Returns the bundle node that comes before the others in program order.
Definition Scheduler.cpp:15
bool isSingleton() const
Singleton bundles are created when scheduling instructions temporarily to fill in the schedule until ...
Definition Scheduler.h:145
SmallVector< DGNode *, 4 > ContainerTy
Definition Scheduler.h:117
const_iterator begin() const
Definition Scheduler.h:151
LLVM_DUMP_METHOD void dump() const
Definition Scheduler.cpp:48
SchedBundle(const SchedBundle &Other)=delete
Copy CTOR (unimplemented).
ContainerTy::iterator iterator
Definition Scheduler.h:147
const_iterator end() const
Definition Scheduler.h:152
ContainerTy::const_iterator const_iterator
Definition Scheduler.h:148
LLVM_ABI void cluster(BasicBlock::iterator Where)
Move all bundle instructions to Where back-to-back.
Definition Scheduler.cpp:33
bool ready(SchedDirection Dir) const
\Returns true if all nodes in the bundle are ready.
Definition Scheduler.h:160
A client-attorney class for accessing the Scheduler's internals (used for unit tests).
Definition Scheduler.h:372
static BndlSchedState getBndlSchedState(const Scheduler &Sched, ArrayRef< Instruction * > Instrs)
Definition Scheduler.h:376
Scheduler::BndlSchedState BndlSchedState
Definition Scheduler.h:375
static DependencyGraph & getDAG(Scheduler &Sched)
Definition Scheduler.h:374
The list scheduler.
Definition Scheduler.h:273
friend class SchedulerInternalsAttorney
Definition Scheduler.h:281
LLVM_DUMP_METHOD void dump() const
LLVM_ABI bool trySchedule(ArrayRef< Instruction * > Instrs)
Tries to build a schedule that includes all of Instrs scheduled at the same scheduling cycle.
void clear()
Clear the scheduler's state, including the DAG.
Definition Scheduler.h:352
Scheduler(AAResults &AA, Context &Ctx, SchedDirection Dir)
Definition Scheduler.h:334
SchedulingPoint getNext() const
Returns the SchedulingPoint pointing after this.
Definition Scheduler.h:248
BasicBlock * atEndOrNull() const
If the SchedulingPoint points after the last instruction in the BB then this returns the correspondin...
Definition Scheduler.h:224
Instruction * atInstrOrNull() const
Returns the instruction pointed to by this SchedulingPoint or null if we are before/after BB.
Definition Scheduler.h:232
LLVM_DUMP_METHOD void dump() const
Definition Scheduler.cpp:77
SchedulingPoint getPrev() const
Returns the SchedulingPoint pointing before this.
Definition Scheduler.h:255
BasicBlock::iterator getIterator() const
Returns the corresponding BB::iterator.
Definition Scheduler.h:242
BasicBlock * atBeforeBeginOrNull() const
If the SchedulingPoint points to before the beginning of a BB, then this returns that BB,...
Definition Scheduler.h:217
static SchedulingPoint createAt(BasicBlock::iterator It)
Returns a SchedulingPoint that points to It.
Definition Scheduler.h:199
static SchedulingPoint createBefore(BasicBlock::iterator It)
Returns a SchedulingPoint that points to one element before It.
Definition Scheduler.h:203
SchedulingPoint(BasicBlock::iterator It)
Creates a scheduling point pointing at It, meaning any instruction in a BB or BB.end().
Definition Scheduler.h:197
bool operator==(const SchedulingPoint &Other) const
Definition Scheduler.h:263
void print(raw_ostream &OS) const
Definition Scheduler.cpp:68
static SchedulingPoint createAfter(BasicBlock::iterator It)
Returns a SchedulingPoint that points to one element after It.
Definition Scheduler.h:210
Abstract Attribute helper functions.
Definition Attributor.h:165
BasicBlock(llvm::BasicBlock *BB, Context &SBCtx)
Definition BasicBlock.h:75
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
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
@ Other
Any other memory.
Definition ModRef.h:68
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
@ Keep
No function return thunk.
Definition CodeGen.h:229
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N