1 //==- MachineScheduler.h - MachineInstr Scheduling Pass ----------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides an interface for customizing the standard MachineScheduler
11 // pass. Note that the entire pass may be replaced as follows:
13 // <Target>TargetMachine::createPassConfig(PassManagerBase &PM) {
14 // PM.substitutePass(&MachineSchedulerID, &CustomSchedulerPassID);
17 // The MachineScheduler pass is only responsible for choosing the regions to be
18 // scheduled. Targets can override the DAG builder and scheduler without
19 // replacing the pass as follows:
21 // ScheduleDAGInstrs *<Target>PassConfig::
22 // createMachineScheduler(MachineSchedContext *C) {
23 // return new CustomMachineScheduler(C);
26 // The default scheduler, ScheduleDAGMI, builds the DAG and drives list
27 // scheduling while updating the instruction stream, register pressure, and live
28 // intervals. Most targets don't need to override the DAG builder and list
29 // schedulier, but subtargets that require custom scheduling heuristics may
30 // plugin an alternate MachineSchedStrategy. The strategy is responsible for
31 // selecting the highest priority node from the list:
33 // ScheduleDAGInstrs *<Target>PassConfig::
34 // createMachineScheduler(MachineSchedContext *C) {
35 // return new ScheduleDAGMI(C, CustomStrategy(C));
38 // The DAG builder can also be customized in a sense by adding DAG mutations
39 // that will run after DAG building and before list scheduling. DAG mutations
40 // can adjust dependencies based on target-specific knowledge or add weak edges
43 // ScheduleDAGInstrs *<Target>PassConfig::
44 // createMachineScheduler(MachineSchedContext *C) {
45 // ScheduleDAGMI *DAG = new ScheduleDAGMI(C, CustomStrategy(C));
46 // DAG->addMutation(new CustomDependencies(DAG->TII, DAG->TRI));
50 // A target that supports alternative schedulers can use the
51 // MachineSchedRegistry to allow command line selection. This can be done by
52 // implementing the following boilerplate:
54 // static ScheduleDAGInstrs *createCustomMachineSched(MachineSchedContext *C) {
55 // return new CustomMachineScheduler(C);
57 // static MachineSchedRegistry
58 // SchedCustomRegistry("custom", "Run my target's custom scheduler",
59 // createCustomMachineSched);
62 // Finally, subtargets that don't need to implement custom heuristics but would
63 // like to configure the GenericScheduler's policy for a given scheduler region,
64 // including scheduling direction and register pressure tracking policy, can do
67 // void <SubTarget>Subtarget::
68 // overrideSchedPolicy(MachineSchedPolicy &Policy,
69 // MachineInstr *begin,
71 // unsigned NumRegionInstrs) const {
72 // Policy.<Flag> = true;
75 //===----------------------------------------------------------------------===//
77 #ifndef LLVM_CODEGEN_MACHINESCHEDULER_H
78 #define LLVM_CODEGEN_MACHINESCHEDULER_H
80 #include "llvm/CodeGen/MachinePassRegistry.h"
81 #include "llvm/CodeGen/RegisterPressure.h"
82 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
86 extern cl::opt<bool> ForceTopDown;
87 extern cl::opt<bool> ForceBottomUp;
91 class MachineDominatorTree;
92 class MachineLoopInfo;
93 class RegisterClassInfo;
94 class ScheduleDAGInstrs;
96 class ScheduleHazardRecognizer;
98 /// MachineSchedContext provides enough context from the MachineScheduler pass
99 /// for the target to instantiate a scheduler.
100 struct MachineSchedContext {
102 const MachineLoopInfo *MLI;
103 const MachineDominatorTree *MDT;
104 const TargetPassConfig *PassConfig;
108 RegisterClassInfo *RegClassInfo;
110 MachineSchedContext();
111 virtual ~MachineSchedContext();
114 /// MachineSchedRegistry provides a selection of available machine instruction
116 class MachineSchedRegistry : public MachinePassRegistryNode {
118 typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineSchedContext *);
120 // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
121 typedef ScheduleDAGCtor FunctionPassCtor;
123 static MachinePassRegistry Registry;
125 MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
126 : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
129 ~MachineSchedRegistry() { Registry.Remove(this); }
133 MachineSchedRegistry *getNext() const {
134 return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
136 static MachineSchedRegistry *getList() {
137 return (MachineSchedRegistry *)Registry.getList();
139 static void setListener(MachinePassRegistryListener *L) {
140 Registry.setListener(L);
146 /// Define a generic scheduling policy for targets that don't provide their own
147 /// MachineSchedStrategy. This can be overriden for each scheduling region
148 /// before building the DAG.
149 struct MachineSchedPolicy {
150 // Allow the scheduler to disable register pressure tracking.
151 bool ShouldTrackPressure;
153 // Allow the scheduler to force top-down or bottom-up scheduling. If neither
154 // is true, the scheduler runs in both directions and converges.
158 MachineSchedPolicy():
159 ShouldTrackPressure(false), OnlyTopDown(false), OnlyBottomUp(false) {}
162 /// MachineSchedStrategy - Interface to the scheduling algorithm used by
165 /// Initialization sequence:
166 /// initPolicy -> shouldTrackPressure -> initialize(DAG) -> registerRoots
167 class MachineSchedStrategy {
168 virtual void anchor();
170 virtual ~MachineSchedStrategy() {}
172 /// Optionally override the per-region scheduling policy.
173 virtual void initPolicy(MachineBasicBlock::iterator Begin,
174 MachineBasicBlock::iterator End,
175 unsigned NumRegionInstrs) {}
177 /// Check if pressure tracking is needed before building the DAG and
178 /// initializing this strategy. Called after initPolicy.
179 virtual bool shouldTrackPressure() const { return true; }
181 /// Initialize the strategy after building the DAG for a new region.
182 virtual void initialize(ScheduleDAGMI *DAG) = 0;
184 /// Notify this strategy that all roots have been released (including those
185 /// that depend on EntrySU or ExitSU).
186 virtual void registerRoots() {}
188 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
189 /// schedule the node at the top of the unscheduled region. Otherwise it will
190 /// be scheduled at the bottom.
191 virtual SUnit *pickNode(bool &IsTopNode) = 0;
193 /// \brief Scheduler callback to notify that a new subtree is scheduled.
194 virtual void scheduleTree(unsigned SubtreeID) {}
196 /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an
197 /// instruction and updated scheduled/remaining flags in the DAG nodes.
198 virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
200 /// When all predecessor dependencies have been resolved, free this node for
201 /// top-down scheduling.
202 virtual void releaseTopNode(SUnit *SU) = 0;
203 /// When all successor dependencies have been resolved, free this node for
204 /// bottom-up scheduling.
205 virtual void releaseBottomNode(SUnit *SU) = 0;
208 /// Mutate the DAG as a postpass after normal DAG building.
209 class ScheduleDAGMutation {
210 virtual void anchor();
212 virtual ~ScheduleDAGMutation() {}
214 virtual void apply(ScheduleDAGMI *DAG) = 0;
217 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
218 /// machine instructions while updating LiveIntervals and tracking regpressure.
219 class ScheduleDAGMI : public ScheduleDAGInstrs {
222 RegisterClassInfo *RegClassInfo;
223 MachineSchedStrategy *SchedImpl;
225 /// Information about DAG subtrees. If DFSResult is NULL, then SchedulerTrees
227 SchedDFSResult *DFSResult;
228 BitVector ScheduledTrees;
230 /// Topo - A topological ordering for SUnits which permits fast IsReachable
231 /// and similar queries.
232 ScheduleDAGTopologicalSort Topo;
234 /// Ordered list of DAG postprocessing steps.
235 std::vector<ScheduleDAGMutation*> Mutations;
237 MachineBasicBlock::iterator LiveRegionEnd;
239 // Map each SU to its summary of pressure changes. This array is updated for
240 // liveness during bottom-up scheduling. Top-down scheduling may proceed but
241 // has no affect on the pressure diffs.
242 PressureDiffs SUPressureDiffs;
244 /// Register pressure in this region computed by initRegPressure.
245 bool ShouldTrackPressure;
246 IntervalPressure RegPressure;
247 RegPressureTracker RPTracker;
249 /// List of pressure sets that exceed the target's pressure limit before
250 /// scheduling, listed in increasing set ID order. Each pressure set is paired
251 /// with its max pressure in the currently scheduled regions.
252 std::vector<PressureChange> RegionCriticalPSets;
254 /// The top of the unscheduled zone.
255 MachineBasicBlock::iterator CurrentTop;
256 IntervalPressure TopPressure;
257 RegPressureTracker TopRPTracker;
259 /// The bottom of the unscheduled zone.
260 MachineBasicBlock::iterator CurrentBottom;
261 IntervalPressure BotPressure;
262 RegPressureTracker BotRPTracker;
264 /// Record the next node in a scheduled cluster.
265 const SUnit *NextClusterPred;
266 const SUnit *NextClusterSucc;
269 /// The number of instructions scheduled so far. Used to cut off the
270 /// scheduler at the point determined by misched-cutoff.
271 unsigned NumInstrsScheduled;
275 ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
276 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
277 AA(C->AA), RegClassInfo(C->RegClassInfo), SchedImpl(S), DFSResult(0),
278 Topo(SUnits, &ExitSU), ShouldTrackPressure(false),
279 RPTracker(RegPressure), CurrentTop(), TopRPTracker(TopPressure),
280 CurrentBottom(), BotRPTracker(BotPressure),
281 NextClusterPred(NULL), NextClusterSucc(NULL) {
283 NumInstrsScheduled = 0;
287 virtual ~ScheduleDAGMI();
289 /// \brief Return true if register pressure tracking is enabled.
290 bool isTrackingPressure() const { return ShouldTrackPressure; }
292 /// Add a postprocessing step to the DAG builder.
293 /// Mutations are applied in the order that they are added after normal DAG
294 /// building and before MachineSchedStrategy initialization.
296 /// ScheduleDAGMI takes ownership of the Mutation object.
297 void addMutation(ScheduleDAGMutation *Mutation) {
298 Mutations.push_back(Mutation);
301 /// \brief True if an edge can be added from PredSU to SuccSU without creating
303 bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
305 /// \brief Add a DAG edge to the given SU with the given predecessor
308 /// \returns true if the edge may be added without creating a cycle OR if an
309 /// equivalent edge already existed (false indicates failure).
310 bool addEdge(SUnit *SuccSU, const SDep &PredDep);
312 MachineBasicBlock::iterator top() const { return CurrentTop; }
313 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
315 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
316 /// region. This covers all instructions in a block, while schedule() may only
318 void enterRegion(MachineBasicBlock *bb,
319 MachineBasicBlock::iterator begin,
320 MachineBasicBlock::iterator end,
321 unsigned regioninstrs) LLVM_OVERRIDE;
323 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
324 /// reorderable instructions.
325 virtual void schedule();
327 /// Change the position of an instruction within the basic block and update
328 /// live ranges and region boundary iterators.
329 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
331 /// Get current register pressure for the top scheduled instructions.
332 const IntervalPressure &getTopPressure() const { return TopPressure; }
333 const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
335 /// Get current register pressure for the bottom scheduled instructions.
336 const IntervalPressure &getBotPressure() const { return BotPressure; }
337 const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
339 /// Get register pressure for the entire scheduling region before scheduling.
340 const IntervalPressure &getRegPressure() const { return RegPressure; }
342 const std::vector<PressureChange> &getRegionCriticalPSets() const {
343 return RegionCriticalPSets;
346 PressureDiff &getPressureDiff(const SUnit *SU) {
347 return SUPressureDiffs[SU->NodeNum];
350 const SUnit *getNextClusterPred() const { return NextClusterPred; }
352 const SUnit *getNextClusterSucc() const { return NextClusterSucc; }
354 /// Compute a DFSResult after DAG building is complete, and before any
355 /// queue comparisons.
356 void computeDFSResult();
358 /// Return a non-null DFS result if the scheduling strategy initialized it.
359 const SchedDFSResult *getDFSResult() const { return DFSResult; }
361 BitVector &getScheduledTrees() { return ScheduledTrees; }
363 /// Compute the cyclic critical path through the DAG.
364 unsigned computeCyclicCriticalPath();
366 void viewGraph(const Twine &Name, const Twine &Title) LLVM_OVERRIDE;
367 void viewGraph() LLVM_OVERRIDE;
370 // Top-Level entry points for the schedule() driver...
372 /// Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking
373 /// enabled. This sets up three trackers. RPTracker will cover the entire DAG
374 /// region, TopTracker and BottomTracker will be initialized to the top and
375 /// bottom of the DAG region without covereing any unscheduled instruction.
376 void buildDAGWithRegPressure();
378 /// Apply each ScheduleDAGMutation step in order. This allows different
379 /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
380 void postprocessDAG();
382 /// Release ExitSU predecessors and setup scheduler queues.
383 void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
385 /// Move an instruction and update register pressure.
386 void scheduleMI(SUnit *SU, bool IsTopNode);
388 /// Update scheduler DAG and queues after scheduling an instruction.
389 void updateQueues(SUnit *SU, bool IsTopNode);
391 /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
392 void placeDebugValues();
394 /// \brief dump the scheduled Sequence.
395 void dumpSchedule() const;
399 void initRegPressure();
401 void updatePressureDiffs(ArrayRef<unsigned> LiveUses);
403 void updateScheduledPressure(const SUnit *SU,
404 const std::vector<unsigned> &NewMaxPressure);
406 bool checkSchedLimit();
408 void findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
409 SmallVectorImpl<SUnit*> &BotRoots);
411 void releaseSucc(SUnit *SU, SDep *SuccEdge);
412 void releaseSuccessors(SUnit *SU);
413 void releasePred(SUnit *SU, SDep *PredEdge);
414 void releasePredecessors(SUnit *SU);
417 //===----------------------------------------------------------------------===//
419 /// Helpers for implementing custom MachineSchedStrategy classes. These take
420 /// care of the book-keeping associated with list scheduling heuristics.
422 //===----------------------------------------------------------------------===//
424 /// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
425 /// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
426 /// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
428 /// This is a convenience class that may be used by implementations of
429 /// MachineSchedStrategy.
433 std::vector<SUnit*> Queue;
436 ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
438 unsigned getID() const { return ID; }
440 StringRef getName() const { return Name; }
442 // SU is in this queue if it's NodeQueueID is a superset of this ID.
443 bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
445 bool empty() const { return Queue.empty(); }
447 void clear() { Queue.clear(); }
449 unsigned size() const { return Queue.size(); }
451 typedef std::vector<SUnit*>::iterator iterator;
453 iterator begin() { return Queue.begin(); }
455 iterator end() { return Queue.end(); }
457 ArrayRef<SUnit*> elements() { return Queue; }
459 iterator find(SUnit *SU) {
460 return std::find(Queue.begin(), Queue.end(), SU);
463 void push(SUnit *SU) {
465 SU->NodeQueueId |= ID;
468 iterator remove(iterator I) {
469 (*I)->NodeQueueId &= ~ID;
471 unsigned idx = I - Queue.begin();
473 return Queue.begin() + idx;
476 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
481 /// Summarize the unscheduled region.
482 struct SchedRemainder {
483 // Critical path through the DAG in expected latency.
484 unsigned CriticalPath;
485 unsigned CyclicCritPath;
487 // Scaled count of micro-ops left to schedule.
488 unsigned RemIssueCount;
490 bool IsAcyclicLatencyLimited;
492 // Unscheduled resources
493 SmallVector<unsigned, 16> RemainingCounts;
499 IsAcyclicLatencyLimited = false;
500 RemainingCounts.clear();
503 SchedRemainder() { reset(); }
505 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
508 /// Each Scheduling boundary is associated with ready queues. It tracks the
509 /// current cycle in the direction of movement, and maintains the state
510 /// of "hazards" and other interlocks at the current cycle.
511 class SchedBoundary {
513 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
521 const TargetSchedModel *SchedModel;
524 ReadyQueue Available;
527 ScheduleHazardRecognizer *HazardRec;
530 /// True if the pending Q should be checked/updated before scheduling another
534 // For heuristics, keep a list of the nodes that immediately depend on the
535 // most recently scheduled node.
536 SmallPtrSet<const SUnit*, 8> NextSUs;
538 /// Number of cycles it takes to issue the instructions scheduled in this
539 /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
543 /// Micro-ops issued in the current cycle
546 /// MinReadyCycle - Cycle of the soonest available instruction.
547 unsigned MinReadyCycle;
549 // The expected latency of the critical path in this scheduled zone.
550 unsigned ExpectedLatency;
552 // The latency of dependence chains leading into this zone.
553 // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
554 // For each cycle scheduled: DLat -= 1.
555 unsigned DependentLatency;
557 /// Count the scheduled (issued) micro-ops that can be retired by
558 /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
559 unsigned RetiredMOps;
561 // Count scheduled resources that have been executed. Resources are
562 // considered executed if they become ready in the time that it takes to
563 // saturate any resource including the one in question. Counts are scaled
564 // for direct comparison with other resources. Counts can be compared with
565 // MOps * getMicroOpFactor and Latency * getLatencyFactor.
566 SmallVector<unsigned, 16> ExecutedResCounts;
568 /// Cache the max count for a single resource.
569 unsigned MaxExecutedResCount;
571 // Cache the critical resources ID in this scheduled zone.
572 unsigned ZoneCritResIdx;
574 // Is the scheduled region resource limited vs. latency limited.
575 bool IsResourceLimited;
577 // Record the highest cycle at which each resource has been reserved by a
578 // scheduled instruction.
579 SmallVector<unsigned, 16> ReservedCycles;
582 // Remember the greatest operand latency as an upper bound on the number of
583 // times we should retry the pending queue because of a hazard.
584 unsigned MaxObservedLatency;
588 /// Pending queues extend the ready queues with the same ID and the
590 SchedBoundary(unsigned ID, const Twine &Name):
591 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
592 Pending(ID << LogMaxQID, Name+".P"),
601 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
602 SchedRemainder *rem);
605 return Available.getID() == TopQID;
608 /// Number of cycles to issue the instructions scheduled in this zone.
609 unsigned getCurrCycle() const { return CurrCycle; }
611 /// Micro-ops issued in the current cycle
612 unsigned getCurrMOps() const { return CurrMOps; }
614 /// Return true if the given SU is used by the most recently scheduled
616 bool isNextSU(const SUnit *SU) const { return NextSUs.count(SU); }
618 // The latency of dependence chains leading into this zone.
619 unsigned getDependentLatency() const { return DependentLatency; }
621 /// Get the number of latency cycles "covered" by the scheduled
622 /// instructions. This is the larger of the critical path within the zone
623 /// and the number of cycles required to issue the instructions.
624 unsigned getScheduledLatency() const {
625 return std::max(ExpectedLatency, CurrCycle);
628 unsigned getUnscheduledLatency(SUnit *SU) const {
629 return isTop() ? SU->getHeight() : SU->getDepth();
632 unsigned getResourceCount(unsigned ResIdx) const {
633 return ExecutedResCounts[ResIdx];
636 /// Get the scaled count of scheduled micro-ops and resources, including
637 /// executed resources.
638 unsigned getCriticalCount() const {
640 return RetiredMOps * SchedModel->getMicroOpFactor();
641 return getResourceCount(ZoneCritResIdx);
644 /// Get a scaled count for the minimum execution time of the scheduled
645 /// micro-ops that are ready to execute by getExecutedCount. Notice the
647 unsigned getExecutedCount() const {
648 return std::max(CurrCycle * SchedModel->getLatencyFactor(),
649 MaxExecutedResCount);
652 unsigned getZoneCritResIdx() const { return ZoneCritResIdx; }
654 // Is the scheduled region resource limited vs. latency limited.
655 bool isResourceLimited() const { return IsResourceLimited; }
657 /// Get the difference between the given SUnit's ready time and the current
659 unsigned getLatencyStallCycles(SUnit *SU);
661 unsigned getNextResourceCycle(unsigned PIdx, unsigned Cycles);
663 bool checkHazard(SUnit *SU);
665 unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
667 unsigned getOtherResourceCount(unsigned &OtherCritIdx);
669 void releaseNode(SUnit *SU, unsigned ReadyCycle);
671 void releaseTopNode(SUnit *SU);
673 void releaseBottomNode(SUnit *SU);
675 void bumpCycle(unsigned NextCycle);
677 void incExecutedResources(unsigned PIdx, unsigned Count);
679 unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
681 void bumpNode(SUnit *SU);
683 void releasePending();
685 void removeReady(SUnit *SU);
687 /// Call this before applying any other heuristics to the Available queue.
688 /// Updates the Available/Pending Q's if necessary and returns the single
689 /// available instruction, or NULL if there are multiple candidates.
690 SUnit *pickOnlyChoice();
693 void dumpScheduledState();