1 //===- MachineScheduler.cpp - Machine Instruction 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 // MachineScheduler schedules machine instructions after phi elimination. It 11 // preserves LiveIntervals so it can be invoked before register allocation. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/MachineScheduler.h" 16 #include "llvm/ADT/PriorityQueue.h" 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 19 #include "llvm/CodeGen/MachineDominators.h" 20 #include "llvm/CodeGen/MachineLoopInfo.h" 21 #include "llvm/CodeGen/MachineRegisterInfo.h" 22 #include "llvm/CodeGen/Passes.h" 23 #include "llvm/CodeGen/RegisterClassInfo.h" 24 #include "llvm/CodeGen/ScheduleDFS.h" 25 #include "llvm/CodeGen/ScheduleHazardRecognizer.h" 26 #include "llvm/CodeGen/TargetPassConfig.h" 27 #include "llvm/Support/CommandLine.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/GraphWriter.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include "llvm/Target/TargetInstrInfo.h" 33 34 using namespace llvm; 35 36 #define DEBUG_TYPE "misched" 37 38 namespace llvm { 39 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden, 40 cl::desc("Force top-down list scheduling")); 41 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden, 42 cl::desc("Force bottom-up list scheduling")); 43 cl::opt<bool> 44 DumpCriticalPathLength("misched-dcpl", cl::Hidden, 45 cl::desc("Print critical path length to stdout")); 46 } 47 48 #ifndef NDEBUG 49 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden, 50 cl::desc("Pop up a window to show MISched dags after they are processed")); 51 52 /// In some situations a few uninteresting nodes depend on nearly all other 53 /// nodes in the graph, provide a cutoff to hide them. 54 static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden, 55 cl::desc("Hide nodes with more predecessor/successor than cutoff")); 56 57 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden, 58 cl::desc("Stop scheduling after N instructions"), cl::init(~0U)); 59 60 static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden, 61 cl::desc("Only schedule this function")); 62 static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden, 63 cl::desc("Only schedule this MBB#")); 64 #else 65 static bool ViewMISchedDAGs = false; 66 #endif // NDEBUG 67 68 /// Avoid quadratic complexity in unusually large basic blocks by limiting the 69 /// size of the ready lists. 70 static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden, 71 cl::desc("Limit ready list to N instructions"), cl::init(256)); 72 73 static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden, 74 cl::desc("Enable register pressure scheduling."), cl::init(true)); 75 76 static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden, 77 cl::desc("Enable cyclic critical path analysis."), cl::init(true)); 78 79 static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden, 80 cl::desc("Enable memop clustering."), 81 cl::init(true)); 82 83 // Experimental heuristics 84 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden, 85 cl::desc("Enable scheduling for macro fusion."), cl::init(true)); 86 87 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden, 88 cl::desc("Verify machine instrs before and after machine scheduling")); 89 90 // DAG subtrees must have at least this many nodes. 91 static const unsigned MinSubtreeSize = 8; 92 93 // Pin the vtables to this file. 94 void MachineSchedStrategy::anchor() {} 95 void ScheduleDAGMutation::anchor() {} 96 97 //===----------------------------------------------------------------------===// 98 // Machine Instruction Scheduling Pass and Registry 99 //===----------------------------------------------------------------------===// 100 101 MachineSchedContext::MachineSchedContext(): 102 MF(nullptr), MLI(nullptr), MDT(nullptr), PassConfig(nullptr), AA(nullptr), LIS(nullptr) { 103 RegClassInfo = new RegisterClassInfo(); 104 } 105 106 MachineSchedContext::~MachineSchedContext() { 107 delete RegClassInfo; 108 } 109 110 namespace { 111 /// Base class for a machine scheduler class that can run at any point. 112 class MachineSchedulerBase : public MachineSchedContext, 113 public MachineFunctionPass { 114 public: 115 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {} 116 117 void print(raw_ostream &O, const Module* = nullptr) const override; 118 119 protected: 120 void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags); 121 }; 122 123 /// MachineScheduler runs after coalescing and before register allocation. 124 class MachineScheduler : public MachineSchedulerBase { 125 public: 126 MachineScheduler(); 127 128 void getAnalysisUsage(AnalysisUsage &AU) const override; 129 130 bool runOnMachineFunction(MachineFunction&) override; 131 132 static char ID; // Class identification, replacement for typeinfo 133 134 protected: 135 ScheduleDAGInstrs *createMachineScheduler(); 136 }; 137 138 /// PostMachineScheduler runs after shortly before code emission. 139 class PostMachineScheduler : public MachineSchedulerBase { 140 public: 141 PostMachineScheduler(); 142 143 void getAnalysisUsage(AnalysisUsage &AU) const override; 144 145 bool runOnMachineFunction(MachineFunction&) override; 146 147 static char ID; // Class identification, replacement for typeinfo 148 149 protected: 150 ScheduleDAGInstrs *createPostMachineScheduler(); 151 }; 152 } // namespace 153 154 char MachineScheduler::ID = 0; 155 156 char &llvm::MachineSchedulerID = MachineScheduler::ID; 157 158 INITIALIZE_PASS_BEGIN(MachineScheduler, "machine-scheduler", 159 "Machine Instruction Scheduler", false, false) 160 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 161 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 162 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 163 INITIALIZE_PASS_END(MachineScheduler, "machine-scheduler", 164 "Machine Instruction Scheduler", false, false) 165 166 MachineScheduler::MachineScheduler() 167 : MachineSchedulerBase(ID) { 168 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry()); 169 } 170 171 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const { 172 AU.setPreservesCFG(); 173 AU.addRequiredID(MachineDominatorsID); 174 AU.addRequired<MachineLoopInfo>(); 175 AU.addRequired<AAResultsWrapperPass>(); 176 AU.addRequired<TargetPassConfig>(); 177 AU.addRequired<SlotIndexes>(); 178 AU.addPreserved<SlotIndexes>(); 179 AU.addRequired<LiveIntervals>(); 180 AU.addPreserved<LiveIntervals>(); 181 MachineFunctionPass::getAnalysisUsage(AU); 182 } 183 184 char PostMachineScheduler::ID = 0; 185 186 char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID; 187 188 INITIALIZE_PASS(PostMachineScheduler, "postmisched", 189 "PostRA Machine Instruction Scheduler", false, false) 190 191 PostMachineScheduler::PostMachineScheduler() 192 : MachineSchedulerBase(ID) { 193 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry()); 194 } 195 196 void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const { 197 AU.setPreservesCFG(); 198 AU.addRequiredID(MachineDominatorsID); 199 AU.addRequired<MachineLoopInfo>(); 200 AU.addRequired<TargetPassConfig>(); 201 MachineFunctionPass::getAnalysisUsage(AU); 202 } 203 204 MachinePassRegistry MachineSchedRegistry::Registry; 205 206 /// A dummy default scheduler factory indicates whether the scheduler 207 /// is overridden on the command line. 208 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) { 209 return nullptr; 210 } 211 212 /// MachineSchedOpt allows command line selection of the scheduler. 213 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false, 214 RegisterPassParser<MachineSchedRegistry> > 215 MachineSchedOpt("misched", 216 cl::init(&useDefaultMachineSched), cl::Hidden, 217 cl::desc("Machine instruction scheduler to use")); 218 219 static MachineSchedRegistry 220 DefaultSchedRegistry("default", "Use the target's default scheduler choice.", 221 useDefaultMachineSched); 222 223 static cl::opt<bool> EnableMachineSched( 224 "enable-misched", 225 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true), 226 cl::Hidden); 227 228 static cl::opt<bool> EnablePostRAMachineSched( 229 "enable-post-misched", 230 cl::desc("Enable the post-ra machine instruction scheduling pass."), 231 cl::init(true), cl::Hidden); 232 233 /// Forward declare the standard machine scheduler. This will be used as the 234 /// default scheduler if the target does not set a default. 235 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C); 236 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C); 237 238 /// Decrement this iterator until reaching the top or a non-debug instr. 239 static MachineBasicBlock::const_iterator 240 priorNonDebug(MachineBasicBlock::const_iterator I, 241 MachineBasicBlock::const_iterator Beg) { 242 assert(I != Beg && "reached the top of the region, cannot decrement"); 243 while (--I != Beg) { 244 if (!I->isDebugValue()) 245 break; 246 } 247 return I; 248 } 249 250 /// Non-const version. 251 static MachineBasicBlock::iterator 252 priorNonDebug(MachineBasicBlock::iterator I, 253 MachineBasicBlock::const_iterator Beg) { 254 return const_cast<MachineInstr*>( 255 &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)); 256 } 257 258 /// If this iterator is a debug value, increment until reaching the End or a 259 /// non-debug instruction. 260 static MachineBasicBlock::const_iterator 261 nextIfDebug(MachineBasicBlock::const_iterator I, 262 MachineBasicBlock::const_iterator End) { 263 for(; I != End; ++I) { 264 if (!I->isDebugValue()) 265 break; 266 } 267 return I; 268 } 269 270 /// Non-const version. 271 static MachineBasicBlock::iterator 272 nextIfDebug(MachineBasicBlock::iterator I, 273 MachineBasicBlock::const_iterator End) { 274 // Cast the return value to nonconst MachineInstr, then cast to an 275 // instr_iterator, which does not check for null, finally return a 276 // bundle_iterator. 277 return MachineBasicBlock::instr_iterator( 278 const_cast<MachineInstr*>( 279 &*nextIfDebug(MachineBasicBlock::const_iterator(I), End))); 280 } 281 282 /// Instantiate a ScheduleDAGInstrs that will be owned by the caller. 283 ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() { 284 // Select the scheduler, or set the default. 285 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt; 286 if (Ctor != useDefaultMachineSched) 287 return Ctor(this); 288 289 // Get the default scheduler set by the target for this function. 290 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this); 291 if (Scheduler) 292 return Scheduler; 293 294 // Default to GenericScheduler. 295 return createGenericSchedLive(this); 296 } 297 298 /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by 299 /// the caller. We don't have a command line option to override the postRA 300 /// scheduler. The Target must configure it. 301 ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() { 302 // Get the postRA scheduler set by the target for this function. 303 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this); 304 if (Scheduler) 305 return Scheduler; 306 307 // Default to GenericScheduler. 308 return createGenericSchedPostRA(this); 309 } 310 311 /// Top-level MachineScheduler pass driver. 312 /// 313 /// Visit blocks in function order. Divide each block into scheduling regions 314 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is 315 /// consistent with the DAG builder, which traverses the interior of the 316 /// scheduling regions bottom-up. 317 /// 318 /// This design avoids exposing scheduling boundaries to the DAG builder, 319 /// simplifying the DAG builder's support for "special" target instructions. 320 /// At the same time the design allows target schedulers to operate across 321 /// scheduling boundaries, for example to bundle the boudary instructions 322 /// without reordering them. This creates complexity, because the target 323 /// scheduler must update the RegionBegin and RegionEnd positions cached by 324 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler 325 /// design would be to split blocks at scheduling boundaries, but LLVM has a 326 /// general bias against block splitting purely for implementation simplicity. 327 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) { 328 if (skipFunction(*mf.getFunction())) 329 return false; 330 331 if (EnableMachineSched.getNumOccurrences()) { 332 if (!EnableMachineSched) 333 return false; 334 } else if (!mf.getSubtarget().enableMachineScheduler()) 335 return false; 336 337 DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs())); 338 339 // Initialize the context of the pass. 340 MF = &mf; 341 MLI = &getAnalysis<MachineLoopInfo>(); 342 MDT = &getAnalysis<MachineDominatorTree>(); 343 PassConfig = &getAnalysis<TargetPassConfig>(); 344 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 345 346 LIS = &getAnalysis<LiveIntervals>(); 347 348 if (VerifyScheduling) { 349 DEBUG(LIS->dump()); 350 MF->verify(this, "Before machine scheduling."); 351 } 352 RegClassInfo->runOnMachineFunction(*MF); 353 354 // Instantiate the selected scheduler for this target, function, and 355 // optimization level. 356 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler()); 357 scheduleRegions(*Scheduler, false); 358 359 DEBUG(LIS->dump()); 360 if (VerifyScheduling) 361 MF->verify(this, "After machine scheduling."); 362 return true; 363 } 364 365 bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) { 366 if (skipFunction(*mf.getFunction())) 367 return false; 368 369 if (EnablePostRAMachineSched.getNumOccurrences()) { 370 if (!EnablePostRAMachineSched) 371 return false; 372 } else if (!mf.getSubtarget().enablePostRAScheduler()) { 373 DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n"); 374 return false; 375 } 376 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs())); 377 378 // Initialize the context of the pass. 379 MF = &mf; 380 PassConfig = &getAnalysis<TargetPassConfig>(); 381 382 if (VerifyScheduling) 383 MF->verify(this, "Before post machine scheduling."); 384 385 // Instantiate the selected scheduler for this target, function, and 386 // optimization level. 387 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler()); 388 scheduleRegions(*Scheduler, true); 389 390 if (VerifyScheduling) 391 MF->verify(this, "After post machine scheduling."); 392 return true; 393 } 394 395 /// Return true of the given instruction should not be included in a scheduling 396 /// region. 397 /// 398 /// MachineScheduler does not currently support scheduling across calls. To 399 /// handle calls, the DAG builder needs to be modified to create register 400 /// anti/output dependencies on the registers clobbered by the call's regmask 401 /// operand. In PreRA scheduling, the stack pointer adjustment already prevents 402 /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce 403 /// the boundary, but there would be no benefit to postRA scheduling across 404 /// calls this late anyway. 405 static bool isSchedBoundary(MachineBasicBlock::iterator MI, 406 MachineBasicBlock *MBB, 407 MachineFunction *MF, 408 const TargetInstrInfo *TII) { 409 return MI->isCall() || TII->isSchedulingBoundary(MI, MBB, *MF); 410 } 411 412 /// Main driver for both MachineScheduler and PostMachineScheduler. 413 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler, 414 bool FixKillFlags) { 415 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 416 417 // Visit all machine basic blocks. 418 // 419 // TODO: Visit blocks in global postorder or postorder within the bottom-up 420 // loop tree. Then we can optionally compute global RegPressure. 421 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end(); 422 MBB != MBBEnd; ++MBB) { 423 424 Scheduler.startBlock(&*MBB); 425 426 #ifndef NDEBUG 427 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName()) 428 continue; 429 if (SchedOnlyBlock.getNumOccurrences() 430 && (int)SchedOnlyBlock != MBB->getNumber()) 431 continue; 432 #endif 433 434 // Break the block into scheduling regions [I, RegionEnd), and schedule each 435 // region as soon as it is discovered. RegionEnd points the scheduling 436 // boundary at the bottom of the region. The DAG does not include RegionEnd, 437 // but the region does (i.e. the next RegionEnd is above the previous 438 // RegionBegin). If the current block has no terminator then RegionEnd == 439 // MBB->end() for the bottom region. 440 // 441 // The Scheduler may insert instructions during either schedule() or 442 // exitRegion(), even for empty regions. So the local iterators 'I' and 443 // 'RegionEnd' are invalid across these calls. 444 // 445 // MBB::size() uses instr_iterator to count. Here we need a bundle to count 446 // as a single instruction. 447 for(MachineBasicBlock::iterator RegionEnd = MBB->end(); 448 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) { 449 450 // Avoid decrementing RegionEnd for blocks with no terminator. 451 if (RegionEnd != MBB->end() || 452 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) { 453 --RegionEnd; 454 } 455 456 // The next region starts above the previous region. Look backward in the 457 // instruction stream until we find the nearest boundary. 458 unsigned NumRegionInstrs = 0; 459 MachineBasicBlock::iterator I = RegionEnd; 460 for (;I != MBB->begin(); --I) { 461 if (isSchedBoundary(&*std::prev(I), &*MBB, MF, TII)) 462 break; 463 if (!I->isDebugValue()) 464 ++NumRegionInstrs; 465 } 466 // Notify the scheduler of the region, even if we may skip scheduling 467 // it. Perhaps it still needs to be bundled. 468 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs); 469 470 // Skip empty scheduling regions (0 or 1 schedulable instructions). 471 if (I == RegionEnd || I == std::prev(RegionEnd)) { 472 // Close the current region. Bundle the terminator if needed. 473 // This invalidates 'RegionEnd' and 'I'. 474 Scheduler.exitRegion(); 475 continue; 476 } 477 DEBUG(dbgs() << "********** MI Scheduling **********\n"); 478 DEBUG(dbgs() << MF->getName() 479 << ":BB#" << MBB->getNumber() << " " << MBB->getName() 480 << "\n From: " << *I << " To: "; 481 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd; 482 else dbgs() << "End"; 483 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n'); 484 if (DumpCriticalPathLength) { 485 errs() << MF->getName(); 486 errs() << ":BB# " << MBB->getNumber(); 487 errs() << " " << MBB->getName() << " \n"; 488 } 489 490 // Schedule a region: possibly reorder instructions. 491 // This invalidates 'RegionEnd' and 'I'. 492 Scheduler.schedule(); 493 494 // Close the current region. 495 Scheduler.exitRegion(); 496 497 // Scheduling has invalidated the current iterator 'I'. Ask the 498 // scheduler for the top of it's scheduled region. 499 RegionEnd = Scheduler.begin(); 500 } 501 Scheduler.finishBlock(); 502 // FIXME: Ideally, no further passes should rely on kill flags. However, 503 // thumb2 size reduction is currently an exception, so the PostMIScheduler 504 // needs to do this. 505 if (FixKillFlags) 506 Scheduler.fixupKills(&*MBB); 507 } 508 Scheduler.finalizeSchedule(); 509 } 510 511 void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const { 512 // unimplemented 513 } 514 515 LLVM_DUMP_METHOD 516 void ReadyQueue::dump() { 517 dbgs() << "Queue " << Name << ": "; 518 for (unsigned i = 0, e = Queue.size(); i < e; ++i) 519 dbgs() << Queue[i]->NodeNum << " "; 520 dbgs() << "\n"; 521 } 522 523 //===----------------------------------------------------------------------===// 524 // ScheduleDAGMI - Basic machine instruction scheduling. This is 525 // independent of PreRA/PostRA scheduling and involves no extra book-keeping for 526 // virtual registers. 527 // ===----------------------------------------------------------------------===/ 528 529 // Provide a vtable anchor. 530 ScheduleDAGMI::~ScheduleDAGMI() { 531 } 532 533 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) { 534 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU); 535 } 536 537 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) { 538 if (SuccSU != &ExitSU) { 539 // Do not use WillCreateCycle, it assumes SD scheduling. 540 // If Pred is reachable from Succ, then the edge creates a cycle. 541 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU)) 542 return false; 543 Topo.AddPred(SuccSU, PredDep.getSUnit()); 544 } 545 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial()); 546 // Return true regardless of whether a new edge needed to be inserted. 547 return true; 548 } 549 550 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When 551 /// NumPredsLeft reaches zero, release the successor node. 552 /// 553 /// FIXME: Adjust SuccSU height based on MinLatency. 554 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) { 555 SUnit *SuccSU = SuccEdge->getSUnit(); 556 557 if (SuccEdge->isWeak()) { 558 --SuccSU->WeakPredsLeft; 559 if (SuccEdge->isCluster()) 560 NextClusterSucc = SuccSU; 561 return; 562 } 563 #ifndef NDEBUG 564 if (SuccSU->NumPredsLeft == 0) { 565 dbgs() << "*** Scheduling failed! ***\n"; 566 SuccSU->dump(this); 567 dbgs() << " has been released too many times!\n"; 568 llvm_unreachable(nullptr); 569 } 570 #endif 571 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However, 572 // CurrCycle may have advanced since then. 573 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency()) 574 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency(); 575 576 --SuccSU->NumPredsLeft; 577 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) 578 SchedImpl->releaseTopNode(SuccSU); 579 } 580 581 /// releaseSuccessors - Call releaseSucc on each of SU's successors. 582 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) { 583 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end(); 584 I != E; ++I) { 585 releaseSucc(SU, &*I); 586 } 587 } 588 589 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When 590 /// NumSuccsLeft reaches zero, release the predecessor node. 591 /// 592 /// FIXME: Adjust PredSU height based on MinLatency. 593 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) { 594 SUnit *PredSU = PredEdge->getSUnit(); 595 596 if (PredEdge->isWeak()) { 597 --PredSU->WeakSuccsLeft; 598 if (PredEdge->isCluster()) 599 NextClusterPred = PredSU; 600 return; 601 } 602 #ifndef NDEBUG 603 if (PredSU->NumSuccsLeft == 0) { 604 dbgs() << "*** Scheduling failed! ***\n"; 605 PredSU->dump(this); 606 dbgs() << " has been released too many times!\n"; 607 llvm_unreachable(nullptr); 608 } 609 #endif 610 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However, 611 // CurrCycle may have advanced since then. 612 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency()) 613 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency(); 614 615 --PredSU->NumSuccsLeft; 616 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) 617 SchedImpl->releaseBottomNode(PredSU); 618 } 619 620 /// releasePredecessors - Call releasePred on each of SU's predecessors. 621 void ScheduleDAGMI::releasePredecessors(SUnit *SU) { 622 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); 623 I != E; ++I) { 624 releasePred(SU, &*I); 625 } 626 } 627 628 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after 629 /// crossing a scheduling boundary. [begin, end) includes all instructions in 630 /// the region, including the boundary itself and single-instruction regions 631 /// that don't get scheduled. 632 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb, 633 MachineBasicBlock::iterator begin, 634 MachineBasicBlock::iterator end, 635 unsigned regioninstrs) 636 { 637 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs); 638 639 SchedImpl->initPolicy(begin, end, regioninstrs); 640 } 641 642 /// This is normally called from the main scheduler loop but may also be invoked 643 /// by the scheduling strategy to perform additional code motion. 644 void ScheduleDAGMI::moveInstruction( 645 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) { 646 // Advance RegionBegin if the first instruction moves down. 647 if (&*RegionBegin == MI) 648 ++RegionBegin; 649 650 // Update the instruction stream. 651 BB->splice(InsertPos, BB, MI); 652 653 // Update LiveIntervals 654 if (LIS) 655 LIS->handleMove(*MI, /*UpdateFlags=*/true); 656 657 // Recede RegionBegin if an instruction moves above the first. 658 if (RegionBegin == InsertPos) 659 RegionBegin = MI; 660 } 661 662 bool ScheduleDAGMI::checkSchedLimit() { 663 #ifndef NDEBUG 664 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) { 665 CurrentTop = CurrentBottom; 666 return false; 667 } 668 ++NumInstrsScheduled; 669 #endif 670 return true; 671 } 672 673 /// Per-region scheduling driver, called back from 674 /// MachineScheduler::runOnMachineFunction. This is a simplified driver that 675 /// does not consider liveness or register pressure. It is useful for PostRA 676 /// scheduling and potentially other custom schedulers. 677 void ScheduleDAGMI::schedule() { 678 DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n"); 679 DEBUG(SchedImpl->dumpPolicy()); 680 681 // Build the DAG. 682 buildSchedGraph(AA); 683 684 Topo.InitDAGTopologicalSorting(); 685 686 postprocessDAG(); 687 688 SmallVector<SUnit*, 8> TopRoots, BotRoots; 689 findRootsAndBiasEdges(TopRoots, BotRoots); 690 691 // Initialize the strategy before modifying the DAG. 692 // This may initialize a DFSResult to be used for queue priority. 693 SchedImpl->initialize(this); 694 695 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su) 696 SUnits[su].dumpAll(this)); 697 if (ViewMISchedDAGs) viewGraph(); 698 699 // Initialize ready queues now that the DAG and priority data are finalized. 700 initQueues(TopRoots, BotRoots); 701 702 bool IsTopNode = false; 703 while (true) { 704 DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n"); 705 SUnit *SU = SchedImpl->pickNode(IsTopNode); 706 if (!SU) break; 707 708 assert(!SU->isScheduled && "Node already scheduled"); 709 if (!checkSchedLimit()) 710 break; 711 712 MachineInstr *MI = SU->getInstr(); 713 if (IsTopNode) { 714 assert(SU->isTopReady() && "node still has unscheduled dependencies"); 715 if (&*CurrentTop == MI) 716 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom); 717 else 718 moveInstruction(MI, CurrentTop); 719 } else { 720 assert(SU->isBottomReady() && "node still has unscheduled dependencies"); 721 MachineBasicBlock::iterator priorII = 722 priorNonDebug(CurrentBottom, CurrentTop); 723 if (&*priorII == MI) 724 CurrentBottom = priorII; 725 else { 726 if (&*CurrentTop == MI) 727 CurrentTop = nextIfDebug(++CurrentTop, priorII); 728 moveInstruction(MI, CurrentBottom); 729 CurrentBottom = MI; 730 } 731 } 732 // Notify the scheduling strategy before updating the DAG. 733 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues 734 // runs, it can then use the accurate ReadyCycle time to determine whether 735 // newly released nodes can move to the readyQ. 736 SchedImpl->schedNode(SU, IsTopNode); 737 738 updateQueues(SU, IsTopNode); 739 } 740 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone."); 741 742 placeDebugValues(); 743 744 DEBUG({ 745 unsigned BBNum = begin()->getParent()->getNumber(); 746 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n"; 747 dumpSchedule(); 748 dbgs() << '\n'; 749 }); 750 } 751 752 /// Apply each ScheduleDAGMutation step in order. 753 void ScheduleDAGMI::postprocessDAG() { 754 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) { 755 Mutations[i]->apply(this); 756 } 757 } 758 759 void ScheduleDAGMI:: 760 findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots, 761 SmallVectorImpl<SUnit*> &BotRoots) { 762 for (std::vector<SUnit>::iterator 763 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) { 764 SUnit *SU = &(*I); 765 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits"); 766 767 // Order predecessors so DFSResult follows the critical path. 768 SU->biasCriticalPath(); 769 770 // A SUnit is ready to top schedule if it has no predecessors. 771 if (!I->NumPredsLeft) 772 TopRoots.push_back(SU); 773 // A SUnit is ready to bottom schedule if it has no successors. 774 if (!I->NumSuccsLeft) 775 BotRoots.push_back(SU); 776 } 777 ExitSU.biasCriticalPath(); 778 } 779 780 /// Identify DAG roots and setup scheduler queues. 781 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots, 782 ArrayRef<SUnit*> BotRoots) { 783 NextClusterSucc = nullptr; 784 NextClusterPred = nullptr; 785 786 // Release all DAG roots for scheduling, not including EntrySU/ExitSU. 787 // 788 // Nodes with unreleased weak edges can still be roots. 789 // Release top roots in forward order. 790 for (SmallVectorImpl<SUnit*>::const_iterator 791 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) { 792 SchedImpl->releaseTopNode(*I); 793 } 794 // Release bottom roots in reverse order so the higher priority nodes appear 795 // first. This is more natural and slightly more efficient. 796 for (SmallVectorImpl<SUnit*>::const_reverse_iterator 797 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) { 798 SchedImpl->releaseBottomNode(*I); 799 } 800 801 releaseSuccessors(&EntrySU); 802 releasePredecessors(&ExitSU); 803 804 SchedImpl->registerRoots(); 805 806 // Advance past initial DebugValues. 807 CurrentTop = nextIfDebug(RegionBegin, RegionEnd); 808 CurrentBottom = RegionEnd; 809 } 810 811 /// Update scheduler queues after scheduling an instruction. 812 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) { 813 // Release dependent instructions for scheduling. 814 if (IsTopNode) 815 releaseSuccessors(SU); 816 else 817 releasePredecessors(SU); 818 819 SU->isScheduled = true; 820 } 821 822 /// Reinsert any remaining debug_values, just like the PostRA scheduler. 823 void ScheduleDAGMI::placeDebugValues() { 824 // If first instruction was a DBG_VALUE then put it back. 825 if (FirstDbgValue) { 826 BB->splice(RegionBegin, BB, FirstDbgValue); 827 RegionBegin = FirstDbgValue; 828 } 829 830 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator 831 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) { 832 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI); 833 MachineInstr *DbgValue = P.first; 834 MachineBasicBlock::iterator OrigPrevMI = P.second; 835 if (&*RegionBegin == DbgValue) 836 ++RegionBegin; 837 BB->splice(++OrigPrevMI, BB, DbgValue); 838 if (OrigPrevMI == std::prev(RegionEnd)) 839 RegionEnd = DbgValue; 840 } 841 DbgValues.clear(); 842 FirstDbgValue = nullptr; 843 } 844 845 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 846 void ScheduleDAGMI::dumpSchedule() const { 847 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) { 848 if (SUnit *SU = getSUnit(&(*MI))) 849 SU->dump(this); 850 else 851 dbgs() << "Missing SUnit\n"; 852 } 853 } 854 #endif 855 856 //===----------------------------------------------------------------------===// 857 // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals 858 // preservation. 859 //===----------------------------------------------------------------------===// 860 861 ScheduleDAGMILive::~ScheduleDAGMILive() { 862 delete DFSResult; 863 } 864 865 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after 866 /// crossing a scheduling boundary. [begin, end) includes all instructions in 867 /// the region, including the boundary itself and single-instruction regions 868 /// that don't get scheduled. 869 void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb, 870 MachineBasicBlock::iterator begin, 871 MachineBasicBlock::iterator end, 872 unsigned regioninstrs) 873 { 874 // ScheduleDAGMI initializes SchedImpl's per-region policy. 875 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs); 876 877 // For convenience remember the end of the liveness region. 878 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd); 879 880 SUPressureDiffs.clear(); 881 882 ShouldTrackPressure = SchedImpl->shouldTrackPressure(); 883 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks(); 884 885 if (ShouldTrackLaneMasks) { 886 if (!ShouldTrackPressure) 887 report_fatal_error("ShouldTrackLaneMasks requires ShouldTrackPressure"); 888 // Dead subregister defs have no users and therefore no dependencies, 889 // moving them around may cause liveintervals to degrade into multiple 890 // components. Change independent components to have their own vreg to avoid 891 // this. 892 if (!DisconnectedComponentsRenamed) 893 LIS->renameDisconnectedComponents(); 894 } 895 } 896 897 // Setup the register pressure trackers for the top scheduled top and bottom 898 // scheduled regions. 899 void ScheduleDAGMILive::initRegPressure() { 900 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin, 901 ShouldTrackLaneMasks, false); 902 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd, 903 ShouldTrackLaneMasks, false); 904 905 // Close the RPTracker to finalize live ins. 906 RPTracker.closeRegion(); 907 908 DEBUG(RPTracker.dump()); 909 910 // Initialize the live ins and live outs. 911 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs); 912 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs); 913 914 // Close one end of the tracker so we can call 915 // getMaxUpward/DownwardPressureDelta before advancing across any 916 // instructions. This converts currently live regs into live ins/outs. 917 TopRPTracker.closeTop(); 918 BotRPTracker.closeBottom(); 919 920 BotRPTracker.initLiveThru(RPTracker); 921 if (!BotRPTracker.getLiveThru().empty()) { 922 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru()); 923 DEBUG(dbgs() << "Live Thru: "; 924 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI)); 925 }; 926 927 // For each live out vreg reduce the pressure change associated with other 928 // uses of the same vreg below the live-out reaching def. 929 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs); 930 931 // Account for liveness generated by the region boundary. 932 if (LiveRegionEnd != RegionEnd) { 933 SmallVector<RegisterMaskPair, 8> LiveUses; 934 BotRPTracker.recede(&LiveUses); 935 updatePressureDiffs(LiveUses); 936 } 937 938 DEBUG( 939 dbgs() << "Top Pressure:\n"; 940 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI); 941 dbgs() << "Bottom Pressure:\n"; 942 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI); 943 ); 944 945 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom"); 946 947 // Cache the list of excess pressure sets in this region. This will also track 948 // the max pressure in the scheduled code for these sets. 949 RegionCriticalPSets.clear(); 950 const std::vector<unsigned> &RegionPressure = 951 RPTracker.getPressure().MaxSetPressure; 952 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) { 953 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i); 954 if (RegionPressure[i] > Limit) { 955 DEBUG(dbgs() << TRI->getRegPressureSetName(i) 956 << " Limit " << Limit 957 << " Actual " << RegionPressure[i] << "\n"); 958 RegionCriticalPSets.push_back(PressureChange(i)); 959 } 960 } 961 DEBUG(dbgs() << "Excess PSets: "; 962 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i) 963 dbgs() << TRI->getRegPressureSetName( 964 RegionCriticalPSets[i].getPSet()) << " "; 965 dbgs() << "\n"); 966 } 967 968 void ScheduleDAGMILive:: 969 updateScheduledPressure(const SUnit *SU, 970 const std::vector<unsigned> &NewMaxPressure) { 971 const PressureDiff &PDiff = getPressureDiff(SU); 972 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size(); 973 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end(); 974 I != E; ++I) { 975 if (!I->isValid()) 976 break; 977 unsigned ID = I->getPSet(); 978 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID) 979 ++CritIdx; 980 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) { 981 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc() 982 && NewMaxPressure[ID] <= INT16_MAX) 983 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]); 984 } 985 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID); 986 if (NewMaxPressure[ID] >= Limit - 2) { 987 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": " 988 << NewMaxPressure[ID] 989 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit 990 << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n"); 991 } 992 } 993 } 994 995 /// Update the PressureDiff array for liveness after scheduling this 996 /// instruction. 997 void ScheduleDAGMILive::updatePressureDiffs( 998 ArrayRef<RegisterMaskPair> LiveUses) { 999 for (const RegisterMaskPair &P : LiveUses) { 1000 unsigned Reg = P.RegUnit; 1001 /// FIXME: Currently assuming single-use physregs. 1002 if (!TRI->isVirtualRegister(Reg)) 1003 continue; 1004 1005 if (ShouldTrackLaneMasks) { 1006 // If the register has just become live then other uses won't change 1007 // this fact anymore => decrement pressure. 1008 // If the register has just become dead then other uses make it come 1009 // back to life => increment pressure. 1010 bool Decrement = P.LaneMask != 0; 1011 1012 for (const VReg2SUnit &V2SU 1013 : make_range(VRegUses.find(Reg), VRegUses.end())) { 1014 SUnit &SU = *V2SU.SU; 1015 if (SU.isScheduled || &SU == &ExitSU) 1016 continue; 1017 1018 PressureDiff &PDiff = getPressureDiff(&SU); 1019 PDiff.addPressureChange(Reg, Decrement, &MRI); 1020 DEBUG( 1021 dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") " 1022 << PrintReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask) 1023 << ' ' << *SU.getInstr(); 1024 dbgs() << " to "; 1025 PDiff.dump(*TRI); 1026 ); 1027 } 1028 } else { 1029 assert(P.LaneMask != 0); 1030 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n"); 1031 // This may be called before CurrentBottom has been initialized. However, 1032 // BotRPTracker must have a valid position. We want the value live into the 1033 // instruction or live out of the block, so ask for the previous 1034 // instruction's live-out. 1035 const LiveInterval &LI = LIS->getInterval(Reg); 1036 VNInfo *VNI; 1037 MachineBasicBlock::const_iterator I = 1038 nextIfDebug(BotRPTracker.getPos(), BB->end()); 1039 if (I == BB->end()) 1040 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB)); 1041 else { 1042 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I)); 1043 VNI = LRQ.valueIn(); 1044 } 1045 // RegisterPressureTracker guarantees that readsReg is true for LiveUses. 1046 assert(VNI && "No live value at use."); 1047 for (const VReg2SUnit &V2SU 1048 : make_range(VRegUses.find(Reg), VRegUses.end())) { 1049 SUnit *SU = V2SU.SU; 1050 // If this use comes before the reaching def, it cannot be a last use, 1051 // so decrease its pressure change. 1052 if (!SU->isScheduled && SU != &ExitSU) { 1053 LiveQueryResult LRQ = 1054 LI.Query(LIS->getInstructionIndex(*SU->getInstr())); 1055 if (LRQ.valueIn() == VNI) { 1056 PressureDiff &PDiff = getPressureDiff(SU); 1057 PDiff.addPressureChange(Reg, true, &MRI); 1058 DEBUG( 1059 dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") " 1060 << *SU->getInstr(); 1061 dbgs() << " to "; 1062 PDiff.dump(*TRI); 1063 ); 1064 } 1065 } 1066 } 1067 } 1068 } 1069 } 1070 1071 /// schedule - Called back from MachineScheduler::runOnMachineFunction 1072 /// after setting up the current scheduling region. [RegionBegin, RegionEnd) 1073 /// only includes instructions that have DAG nodes, not scheduling boundaries. 1074 /// 1075 /// This is a skeletal driver, with all the functionality pushed into helpers, 1076 /// so that it can be easily extended by experimental schedulers. Generally, 1077 /// implementing MachineSchedStrategy should be sufficient to implement a new 1078 /// scheduling algorithm. However, if a scheduler further subclasses 1079 /// ScheduleDAGMILive then it will want to override this virtual method in order 1080 /// to update any specialized state. 1081 void ScheduleDAGMILive::schedule() { 1082 DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n"); 1083 DEBUG(SchedImpl->dumpPolicy()); 1084 buildDAGWithRegPressure(); 1085 1086 Topo.InitDAGTopologicalSorting(); 1087 1088 postprocessDAG(); 1089 1090 SmallVector<SUnit*, 8> TopRoots, BotRoots; 1091 findRootsAndBiasEdges(TopRoots, BotRoots); 1092 1093 // Initialize the strategy before modifying the DAG. 1094 // This may initialize a DFSResult to be used for queue priority. 1095 SchedImpl->initialize(this); 1096 1097 DEBUG( 1098 for (const SUnit &SU : SUnits) { 1099 SU.dumpAll(this); 1100 if (ShouldTrackPressure) { 1101 dbgs() << " Pressure Diff : "; 1102 getPressureDiff(&SU).dump(*TRI); 1103 } 1104 dbgs() << '\n'; 1105 } 1106 ); 1107 if (ViewMISchedDAGs) viewGraph(); 1108 1109 // Initialize ready queues now that the DAG and priority data are finalized. 1110 initQueues(TopRoots, BotRoots); 1111 1112 bool IsTopNode = false; 1113 while (true) { 1114 DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n"); 1115 SUnit *SU = SchedImpl->pickNode(IsTopNode); 1116 if (!SU) break; 1117 1118 assert(!SU->isScheduled && "Node already scheduled"); 1119 if (!checkSchedLimit()) 1120 break; 1121 1122 scheduleMI(SU, IsTopNode); 1123 1124 if (DFSResult) { 1125 unsigned SubtreeID = DFSResult->getSubtreeID(SU); 1126 if (!ScheduledTrees.test(SubtreeID)) { 1127 ScheduledTrees.set(SubtreeID); 1128 DFSResult->scheduleTree(SubtreeID); 1129 SchedImpl->scheduleTree(SubtreeID); 1130 } 1131 } 1132 1133 // Notify the scheduling strategy after updating the DAG. 1134 SchedImpl->schedNode(SU, IsTopNode); 1135 1136 updateQueues(SU, IsTopNode); 1137 } 1138 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone."); 1139 1140 placeDebugValues(); 1141 1142 DEBUG({ 1143 unsigned BBNum = begin()->getParent()->getNumber(); 1144 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n"; 1145 dumpSchedule(); 1146 dbgs() << '\n'; 1147 }); 1148 } 1149 1150 /// Build the DAG and setup three register pressure trackers. 1151 void ScheduleDAGMILive::buildDAGWithRegPressure() { 1152 if (!ShouldTrackPressure) { 1153 RPTracker.reset(); 1154 RegionCriticalPSets.clear(); 1155 buildSchedGraph(AA); 1156 return; 1157 } 1158 1159 // Initialize the register pressure tracker used by buildSchedGraph. 1160 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd, 1161 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true); 1162 1163 // Account for liveness generate by the region boundary. 1164 if (LiveRegionEnd != RegionEnd) 1165 RPTracker.recede(); 1166 1167 // Build the DAG, and compute current register pressure. 1168 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks); 1169 1170 // Initialize top/bottom trackers after computing region pressure. 1171 initRegPressure(); 1172 } 1173 1174 void ScheduleDAGMILive::computeDFSResult() { 1175 if (!DFSResult) 1176 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize); 1177 DFSResult->clear(); 1178 ScheduledTrees.clear(); 1179 DFSResult->resize(SUnits.size()); 1180 DFSResult->compute(SUnits); 1181 ScheduledTrees.resize(DFSResult->getNumSubtrees()); 1182 } 1183 1184 /// Compute the max cyclic critical path through the DAG. The scheduling DAG 1185 /// only provides the critical path for single block loops. To handle loops that 1186 /// span blocks, we could use the vreg path latencies provided by 1187 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently 1188 /// available for use in the scheduler. 1189 /// 1190 /// The cyclic path estimation identifies a def-use pair that crosses the back 1191 /// edge and considers the depth and height of the nodes. For example, consider 1192 /// the following instruction sequence where each instruction has unit latency 1193 /// and defines an epomymous virtual register: 1194 /// 1195 /// a->b(a,c)->c(b)->d(c)->exit 1196 /// 1197 /// The cyclic critical path is a two cycles: b->c->b 1198 /// The acyclic critical path is four cycles: a->b->c->d->exit 1199 /// LiveOutHeight = height(c) = len(c->d->exit) = 2 1200 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3 1201 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4 1202 /// LiveInDepth = depth(b) = len(a->b) = 1 1203 /// 1204 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2 1205 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2 1206 /// CyclicCriticalPath = min(2, 2) = 2 1207 /// 1208 /// This could be relevant to PostRA scheduling, but is currently implemented 1209 /// assuming LiveIntervals. 1210 unsigned ScheduleDAGMILive::computeCyclicCriticalPath() { 1211 // This only applies to single block loop. 1212 if (!BB->isSuccessor(BB)) 1213 return 0; 1214 1215 unsigned MaxCyclicLatency = 0; 1216 // Visit each live out vreg def to find def/use pairs that cross iterations. 1217 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) { 1218 unsigned Reg = P.RegUnit; 1219 if (!TRI->isVirtualRegister(Reg)) 1220 continue; 1221 const LiveInterval &LI = LIS->getInterval(Reg); 1222 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB)); 1223 if (!DefVNI) 1224 continue; 1225 1226 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def); 1227 const SUnit *DefSU = getSUnit(DefMI); 1228 if (!DefSU) 1229 continue; 1230 1231 unsigned LiveOutHeight = DefSU->getHeight(); 1232 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency; 1233 // Visit all local users of the vreg def. 1234 for (const VReg2SUnit &V2SU 1235 : make_range(VRegUses.find(Reg), VRegUses.end())) { 1236 SUnit *SU = V2SU.SU; 1237 if (SU == &ExitSU) 1238 continue; 1239 1240 // Only consider uses of the phi. 1241 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr())); 1242 if (!LRQ.valueIn()->isPHIDef()) 1243 continue; 1244 1245 // Assume that a path spanning two iterations is a cycle, which could 1246 // overestimate in strange cases. This allows cyclic latency to be 1247 // estimated as the minimum slack of the vreg's depth or height. 1248 unsigned CyclicLatency = 0; 1249 if (LiveOutDepth > SU->getDepth()) 1250 CyclicLatency = LiveOutDepth - SU->getDepth(); 1251 1252 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency; 1253 if (LiveInHeight > LiveOutHeight) { 1254 if (LiveInHeight - LiveOutHeight < CyclicLatency) 1255 CyclicLatency = LiveInHeight - LiveOutHeight; 1256 } else 1257 CyclicLatency = 0; 1258 1259 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU(" 1260 << SU->NodeNum << ") = " << CyclicLatency << "c\n"); 1261 if (CyclicLatency > MaxCyclicLatency) 1262 MaxCyclicLatency = CyclicLatency; 1263 } 1264 } 1265 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n"); 1266 return MaxCyclicLatency; 1267 } 1268 1269 /// Release ExitSU predecessors and setup scheduler queues. Re-position 1270 /// the Top RP tracker in case the region beginning has changed. 1271 void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots, 1272 ArrayRef<SUnit*> BotRoots) { 1273 ScheduleDAGMI::initQueues(TopRoots, BotRoots); 1274 if (ShouldTrackPressure) { 1275 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker"); 1276 TopRPTracker.setPos(CurrentTop); 1277 } 1278 } 1279 1280 /// Move an instruction and update register pressure. 1281 void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) { 1282 // Move the instruction to its new location in the instruction stream. 1283 MachineInstr *MI = SU->getInstr(); 1284 1285 if (IsTopNode) { 1286 assert(SU->isTopReady() && "node still has unscheduled dependencies"); 1287 if (&*CurrentTop == MI) 1288 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom); 1289 else { 1290 moveInstruction(MI, CurrentTop); 1291 TopRPTracker.setPos(MI); 1292 } 1293 1294 if (ShouldTrackPressure) { 1295 // Update top scheduled pressure. 1296 RegisterOperands RegOpers; 1297 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false); 1298 if (ShouldTrackLaneMasks) { 1299 // Adjust liveness and add missing dead+read-undef flags. 1300 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot(); 1301 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI); 1302 } else { 1303 // Adjust for missing dead-def flags. 1304 RegOpers.detectDeadDefs(*MI, *LIS); 1305 } 1306 1307 TopRPTracker.advance(RegOpers); 1308 assert(TopRPTracker.getPos() == CurrentTop && "out of sync"); 1309 DEBUG( 1310 dbgs() << "Top Pressure:\n"; 1311 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI); 1312 ); 1313 1314 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure); 1315 } 1316 } else { 1317 assert(SU->isBottomReady() && "node still has unscheduled dependencies"); 1318 MachineBasicBlock::iterator priorII = 1319 priorNonDebug(CurrentBottom, CurrentTop); 1320 if (&*priorII == MI) 1321 CurrentBottom = priorII; 1322 else { 1323 if (&*CurrentTop == MI) { 1324 CurrentTop = nextIfDebug(++CurrentTop, priorII); 1325 TopRPTracker.setPos(CurrentTop); 1326 } 1327 moveInstruction(MI, CurrentBottom); 1328 CurrentBottom = MI; 1329 } 1330 if (ShouldTrackPressure) { 1331 RegisterOperands RegOpers; 1332 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false); 1333 if (ShouldTrackLaneMasks) { 1334 // Adjust liveness and add missing dead+read-undef flags. 1335 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot(); 1336 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI); 1337 } else { 1338 // Adjust for missing dead-def flags. 1339 RegOpers.detectDeadDefs(*MI, *LIS); 1340 } 1341 1342 BotRPTracker.recedeSkipDebugValues(); 1343 SmallVector<RegisterMaskPair, 8> LiveUses; 1344 BotRPTracker.recede(RegOpers, &LiveUses); 1345 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync"); 1346 DEBUG( 1347 dbgs() << "Bottom Pressure:\n"; 1348 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI); 1349 ); 1350 1351 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure); 1352 updatePressureDiffs(LiveUses); 1353 } 1354 } 1355 } 1356 1357 //===----------------------------------------------------------------------===// 1358 // BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores. 1359 //===----------------------------------------------------------------------===// 1360 1361 namespace { 1362 /// \brief Post-process the DAG to create cluster edges between neighboring 1363 /// loads or between neighboring stores. 1364 class BaseMemOpClusterMutation : public ScheduleDAGMutation { 1365 struct MemOpInfo { 1366 SUnit *SU; 1367 unsigned BaseReg; 1368 int64_t Offset; 1369 MemOpInfo(SUnit *su, unsigned reg, int64_t ofs) 1370 : SU(su), BaseReg(reg), Offset(ofs) {} 1371 1372 bool operator<(const MemOpInfo&RHS) const { 1373 return std::tie(BaseReg, Offset) < std::tie(RHS.BaseReg, RHS.Offset); 1374 } 1375 }; 1376 1377 const TargetInstrInfo *TII; 1378 const TargetRegisterInfo *TRI; 1379 bool IsLoad; 1380 1381 public: 1382 BaseMemOpClusterMutation(const TargetInstrInfo *tii, 1383 const TargetRegisterInfo *tri, bool IsLoad) 1384 : TII(tii), TRI(tri), IsLoad(IsLoad) {} 1385 1386 void apply(ScheduleDAGInstrs *DAGInstrs) override; 1387 1388 protected: 1389 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG); 1390 }; 1391 1392 class StoreClusterMutation : public BaseMemOpClusterMutation { 1393 public: 1394 StoreClusterMutation(const TargetInstrInfo *tii, 1395 const TargetRegisterInfo *tri) 1396 : BaseMemOpClusterMutation(tii, tri, false) {} 1397 }; 1398 1399 class LoadClusterMutation : public BaseMemOpClusterMutation { 1400 public: 1401 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri) 1402 : BaseMemOpClusterMutation(tii, tri, true) {} 1403 }; 1404 } // anonymous 1405 1406 void BaseMemOpClusterMutation::clusterNeighboringMemOps( 1407 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) { 1408 SmallVector<MemOpInfo, 32> MemOpRecords; 1409 for (unsigned Idx = 0, End = MemOps.size(); Idx != End; ++Idx) { 1410 SUnit *SU = MemOps[Idx]; 1411 unsigned BaseReg; 1412 int64_t Offset; 1413 if (TII->getMemOpBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI)) 1414 MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset)); 1415 } 1416 if (MemOpRecords.size() < 2) 1417 return; 1418 1419 std::sort(MemOpRecords.begin(), MemOpRecords.end()); 1420 unsigned ClusterLength = 1; 1421 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) { 1422 if (MemOpRecords[Idx].BaseReg != MemOpRecords[Idx+1].BaseReg) { 1423 ClusterLength = 1; 1424 continue; 1425 } 1426 1427 SUnit *SUa = MemOpRecords[Idx].SU; 1428 SUnit *SUb = MemOpRecords[Idx+1].SU; 1429 if (TII->shouldClusterMemOps(SUa->getInstr(), SUb->getInstr(), ClusterLength) 1430 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) { 1431 DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU(" 1432 << SUb->NodeNum << ")\n"); 1433 // Copy successor edges from SUa to SUb. Interleaving computation 1434 // dependent on SUa can prevent load combining due to register reuse. 1435 // Predecessor edges do not need to be copied from SUb to SUa since nearby 1436 // loads should have effectively the same inputs. 1437 for (SUnit::const_succ_iterator 1438 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) { 1439 if (SI->getSUnit() == SUb) 1440 continue; 1441 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n"); 1442 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial)); 1443 } 1444 ++ClusterLength; 1445 } else 1446 ClusterLength = 1; 1447 } 1448 } 1449 1450 /// \brief Callback from DAG postProcessing to create cluster edges for loads. 1451 void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) { 1452 1453 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs); 1454 1455 // Map DAG NodeNum to store chain ID. 1456 DenseMap<unsigned, unsigned> StoreChainIDs; 1457 // Map each store chain to a set of dependent MemOps. 1458 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents; 1459 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) { 1460 SUnit *SU = &DAG->SUnits[Idx]; 1461 if ((IsLoad && !SU->getInstr()->mayLoad()) || 1462 (!IsLoad && !SU->getInstr()->mayStore())) 1463 continue; 1464 1465 unsigned ChainPredID = DAG->SUnits.size(); 1466 for (SUnit::const_pred_iterator 1467 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) { 1468 if (PI->isCtrl()) { 1469 ChainPredID = PI->getSUnit()->NodeNum; 1470 break; 1471 } 1472 } 1473 // Check if this chain-like pred has been seen 1474 // before. ChainPredID==MaxNodeID at the top of the schedule. 1475 unsigned NumChains = StoreChainDependents.size(); 1476 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result = 1477 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains)); 1478 if (Result.second) 1479 StoreChainDependents.resize(NumChains + 1); 1480 StoreChainDependents[Result.first->second].push_back(SU); 1481 } 1482 1483 // Iterate over the store chains. 1484 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx) 1485 clusterNeighboringMemOps(StoreChainDependents[Idx], DAG); 1486 } 1487 1488 //===----------------------------------------------------------------------===// 1489 // MacroFusion - DAG post-processing to encourage fusion of macro ops. 1490 //===----------------------------------------------------------------------===// 1491 1492 namespace { 1493 /// \brief Post-process the DAG to create cluster edges between instructions 1494 /// that may be fused by the processor into a single operation. 1495 class MacroFusion : public ScheduleDAGMutation { 1496 const TargetInstrInfo &TII; 1497 const TargetRegisterInfo &TRI; 1498 public: 1499 MacroFusion(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) 1500 : TII(TII), TRI(TRI) {} 1501 1502 void apply(ScheduleDAGInstrs *DAGInstrs) override; 1503 }; 1504 } // anonymous 1505 1506 /// Returns true if \p MI reads a register written by \p Other. 1507 static bool HasDataDep(const TargetRegisterInfo &TRI, const MachineInstr &MI, 1508 const MachineInstr &Other) { 1509 for (const MachineOperand &MO : MI.uses()) { 1510 if (!MO.isReg() || !MO.readsReg()) 1511 continue; 1512 1513 unsigned Reg = MO.getReg(); 1514 if (Other.modifiesRegister(Reg, &TRI)) 1515 return true; 1516 } 1517 return false; 1518 } 1519 1520 /// \brief Callback from DAG postProcessing to create cluster edges to encourage 1521 /// fused operations. 1522 void MacroFusion::apply(ScheduleDAGInstrs *DAGInstrs) { 1523 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs); 1524 1525 // For now, assume targets can only fuse with the branch. 1526 SUnit &ExitSU = DAG->ExitSU; 1527 MachineInstr *Branch = ExitSU.getInstr(); 1528 if (!Branch) 1529 return; 1530 1531 for (SUnit &SU : DAG->SUnits) { 1532 // SUnits with successors can't be schedule in front of the ExitSU. 1533 if (!SU.Succs.empty()) 1534 continue; 1535 // We only care if the node writes to a register that the branch reads. 1536 MachineInstr *Pred = SU.getInstr(); 1537 if (!HasDataDep(TRI, *Branch, *Pred)) 1538 continue; 1539 1540 if (!TII.shouldScheduleAdjacent(Pred, Branch)) 1541 continue; 1542 1543 // Create a single weak edge from SU to ExitSU. The only effect is to cause 1544 // bottom-up scheduling to heavily prioritize the clustered SU. There is no 1545 // need to copy predecessor edges from ExitSU to SU, since top-down 1546 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling 1547 // of SU, we could create an artificial edge from the deepest root, but it 1548 // hasn't been needed yet. 1549 bool Success = DAG->addEdge(&ExitSU, SDep(&SU, SDep::Cluster)); 1550 (void)Success; 1551 assert(Success && "No DAG nodes should be reachable from ExitSU"); 1552 1553 DEBUG(dbgs() << "Macro Fuse SU(" << SU.NodeNum << ")\n"); 1554 break; 1555 } 1556 } 1557 1558 //===----------------------------------------------------------------------===// 1559 // CopyConstrain - DAG post-processing to encourage copy elimination. 1560 //===----------------------------------------------------------------------===// 1561 1562 namespace { 1563 /// \brief Post-process the DAG to create weak edges from all uses of a copy to 1564 /// the one use that defines the copy's source vreg, most likely an induction 1565 /// variable increment. 1566 class CopyConstrain : public ScheduleDAGMutation { 1567 // Transient state. 1568 SlotIndex RegionBeginIdx; 1569 // RegionEndIdx is the slot index of the last non-debug instruction in the 1570 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx. 1571 SlotIndex RegionEndIdx; 1572 public: 1573 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {} 1574 1575 void apply(ScheduleDAGInstrs *DAGInstrs) override; 1576 1577 protected: 1578 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG); 1579 }; 1580 } // anonymous 1581 1582 /// constrainLocalCopy handles two possibilities: 1583 /// 1) Local src: 1584 /// I0: = dst 1585 /// I1: src = ... 1586 /// I2: = dst 1587 /// I3: dst = src (copy) 1588 /// (create pred->succ edges I0->I1, I2->I1) 1589 /// 1590 /// 2) Local copy: 1591 /// I0: dst = src (copy) 1592 /// I1: = dst 1593 /// I2: src = ... 1594 /// I3: = dst 1595 /// (create pred->succ edges I1->I2, I3->I2) 1596 /// 1597 /// Although the MachineScheduler is currently constrained to single blocks, 1598 /// this algorithm should handle extended blocks. An EBB is a set of 1599 /// contiguously numbered blocks such that the previous block in the EBB is 1600 /// always the single predecessor. 1601 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) { 1602 LiveIntervals *LIS = DAG->getLIS(); 1603 MachineInstr *Copy = CopySU->getInstr(); 1604 1605 // Check for pure vreg copies. 1606 const MachineOperand &SrcOp = Copy->getOperand(1); 1607 unsigned SrcReg = SrcOp.getReg(); 1608 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg()) 1609 return; 1610 1611 const MachineOperand &DstOp = Copy->getOperand(0); 1612 unsigned DstReg = DstOp.getReg(); 1613 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead()) 1614 return; 1615 1616 // Check if either the dest or source is local. If it's live across a back 1617 // edge, it's not local. Note that if both vregs are live across the back 1618 // edge, we cannot successfully contrain the copy without cyclic scheduling. 1619 // If both the copy's source and dest are local live intervals, then we 1620 // should treat the dest as the global for the purpose of adding 1621 // constraints. This adds edges from source's other uses to the copy. 1622 unsigned LocalReg = SrcReg; 1623 unsigned GlobalReg = DstReg; 1624 LiveInterval *LocalLI = &LIS->getInterval(LocalReg); 1625 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) { 1626 LocalReg = DstReg; 1627 GlobalReg = SrcReg; 1628 LocalLI = &LIS->getInterval(LocalReg); 1629 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) 1630 return; 1631 } 1632 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg); 1633 1634 // Find the global segment after the start of the local LI. 1635 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex()); 1636 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a 1637 // local live range. We could create edges from other global uses to the local 1638 // start, but the coalescer should have already eliminated these cases, so 1639 // don't bother dealing with it. 1640 if (GlobalSegment == GlobalLI->end()) 1641 return; 1642 1643 // If GlobalSegment is killed at the LocalLI->start, the call to find() 1644 // returned the next global segment. But if GlobalSegment overlaps with 1645 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI 1646 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole. 1647 if (GlobalSegment->contains(LocalLI->beginIndex())) 1648 ++GlobalSegment; 1649 1650 if (GlobalSegment == GlobalLI->end()) 1651 return; 1652 1653 // Check if GlobalLI contains a hole in the vicinity of LocalLI. 1654 if (GlobalSegment != GlobalLI->begin()) { 1655 // Two address defs have no hole. 1656 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end, 1657 GlobalSegment->start)) { 1658 return; 1659 } 1660 // If the prior global segment may be defined by the same two-address 1661 // instruction that also defines LocalLI, then can't make a hole here. 1662 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start, 1663 LocalLI->beginIndex())) { 1664 return; 1665 } 1666 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise 1667 // it would be a disconnected component in the live range. 1668 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() && 1669 "Disconnected LRG within the scheduling region."); 1670 } 1671 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start); 1672 if (!GlobalDef) 1673 return; 1674 1675 SUnit *GlobalSU = DAG->getSUnit(GlobalDef); 1676 if (!GlobalSU) 1677 return; 1678 1679 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by 1680 // constraining the uses of the last local def to precede GlobalDef. 1681 SmallVector<SUnit*,8> LocalUses; 1682 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex()); 1683 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def); 1684 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef); 1685 for (SUnit::const_succ_iterator 1686 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end(); 1687 I != E; ++I) { 1688 if (I->getKind() != SDep::Data || I->getReg() != LocalReg) 1689 continue; 1690 if (I->getSUnit() == GlobalSU) 1691 continue; 1692 if (!DAG->canAddEdge(GlobalSU, I->getSUnit())) 1693 return; 1694 LocalUses.push_back(I->getSUnit()); 1695 } 1696 // Open the top of the GlobalLI hole by constraining any earlier global uses 1697 // to precede the start of LocalLI. 1698 SmallVector<SUnit*,8> GlobalUses; 1699 MachineInstr *FirstLocalDef = 1700 LIS->getInstructionFromIndex(LocalLI->beginIndex()); 1701 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef); 1702 for (SUnit::const_pred_iterator 1703 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) { 1704 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg) 1705 continue; 1706 if (I->getSUnit() == FirstLocalSU) 1707 continue; 1708 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit())) 1709 return; 1710 GlobalUses.push_back(I->getSUnit()); 1711 } 1712 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n"); 1713 // Add the weak edges. 1714 for (SmallVectorImpl<SUnit*>::const_iterator 1715 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) { 1716 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU(" 1717 << GlobalSU->NodeNum << ")\n"); 1718 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak)); 1719 } 1720 for (SmallVectorImpl<SUnit*>::const_iterator 1721 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) { 1722 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU(" 1723 << FirstLocalSU->NodeNum << ")\n"); 1724 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak)); 1725 } 1726 } 1727 1728 /// \brief Callback from DAG postProcessing to create weak edges to encourage 1729 /// copy elimination. 1730 void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) { 1731 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs); 1732 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals"); 1733 1734 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end()); 1735 if (FirstPos == DAG->end()) 1736 return; 1737 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos); 1738 RegionEndIdx = DAG->getLIS()->getInstructionIndex( 1739 *priorNonDebug(DAG->end(), DAG->begin())); 1740 1741 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) { 1742 SUnit *SU = &DAG->SUnits[Idx]; 1743 if (!SU->getInstr()->isCopy()) 1744 continue; 1745 1746 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG)); 1747 } 1748 } 1749 1750 //===----------------------------------------------------------------------===// 1751 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler 1752 // and possibly other custom schedulers. 1753 //===----------------------------------------------------------------------===// 1754 1755 static const unsigned InvalidCycle = ~0U; 1756 1757 SchedBoundary::~SchedBoundary() { delete HazardRec; } 1758 1759 void SchedBoundary::reset() { 1760 // A new HazardRec is created for each DAG and owned by SchedBoundary. 1761 // Destroying and reconstructing it is very expensive though. So keep 1762 // invalid, placeholder HazardRecs. 1763 if (HazardRec && HazardRec->isEnabled()) { 1764 delete HazardRec; 1765 HazardRec = nullptr; 1766 } 1767 Available.clear(); 1768 Pending.clear(); 1769 CheckPending = false; 1770 NextSUs.clear(); 1771 CurrCycle = 0; 1772 CurrMOps = 0; 1773 MinReadyCycle = UINT_MAX; 1774 ExpectedLatency = 0; 1775 DependentLatency = 0; 1776 RetiredMOps = 0; 1777 MaxExecutedResCount = 0; 1778 ZoneCritResIdx = 0; 1779 IsResourceLimited = false; 1780 ReservedCycles.clear(); 1781 #ifndef NDEBUG 1782 // Track the maximum number of stall cycles that could arise either from the 1783 // latency of a DAG edge or the number of cycles that a processor resource is 1784 // reserved (SchedBoundary::ReservedCycles). 1785 MaxObservedStall = 0; 1786 #endif 1787 // Reserve a zero-count for invalid CritResIdx. 1788 ExecutedResCounts.resize(1); 1789 assert(!ExecutedResCounts[0] && "nonzero count for bad resource"); 1790 } 1791 1792 void SchedRemainder:: 1793 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) { 1794 reset(); 1795 if (!SchedModel->hasInstrSchedModel()) 1796 return; 1797 RemainingCounts.resize(SchedModel->getNumProcResourceKinds()); 1798 for (std::vector<SUnit>::iterator 1799 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) { 1800 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I); 1801 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC) 1802 * SchedModel->getMicroOpFactor(); 1803 for (TargetSchedModel::ProcResIter 1804 PI = SchedModel->getWriteProcResBegin(SC), 1805 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 1806 unsigned PIdx = PI->ProcResourceIdx; 1807 unsigned Factor = SchedModel->getResourceFactor(PIdx); 1808 RemainingCounts[PIdx] += (Factor * PI->Cycles); 1809 } 1810 } 1811 } 1812 1813 void SchedBoundary:: 1814 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) { 1815 reset(); 1816 DAG = dag; 1817 SchedModel = smodel; 1818 Rem = rem; 1819 if (SchedModel->hasInstrSchedModel()) { 1820 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds()); 1821 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle); 1822 } 1823 } 1824 1825 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat 1826 /// these "soft stalls" differently than the hard stall cycles based on CPU 1827 /// resources and computed by checkHazard(). A fully in-order model 1828 /// (MicroOpBufferSize==0) will not make use of this since instructions are not 1829 /// available for scheduling until they are ready. However, a weaker in-order 1830 /// model may use this for heuristics. For example, if a processor has in-order 1831 /// behavior when reading certain resources, this may come into play. 1832 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) { 1833 if (!SU->isUnbuffered) 1834 return 0; 1835 1836 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle); 1837 if (ReadyCycle > CurrCycle) 1838 return ReadyCycle - CurrCycle; 1839 return 0; 1840 } 1841 1842 /// Compute the next cycle at which the given processor resource can be 1843 /// scheduled. 1844 unsigned SchedBoundary:: 1845 getNextResourceCycle(unsigned PIdx, unsigned Cycles) { 1846 unsigned NextUnreserved = ReservedCycles[PIdx]; 1847 // If this resource has never been used, always return cycle zero. 1848 if (NextUnreserved == InvalidCycle) 1849 return 0; 1850 // For bottom-up scheduling add the cycles needed for the current operation. 1851 if (!isTop()) 1852 NextUnreserved += Cycles; 1853 return NextUnreserved; 1854 } 1855 1856 /// Does this SU have a hazard within the current instruction group. 1857 /// 1858 /// The scheduler supports two modes of hazard recognition. The first is the 1859 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that 1860 /// supports highly complicated in-order reservation tables 1861 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic. 1862 /// 1863 /// The second is a streamlined mechanism that checks for hazards based on 1864 /// simple counters that the scheduler itself maintains. It explicitly checks 1865 /// for instruction dispatch limitations, including the number of micro-ops that 1866 /// can dispatch per cycle. 1867 /// 1868 /// TODO: Also check whether the SU must start a new group. 1869 bool SchedBoundary::checkHazard(SUnit *SU) { 1870 if (HazardRec->isEnabled() 1871 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) { 1872 return true; 1873 } 1874 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr()); 1875 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) { 1876 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops=" 1877 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n'); 1878 return true; 1879 } 1880 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) { 1881 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 1882 for (TargetSchedModel::ProcResIter 1883 PI = SchedModel->getWriteProcResBegin(SC), 1884 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 1885 unsigned NRCycle = getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles); 1886 if (NRCycle > CurrCycle) { 1887 #ifndef NDEBUG 1888 MaxObservedStall = std::max(PI->Cycles, MaxObservedStall); 1889 #endif 1890 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") " 1891 << SchedModel->getResourceName(PI->ProcResourceIdx) 1892 << "=" << NRCycle << "c\n"); 1893 return true; 1894 } 1895 } 1896 } 1897 return false; 1898 } 1899 1900 // Find the unscheduled node in ReadySUs with the highest latency. 1901 unsigned SchedBoundary:: 1902 findMaxLatency(ArrayRef<SUnit*> ReadySUs) { 1903 SUnit *LateSU = nullptr; 1904 unsigned RemLatency = 0; 1905 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end(); 1906 I != E; ++I) { 1907 unsigned L = getUnscheduledLatency(*I); 1908 if (L > RemLatency) { 1909 RemLatency = L; 1910 LateSU = *I; 1911 } 1912 } 1913 if (LateSU) { 1914 DEBUG(dbgs() << Available.getName() << " RemLatency SU(" 1915 << LateSU->NodeNum << ") " << RemLatency << "c\n"); 1916 } 1917 return RemLatency; 1918 } 1919 1920 // Count resources in this zone and the remaining unscheduled 1921 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical 1922 // resource index, or zero if the zone is issue limited. 1923 unsigned SchedBoundary:: 1924 getOtherResourceCount(unsigned &OtherCritIdx) { 1925 OtherCritIdx = 0; 1926 if (!SchedModel->hasInstrSchedModel()) 1927 return 0; 1928 1929 unsigned OtherCritCount = Rem->RemIssueCount 1930 + (RetiredMOps * SchedModel->getMicroOpFactor()); 1931 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: " 1932 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n'); 1933 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds(); 1934 PIdx != PEnd; ++PIdx) { 1935 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx]; 1936 if (OtherCount > OtherCritCount) { 1937 OtherCritCount = OtherCount; 1938 OtherCritIdx = PIdx; 1939 } 1940 } 1941 if (OtherCritIdx) { 1942 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: " 1943 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx) 1944 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n"); 1945 } 1946 return OtherCritCount; 1947 } 1948 1949 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) { 1950 assert(SU->getInstr() && "Scheduled SUnit must have instr"); 1951 1952 #ifndef NDEBUG 1953 // ReadyCycle was been bumped up to the CurrCycle when this node was 1954 // scheduled, but CurrCycle may have been eagerly advanced immediately after 1955 // scheduling, so may now be greater than ReadyCycle. 1956 if (ReadyCycle > CurrCycle) 1957 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall); 1958 #endif 1959 1960 if (ReadyCycle < MinReadyCycle) 1961 MinReadyCycle = ReadyCycle; 1962 1963 // Check for interlocks first. For the purpose of other heuristics, an 1964 // instruction that cannot issue appears as if it's not in the ReadyQueue. 1965 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0; 1966 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) || 1967 Available.size() >= ReadyListLimit) 1968 Pending.push(SU); 1969 else 1970 Available.push(SU); 1971 1972 // Record this node as an immediate dependent of the scheduled node. 1973 NextSUs.insert(SU); 1974 } 1975 1976 void SchedBoundary::releaseTopNode(SUnit *SU) { 1977 if (SU->isScheduled) 1978 return; 1979 1980 releaseNode(SU, SU->TopReadyCycle); 1981 } 1982 1983 void SchedBoundary::releaseBottomNode(SUnit *SU) { 1984 if (SU->isScheduled) 1985 return; 1986 1987 releaseNode(SU, SU->BotReadyCycle); 1988 } 1989 1990 /// Move the boundary of scheduled code by one cycle. 1991 void SchedBoundary::bumpCycle(unsigned NextCycle) { 1992 if (SchedModel->getMicroOpBufferSize() == 0) { 1993 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized"); 1994 if (MinReadyCycle > NextCycle) 1995 NextCycle = MinReadyCycle; 1996 } 1997 // Update the current micro-ops, which will issue in the next cycle. 1998 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle); 1999 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps; 2000 2001 // Decrement DependentLatency based on the next cycle. 2002 if ((NextCycle - CurrCycle) > DependentLatency) 2003 DependentLatency = 0; 2004 else 2005 DependentLatency -= (NextCycle - CurrCycle); 2006 2007 if (!HazardRec->isEnabled()) { 2008 // Bypass HazardRec virtual calls. 2009 CurrCycle = NextCycle; 2010 } else { 2011 // Bypass getHazardType calls in case of long latency. 2012 for (; CurrCycle != NextCycle; ++CurrCycle) { 2013 if (isTop()) 2014 HazardRec->AdvanceCycle(); 2015 else 2016 HazardRec->RecedeCycle(); 2017 } 2018 } 2019 CheckPending = true; 2020 unsigned LFactor = SchedModel->getLatencyFactor(); 2021 IsResourceLimited = 2022 (int)(getCriticalCount() - (getScheduledLatency() * LFactor)) 2023 > (int)LFactor; 2024 2025 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n'); 2026 } 2027 2028 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) { 2029 ExecutedResCounts[PIdx] += Count; 2030 if (ExecutedResCounts[PIdx] > MaxExecutedResCount) 2031 MaxExecutedResCount = ExecutedResCounts[PIdx]; 2032 } 2033 2034 /// Add the given processor resource to this scheduled zone. 2035 /// 2036 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles 2037 /// during which this resource is consumed. 2038 /// 2039 /// \return the next cycle at which the instruction may execute without 2040 /// oversubscribing resources. 2041 unsigned SchedBoundary:: 2042 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) { 2043 unsigned Factor = SchedModel->getResourceFactor(PIdx); 2044 unsigned Count = Factor * Cycles; 2045 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx) 2046 << " +" << Cycles << "x" << Factor << "u\n"); 2047 2048 // Update Executed resources counts. 2049 incExecutedResources(PIdx, Count); 2050 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted"); 2051 Rem->RemainingCounts[PIdx] -= Count; 2052 2053 // Check if this resource exceeds the current critical resource. If so, it 2054 // becomes the critical resource. 2055 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) { 2056 ZoneCritResIdx = PIdx; 2057 DEBUG(dbgs() << " *** Critical resource " 2058 << SchedModel->getResourceName(PIdx) << ": " 2059 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n"); 2060 } 2061 // For reserved resources, record the highest cycle using the resource. 2062 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles); 2063 if (NextAvailable > CurrCycle) { 2064 DEBUG(dbgs() << " Resource conflict: " 2065 << SchedModel->getProcResource(PIdx)->Name << " reserved until @" 2066 << NextAvailable << "\n"); 2067 } 2068 return NextAvailable; 2069 } 2070 2071 /// Move the boundary of scheduled code by one SUnit. 2072 void SchedBoundary::bumpNode(SUnit *SU) { 2073 // Update the reservation table. 2074 if (HazardRec->isEnabled()) { 2075 if (!isTop() && SU->isCall) { 2076 // Calls are scheduled with their preceding instructions. For bottom-up 2077 // scheduling, clear the pipeline state before emitting. 2078 HazardRec->Reset(); 2079 } 2080 HazardRec->EmitInstruction(SU); 2081 } 2082 // checkHazard should prevent scheduling multiple instructions per cycle that 2083 // exceed the issue width. 2084 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 2085 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr()); 2086 assert( 2087 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) && 2088 "Cannot schedule this instruction's MicroOps in the current cycle."); 2089 2090 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle); 2091 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n"); 2092 2093 unsigned NextCycle = CurrCycle; 2094 switch (SchedModel->getMicroOpBufferSize()) { 2095 case 0: 2096 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue"); 2097 break; 2098 case 1: 2099 if (ReadyCycle > NextCycle) { 2100 NextCycle = ReadyCycle; 2101 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n"); 2102 } 2103 break; 2104 default: 2105 // We don't currently model the OOO reorder buffer, so consider all 2106 // scheduled MOps to be "retired". We do loosely model in-order resource 2107 // latency. If this instruction uses an in-order resource, account for any 2108 // likely stall cycles. 2109 if (SU->isUnbuffered && ReadyCycle > NextCycle) 2110 NextCycle = ReadyCycle; 2111 break; 2112 } 2113 RetiredMOps += IncMOps; 2114 2115 // Update resource counts and critical resource. 2116 if (SchedModel->hasInstrSchedModel()) { 2117 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor(); 2118 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted"); 2119 Rem->RemIssueCount -= DecRemIssue; 2120 if (ZoneCritResIdx) { 2121 // Scale scheduled micro-ops for comparing with the critical resource. 2122 unsigned ScaledMOps = 2123 RetiredMOps * SchedModel->getMicroOpFactor(); 2124 2125 // If scaled micro-ops are now more than the previous critical resource by 2126 // a full cycle, then micro-ops issue becomes critical. 2127 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx)) 2128 >= (int)SchedModel->getLatencyFactor()) { 2129 ZoneCritResIdx = 0; 2130 DEBUG(dbgs() << " *** Critical resource NumMicroOps: " 2131 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n"); 2132 } 2133 } 2134 for (TargetSchedModel::ProcResIter 2135 PI = SchedModel->getWriteProcResBegin(SC), 2136 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 2137 unsigned RCycle = 2138 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle); 2139 if (RCycle > NextCycle) 2140 NextCycle = RCycle; 2141 } 2142 if (SU->hasReservedResource) { 2143 // For reserved resources, record the highest cycle using the resource. 2144 // For top-down scheduling, this is the cycle in which we schedule this 2145 // instruction plus the number of cycles the operations reserves the 2146 // resource. For bottom-up is it simply the instruction's cycle. 2147 for (TargetSchedModel::ProcResIter 2148 PI = SchedModel->getWriteProcResBegin(SC), 2149 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 2150 unsigned PIdx = PI->ProcResourceIdx; 2151 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) { 2152 if (isTop()) { 2153 ReservedCycles[PIdx] = 2154 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles); 2155 } 2156 else 2157 ReservedCycles[PIdx] = NextCycle; 2158 } 2159 } 2160 } 2161 } 2162 // Update ExpectedLatency and DependentLatency. 2163 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency; 2164 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency; 2165 if (SU->getDepth() > TopLatency) { 2166 TopLatency = SU->getDepth(); 2167 DEBUG(dbgs() << " " << Available.getName() 2168 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n"); 2169 } 2170 if (SU->getHeight() > BotLatency) { 2171 BotLatency = SU->getHeight(); 2172 DEBUG(dbgs() << " " << Available.getName() 2173 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n"); 2174 } 2175 // If we stall for any reason, bump the cycle. 2176 if (NextCycle > CurrCycle) { 2177 bumpCycle(NextCycle); 2178 } else { 2179 // After updating ZoneCritResIdx and ExpectedLatency, check if we're 2180 // resource limited. If a stall occurred, bumpCycle does this. 2181 unsigned LFactor = SchedModel->getLatencyFactor(); 2182 IsResourceLimited = 2183 (int)(getCriticalCount() - (getScheduledLatency() * LFactor)) 2184 > (int)LFactor; 2185 } 2186 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle 2187 // resets CurrMOps. Loop to handle instructions with more MOps than issue in 2188 // one cycle. Since we commonly reach the max MOps here, opportunistically 2189 // bump the cycle to avoid uselessly checking everything in the readyQ. 2190 CurrMOps += IncMOps; 2191 while (CurrMOps >= SchedModel->getIssueWidth()) { 2192 DEBUG(dbgs() << " *** Max MOps " << CurrMOps 2193 << " at cycle " << CurrCycle << '\n'); 2194 bumpCycle(++NextCycle); 2195 } 2196 DEBUG(dumpScheduledState()); 2197 } 2198 2199 /// Release pending ready nodes in to the available queue. This makes them 2200 /// visible to heuristics. 2201 void SchedBoundary::releasePending() { 2202 // If the available queue is empty, it is safe to reset MinReadyCycle. 2203 if (Available.empty()) 2204 MinReadyCycle = UINT_MAX; 2205 2206 // Check to see if any of the pending instructions are ready to issue. If 2207 // so, add them to the available queue. 2208 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0; 2209 for (unsigned i = 0, e = Pending.size(); i != e; ++i) { 2210 SUnit *SU = *(Pending.begin()+i); 2211 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle; 2212 2213 if (ReadyCycle < MinReadyCycle) 2214 MinReadyCycle = ReadyCycle; 2215 2216 if (!IsBuffered && ReadyCycle > CurrCycle) 2217 continue; 2218 2219 if (checkHazard(SU)) 2220 continue; 2221 2222 if (Available.size() >= ReadyListLimit) 2223 break; 2224 2225 Available.push(SU); 2226 Pending.remove(Pending.begin()+i); 2227 --i; --e; 2228 } 2229 DEBUG(if (!Pending.empty()) Pending.dump()); 2230 CheckPending = false; 2231 } 2232 2233 /// Remove SU from the ready set for this boundary. 2234 void SchedBoundary::removeReady(SUnit *SU) { 2235 if (Available.isInQueue(SU)) 2236 Available.remove(Available.find(SU)); 2237 else { 2238 assert(Pending.isInQueue(SU) && "bad ready count"); 2239 Pending.remove(Pending.find(SU)); 2240 } 2241 } 2242 2243 /// If this queue only has one ready candidate, return it. As a side effect, 2244 /// defer any nodes that now hit a hazard, and advance the cycle until at least 2245 /// one node is ready. If multiple instructions are ready, return NULL. 2246 SUnit *SchedBoundary::pickOnlyChoice() { 2247 if (CheckPending) 2248 releasePending(); 2249 2250 if (CurrMOps > 0) { 2251 // Defer any ready instrs that now have a hazard. 2252 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) { 2253 if (checkHazard(*I)) { 2254 Pending.push(*I); 2255 I = Available.remove(I); 2256 continue; 2257 } 2258 ++I; 2259 } 2260 } 2261 for (unsigned i = 0; Available.empty(); ++i) { 2262 // FIXME: Re-enable assert once PR20057 is resolved. 2263 // assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) && 2264 // "permanent hazard"); 2265 (void)i; 2266 bumpCycle(CurrCycle + 1); 2267 releasePending(); 2268 } 2269 if (Available.size() == 1) 2270 return *Available.begin(); 2271 return nullptr; 2272 } 2273 2274 #ifndef NDEBUG 2275 // This is useful information to dump after bumpNode. 2276 // Note that the Queue contents are more useful before pickNodeFromQueue. 2277 void SchedBoundary::dumpScheduledState() { 2278 unsigned ResFactor; 2279 unsigned ResCount; 2280 if (ZoneCritResIdx) { 2281 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx); 2282 ResCount = getResourceCount(ZoneCritResIdx); 2283 } else { 2284 ResFactor = SchedModel->getMicroOpFactor(); 2285 ResCount = RetiredMOps * SchedModel->getMicroOpFactor(); 2286 } 2287 unsigned LFactor = SchedModel->getLatencyFactor(); 2288 dbgs() << Available.getName() << " @" << CurrCycle << "c\n" 2289 << " Retired: " << RetiredMOps; 2290 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c"; 2291 dbgs() << "\n Critical: " << ResCount / LFactor << "c, " 2292 << ResCount / ResFactor << " " 2293 << SchedModel->getResourceName(ZoneCritResIdx) 2294 << "\n ExpectedLatency: " << ExpectedLatency << "c\n" 2295 << (IsResourceLimited ? " - Resource" : " - Latency") 2296 << " limited.\n"; 2297 } 2298 #endif 2299 2300 //===----------------------------------------------------------------------===// 2301 // GenericScheduler - Generic implementation of MachineSchedStrategy. 2302 //===----------------------------------------------------------------------===// 2303 2304 void GenericSchedulerBase::SchedCandidate:: 2305 initResourceDelta(const ScheduleDAGMI *DAG, 2306 const TargetSchedModel *SchedModel) { 2307 if (!Policy.ReduceResIdx && !Policy.DemandResIdx) 2308 return; 2309 2310 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 2311 for (TargetSchedModel::ProcResIter 2312 PI = SchedModel->getWriteProcResBegin(SC), 2313 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 2314 if (PI->ProcResourceIdx == Policy.ReduceResIdx) 2315 ResDelta.CritResources += PI->Cycles; 2316 if (PI->ProcResourceIdx == Policy.DemandResIdx) 2317 ResDelta.DemandedResources += PI->Cycles; 2318 } 2319 } 2320 2321 /// Set the CandPolicy given a scheduling zone given the current resources and 2322 /// latencies inside and outside the zone. 2323 void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA, 2324 SchedBoundary &CurrZone, 2325 SchedBoundary *OtherZone) { 2326 // Apply preemptive heuristics based on the total latency and resources 2327 // inside and outside this zone. Potential stalls should be considered before 2328 // following this policy. 2329 2330 // Compute remaining latency. We need this both to determine whether the 2331 // overall schedule has become latency-limited and whether the instructions 2332 // outside this zone are resource or latency limited. 2333 // 2334 // The "dependent" latency is updated incrementally during scheduling as the 2335 // max height/depth of scheduled nodes minus the cycles since it was 2336 // scheduled: 2337 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone 2338 // 2339 // The "independent" latency is the max ready queue depth: 2340 // ILat = max N.depth for N in Available|Pending 2341 // 2342 // RemainingLatency is the greater of independent and dependent latency. 2343 unsigned RemLatency = CurrZone.getDependentLatency(); 2344 RemLatency = std::max(RemLatency, 2345 CurrZone.findMaxLatency(CurrZone.Available.elements())); 2346 RemLatency = std::max(RemLatency, 2347 CurrZone.findMaxLatency(CurrZone.Pending.elements())); 2348 2349 // Compute the critical resource outside the zone. 2350 unsigned OtherCritIdx = 0; 2351 unsigned OtherCount = 2352 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0; 2353 2354 bool OtherResLimited = false; 2355 if (SchedModel->hasInstrSchedModel()) { 2356 unsigned LFactor = SchedModel->getLatencyFactor(); 2357 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor; 2358 } 2359 // Schedule aggressively for latency in PostRA mode. We don't check for 2360 // acyclic latency during PostRA, and highly out-of-order processors will 2361 // skip PostRA scheduling. 2362 if (!OtherResLimited) { 2363 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) { 2364 Policy.ReduceLatency |= true; 2365 DEBUG(dbgs() << " " << CurrZone.Available.getName() 2366 << " RemainingLatency " << RemLatency << " + " 2367 << CurrZone.getCurrCycle() << "c > CritPath " 2368 << Rem.CriticalPath << "\n"); 2369 } 2370 } 2371 // If the same resource is limiting inside and outside the zone, do nothing. 2372 if (CurrZone.getZoneCritResIdx() == OtherCritIdx) 2373 return; 2374 2375 DEBUG( 2376 if (CurrZone.isResourceLimited()) { 2377 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: " 2378 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) 2379 << "\n"; 2380 } 2381 if (OtherResLimited) 2382 dbgs() << " RemainingLimit: " 2383 << SchedModel->getResourceName(OtherCritIdx) << "\n"; 2384 if (!CurrZone.isResourceLimited() && !OtherResLimited) 2385 dbgs() << " Latency limited both directions.\n"); 2386 2387 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx) 2388 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx(); 2389 2390 if (OtherResLimited) 2391 Policy.DemandResIdx = OtherCritIdx; 2392 } 2393 2394 #ifndef NDEBUG 2395 const char *GenericSchedulerBase::getReasonStr( 2396 GenericSchedulerBase::CandReason Reason) { 2397 switch (Reason) { 2398 case NoCand: return "NOCAND "; 2399 case PhysRegCopy: return "PREG-COPY"; 2400 case RegExcess: return "REG-EXCESS"; 2401 case RegCritical: return "REG-CRIT "; 2402 case Stall: return "STALL "; 2403 case Cluster: return "CLUSTER "; 2404 case Weak: return "WEAK "; 2405 case RegMax: return "REG-MAX "; 2406 case ResourceReduce: return "RES-REDUCE"; 2407 case ResourceDemand: return "RES-DEMAND"; 2408 case TopDepthReduce: return "TOP-DEPTH "; 2409 case TopPathReduce: return "TOP-PATH "; 2410 case BotHeightReduce:return "BOT-HEIGHT"; 2411 case BotPathReduce: return "BOT-PATH "; 2412 case NextDefUse: return "DEF-USE "; 2413 case NodeOrder: return "ORDER "; 2414 }; 2415 llvm_unreachable("Unknown reason!"); 2416 } 2417 2418 void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) { 2419 PressureChange P; 2420 unsigned ResIdx = 0; 2421 unsigned Latency = 0; 2422 switch (Cand.Reason) { 2423 default: 2424 break; 2425 case RegExcess: 2426 P = Cand.RPDelta.Excess; 2427 break; 2428 case RegCritical: 2429 P = Cand.RPDelta.CriticalMax; 2430 break; 2431 case RegMax: 2432 P = Cand.RPDelta.CurrentMax; 2433 break; 2434 case ResourceReduce: 2435 ResIdx = Cand.Policy.ReduceResIdx; 2436 break; 2437 case ResourceDemand: 2438 ResIdx = Cand.Policy.DemandResIdx; 2439 break; 2440 case TopDepthReduce: 2441 Latency = Cand.SU->getDepth(); 2442 break; 2443 case TopPathReduce: 2444 Latency = Cand.SU->getHeight(); 2445 break; 2446 case BotHeightReduce: 2447 Latency = Cand.SU->getHeight(); 2448 break; 2449 case BotPathReduce: 2450 Latency = Cand.SU->getDepth(); 2451 break; 2452 } 2453 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason); 2454 if (P.isValid()) 2455 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet()) 2456 << ":" << P.getUnitInc() << " "; 2457 else 2458 dbgs() << " "; 2459 if (ResIdx) 2460 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " "; 2461 else 2462 dbgs() << " "; 2463 if (Latency) 2464 dbgs() << " " << Latency << " cycles "; 2465 else 2466 dbgs() << " "; 2467 dbgs() << '\n'; 2468 } 2469 #endif 2470 2471 /// Return true if this heuristic determines order. 2472 static bool tryLess(int TryVal, int CandVal, 2473 GenericSchedulerBase::SchedCandidate &TryCand, 2474 GenericSchedulerBase::SchedCandidate &Cand, 2475 GenericSchedulerBase::CandReason Reason) { 2476 if (TryVal < CandVal) { 2477 TryCand.Reason = Reason; 2478 return true; 2479 } 2480 if (TryVal > CandVal) { 2481 if (Cand.Reason > Reason) 2482 Cand.Reason = Reason; 2483 return true; 2484 } 2485 Cand.setRepeat(Reason); 2486 return false; 2487 } 2488 2489 static bool tryGreater(int TryVal, int CandVal, 2490 GenericSchedulerBase::SchedCandidate &TryCand, 2491 GenericSchedulerBase::SchedCandidate &Cand, 2492 GenericSchedulerBase::CandReason Reason) { 2493 if (TryVal > CandVal) { 2494 TryCand.Reason = Reason; 2495 return true; 2496 } 2497 if (TryVal < CandVal) { 2498 if (Cand.Reason > Reason) 2499 Cand.Reason = Reason; 2500 return true; 2501 } 2502 Cand.setRepeat(Reason); 2503 return false; 2504 } 2505 2506 static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, 2507 GenericSchedulerBase::SchedCandidate &Cand, 2508 SchedBoundary &Zone) { 2509 if (Zone.isTop()) { 2510 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) { 2511 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(), 2512 TryCand, Cand, GenericSchedulerBase::TopDepthReduce)) 2513 return true; 2514 } 2515 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(), 2516 TryCand, Cand, GenericSchedulerBase::TopPathReduce)) 2517 return true; 2518 } else { 2519 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) { 2520 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(), 2521 TryCand, Cand, GenericSchedulerBase::BotHeightReduce)) 2522 return true; 2523 } 2524 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(), 2525 TryCand, Cand, GenericSchedulerBase::BotPathReduce)) 2526 return true; 2527 } 2528 return false; 2529 } 2530 2531 static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand, 2532 bool IsTop) { 2533 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ") 2534 << GenericSchedulerBase::getReasonStr(Cand.Reason) << '\n'); 2535 } 2536 2537 void GenericScheduler::initialize(ScheduleDAGMI *dag) { 2538 assert(dag->hasVRegLiveness() && 2539 "(PreRA)GenericScheduler needs vreg liveness"); 2540 DAG = static_cast<ScheduleDAGMILive*>(dag); 2541 SchedModel = DAG->getSchedModel(); 2542 TRI = DAG->TRI; 2543 2544 Rem.init(DAG, SchedModel); 2545 Top.init(DAG, SchedModel, &Rem); 2546 Bot.init(DAG, SchedModel, &Rem); 2547 2548 // Initialize resource counts. 2549 2550 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or 2551 // are disabled, then these HazardRecs will be disabled. 2552 const InstrItineraryData *Itin = SchedModel->getInstrItineraries(); 2553 if (!Top.HazardRec) { 2554 Top.HazardRec = 2555 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer( 2556 Itin, DAG); 2557 } 2558 if (!Bot.HazardRec) { 2559 Bot.HazardRec = 2560 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer( 2561 Itin, DAG); 2562 } 2563 } 2564 2565 /// Initialize the per-region scheduling policy. 2566 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin, 2567 MachineBasicBlock::iterator End, 2568 unsigned NumRegionInstrs) { 2569 const MachineFunction &MF = *Begin->getParent()->getParent(); 2570 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering(); 2571 2572 // Avoid setting up the register pressure tracker for small regions to save 2573 // compile time. As a rough heuristic, only track pressure when the number of 2574 // schedulable instructions exceeds half the integer register file. 2575 RegionPolicy.ShouldTrackPressure = true; 2576 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) { 2577 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT; 2578 if (TLI->isTypeLegal(LegalIntVT)) { 2579 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs( 2580 TLI->getRegClassFor(LegalIntVT)); 2581 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2); 2582 } 2583 } 2584 2585 // For generic targets, we default to bottom-up, because it's simpler and more 2586 // compile-time optimizations have been implemented in that direction. 2587 RegionPolicy.OnlyBottomUp = true; 2588 2589 // Allow the subtarget to override default policy. 2590 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, Begin, End, 2591 NumRegionInstrs); 2592 2593 // After subtarget overrides, apply command line options. 2594 if (!EnableRegPressure) 2595 RegionPolicy.ShouldTrackPressure = false; 2596 2597 // Check -misched-topdown/bottomup can force or unforce scheduling direction. 2598 // e.g. -misched-bottomup=false allows scheduling in both directions. 2599 assert((!ForceTopDown || !ForceBottomUp) && 2600 "-misched-topdown incompatible with -misched-bottomup"); 2601 if (ForceBottomUp.getNumOccurrences() > 0) { 2602 RegionPolicy.OnlyBottomUp = ForceBottomUp; 2603 if (RegionPolicy.OnlyBottomUp) 2604 RegionPolicy.OnlyTopDown = false; 2605 } 2606 if (ForceTopDown.getNumOccurrences() > 0) { 2607 RegionPolicy.OnlyTopDown = ForceTopDown; 2608 if (RegionPolicy.OnlyTopDown) 2609 RegionPolicy.OnlyBottomUp = false; 2610 } 2611 } 2612 2613 void GenericScheduler::dumpPolicy() { 2614 dbgs() << "GenericScheduler RegionPolicy: " 2615 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure 2616 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown 2617 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp 2618 << "\n"; 2619 } 2620 2621 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic 2622 /// critical path by more cycles than it takes to drain the instruction buffer. 2623 /// We estimate an upper bounds on in-flight instructions as: 2624 /// 2625 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height ) 2626 /// InFlightIterations = AcyclicPath / CyclesPerIteration 2627 /// InFlightResources = InFlightIterations * LoopResources 2628 /// 2629 /// TODO: Check execution resources in addition to IssueCount. 2630 void GenericScheduler::checkAcyclicLatency() { 2631 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath) 2632 return; 2633 2634 // Scaled number of cycles per loop iteration. 2635 unsigned IterCount = 2636 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(), 2637 Rem.RemIssueCount); 2638 // Scaled acyclic critical path. 2639 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor(); 2640 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop 2641 unsigned InFlightCount = 2642 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount; 2643 unsigned BufferLimit = 2644 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor(); 2645 2646 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit; 2647 2648 DEBUG(dbgs() << "IssueCycles=" 2649 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c " 2650 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor() 2651 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount 2652 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor() 2653 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n"; 2654 if (Rem.IsAcyclicLatencyLimited) 2655 dbgs() << " ACYCLIC LATENCY LIMIT\n"); 2656 } 2657 2658 void GenericScheduler::registerRoots() { 2659 Rem.CriticalPath = DAG->ExitSU.getDepth(); 2660 2661 // Some roots may not feed into ExitSU. Check all of them in case. 2662 for (std::vector<SUnit*>::const_iterator 2663 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) { 2664 if ((*I)->getDepth() > Rem.CriticalPath) 2665 Rem.CriticalPath = (*I)->getDepth(); 2666 } 2667 DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n'); 2668 if (DumpCriticalPathLength) { 2669 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n"; 2670 } 2671 2672 if (EnableCyclicPath) { 2673 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath(); 2674 checkAcyclicLatency(); 2675 } 2676 } 2677 2678 static bool tryPressure(const PressureChange &TryP, 2679 const PressureChange &CandP, 2680 GenericSchedulerBase::SchedCandidate &TryCand, 2681 GenericSchedulerBase::SchedCandidate &Cand, 2682 GenericSchedulerBase::CandReason Reason, 2683 const TargetRegisterInfo *TRI, 2684 const MachineFunction &MF) { 2685 unsigned TryPSet = TryP.getPSetOrMax(); 2686 unsigned CandPSet = CandP.getPSetOrMax(); 2687 // If both candidates affect the same set, go with the smallest increase. 2688 if (TryPSet == CandPSet) { 2689 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand, 2690 Reason); 2691 } 2692 // If one candidate decreases and the other increases, go with it. 2693 // Invalid candidates have UnitInc==0. 2694 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand, 2695 Reason)) { 2696 return true; 2697 } 2698 2699 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) : 2700 std::numeric_limits<int>::max(); 2701 2702 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) : 2703 std::numeric_limits<int>::max(); 2704 2705 // If the candidates are decreasing pressure, reverse priority. 2706 if (TryP.getUnitInc() < 0) 2707 std::swap(TryRank, CandRank); 2708 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason); 2709 } 2710 2711 static unsigned getWeakLeft(const SUnit *SU, bool isTop) { 2712 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft; 2713 } 2714 2715 /// Minimize physical register live ranges. Regalloc wants them adjacent to 2716 /// their physreg def/use. 2717 /// 2718 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf 2719 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled 2720 /// with the operation that produces or consumes the physreg. We'll do this when 2721 /// regalloc has support for parallel copies. 2722 static int biasPhysRegCopy(const SUnit *SU, bool isTop) { 2723 const MachineInstr *MI = SU->getInstr(); 2724 if (!MI->isCopy()) 2725 return 0; 2726 2727 unsigned ScheduledOper = isTop ? 1 : 0; 2728 unsigned UnscheduledOper = isTop ? 0 : 1; 2729 // If we have already scheduled the physreg produce/consumer, immediately 2730 // schedule the copy. 2731 if (TargetRegisterInfo::isPhysicalRegister( 2732 MI->getOperand(ScheduledOper).getReg())) 2733 return 1; 2734 // If the physreg is at the boundary, defer it. Otherwise schedule it 2735 // immediately to free the dependent. We can hoist the copy later. 2736 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft; 2737 if (TargetRegisterInfo::isPhysicalRegister( 2738 MI->getOperand(UnscheduledOper).getReg())) 2739 return AtBoundary ? -1 : 1; 2740 return 0; 2741 } 2742 2743 void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU, 2744 bool AtTop, 2745 const RegPressureTracker &RPTracker, 2746 RegPressureTracker &TempTracker) { 2747 Cand.SU = SU; 2748 if (DAG->isTrackingPressure()) { 2749 if (AtTop) { 2750 TempTracker.getMaxDownwardPressureDelta( 2751 Cand.SU->getInstr(), 2752 Cand.RPDelta, 2753 DAG->getRegionCriticalPSets(), 2754 DAG->getRegPressure().MaxSetPressure); 2755 } else { 2756 if (VerifyScheduling) { 2757 TempTracker.getMaxUpwardPressureDelta( 2758 Cand.SU->getInstr(), 2759 &DAG->getPressureDiff(Cand.SU), 2760 Cand.RPDelta, 2761 DAG->getRegionCriticalPSets(), 2762 DAG->getRegPressure().MaxSetPressure); 2763 } else { 2764 RPTracker.getUpwardPressureDelta( 2765 Cand.SU->getInstr(), 2766 DAG->getPressureDiff(Cand.SU), 2767 Cand.RPDelta, 2768 DAG->getRegionCriticalPSets(), 2769 DAG->getRegPressure().MaxSetPressure); 2770 } 2771 } 2772 } 2773 DEBUG(if (Cand.RPDelta.Excess.isValid()) 2774 dbgs() << " Try SU(" << Cand.SU->NodeNum << ") " 2775 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) 2776 << ":" << Cand.RPDelta.Excess.getUnitInc() << "\n"); 2777 } 2778 2779 /// Apply a set of heursitics to a new candidate. Heuristics are currently 2780 /// hierarchical. This may be more efficient than a graduated cost model because 2781 /// we don't need to evaluate all aspects of the model for each node in the 2782 /// queue. But it's really done to make the heuristics easier to debug and 2783 /// statistically analyze. 2784 /// 2785 /// \param Cand provides the policy and current best candidate. 2786 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized. 2787 /// \param Zone describes the scheduled zone that we are extending. 2788 void GenericScheduler::tryCandidate(SchedCandidate &Cand, 2789 SchedCandidate &TryCand, 2790 SchedBoundary &Zone) { 2791 // Initialize the candidate if needed. 2792 if (!Cand.isValid()) { 2793 TryCand.Reason = NodeOrder; 2794 return; 2795 } 2796 2797 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()), 2798 biasPhysRegCopy(Cand.SU, Zone.isTop()), 2799 TryCand, Cand, PhysRegCopy)) 2800 return; 2801 2802 // Avoid exceeding the target's limit. 2803 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess, 2804 Cand.RPDelta.Excess, 2805 TryCand, Cand, RegExcess, TRI, 2806 DAG->MF)) 2807 return; 2808 2809 // Avoid increasing the max critical pressure in the scheduled region. 2810 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax, 2811 Cand.RPDelta.CriticalMax, 2812 TryCand, Cand, RegCritical, TRI, 2813 DAG->MF)) 2814 return; 2815 2816 // For loops that are acyclic path limited, aggressively schedule for latency. 2817 // This can result in very long dependence chains scheduled in sequence, so 2818 // once every cycle (when CurrMOps == 0), switch to normal heuristics. 2819 if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps() 2820 && tryLatency(TryCand, Cand, Zone)) 2821 return; 2822 2823 // Prioritize instructions that read unbuffered resources by stall cycles. 2824 if (tryLess(Zone.getLatencyStallCycles(TryCand.SU), 2825 Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall)) 2826 return; 2827 2828 // Keep clustered nodes together to encourage downstream peephole 2829 // optimizations which may reduce resource requirements. 2830 // 2831 // This is a best effort to set things up for a post-RA pass. Optimizations 2832 // like generating loads of multiple registers should ideally be done within 2833 // the scheduler pass by combining the loads during DAG postprocessing. 2834 const SUnit *NextClusterSU = 2835 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred(); 2836 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU, 2837 TryCand, Cand, Cluster)) 2838 return; 2839 2840 // Weak edges are for clustering and other constraints. 2841 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()), 2842 getWeakLeft(Cand.SU, Zone.isTop()), 2843 TryCand, Cand, Weak)) { 2844 return; 2845 } 2846 // Avoid increasing the max pressure of the entire region. 2847 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax, 2848 Cand.RPDelta.CurrentMax, 2849 TryCand, Cand, RegMax, TRI, 2850 DAG->MF)) 2851 return; 2852 2853 // Avoid critical resource consumption and balance the schedule. 2854 TryCand.initResourceDelta(DAG, SchedModel); 2855 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources, 2856 TryCand, Cand, ResourceReduce)) 2857 return; 2858 if (tryGreater(TryCand.ResDelta.DemandedResources, 2859 Cand.ResDelta.DemandedResources, 2860 TryCand, Cand, ResourceDemand)) 2861 return; 2862 2863 // Avoid serializing long latency dependence chains. 2864 // For acyclic path limited loops, latency was already checked above. 2865 if (!RegionPolicy.DisableLatencyHeuristic && Cand.Policy.ReduceLatency && 2866 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, Zone)) { 2867 return; 2868 } 2869 2870 // Prefer immediate defs/users of the last scheduled instruction. This is a 2871 // local pressure avoidance strategy that also makes the machine code 2872 // readable. 2873 if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU), 2874 TryCand, Cand, NextDefUse)) 2875 return; 2876 2877 // Fall through to original instruction order. 2878 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum) 2879 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) { 2880 TryCand.Reason = NodeOrder; 2881 } 2882 } 2883 2884 /// Pick the best candidate from the queue. 2885 /// 2886 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during 2887 /// DAG building. To adjust for the current scheduling location we need to 2888 /// maintain the number of vreg uses remaining to be top-scheduled. 2889 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone, 2890 const RegPressureTracker &RPTracker, 2891 SchedCandidate &Cand) { 2892 ReadyQueue &Q = Zone.Available; 2893 2894 DEBUG(Q.dump()); 2895 2896 // getMaxPressureDelta temporarily modifies the tracker. 2897 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker); 2898 2899 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) { 2900 2901 SchedCandidate TryCand(Cand.Policy); 2902 initCandidate(TryCand, *I, Zone.isTop(), RPTracker, TempTracker); 2903 tryCandidate(Cand, TryCand, Zone); 2904 if (TryCand.Reason != NoCand) { 2905 // Initialize resource delta if needed in case future heuristics query it. 2906 if (TryCand.ResDelta == SchedResourceDelta()) 2907 TryCand.initResourceDelta(DAG, SchedModel); 2908 Cand.setBest(TryCand); 2909 DEBUG(traceCandidate(Cand)); 2910 } 2911 } 2912 } 2913 2914 /// Pick the best candidate node from either the top or bottom queue. 2915 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) { 2916 // Schedule as far as possible in the direction of no choice. This is most 2917 // efficient, but also provides the best heuristics for CriticalPSets. 2918 if (SUnit *SU = Bot.pickOnlyChoice()) { 2919 IsTopNode = false; 2920 DEBUG(dbgs() << "Pick Bot ONLY1\n"); 2921 return SU; 2922 } 2923 if (SUnit *SU = Top.pickOnlyChoice()) { 2924 IsTopNode = true; 2925 DEBUG(dbgs() << "Pick Top ONLY1\n"); 2926 return SU; 2927 } 2928 CandPolicy NoPolicy; 2929 SchedCandidate BotCand(NoPolicy); 2930 SchedCandidate TopCand(NoPolicy); 2931 // Set the bottom-up policy based on the state of the current bottom zone and 2932 // the instructions outside the zone, including the top zone. 2933 setPolicy(BotCand.Policy, /*IsPostRA=*/false, Bot, &Top); 2934 // Set the top-down policy based on the state of the current top zone and 2935 // the instructions outside the zone, including the bottom zone. 2936 setPolicy(TopCand.Policy, /*IsPostRA=*/false, Top, &Bot); 2937 2938 // Prefer bottom scheduling when heuristics are silent. 2939 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand); 2940 assert(BotCand.Reason != NoCand && "failed to find the first candidate"); 2941 2942 // If either Q has a single candidate that provides the least increase in 2943 // Excess pressure, we can immediately schedule from that Q. 2944 // 2945 // RegionCriticalPSets summarizes the pressure within the scheduled region and 2946 // affects picking from either Q. If scheduling in one direction must 2947 // increase pressure for one of the excess PSets, then schedule in that 2948 // direction first to provide more freedom in the other direction. 2949 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess)) 2950 || (BotCand.Reason == RegCritical && !BotCand.isRepeat(RegCritical))) 2951 { 2952 IsTopNode = false; 2953 tracePick(BotCand, IsTopNode); 2954 return BotCand.SU; 2955 } 2956 // Check if the top Q has a better candidate. 2957 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand); 2958 assert(TopCand.Reason != NoCand && "failed to find the first candidate"); 2959 2960 // Choose the queue with the most important (lowest enum) reason. 2961 if (TopCand.Reason < BotCand.Reason) { 2962 IsTopNode = true; 2963 tracePick(TopCand, IsTopNode); 2964 return TopCand.SU; 2965 } 2966 // Otherwise prefer the bottom candidate, in node order if all else failed. 2967 IsTopNode = false; 2968 tracePick(BotCand, IsTopNode); 2969 return BotCand.SU; 2970 } 2971 2972 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy. 2973 SUnit *GenericScheduler::pickNode(bool &IsTopNode) { 2974 if (DAG->top() == DAG->bottom()) { 2975 assert(Top.Available.empty() && Top.Pending.empty() && 2976 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage"); 2977 return nullptr; 2978 } 2979 SUnit *SU; 2980 do { 2981 if (RegionPolicy.OnlyTopDown) { 2982 SU = Top.pickOnlyChoice(); 2983 if (!SU) { 2984 CandPolicy NoPolicy; 2985 SchedCandidate TopCand(NoPolicy); 2986 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand); 2987 assert(TopCand.Reason != NoCand && "failed to find a candidate"); 2988 tracePick(TopCand, true); 2989 SU = TopCand.SU; 2990 } 2991 IsTopNode = true; 2992 } else if (RegionPolicy.OnlyBottomUp) { 2993 SU = Bot.pickOnlyChoice(); 2994 if (!SU) { 2995 CandPolicy NoPolicy; 2996 SchedCandidate BotCand(NoPolicy); 2997 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand); 2998 assert(BotCand.Reason != NoCand && "failed to find a candidate"); 2999 tracePick(BotCand, false); 3000 SU = BotCand.SU; 3001 } 3002 IsTopNode = false; 3003 } else { 3004 SU = pickNodeBidirectional(IsTopNode); 3005 } 3006 } while (SU->isScheduled); 3007 3008 if (SU->isTopReady()) 3009 Top.removeReady(SU); 3010 if (SU->isBottomReady()) 3011 Bot.removeReady(SU); 3012 3013 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr()); 3014 return SU; 3015 } 3016 3017 void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) { 3018 3019 MachineBasicBlock::iterator InsertPos = SU->getInstr(); 3020 if (!isTop) 3021 ++InsertPos; 3022 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs; 3023 3024 // Find already scheduled copies with a single physreg dependence and move 3025 // them just above the scheduled instruction. 3026 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end(); 3027 I != E; ++I) { 3028 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg())) 3029 continue; 3030 SUnit *DepSU = I->getSUnit(); 3031 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1) 3032 continue; 3033 MachineInstr *Copy = DepSU->getInstr(); 3034 if (!Copy->isCopy()) 3035 continue; 3036 DEBUG(dbgs() << " Rescheduling physreg copy "; 3037 I->getSUnit()->dump(DAG)); 3038 DAG->moveInstruction(Copy, InsertPos); 3039 } 3040 } 3041 3042 /// Update the scheduler's state after scheduling a node. This is the same node 3043 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to 3044 /// update it's state based on the current cycle before MachineSchedStrategy 3045 /// does. 3046 /// 3047 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling 3048 /// them here. See comments in biasPhysRegCopy. 3049 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) { 3050 if (IsTopNode) { 3051 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle()); 3052 Top.bumpNode(SU); 3053 if (SU->hasPhysRegUses) 3054 reschedulePhysRegCopies(SU, true); 3055 } else { 3056 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle()); 3057 Bot.bumpNode(SU); 3058 if (SU->hasPhysRegDefs) 3059 reschedulePhysRegCopies(SU, false); 3060 } 3061 } 3062 3063 /// Create the standard converging machine scheduler. This will be used as the 3064 /// default scheduler if the target does not set a default. 3065 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C) { 3066 ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, make_unique<GenericScheduler>(C)); 3067 // Register DAG post-processors. 3068 // 3069 // FIXME: extend the mutation API to allow earlier mutations to instantiate 3070 // data and pass it to later mutations. Have a single mutation that gathers 3071 // the interesting nodes in one pass. 3072 DAG->addMutation(make_unique<CopyConstrain>(DAG->TII, DAG->TRI)); 3073 if (EnableMemOpCluster) { 3074 if (DAG->TII->enableClusterLoads()) 3075 DAG->addMutation(make_unique<LoadClusterMutation>(DAG->TII, DAG->TRI)); 3076 if (DAG->TII->enableClusterStores()) 3077 DAG->addMutation(make_unique<StoreClusterMutation>(DAG->TII, DAG->TRI)); 3078 } 3079 if (EnableMacroFusion) 3080 DAG->addMutation(make_unique<MacroFusion>(*DAG->TII, *DAG->TRI)); 3081 return DAG; 3082 } 3083 3084 static MachineSchedRegistry 3085 GenericSchedRegistry("converge", "Standard converging scheduler.", 3086 createGenericSchedLive); 3087 3088 //===----------------------------------------------------------------------===// 3089 // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy. 3090 //===----------------------------------------------------------------------===// 3091 3092 void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) { 3093 DAG = Dag; 3094 SchedModel = DAG->getSchedModel(); 3095 TRI = DAG->TRI; 3096 3097 Rem.init(DAG, SchedModel); 3098 Top.init(DAG, SchedModel, &Rem); 3099 BotRoots.clear(); 3100 3101 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, 3102 // or are disabled, then these HazardRecs will be disabled. 3103 const InstrItineraryData *Itin = SchedModel->getInstrItineraries(); 3104 if (!Top.HazardRec) { 3105 Top.HazardRec = 3106 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer( 3107 Itin, DAG); 3108 } 3109 } 3110 3111 3112 void PostGenericScheduler::registerRoots() { 3113 Rem.CriticalPath = DAG->ExitSU.getDepth(); 3114 3115 // Some roots may not feed into ExitSU. Check all of them in case. 3116 for (SmallVectorImpl<SUnit*>::const_iterator 3117 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) { 3118 if ((*I)->getDepth() > Rem.CriticalPath) 3119 Rem.CriticalPath = (*I)->getDepth(); 3120 } 3121 DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n'); 3122 if (DumpCriticalPathLength) { 3123 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n"; 3124 } 3125 } 3126 3127 /// Apply a set of heursitics to a new candidate for PostRA scheduling. 3128 /// 3129 /// \param Cand provides the policy and current best candidate. 3130 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized. 3131 void PostGenericScheduler::tryCandidate(SchedCandidate &Cand, 3132 SchedCandidate &TryCand) { 3133 3134 // Initialize the candidate if needed. 3135 if (!Cand.isValid()) { 3136 TryCand.Reason = NodeOrder; 3137 return; 3138 } 3139 3140 // Prioritize instructions that read unbuffered resources by stall cycles. 3141 if (tryLess(Top.getLatencyStallCycles(TryCand.SU), 3142 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall)) 3143 return; 3144 3145 // Avoid critical resource consumption and balance the schedule. 3146 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources, 3147 TryCand, Cand, ResourceReduce)) 3148 return; 3149 if (tryGreater(TryCand.ResDelta.DemandedResources, 3150 Cand.ResDelta.DemandedResources, 3151 TryCand, Cand, ResourceDemand)) 3152 return; 3153 3154 // Avoid serializing long latency dependence chains. 3155 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) { 3156 return; 3157 } 3158 3159 // Fall through to original instruction order. 3160 if (TryCand.SU->NodeNum < Cand.SU->NodeNum) 3161 TryCand.Reason = NodeOrder; 3162 } 3163 3164 void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) { 3165 ReadyQueue &Q = Top.Available; 3166 3167 DEBUG(Q.dump()); 3168 3169 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) { 3170 SchedCandidate TryCand(Cand.Policy); 3171 TryCand.SU = *I; 3172 TryCand.initResourceDelta(DAG, SchedModel); 3173 tryCandidate(Cand, TryCand); 3174 if (TryCand.Reason != NoCand) { 3175 Cand.setBest(TryCand); 3176 DEBUG(traceCandidate(Cand)); 3177 } 3178 } 3179 } 3180 3181 /// Pick the next node to schedule. 3182 SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) { 3183 if (DAG->top() == DAG->bottom()) { 3184 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage"); 3185 return nullptr; 3186 } 3187 SUnit *SU; 3188 do { 3189 SU = Top.pickOnlyChoice(); 3190 if (!SU) { 3191 CandPolicy NoPolicy; 3192 SchedCandidate TopCand(NoPolicy); 3193 // Set the top-down policy based on the state of the current top zone and 3194 // the instructions outside the zone, including the bottom zone. 3195 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr); 3196 pickNodeFromQueue(TopCand); 3197 assert(TopCand.Reason != NoCand && "failed to find a candidate"); 3198 tracePick(TopCand, true); 3199 SU = TopCand.SU; 3200 } 3201 } while (SU->isScheduled); 3202 3203 IsTopNode = true; 3204 Top.removeReady(SU); 3205 3206 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr()); 3207 return SU; 3208 } 3209 3210 /// Called after ScheduleDAGMI has scheduled an instruction and updated 3211 /// scheduled/remaining flags in the DAG nodes. 3212 void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) { 3213 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle()); 3214 Top.bumpNode(SU); 3215 } 3216 3217 /// Create a generic scheduler with no vreg liveness or DAG mutation passes. 3218 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C) { 3219 return new ScheduleDAGMI(C, make_unique<PostGenericScheduler>(C), /*IsPostRA=*/true); 3220 } 3221 3222 //===----------------------------------------------------------------------===// 3223 // ILP Scheduler. Currently for experimental analysis of heuristics. 3224 //===----------------------------------------------------------------------===// 3225 3226 namespace { 3227 /// \brief Order nodes by the ILP metric. 3228 struct ILPOrder { 3229 const SchedDFSResult *DFSResult; 3230 const BitVector *ScheduledTrees; 3231 bool MaximizeILP; 3232 3233 ILPOrder(bool MaxILP) 3234 : DFSResult(nullptr), ScheduledTrees(nullptr), MaximizeILP(MaxILP) {} 3235 3236 /// \brief Apply a less-than relation on node priority. 3237 /// 3238 /// (Return true if A comes after B in the Q.) 3239 bool operator()(const SUnit *A, const SUnit *B) const { 3240 unsigned SchedTreeA = DFSResult->getSubtreeID(A); 3241 unsigned SchedTreeB = DFSResult->getSubtreeID(B); 3242 if (SchedTreeA != SchedTreeB) { 3243 // Unscheduled trees have lower priority. 3244 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB)) 3245 return ScheduledTrees->test(SchedTreeB); 3246 3247 // Trees with shallower connections have have lower priority. 3248 if (DFSResult->getSubtreeLevel(SchedTreeA) 3249 != DFSResult->getSubtreeLevel(SchedTreeB)) { 3250 return DFSResult->getSubtreeLevel(SchedTreeA) 3251 < DFSResult->getSubtreeLevel(SchedTreeB); 3252 } 3253 } 3254 if (MaximizeILP) 3255 return DFSResult->getILP(A) < DFSResult->getILP(B); 3256 else 3257 return DFSResult->getILP(A) > DFSResult->getILP(B); 3258 } 3259 }; 3260 3261 /// \brief Schedule based on the ILP metric. 3262 class ILPScheduler : public MachineSchedStrategy { 3263 ScheduleDAGMILive *DAG; 3264 ILPOrder Cmp; 3265 3266 std::vector<SUnit*> ReadyQ; 3267 public: 3268 ILPScheduler(bool MaximizeILP): DAG(nullptr), Cmp(MaximizeILP) {} 3269 3270 void initialize(ScheduleDAGMI *dag) override { 3271 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness"); 3272 DAG = static_cast<ScheduleDAGMILive*>(dag); 3273 DAG->computeDFSResult(); 3274 Cmp.DFSResult = DAG->getDFSResult(); 3275 Cmp.ScheduledTrees = &DAG->getScheduledTrees(); 3276 ReadyQ.clear(); 3277 } 3278 3279 void registerRoots() override { 3280 // Restore the heap in ReadyQ with the updated DFS results. 3281 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3282 } 3283 3284 /// Implement MachineSchedStrategy interface. 3285 /// ----------------------------------------- 3286 3287 /// Callback to select the highest priority node from the ready Q. 3288 SUnit *pickNode(bool &IsTopNode) override { 3289 if (ReadyQ.empty()) return nullptr; 3290 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3291 SUnit *SU = ReadyQ.back(); 3292 ReadyQ.pop_back(); 3293 IsTopNode = false; 3294 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") " 3295 << " ILP: " << DAG->getDFSResult()->getILP(SU) 3296 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @" 3297 << DAG->getDFSResult()->getSubtreeLevel( 3298 DAG->getDFSResult()->getSubtreeID(SU)) << '\n' 3299 << "Scheduling " << *SU->getInstr()); 3300 return SU; 3301 } 3302 3303 /// \brief Scheduler callback to notify that a new subtree is scheduled. 3304 void scheduleTree(unsigned SubtreeID) override { 3305 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3306 } 3307 3308 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify 3309 /// DFSResults, and resort the priority Q. 3310 void schedNode(SUnit *SU, bool IsTopNode) override { 3311 assert(!IsTopNode && "SchedDFSResult needs bottom-up"); 3312 } 3313 3314 void releaseTopNode(SUnit *) override { /*only called for top roots*/ } 3315 3316 void releaseBottomNode(SUnit *SU) override { 3317 ReadyQ.push_back(SU); 3318 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3319 } 3320 }; 3321 } // namespace 3322 3323 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) { 3324 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(true)); 3325 } 3326 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) { 3327 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(false)); 3328 } 3329 static MachineSchedRegistry ILPMaxRegistry( 3330 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler); 3331 static MachineSchedRegistry ILPMinRegistry( 3332 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler); 3333 3334 //===----------------------------------------------------------------------===// 3335 // Machine Instruction Shuffler for Correctness Testing 3336 //===----------------------------------------------------------------------===// 3337 3338 #ifndef NDEBUG 3339 namespace { 3340 /// Apply a less-than relation on the node order, which corresponds to the 3341 /// instruction order prior to scheduling. IsReverse implements greater-than. 3342 template<bool IsReverse> 3343 struct SUnitOrder { 3344 bool operator()(SUnit *A, SUnit *B) const { 3345 if (IsReverse) 3346 return A->NodeNum > B->NodeNum; 3347 else 3348 return A->NodeNum < B->NodeNum; 3349 } 3350 }; 3351 3352 /// Reorder instructions as much as possible. 3353 class InstructionShuffler : public MachineSchedStrategy { 3354 bool IsAlternating; 3355 bool IsTopDown; 3356 3357 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority 3358 // gives nodes with a higher number higher priority causing the latest 3359 // instructions to be scheduled first. 3360 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> > 3361 TopQ; 3362 // When scheduling bottom-up, use greater-than as the queue priority. 3363 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> > 3364 BottomQ; 3365 public: 3366 InstructionShuffler(bool alternate, bool topdown) 3367 : IsAlternating(alternate), IsTopDown(topdown) {} 3368 3369 void initialize(ScheduleDAGMI*) override { 3370 TopQ.clear(); 3371 BottomQ.clear(); 3372 } 3373 3374 /// Implement MachineSchedStrategy interface. 3375 /// ----------------------------------------- 3376 3377 SUnit *pickNode(bool &IsTopNode) override { 3378 SUnit *SU; 3379 if (IsTopDown) { 3380 do { 3381 if (TopQ.empty()) return nullptr; 3382 SU = TopQ.top(); 3383 TopQ.pop(); 3384 } while (SU->isScheduled); 3385 IsTopNode = true; 3386 } else { 3387 do { 3388 if (BottomQ.empty()) return nullptr; 3389 SU = BottomQ.top(); 3390 BottomQ.pop(); 3391 } while (SU->isScheduled); 3392 IsTopNode = false; 3393 } 3394 if (IsAlternating) 3395 IsTopDown = !IsTopDown; 3396 return SU; 3397 } 3398 3399 void schedNode(SUnit *SU, bool IsTopNode) override {} 3400 3401 void releaseTopNode(SUnit *SU) override { 3402 TopQ.push(SU); 3403 } 3404 void releaseBottomNode(SUnit *SU) override { 3405 BottomQ.push(SU); 3406 } 3407 }; 3408 } // namespace 3409 3410 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) { 3411 bool Alternate = !ForceTopDown && !ForceBottomUp; 3412 bool TopDown = !ForceBottomUp; 3413 assert((TopDown || !ForceTopDown) && 3414 "-misched-topdown incompatible with -misched-bottomup"); 3415 return new ScheduleDAGMILive(C, make_unique<InstructionShuffler>(Alternate, TopDown)); 3416 } 3417 static MachineSchedRegistry ShufflerRegistry( 3418 "shuffle", "Shuffle machine instructions alternating directions", 3419 createInstructionShuffler); 3420 #endif // !NDEBUG 3421 3422 //===----------------------------------------------------------------------===// 3423 // GraphWriter support for ScheduleDAGMILive. 3424 //===----------------------------------------------------------------------===// 3425 3426 #ifndef NDEBUG 3427 namespace llvm { 3428 3429 template<> struct GraphTraits< 3430 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {}; 3431 3432 template<> 3433 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits { 3434 3435 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 3436 3437 static std::string getGraphName(const ScheduleDAG *G) { 3438 return G->MF.getName(); 3439 } 3440 3441 static bool renderGraphFromBottomUp() { 3442 return true; 3443 } 3444 3445 static bool isNodeHidden(const SUnit *Node) { 3446 if (ViewMISchedCutoff == 0) 3447 return false; 3448 return (Node->Preds.size() > ViewMISchedCutoff 3449 || Node->Succs.size() > ViewMISchedCutoff); 3450 } 3451 3452 /// If you want to override the dot attributes printed for a particular 3453 /// edge, override this method. 3454 static std::string getEdgeAttributes(const SUnit *Node, 3455 SUnitIterator EI, 3456 const ScheduleDAG *Graph) { 3457 if (EI.isArtificialDep()) 3458 return "color=cyan,style=dashed"; 3459 if (EI.isCtrlDep()) 3460 return "color=blue,style=dashed"; 3461 return ""; 3462 } 3463 3464 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) { 3465 std::string Str; 3466 raw_string_ostream SS(Str); 3467 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G); 3468 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ? 3469 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr; 3470 SS << "SU:" << SU->NodeNum; 3471 if (DFS) 3472 SS << " I:" << DFS->getNumInstrs(SU); 3473 return SS.str(); 3474 } 3475 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) { 3476 return G->getGraphNodeLabel(SU); 3477 } 3478 3479 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) { 3480 std::string Str("shape=Mrecord"); 3481 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G); 3482 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ? 3483 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr; 3484 if (DFS) { 3485 Str += ",style=filled,fillcolor=\"#"; 3486 Str += DOT::getColorString(DFS->getSubtreeID(N)); 3487 Str += '"'; 3488 } 3489 return Str; 3490 } 3491 }; 3492 } // namespace llvm 3493 #endif // NDEBUG 3494 3495 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG 3496 /// rendered using 'dot'. 3497 /// 3498 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) { 3499 #ifndef NDEBUG 3500 ViewGraph(this, Name, false, Title); 3501 #else 3502 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on " 3503 << "systems with Graphviz or gv!\n"; 3504 #endif // NDEBUG 3505 } 3506 3507 /// Out-of-line implementation with no arguments is handy for gdb. 3508 void ScheduleDAGMI::viewGraph() { 3509 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName()); 3510 } 3511