PostRASchedulerList.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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<AliasAnalysis>();
  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, /*IsPostRA=*/true), 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<AliasAnalysis>();
  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 (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
  258. MBB != MBBe; ++MBB) {
  259. #ifndef NDEBUG
  260. // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
  261. if (DebugDiv > 0) {
  262. static int bbcnt = 0;
  263. if (bbcnt++ % DebugDiv != DebugMod)
  264. continue;
  265. dbgs() << "*** DEBUG scheduling " << Fn.getName()
  266. << ":BB#" << MBB->getNumber() << " ***\n";
  267. }
  268. #endif
  269. // Initialize register live-range state for scheduling in this block.
  270. Scheduler.startBlock(MBB);
  271. // Schedule each sequence of instructions not interrupted by a label
  272. // or anything else that effectively needs to shut down scheduling.
  273. MachineBasicBlock::iterator Current = MBB->end();
  274. unsigned Count = MBB->size(), CurrentCount = Count;
  275. for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
  276. MachineInstr *MI = std::prev(I);
  277. --Count;
  278. // Calls are not scheduling boundaries before register allocation, but
  279. // post-ra we don't gain anything by scheduling across calls since we
  280. // don't need to worry about register pressure.
  281. if (MI->isCall() || TII->isSchedulingBoundary(MI, MBB, Fn)) {
  282. Scheduler.enterRegion(MBB, I, Current, CurrentCount - Count);
  283. Scheduler.setEndIndex(CurrentCount);
  284. Scheduler.schedule();
  285. Scheduler.exitRegion();
  286. Scheduler.EmitSchedule();
  287. Current = MI;
  288. CurrentCount = Count;
  289. Scheduler.Observe(MI, CurrentCount);
  290. }
  291. I = MI;
  292. if (MI->isBundle())
  293. Count -= MI->getBundleSize();
  294. }
  295. assert(Count == 0 && "Instruction count mismatch!");
  296. assert((MBB->begin() == Current || CurrentCount != 0) &&
  297. "Instruction count mismatch!");
  298. Scheduler.enterRegion(MBB, MBB->begin(), Current, CurrentCount);
  299. Scheduler.setEndIndex(CurrentCount);
  300. Scheduler.schedule();
  301. Scheduler.exitRegion();
  302. Scheduler.EmitSchedule();
  303. // Clean up register live-range state.
  304. Scheduler.finishBlock();
  305. // Update register kills
  306. Scheduler.fixupKills(MBB);
  307. }
  308. return true;
  309. }
  310. /// StartBlock - Initialize register live-range state for scheduling in
  311. /// this block.
  312. ///
  313. void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) {
  314. // Call the superclass.
  315. ScheduleDAGInstrs::startBlock(BB);
  316. // Reset the hazard recognizer and anti-dep breaker.
  317. HazardRec->Reset();
  318. if (AntiDepBreak)
  319. AntiDepBreak->StartBlock(BB);
  320. }
  321. /// Schedule - Schedule the instruction range using list scheduling.
  322. ///
  323. void SchedulePostRATDList::schedule() {
  324. // Build the scheduling graph.
  325. buildSchedGraph(AA);
  326. if (AntiDepBreak) {
  327. unsigned Broken =
  328. AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd,
  329. EndIndex, DbgValues);
  330. if (Broken != 0) {
  331. // We made changes. Update the dependency graph.
  332. // Theoretically we could update the graph in place:
  333. // When a live range is changed to use a different register, remove
  334. // the def's anti-dependence *and* output-dependence edges due to
  335. // that register, and add new anti-dependence and output-dependence
  336. // edges based on the next live range of the register.
  337. ScheduleDAG::clearDAG();
  338. buildSchedGraph(AA);
  339. NumFixedAnti += Broken;
  340. }
  341. }
  342. DEBUG(dbgs() << "********** List Scheduling **********\n");
  343. DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  344. SUnits[su].dumpAll(this));
  345. AvailableQueue.initNodes(SUnits);
  346. ListScheduleTopDown();
  347. AvailableQueue.releaseState();
  348. }
  349. /// Observe - Update liveness information to account for the current
  350. /// instruction, which will not be scheduled.
  351. ///
  352. void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
  353. if (AntiDepBreak)
  354. AntiDepBreak->Observe(MI, Count, EndIndex);
  355. }
  356. /// FinishBlock - Clean up register live-range state.
  357. ///
  358. void SchedulePostRATDList::finishBlock() {
  359. if (AntiDepBreak)
  360. AntiDepBreak->FinishBlock();
  361. // Call the superclass.
  362. ScheduleDAGInstrs::finishBlock();
  363. }
  364. //===----------------------------------------------------------------------===//
  365. // Top-Down Scheduling
  366. //===----------------------------------------------------------------------===//
  367. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
  368. /// the PendingQueue if the count reaches zero.
  369. void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
  370. SUnit *SuccSU = SuccEdge->getSUnit();
  371. if (SuccEdge->isWeak()) {
  372. --SuccSU->WeakPredsLeft;
  373. return;
  374. }
  375. #ifndef NDEBUG
  376. if (SuccSU->NumPredsLeft == 0) {
  377. dbgs() << "*** Scheduling failed! ***\n";
  378. SuccSU->dump(this);
  379. dbgs() << " has been released too many times!\n";
  380. llvm_unreachable(nullptr);
  381. }
  382. #endif
  383. --SuccSU->NumPredsLeft;
  384. // Standard scheduler algorithms will recompute the depth of the successor
  385. // here as such:
  386. // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
  387. //
  388. // However, we lazily compute node depth instead. Note that
  389. // ScheduleNodeTopDown has already updated the depth of this node which causes
  390. // all descendents to be marked dirty. Setting the successor depth explicitly
  391. // here would cause depth to be recomputed for all its ancestors. If the
  392. // successor is not yet ready (because of a transitively redundant edge) then
  393. // this causes depth computation to be quadratic in the size of the DAG.
  394. // If all the node's predecessors are scheduled, this node is ready
  395. // to be scheduled. Ignore the special ExitSU node.
  396. if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
  397. PendingQueue.push_back(SuccSU);
  398. }
  399. /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
  400. void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
  401. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  402. I != E; ++I) {
  403. ReleaseSucc(SU, &*I);
  404. }
  405. }
  406. /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
  407. /// count of its successors. If a successor pending count is zero, add it to
  408. /// the Available queue.
  409. void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
  410. DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
  411. DEBUG(SU->dump(this));
  412. Sequence.push_back(SU);
  413. assert(CurCycle >= SU->getDepth() &&
  414. "Node scheduled above its depth!");
  415. SU->setDepthToAtLeast(CurCycle);
  416. ReleaseSuccessors(SU);
  417. SU->isScheduled = true;
  418. AvailableQueue.scheduledNode(SU);
  419. }
  420. /// emitNoop - Add a noop to the current instruction sequence.
  421. void SchedulePostRATDList::emitNoop(unsigned CurCycle) {
  422. DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
  423. HazardRec->EmitNoop();
  424. Sequence.push_back(nullptr); // NULL here means noop
  425. ++NumNoops;
  426. }
  427. /// ListScheduleTopDown - The main loop of list scheduling for top-down
  428. /// schedulers.
  429. void SchedulePostRATDList::ListScheduleTopDown() {
  430. unsigned CurCycle = 0;
  431. // We're scheduling top-down but we're visiting the regions in
  432. // bottom-up order, so we don't know the hazards at the start of a
  433. // region. So assume no hazards (this should usually be ok as most
  434. // blocks are a single region).
  435. HazardRec->Reset();
  436. // Release any successors of the special Entry node.
  437. ReleaseSuccessors(&EntrySU);
  438. // Add all leaves to Available queue.
  439. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  440. // It is available if it has no predecessors.
  441. if (!SUnits[i].NumPredsLeft && !SUnits[i].isAvailable) {
  442. AvailableQueue.push(&SUnits[i]);
  443. SUnits[i].isAvailable = true;
  444. }
  445. }
  446. // In any cycle where we can't schedule any instructions, we must
  447. // stall or emit a noop, depending on the target.
  448. bool CycleHasInsts = false;
  449. // While Available queue is not empty, grab the node with the highest
  450. // priority. If it is not ready put it back. Schedule the node.
  451. std::vector<SUnit*> NotReady;
  452. Sequence.reserve(SUnits.size());
  453. while (!AvailableQueue.empty() || !PendingQueue.empty()) {
  454. // Check to see if any of the pending instructions are ready to issue. If
  455. // so, add them to the available queue.
  456. unsigned MinDepth = ~0u;
  457. for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
  458. if (PendingQueue[i]->getDepth() <= CurCycle) {
  459. AvailableQueue.push(PendingQueue[i]);
  460. PendingQueue[i]->isAvailable = true;
  461. PendingQueue[i] = PendingQueue.back();
  462. PendingQueue.pop_back();
  463. --i; --e;
  464. } else if (PendingQueue[i]->getDepth() < MinDepth)
  465. MinDepth = PendingQueue[i]->getDepth();
  466. }
  467. DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
  468. SUnit *FoundSUnit = nullptr, *NotPreferredSUnit = nullptr;
  469. bool HasNoopHazards = false;
  470. while (!AvailableQueue.empty()) {
  471. SUnit *CurSUnit = AvailableQueue.pop();
  472. ScheduleHazardRecognizer::HazardType HT =
  473. HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
  474. if (HT == ScheduleHazardRecognizer::NoHazard) {
  475. if (HazardRec->ShouldPreferAnother(CurSUnit)) {
  476. if (!NotPreferredSUnit) {
  477. // If this is the first non-preferred node for this cycle, then
  478. // record it and continue searching for a preferred node. If this
  479. // is not the first non-preferred node, then treat it as though
  480. // there had been a hazard.
  481. NotPreferredSUnit = CurSUnit;
  482. continue;
  483. }
  484. } else {
  485. FoundSUnit = CurSUnit;
  486. break;
  487. }
  488. }
  489. // Remember if this is a noop hazard.
  490. HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
  491. NotReady.push_back(CurSUnit);
  492. }
  493. // If we have a non-preferred node, push it back onto the available list.
  494. // If we did not find a preferred node, then schedule this first
  495. // non-preferred node.
  496. if (NotPreferredSUnit) {
  497. if (!FoundSUnit) {
  498. DEBUG(dbgs() << "*** Will schedule a non-preferred instruction...\n");
  499. FoundSUnit = NotPreferredSUnit;
  500. } else {
  501. AvailableQueue.push(NotPreferredSUnit);
  502. }
  503. NotPreferredSUnit = nullptr;
  504. }
  505. // Add the nodes that aren't ready back onto the available list.
  506. if (!NotReady.empty()) {
  507. AvailableQueue.push_all(NotReady);
  508. NotReady.clear();
  509. }
  510. // If we found a node to schedule...
  511. if (FoundSUnit) {
  512. // If we need to emit noops prior to this instruction, then do so.
  513. unsigned NumPreNoops = HazardRec->PreEmitNoops(FoundSUnit);
  514. for (unsigned i = 0; i != NumPreNoops; ++i)
  515. emitNoop(CurCycle);
  516. // ... schedule the node...
  517. ScheduleNodeTopDown(FoundSUnit, CurCycle);
  518. HazardRec->EmitInstruction(FoundSUnit);
  519. CycleHasInsts = true;
  520. if (HazardRec->atIssueLimit()) {
  521. DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n');
  522. HazardRec->AdvanceCycle();
  523. ++CurCycle;
  524. CycleHasInsts = false;
  525. }
  526. } else {
  527. if (CycleHasInsts) {
  528. DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
  529. HazardRec->AdvanceCycle();
  530. } else if (!HasNoopHazards) {
  531. // Otherwise, we have a pipeline stall, but no other problem,
  532. // just advance the current cycle and try again.
  533. DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
  534. HazardRec->AdvanceCycle();
  535. ++NumStalls;
  536. } else {
  537. // Otherwise, we have no instructions to issue and we have instructions
  538. // that will fault if we don't do this right. This is the case for
  539. // processors without pipeline interlocks and other cases.
  540. emitNoop(CurCycle);
  541. }
  542. ++CurCycle;
  543. CycleHasInsts = false;
  544. }
  545. }
  546. #ifndef NDEBUG
  547. unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
  548. unsigned Noops = 0;
  549. for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
  550. if (!Sequence[i])
  551. ++Noops;
  552. assert(Sequence.size() - Noops == ScheduledNodes &&
  553. "The number of nodes scheduled doesn't match the expected number!");
  554. #endif // NDEBUG
  555. }
  556. // EmitSchedule - Emit the machine code in scheduled order.
  557. void SchedulePostRATDList::EmitSchedule() {
  558. RegionBegin = RegionEnd;
  559. // If first instruction was a DBG_VALUE then put it back.
  560. if (FirstDbgValue)
  561. BB->splice(RegionEnd, BB, FirstDbgValue);
  562. // Then re-insert them according to the given schedule.
  563. for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
  564. if (SUnit *SU = Sequence[i])
  565. BB->splice(RegionEnd, BB, SU->getInstr());
  566. else
  567. // Null SUnit* is a noop.
  568. TII->insertNoop(*BB, RegionEnd);
  569. // Update the Begin iterator, as the first instruction in the block
  570. // may have been scheduled later.
  571. if (i == 0)
  572. RegionBegin = std::prev(RegionEnd);
  573. }
  574. // Reinsert any remaining debug_values.
  575. for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
  576. DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
  577. std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
  578. MachineInstr *DbgValue = P.first;
  579. MachineBasicBlock::iterator OrigPrivMI = P.second;
  580. BB->splice(++OrigPrivMI, BB, DbgValue);
  581. }
  582. DbgValues.clear();
  583. FirstDbgValue = nullptr;
  584. }