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 LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
16 #define LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/SparseMultiSet.h"
20 #include "llvm/ADT/SparseSet.h"
21 #include "llvm/CodeGen/ScheduleDAG.h"
22 #include "llvm/CodeGen/TargetSchedule.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
28 class MachineFrameInfo;
29 class MachineLoopInfo;
30 class MachineDominatorTree;
31 class RegPressureTracker;
34 /// An individual mapping from virtual register number to SUnit.
40 VReg2SUnit(unsigned VReg, LaneBitmask LaneMask, SUnit *SU)
41 : VirtReg(VReg), LaneMask(LaneMask), SU(SU) {}
43 unsigned getSparseSetIndex() const {
44 return TargetRegisterInfo::virtReg2Index(VirtReg);
48 /// Mapping from virtual register to SUnit including an operand index.
49 struct VReg2SUnitOperIdx : public VReg2SUnit {
50 unsigned OperandIndex;
52 VReg2SUnitOperIdx(unsigned VReg, LaneBitmask LaneMask,
53 unsigned OperandIndex, SUnit *SU)
54 : VReg2SUnit(VReg, LaneMask, SU), OperandIndex(OperandIndex) {}
57 /// Record a physical register access.
58 /// For non-data-dependent uses, OpIdx == -1.
59 struct PhysRegSUOper {
64 PhysRegSUOper(SUnit *su, int op, unsigned R): SU(su), OpIdx(op), Reg(R) {}
66 unsigned getSparseSetIndex() const { return Reg; }
69 /// Use a SparseMultiSet to track physical registers. Storage is only
70 /// allocated once for the pass. It can be cleared in constant time and reused
71 /// without any frees.
72 typedef SparseMultiSet<PhysRegSUOper, llvm::identity<unsigned>, uint16_t>
75 /// Use SparseSet as a SparseMap by relying on the fact that it never
76 /// compares ValueT's, only unsigned keys. This allows the set to be cleared
77 /// between scheduling regions in constant time as long as ValueT does not
78 /// require a destructor.
79 typedef SparseSet<VReg2SUnit, VirtReg2IndexFunctor> VReg2SUnitMap;
81 /// Track local uses of virtual registers. These uses are gathered by the DAG
82 /// builder and may be consulted by the scheduler to avoid iterating an entire
84 typedef SparseMultiSet<VReg2SUnit, VirtReg2IndexFunctor> VReg2SUnitMultiMap;
86 typedef SparseMultiSet<VReg2SUnitOperIdx, VirtReg2IndexFunctor>
87 VReg2SUnitOperIdxMultiMap;
89 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
90 struct UnderlyingObject : PointerIntPair<ValueType, 1, bool> {
91 UnderlyingObject(ValueType V, bool MayAlias)
92 : PointerIntPair<ValueType, 1, bool>(V, MayAlias) {}
93 ValueType getValue() const { return getPointer(); }
94 bool mayAlias() const { return getInt(); }
96 typedef SmallVector<UnderlyingObject, 4> UnderlyingObjectsVector;
98 /// ScheduleDAGInstrs - A ScheduleDAG subclass for scheduling lists of
100 class ScheduleDAGInstrs : public ScheduleDAG {
102 const MachineLoopInfo *MLI;
103 const MachineFrameInfo &MFI;
105 /// TargetSchedModel provides an interface to the machine model.
106 TargetSchedModel SchedModel;
108 /// True if the DAG builder should remove kill flags (in preparation for
110 bool RemoveKillFlags;
112 /// The standard DAG builder does not normally include terminators as DAG
113 /// nodes because it does not create the necessary dependencies to prevent
114 /// reordering. A specialized scheduler can override
115 /// TargetInstrInfo::isSchedulingBoundary then enable this flag to indicate
116 /// it has taken responsibility for scheduling the terminator correctly.
117 bool CanHandleTerminators;
119 /// Whether lane masks should get tracked.
122 /// State specific to the current scheduling region.
123 /// ------------------------------------------------
125 /// The block in which to insert instructions
126 MachineBasicBlock *BB;
128 /// The beginning of the range to be scheduled.
129 MachineBasicBlock::iterator RegionBegin;
131 /// The end of the range to be scheduled.
132 MachineBasicBlock::iterator RegionEnd;
134 /// Instructions in this region (distance(RegionBegin, RegionEnd)).
135 unsigned NumRegionInstrs;
137 /// After calling BuildSchedGraph, each machine instruction in the current
138 /// scheduling region is mapped to an SUnit.
139 DenseMap<MachineInstr*, SUnit*> MISUnitMap;
141 /// State internal to DAG building.
142 /// -------------------------------
144 /// Defs, Uses - Remember where defs and uses of each register are as we
145 /// iterate upward through the instructions. This is allocated here instead
146 /// of inside BuildSchedGraph to avoid the need for it to be initialized and
147 /// destructed for each block.
151 /// Tracks the last instruction(s) in this region defining each virtual
152 /// register. There may be multiple current definitions for a register with
153 /// disjunct lanemasks.
154 VReg2SUnitMultiMap CurrentVRegDefs;
155 /// Tracks the last instructions in this region using each virtual register.
156 VReg2SUnitOperIdxMultiMap CurrentVRegUses;
158 AliasAnalysis *AAForDep;
160 /// Remember a generic side-effecting instruction as we proceed.
161 /// No other SU ever gets scheduled around it (except in the special
162 /// case of a huge region that gets reduced).
167 /// A list of SUnits, used in Value2SUsMap, during DAG construction.
168 /// Note: to gain speed it might be worth investigating an optimized
169 /// implementation of this data structure, such as a singly linked list
170 /// with a memory pool (SmallVector was tried but slow and SparseSet is not
172 typedef std::list<SUnit *> SUList;
174 /// A map from ValueType to SUList, used during DAG construction,
175 /// as a means of remembering which SUs depend on which memory
179 /// Remove in FIFO order some SUs from huge maps.
180 void reduceHugeMemNodeMaps(Value2SUsMap &stores,
181 Value2SUsMap &loads, unsigned N);
183 /// Add a chain edge between SUa and SUb, but only if both AliasAnalysis
184 /// and Target fail to deny the dependency.
185 void addChainDependency(SUnit *SUa, SUnit *SUb,
186 unsigned Latency = 0);
188 /// Add dependencies as needed from all SUs in list to SU.
189 void addChainDependencies(SUnit *SU, SUList &sus, unsigned Latency) {
191 addChainDependency(SU, su, Latency);
194 /// Add dependencies as needed from all SUs in map, to SU.
195 void addChainDependencies(SUnit *SU, Value2SUsMap &Val2SUsMap);
197 /// Add dependencies as needed to SU, from all SUs mapped to V.
198 void addChainDependencies(SUnit *SU, Value2SUsMap &Val2SUsMap,
201 /// Add barrier chain edges from all SUs in map, and then clear
202 /// the map. This is equivalent to insertBarrierChain(), but
203 /// optimized for the common case where the new BarrierChain (a
204 /// global memory object) has a higher NodeNum than all SUs in
205 /// map. It is assumed BarrierChain has been set before calling
207 void addBarrierChain(Value2SUsMap &map);
209 /// Insert a barrier chain in a huge region, far below current
210 /// SU. Add barrier chain edges from all SUs in map with higher
211 /// NodeNums than this new BarrierChain, and remove them from
212 /// map. It is assumed BarrierChain has been set before calling
214 void insertBarrierChain(Value2SUsMap &map);
216 /// For an unanalyzable memory access, this Value is used in maps.
217 UndefValue *UnknownValue;
219 /// DbgValues - Remember instruction that precedes DBG_VALUE.
220 /// These are generated by buildSchedGraph but persist so they can be
221 /// referenced when emitting the final schedule.
222 typedef std::vector<std::pair<MachineInstr *, MachineInstr *> >
224 DbgValueVector DbgValues;
225 MachineInstr *FirstDbgValue;
227 /// Set of live physical registers for updating kill flags.
231 explicit ScheduleDAGInstrs(MachineFunction &mf,
232 const MachineLoopInfo *mli,
233 bool RemoveKillFlags = false);
235 ~ScheduleDAGInstrs() override {}
237 /// \brief Get the machine model for instruction scheduling.
238 const TargetSchedModel *getSchedModel() const { return &SchedModel; }
240 /// \brief Resolve and cache a resolved scheduling class for an SUnit.
241 const MCSchedClassDesc *getSchedClass(SUnit *SU) const {
242 if (!SU->SchedClass && SchedModel.hasInstrSchedModel())
243 SU->SchedClass = SchedModel.resolveSchedClass(SU->getInstr());
244 return SU->SchedClass;
247 /// begin - Return an iterator to the top of the current scheduling region.
248 MachineBasicBlock::iterator begin() const { return RegionBegin; }
250 /// end - Return an iterator to the bottom of the current scheduling region.
251 MachineBasicBlock::iterator end() const { return RegionEnd; }
253 /// newSUnit - Creates a new SUnit and return a ptr to it.
254 SUnit *newSUnit(MachineInstr *MI);
256 /// getSUnit - Return an existing SUnit for this MI, or NULL.
257 SUnit *getSUnit(MachineInstr *MI) const;
259 /// startBlock - Prepare to perform scheduling in the given block.
260 virtual void startBlock(MachineBasicBlock *BB);
262 /// finishBlock - Clean up after scheduling in the given block.
263 virtual void finishBlock();
265 /// Initialize the scheduler state for the next scheduling region.
266 virtual void enterRegion(MachineBasicBlock *bb,
267 MachineBasicBlock::iterator begin,
268 MachineBasicBlock::iterator end,
269 unsigned regioninstrs);
271 /// Notify that the scheduler has finished scheduling the current region.
272 virtual void exitRegion();
274 /// buildSchedGraph - Build SUnits from the MachineBasicBlock that we are
276 void buildSchedGraph(AliasAnalysis *AA,
277 RegPressureTracker *RPTracker = nullptr,
278 PressureDiffs *PDiffs = nullptr,
279 LiveIntervals *LIS = nullptr,
280 bool TrackLaneMasks = false);
282 /// addSchedBarrierDeps - Add dependencies from instructions in the current
283 /// list of instructions being scheduled to scheduling barrier. We want to
284 /// make sure instructions which define registers that are either used by
285 /// the terminator or are live-out are properly scheduled. This is
286 /// especially important when the definition latency of the return value(s)
287 /// are too high to be hidden by the branch or when the liveout registers
288 /// used by instructions in the fallthrough block.
289 void addSchedBarrierDeps();
291 /// schedule - Order nodes according to selected style, filling
292 /// in the Sequence member.
294 /// Typically, a scheduling algorithm will implement schedule() without
295 /// overriding enterRegion() or exitRegion().
296 virtual void schedule() = 0;
298 /// finalizeSchedule - Allow targets to perform final scheduling actions at
299 /// the level of the whole MachineFunction. By default does nothing.
300 virtual void finalizeSchedule() {}
302 void dumpNode(const SUnit *SU) const override;
304 /// Return a label for a DAG node that points to an instruction.
305 std::string getGraphNodeLabel(const SUnit *SU) const override;
307 /// Return a label for the region of code covered by the DAG.
308 std::string getDAGName() const override;
310 /// \brief Fix register kill flags that scheduling has made invalid.
311 void fixupKills(MachineBasicBlock *MBB);
314 void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx);
315 void addPhysRegDeps(SUnit *SU, unsigned OperIdx);
316 void addVRegDefDeps(SUnit *SU, unsigned OperIdx);
317 void addVRegUseDeps(SUnit *SU, unsigned OperIdx);
319 /// \brief PostRA helper for rewriting kill flags.
320 void startBlockForKills(MachineBasicBlock *BB);
322 /// \brief Toggle a register operand kill flag.
324 /// Other adjustments may be made to the instruction if necessary. Return
325 /// true if the operand has been deleted, false if not.
326 bool toggleKillFlag(MachineInstr *MI, MachineOperand &MO);
328 /// Returns a mask for which lanes get read/written by the given (register)
330 LaneBitmask getLaneMaskForMO(const MachineOperand &MO) const;
333 /// newSUnit - Creates a new SUnit and return a ptr to it.
334 inline SUnit *ScheduleDAGInstrs::newSUnit(MachineInstr *MI) {
336 const SUnit *Addr = SUnits.empty() ? nullptr : &SUnits[0];
338 SUnits.emplace_back(MI, (unsigned)SUnits.size());
339 assert((Addr == nullptr || Addr == &SUnits[0]) &&
340 "SUnits std::vector reallocated on the fly!");
341 return &SUnits.back();
344 /// getSUnit - Return an existing SUnit for this MI, or NULL.
345 inline SUnit *ScheduleDAGInstrs::getSUnit(MachineInstr *MI) const {
346 DenseMap<MachineInstr*, SUnit*>::const_iterator I = MISUnitMap.find(MI);
347 if (I == MISUnitMap.end())