PostRASchedulerList.cpp 24 KB

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