TargetSchedModel API. Implement latency lookup, disabled.
[oota-llvm.git] / include / llvm / CodeGen / ScheduleDAGInstrs.h
1 //==- ScheduleDAGInstrs.h - MachineInstr Scheduling --------------*- 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 implements the ScheduleDAGInstrs class, which implements
11 // scheduling for a MachineInstr-based dependency graph.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef SCHEDULEDAGINSTRS_H
16 #define SCHEDULEDAGINSTRS_H
17
18 #include "llvm/CodeGen/MachineDominators.h"
19 #include "llvm/CodeGen/MachineLoopInfo.h"
20 #include "llvm/CodeGen/ScheduleDAG.h"
21 #include "llvm/CodeGen/TargetSchedule.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SparseSet.h"
26 #include <map>
27
28 namespace llvm {
29   class MachineLoopInfo;
30   class MachineDominatorTree;
31   class LiveIntervals;
32   class RegPressureTracker;
33
34   /// LoopDependencies - This class analyzes loop-oriented register
35   /// dependencies, which are used to guide scheduling decisions.
36   /// For example, loop induction variable increments should be
37   /// scheduled as soon as possible after the variable's last use.
38   ///
39   class LoopDependencies {
40     const MachineDominatorTree &MDT;
41
42   public:
43     typedef std::map<unsigned, std::pair<const MachineOperand *, unsigned> >
44       LoopDeps;
45     LoopDeps Deps;
46
47     LoopDependencies(const MachineDominatorTree &mdt) : MDT(mdt) {}
48
49     /// VisitLoop - Clear out any previous state and analyze the given loop.
50     ///
51     void VisitLoop(const MachineLoop *Loop) {
52       assert(Deps.empty() && "stale loop dependencies");
53
54       MachineBasicBlock *Header = Loop->getHeader();
55       SmallSet<unsigned, 8> LoopLiveIns;
56       for (MachineBasicBlock::livein_iterator LI = Header->livein_begin(),
57            LE = Header->livein_end(); LI != LE; ++LI)
58         LoopLiveIns.insert(*LI);
59
60       const MachineDomTreeNode *Node = MDT.getNode(Header);
61       const MachineBasicBlock *MBB = Node->getBlock();
62       assert(Loop->contains(MBB) &&
63              "Loop does not contain header!");
64       VisitRegion(Node, MBB, Loop, LoopLiveIns);
65     }
66
67   private:
68     void VisitRegion(const MachineDomTreeNode *Node,
69                      const MachineBasicBlock *MBB,
70                      const MachineLoop *Loop,
71                      const SmallSet<unsigned, 8> &LoopLiveIns) {
72       unsigned Count = 0;
73       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
74            I != E; ++I) {
75         const MachineInstr *MI = I;
76         if (MI->isDebugValue())
77           continue;
78         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
79           const MachineOperand &MO = MI->getOperand(i);
80           if (!MO.isReg() || !MO.isUse())
81             continue;
82           unsigned MOReg = MO.getReg();
83           if (LoopLiveIns.count(MOReg))
84             Deps.insert(std::make_pair(MOReg, std::make_pair(&MO, Count)));
85         }
86         ++Count; // Not every iteration due to dbg_value above.
87       }
88
89       const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
90       for (std::vector<MachineDomTreeNode*>::const_iterator I =
91            Children.begin(), E = Children.end(); I != E; ++I) {
92         const MachineDomTreeNode *ChildNode = *I;
93         MachineBasicBlock *ChildBlock = ChildNode->getBlock();
94         if (Loop->contains(ChildBlock))
95           VisitRegion(ChildNode, ChildBlock, Loop, LoopLiveIns);
96       }
97     }
98   };
99
100   /// An individual mapping from virtual register number to SUnit.
101   struct VReg2SUnit {
102     unsigned VirtReg;
103     SUnit *SU;
104
105     VReg2SUnit(unsigned reg, SUnit *su): VirtReg(reg), SU(su) {}
106
107     unsigned getSparseSetIndex() const {
108       return TargetRegisterInfo::virtReg2Index(VirtReg);
109     }
110   };
111
112   /// Record a physical register access.
113   /// For non data-dependent uses, OpIdx == -1.
114   struct PhysRegSUOper {
115     SUnit *SU;
116     int OpIdx;
117
118     PhysRegSUOper(SUnit *su, int op): SU(su), OpIdx(op) {}
119   };
120
121   /// Combine a SparseSet with a 1x1 vector to track physical registers.
122   /// The SparseSet allows iterating over the (few) live registers for quickly
123   /// comparing against a regmask or clearing the set.
124   ///
125   /// Storage for the map is allocated once for the pass. The map can be
126   /// cleared between scheduling regions without freeing unused entries.
127   class Reg2SUnitsMap {
128     SparseSet<unsigned> PhysRegSet;
129     std::vector<std::vector<PhysRegSUOper> > SUnits;
130   public:
131     typedef SparseSet<unsigned>::const_iterator const_iterator;
132
133     // Allow iteration over register numbers (keys) in the map. If needed, we
134     // can provide an iterator over SUnits (values) as well.
135     const_iterator reg_begin() const { return PhysRegSet.begin(); }
136     const_iterator reg_end() const { return PhysRegSet.end(); }
137
138     /// Initialize the map with the number of registers.
139     /// If the map is already large enough, no allocation occurs.
140     /// For simplicity we expect the map to be empty().
141     void setRegLimit(unsigned Limit);
142
143     /// Returns true if the map is empty.
144     bool empty() const { return PhysRegSet.empty(); }
145
146     /// Clear the map without deallocating storage.
147     void clear();
148
149     bool contains(unsigned Reg) const { return PhysRegSet.count(Reg); }
150
151     /// If this register is mapped, return its existing SUnits vector.
152     /// Otherwise map the register and return an empty SUnits vector.
153     std::vector<PhysRegSUOper> &operator[](unsigned Reg) {
154       bool New = PhysRegSet.insert(Reg).second;
155       assert((!New || SUnits[Reg].empty()) && "stale SUnits vector");
156       (void)New;
157       return SUnits[Reg];
158     }
159
160     /// Erase an existing element without freeing memory.
161     void erase(unsigned Reg) {
162       PhysRegSet.erase(Reg);
163       SUnits[Reg].clear();
164     }
165   };
166
167   /// Use SparseSet as a SparseMap by relying on the fact that it never
168   /// compares ValueT's, only unsigned keys. This allows the set to be cleared
169   /// between scheduling regions in constant time as long as ValueT does not
170   /// require a destructor.
171   typedef SparseSet<VReg2SUnit, VirtReg2IndexFunctor> VReg2SUnitMap;
172
173   /// ScheduleDAGInstrs - A ScheduleDAG subclass for scheduling lists of
174   /// MachineInstrs.
175   class ScheduleDAGInstrs : public ScheduleDAG {
176   protected:
177     const MachineLoopInfo &MLI;
178     const MachineDominatorTree &MDT;
179     const MachineFrameInfo *MFI;
180     const InstrItineraryData *InstrItins;
181
182     /// Live Intervals provides reaching defs in preRA scheduling.
183     LiveIntervals *LIS;
184
185     /// TargetSchedModel provides an interface to the machine model.
186     TargetSchedModel SchedModel;
187
188     /// isPostRA flag indicates vregs cannot be present.
189     bool IsPostRA;
190
191     /// UnitLatencies (misnamed) flag avoids computing def-use latencies, using
192     /// the def-side latency only.
193     bool UnitLatencies;
194
195     /// The standard DAG builder does not normally include terminators as DAG
196     /// nodes because it does not create the necessary dependencies to prevent
197     /// reordering. A specialized scheduler can overide
198     /// TargetInstrInfo::isSchedulingBoundary then enable this flag to indicate
199     /// it has taken responsibility for scheduling the terminator correctly.
200     bool CanHandleTerminators;
201
202     /// State specific to the current scheduling region.
203     /// ------------------------------------------------
204
205     /// The block in which to insert instructions
206     MachineBasicBlock *BB;
207
208     /// The beginning of the range to be scheduled.
209     MachineBasicBlock::iterator RegionBegin;
210
211     /// The end of the range to be scheduled.
212     MachineBasicBlock::iterator RegionEnd;
213
214     /// The index in BB of RegionEnd.
215     unsigned EndIndex;
216
217     /// After calling BuildSchedGraph, each machine instruction in the current
218     /// scheduling region is mapped to an SUnit.
219     DenseMap<MachineInstr*, SUnit*> MISUnitMap;
220
221     /// State internal to DAG building.
222     /// -------------------------------
223
224     /// Defs, Uses - Remember where defs and uses of each register are as we
225     /// iterate upward through the instructions. This is allocated here instead
226     /// of inside BuildSchedGraph to avoid the need for it to be initialized and
227     /// destructed for each block.
228     Reg2SUnitsMap Defs;
229     Reg2SUnitsMap Uses;
230
231     /// Track the last instructon in this region defining each virtual register.
232     VReg2SUnitMap VRegDefs;
233
234     /// PendingLoads - Remember where unknown loads are after the most recent
235     /// unknown store, as we iterate. As with Defs and Uses, this is here
236     /// to minimize construction/destruction.
237     std::vector<SUnit *> PendingLoads;
238
239     /// LoopRegs - Track which registers are used for loop-carried dependencies.
240     ///
241     LoopDependencies LoopRegs;
242
243     /// DbgValues - Remember instruction that precedes DBG_VALUE.
244     /// These are generated by buildSchedGraph but persist so they can be
245     /// referenced when emitting the final schedule.
246     typedef std::vector<std::pair<MachineInstr *, MachineInstr *> >
247       DbgValueVector;
248     DbgValueVector DbgValues;
249     MachineInstr *FirstDbgValue;
250
251   public:
252     explicit ScheduleDAGInstrs(MachineFunction &mf,
253                                const MachineLoopInfo &mli,
254                                const MachineDominatorTree &mdt,
255                                bool IsPostRAFlag,
256                                LiveIntervals *LIS = 0);
257
258     virtual ~ScheduleDAGInstrs() {}
259
260     /// begin - Return an iterator to the top of the current scheduling region.
261     MachineBasicBlock::iterator begin() const { return RegionBegin; }
262
263     /// end - Return an iterator to the bottom of the current scheduling region.
264     MachineBasicBlock::iterator end() const { return RegionEnd; }
265
266     /// newSUnit - Creates a new SUnit and return a ptr to it.
267     SUnit *newSUnit(MachineInstr *MI);
268
269     /// getSUnit - Return an existing SUnit for this MI, or NULL.
270     SUnit *getSUnit(MachineInstr *MI) const;
271
272     /// startBlock - Prepare to perform scheduling in the given block.
273     virtual void startBlock(MachineBasicBlock *BB);
274
275     /// finishBlock - Clean up after scheduling in the given block.
276     virtual void finishBlock();
277
278     /// Initialize the scheduler state for the next scheduling region.
279     virtual void enterRegion(MachineBasicBlock *bb,
280                              MachineBasicBlock::iterator begin,
281                              MachineBasicBlock::iterator end,
282                              unsigned endcount);
283
284     /// Notify that the scheduler has finished scheduling the current region.
285     virtual void exitRegion();
286
287     /// buildSchedGraph - Build SUnits from the MachineBasicBlock that we are
288     /// input.
289     void buildSchedGraph(AliasAnalysis *AA, RegPressureTracker *RPTracker = 0);
290
291     /// addSchedBarrierDeps - Add dependencies from instructions in the current
292     /// list of instructions being scheduled to scheduling barrier. We want to
293     /// make sure instructions which define registers that are either used by
294     /// the terminator or are live-out are properly scheduled. This is
295     /// especially important when the definition latency of the return value(s)
296     /// are too high to be hidden by the branch or when the liveout registers
297     /// used by instructions in the fallthrough block.
298     void addSchedBarrierDeps();
299
300     /// computeLatency - Compute node latency.
301     ///
302     virtual void computeLatency(SUnit *SU);
303
304     /// schedule - Order nodes according to selected style, filling
305     /// in the Sequence member.
306     ///
307     /// Typically, a scheduling algorithm will implement schedule() without
308     /// overriding enterRegion() or exitRegion().
309     virtual void schedule() = 0;
310
311     /// finalizeSchedule - Allow targets to perform final scheduling actions at
312     /// the level of the whole MachineFunction. By default does nothing.
313     virtual void finalizeSchedule() {}
314
315     virtual void dumpNode(const SUnit *SU) const;
316
317     /// Return a label for a DAG node that points to an instruction.
318     virtual std::string getGraphNodeLabel(const SUnit *SU) const;
319
320     /// Return a label for the region of code covered by the DAG.
321     virtual std::string getDAGName() const;
322
323   protected:
324     void initSUnits();
325     void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx);
326     void addPhysRegDeps(SUnit *SU, unsigned OperIdx);
327     void addVRegDefDeps(SUnit *SU, unsigned OperIdx);
328     void addVRegUseDeps(SUnit *SU, unsigned OperIdx);
329   };
330
331   /// newSUnit - Creates a new SUnit and return a ptr to it.
332   inline SUnit *ScheduleDAGInstrs::newSUnit(MachineInstr *MI) {
333 #ifndef NDEBUG
334     const SUnit *Addr = SUnits.empty() ? 0 : &SUnits[0];
335 #endif
336     SUnits.push_back(SUnit(MI, (unsigned)SUnits.size()));
337     assert((Addr == 0 || Addr == &SUnits[0]) &&
338            "SUnits std::vector reallocated on the fly!");
339     SUnits.back().OrigNode = &SUnits.back();
340     return &SUnits.back();
341   }
342
343   /// getSUnit - Return an existing SUnit for this MI, or NULL.
344   inline SUnit *ScheduleDAGInstrs::getSUnit(MachineInstr *MI) const {
345     DenseMap<MachineInstr*, SUnit*>::const_iterator I = MISUnitMap.find(MI);
346     if (I == MISUnitMap.end())
347       return 0;
348     return I->second;
349   }
350 } // namespace llvm
351
352 #endif