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