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