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