MachineScheduler.h 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. //===- MachineScheduler.h - MachineInstr Scheduling Pass --------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file provides an interface for customizing the standard MachineScheduler
  10. // pass. Note that the entire pass may be replaced as follows:
  11. //
  12. // <Target>TargetMachine::createPassConfig(PassManagerBase &PM) {
  13. // PM.substitutePass(&MachineSchedulerID, &CustomSchedulerPassID);
  14. // ...}
  15. //
  16. // The MachineScheduler pass is only responsible for choosing the regions to be
  17. // scheduled. Targets can override the DAG builder and scheduler without
  18. // replacing the pass as follows:
  19. //
  20. // ScheduleDAGInstrs *<Target>PassConfig::
  21. // createMachineScheduler(MachineSchedContext *C) {
  22. // return new CustomMachineScheduler(C);
  23. // }
  24. //
  25. // The default scheduler, ScheduleDAGMILive, builds the DAG and drives list
  26. // scheduling while updating the instruction stream, register pressure, and live
  27. // intervals. Most targets don't need to override the DAG builder and list
  28. // scheduler, but subtargets that require custom scheduling heuristics may
  29. // plugin an alternate MachineSchedStrategy. The strategy is responsible for
  30. // selecting the highest priority node from the list:
  31. //
  32. // ScheduleDAGInstrs *<Target>PassConfig::
  33. // createMachineScheduler(MachineSchedContext *C) {
  34. // return new ScheduleDAGMILive(C, CustomStrategy(C));
  35. // }
  36. //
  37. // The DAG builder can also be customized in a sense by adding DAG mutations
  38. // that will run after DAG building and before list scheduling. DAG mutations
  39. // can adjust dependencies based on target-specific knowledge or add weak edges
  40. // to aid heuristics:
  41. //
  42. // ScheduleDAGInstrs *<Target>PassConfig::
  43. // createMachineScheduler(MachineSchedContext *C) {
  44. // ScheduleDAGMI *DAG = createGenericSchedLive(C);
  45. // DAG->addMutation(new CustomDAGMutation(...));
  46. // return DAG;
  47. // }
  48. //
  49. // A target that supports alternative schedulers can use the
  50. // MachineSchedRegistry to allow command line selection. This can be done by
  51. // implementing the following boilerplate:
  52. //
  53. // static ScheduleDAGInstrs *createCustomMachineSched(MachineSchedContext *C) {
  54. // return new CustomMachineScheduler(C);
  55. // }
  56. // static MachineSchedRegistry
  57. // SchedCustomRegistry("custom", "Run my target's custom scheduler",
  58. // createCustomMachineSched);
  59. //
  60. //
  61. // Finally, subtargets that don't need to implement custom heuristics but would
  62. // like to configure the GenericScheduler's policy for a given scheduler region,
  63. // including scheduling direction and register pressure tracking policy, can do
  64. // this:
  65. //
  66. // void <SubTarget>Subtarget::
  67. // overrideSchedPolicy(MachineSchedPolicy &Policy,
  68. // unsigned NumRegionInstrs) const {
  69. // Policy.<Flag> = true;
  70. // }
  71. //
  72. //===----------------------------------------------------------------------===//
  73. #ifndef LLVM_CODEGEN_MACHINESCHEDULER_H
  74. #define LLVM_CODEGEN_MACHINESCHEDULER_H
  75. #include "llvm/ADT/APInt.h"
  76. #include "llvm/ADT/ArrayRef.h"
  77. #include "llvm/ADT/BitVector.h"
  78. #include "llvm/ADT/STLExtras.h"
  79. #include "llvm/ADT/SmallVector.h"
  80. #include "llvm/ADT/StringRef.h"
  81. #include "llvm/ADT/Twine.h"
  82. #include "llvm/CodeGen/MachineBasicBlock.h"
  83. #include "llvm/CodeGen/MachinePassRegistry.h"
  84. #include "llvm/CodeGen/RegisterPressure.h"
  85. #include "llvm/CodeGen/ScheduleDAG.h"
  86. #include "llvm/CodeGen/ScheduleDAGInstrs.h"
  87. #include "llvm/CodeGen/ScheduleDAGMutation.h"
  88. #include "llvm/CodeGen/TargetSchedule.h"
  89. #include "llvm/Support/CommandLine.h"
  90. #include "llvm/Support/ErrorHandling.h"
  91. #include <algorithm>
  92. #include <cassert>
  93. #include <memory>
  94. #include <string>
  95. #include <vector>
  96. namespace llvm {
  97. extern cl::opt<bool> ForceTopDown;
  98. extern cl::opt<bool> ForceBottomUp;
  99. extern cl::opt<bool> VerifyScheduling;
  100. class AAResults;
  101. class LiveIntervals;
  102. class MachineDominatorTree;
  103. class MachineFunction;
  104. class MachineInstr;
  105. class MachineLoopInfo;
  106. class RegisterClassInfo;
  107. class SchedDFSResult;
  108. class ScheduleHazardRecognizer;
  109. class TargetInstrInfo;
  110. class TargetPassConfig;
  111. class TargetRegisterInfo;
  112. /// MachineSchedContext provides enough context from the MachineScheduler pass
  113. /// for the target to instantiate a scheduler.
  114. struct MachineSchedContext {
  115. MachineFunction *MF = nullptr;
  116. const MachineLoopInfo *MLI = nullptr;
  117. const MachineDominatorTree *MDT = nullptr;
  118. const TargetPassConfig *PassConfig = nullptr;
  119. AAResults *AA = nullptr;
  120. LiveIntervals *LIS = nullptr;
  121. RegisterClassInfo *RegClassInfo;
  122. MachineSchedContext();
  123. virtual ~MachineSchedContext();
  124. };
  125. /// MachineSchedRegistry provides a selection of available machine instruction
  126. /// schedulers.
  127. class MachineSchedRegistry
  128. : public MachinePassRegistryNode<
  129. ScheduleDAGInstrs *(*)(MachineSchedContext *)> {
  130. public:
  131. using ScheduleDAGCtor = ScheduleDAGInstrs *(*)(MachineSchedContext *);
  132. // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
  133. using FunctionPassCtor = ScheduleDAGCtor;
  134. static MachinePassRegistry<ScheduleDAGCtor> Registry;
  135. MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
  136. : MachinePassRegistryNode(N, D, C) {
  137. Registry.Add(this);
  138. }
  139. ~MachineSchedRegistry() { Registry.Remove(this); }
  140. // Accessors.
  141. //
  142. MachineSchedRegistry *getNext() const {
  143. return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
  144. }
  145. static MachineSchedRegistry *getList() {
  146. return (MachineSchedRegistry *)Registry.getList();
  147. }
  148. static void setListener(MachinePassRegistryListener<FunctionPassCtor> *L) {
  149. Registry.setListener(L);
  150. }
  151. };
  152. class ScheduleDAGMI;
  153. /// Define a generic scheduling policy for targets that don't provide their own
  154. /// MachineSchedStrategy. This can be overriden for each scheduling region
  155. /// before building the DAG.
  156. struct MachineSchedPolicy {
  157. // Allow the scheduler to disable register pressure tracking.
  158. bool ShouldTrackPressure = false;
  159. /// Track LaneMasks to allow reordering of independent subregister writes
  160. /// of the same vreg. \sa MachineSchedStrategy::shouldTrackLaneMasks()
  161. bool ShouldTrackLaneMasks = false;
  162. // Allow the scheduler to force top-down or bottom-up scheduling. If neither
  163. // is true, the scheduler runs in both directions and converges.
  164. bool OnlyTopDown = false;
  165. bool OnlyBottomUp = false;
  166. // Disable heuristic that tries to fetch nodes from long dependency chains
  167. // first.
  168. bool DisableLatencyHeuristic = false;
  169. // Compute DFSResult for use in scheduling heuristics.
  170. bool ComputeDFSResult = false;
  171. MachineSchedPolicy() = default;
  172. };
  173. /// MachineSchedStrategy - Interface to the scheduling algorithm used by
  174. /// ScheduleDAGMI.
  175. ///
  176. /// Initialization sequence:
  177. /// initPolicy -> shouldTrackPressure -> initialize(DAG) -> registerRoots
  178. class MachineSchedStrategy {
  179. virtual void anchor();
  180. public:
  181. virtual ~MachineSchedStrategy() = default;
  182. /// Optionally override the per-region scheduling policy.
  183. virtual void initPolicy(MachineBasicBlock::iterator Begin,
  184. MachineBasicBlock::iterator End,
  185. unsigned NumRegionInstrs) {}
  186. virtual void dumpPolicy() const {}
  187. /// Check if pressure tracking is needed before building the DAG and
  188. /// initializing this strategy. Called after initPolicy.
  189. virtual bool shouldTrackPressure() const { return true; }
  190. /// Returns true if lanemasks should be tracked. LaneMask tracking is
  191. /// necessary to reorder independent subregister defs for the same vreg.
  192. /// This has to be enabled in combination with shouldTrackPressure().
  193. virtual bool shouldTrackLaneMasks() const { return false; }
  194. // If this method returns true, handling of the scheduling regions
  195. // themselves (in case of a scheduling boundary in MBB) will be done
  196. // beginning with the topmost region of MBB.
  197. virtual bool doMBBSchedRegionsTopDown() const { return false; }
  198. /// Initialize the strategy after building the DAG for a new region.
  199. virtual void initialize(ScheduleDAGMI *DAG) = 0;
  200. /// Tell the strategy that MBB is about to be processed.
  201. virtual void enterMBB(MachineBasicBlock *MBB) {};
  202. /// Tell the strategy that current MBB is done.
  203. virtual void leaveMBB() {};
  204. /// Notify this strategy that all roots have been released (including those
  205. /// that depend on EntrySU or ExitSU).
  206. virtual void registerRoots() {}
  207. /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
  208. /// schedule the node at the top of the unscheduled region. Otherwise it will
  209. /// be scheduled at the bottom.
  210. virtual SUnit *pickNode(bool &IsTopNode) = 0;
  211. /// Scheduler callback to notify that a new subtree is scheduled.
  212. virtual void scheduleTree(unsigned SubtreeID) {}
  213. /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an
  214. /// instruction and updated scheduled/remaining flags in the DAG nodes.
  215. virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
  216. /// When all predecessor dependencies have been resolved, free this node for
  217. /// top-down scheduling.
  218. virtual void releaseTopNode(SUnit *SU) = 0;
  219. /// When all successor dependencies have been resolved, free this node for
  220. /// bottom-up scheduling.
  221. virtual void releaseBottomNode(SUnit *SU) = 0;
  222. };
  223. /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply
  224. /// schedules machine instructions according to the given MachineSchedStrategy
  225. /// without much extra book-keeping. This is the common functionality between
  226. /// PreRA and PostRA MachineScheduler.
  227. class ScheduleDAGMI : public ScheduleDAGInstrs {
  228. protected:
  229. AAResults *AA;
  230. LiveIntervals *LIS;
  231. std::unique_ptr<MachineSchedStrategy> SchedImpl;
  232. /// Ordered list of DAG postprocessing steps.
  233. std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
  234. /// The top of the unscheduled zone.
  235. MachineBasicBlock::iterator CurrentTop;
  236. /// The bottom of the unscheduled zone.
  237. MachineBasicBlock::iterator CurrentBottom;
  238. /// Record the next node in a scheduled cluster.
  239. const SUnit *NextClusterPred = nullptr;
  240. const SUnit *NextClusterSucc = nullptr;
  241. #ifndef NDEBUG
  242. /// The number of instructions scheduled so far. Used to cut off the
  243. /// scheduler at the point determined by misched-cutoff.
  244. unsigned NumInstrsScheduled = 0;
  245. #endif
  246. public:
  247. ScheduleDAGMI(MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S,
  248. bool RemoveKillFlags)
  249. : ScheduleDAGInstrs(*C->MF, C->MLI, RemoveKillFlags), AA(C->AA),
  250. LIS(C->LIS), SchedImpl(std::move(S)) {}
  251. // Provide a vtable anchor
  252. ~ScheduleDAGMI() override;
  253. /// If this method returns true, handling of the scheduling regions
  254. /// themselves (in case of a scheduling boundary in MBB) will be done
  255. /// beginning with the topmost region of MBB.
  256. bool doMBBSchedRegionsTopDown() const override {
  257. return SchedImpl->doMBBSchedRegionsTopDown();
  258. }
  259. // Returns LiveIntervals instance for use in DAG mutators and such.
  260. LiveIntervals *getLIS() const { return LIS; }
  261. /// Return true if this DAG supports VReg liveness and RegPressure.
  262. virtual bool hasVRegLiveness() const { return false; }
  263. /// Add a postprocessing step to the DAG builder.
  264. /// Mutations are applied in the order that they are added after normal DAG
  265. /// building and before MachineSchedStrategy initialization.
  266. ///
  267. /// ScheduleDAGMI takes ownership of the Mutation object.
  268. void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
  269. if (Mutation)
  270. Mutations.push_back(std::move(Mutation));
  271. }
  272. MachineBasicBlock::iterator top() const { return CurrentTop; }
  273. MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
  274. /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
  275. /// region. This covers all instructions in a block, while schedule() may only
  276. /// cover a subset.
  277. void enterRegion(MachineBasicBlock *bb,
  278. MachineBasicBlock::iterator begin,
  279. MachineBasicBlock::iterator end,
  280. unsigned regioninstrs) override;
  281. /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
  282. /// reorderable instructions.
  283. void schedule() override;
  284. void startBlock(MachineBasicBlock *bb) override;
  285. void finishBlock() override;
  286. /// Change the position of an instruction within the basic block and update
  287. /// live ranges and region boundary iterators.
  288. void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
  289. const SUnit *getNextClusterPred() const { return NextClusterPred; }
  290. const SUnit *getNextClusterSucc() const { return NextClusterSucc; }
  291. void viewGraph(const Twine &Name, const Twine &Title) override;
  292. void viewGraph() override;
  293. protected:
  294. // Top-Level entry points for the schedule() driver...
  295. /// Apply each ScheduleDAGMutation step in order. This allows different
  296. /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
  297. void postprocessDAG();
  298. /// Release ExitSU predecessors and setup scheduler queues.
  299. void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
  300. /// Update scheduler DAG and queues after scheduling an instruction.
  301. void updateQueues(SUnit *SU, bool IsTopNode);
  302. /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
  303. void placeDebugValues();
  304. /// dump the scheduled Sequence.
  305. void dumpSchedule() const;
  306. // Lesser helpers...
  307. bool checkSchedLimit();
  308. void findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
  309. SmallVectorImpl<SUnit*> &BotRoots);
  310. void releaseSucc(SUnit *SU, SDep *SuccEdge);
  311. void releaseSuccessors(SUnit *SU);
  312. void releasePred(SUnit *SU, SDep *PredEdge);
  313. void releasePredecessors(SUnit *SU);
  314. };
  315. /// ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules
  316. /// machine instructions while updating LiveIntervals and tracking regpressure.
  317. class ScheduleDAGMILive : public ScheduleDAGMI {
  318. protected:
  319. RegisterClassInfo *RegClassInfo;
  320. /// Information about DAG subtrees. If DFSResult is NULL, then SchedulerTrees
  321. /// will be empty.
  322. SchedDFSResult *DFSResult = nullptr;
  323. BitVector ScheduledTrees;
  324. MachineBasicBlock::iterator LiveRegionEnd;
  325. /// Maps vregs to the SUnits of their uses in the current scheduling region.
  326. VReg2SUnitMultiMap VRegUses;
  327. // Map each SU to its summary of pressure changes. This array is updated for
  328. // liveness during bottom-up scheduling. Top-down scheduling may proceed but
  329. // has no affect on the pressure diffs.
  330. PressureDiffs SUPressureDiffs;
  331. /// Register pressure in this region computed by initRegPressure.
  332. bool ShouldTrackPressure = false;
  333. bool ShouldTrackLaneMasks = false;
  334. IntervalPressure RegPressure;
  335. RegPressureTracker RPTracker;
  336. /// List of pressure sets that exceed the target's pressure limit before
  337. /// scheduling, listed in increasing set ID order. Each pressure set is paired
  338. /// with its max pressure in the currently scheduled regions.
  339. std::vector<PressureChange> RegionCriticalPSets;
  340. /// The top of the unscheduled zone.
  341. IntervalPressure TopPressure;
  342. RegPressureTracker TopRPTracker;
  343. /// The bottom of the unscheduled zone.
  344. IntervalPressure BotPressure;
  345. RegPressureTracker BotRPTracker;
  346. /// True if disconnected subregister components are already renamed.
  347. /// The renaming is only done on demand if lane masks are tracked.
  348. bool DisconnectedComponentsRenamed = false;
  349. public:
  350. ScheduleDAGMILive(MachineSchedContext *C,
  351. std::unique_ptr<MachineSchedStrategy> S)
  352. : ScheduleDAGMI(C, std::move(S), /*RemoveKillFlags=*/false),
  353. RegClassInfo(C->RegClassInfo), RPTracker(RegPressure),
  354. TopRPTracker(TopPressure), BotRPTracker(BotPressure) {}
  355. ~ScheduleDAGMILive() override;
  356. /// Return true if this DAG supports VReg liveness and RegPressure.
  357. bool hasVRegLiveness() const override { return true; }
  358. /// Return true if register pressure tracking is enabled.
  359. bool isTrackingPressure() const { return ShouldTrackPressure; }
  360. /// Get current register pressure for the top scheduled instructions.
  361. const IntervalPressure &getTopPressure() const { return TopPressure; }
  362. const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
  363. /// Get current register pressure for the bottom scheduled instructions.
  364. const IntervalPressure &getBotPressure() const { return BotPressure; }
  365. const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
  366. /// Get register pressure for the entire scheduling region before scheduling.
  367. const IntervalPressure &getRegPressure() const { return RegPressure; }
  368. const std::vector<PressureChange> &getRegionCriticalPSets() const {
  369. return RegionCriticalPSets;
  370. }
  371. PressureDiff &getPressureDiff(const SUnit *SU) {
  372. return SUPressureDiffs[SU->NodeNum];
  373. }
  374. const PressureDiff &getPressureDiff(const SUnit *SU) const {
  375. return SUPressureDiffs[SU->NodeNum];
  376. }
  377. /// Compute a DFSResult after DAG building is complete, and before any
  378. /// queue comparisons.
  379. void computeDFSResult();
  380. /// Return a non-null DFS result if the scheduling strategy initialized it.
  381. const SchedDFSResult *getDFSResult() const { return DFSResult; }
  382. BitVector &getScheduledTrees() { return ScheduledTrees; }
  383. /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
  384. /// region. This covers all instructions in a block, while schedule() may only
  385. /// cover a subset.
  386. void enterRegion(MachineBasicBlock *bb,
  387. MachineBasicBlock::iterator begin,
  388. MachineBasicBlock::iterator end,
  389. unsigned regioninstrs) override;
  390. /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
  391. /// reorderable instructions.
  392. void schedule() override;
  393. /// Compute the cyclic critical path through the DAG.
  394. unsigned computeCyclicCriticalPath();
  395. void dump() const override;
  396. protected:
  397. // Top-Level entry points for the schedule() driver...
  398. /// Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking
  399. /// enabled. This sets up three trackers. RPTracker will cover the entire DAG
  400. /// region, TopTracker and BottomTracker will be initialized to the top and
  401. /// bottom of the DAG region without covereing any unscheduled instruction.
  402. void buildDAGWithRegPressure();
  403. /// Release ExitSU predecessors and setup scheduler queues. Re-position
  404. /// the Top RP tracker in case the region beginning has changed.
  405. void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
  406. /// Move an instruction and update register pressure.
  407. void scheduleMI(SUnit *SU, bool IsTopNode);
  408. // Lesser helpers...
  409. void initRegPressure();
  410. void updatePressureDiffs(ArrayRef<RegisterMaskPair> LiveUses);
  411. void updateScheduledPressure(const SUnit *SU,
  412. const std::vector<unsigned> &NewMaxPressure);
  413. void collectVRegUses(SUnit &SU);
  414. };
  415. //===----------------------------------------------------------------------===//
  416. ///
  417. /// Helpers for implementing custom MachineSchedStrategy classes. These take
  418. /// care of the book-keeping associated with list scheduling heuristics.
  419. ///
  420. //===----------------------------------------------------------------------===//
  421. /// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
  422. /// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
  423. /// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
  424. ///
  425. /// This is a convenience class that may be used by implementations of
  426. /// MachineSchedStrategy.
  427. class ReadyQueue {
  428. unsigned ID;
  429. std::string Name;
  430. std::vector<SUnit*> Queue;
  431. public:
  432. ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
  433. unsigned getID() const { return ID; }
  434. StringRef getName() const { return Name; }
  435. // SU is in this queue if it's NodeQueueID is a superset of this ID.
  436. bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
  437. bool empty() const { return Queue.empty(); }
  438. void clear() { Queue.clear(); }
  439. unsigned size() const { return Queue.size(); }
  440. using iterator = std::vector<SUnit*>::iterator;
  441. iterator begin() { return Queue.begin(); }
  442. iterator end() { return Queue.end(); }
  443. ArrayRef<SUnit*> elements() { return Queue; }
  444. iterator find(SUnit *SU) { return llvm::find(Queue, SU); }
  445. void push(SUnit *SU) {
  446. Queue.push_back(SU);
  447. SU->NodeQueueId |= ID;
  448. }
  449. iterator remove(iterator I) {
  450. (*I)->NodeQueueId &= ~ID;
  451. *I = Queue.back();
  452. unsigned idx = I - Queue.begin();
  453. Queue.pop_back();
  454. return Queue.begin() + idx;
  455. }
  456. void dump() const;
  457. };
  458. /// Summarize the unscheduled region.
  459. struct SchedRemainder {
  460. // Critical path through the DAG in expected latency.
  461. unsigned CriticalPath;
  462. unsigned CyclicCritPath;
  463. // Scaled count of micro-ops left to schedule.
  464. unsigned RemIssueCount;
  465. bool IsAcyclicLatencyLimited;
  466. // Unscheduled resources
  467. SmallVector<unsigned, 16> RemainingCounts;
  468. SchedRemainder() { reset(); }
  469. void reset() {
  470. CriticalPath = 0;
  471. CyclicCritPath = 0;
  472. RemIssueCount = 0;
  473. IsAcyclicLatencyLimited = false;
  474. RemainingCounts.clear();
  475. }
  476. void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
  477. };
  478. /// Each Scheduling boundary is associated with ready queues. It tracks the
  479. /// current cycle in the direction of movement, and maintains the state
  480. /// of "hazards" and other interlocks at the current cycle.
  481. class SchedBoundary {
  482. public:
  483. /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
  484. enum {
  485. TopQID = 1,
  486. BotQID = 2,
  487. LogMaxQID = 2
  488. };
  489. ScheduleDAGMI *DAG = nullptr;
  490. const TargetSchedModel *SchedModel = nullptr;
  491. SchedRemainder *Rem = nullptr;
  492. ReadyQueue Available;
  493. ReadyQueue Pending;
  494. ScheduleHazardRecognizer *HazardRec = nullptr;
  495. private:
  496. /// True if the pending Q should be checked/updated before scheduling another
  497. /// instruction.
  498. bool CheckPending;
  499. /// Number of cycles it takes to issue the instructions scheduled in this
  500. /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
  501. /// See getStalls().
  502. unsigned CurrCycle;
  503. /// Micro-ops issued in the current cycle
  504. unsigned CurrMOps;
  505. /// MinReadyCycle - Cycle of the soonest available instruction.
  506. unsigned MinReadyCycle;
  507. // The expected latency of the critical path in this scheduled zone.
  508. unsigned ExpectedLatency;
  509. // The latency of dependence chains leading into this zone.
  510. // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
  511. // For each cycle scheduled: DLat -= 1.
  512. unsigned DependentLatency;
  513. /// Count the scheduled (issued) micro-ops that can be retired by
  514. /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
  515. unsigned RetiredMOps;
  516. // Count scheduled resources that have been executed. Resources are
  517. // considered executed if they become ready in the time that it takes to
  518. // saturate any resource including the one in question. Counts are scaled
  519. // for direct comparison with other resources. Counts can be compared with
  520. // MOps * getMicroOpFactor and Latency * getLatencyFactor.
  521. SmallVector<unsigned, 16> ExecutedResCounts;
  522. /// Cache the max count for a single resource.
  523. unsigned MaxExecutedResCount;
  524. // Cache the critical resources ID in this scheduled zone.
  525. unsigned ZoneCritResIdx;
  526. // Is the scheduled region resource limited vs. latency limited.
  527. bool IsResourceLimited;
  528. // Record the highest cycle at which each resource has been reserved by a
  529. // scheduled instruction.
  530. SmallVector<unsigned, 16> ReservedCycles;
  531. // For each PIdx, stores first index into ReservedCycles that corresponds to
  532. // it.
  533. SmallVector<unsigned, 16> ReservedCyclesIndex;
  534. // For each PIdx, stores the resource group IDs of its subunits
  535. SmallVector<APInt, 16> ResourceGroupSubUnitMasks;
  536. #ifndef NDEBUG
  537. // Remember the greatest possible stall as an upper bound on the number of
  538. // times we should retry the pending queue because of a hazard.
  539. unsigned MaxObservedStall;
  540. #endif
  541. public:
  542. /// Pending queues extend the ready queues with the same ID and the
  543. /// PendingFlag set.
  544. SchedBoundary(unsigned ID, const Twine &Name):
  545. Available(ID, Name+".A"), Pending(ID << LogMaxQID, Name+".P") {
  546. reset();
  547. }
  548. ~SchedBoundary();
  549. void reset();
  550. void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
  551. SchedRemainder *rem);
  552. bool isTop() const {
  553. return Available.getID() == TopQID;
  554. }
  555. /// Number of cycles to issue the instructions scheduled in this zone.
  556. unsigned getCurrCycle() const { return CurrCycle; }
  557. /// Micro-ops issued in the current cycle
  558. unsigned getCurrMOps() const { return CurrMOps; }
  559. // The latency of dependence chains leading into this zone.
  560. unsigned getDependentLatency() const { return DependentLatency; }
  561. /// Get the number of latency cycles "covered" by the scheduled
  562. /// instructions. This is the larger of the critical path within the zone
  563. /// and the number of cycles required to issue the instructions.
  564. unsigned getScheduledLatency() const {
  565. return std::max(ExpectedLatency, CurrCycle);
  566. }
  567. unsigned getUnscheduledLatency(SUnit *SU) const {
  568. return isTop() ? SU->getHeight() : SU->getDepth();
  569. }
  570. unsigned getResourceCount(unsigned ResIdx) const {
  571. return ExecutedResCounts[ResIdx];
  572. }
  573. /// Get the scaled count of scheduled micro-ops and resources, including
  574. /// executed resources.
  575. unsigned getCriticalCount() const {
  576. if (!ZoneCritResIdx)
  577. return RetiredMOps * SchedModel->getMicroOpFactor();
  578. return getResourceCount(ZoneCritResIdx);
  579. }
  580. /// Get a scaled count for the minimum execution time of the scheduled
  581. /// micro-ops that are ready to execute by getExecutedCount. Notice the
  582. /// feedback loop.
  583. unsigned getExecutedCount() const {
  584. return std::max(CurrCycle * SchedModel->getLatencyFactor(),
  585. MaxExecutedResCount);
  586. }
  587. unsigned getZoneCritResIdx() const { return ZoneCritResIdx; }
  588. // Is the scheduled region resource limited vs. latency limited.
  589. bool isResourceLimited() const { return IsResourceLimited; }
  590. /// Get the difference between the given SUnit's ready time and the current
  591. /// cycle.
  592. unsigned getLatencyStallCycles(SUnit *SU);
  593. unsigned getNextResourceCycleByInstance(unsigned InstanceIndex,
  594. unsigned Cycles);
  595. std::pair<unsigned, unsigned> getNextResourceCycle(const MCSchedClassDesc *SC,
  596. unsigned PIdx,
  597. unsigned Cycles);
  598. bool isUnbufferedGroup(unsigned PIdx) const {
  599. return SchedModel->getProcResource(PIdx)->SubUnitsIdxBegin &&
  600. !SchedModel->getProcResource(PIdx)->BufferSize;
  601. }
  602. bool checkHazard(SUnit *SU);
  603. unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
  604. unsigned getOtherResourceCount(unsigned &OtherCritIdx);
  605. /// Release SU to make it ready. If it's not in hazard, remove it from
  606. /// pending queue (if already in) and push into available queue.
  607. /// Otherwise, push the SU into pending queue.
  608. ///
  609. /// @param SU The unit to be released.
  610. /// @param ReadyCycle Until which cycle the unit is ready.
  611. /// @param InPQueue Whether SU is already in pending queue.
  612. /// @param Idx Position offset in pending queue (if in it).
  613. void releaseNode(SUnit *SU, unsigned ReadyCycle, bool InPQueue,
  614. unsigned Idx = 0);
  615. void bumpCycle(unsigned NextCycle);
  616. void incExecutedResources(unsigned PIdx, unsigned Count);
  617. unsigned countResource(const MCSchedClassDesc *SC, unsigned PIdx,
  618. unsigned Cycles, unsigned ReadyCycle);
  619. void bumpNode(SUnit *SU);
  620. void releasePending();
  621. void removeReady(SUnit *SU);
  622. /// Call this before applying any other heuristics to the Available queue.
  623. /// Updates the Available/Pending Q's if necessary and returns the single
  624. /// available instruction, or NULL if there are multiple candidates.
  625. SUnit *pickOnlyChoice();
  626. void dumpScheduledState() const;
  627. };
  628. /// Base class for GenericScheduler. This class maintains information about
  629. /// scheduling candidates based on TargetSchedModel making it easy to implement
  630. /// heuristics for either preRA or postRA scheduling.
  631. class GenericSchedulerBase : public MachineSchedStrategy {
  632. public:
  633. /// Represent the type of SchedCandidate found within a single queue.
  634. /// pickNodeBidirectional depends on these listed by decreasing priority.
  635. enum CandReason : uint8_t {
  636. NoCand, Only1, PhysReg, RegExcess, RegCritical, Stall, Cluster, Weak,
  637. RegMax, ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
  638. TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
  639. #ifndef NDEBUG
  640. static const char *getReasonStr(GenericSchedulerBase::CandReason Reason);
  641. #endif
  642. /// Policy for scheduling the next instruction in the candidate's zone.
  643. struct CandPolicy {
  644. bool ReduceLatency = false;
  645. unsigned ReduceResIdx = 0;
  646. unsigned DemandResIdx = 0;
  647. CandPolicy() = default;
  648. bool operator==(const CandPolicy &RHS) const {
  649. return ReduceLatency == RHS.ReduceLatency &&
  650. ReduceResIdx == RHS.ReduceResIdx &&
  651. DemandResIdx == RHS.DemandResIdx;
  652. }
  653. bool operator!=(const CandPolicy &RHS) const {
  654. return !(*this == RHS);
  655. }
  656. };
  657. /// Status of an instruction's critical resource consumption.
  658. struct SchedResourceDelta {
  659. // Count critical resources in the scheduled region required by SU.
  660. unsigned CritResources = 0;
  661. // Count critical resources from another region consumed by SU.
  662. unsigned DemandedResources = 0;
  663. SchedResourceDelta() = default;
  664. bool operator==(const SchedResourceDelta &RHS) const {
  665. return CritResources == RHS.CritResources
  666. && DemandedResources == RHS.DemandedResources;
  667. }
  668. bool operator!=(const SchedResourceDelta &RHS) const {
  669. return !operator==(RHS);
  670. }
  671. };
  672. /// Store the state used by GenericScheduler heuristics, required for the
  673. /// lifetime of one invocation of pickNode().
  674. struct SchedCandidate {
  675. CandPolicy Policy;
  676. // The best SUnit candidate.
  677. SUnit *SU;
  678. // The reason for this candidate.
  679. CandReason Reason;
  680. // Whether this candidate should be scheduled at top/bottom.
  681. bool AtTop;
  682. // Register pressure values for the best candidate.
  683. RegPressureDelta RPDelta;
  684. // Critical resource consumption of the best candidate.
  685. SchedResourceDelta ResDelta;
  686. SchedCandidate() { reset(CandPolicy()); }
  687. SchedCandidate(const CandPolicy &Policy) { reset(Policy); }
  688. void reset(const CandPolicy &NewPolicy) {
  689. Policy = NewPolicy;
  690. SU = nullptr;
  691. Reason = NoCand;
  692. AtTop = false;
  693. RPDelta = RegPressureDelta();
  694. ResDelta = SchedResourceDelta();
  695. }
  696. bool isValid() const { return SU; }
  697. // Copy the status of another candidate without changing policy.
  698. void setBest(SchedCandidate &Best) {
  699. assert(Best.Reason != NoCand && "uninitialized Sched candidate");
  700. SU = Best.SU;
  701. Reason = Best.Reason;
  702. AtTop = Best.AtTop;
  703. RPDelta = Best.RPDelta;
  704. ResDelta = Best.ResDelta;
  705. }
  706. void initResourceDelta(const ScheduleDAGMI *DAG,
  707. const TargetSchedModel *SchedModel);
  708. };
  709. protected:
  710. const MachineSchedContext *Context;
  711. const TargetSchedModel *SchedModel = nullptr;
  712. const TargetRegisterInfo *TRI = nullptr;
  713. SchedRemainder Rem;
  714. GenericSchedulerBase(const MachineSchedContext *C) : Context(C) {}
  715. void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone,
  716. SchedBoundary *OtherZone);
  717. #ifndef NDEBUG
  718. void traceCandidate(const SchedCandidate &Cand);
  719. #endif
  720. private:
  721. bool shouldReduceLatency(const CandPolicy &Policy, SchedBoundary &CurrZone,
  722. bool ComputeRemLatency, unsigned &RemLatency) const;
  723. };
  724. // Utility functions used by heuristics in tryCandidate().
  725. bool tryLess(int TryVal, int CandVal,
  726. GenericSchedulerBase::SchedCandidate &TryCand,
  727. GenericSchedulerBase::SchedCandidate &Cand,
  728. GenericSchedulerBase::CandReason Reason);
  729. bool tryGreater(int TryVal, int CandVal,
  730. GenericSchedulerBase::SchedCandidate &TryCand,
  731. GenericSchedulerBase::SchedCandidate &Cand,
  732. GenericSchedulerBase::CandReason Reason);
  733. bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
  734. GenericSchedulerBase::SchedCandidate &Cand,
  735. SchedBoundary &Zone);
  736. bool tryPressure(const PressureChange &TryP,
  737. const PressureChange &CandP,
  738. GenericSchedulerBase::SchedCandidate &TryCand,
  739. GenericSchedulerBase::SchedCandidate &Cand,
  740. GenericSchedulerBase::CandReason Reason,
  741. const TargetRegisterInfo *TRI,
  742. const MachineFunction &MF);
  743. unsigned getWeakLeft(const SUnit *SU, bool isTop);
  744. int biasPhysReg(const SUnit *SU, bool isTop);
  745. /// GenericScheduler shrinks the unscheduled zone using heuristics to balance
  746. /// the schedule.
  747. class GenericScheduler : public GenericSchedulerBase {
  748. public:
  749. GenericScheduler(const MachineSchedContext *C):
  750. GenericSchedulerBase(C), Top(SchedBoundary::TopQID, "TopQ"),
  751. Bot(SchedBoundary::BotQID, "BotQ") {}
  752. void initPolicy(MachineBasicBlock::iterator Begin,
  753. MachineBasicBlock::iterator End,
  754. unsigned NumRegionInstrs) override;
  755. void dumpPolicy() const override;
  756. bool shouldTrackPressure() const override {
  757. return RegionPolicy.ShouldTrackPressure;
  758. }
  759. bool shouldTrackLaneMasks() const override {
  760. return RegionPolicy.ShouldTrackLaneMasks;
  761. }
  762. void initialize(ScheduleDAGMI *dag) override;
  763. SUnit *pickNode(bool &IsTopNode) override;
  764. void schedNode(SUnit *SU, bool IsTopNode) override;
  765. void releaseTopNode(SUnit *SU) override {
  766. if (SU->isScheduled)
  767. return;
  768. Top.releaseNode(SU, SU->TopReadyCycle, false);
  769. TopCand.SU = nullptr;
  770. }
  771. void releaseBottomNode(SUnit *SU) override {
  772. if (SU->isScheduled)
  773. return;
  774. Bot.releaseNode(SU, SU->BotReadyCycle, false);
  775. BotCand.SU = nullptr;
  776. }
  777. void registerRoots() override;
  778. protected:
  779. ScheduleDAGMILive *DAG = nullptr;
  780. MachineSchedPolicy RegionPolicy;
  781. // State of the top and bottom scheduled instruction boundaries.
  782. SchedBoundary Top;
  783. SchedBoundary Bot;
  784. /// Candidate last picked from Top boundary.
  785. SchedCandidate TopCand;
  786. /// Candidate last picked from Bot boundary.
  787. SchedCandidate BotCand;
  788. void checkAcyclicLatency();
  789. void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop,
  790. const RegPressureTracker &RPTracker,
  791. RegPressureTracker &TempTracker);
  792. virtual void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand,
  793. SchedBoundary *Zone) const;
  794. SUnit *pickNodeBidirectional(bool &IsTopNode);
  795. void pickNodeFromQueue(SchedBoundary &Zone,
  796. const CandPolicy &ZonePolicy,
  797. const RegPressureTracker &RPTracker,
  798. SchedCandidate &Candidate);
  799. void reschedulePhysReg(SUnit *SU, bool isTop);
  800. };
  801. /// PostGenericScheduler - Interface to the scheduling algorithm used by
  802. /// ScheduleDAGMI.
  803. ///
  804. /// Callbacks from ScheduleDAGMI:
  805. /// initPolicy -> initialize(DAG) -> registerRoots -> pickNode ...
  806. class PostGenericScheduler : public GenericSchedulerBase {
  807. protected:
  808. ScheduleDAGMI *DAG = nullptr;
  809. SchedBoundary Top;
  810. SmallVector<SUnit*, 8> BotRoots;
  811. public:
  812. PostGenericScheduler(const MachineSchedContext *C):
  813. GenericSchedulerBase(C), Top(SchedBoundary::TopQID, "TopQ") {}
  814. ~PostGenericScheduler() override = default;
  815. void initPolicy(MachineBasicBlock::iterator Begin,
  816. MachineBasicBlock::iterator End,
  817. unsigned NumRegionInstrs) override {
  818. /* no configurable policy */
  819. }
  820. /// PostRA scheduling does not track pressure.
  821. bool shouldTrackPressure() const override { return false; }
  822. void initialize(ScheduleDAGMI *Dag) override;
  823. void registerRoots() override;
  824. SUnit *pickNode(bool &IsTopNode) override;
  825. void scheduleTree(unsigned SubtreeID) override {
  826. llvm_unreachable("PostRA scheduler does not support subtree analysis.");
  827. }
  828. void schedNode(SUnit *SU, bool IsTopNode) override;
  829. void releaseTopNode(SUnit *SU) override {
  830. if (SU->isScheduled)
  831. return;
  832. Top.releaseNode(SU, SU->TopReadyCycle, false);
  833. }
  834. // Only called for roots.
  835. void releaseBottomNode(SUnit *SU) override {
  836. BotRoots.push_back(SU);
  837. }
  838. protected:
  839. virtual void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand);
  840. void pickNodeFromQueue(SchedCandidate &Cand);
  841. };
  842. /// Create the standard converging machine scheduler. This will be used as the
  843. /// default scheduler if the target does not set a default.
  844. /// Adds default DAG mutations.
  845. ScheduleDAGMILive *createGenericSchedLive(MachineSchedContext *C);
  846. /// Create a generic scheduler with no vreg liveness or DAG mutation passes.
  847. ScheduleDAGMI *createGenericSchedPostRA(MachineSchedContext *C);
  848. std::unique_ptr<ScheduleDAGMutation>
  849. createLoadClusterDAGMutation(const TargetInstrInfo *TII,
  850. const TargetRegisterInfo *TRI);
  851. std::unique_ptr<ScheduleDAGMutation>
  852. createStoreClusterDAGMutation(const TargetInstrInfo *TII,
  853. const TargetRegisterInfo *TRI);
  854. std::unique_ptr<ScheduleDAGMutation>
  855. createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
  856. const TargetRegisterInfo *TRI);
  857. } // end namespace llvm
  858. #endif // LLVM_CODEGEN_MACHINESCHEDULER_H