1 //==- ScheduleDAGInstrs.h - MachineInstr Scheduling --------------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ScheduleDAGInstrs class, which implements
11 // scheduling for a MachineInstr-based dependency graph.
13 //===----------------------------------------------------------------------===//
15 #ifndef SCHEDULEDAGINSTRS_H
16 #define SCHEDULEDAGINSTRS_H
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"
28 class MachineLoopInfo;
29 class MachineDominatorTree;
31 class RegPressureTracker;
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.
38 class LoopDependencies {
39 const MachineLoopInfo &MLI;
40 const MachineDominatorTree &MDT;
43 typedef std::map<unsigned, std::pair<const MachineOperand *, unsigned> >
47 LoopDependencies(const MachineLoopInfo &mli,
48 const MachineDominatorTree &mdt) :
51 /// VisitLoop - Clear out any previous state and analyze the given loop.
53 void VisitLoop(const MachineLoop *Loop) {
54 assert(Deps.empty() && "stale loop dependencies");
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);
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);
70 void VisitRegion(const MachineDomTreeNode *Node,
71 const MachineBasicBlock *MBB,
72 const MachineLoop *Loop,
73 const SmallSet<unsigned, 8> &LoopLiveIns) {
75 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
77 const MachineInstr *MI = I;
78 if (MI->isDebugValue())
80 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
81 const MachineOperand &MO = MI->getOperand(i);
82 if (!MO.isReg() || !MO.isUse())
84 unsigned MOReg = MO.getReg();
85 if (LoopLiveIns.count(MOReg))
86 Deps.insert(std::make_pair(MOReg, std::make_pair(&MO, Count)));
88 ++Count; // Not every iteration due to dbg_value above.
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);
102 /// An individual mapping from virtual register number to SUnit.
107 VReg2SUnit(unsigned reg, SUnit *su): VirtReg(reg), SU(su) {}
109 unsigned getSparseSetIndex() const {
110 return TargetRegisterInfo::virtReg2Index(VirtReg);
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.
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;
124 typedef SparseSet<unsigned>::const_iterator const_iterator;
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(); }
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);
136 /// Returns true if the map is empty.
137 bool empty() const { return PhysRegSet.empty(); }
139 /// Clear the map without deallocating storage.
142 bool contains(unsigned Reg) const { return PhysRegSet.count(Reg); }
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");
153 /// Erase an existing element without freeing memory.
154 void erase(unsigned Reg) {
155 PhysRegSet.erase(Reg);
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;
166 /// ScheduleDAGInstrs - A ScheduleDAG subclass for scheduling lists of
168 class ScheduleDAGInstrs : public ScheduleDAG {
170 const MachineLoopInfo &MLI;
171 const MachineDominatorTree &MDT;
172 const MachineFrameInfo *MFI;
173 const InstrItineraryData *InstrItins;
175 /// Live Intervals provides reaching defs in preRA scheduling.
178 /// isPostRA flag indicates vregs cannot be present.
181 /// UnitLatencies (misnamed) flag avoids computing def-use latencies, using
182 /// the def-side latency only.
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;
192 /// State specific to the current scheduling region.
193 /// ------------------------------------------------
195 /// The block in which to insert instructions
196 MachineBasicBlock *BB;
198 /// The beginning of the range to be scheduled.
199 MachineBasicBlock::iterator RegionBegin;
201 /// The end of the range to be scheduled.
202 MachineBasicBlock::iterator RegionEnd;
204 /// The index in BB of RegionEnd.
207 /// After calling BuildSchedGraph, each machine instruction in the current
208 /// scheduling region is mapped to an SUnit.
209 DenseMap<MachineInstr*, SUnit*> MISUnitMap;
211 /// State internal to DAG building.
212 /// -------------------------------
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.
221 /// Track the last instructon in this region defining each virtual register.
222 VReg2SUnitMap VRegDefs;
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;
229 /// LoopRegs - Track which registers are used for loop-carried dependencies.
231 LoopDependencies LoopRegs;
233 /// DbgValues - Remember instruction that preceeds 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 *> >
238 DbgValueVector DbgValues;
239 MachineInstr *FirstDbgValue;
242 explicit ScheduleDAGInstrs(MachineFunction &mf,
243 const MachineLoopInfo &mli,
244 const MachineDominatorTree &mdt,
246 LiveIntervals *LIS = 0);
248 virtual ~ScheduleDAGInstrs() {}
250 /// begin - Return an iterator to the top of the current scheduling region.
251 MachineBasicBlock::iterator begin() const { return RegionBegin; }
253 /// end - Return an iterator to the bottom of the current scheduling region.
254 MachineBasicBlock::iterator end() const { return RegionEnd; }
256 /// newSUnit - Creates a new SUnit and return a ptr to it.
257 SUnit *newSUnit(MachineInstr *MI);
259 /// getSUnit - Return an existing SUnit for this MI, or NULL.
260 SUnit *getSUnit(MachineInstr *MI) const;
262 /// startBlock - Prepare to perform scheduling in the given block.
263 virtual void startBlock(MachineBasicBlock *BB);
265 /// finishBlock - Clean up after scheduling in the given block.
266 virtual void finishBlock();
268 /// Initialize the scheduler state for the next scheduling region.
269 virtual void enterRegion(MachineBasicBlock *bb,
270 MachineBasicBlock::iterator begin,
271 MachineBasicBlock::iterator end,
274 /// Notify that the scheduler has finished scheduling the current region.
275 virtual void exitRegion();
277 /// buildSchedGraph - Build SUnits from the MachineBasicBlock that we are
279 void buildSchedGraph(AliasAnalysis *AA, RegPressureTracker *RPTracker = 0);
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();
290 /// computeLatency - Compute node latency.
292 virtual void computeLatency(SUnit *SU);
294 /// computeOperandLatency - Override dependence edge latency using
295 /// operand use/def information
297 virtual void computeOperandLatency(SUnit *Def, SUnit *Use,
300 /// schedule - Order nodes according to selected style, filling
301 /// in the Sequence member.
303 /// Typically, a scheduling algorithm will implement schedule() without
304 /// overriding enterRegion() or exitRegion().
305 virtual void schedule() = 0;
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() {}
311 virtual void dumpNode(const SUnit *SU) const;
313 /// Return a label for a DAG node that points to an instruction.
314 virtual std::string getGraphNodeLabel(const SUnit *SU) const;
316 /// Return a label for the region of code covered by the DAG.
317 virtual std::string getDAGName() const;
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);
327 /// newSUnit - Creates a new SUnit and return a ptr to it.
328 inline SUnit *ScheduleDAGInstrs::newSUnit(MachineInstr *MI) {
330 const SUnit *Addr = SUnits.empty() ? 0 : &SUnits[0];
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();
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())