PostRASchedulerList.cpp 24 KB

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