PostRASchedulerList.cpp 27 KB

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