misched: add a hook for custom DAG postprocessing.
[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 a MachineSchedRegistry for registering alternative machine
11 // schedulers. A Target may provide an alternative scheduler implementation by
12 // implementing the following boilerplate:
13 //
14 // static ScheduleDAGInstrs *createCustomMachineSched(MachineSchedContext *C) {
15 //  return new CustomMachineScheduler(C);
16 // }
17 // static MachineSchedRegistry
18 // SchedCustomRegistry("custom", "Run my target's custom scheduler",
19 //                     createCustomMachineSched);
20 //
21 // Inside <Target>PassConfig:
22 //   enablePass(&MachineSchedulerID);
23 //   MachineSchedRegistry::setDefault(createCustomMachineSched);
24 //
25 //===----------------------------------------------------------------------===//
26
27 #ifndef MACHINESCHEDULER_H
28 #define MACHINESCHEDULER_H
29
30 #include "llvm/CodeGen/MachinePassRegistry.h"
31 #include "llvm/CodeGen/RegisterPressure.h"
32 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/MC/MCInstrItineraries.h"
35
36 namespace llvm {
37
38 extern cl::opt<bool> ForceTopDown;
39 extern cl::opt<bool> ForceBottomUp;
40
41 class AliasAnalysis;
42 class LiveIntervals;
43 class MachineDominatorTree;
44 class MachineLoopInfo;
45 class RegisterClassInfo;
46 class ScheduleDAGInstrs;
47
48 /// MachineSchedContext provides enough context from the MachineScheduler pass
49 /// for the target to instantiate a scheduler.
50 struct MachineSchedContext {
51   MachineFunction *MF;
52   const MachineLoopInfo *MLI;
53   const MachineDominatorTree *MDT;
54   const TargetPassConfig *PassConfig;
55   AliasAnalysis *AA;
56   LiveIntervals *LIS;
57
58   RegisterClassInfo *RegClassInfo;
59
60   MachineSchedContext();
61   virtual ~MachineSchedContext();
62 };
63
64 /// MachineSchedRegistry provides a selection of available machine instruction
65 /// schedulers.
66 class MachineSchedRegistry : public MachinePassRegistryNode {
67 public:
68   typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineSchedContext *);
69
70   // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
71   typedef ScheduleDAGCtor FunctionPassCtor;
72
73   static MachinePassRegistry Registry;
74
75   MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
76     : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
77     Registry.Add(this);
78   }
79   ~MachineSchedRegistry() { Registry.Remove(this); }
80
81   // Accessors.
82   //
83   MachineSchedRegistry *getNext() const {
84     return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
85   }
86   static MachineSchedRegistry *getList() {
87     return (MachineSchedRegistry *)Registry.getList();
88   }
89   static ScheduleDAGCtor getDefault() {
90     return (ScheduleDAGCtor)Registry.getDefault();
91   }
92   static void setDefault(ScheduleDAGCtor C) {
93     Registry.setDefault((MachinePassCtor)C);
94   }
95   static void setDefault(StringRef Name) {
96     Registry.setDefault(Name);
97   }
98   static void setListener(MachinePassRegistryListener *L) {
99     Registry.setListener(L);
100   }
101 };
102
103 class ScheduleDAGMI;
104
105 /// MachineSchedStrategy - Interface to the scheduling algorithm used by
106 /// ScheduleDAGMI.
107 class MachineSchedStrategy {
108 public:
109   virtual ~MachineSchedStrategy() {}
110
111   /// Initialize the strategy after building the DAG for a new region.
112   virtual void initialize(ScheduleDAGMI *DAG) = 0;
113
114   /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
115   /// schedule the node at the top of the unscheduled region. Otherwise it will
116   /// be scheduled at the bottom.
117   virtual SUnit *pickNode(bool &IsTopNode) = 0;
118
119   /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an
120   /// instruction and updated scheduled/remaining flags in the DAG nodes.
121   virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
122
123   /// When all predecessor dependencies have been resolved, free this node for
124   /// top-down scheduling.
125   virtual void releaseTopNode(SUnit *SU) = 0;
126   /// When all successor dependencies have been resolved, free this node for
127   /// bottom-up scheduling.
128   virtual void releaseBottomNode(SUnit *SU) = 0;
129 };
130
131 /// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
132 /// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
133 /// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
134 ///
135 /// This is a convenience class that may be used by implementations of
136 /// MachineSchedStrategy.
137 class ReadyQueue {
138   unsigned ID;
139   std::string Name;
140   std::vector<SUnit*> Queue;
141
142 public:
143   ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
144
145   unsigned getID() const { return ID; }
146
147   StringRef getName() const { return Name; }
148
149   // SU is in this queue if it's NodeQueueID is a superset of this ID.
150   bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
151
152   bool empty() const { return Queue.empty(); }
153
154   unsigned size() const { return Queue.size(); }
155
156   typedef std::vector<SUnit*>::iterator iterator;
157
158   iterator begin() { return Queue.begin(); }
159
160   iterator end() { return Queue.end(); }
161
162   iterator find(SUnit *SU) {
163     return std::find(Queue.begin(), Queue.end(), SU);
164   }
165
166   void push(SUnit *SU) {
167     Queue.push_back(SU);
168     SU->NodeQueueId |= ID;
169   }
170
171   void remove(iterator I) {
172     (*I)->NodeQueueId &= ~ID;
173     *I = Queue.back();
174     Queue.pop_back();
175   }
176
177 #ifndef NDEBUG
178   void dump();
179 #endif
180 };
181
182 /// Mutate the DAG as a postpass after normal DAG building.
183 class ScheduleDAGMutation {
184 public:
185   virtual ~ScheduleDAGMutation() {}
186
187   virtual void apply(ScheduleDAGMI *DAG) = 0;
188 };
189
190 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
191 /// machine instructions while updating LiveIntervals and tracking regpressure.
192 class ScheduleDAGMI : public ScheduleDAGInstrs {
193 protected:
194   AliasAnalysis *AA;
195   RegisterClassInfo *RegClassInfo;
196   MachineSchedStrategy *SchedImpl;
197
198   /// Ordered list of DAG postprocessing steps.
199   std::vector<ScheduleDAGMutation*> Mutations;
200
201   MachineBasicBlock::iterator LiveRegionEnd;
202
203   /// Register pressure in this region computed by buildSchedGraph.
204   IntervalPressure RegPressure;
205   RegPressureTracker RPTracker;
206
207   /// List of pressure sets that exceed the target's pressure limit before
208   /// scheduling, listed in increasing set ID order. Each pressure set is paired
209   /// with its max pressure in the currently scheduled regions.
210   std::vector<PressureElement> RegionCriticalPSets;
211
212   /// The top of the unscheduled zone.
213   MachineBasicBlock::iterator CurrentTop;
214   IntervalPressure TopPressure;
215   RegPressureTracker TopRPTracker;
216
217   /// The bottom of the unscheduled zone.
218   MachineBasicBlock::iterator CurrentBottom;
219   IntervalPressure BotPressure;
220   RegPressureTracker BotRPTracker;
221
222 #ifndef NDEBUG
223   /// The number of instructions scheduled so far. Used to cut off the
224   /// scheduler at the point determined by misched-cutoff.
225   unsigned NumInstrsScheduled;
226 #endif
227
228 public:
229   ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
230     ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
231     AA(C->AA), RegClassInfo(C->RegClassInfo), SchedImpl(S),
232     RPTracker(RegPressure), CurrentTop(), TopRPTracker(TopPressure),
233     CurrentBottom(), BotRPTracker(BotPressure) {
234 #ifndef NDEBUG
235     NumInstrsScheduled = 0;
236 #endif
237   }
238
239   virtual ~ScheduleDAGMI() {
240     delete SchedImpl;
241   }
242
243   /// Add a postprocessing step to the DAG builder.
244   /// Mutations are applied in the order that they are added after normal DAG
245   /// building and before MachineSchedStrategy initialization.
246   void addMutation(ScheduleDAGMutation *Mutation) {
247     Mutations.push_back(Mutation);
248   }
249
250   MachineBasicBlock::iterator top() const { return CurrentTop; }
251   MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
252
253   /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
254   /// region. This covers all instructions in a block, while schedule() may only
255   /// cover a subset.
256   void enterRegion(MachineBasicBlock *bb,
257                    MachineBasicBlock::iterator begin,
258                    MachineBasicBlock::iterator end,
259                    unsigned endcount);
260
261
262   /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
263   /// reorderable instructions.
264   virtual void schedule();
265
266   /// Get current register pressure for the top scheduled instructions.
267   const IntervalPressure &getTopPressure() const { return TopPressure; }
268   const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
269
270   /// Get current register pressure for the bottom scheduled instructions.
271   const IntervalPressure &getBotPressure() const { return BotPressure; }
272   const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
273
274   /// Get register pressure for the entire scheduling region before scheduling.
275   const IntervalPressure &getRegPressure() const { return RegPressure; }
276
277   const std::vector<PressureElement> &getRegionCriticalPSets() const {
278     return RegionCriticalPSets;
279   }
280
281   /// getIssueWidth - Return the max instructions per scheduling group.
282   unsigned getIssueWidth() const {
283     return (InstrItins && InstrItins->SchedModel)
284       ? InstrItins->SchedModel->IssueWidth : 1;
285   }
286
287   /// getNumMicroOps - Return the number of issue slots required for this MI.
288   unsigned getNumMicroOps(MachineInstr *MI) const {
289     if (!InstrItins) return 1;
290     int UOps = InstrItins->getNumMicroOps(MI->getDesc().getSchedClass());
291     return (UOps >= 0) ? UOps : TII->getNumMicroOps(InstrItins, MI);
292   }
293
294 protected:
295   // Top-Level entry points for the schedule() driver...
296
297   /// Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking
298   /// enabled. This sets up three trackers. RPTracker will cover the entire DAG
299   /// region, TopTracker and BottomTracker will be initialized to the top and
300   /// bottom of the DAG region without covereing any unscheduled instruction.
301   void buildDAGWithRegPressure();
302
303   /// Apply each ScheduleDAGMutation step in order. This allows different
304   /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
305   void postprocessDAG();
306
307   /// Identify DAG roots and setup scheduler queues.
308   void initQueues();
309
310   /// Move an instruction and update register pressure.
311   void scheduleMI(SUnit *SU, bool IsTopNode);
312
313   /// Update scheduler DAG and queues after scheduling an instruction.
314   void updateQueues(SUnit *SU, bool IsTopNode);
315
316   /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
317   void placeDebugValues();
318
319   // Lesser helpers...
320
321   void initRegPressure();
322
323   void updateScheduledPressure(std::vector<unsigned> NewMaxPressure);
324
325   void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
326   bool checkSchedLimit();
327
328   void releaseRoots();
329
330   void releaseSucc(SUnit *SU, SDep *SuccEdge);
331   void releaseSuccessors(SUnit *SU);
332   void releasePred(SUnit *SU, SDep *PredEdge);
333   void releasePredecessors(SUnit *SU);
334 };
335
336 } // namespace llvm
337
338 #endif