Factor out the SchedRemainder/SchedBoundary from GenericScheduler strategy.
[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, 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:
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/CodeGen/MachinePassRegistry.h"
81 #include "llvm/CodeGen/RegisterPressure.h"
82 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
83
84 namespace llvm {
85
86 extern cl::opt<bool> ForceTopDown;
87 extern cl::opt<bool> ForceBottomUp;
88
89 class AliasAnalysis;
90 class LiveIntervals;
91 class MachineDominatorTree;
92 class MachineLoopInfo;
93 class RegisterClassInfo;
94 class ScheduleDAGInstrs;
95 class SchedDFSResult;
96 class ScheduleHazardRecognizer;
97
98 /// MachineSchedContext provides enough context from the MachineScheduler pass
99 /// for the target to instantiate a scheduler.
100 struct MachineSchedContext {
101   MachineFunction *MF;
102   const MachineLoopInfo *MLI;
103   const MachineDominatorTree *MDT;
104   const TargetPassConfig *PassConfig;
105   AliasAnalysis *AA;
106   LiveIntervals *LIS;
107
108   RegisterClassInfo *RegClassInfo;
109
110   MachineSchedContext();
111   virtual ~MachineSchedContext();
112 };
113
114 /// MachineSchedRegistry provides a selection of available machine instruction
115 /// schedulers.
116 class MachineSchedRegistry : public MachinePassRegistryNode {
117 public:
118   typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineSchedContext *);
119
120   // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
121   typedef ScheduleDAGCtor FunctionPassCtor;
122
123   static MachinePassRegistry Registry;
124
125   MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
126     : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
127     Registry.Add(this);
128   }
129   ~MachineSchedRegistry() { Registry.Remove(this); }
130
131   // Accessors.
132   //
133   MachineSchedRegistry *getNext() const {
134     return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
135   }
136   static MachineSchedRegistry *getList() {
137     return (MachineSchedRegistry *)Registry.getList();
138   }
139   static void setListener(MachinePassRegistryListener *L) {
140     Registry.setListener(L);
141   }
142 };
143
144 class ScheduleDAGMI;
145
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;
152
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.
155   bool OnlyTopDown;
156   bool OnlyBottomUp;
157
158   MachineSchedPolicy():
159     ShouldTrackPressure(false), OnlyTopDown(false), OnlyBottomUp(false) {}
160 };
161
162 /// MachineSchedStrategy - Interface to the scheduling algorithm used by
163 /// ScheduleDAGMI.
164 ///
165 /// Initialization sequence:
166 ///   initPolicy -> shouldTrackPressure -> initialize(DAG) -> registerRoots
167 class MachineSchedStrategy {
168   virtual void anchor();
169 public:
170   virtual ~MachineSchedStrategy() {}
171
172   /// Optionally override the per-region scheduling policy.
173   virtual void initPolicy(MachineBasicBlock::iterator Begin,
174                           MachineBasicBlock::iterator End,
175                           unsigned NumRegionInstrs) {}
176
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; }
180
181   /// Initialize the strategy after building the DAG for a new region.
182   virtual void initialize(ScheduleDAGMI *DAG) = 0;
183
184   /// Notify this strategy that all roots have been released (including those
185   /// that depend on EntrySU or ExitSU).
186   virtual void registerRoots() {}
187
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;
192
193   /// \brief Scheduler callback to notify that a new subtree is scheduled.
194   virtual void scheduleTree(unsigned SubtreeID) {}
195
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;
199
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;
206 };
207
208 /// Mutate the DAG as a postpass after normal DAG building.
209 class ScheduleDAGMutation {
210   virtual void anchor();
211 public:
212   virtual ~ScheduleDAGMutation() {}
213
214   virtual void apply(ScheduleDAGMI *DAG) = 0;
215 };
216
217 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
218 /// machine instructions while updating LiveIntervals and tracking regpressure.
219 class ScheduleDAGMI : public ScheduleDAGInstrs {
220 protected:
221   AliasAnalysis *AA;
222   RegisterClassInfo *RegClassInfo;
223   MachineSchedStrategy *SchedImpl;
224
225   /// Information about DAG subtrees. If DFSResult is NULL, then SchedulerTrees
226   /// will be empty.
227   SchedDFSResult *DFSResult;
228   BitVector ScheduledTrees;
229
230   /// Topo - A topological ordering for SUnits which permits fast IsReachable
231   /// and similar queries.
232   ScheduleDAGTopologicalSort Topo;
233
234   /// Ordered list of DAG postprocessing steps.
235   std::vector<ScheduleDAGMutation*> Mutations;
236
237   MachineBasicBlock::iterator LiveRegionEnd;
238
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;
243
244   /// Register pressure in this region computed by initRegPressure.
245   bool ShouldTrackPressure;
246   IntervalPressure RegPressure;
247   RegPressureTracker RPTracker;
248
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;
253
254   /// The top of the unscheduled zone.
255   MachineBasicBlock::iterator CurrentTop;
256   IntervalPressure TopPressure;
257   RegPressureTracker TopRPTracker;
258
259   /// The bottom of the unscheduled zone.
260   MachineBasicBlock::iterator CurrentBottom;
261   IntervalPressure BotPressure;
262   RegPressureTracker BotRPTracker;
263
264   /// Record the next node in a scheduled cluster.
265   const SUnit *NextClusterPred;
266   const SUnit *NextClusterSucc;
267
268 #ifndef NDEBUG
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;
272 #endif
273
274 public:
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) {
282 #ifndef NDEBUG
283     NumInstrsScheduled = 0;
284 #endif
285   }
286
287   virtual ~ScheduleDAGMI();
288
289   /// \brief Return true if register pressure tracking is enabled.
290   bool isTrackingPressure() const { return ShouldTrackPressure; }
291
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.
295   ///
296   /// ScheduleDAGMI takes ownership of the Mutation object.
297   void addMutation(ScheduleDAGMutation *Mutation) {
298     Mutations.push_back(Mutation);
299   }
300
301   /// \brief True if an edge can be added from PredSU to SuccSU without creating
302   /// a cycle.
303   bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
304
305   /// \brief Add a DAG edge to the given SU with the given predecessor
306   /// dependence data.
307   ///
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);
311
312   MachineBasicBlock::iterator top() const { return CurrentTop; }
313   MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
314
315   /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
316   /// region. This covers all instructions in a block, while schedule() may only
317   /// cover a subset.
318   void enterRegion(MachineBasicBlock *bb,
319                    MachineBasicBlock::iterator begin,
320                    MachineBasicBlock::iterator end,
321                    unsigned regioninstrs) LLVM_OVERRIDE;
322
323   /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
324   /// reorderable instructions.
325   virtual void schedule();
326
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);
330
331   /// Get current register pressure for the top scheduled instructions.
332   const IntervalPressure &getTopPressure() const { return TopPressure; }
333   const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
334
335   /// Get current register pressure for the bottom scheduled instructions.
336   const IntervalPressure &getBotPressure() const { return BotPressure; }
337   const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
338
339   /// Get register pressure for the entire scheduling region before scheduling.
340   const IntervalPressure &getRegPressure() const { return RegPressure; }
341
342   const std::vector<PressureChange> &getRegionCriticalPSets() const {
343     return RegionCriticalPSets;
344   }
345
346   PressureDiff &getPressureDiff(const SUnit *SU) {
347     return SUPressureDiffs[SU->NodeNum];
348   }
349
350   const SUnit *getNextClusterPred() const { return NextClusterPred; }
351
352   const SUnit *getNextClusterSucc() const { return NextClusterSucc; }
353
354   /// Compute a DFSResult after DAG building is complete, and before any
355   /// queue comparisons.
356   void computeDFSResult();
357
358   /// Return a non-null DFS result if the scheduling strategy initialized it.
359   const SchedDFSResult *getDFSResult() const { return DFSResult; }
360
361   BitVector &getScheduledTrees() { return ScheduledTrees; }
362
363   /// Compute the cyclic critical path through the DAG.
364   unsigned computeCyclicCriticalPath();
365
366   void viewGraph(const Twine &Name, const Twine &Title) LLVM_OVERRIDE;
367   void viewGraph() LLVM_OVERRIDE;
368
369 protected:
370   // Top-Level entry points for the schedule() driver...
371
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();
377
378   /// Apply each ScheduleDAGMutation step in order. This allows different
379   /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
380   void postprocessDAG();
381
382   /// Release ExitSU predecessors and setup scheduler queues.
383   void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
384
385   /// Move an instruction and update register pressure.
386   void scheduleMI(SUnit *SU, bool IsTopNode);
387
388   /// Update scheduler DAG and queues after scheduling an instruction.
389   void updateQueues(SUnit *SU, bool IsTopNode);
390
391   /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
392   void placeDebugValues();
393
394   /// \brief dump the scheduled Sequence.
395   void dumpSchedule() const;
396
397   // Lesser helpers...
398
399   void initRegPressure();
400
401   void updatePressureDiffs(ArrayRef<unsigned> LiveUses);
402
403   void updateScheduledPressure(const SUnit *SU,
404                                const std::vector<unsigned> &NewMaxPressure);
405
406   bool checkSchedLimit();
407
408   void findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
409                              SmallVectorImpl<SUnit*> &BotRoots);
410
411   void releaseSucc(SUnit *SU, SDep *SuccEdge);
412   void releaseSuccessors(SUnit *SU);
413   void releasePred(SUnit *SU, SDep *PredEdge);
414   void releasePredecessors(SUnit *SU);
415 };
416
417 //===----------------------------------------------------------------------===//
418 ///
419 /// Helpers for implementing custom MachineSchedStrategy classes. These take
420 /// care of the book-keeping associated with list scheduling heuristics.
421 ///
422 //===----------------------------------------------------------------------===//
423
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.
427 ///
428 /// This is a convenience class that may be used by implementations of
429 /// MachineSchedStrategy.
430 class ReadyQueue {
431   unsigned ID;
432   std::string Name;
433   std::vector<SUnit*> Queue;
434
435 public:
436   ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
437
438   unsigned getID() const { return ID; }
439
440   StringRef getName() const { return Name; }
441
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); }
444
445   bool empty() const { return Queue.empty(); }
446
447   void clear() { Queue.clear(); }
448
449   unsigned size() const { return Queue.size(); }
450
451   typedef std::vector<SUnit*>::iterator iterator;
452
453   iterator begin() { return Queue.begin(); }
454
455   iterator end() { return Queue.end(); }
456
457   ArrayRef<SUnit*> elements() { return Queue; }
458
459   iterator find(SUnit *SU) {
460     return std::find(Queue.begin(), Queue.end(), SU);
461   }
462
463   void push(SUnit *SU) {
464     Queue.push_back(SU);
465     SU->NodeQueueId |= ID;
466   }
467
468   iterator remove(iterator I) {
469     (*I)->NodeQueueId &= ~ID;
470     *I = Queue.back();
471     unsigned idx = I - Queue.begin();
472     Queue.pop_back();
473     return Queue.begin() + idx;
474   }
475
476 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
477   void dump();
478 #endif
479 };
480
481 /// Summarize the unscheduled region.
482 struct SchedRemainder {
483   // Critical path through the DAG in expected latency.
484   unsigned CriticalPath;
485   unsigned CyclicCritPath;
486
487   // Scaled count of micro-ops left to schedule.
488   unsigned RemIssueCount;
489
490   bool IsAcyclicLatencyLimited;
491
492   // Unscheduled resources
493   SmallVector<unsigned, 16> RemainingCounts;
494
495   void reset() {
496     CriticalPath = 0;
497     CyclicCritPath = 0;
498     RemIssueCount = 0;
499     IsAcyclicLatencyLimited = false;
500     RemainingCounts.clear();
501   }
502
503   SchedRemainder() { reset(); }
504
505   void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
506 };
507
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 {
512 public:
513   /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
514   enum {
515     TopQID = 1,
516     BotQID = 2,
517     LogMaxQID = 2
518   };
519
520   ScheduleDAGMI *DAG;
521   const TargetSchedModel *SchedModel;
522   SchedRemainder *Rem;
523
524   ReadyQueue Available;
525   ReadyQueue Pending;
526
527   ScheduleHazardRecognizer *HazardRec;
528
529 private:
530   /// True if the pending Q should be checked/updated before scheduling another
531   /// instruction.
532   bool CheckPending;
533
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;
537
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.
540   /// See getStalls().
541   unsigned CurrCycle;
542
543   /// Micro-ops issued in the current cycle
544   unsigned CurrMOps;
545
546   /// MinReadyCycle - Cycle of the soonest available instruction.
547   unsigned MinReadyCycle;
548
549   // The expected latency of the critical path in this scheduled zone.
550   unsigned ExpectedLatency;
551
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;
556
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;
560
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;
567
568   /// Cache the max count for a single resource.
569   unsigned MaxExecutedResCount;
570
571   // Cache the critical resources ID in this scheduled zone.
572   unsigned ZoneCritResIdx;
573
574   // Is the scheduled region resource limited vs. latency limited.
575   bool IsResourceLimited;
576
577   // Record the highest cycle at which each resource has been reserved by a
578   // scheduled instruction.
579   SmallVector<unsigned, 16> ReservedCycles;
580
581 #ifndef NDEBUG
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;
585 #endif
586
587 public:
588   /// Pending queues extend the ready queues with the same ID and the
589   /// PendingFlag set.
590   SchedBoundary(unsigned ID, const Twine &Name):
591     DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
592     Pending(ID << LogMaxQID, Name+".P"),
593     HazardRec(0) {
594     reset();
595   }
596
597   ~SchedBoundary();
598
599   void reset();
600
601   void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
602             SchedRemainder *rem);
603
604   bool isTop() const {
605     return Available.getID() == TopQID;
606   }
607
608   /// Number of cycles to issue the instructions scheduled in this zone.
609   unsigned getCurrCycle() const { return CurrCycle; }
610
611   /// Micro-ops issued in the current cycle
612   unsigned getCurrMOps() const { return CurrMOps; }
613
614   /// Return true if the given SU is used by the most recently scheduled
615   /// instruction.
616   bool isNextSU(const SUnit *SU) const { return NextSUs.count(SU); }
617
618   // The latency of dependence chains leading into this zone.
619   unsigned getDependentLatency() const { return DependentLatency; }
620
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);
626   }
627
628   unsigned getUnscheduledLatency(SUnit *SU) const {
629     return isTop() ? SU->getHeight() : SU->getDepth();
630   }
631
632   unsigned getResourceCount(unsigned ResIdx) const {
633     return ExecutedResCounts[ResIdx];
634   }
635
636   /// Get the scaled count of scheduled micro-ops and resources, including
637   /// executed resources.
638   unsigned getCriticalCount() const {
639     if (!ZoneCritResIdx)
640       return RetiredMOps * SchedModel->getMicroOpFactor();
641     return getResourceCount(ZoneCritResIdx);
642   }
643
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
646   /// feedback loop.
647   unsigned getExecutedCount() const {
648     return std::max(CurrCycle * SchedModel->getLatencyFactor(),
649                     MaxExecutedResCount);
650   }
651
652   unsigned getZoneCritResIdx() const { return ZoneCritResIdx; }
653
654   // Is the scheduled region resource limited vs. latency limited.
655   bool isResourceLimited() const { return IsResourceLimited; }
656
657   /// Get the difference between the given SUnit's ready time and the current
658   /// cycle.
659   unsigned getLatencyStallCycles(SUnit *SU);
660
661   unsigned getNextResourceCycle(unsigned PIdx, unsigned Cycles);
662
663   bool checkHazard(SUnit *SU);
664
665   unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
666
667   unsigned getOtherResourceCount(unsigned &OtherCritIdx);
668
669   void releaseNode(SUnit *SU, unsigned ReadyCycle);
670
671   void releaseTopNode(SUnit *SU);
672
673   void releaseBottomNode(SUnit *SU);
674
675   void bumpCycle(unsigned NextCycle);
676
677   void incExecutedResources(unsigned PIdx, unsigned Count);
678
679   unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
680
681   void bumpNode(SUnit *SU);
682
683   void releasePending();
684
685   void removeReady(SUnit *SU);
686
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();
691
692 #ifndef NDEBUG
693   void dumpScheduledState();
694 #endif
695 };
696
697 } // namespace llvm
698
699 #endif