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