]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/CodeGen/MachineScheduler.h
Update mandoc to 1.14.2
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / CodeGen / MachineScheduler.h
1 //===- MachineScheduler.h - MachineInstr Scheduling Pass --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides an interface for customizing the standard MachineScheduler
11 // pass. Note that the entire pass may be replaced as follows:
12 //
13 // <Target>TargetMachine::createPassConfig(PassManagerBase &PM) {
14 //   PM.substitutePass(&MachineSchedulerID, &CustomSchedulerPassID);
15 //   ...}
16 //
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:
20 //
21 // ScheduleDAGInstrs *<Target>PassConfig::
22 // createMachineScheduler(MachineSchedContext *C) {
23 //   return new CustomMachineScheduler(C);
24 // }
25 //
26 // The default scheduler, ScheduleDAGMILive, 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:
32 //
33 // ScheduleDAGInstrs *<Target>PassConfig::
34 // createMachineScheduler(MachineSchedContext *C) {
35 //   return new ScheduleDAGMILive(C, CustomStrategy(C));
36 // }
37 //
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
41 // to aid heuristics:
42 //
43 // ScheduleDAGInstrs *<Target>PassConfig::
44 // createMachineScheduler(MachineSchedContext *C) {
45 //   ScheduleDAGMI *DAG = createGenericSchedLive(C);
46 //   DAG->addMutation(new CustomDAGMutation(...));
47 //   return DAG;
48 // }
49 //
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:
53 //
54 // static ScheduleDAGInstrs *createCustomMachineSched(MachineSchedContext *C) {
55 //  return new CustomMachineScheduler(C);
56 // }
57 // static MachineSchedRegistry
58 // SchedCustomRegistry("custom", "Run my target's custom scheduler",
59 //                     createCustomMachineSched);
60 //
61 //
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
65 // this:
66 //
67 // void <SubTarget>Subtarget::
68 // overrideSchedPolicy(MachineSchedPolicy &Policy,
69 //                     unsigned NumRegionInstrs) const {
70 //   Policy.<Flag> = true;
71 // }
72 //
73 //===----------------------------------------------------------------------===//
74
75 #ifndef LLVM_CODEGEN_MACHINESCHEDULER_H
76 #define LLVM_CODEGEN_MACHINESCHEDULER_H
77
78 #include "llvm/ADT/ArrayRef.h"
79 #include "llvm/ADT/BitVector.h"
80 #include "llvm/ADT/STLExtras.h"
81 #include "llvm/ADT/SmallVector.h"
82 #include "llvm/ADT/StringRef.h"
83 #include "llvm/ADT/Twine.h"
84 #include "llvm/Analysis/AliasAnalysis.h"
85 #include "llvm/CodeGen/MachineBasicBlock.h"
86 #include "llvm/CodeGen/MachinePassRegistry.h"
87 #include "llvm/CodeGen/RegisterPressure.h"
88 #include "llvm/CodeGen/ScheduleDAG.h"
89 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
90 #include "llvm/CodeGen/ScheduleDAGMutation.h"
91 #include "llvm/CodeGen/TargetSchedule.h"
92 #include "llvm/Support/CommandLine.h"
93 #include "llvm/Support/ErrorHandling.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <memory>
97 #include <string>
98 #include <vector>
99
100 namespace llvm {
101
102 extern cl::opt<bool> ForceTopDown;
103 extern cl::opt<bool> ForceBottomUp;
104
105 class LiveIntervals;
106 class MachineDominatorTree;
107 class MachineFunction;
108 class MachineInstr;
109 class MachineLoopInfo;
110 class RegisterClassInfo;
111 class SchedDFSResult;
112 class ScheduleHazardRecognizer;
113 class TargetInstrInfo;
114 class TargetPassConfig;
115 class TargetRegisterInfo;
116
117 /// MachineSchedContext provides enough context from the MachineScheduler pass
118 /// for the target to instantiate a scheduler.
119 struct MachineSchedContext {
120   MachineFunction *MF = nullptr;
121   const MachineLoopInfo *MLI = nullptr;
122   const MachineDominatorTree *MDT = nullptr;
123   const TargetPassConfig *PassConfig = nullptr;
124   AliasAnalysis *AA = nullptr;
125   LiveIntervals *LIS = nullptr;
126
127   RegisterClassInfo *RegClassInfo;
128
129   MachineSchedContext();
130   virtual ~MachineSchedContext();
131 };
132
133 /// MachineSchedRegistry provides a selection of available machine instruction
134 /// schedulers.
135 class MachineSchedRegistry : public MachinePassRegistryNode {
136 public:
137   using ScheduleDAGCtor = ScheduleDAGInstrs *(*)(MachineSchedContext *);
138
139   // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
140   using FunctionPassCtor = ScheduleDAGCtor;
141
142   static MachinePassRegistry Registry;
143
144   MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
145     : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
146     Registry.Add(this);
147   }
148
149   ~MachineSchedRegistry() { Registry.Remove(this); }
150
151   // Accessors.
152   //
153   MachineSchedRegistry *getNext() const {
154     return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
155   }
156
157   static MachineSchedRegistry *getList() {
158     return (MachineSchedRegistry *)Registry.getList();
159   }
160
161   static void setListener(MachinePassRegistryListener *L) {
162     Registry.setListener(L);
163   }
164 };
165
166 class ScheduleDAGMI;
167
168 /// Define a generic scheduling policy for targets that don't provide their own
169 /// MachineSchedStrategy. This can be overriden for each scheduling region
170 /// before building the DAG.
171 struct MachineSchedPolicy {
172   // Allow the scheduler to disable register pressure tracking.
173   bool ShouldTrackPressure = false;
174   /// Track LaneMasks to allow reordering of independent subregister writes
175   /// of the same vreg. \sa MachineSchedStrategy::shouldTrackLaneMasks()
176   bool ShouldTrackLaneMasks = false;
177
178   // Allow the scheduler to force top-down or bottom-up scheduling. If neither
179   // is true, the scheduler runs in both directions and converges.
180   bool OnlyTopDown = false;
181   bool OnlyBottomUp = false;
182
183   // Disable heuristic that tries to fetch nodes from long dependency chains
184   // first.
185   bool DisableLatencyHeuristic = false;
186
187   MachineSchedPolicy() = default;
188 };
189
190 /// MachineSchedStrategy - Interface to the scheduling algorithm used by
191 /// ScheduleDAGMI.
192 ///
193 /// Initialization sequence:
194 ///   initPolicy -> shouldTrackPressure -> initialize(DAG) -> registerRoots
195 class MachineSchedStrategy {
196   virtual void anchor();
197
198 public:
199   virtual ~MachineSchedStrategy() = default;
200
201   /// Optionally override the per-region scheduling policy.
202   virtual void initPolicy(MachineBasicBlock::iterator Begin,
203                           MachineBasicBlock::iterator End,
204                           unsigned NumRegionInstrs) {}
205
206   virtual void dumpPolicy() const {}
207
208   /// Check if pressure tracking is needed before building the DAG and
209   /// initializing this strategy. Called after initPolicy.
210   virtual bool shouldTrackPressure() const { return true; }
211
212   /// Returns true if lanemasks should be tracked. LaneMask tracking is
213   /// necessary to reorder independent subregister defs for the same vreg.
214   /// This has to be enabled in combination with shouldTrackPressure().
215   virtual bool shouldTrackLaneMasks() const { return false; }
216
217   /// Initialize the strategy after building the DAG for a new region.
218   virtual void initialize(ScheduleDAGMI *DAG) = 0;
219
220   /// Notify this strategy that all roots have been released (including those
221   /// that depend on EntrySU or ExitSU).
222   virtual void registerRoots() {}
223
224   /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
225   /// schedule the node at the top of the unscheduled region. Otherwise it will
226   /// be scheduled at the bottom.
227   virtual SUnit *pickNode(bool &IsTopNode) = 0;
228
229   /// \brief Scheduler callback to notify that a new subtree is scheduled.
230   virtual void scheduleTree(unsigned SubtreeID) {}
231
232   /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an
233   /// instruction and updated scheduled/remaining flags in the DAG nodes.
234   virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
235
236   /// When all predecessor dependencies have been resolved, free this node for
237   /// top-down scheduling.
238   virtual void releaseTopNode(SUnit *SU) = 0;
239
240   /// When all successor dependencies have been resolved, free this node for
241   /// bottom-up scheduling.
242   virtual void releaseBottomNode(SUnit *SU) = 0;
243 };
244
245 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply
246 /// schedules machine instructions according to the given MachineSchedStrategy
247 /// without much extra book-keeping. This is the common functionality between
248 /// PreRA and PostRA MachineScheduler.
249 class ScheduleDAGMI : public ScheduleDAGInstrs {
250 protected:
251   AliasAnalysis *AA;
252   LiveIntervals *LIS;
253   std::unique_ptr<MachineSchedStrategy> SchedImpl;
254
255   /// Topo - A topological ordering for SUnits which permits fast IsReachable
256   /// and similar queries.
257   ScheduleDAGTopologicalSort Topo;
258
259   /// Ordered list of DAG postprocessing steps.
260   std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
261
262   /// The top of the unscheduled zone.
263   MachineBasicBlock::iterator CurrentTop;
264
265   /// The bottom of the unscheduled zone.
266   MachineBasicBlock::iterator CurrentBottom;
267
268   /// Record the next node in a scheduled cluster.
269   const SUnit *NextClusterPred = nullptr;
270   const SUnit *NextClusterSucc = nullptr;
271
272 #ifndef NDEBUG
273   /// The number of instructions scheduled so far. Used to cut off the
274   /// scheduler at the point determined by misched-cutoff.
275   unsigned NumInstrsScheduled = 0;
276 #endif
277
278 public:
279   ScheduleDAGMI(MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S,
280                 bool RemoveKillFlags)
281       : ScheduleDAGInstrs(*C->MF, C->MLI, RemoveKillFlags), AA(C->AA),
282         LIS(C->LIS), SchedImpl(std::move(S)), Topo(SUnits, &ExitSU) {}
283
284   // Provide a vtable anchor
285   ~ScheduleDAGMI() override;
286
287   // Returns LiveIntervals instance for use in DAG mutators and such.
288   LiveIntervals *getLIS() const { return LIS; }
289
290   /// Return true if this DAG supports VReg liveness and RegPressure.
291   virtual bool hasVRegLiveness() const { return false; }
292
293   /// Add a postprocessing step to the DAG builder.
294   /// Mutations are applied in the order that they are added after normal DAG
295   /// building and before MachineSchedStrategy initialization.
296   ///
297   /// ScheduleDAGMI takes ownership of the Mutation object.
298   void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
299     if (Mutation)
300       Mutations.push_back(std::move(Mutation));
301   }
302
303   /// \brief True if an edge can be added from PredSU to SuccSU without creating
304   /// a cycle.
305   bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
306
307   /// \brief Add a DAG edge to the given SU with the given predecessor
308   /// dependence data.
309   ///
310   /// \returns true if the edge may be added without creating a cycle OR if an
311   /// equivalent edge already existed (false indicates failure).
312   bool addEdge(SUnit *SuccSU, const SDep &PredDep);
313
314   MachineBasicBlock::iterator top() const { return CurrentTop; }
315   MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
316
317   /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
318   /// region. This covers all instructions in a block, while schedule() may only
319   /// cover a subset.
320   void enterRegion(MachineBasicBlock *bb,
321                    MachineBasicBlock::iterator begin,
322                    MachineBasicBlock::iterator end,
323                    unsigned regioninstrs) override;
324
325   /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
326   /// reorderable instructions.
327   void schedule() override;
328
329   /// Change the position of an instruction within the basic block and update
330   /// live ranges and region boundary iterators.
331   void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
332
333   const SUnit *getNextClusterPred() const { return NextClusterPred; }
334
335   const SUnit *getNextClusterSucc() const { return NextClusterSucc; }
336
337   void viewGraph(const Twine &Name, const Twine &Title) override;
338   void viewGraph() override;
339
340 protected:
341   // Top-Level entry points for the schedule() driver...
342
343   /// Apply each ScheduleDAGMutation step in order. This allows different
344   /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
345   void postprocessDAG();
346
347   /// Release ExitSU predecessors and setup scheduler queues.
348   void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
349
350   /// Update scheduler DAG and queues after scheduling an instruction.
351   void updateQueues(SUnit *SU, bool IsTopNode);
352
353   /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
354   void placeDebugValues();
355
356   /// \brief dump the scheduled Sequence.
357   void dumpSchedule() const;
358
359   // Lesser helpers...
360   bool checkSchedLimit();
361
362   void findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
363                              SmallVectorImpl<SUnit*> &BotRoots);
364
365   void releaseSucc(SUnit *SU, SDep *SuccEdge);
366   void releaseSuccessors(SUnit *SU);
367   void releasePred(SUnit *SU, SDep *PredEdge);
368   void releasePredecessors(SUnit *SU);
369 };
370
371 /// ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules
372 /// machine instructions while updating LiveIntervals and tracking regpressure.
373 class ScheduleDAGMILive : public ScheduleDAGMI {
374 protected:
375   RegisterClassInfo *RegClassInfo;
376
377   /// Information about DAG subtrees. If DFSResult is NULL, then SchedulerTrees
378   /// will be empty.
379   SchedDFSResult *DFSResult = nullptr;
380   BitVector ScheduledTrees;
381
382   MachineBasicBlock::iterator LiveRegionEnd;
383
384   /// Maps vregs to the SUnits of their uses in the current scheduling region.
385   VReg2SUnitMultiMap VRegUses;
386
387   // Map each SU to its summary of pressure changes. This array is updated for
388   // liveness during bottom-up scheduling. Top-down scheduling may proceed but
389   // has no affect on the pressure diffs.
390   PressureDiffs SUPressureDiffs;
391
392   /// Register pressure in this region computed by initRegPressure.
393   bool ShouldTrackPressure = false;
394   bool ShouldTrackLaneMasks = false;
395   IntervalPressure RegPressure;
396   RegPressureTracker RPTracker;
397
398   /// List of pressure sets that exceed the target's pressure limit before
399   /// scheduling, listed in increasing set ID order. Each pressure set is paired
400   /// with its max pressure in the currently scheduled regions.
401   std::vector<PressureChange> RegionCriticalPSets;
402
403   /// The top of the unscheduled zone.
404   IntervalPressure TopPressure;
405   RegPressureTracker TopRPTracker;
406
407   /// The bottom of the unscheduled zone.
408   IntervalPressure BotPressure;
409   RegPressureTracker BotRPTracker;
410
411   /// True if disconnected subregister components are already renamed.
412   /// The renaming is only done on demand if lane masks are tracked.
413   bool DisconnectedComponentsRenamed = false;
414
415 public:
416   ScheduleDAGMILive(MachineSchedContext *C,
417                     std::unique_ptr<MachineSchedStrategy> S)
418       : ScheduleDAGMI(C, std::move(S), /*RemoveKillFlags=*/false),
419         RegClassInfo(C->RegClassInfo), RPTracker(RegPressure),
420         TopRPTracker(TopPressure), BotRPTracker(BotPressure) {}
421
422   ~ScheduleDAGMILive() override;
423
424   /// Return true if this DAG supports VReg liveness and RegPressure.
425   bool hasVRegLiveness() const override { return true; }
426
427   /// \brief Return true if register pressure tracking is enabled.
428   bool isTrackingPressure() const { return ShouldTrackPressure; }
429
430   /// Get current register pressure for the top scheduled instructions.
431   const IntervalPressure &getTopPressure() const { return TopPressure; }
432   const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
433
434   /// Get current register pressure for the bottom scheduled instructions.
435   const IntervalPressure &getBotPressure() const { return BotPressure; }
436   const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
437
438   /// Get register pressure for the entire scheduling region before scheduling.
439   const IntervalPressure &getRegPressure() const { return RegPressure; }
440
441   const std::vector<PressureChange> &getRegionCriticalPSets() const {
442     return RegionCriticalPSets;
443   }
444
445   PressureDiff &getPressureDiff(const SUnit *SU) {
446     return SUPressureDiffs[SU->NodeNum];
447   }
448
449   /// Compute a DFSResult after DAG building is complete, and before any
450   /// queue comparisons.
451   void computeDFSResult();
452
453   /// Return a non-null DFS result if the scheduling strategy initialized it.
454   const SchedDFSResult *getDFSResult() const { return DFSResult; }
455
456   BitVector &getScheduledTrees() { return ScheduledTrees; }
457
458   /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
459   /// region. This covers all instructions in a block, while schedule() may only
460   /// cover a subset.
461   void enterRegion(MachineBasicBlock *bb,
462                    MachineBasicBlock::iterator begin,
463                    MachineBasicBlock::iterator end,
464                    unsigned regioninstrs) override;
465
466   /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
467   /// reorderable instructions.
468   void schedule() override;
469
470   /// Compute the cyclic critical path through the DAG.
471   unsigned computeCyclicCriticalPath();
472
473 protected:
474   // Top-Level entry points for the schedule() driver...
475
476   /// Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking
477   /// enabled. This sets up three trackers. RPTracker will cover the entire DAG
478   /// region, TopTracker and BottomTracker will be initialized to the top and
479   /// bottom of the DAG region without covereing any unscheduled instruction.
480   void buildDAGWithRegPressure();
481
482   /// Release ExitSU predecessors and setup scheduler queues. Re-position
483   /// the Top RP tracker in case the region beginning has changed.
484   void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
485
486   /// Move an instruction and update register pressure.
487   void scheduleMI(SUnit *SU, bool IsTopNode);
488
489   // Lesser helpers...
490
491   void initRegPressure();
492
493   void updatePressureDiffs(ArrayRef<RegisterMaskPair> LiveUses);
494
495   void updateScheduledPressure(const SUnit *SU,
496                                const std::vector<unsigned> &NewMaxPressure);
497
498   void collectVRegUses(SUnit &SU);
499 };
500
501 //===----------------------------------------------------------------------===//
502 ///
503 /// Helpers for implementing custom MachineSchedStrategy classes. These take
504 /// care of the book-keeping associated with list scheduling heuristics.
505 ///
506 //===----------------------------------------------------------------------===//
507
508 /// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
509 /// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
510 /// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
511 ///
512 /// This is a convenience class that may be used by implementations of
513 /// MachineSchedStrategy.
514 class ReadyQueue {
515   unsigned ID;
516   std::string Name;
517   std::vector<SUnit*> Queue;
518
519 public:
520   ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
521
522   unsigned getID() const { return ID; }
523
524   StringRef getName() const { return Name; }
525
526   // SU is in this queue if it's NodeQueueID is a superset of this ID.
527   bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
528
529   bool empty() const { return Queue.empty(); }
530
531   void clear() { Queue.clear(); }
532
533   unsigned size() const { return Queue.size(); }
534
535   using iterator = std::vector<SUnit*>::iterator;
536
537   iterator begin() { return Queue.begin(); }
538
539   iterator end() { return Queue.end(); }
540
541   ArrayRef<SUnit*> elements() { return Queue; }
542
543   iterator find(SUnit *SU) { return llvm::find(Queue, SU); }
544
545   void push(SUnit *SU) {
546     Queue.push_back(SU);
547     SU->NodeQueueId |= ID;
548   }
549
550   iterator remove(iterator I) {
551     (*I)->NodeQueueId &= ~ID;
552     *I = Queue.back();
553     unsigned idx = I - Queue.begin();
554     Queue.pop_back();
555     return Queue.begin() + idx;
556   }
557
558   void dump() const;
559 };
560
561 /// Summarize the unscheduled region.
562 struct SchedRemainder {
563   // Critical path through the DAG in expected latency.
564   unsigned CriticalPath;
565   unsigned CyclicCritPath;
566
567   // Scaled count of micro-ops left to schedule.
568   unsigned RemIssueCount;
569
570   bool IsAcyclicLatencyLimited;
571
572   // Unscheduled resources
573   SmallVector<unsigned, 16> RemainingCounts;
574
575   SchedRemainder() { reset(); }
576
577   void reset() {
578     CriticalPath = 0;
579     CyclicCritPath = 0;
580     RemIssueCount = 0;
581     IsAcyclicLatencyLimited = false;
582     RemainingCounts.clear();
583   }
584
585   void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
586 };
587
588 /// Each Scheduling boundary is associated with ready queues. It tracks the
589 /// current cycle in the direction of movement, and maintains the state
590 /// of "hazards" and other interlocks at the current cycle.
591 class SchedBoundary {
592 public:
593   /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
594   enum {
595     TopQID = 1,
596     BotQID = 2,
597     LogMaxQID = 2
598   };
599
600   ScheduleDAGMI *DAG = nullptr;
601   const TargetSchedModel *SchedModel = nullptr;
602   SchedRemainder *Rem = nullptr;
603
604   ReadyQueue Available;
605   ReadyQueue Pending;
606
607   ScheduleHazardRecognizer *HazardRec = nullptr;
608
609 private:
610   /// True if the pending Q should be checked/updated before scheduling another
611   /// instruction.
612   bool CheckPending;
613
614   /// Number of cycles it takes to issue the instructions scheduled in this
615   /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
616   /// See getStalls().
617   unsigned CurrCycle;
618
619   /// Micro-ops issued in the current cycle
620   unsigned CurrMOps;
621
622   /// MinReadyCycle - Cycle of the soonest available instruction.
623   unsigned MinReadyCycle;
624
625   // The expected latency of the critical path in this scheduled zone.
626   unsigned ExpectedLatency;
627
628   // The latency of dependence chains leading into this zone.
629   // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
630   // For each cycle scheduled: DLat -= 1.
631   unsigned DependentLatency;
632
633   /// Count the scheduled (issued) micro-ops that can be retired by
634   /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
635   unsigned RetiredMOps;
636
637   // Count scheduled resources that have been executed. Resources are
638   // considered executed if they become ready in the time that it takes to
639   // saturate any resource including the one in question. Counts are scaled
640   // for direct comparison with other resources. Counts can be compared with
641   // MOps * getMicroOpFactor and Latency * getLatencyFactor.
642   SmallVector<unsigned, 16> ExecutedResCounts;
643
644   /// Cache the max count for a single resource.
645   unsigned MaxExecutedResCount;
646
647   // Cache the critical resources ID in this scheduled zone.
648   unsigned ZoneCritResIdx;
649
650   // Is the scheduled region resource limited vs. latency limited.
651   bool IsResourceLimited;
652
653   // Record the highest cycle at which each resource has been reserved by a
654   // scheduled instruction.
655   SmallVector<unsigned, 16> ReservedCycles;
656
657 #ifndef NDEBUG
658   // Remember the greatest possible stall as an upper bound on the number of
659   // times we should retry the pending queue because of a hazard.
660   unsigned MaxObservedStall;
661 #endif
662
663 public:
664   /// Pending queues extend the ready queues with the same ID and the
665   /// PendingFlag set.
666   SchedBoundary(unsigned ID, const Twine &Name):
667     Available(ID, Name+".A"), Pending(ID << LogMaxQID, Name+".P") {
668     reset();
669   }
670
671   ~SchedBoundary();
672
673   void reset();
674
675   void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
676             SchedRemainder *rem);
677
678   bool isTop() const {
679     return Available.getID() == TopQID;
680   }
681
682   /// Number of cycles to issue the instructions scheduled in this zone.
683   unsigned getCurrCycle() const { return CurrCycle; }
684
685   /// Micro-ops issued in the current cycle
686   unsigned getCurrMOps() const { return CurrMOps; }
687
688   // The latency of dependence chains leading into this zone.
689   unsigned getDependentLatency() const { return DependentLatency; }
690
691   /// Get the number of latency cycles "covered" by the scheduled
692   /// instructions. This is the larger of the critical path within the zone
693   /// and the number of cycles required to issue the instructions.
694   unsigned getScheduledLatency() const {
695     return std::max(ExpectedLatency, CurrCycle);
696   }
697
698   unsigned getUnscheduledLatency(SUnit *SU) const {
699     return isTop() ? SU->getHeight() : SU->getDepth();
700   }
701
702   unsigned getResourceCount(unsigned ResIdx) const {
703     return ExecutedResCounts[ResIdx];
704   }
705
706   /// Get the scaled count of scheduled micro-ops and resources, including
707   /// executed resources.
708   unsigned getCriticalCount() const {
709     if (!ZoneCritResIdx)
710       return RetiredMOps * SchedModel->getMicroOpFactor();
711     return getResourceCount(ZoneCritResIdx);
712   }
713
714   /// Get a scaled count for the minimum execution time of the scheduled
715   /// micro-ops that are ready to execute by getExecutedCount. Notice the
716   /// feedback loop.
717   unsigned getExecutedCount() const {
718     return std::max(CurrCycle * SchedModel->getLatencyFactor(),
719                     MaxExecutedResCount);
720   }
721
722   unsigned getZoneCritResIdx() const { return ZoneCritResIdx; }
723
724   // Is the scheduled region resource limited vs. latency limited.
725   bool isResourceLimited() const { return IsResourceLimited; }
726
727   /// Get the difference between the given SUnit's ready time and the current
728   /// cycle.
729   unsigned getLatencyStallCycles(SUnit *SU);
730
731   unsigned getNextResourceCycle(unsigned PIdx, unsigned Cycles);
732
733   bool checkHazard(SUnit *SU);
734
735   unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
736
737   unsigned getOtherResourceCount(unsigned &OtherCritIdx);
738
739   void releaseNode(SUnit *SU, unsigned ReadyCycle);
740
741   void bumpCycle(unsigned NextCycle);
742
743   void incExecutedResources(unsigned PIdx, unsigned Count);
744
745   unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
746
747   void bumpNode(SUnit *SU);
748
749   void releasePending();
750
751   void removeReady(SUnit *SU);
752
753   /// Call this before applying any other heuristics to the Available queue.
754   /// Updates the Available/Pending Q's if necessary and returns the single
755   /// available instruction, or NULL if there are multiple candidates.
756   SUnit *pickOnlyChoice();
757
758 #ifndef NDEBUG
759   void dumpScheduledState() const;
760 #endif
761 };
762
763 /// Base class for GenericScheduler. This class maintains information about
764 /// scheduling candidates based on TargetSchedModel making it easy to implement
765 /// heuristics for either preRA or postRA scheduling.
766 class GenericSchedulerBase : public MachineSchedStrategy {
767 public:
768   /// Represent the type of SchedCandidate found within a single queue.
769   /// pickNodeBidirectional depends on these listed by decreasing priority.
770   enum CandReason : uint8_t {
771     NoCand, Only1, PhysRegCopy, RegExcess, RegCritical, Stall, Cluster, Weak,
772     RegMax, ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
773     TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
774
775 #ifndef NDEBUG
776   static const char *getReasonStr(GenericSchedulerBase::CandReason Reason);
777 #endif
778
779   /// Policy for scheduling the next instruction in the candidate's zone.
780   struct CandPolicy {
781     bool ReduceLatency = false;
782     unsigned ReduceResIdx = 0;
783     unsigned DemandResIdx = 0;
784
785     CandPolicy() = default;
786
787     bool operator==(const CandPolicy &RHS) const {
788       return ReduceLatency == RHS.ReduceLatency &&
789              ReduceResIdx == RHS.ReduceResIdx &&
790              DemandResIdx == RHS.DemandResIdx;
791     }
792     bool operator!=(const CandPolicy &RHS) const {
793       return !(*this == RHS);
794     }
795   };
796
797   /// Status of an instruction's critical resource consumption.
798   struct SchedResourceDelta {
799     // Count critical resources in the scheduled region required by SU.
800     unsigned CritResources = 0;
801
802     // Count critical resources from another region consumed by SU.
803     unsigned DemandedResources = 0;
804
805     SchedResourceDelta() = default;
806
807     bool operator==(const SchedResourceDelta &RHS) const {
808       return CritResources == RHS.CritResources
809         && DemandedResources == RHS.DemandedResources;
810     }
811     bool operator!=(const SchedResourceDelta &RHS) const {
812       return !operator==(RHS);
813     }
814   };
815
816   /// Store the state used by GenericScheduler heuristics, required for the
817   /// lifetime of one invocation of pickNode().
818   struct SchedCandidate {
819     CandPolicy Policy;
820
821     // The best SUnit candidate.
822     SUnit *SU;
823
824     // The reason for this candidate.
825     CandReason Reason;
826
827     // Whether this candidate should be scheduled at top/bottom.
828     bool AtTop;
829
830     // Register pressure values for the best candidate.
831     RegPressureDelta RPDelta;
832
833     // Critical resource consumption of the best candidate.
834     SchedResourceDelta ResDelta;
835
836     SchedCandidate() { reset(CandPolicy()); }
837     SchedCandidate(const CandPolicy &Policy) { reset(Policy); }
838
839     void reset(const CandPolicy &NewPolicy) {
840       Policy = NewPolicy;
841       SU = nullptr;
842       Reason = NoCand;
843       AtTop = false;
844       RPDelta = RegPressureDelta();
845       ResDelta = SchedResourceDelta();
846     }
847
848     bool isValid() const { return SU; }
849
850     // Copy the status of another candidate without changing policy.
851     void setBest(SchedCandidate &Best) {
852       assert(Best.Reason != NoCand && "uninitialized Sched candidate");
853       SU = Best.SU;
854       Reason = Best.Reason;
855       AtTop = Best.AtTop;
856       RPDelta = Best.RPDelta;
857       ResDelta = Best.ResDelta;
858     }
859
860     void initResourceDelta(const ScheduleDAGMI *DAG,
861                            const TargetSchedModel *SchedModel);
862   };
863
864 protected:
865   const MachineSchedContext *Context;
866   const TargetSchedModel *SchedModel = nullptr;
867   const TargetRegisterInfo *TRI = nullptr;
868
869   SchedRemainder Rem;
870
871   GenericSchedulerBase(const MachineSchedContext *C) : Context(C) {}
872
873   void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone,
874                  SchedBoundary *OtherZone);
875
876 #ifndef NDEBUG
877   void traceCandidate(const SchedCandidate &Cand);
878 #endif
879 };
880
881 /// GenericScheduler shrinks the unscheduled zone using heuristics to balance
882 /// the schedule.
883 class GenericScheduler : public GenericSchedulerBase {
884 public:
885   GenericScheduler(const MachineSchedContext *C):
886     GenericSchedulerBase(C), Top(SchedBoundary::TopQID, "TopQ"),
887     Bot(SchedBoundary::BotQID, "BotQ") {}
888
889   void initPolicy(MachineBasicBlock::iterator Begin,
890                   MachineBasicBlock::iterator End,
891                   unsigned NumRegionInstrs) override;
892
893   void dumpPolicy() const override;
894
895   bool shouldTrackPressure() const override {
896     return RegionPolicy.ShouldTrackPressure;
897   }
898
899   bool shouldTrackLaneMasks() const override {
900     return RegionPolicy.ShouldTrackLaneMasks;
901   }
902
903   void initialize(ScheduleDAGMI *dag) override;
904
905   SUnit *pickNode(bool &IsTopNode) override;
906
907   void schedNode(SUnit *SU, bool IsTopNode) override;
908
909   void releaseTopNode(SUnit *SU) override {
910     if (SU->isScheduled)
911       return;
912
913     Top.releaseNode(SU, SU->TopReadyCycle);
914     TopCand.SU = nullptr;
915   }
916
917   void releaseBottomNode(SUnit *SU) override {
918     if (SU->isScheduled)
919       return;
920
921     Bot.releaseNode(SU, SU->BotReadyCycle);
922     BotCand.SU = nullptr;
923   }
924
925   void registerRoots() override;
926
927 protected:
928   ScheduleDAGMILive *DAG = nullptr;
929
930   MachineSchedPolicy RegionPolicy;
931
932   // State of the top and bottom scheduled instruction boundaries.
933   SchedBoundary Top;
934   SchedBoundary Bot;
935
936   /// Candidate last picked from Top boundary.
937   SchedCandidate TopCand;
938   /// Candidate last picked from Bot boundary.
939   SchedCandidate BotCand;
940
941   void checkAcyclicLatency();
942
943   void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop,
944                      const RegPressureTracker &RPTracker,
945                      RegPressureTracker &TempTracker);
946
947   void tryCandidate(SchedCandidate &Cand,
948                     SchedCandidate &TryCand,
949                     SchedBoundary *Zone);
950
951   SUnit *pickNodeBidirectional(bool &IsTopNode);
952
953   void pickNodeFromQueue(SchedBoundary &Zone,
954                          const CandPolicy &ZonePolicy,
955                          const RegPressureTracker &RPTracker,
956                          SchedCandidate &Candidate);
957
958   void reschedulePhysRegCopies(SUnit *SU, bool isTop);
959 };
960
961 /// PostGenericScheduler - Interface to the scheduling algorithm used by
962 /// ScheduleDAGMI.
963 ///
964 /// Callbacks from ScheduleDAGMI:
965 ///   initPolicy -> initialize(DAG) -> registerRoots -> pickNode ...
966 class PostGenericScheduler : public GenericSchedulerBase {
967   ScheduleDAGMI *DAG;
968   SchedBoundary Top;
969   SmallVector<SUnit*, 8> BotRoots;
970
971 public:
972   PostGenericScheduler(const MachineSchedContext *C):
973     GenericSchedulerBase(C), Top(SchedBoundary::TopQID, "TopQ") {}
974
975   ~PostGenericScheduler() override = default;
976
977   void initPolicy(MachineBasicBlock::iterator Begin,
978                   MachineBasicBlock::iterator End,
979                   unsigned NumRegionInstrs) override {
980     /* no configurable policy */
981   }
982
983   /// PostRA scheduling does not track pressure.
984   bool shouldTrackPressure() const override { return false; }
985
986   void initialize(ScheduleDAGMI *Dag) override;
987
988   void registerRoots() override;
989
990   SUnit *pickNode(bool &IsTopNode) override;
991
992   void scheduleTree(unsigned SubtreeID) override {
993     llvm_unreachable("PostRA scheduler does not support subtree analysis.");
994   }
995
996   void schedNode(SUnit *SU, bool IsTopNode) override;
997
998   void releaseTopNode(SUnit *SU) override {
999     if (SU->isScheduled)
1000       return;
1001     Top.releaseNode(SU, SU->TopReadyCycle);
1002   }
1003
1004   // Only called for roots.
1005   void releaseBottomNode(SUnit *SU) override {
1006     BotRoots.push_back(SU);
1007   }
1008
1009 protected:
1010   void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand);
1011
1012   void pickNodeFromQueue(SchedCandidate &Cand);
1013 };
1014
1015 /// Create the standard converging machine scheduler. This will be used as the
1016 /// default scheduler if the target does not set a default.
1017 /// Adds default DAG mutations.
1018 ScheduleDAGMILive *createGenericSchedLive(MachineSchedContext *C);
1019
1020 /// Create a generic scheduler with no vreg liveness or DAG mutation passes.
1021 ScheduleDAGMI *createGenericSchedPostRA(MachineSchedContext *C);
1022
1023 std::unique_ptr<ScheduleDAGMutation>
1024 createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1025                              const TargetRegisterInfo *TRI);
1026
1027 std::unique_ptr<ScheduleDAGMutation>
1028 createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1029                               const TargetRegisterInfo *TRI);
1030
1031 std::unique_ptr<ScheduleDAGMutation>
1032 createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
1033                                const TargetRegisterInfo *TRI);
1034
1035 } // end namespace llvm
1036
1037 #endif // LLVM_CODEGEN_MACHINESCHEDULER_H