PostRASchedulerList.cpp 23 KB

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