PostRASchedulerList.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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 "AntiDepBreaker.h"
  22. #include "AggressiveAntiDepBreaker.h"
  23. #include "CriticalAntiDepBreaker.h"
  24. #include "ScheduleDAGInstrs.h"
  25. #include "llvm/CodeGen/Passes.h"
  26. #include "llvm/CodeGen/LatencyPriorityQueue.h"
  27. #include "llvm/CodeGen/SchedulerRegistry.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/ScheduleHazardRecognizer.h"
  34. #include "llvm/Analysis/AliasAnalysis.h"
  35. #include "llvm/Target/TargetLowering.h"
  36. #include "llvm/Target/TargetMachine.h"
  37. #include "llvm/Target/TargetInstrInfo.h"
  38. #include "llvm/Target/TargetRegisterInfo.h"
  39. #include "llvm/Target/TargetSubtarget.h"
  40. #include "llvm/Support/CommandLine.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/Support/ErrorHandling.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include "llvm/ADT/BitVector.h"
  45. #include "llvm/ADT/Statistic.h"
  46. #include <set>
  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. // TargetSubtarget.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. AliasAnalysis *AA;
  76. const TargetInstrInfo *TII;
  77. CodeGenOpt::Level OptLevel;
  78. public:
  79. static char ID;
  80. PostRAScheduler(CodeGenOpt::Level ol) :
  81. MachineFunctionPass(ID), OptLevel(ol) {}
  82. void getAnalysisUsage(AnalysisUsage &AU) const {
  83. AU.setPreservesCFG();
  84. AU.addRequired<AliasAnalysis>();
  85. AU.addRequired<MachineDominatorTree>();
  86. AU.addPreserved<MachineDominatorTree>();
  87. AU.addRequired<MachineLoopInfo>();
  88. AU.addPreserved<MachineLoopInfo>();
  89. MachineFunctionPass::getAnalysisUsage(AU);
  90. }
  91. const char *getPassName() const {
  92. return "Post RA top-down list latency scheduler";
  93. }
  94. bool runOnMachineFunction(MachineFunction &Fn);
  95. };
  96. char PostRAScheduler::ID = 0;
  97. class SchedulePostRATDList : public ScheduleDAGInstrs {
  98. /// AvailableQueue - The priority queue to use for the available SUnits.
  99. ///
  100. LatencyPriorityQueue AvailableQueue;
  101. /// PendingQueue - This contains all of the instructions whose operands have
  102. /// been issued, but their results are not ready yet (due to the latency of
  103. /// the operation). Once the operands becomes available, the instruction is
  104. /// added to the AvailableQueue.
  105. std::vector<SUnit*> PendingQueue;
  106. /// Topo - A topological ordering for SUnits.
  107. ScheduleDAGTopologicalSort Topo;
  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. /// KillIndices - The index of the most recent kill (proceding bottom-up),
  115. /// or ~0u if the register is not live.
  116. std::vector<unsigned> KillIndices;
  117. public:
  118. SchedulePostRATDList(
  119. MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
  120. AliasAnalysis *AA, TargetSubtarget::AntiDepBreakMode AntiDepMode,
  121. SmallVectorImpl<TargetRegisterClass*> &CriticalPathRCs);
  122. ~SchedulePostRATDList();
  123. /// StartBlock - Initialize register live-range state for scheduling in
  124. /// this block.
  125. ///
  126. void StartBlock(MachineBasicBlock *BB);
  127. /// Schedule - Schedule the instruction range using list scheduling.
  128. ///
  129. void Schedule();
  130. /// Observe - Update liveness information to account for the current
  131. /// instruction, which will not be scheduled.
  132. ///
  133. void Observe(MachineInstr *MI, unsigned Count);
  134. /// FinishBlock - Clean up register live-range state.
  135. ///
  136. void FinishBlock();
  137. /// FixupKills - Fix register kill flags that have been made
  138. /// invalid due to scheduling
  139. ///
  140. void FixupKills(MachineBasicBlock *MBB);
  141. private:
  142. void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
  143. void ReleaseSuccessors(SUnit *SU);
  144. void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
  145. void ListScheduleTopDown();
  146. void StartBlockForKills(MachineBasicBlock *BB);
  147. // ToggleKillFlag - Toggle a register operand kill flag. Other
  148. // adjustments may be made to the instruction if necessary. Return
  149. // true if the operand has been deleted, false if not.
  150. bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
  151. };
  152. }
  153. SchedulePostRATDList::SchedulePostRATDList(
  154. MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
  155. AliasAnalysis *AA, TargetSubtarget::AntiDepBreakMode AntiDepMode,
  156. SmallVectorImpl<TargetRegisterClass*> &CriticalPathRCs)
  157. : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits), AA(AA),
  158. KillIndices(TRI->getNumRegs())
  159. {
  160. const TargetMachine &TM = MF.getTarget();
  161. const InstrItineraryData *InstrItins = TM.getInstrItineraryData();
  162. HazardRec =
  163. TM.getInstrInfo()->CreateTargetPostRAHazardRecognizer(InstrItins, this);
  164. AntiDepBreak =
  165. ((AntiDepMode == TargetSubtarget::ANTIDEP_ALL) ?
  166. (AntiDepBreaker *)new AggressiveAntiDepBreaker(MF, CriticalPathRCs) :
  167. ((AntiDepMode == TargetSubtarget::ANTIDEP_CRITICAL) ?
  168. (AntiDepBreaker *)new CriticalAntiDepBreaker(MF) : NULL));
  169. }
  170. SchedulePostRATDList::~SchedulePostRATDList() {
  171. delete HazardRec;
  172. delete AntiDepBreak;
  173. }
  174. bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
  175. TII = Fn.getTarget().getInstrInfo();
  176. MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
  177. MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
  178. AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
  179. // Check for explicit enable/disable of post-ra scheduling.
  180. TargetSubtarget::AntiDepBreakMode AntiDepMode = TargetSubtarget::ANTIDEP_NONE;
  181. SmallVector<TargetRegisterClass*, 4> CriticalPathRCs;
  182. if (EnablePostRAScheduler.getPosition() > 0) {
  183. if (!EnablePostRAScheduler)
  184. return false;
  185. } else {
  186. // Check that post-RA scheduling is enabled for this target.
  187. // This may upgrade the AntiDepMode.
  188. const TargetSubtarget &ST = Fn.getTarget().getSubtarget<TargetSubtarget>();
  189. if (!ST.enablePostRAScheduler(OptLevel, AntiDepMode, CriticalPathRCs))
  190. return false;
  191. }
  192. // Check for antidep breaking override...
  193. if (EnableAntiDepBreaking.getPosition() > 0) {
  194. AntiDepMode = (EnableAntiDepBreaking == "all") ?
  195. TargetSubtarget::ANTIDEP_ALL :
  196. (EnableAntiDepBreaking == "critical")
  197. ? TargetSubtarget::ANTIDEP_CRITICAL : TargetSubtarget::ANTIDEP_NONE;
  198. }
  199. DEBUG(dbgs() << "PostRAScheduler\n");
  200. SchedulePostRATDList Scheduler(Fn, MLI, MDT, AA, AntiDepMode,
  201. CriticalPathRCs);
  202. // Loop over all of the basic blocks
  203. for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
  204. MBB != MBBe; ++MBB) {
  205. #ifndef NDEBUG
  206. // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
  207. if (DebugDiv > 0) {
  208. static int bbcnt = 0;
  209. if (bbcnt++ % DebugDiv != DebugMod)
  210. continue;
  211. dbgs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
  212. ":BB#" << MBB->getNumber() << " ***\n";
  213. }
  214. #endif
  215. // Initialize register live-range state for scheduling in this block.
  216. Scheduler.StartBlock(MBB);
  217. // Schedule each sequence of instructions not interrupted by a label
  218. // or anything else that effectively needs to shut down scheduling.
  219. MachineBasicBlock::iterator Current = MBB->end();
  220. unsigned Count = MBB->size(), CurrentCount = Count;
  221. for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
  222. MachineInstr *MI = llvm::prior(I);
  223. if (TII->isSchedulingBoundary(MI, MBB, Fn)) {
  224. Scheduler.Run(MBB, I, Current, CurrentCount);
  225. Scheduler.EmitSchedule();
  226. Current = MI;
  227. CurrentCount = Count - 1;
  228. Scheduler.Observe(MI, CurrentCount);
  229. }
  230. I = MI;
  231. --Count;
  232. }
  233. assert(Count == 0 && "Instruction count mismatch!");
  234. assert((MBB->begin() == Current || CurrentCount != 0) &&
  235. "Instruction count mismatch!");
  236. Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
  237. Scheduler.EmitSchedule();
  238. // Clean up register live-range state.
  239. Scheduler.FinishBlock();
  240. // Update register kills
  241. Scheduler.FixupKills(MBB);
  242. }
  243. return true;
  244. }
  245. /// StartBlock - Initialize register live-range state for scheduling in
  246. /// this block.
  247. ///
  248. void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
  249. // Call the superclass.
  250. ScheduleDAGInstrs::StartBlock(BB);
  251. // Reset the hazard recognizer and anti-dep breaker.
  252. HazardRec->Reset();
  253. if (AntiDepBreak != NULL)
  254. AntiDepBreak->StartBlock(BB);
  255. }
  256. /// Schedule - Schedule the instruction range using list scheduling.
  257. ///
  258. void SchedulePostRATDList::Schedule() {
  259. // Build the scheduling graph.
  260. BuildSchedGraph(AA);
  261. if (AntiDepBreak != NULL) {
  262. unsigned Broken =
  263. AntiDepBreak->BreakAntiDependencies(SUnits, Begin, InsertPos,
  264. InsertPosIndex, DbgValues);
  265. if (Broken != 0) {
  266. // We made changes. Update the dependency graph.
  267. // Theoretically we could update the graph in place:
  268. // When a live range is changed to use a different register, remove
  269. // the def's anti-dependence *and* output-dependence edges due to
  270. // that register, and add new anti-dependence and output-dependence
  271. // edges based on the next live range of the register.
  272. SUnits.clear();
  273. Sequence.clear();
  274. EntrySU = SUnit();
  275. ExitSU = SUnit();
  276. BuildSchedGraph(AA);
  277. NumFixedAnti += Broken;
  278. }
  279. }
  280. DEBUG(dbgs() << "********** List Scheduling **********\n");
  281. DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  282. SUnits[su].dumpAll(this));
  283. AvailableQueue.initNodes(SUnits);
  284. ListScheduleTopDown();
  285. AvailableQueue.releaseState();
  286. }
  287. /// Observe - Update liveness information to account for the current
  288. /// instruction, which will not be scheduled.
  289. ///
  290. void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
  291. if (AntiDepBreak != NULL)
  292. AntiDepBreak->Observe(MI, Count, InsertPosIndex);
  293. }
  294. /// FinishBlock - Clean up register live-range state.
  295. ///
  296. void SchedulePostRATDList::FinishBlock() {
  297. if (AntiDepBreak != NULL)
  298. AntiDepBreak->FinishBlock();
  299. // Call the superclass.
  300. ScheduleDAGInstrs::FinishBlock();
  301. }
  302. /// StartBlockForKills - Initialize register live-range state for updating kills
  303. ///
  304. void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
  305. // Initialize the indices to indicate that no registers are live.
  306. for (unsigned i = 0; i < TRI->getNumRegs(); ++i)
  307. KillIndices[i] = ~0u;
  308. // Determine the live-out physregs for this block.
  309. if (!BB->empty() && BB->back().getDesc().isReturn()) {
  310. // In a return block, examine the function live-out regs.
  311. for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
  312. E = MRI.liveout_end(); I != E; ++I) {
  313. unsigned Reg = *I;
  314. KillIndices[Reg] = BB->size();
  315. // Repeat, for all subregs.
  316. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  317. *Subreg; ++Subreg) {
  318. KillIndices[*Subreg] = BB->size();
  319. }
  320. }
  321. }
  322. else {
  323. // In a non-return block, examine the live-in regs of all successors.
  324. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  325. SE = BB->succ_end(); SI != SE; ++SI) {
  326. for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
  327. E = (*SI)->livein_end(); I != E; ++I) {
  328. unsigned Reg = *I;
  329. KillIndices[Reg] = BB->size();
  330. // Repeat, for all subregs.
  331. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  332. *Subreg; ++Subreg) {
  333. KillIndices[*Subreg] = BB->size();
  334. }
  335. }
  336. }
  337. }
  338. }
  339. bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
  340. MachineOperand &MO) {
  341. // Setting kill flag...
  342. if (!MO.isKill()) {
  343. MO.setIsKill(true);
  344. return false;
  345. }
  346. // If MO itself is live, clear the kill flag...
  347. if (KillIndices[MO.getReg()] != ~0u) {
  348. MO.setIsKill(false);
  349. return false;
  350. }
  351. // If any subreg of MO is live, then create an imp-def for that
  352. // subreg and keep MO marked as killed.
  353. MO.setIsKill(false);
  354. bool AllDead = true;
  355. const unsigned SuperReg = MO.getReg();
  356. for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
  357. *Subreg; ++Subreg) {
  358. if (KillIndices[*Subreg] != ~0u) {
  359. MI->addOperand(MachineOperand::CreateReg(*Subreg,
  360. true /*IsDef*/,
  361. true /*IsImp*/,
  362. false /*IsKill*/,
  363. false /*IsDead*/));
  364. AllDead = false;
  365. }
  366. }
  367. if(AllDead)
  368. MO.setIsKill(true);
  369. return false;
  370. }
  371. /// FixupKills - Fix the register kill flags, they may have been made
  372. /// incorrect by instruction reordering.
  373. ///
  374. void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
  375. DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
  376. std::set<unsigned> killedRegs;
  377. BitVector ReservedRegs = TRI->getReservedRegs(MF);
  378. StartBlockForKills(MBB);
  379. // Examine block from end to start...
  380. unsigned Count = MBB->size();
  381. for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
  382. I != E; --Count) {
  383. MachineInstr *MI = --I;
  384. if (MI->isDebugValue())
  385. continue;
  386. // Update liveness. Registers that are defed but not used in this
  387. // instruction are now dead. Mark register and all subregs as they
  388. // are completely defined.
  389. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  390. MachineOperand &MO = MI->getOperand(i);
  391. if (!MO.isReg()) continue;
  392. unsigned Reg = MO.getReg();
  393. if (Reg == 0) continue;
  394. if (!MO.isDef()) continue;
  395. // Ignore two-addr defs.
  396. if (MI->isRegTiedToUseOperand(i)) continue;
  397. KillIndices[Reg] = ~0u;
  398. // Repeat for all subregs.
  399. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  400. *Subreg; ++Subreg) {
  401. KillIndices[*Subreg] = ~0u;
  402. }
  403. }
  404. // Examine all used registers and set/clear kill flag. When a
  405. // register is used multiple times we only set the kill flag on
  406. // the first use.
  407. killedRegs.clear();
  408. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  409. MachineOperand &MO = MI->getOperand(i);
  410. if (!MO.isReg() || !MO.isUse()) continue;
  411. unsigned Reg = MO.getReg();
  412. if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
  413. bool kill = false;
  414. if (killedRegs.find(Reg) == killedRegs.end()) {
  415. kill = true;
  416. // A register is not killed if any subregs are live...
  417. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  418. *Subreg; ++Subreg) {
  419. if (KillIndices[*Subreg] != ~0u) {
  420. kill = false;
  421. break;
  422. }
  423. }
  424. // If subreg is not live, then register is killed if it became
  425. // live in this instruction
  426. if (kill)
  427. kill = (KillIndices[Reg] == ~0u);
  428. }
  429. if (MO.isKill() != kill) {
  430. DEBUG(dbgs() << "Fixing " << MO << " in ");
  431. // Warning: ToggleKillFlag may invalidate MO.
  432. ToggleKillFlag(MI, MO);
  433. DEBUG(MI->dump());
  434. }
  435. killedRegs.insert(Reg);
  436. }
  437. // Mark any used register (that is not using undef) and subregs as
  438. // now live...
  439. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  440. MachineOperand &MO = MI->getOperand(i);
  441. if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
  442. unsigned Reg = MO.getReg();
  443. if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
  444. KillIndices[Reg] = Count;
  445. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  446. *Subreg; ++Subreg) {
  447. KillIndices[*Subreg] = Count;
  448. }
  449. }
  450. }
  451. }
  452. //===----------------------------------------------------------------------===//
  453. // Top-Down Scheduling
  454. //===----------------------------------------------------------------------===//
  455. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
  456. /// the PendingQueue if the count reaches zero. Also update its cycle bound.
  457. void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
  458. SUnit *SuccSU = SuccEdge->getSUnit();
  459. #ifndef NDEBUG
  460. if (SuccSU->NumPredsLeft == 0) {
  461. dbgs() << "*** Scheduling failed! ***\n";
  462. SuccSU->dump(this);
  463. dbgs() << " has been released too many times!\n";
  464. llvm_unreachable(0);
  465. }
  466. #endif
  467. --SuccSU->NumPredsLeft;
  468. // Standard scheduler algorithms will recompute the depth of the successor
  469. // here as such:
  470. // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
  471. //
  472. // However, we lazily compute node depth instead. Note that
  473. // ScheduleNodeTopDown has already updated the depth of this node which causes
  474. // all descendents to be marked dirty. Setting the successor depth explicitly
  475. // here would cause depth to be recomputed for all its ancestors. If the
  476. // successor is not yet ready (because of a transitively redundant edge) then
  477. // this causes depth computation to be quadratic in the size of the DAG.
  478. // If all the node's predecessors are scheduled, this node is ready
  479. // to be scheduled. Ignore the special ExitSU node.
  480. if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
  481. PendingQueue.push_back(SuccSU);
  482. }
  483. /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
  484. void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
  485. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  486. I != E; ++I) {
  487. ReleaseSucc(SU, &*I);
  488. }
  489. }
  490. /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
  491. /// count of its successors. If a successor pending count is zero, add it to
  492. /// the Available queue.
  493. void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
  494. DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
  495. DEBUG(SU->dump(this));
  496. Sequence.push_back(SU);
  497. assert(CurCycle >= SU->getDepth() &&
  498. "Node scheduled above its depth!");
  499. SU->setDepthToAtLeast(CurCycle);
  500. ReleaseSuccessors(SU);
  501. SU->isScheduled = true;
  502. AvailableQueue.ScheduledNode(SU);
  503. }
  504. /// ListScheduleTopDown - The main loop of list scheduling for top-down
  505. /// schedulers.
  506. void SchedulePostRATDList::ListScheduleTopDown() {
  507. unsigned CurCycle = 0;
  508. // We're scheduling top-down but we're visiting the regions in
  509. // bottom-up order, so we don't know the hazards at the start of a
  510. // region. So assume no hazards (this should usually be ok as most
  511. // blocks are a single region).
  512. HazardRec->Reset();
  513. // Release any successors of the special Entry node.
  514. ReleaseSuccessors(&EntrySU);
  515. // Add all leaves to Available queue.
  516. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  517. // It is available if it has no predecessors.
  518. bool available = SUnits[i].Preds.empty();
  519. if (available) {
  520. AvailableQueue.push(&SUnits[i]);
  521. SUnits[i].isAvailable = true;
  522. }
  523. }
  524. // In any cycle where we can't schedule any instructions, we must
  525. // stall or emit a noop, depending on the target.
  526. bool CycleHasInsts = false;
  527. // While Available queue is not empty, grab the node with the highest
  528. // priority. If it is not ready put it back. Schedule the node.
  529. std::vector<SUnit*> NotReady;
  530. Sequence.reserve(SUnits.size());
  531. while (!AvailableQueue.empty() || !PendingQueue.empty()) {
  532. // Check to see if any of the pending instructions are ready to issue. If
  533. // so, add them to the available queue.
  534. unsigned MinDepth = ~0u;
  535. for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
  536. if (PendingQueue[i]->getDepth() <= CurCycle) {
  537. AvailableQueue.push(PendingQueue[i]);
  538. PendingQueue[i]->isAvailable = true;
  539. PendingQueue[i] = PendingQueue.back();
  540. PendingQueue.pop_back();
  541. --i; --e;
  542. } else if (PendingQueue[i]->getDepth() < MinDepth)
  543. MinDepth = PendingQueue[i]->getDepth();
  544. }
  545. DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
  546. SUnit *FoundSUnit = 0;
  547. bool HasNoopHazards = false;
  548. while (!AvailableQueue.empty()) {
  549. SUnit *CurSUnit = AvailableQueue.pop();
  550. ScheduleHazardRecognizer::HazardType HT =
  551. HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
  552. if (HT == ScheduleHazardRecognizer::NoHazard) {
  553. FoundSUnit = CurSUnit;
  554. break;
  555. }
  556. // Remember if this is a noop hazard.
  557. HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
  558. NotReady.push_back(CurSUnit);
  559. }
  560. // Add the nodes that aren't ready back onto the available list.
  561. if (!NotReady.empty()) {
  562. AvailableQueue.push_all(NotReady);
  563. NotReady.clear();
  564. }
  565. // If we found a node to schedule...
  566. if (FoundSUnit) {
  567. // ... schedule the node...
  568. ScheduleNodeTopDown(FoundSUnit, CurCycle);
  569. HazardRec->EmitInstruction(FoundSUnit);
  570. CycleHasInsts = true;
  571. if (HazardRec->atIssueLimit()) {
  572. DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n');
  573. HazardRec->AdvanceCycle();
  574. ++CurCycle;
  575. CycleHasInsts = false;
  576. }
  577. } else {
  578. if (CycleHasInsts) {
  579. DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
  580. HazardRec->AdvanceCycle();
  581. } else if (!HasNoopHazards) {
  582. // Otherwise, we have a pipeline stall, but no other problem,
  583. // just advance the current cycle and try again.
  584. DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
  585. HazardRec->AdvanceCycle();
  586. ++NumStalls;
  587. } else {
  588. // Otherwise, we have no instructions to issue and we have instructions
  589. // that will fault if we don't do this right. This is the case for
  590. // processors without pipeline interlocks and other cases.
  591. DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
  592. HazardRec->EmitNoop();
  593. Sequence.push_back(0); // NULL here means noop
  594. ++NumNoops;
  595. }
  596. ++CurCycle;
  597. CycleHasInsts = false;
  598. }
  599. }
  600. #ifndef NDEBUG
  601. VerifySchedule(/*isBottomUp=*/false);
  602. #endif
  603. }
  604. //===----------------------------------------------------------------------===//
  605. // Public Constructor Functions
  606. //===----------------------------------------------------------------------===//
  607. FunctionPass *llvm::createPostRAScheduler(CodeGenOpt::Level OptLevel) {
  608. return new PostRAScheduler(OptLevel);
  609. }