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