PostRASchedulerList.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. //===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
  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 implements a top-down list scheduler, using standard algorithms.
  10. // The basic approach uses a priority queue of available nodes to schedule.
  11. // One at a time, nodes are taken from the priority queue (thus in priority
  12. // order), checked for legality to schedule, and emitted if legal.
  13. //
  14. // Nodes may not be legal to schedule either due to structural hazards (e.g.
  15. // pipeline or resource constraints) or because an input to the instruction has
  16. // not completed execution.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/CodeGen/AntiDepBreaker.h"
  22. #include "llvm/CodeGen/LatencyPriorityQueue.h"
  23. #include "llvm/CodeGen/MachineDominators.h"
  24. #include "llvm/CodeGen/MachineFunctionPass.h"
  25. #include "llvm/CodeGen/MachineLoopInfo.h"
  26. #include "llvm/CodeGen/MachineRegisterInfo.h"
  27. #include "llvm/CodeGen/Passes.h"
  28. #include "llvm/CodeGen/RegisterClassInfo.h"
  29. #include "llvm/CodeGen/ScheduleDAGInstrs.h"
  30. #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
  31. #include "llvm/CodeGen/SchedulerRegistry.h"
  32. #include "llvm/CodeGen/TargetInstrInfo.h"
  33. #include "llvm/CodeGen/TargetLowering.h"
  34. #include "llvm/CodeGen/TargetPassConfig.h"
  35. #include "llvm/CodeGen/TargetRegisterInfo.h"
  36. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  37. #include "llvm/Config/llvm-config.h"
  38. #include "llvm/InitializePasses.h"
  39. #include "llvm/Support/CommandLine.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. using namespace llvm;
  44. #define DEBUG_TYPE "post-RA-sched"
  45. STATISTIC(NumNoops, "Number of noops inserted");
  46. STATISTIC(NumStalls, "Number of pipeline stalls");
  47. STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
  48. // Post-RA scheduling is enabled with
  49. // TargetSubtargetInfo.enablePostRAScheduler(). This flag can be used to
  50. // override the target.
  51. static cl::opt<bool>
  52. EnablePostRAScheduler("post-RA-scheduler",
  53. cl::desc("Enable scheduling after register allocation"),
  54. cl::init(false), cl::Hidden);
  55. static cl::opt<std::string>
  56. EnableAntiDepBreaking("break-anti-dependencies",
  57. cl::desc("Break post-RA scheduling anti-dependencies: "
  58. "\"critical\", \"all\", or \"none\""),
  59. cl::init("none"), cl::Hidden);
  60. // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
  61. static cl::opt<int>
  62. DebugDiv("postra-sched-debugdiv",
  63. cl::desc("Debug control MBBs that are scheduled"),
  64. cl::init(0), cl::Hidden);
  65. static cl::opt<int>
  66. DebugMod("postra-sched-debugmod",
  67. cl::desc("Debug control MBBs that are scheduled"),
  68. cl::init(0), cl::Hidden);
  69. AntiDepBreaker::~AntiDepBreaker() { }
  70. namespace {
  71. class PostRAScheduler : public MachineFunctionPass {
  72. const TargetInstrInfo *TII = nullptr;
  73. RegisterClassInfo RegClassInfo;
  74. public:
  75. static char ID;
  76. PostRAScheduler() : MachineFunctionPass(ID) {}
  77. void getAnalysisUsage(AnalysisUsage &AU) const override {
  78. AU.setPreservesCFG();
  79. AU.addRequired<AAResultsWrapperPass>();
  80. AU.addRequired<TargetPassConfig>();
  81. AU.addRequired<MachineDominatorTree>();
  82. AU.addPreserved<MachineDominatorTree>();
  83. AU.addRequired<MachineLoopInfo>();
  84. AU.addPreserved<MachineLoopInfo>();
  85. MachineFunctionPass::getAnalysisUsage(AU);
  86. }
  87. MachineFunctionProperties getRequiredProperties() const override {
  88. return MachineFunctionProperties().set(
  89. MachineFunctionProperties::Property::NoVRegs);
  90. }
  91. bool runOnMachineFunction(MachineFunction &Fn) override;
  92. private:
  93. bool enablePostRAScheduler(
  94. const TargetSubtargetInfo &ST, CodeGenOpt::Level OptLevel,
  95. TargetSubtargetInfo::AntiDepBreakMode &Mode,
  96. TargetSubtargetInfo::RegClassVector &CriticalPathRCs) const;
  97. };
  98. char PostRAScheduler::ID = 0;
  99. class SchedulePostRATDList : public ScheduleDAGInstrs {
  100. /// AvailableQueue - The priority queue to use for the available SUnits.
  101. ///
  102. LatencyPriorityQueue AvailableQueue;
  103. /// PendingQueue - This contains all of the instructions whose operands have
  104. /// been issued, but their results are not ready yet (due to the latency of
  105. /// the operation). Once the operands becomes available, the instruction is
  106. /// added to the AvailableQueue.
  107. std::vector<SUnit*> PendingQueue;
  108. /// HazardRec - The hazard recognizer to use.
  109. ScheduleHazardRecognizer *HazardRec;
  110. /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
  111. AntiDepBreaker *AntiDepBreak;
  112. /// AA - AliasAnalysis for making memory reference queries.
  113. AliasAnalysis *AA;
  114. /// The schedule. Null SUnit*'s represent noop instructions.
  115. std::vector<SUnit*> Sequence;
  116. /// Ordered list of DAG postprocessing steps.
  117. std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
  118. /// The index in BB of RegionEnd.
  119. ///
  120. /// This is the instruction number from the top of the current block, not
  121. /// the SlotIndex. It is only used by the AntiDepBreaker.
  122. unsigned EndIndex = 0;
  123. public:
  124. SchedulePostRATDList(
  125. MachineFunction &MF, MachineLoopInfo &MLI, AliasAnalysis *AA,
  126. const RegisterClassInfo &,
  127. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
  128. SmallVectorImpl<const TargetRegisterClass *> &CriticalPathRCs);
  129. ~SchedulePostRATDList() override;
  130. /// startBlock - Initialize register live-range state for scheduling in
  131. /// this block.
  132. ///
  133. void startBlock(MachineBasicBlock *BB) override;
  134. // Set the index of RegionEnd within the current BB.
  135. void setEndIndex(unsigned EndIdx) { EndIndex = EndIdx; }
  136. /// Initialize the scheduler state for the next scheduling region.
  137. void enterRegion(MachineBasicBlock *bb,
  138. MachineBasicBlock::iterator begin,
  139. MachineBasicBlock::iterator end,
  140. unsigned regioninstrs) override;
  141. /// Notify that the scheduler has finished scheduling the current region.
  142. void exitRegion() override;
  143. /// Schedule - Schedule the instruction range using list scheduling.
  144. ///
  145. void schedule() override;
  146. void EmitSchedule();
  147. /// Observe - Update liveness information to account for the current
  148. /// instruction, which will not be scheduled.
  149. ///
  150. void Observe(MachineInstr &MI, unsigned Count);
  151. /// finishBlock - Clean up register live-range state.
  152. ///
  153. void finishBlock() override;
  154. private:
  155. /// Apply each ScheduleDAGMutation step in order.
  156. void postprocessDAG();
  157. void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
  158. void ReleaseSuccessors(SUnit *SU);
  159. void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
  160. void ListScheduleTopDown();
  161. void dumpSchedule() const;
  162. void emitNoop(unsigned CurCycle);
  163. };
  164. }
  165. char &llvm::PostRASchedulerID = PostRAScheduler::ID;
  166. INITIALIZE_PASS(PostRAScheduler, DEBUG_TYPE,
  167. "Post RA top-down list latency scheduler", false, false)
  168. SchedulePostRATDList::SchedulePostRATDList(
  169. MachineFunction &MF, MachineLoopInfo &MLI, AliasAnalysis *AA,
  170. const RegisterClassInfo &RCI,
  171. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
  172. SmallVectorImpl<const TargetRegisterClass *> &CriticalPathRCs)
  173. : ScheduleDAGInstrs(MF, &MLI), AA(AA) {
  174. const InstrItineraryData *InstrItins =
  175. MF.getSubtarget().getInstrItineraryData();
  176. HazardRec =
  177. MF.getSubtarget().getInstrInfo()->CreateTargetPostRAHazardRecognizer(
  178. InstrItins, this);
  179. MF.getSubtarget().getPostRAMutations(Mutations);
  180. assert((AntiDepMode == TargetSubtargetInfo::ANTIDEP_NONE ||
  181. MRI.tracksLiveness()) &&
  182. "Live-ins must be accurate for anti-dependency breaking");
  183. AntiDepBreak = ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL)
  184. ? createAggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs)
  185. : ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL)
  186. ? createCriticalAntiDepBreaker(MF, RCI)
  187. : nullptr));
  188. }
  189. SchedulePostRATDList::~SchedulePostRATDList() {
  190. delete HazardRec;
  191. delete AntiDepBreak;
  192. }
  193. /// Initialize state associated with the next scheduling region.
  194. void SchedulePostRATDList::enterRegion(MachineBasicBlock *bb,
  195. MachineBasicBlock::iterator begin,
  196. MachineBasicBlock::iterator end,
  197. unsigned regioninstrs) {
  198. ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
  199. Sequence.clear();
  200. }
  201. /// Print the schedule before exiting the region.
  202. void SchedulePostRATDList::exitRegion() {
  203. LLVM_DEBUG({
  204. dbgs() << "*** Final schedule ***\n";
  205. dumpSchedule();
  206. dbgs() << '\n';
  207. });
  208. ScheduleDAGInstrs::exitRegion();
  209. }
  210. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  211. /// dumpSchedule - dump the scheduled Sequence.
  212. LLVM_DUMP_METHOD void SchedulePostRATDList::dumpSchedule() const {
  213. for (const SUnit *SU : Sequence) {
  214. if (SU)
  215. dumpNode(*SU);
  216. else
  217. dbgs() << "**** NOOP ****\n";
  218. }
  219. }
  220. #endif
  221. bool PostRAScheduler::enablePostRAScheduler(
  222. const TargetSubtargetInfo &ST,
  223. CodeGenOpt::Level OptLevel,
  224. TargetSubtargetInfo::AntiDepBreakMode &Mode,
  225. TargetSubtargetInfo::RegClassVector &CriticalPathRCs) const {
  226. Mode = ST.getAntiDepBreakMode();
  227. ST.getCriticalPathRCs(CriticalPathRCs);
  228. // Check for explicit enable/disable of post-ra scheduling.
  229. if (EnablePostRAScheduler.getPosition() > 0)
  230. return EnablePostRAScheduler;
  231. return ST.enablePostRAScheduler() &&
  232. OptLevel >= ST.getOptLevelToEnablePostRAScheduler();
  233. }
  234. bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
  235. if (skipFunction(Fn.getFunction()))
  236. return false;
  237. TII = Fn.getSubtarget().getInstrInfo();
  238. MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
  239. AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  240. TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
  241. RegClassInfo.runOnMachineFunction(Fn);
  242. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
  243. TargetSubtargetInfo::ANTIDEP_NONE;
  244. SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
  245. // Check that post-RA scheduling is enabled for this target.
  246. // This may upgrade the AntiDepMode.
  247. if (!enablePostRAScheduler(Fn.getSubtarget(), PassConfig->getOptLevel(),
  248. AntiDepMode, CriticalPathRCs))
  249. return false;
  250. // Check for antidep breaking override...
  251. if (EnableAntiDepBreaking.getPosition() > 0) {
  252. AntiDepMode = (EnableAntiDepBreaking == "all")
  253. ? TargetSubtargetInfo::ANTIDEP_ALL
  254. : ((EnableAntiDepBreaking == "critical")
  255. ? TargetSubtargetInfo::ANTIDEP_CRITICAL
  256. : TargetSubtargetInfo::ANTIDEP_NONE);
  257. }
  258. LLVM_DEBUG(dbgs() << "PostRAScheduler\n");
  259. SchedulePostRATDList Scheduler(Fn, MLI, AA, RegClassInfo, AntiDepMode,
  260. CriticalPathRCs);
  261. // Loop over all of the basic blocks
  262. for (auto &MBB : Fn) {
  263. #ifndef NDEBUG
  264. // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
  265. if (DebugDiv > 0) {
  266. static int bbcnt = 0;
  267. if (bbcnt++ % DebugDiv != DebugMod)
  268. continue;
  269. dbgs() << "*** DEBUG scheduling " << Fn.getName() << ":"
  270. << printMBBReference(MBB) << " ***\n";
  271. }
  272. #endif
  273. // Initialize register live-range state for scheduling in this block.
  274. Scheduler.startBlock(&MBB);
  275. // Schedule each sequence of instructions not interrupted by a label
  276. // or anything else that effectively needs to shut down scheduling.
  277. MachineBasicBlock::iterator Current = MBB.end();
  278. unsigned Count = MBB.size(), CurrentCount = Count;
  279. for (MachineBasicBlock::iterator I = Current; I != MBB.begin();) {
  280. MachineInstr &MI = *std::prev(I);
  281. --Count;
  282. // Calls are not scheduling boundaries before register allocation, but
  283. // post-ra we don't gain anything by scheduling across calls since we
  284. // don't need to worry about register pressure.
  285. if (MI.isCall() || TII->isSchedulingBoundary(MI, &MBB, Fn)) {
  286. Scheduler.enterRegion(&MBB, I, Current, CurrentCount - Count);
  287. Scheduler.setEndIndex(CurrentCount);
  288. Scheduler.schedule();
  289. Scheduler.exitRegion();
  290. Scheduler.EmitSchedule();
  291. Current = &MI;
  292. CurrentCount = Count;
  293. Scheduler.Observe(MI, CurrentCount);
  294. }
  295. I = MI;
  296. if (MI.isBundle())
  297. Count -= MI.getBundleSize();
  298. }
  299. assert(Count == 0 && "Instruction count mismatch!");
  300. assert((MBB.begin() == Current || CurrentCount != 0) &&
  301. "Instruction count mismatch!");
  302. Scheduler.enterRegion(&MBB, MBB.begin(), Current, CurrentCount);
  303. Scheduler.setEndIndex(CurrentCount);
  304. Scheduler.schedule();
  305. Scheduler.exitRegion();
  306. Scheduler.EmitSchedule();
  307. // Clean up register live-range state.
  308. Scheduler.finishBlock();
  309. // Update register kills
  310. Scheduler.fixupKills(MBB);
  311. }
  312. return true;
  313. }
  314. /// StartBlock - Initialize register live-range state for scheduling in
  315. /// this block.
  316. ///
  317. void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) {
  318. // Call the superclass.
  319. ScheduleDAGInstrs::startBlock(BB);
  320. // Reset the hazard recognizer and anti-dep breaker.
  321. HazardRec->Reset();
  322. if (AntiDepBreak)
  323. AntiDepBreak->StartBlock(BB);
  324. }
  325. /// Schedule - Schedule the instruction range using list scheduling.
  326. ///
  327. void SchedulePostRATDList::schedule() {
  328. // Build the scheduling graph.
  329. buildSchedGraph(AA);
  330. if (AntiDepBreak) {
  331. unsigned Broken =
  332. AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd,
  333. EndIndex, DbgValues);
  334. if (Broken != 0) {
  335. // We made changes. Update the dependency graph.
  336. // Theoretically we could update the graph in place:
  337. // When a live range is changed to use a different register, remove
  338. // the def's anti-dependence *and* output-dependence edges due to
  339. // that register, and add new anti-dependence and output-dependence
  340. // edges based on the next live range of the register.
  341. ScheduleDAG::clearDAG();
  342. buildSchedGraph(AA);
  343. NumFixedAnti += Broken;
  344. }
  345. }
  346. postprocessDAG();
  347. LLVM_DEBUG(dbgs() << "********** List Scheduling **********\n");
  348. LLVM_DEBUG(dump());
  349. AvailableQueue.initNodes(SUnits);
  350. ListScheduleTopDown();
  351. AvailableQueue.releaseState();
  352. }
  353. /// Observe - Update liveness information to account for the current
  354. /// instruction, which will not be scheduled.
  355. ///
  356. void SchedulePostRATDList::Observe(MachineInstr &MI, unsigned Count) {
  357. if (AntiDepBreak)
  358. AntiDepBreak->Observe(MI, Count, EndIndex);
  359. }
  360. /// FinishBlock - Clean up register live-range state.
  361. ///
  362. void SchedulePostRATDList::finishBlock() {
  363. if (AntiDepBreak)
  364. AntiDepBreak->FinishBlock();
  365. // Call the superclass.
  366. ScheduleDAGInstrs::finishBlock();
  367. }
  368. /// Apply each ScheduleDAGMutation step in order.
  369. void SchedulePostRATDList::postprocessDAG() {
  370. for (auto &M : Mutations)
  371. M->apply(this);
  372. }
  373. //===----------------------------------------------------------------------===//
  374. // Top-Down Scheduling
  375. //===----------------------------------------------------------------------===//
  376. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
  377. /// the PendingQueue if the count reaches zero.
  378. void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
  379. SUnit *SuccSU = SuccEdge->getSUnit();
  380. if (SuccEdge->isWeak()) {
  381. --SuccSU->WeakPredsLeft;
  382. return;
  383. }
  384. #ifndef NDEBUG
  385. if (SuccSU->NumPredsLeft == 0) {
  386. dbgs() << "*** Scheduling failed! ***\n";
  387. dumpNode(*SuccSU);
  388. dbgs() << " has been released too many times!\n";
  389. llvm_unreachable(nullptr);
  390. }
  391. #endif
  392. --SuccSU->NumPredsLeft;
  393. // Standard scheduler algorithms will recompute the depth of the successor
  394. // here as such:
  395. // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
  396. //
  397. // However, we lazily compute node depth instead. Note that
  398. // ScheduleNodeTopDown has already updated the depth of this node which causes
  399. // all descendents to be marked dirty. Setting the successor depth explicitly
  400. // here would cause depth to be recomputed for all its ancestors. If the
  401. // successor is not yet ready (because of a transitively redundant edge) then
  402. // this causes depth computation to be quadratic in the size of the DAG.
  403. // If all the node's predecessors are scheduled, this node is ready
  404. // to be scheduled. Ignore the special ExitSU node.
  405. if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
  406. PendingQueue.push_back(SuccSU);
  407. }
  408. /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
  409. void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
  410. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  411. I != E; ++I) {
  412. ReleaseSucc(SU, &*I);
  413. }
  414. }
  415. /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
  416. /// count of its successors. If a successor pending count is zero, add it to
  417. /// the Available queue.
  418. void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
  419. LLVM_DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
  420. LLVM_DEBUG(dumpNode(*SU));
  421. Sequence.push_back(SU);
  422. assert(CurCycle >= SU->getDepth() &&
  423. "Node scheduled above its depth!");
  424. SU->setDepthToAtLeast(CurCycle);
  425. ReleaseSuccessors(SU);
  426. SU->isScheduled = true;
  427. AvailableQueue.scheduledNode(SU);
  428. }
  429. /// emitNoop - Add a noop to the current instruction sequence.
  430. void SchedulePostRATDList::emitNoop(unsigned CurCycle) {
  431. LLVM_DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
  432. HazardRec->EmitNoop();
  433. Sequence.push_back(nullptr); // NULL here means noop
  434. ++NumNoops;
  435. }
  436. /// ListScheduleTopDown - The main loop of list scheduling for top-down
  437. /// schedulers.
  438. void SchedulePostRATDList::ListScheduleTopDown() {
  439. unsigned CurCycle = 0;
  440. // We're scheduling top-down but we're visiting the regions in
  441. // bottom-up order, so we don't know the hazards at the start of a
  442. // region. So assume no hazards (this should usually be ok as most
  443. // blocks are a single region).
  444. HazardRec->Reset();
  445. // Release any successors of the special Entry node.
  446. ReleaseSuccessors(&EntrySU);
  447. // Add all leaves to Available queue.
  448. for (SUnit &SUnit : SUnits) {
  449. // It is available if it has no predecessors.
  450. if (!SUnit.NumPredsLeft && !SUnit.isAvailable) {
  451. AvailableQueue.push(&SUnit);
  452. SUnit.isAvailable = true;
  453. }
  454. }
  455. // In any cycle where we can't schedule any instructions, we must
  456. // stall or emit a noop, depending on the target.
  457. bool CycleHasInsts = false;
  458. // While Available queue is not empty, grab the node with the highest
  459. // priority. If it is not ready put it back. Schedule the node.
  460. std::vector<SUnit*> NotReady;
  461. Sequence.reserve(SUnits.size());
  462. while (!AvailableQueue.empty() || !PendingQueue.empty()) {
  463. // Check to see if any of the pending instructions are ready to issue. If
  464. // so, add them to the available queue.
  465. unsigned MinDepth = ~0u;
  466. for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
  467. if (PendingQueue[i]->getDepth() <= CurCycle) {
  468. AvailableQueue.push(PendingQueue[i]);
  469. PendingQueue[i]->isAvailable = true;
  470. PendingQueue[i] = PendingQueue.back();
  471. PendingQueue.pop_back();
  472. --i; --e;
  473. } else if (PendingQueue[i]->getDepth() < MinDepth)
  474. MinDepth = PendingQueue[i]->getDepth();
  475. }
  476. LLVM_DEBUG(dbgs() << "\n*** Examining Available\n";
  477. AvailableQueue.dump(this));
  478. SUnit *FoundSUnit = nullptr, *NotPreferredSUnit = nullptr;
  479. bool HasNoopHazards = false;
  480. while (!AvailableQueue.empty()) {
  481. SUnit *CurSUnit = AvailableQueue.pop();
  482. ScheduleHazardRecognizer::HazardType HT =
  483. HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
  484. if (HT == ScheduleHazardRecognizer::NoHazard) {
  485. if (HazardRec->ShouldPreferAnother(CurSUnit)) {
  486. if (!NotPreferredSUnit) {
  487. // If this is the first non-preferred node for this cycle, then
  488. // record it and continue searching for a preferred node. If this
  489. // is not the first non-preferred node, then treat it as though
  490. // there had been a hazard.
  491. NotPreferredSUnit = CurSUnit;
  492. continue;
  493. }
  494. } else {
  495. FoundSUnit = CurSUnit;
  496. break;
  497. }
  498. }
  499. // Remember if this is a noop hazard.
  500. HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
  501. NotReady.push_back(CurSUnit);
  502. }
  503. // If we have a non-preferred node, push it back onto the available list.
  504. // If we did not find a preferred node, then schedule this first
  505. // non-preferred node.
  506. if (NotPreferredSUnit) {
  507. if (!FoundSUnit) {
  508. LLVM_DEBUG(
  509. dbgs() << "*** Will schedule a non-preferred instruction...\n");
  510. FoundSUnit = NotPreferredSUnit;
  511. } else {
  512. AvailableQueue.push(NotPreferredSUnit);
  513. }
  514. NotPreferredSUnit = nullptr;
  515. }
  516. // Add the nodes that aren't ready back onto the available list.
  517. if (!NotReady.empty()) {
  518. AvailableQueue.push_all(NotReady);
  519. NotReady.clear();
  520. }
  521. // If we found a node to schedule...
  522. if (FoundSUnit) {
  523. // If we need to emit noops prior to this instruction, then do so.
  524. unsigned NumPreNoops = HazardRec->PreEmitNoops(FoundSUnit);
  525. for (unsigned i = 0; i != NumPreNoops; ++i)
  526. emitNoop(CurCycle);
  527. // ... schedule the node...
  528. ScheduleNodeTopDown(FoundSUnit, CurCycle);
  529. HazardRec->EmitInstruction(FoundSUnit);
  530. CycleHasInsts = true;
  531. if (HazardRec->atIssueLimit()) {
  532. LLVM_DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle
  533. << '\n');
  534. HazardRec->AdvanceCycle();
  535. ++CurCycle;
  536. CycleHasInsts = false;
  537. }
  538. } else {
  539. if (CycleHasInsts) {
  540. LLVM_DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
  541. HazardRec->AdvanceCycle();
  542. } else if (!HasNoopHazards) {
  543. // Otherwise, we have a pipeline stall, but no other problem,
  544. // just advance the current cycle and try again.
  545. LLVM_DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
  546. HazardRec->AdvanceCycle();
  547. ++NumStalls;
  548. } else {
  549. // Otherwise, we have no instructions to issue and we have instructions
  550. // that will fault if we don't do this right. This is the case for
  551. // processors without pipeline interlocks and other cases.
  552. emitNoop(CurCycle);
  553. }
  554. ++CurCycle;
  555. CycleHasInsts = false;
  556. }
  557. }
  558. #ifndef NDEBUG
  559. unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
  560. unsigned Noops = llvm::count(Sequence, nullptr);
  561. assert(Sequence.size() - Noops == ScheduledNodes &&
  562. "The number of nodes scheduled doesn't match the expected number!");
  563. #endif // NDEBUG
  564. }
  565. // EmitSchedule - Emit the machine code in scheduled order.
  566. void SchedulePostRATDList::EmitSchedule() {
  567. RegionBegin = RegionEnd;
  568. // If first instruction was a DBG_VALUE then put it back.
  569. if (FirstDbgValue)
  570. BB->splice(RegionEnd, BB, FirstDbgValue);
  571. // Then re-insert them according to the given schedule.
  572. for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
  573. if (SUnit *SU = Sequence[i])
  574. BB->splice(RegionEnd, BB, SU->getInstr());
  575. else
  576. // Null SUnit* is a noop.
  577. TII->insertNoop(*BB, RegionEnd);
  578. // Update the Begin iterator, as the first instruction in the block
  579. // may have been scheduled later.
  580. if (i == 0)
  581. RegionBegin = std::prev(RegionEnd);
  582. }
  583. // Reinsert any remaining debug_values.
  584. for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
  585. DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
  586. std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
  587. MachineInstr *DbgValue = P.first;
  588. MachineBasicBlock::iterator OrigPrivMI = P.second;
  589. BB->splice(++OrigPrivMI, BB, DbgValue);
  590. }
  591. DbgValues.clear();
  592. FirstDbgValue = nullptr;
  593. }