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 #define DEBUG_TYPE "misched" 16 17 #include "llvm/CodeGen/MachineScheduler.h" 18 #include "llvm/ADT/OwningPtr.h" 19 #include "llvm/ADT/PriorityQueue.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/CodeGen/LiveIntervalAnalysis.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/raw_ostream.h" 30 #include <queue> 31 32 using namespace llvm; 33 34 namespace llvm { 35 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden, 36 cl::desc("Force top-down list scheduling")); 37 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden, 38 cl::desc("Force bottom-up list scheduling")); 39 } 40 41 #ifndef NDEBUG 42 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden, 43 cl::desc("Pop up a window to show MISched dags after they are processed")); 44 45 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden, 46 cl::desc("Stop scheduling after N instructions"), cl::init(~0U)); 47 #else 48 static bool ViewMISchedDAGs = false; 49 #endif // NDEBUG 50 51 // Experimental heuristics 52 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden, 53 cl::desc("Enable load clustering."), cl::init(true)); 54 55 // Experimental heuristics 56 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden, 57 cl::desc("Enable scheduling for macro fusion."), cl::init(true)); 58 59 // DAG subtrees must have at least this many nodes. 60 static const unsigned MinSubtreeSize = 8; 61 62 //===----------------------------------------------------------------------===// 63 // Machine Instruction Scheduling Pass and Registry 64 //===----------------------------------------------------------------------===// 65 66 MachineSchedContext::MachineSchedContext(): 67 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) { 68 RegClassInfo = new RegisterClassInfo(); 69 } 70 71 MachineSchedContext::~MachineSchedContext() { 72 delete RegClassInfo; 73 } 74 75 namespace { 76 /// MachineScheduler runs after coalescing and before register allocation. 77 class MachineScheduler : public MachineSchedContext, 78 public MachineFunctionPass { 79 public: 80 MachineScheduler(); 81 82 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 83 84 virtual void releaseMemory() {} 85 86 virtual bool runOnMachineFunction(MachineFunction&); 87 88 virtual void print(raw_ostream &O, const Module* = 0) const; 89 90 static char ID; // Class identification, replacement for typeinfo 91 }; 92 } // namespace 93 94 char MachineScheduler::ID = 0; 95 96 char &llvm::MachineSchedulerID = MachineScheduler::ID; 97 98 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched", 99 "Machine Instruction Scheduler", false, false) 100 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 101 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 102 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 103 INITIALIZE_PASS_END(MachineScheduler, "misched", 104 "Machine Instruction Scheduler", false, false) 105 106 MachineScheduler::MachineScheduler() 107 : MachineFunctionPass(ID) { 108 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry()); 109 } 110 111 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const { 112 AU.setPreservesCFG(); 113 AU.addRequiredID(MachineDominatorsID); 114 AU.addRequired<MachineLoopInfo>(); 115 AU.addRequired<AliasAnalysis>(); 116 AU.addRequired<TargetPassConfig>(); 117 AU.addRequired<SlotIndexes>(); 118 AU.addPreserved<SlotIndexes>(); 119 AU.addRequired<LiveIntervals>(); 120 AU.addPreserved<LiveIntervals>(); 121 MachineFunctionPass::getAnalysisUsage(AU); 122 } 123 124 MachinePassRegistry MachineSchedRegistry::Registry; 125 126 /// A dummy default scheduler factory indicates whether the scheduler 127 /// is overridden on the command line. 128 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) { 129 return 0; 130 } 131 132 /// MachineSchedOpt allows command line selection of the scheduler. 133 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false, 134 RegisterPassParser<MachineSchedRegistry> > 135 MachineSchedOpt("misched", 136 cl::init(&useDefaultMachineSched), cl::Hidden, 137 cl::desc("Machine instruction scheduler to use")); 138 139 static MachineSchedRegistry 140 DefaultSchedRegistry("default", "Use the target's default scheduler choice.", 141 useDefaultMachineSched); 142 143 /// Forward declare the standard machine scheduler. This will be used as the 144 /// default scheduler if the target does not set a default. 145 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C); 146 147 148 /// Decrement this iterator until reaching the top or a non-debug instr. 149 static MachineBasicBlock::iterator 150 priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) { 151 assert(I != Beg && "reached the top of the region, cannot decrement"); 152 while (--I != Beg) { 153 if (!I->isDebugValue()) 154 break; 155 } 156 return I; 157 } 158 159 /// If this iterator is a debug value, increment until reaching the End or a 160 /// non-debug instruction. 161 static MachineBasicBlock::iterator 162 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) { 163 for(; I != End; ++I) { 164 if (!I->isDebugValue()) 165 break; 166 } 167 return I; 168 } 169 170 /// Top-level MachineScheduler pass driver. 171 /// 172 /// Visit blocks in function order. Divide each block into scheduling regions 173 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is 174 /// consistent with the DAG builder, which traverses the interior of the 175 /// scheduling regions bottom-up. 176 /// 177 /// This design avoids exposing scheduling boundaries to the DAG builder, 178 /// simplifying the DAG builder's support for "special" target instructions. 179 /// At the same time the design allows target schedulers to operate across 180 /// scheduling boundaries, for example to bundle the boudary instructions 181 /// without reordering them. This creates complexity, because the target 182 /// scheduler must update the RegionBegin and RegionEnd positions cached by 183 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler 184 /// design would be to split blocks at scheduling boundaries, but LLVM has a 185 /// general bias against block splitting purely for implementation simplicity. 186 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) { 187 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs())); 188 189 // Initialize the context of the pass. 190 MF = &mf; 191 MLI = &getAnalysis<MachineLoopInfo>(); 192 MDT = &getAnalysis<MachineDominatorTree>(); 193 PassConfig = &getAnalysis<TargetPassConfig>(); 194 AA = &getAnalysis<AliasAnalysis>(); 195 196 LIS = &getAnalysis<LiveIntervals>(); 197 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo(); 198 199 RegClassInfo->runOnMachineFunction(*MF); 200 201 // Select the scheduler, or set the default. 202 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt; 203 if (Ctor == useDefaultMachineSched) { 204 // Get the default scheduler set by the target. 205 Ctor = MachineSchedRegistry::getDefault(); 206 if (!Ctor) { 207 Ctor = createConvergingSched; 208 MachineSchedRegistry::setDefault(Ctor); 209 } 210 } 211 // Instantiate the selected scheduler. 212 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this)); 213 214 // Visit all machine basic blocks. 215 // 216 // TODO: Visit blocks in global postorder or postorder within the bottom-up 217 // loop tree. Then we can optionally compute global RegPressure. 218 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end(); 219 MBB != MBBEnd; ++MBB) { 220 221 Scheduler->startBlock(MBB); 222 223 // Break the block into scheduling regions [I, RegionEnd), and schedule each 224 // region as soon as it is discovered. RegionEnd points the scheduling 225 // boundary at the bottom of the region. The DAG does not include RegionEnd, 226 // but the region does (i.e. the next RegionEnd is above the previous 227 // RegionBegin). If the current block has no terminator then RegionEnd == 228 // MBB->end() for the bottom region. 229 // 230 // The Scheduler may insert instructions during either schedule() or 231 // exitRegion(), even for empty regions. So the local iterators 'I' and 232 // 'RegionEnd' are invalid across these calls. 233 unsigned RemainingInstrs = MBB->size(); 234 for(MachineBasicBlock::iterator RegionEnd = MBB->end(); 235 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) { 236 237 // Avoid decrementing RegionEnd for blocks with no terminator. 238 if (RegionEnd != MBB->end() 239 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) { 240 --RegionEnd; 241 // Count the boundary instruction. 242 --RemainingInstrs; 243 } 244 245 // The next region starts above the previous region. Look backward in the 246 // instruction stream until we find the nearest boundary. 247 MachineBasicBlock::iterator I = RegionEnd; 248 for(;I != MBB->begin(); --I, --RemainingInstrs) { 249 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF)) 250 break; 251 } 252 // Notify the scheduler of the region, even if we may skip scheduling 253 // it. Perhaps it still needs to be bundled. 254 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs); 255 256 // Skip empty scheduling regions (0 or 1 schedulable instructions). 257 if (I == RegionEnd || I == llvm::prior(RegionEnd)) { 258 // Close the current region. Bundle the terminator if needed. 259 // This invalidates 'RegionEnd' and 'I'. 260 Scheduler->exitRegion(); 261 continue; 262 } 263 DEBUG(dbgs() << "********** MI Scheduling **********\n"); 264 DEBUG(dbgs() << MF->getName() 265 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: "; 266 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd; 267 else dbgs() << "End"; 268 dbgs() << " Remaining: " << RemainingInstrs << "\n"); 269 270 // Schedule a region: possibly reorder instructions. 271 // This invalidates 'RegionEnd' and 'I'. 272 Scheduler->schedule(); 273 274 // Close the current region. 275 Scheduler->exitRegion(); 276 277 // Scheduling has invalidated the current iterator 'I'. Ask the 278 // scheduler for the top of it's scheduled region. 279 RegionEnd = Scheduler->begin(); 280 } 281 assert(RemainingInstrs == 0 && "Instruction count mismatch!"); 282 Scheduler->finishBlock(); 283 } 284 Scheduler->finalizeSchedule(); 285 DEBUG(LIS->print(dbgs())); 286 return true; 287 } 288 289 void MachineScheduler::print(raw_ostream &O, const Module* m) const { 290 // unimplemented 291 } 292 293 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 294 void ReadyQueue::dump() { 295 dbgs() << Name << ": "; 296 for (unsigned i = 0, e = Queue.size(); i < e; ++i) 297 dbgs() << Queue[i]->NodeNum << " "; 298 dbgs() << "\n"; 299 } 300 #endif 301 302 //===----------------------------------------------------------------------===// 303 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals 304 // preservation. 305 //===----------------------------------------------------------------------===// 306 307 ScheduleDAGMI::~ScheduleDAGMI() { 308 delete DFSResult; 309 DeleteContainerPointers(Mutations); 310 delete SchedImpl; 311 } 312 313 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) { 314 if (SuccSU != &ExitSU) { 315 // Do not use WillCreateCycle, it assumes SD scheduling. 316 // If Pred is reachable from Succ, then the edge creates a cycle. 317 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU)) 318 return false; 319 Topo.AddPred(SuccSU, PredDep.getSUnit()); 320 } 321 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial()); 322 // Return true regardless of whether a new edge needed to be inserted. 323 return true; 324 } 325 326 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When 327 /// NumPredsLeft reaches zero, release the successor node. 328 /// 329 /// FIXME: Adjust SuccSU height based on MinLatency. 330 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) { 331 SUnit *SuccSU = SuccEdge->getSUnit(); 332 333 if (SuccEdge->isWeak()) { 334 --SuccSU->WeakPredsLeft; 335 if (SuccEdge->isCluster()) 336 NextClusterSucc = SuccSU; 337 return; 338 } 339 #ifndef NDEBUG 340 if (SuccSU->NumPredsLeft == 0) { 341 dbgs() << "*** Scheduling failed! ***\n"; 342 SuccSU->dump(this); 343 dbgs() << " has been released too many times!\n"; 344 llvm_unreachable(0); 345 } 346 #endif 347 --SuccSU->NumPredsLeft; 348 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) 349 SchedImpl->releaseTopNode(SuccSU); 350 } 351 352 /// releaseSuccessors - Call releaseSucc on each of SU's successors. 353 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) { 354 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end(); 355 I != E; ++I) { 356 releaseSucc(SU, &*I); 357 } 358 } 359 360 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When 361 /// NumSuccsLeft reaches zero, release the predecessor node. 362 /// 363 /// FIXME: Adjust PredSU height based on MinLatency. 364 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) { 365 SUnit *PredSU = PredEdge->getSUnit(); 366 367 if (PredEdge->isWeak()) { 368 --PredSU->WeakSuccsLeft; 369 if (PredEdge->isCluster()) 370 NextClusterPred = PredSU; 371 return; 372 } 373 #ifndef NDEBUG 374 if (PredSU->NumSuccsLeft == 0) { 375 dbgs() << "*** Scheduling failed! ***\n"; 376 PredSU->dump(this); 377 dbgs() << " has been released too many times!\n"; 378 llvm_unreachable(0); 379 } 380 #endif 381 --PredSU->NumSuccsLeft; 382 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) 383 SchedImpl->releaseBottomNode(PredSU); 384 } 385 386 /// releasePredecessors - Call releasePred on each of SU's predecessors. 387 void ScheduleDAGMI::releasePredecessors(SUnit *SU) { 388 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); 389 I != E; ++I) { 390 releasePred(SU, &*I); 391 } 392 } 393 394 void ScheduleDAGMI::moveInstruction(MachineInstr *MI, 395 MachineBasicBlock::iterator InsertPos) { 396 // Advance RegionBegin if the first instruction moves down. 397 if (&*RegionBegin == MI) 398 ++RegionBegin; 399 400 // Update the instruction stream. 401 BB->splice(InsertPos, BB, MI); 402 403 // Update LiveIntervals 404 LIS->handleMove(MI, /*UpdateFlags=*/true); 405 406 // Recede RegionBegin if an instruction moves above the first. 407 if (RegionBegin == InsertPos) 408 RegionBegin = MI; 409 } 410 411 bool ScheduleDAGMI::checkSchedLimit() { 412 #ifndef NDEBUG 413 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) { 414 CurrentTop = CurrentBottom; 415 return false; 416 } 417 ++NumInstrsScheduled; 418 #endif 419 return true; 420 } 421 422 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after 423 /// crossing a scheduling boundary. [begin, end) includes all instructions in 424 /// the region, including the boundary itself and single-instruction regions 425 /// that don't get scheduled. 426 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb, 427 MachineBasicBlock::iterator begin, 428 MachineBasicBlock::iterator end, 429 unsigned endcount) 430 { 431 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount); 432 433 // For convenience remember the end of the liveness region. 434 LiveRegionEnd = 435 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd); 436 } 437 438 // Setup the register pressure trackers for the top scheduled top and bottom 439 // scheduled regions. 440 void ScheduleDAGMI::initRegPressure() { 441 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin); 442 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd); 443 444 // Close the RPTracker to finalize live ins. 445 RPTracker.closeRegion(); 446 447 DEBUG(RPTracker.getPressure().dump(TRI)); 448 449 // Initialize the live ins and live outs. 450 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs); 451 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs); 452 453 // Close one end of the tracker so we can call 454 // getMaxUpward/DownwardPressureDelta before advancing across any 455 // instructions. This converts currently live regs into live ins/outs. 456 TopRPTracker.closeTop(); 457 BotRPTracker.closeBottom(); 458 459 // Account for liveness generated by the region boundary. 460 if (LiveRegionEnd != RegionEnd) 461 BotRPTracker.recede(); 462 463 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom"); 464 465 // Cache the list of excess pressure sets in this region. This will also track 466 // the max pressure in the scheduled code for these sets. 467 RegionCriticalPSets.clear(); 468 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure; 469 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) { 470 unsigned Limit = TRI->getRegPressureSetLimit(i); 471 DEBUG(dbgs() << TRI->getRegPressureSetName(i) 472 << "Limit " << Limit 473 << " Actual " << RegionPressure[i] << "\n"); 474 if (RegionPressure[i] > Limit) 475 RegionCriticalPSets.push_back(PressureElement(i, 0)); 476 } 477 DEBUG(dbgs() << "Excess PSets: "; 478 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i) 479 dbgs() << TRI->getRegPressureSetName( 480 RegionCriticalPSets[i].PSetID) << " "; 481 dbgs() << "\n"); 482 } 483 484 // FIXME: When the pressure tracker deals in pressure differences then we won't 485 // iterate over all RegionCriticalPSets[i]. 486 void ScheduleDAGMI:: 487 updateScheduledPressure(std::vector<unsigned> NewMaxPressure) { 488 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) { 489 unsigned ID = RegionCriticalPSets[i].PSetID; 490 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease; 491 if ((int)NewMaxPressure[ID] > MaxUnits) 492 MaxUnits = NewMaxPressure[ID]; 493 } 494 } 495 496 /// schedule - Called back from MachineScheduler::runOnMachineFunction 497 /// after setting up the current scheduling region. [RegionBegin, RegionEnd) 498 /// only includes instructions that have DAG nodes, not scheduling boundaries. 499 /// 500 /// This is a skeletal driver, with all the functionality pushed into helpers, 501 /// so that it can be easilly extended by experimental schedulers. Generally, 502 /// implementing MachineSchedStrategy should be sufficient to implement a new 503 /// scheduling algorithm. However, if a scheduler further subclasses 504 /// ScheduleDAGMI then it will want to override this virtual method in order to 505 /// update any specialized state. 506 void ScheduleDAGMI::schedule() { 507 buildDAGWithRegPressure(); 508 509 Topo.InitDAGTopologicalSorting(); 510 511 postprocessDAG(); 512 513 SmallVector<SUnit*, 8> TopRoots, BotRoots; 514 findRootsAndBiasEdges(TopRoots, BotRoots); 515 516 // Initialize the strategy before modifying the DAG. 517 // This may initialize a DFSResult to be used for queue priority. 518 SchedImpl->initialize(this); 519 520 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su) 521 SUnits[su].dumpAll(this)); 522 if (ViewMISchedDAGs) viewGraph(); 523 524 // Initialize ready queues now that the DAG and priority data are finalized. 525 initQueues(TopRoots, BotRoots); 526 527 bool IsTopNode = false; 528 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) { 529 assert(!SU->isScheduled && "Node already scheduled"); 530 if (!checkSchedLimit()) 531 break; 532 533 scheduleMI(SU, IsTopNode); 534 535 updateQueues(SU, IsTopNode); 536 } 537 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone."); 538 539 placeDebugValues(); 540 541 DEBUG({ 542 unsigned BBNum = begin()->getParent()->getNumber(); 543 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n"; 544 dumpSchedule(); 545 dbgs() << '\n'; 546 }); 547 } 548 549 /// Build the DAG and setup three register pressure trackers. 550 void ScheduleDAGMI::buildDAGWithRegPressure() { 551 // Initialize the register pressure tracker used by buildSchedGraph. 552 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd); 553 554 // Account for liveness generate by the region boundary. 555 if (LiveRegionEnd != RegionEnd) 556 RPTracker.recede(); 557 558 // Build the DAG, and compute current register pressure. 559 buildSchedGraph(AA, &RPTracker); 560 if (ViewMISchedDAGs) viewGraph(); 561 562 // Initialize top/bottom trackers after computing region pressure. 563 initRegPressure(); 564 } 565 566 /// Apply each ScheduleDAGMutation step in order. 567 void ScheduleDAGMI::postprocessDAG() { 568 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) { 569 Mutations[i]->apply(this); 570 } 571 } 572 573 void ScheduleDAGMI::computeDFSResult() { 574 if (!DFSResult) 575 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize); 576 DFSResult->clear(); 577 ScheduledTrees.clear(); 578 DFSResult->resize(SUnits.size()); 579 DFSResult->compute(SUnits); 580 ScheduledTrees.resize(DFSResult->getNumSubtrees()); 581 } 582 583 void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots, 584 SmallVectorImpl<SUnit*> &BotRoots) { 585 for (std::vector<SUnit>::iterator 586 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) { 587 SUnit *SU = &(*I); 588 589 // Order predecessors so DFSResult follows the critical path. 590 SU->biasCriticalPath(); 591 592 // A SUnit is ready to top schedule if it has no predecessors. 593 if (!I->NumPredsLeft && SU != &EntrySU) 594 TopRoots.push_back(SU); 595 // A SUnit is ready to bottom schedule if it has no successors. 596 if (!I->NumSuccsLeft && SU != &ExitSU) 597 BotRoots.push_back(SU); 598 } 599 } 600 601 /// Identify DAG roots and setup scheduler queues. 602 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots, 603 ArrayRef<SUnit*> BotRoots) { 604 NextClusterSucc = NULL; 605 NextClusterPred = NULL; 606 607 // Release all DAG roots for scheduling, not including EntrySU/ExitSU. 608 // 609 // Nodes with unreleased weak edges can still be roots. 610 // Release top roots in forward order. 611 for (SmallVectorImpl<SUnit*>::const_iterator 612 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) { 613 SchedImpl->releaseTopNode(*I); 614 } 615 // Release bottom roots in reverse order so the higher priority nodes appear 616 // first. This is more natural and slightly more efficient. 617 for (SmallVectorImpl<SUnit*>::const_reverse_iterator 618 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) { 619 SchedImpl->releaseBottomNode(*I); 620 } 621 622 releaseSuccessors(&EntrySU); 623 releasePredecessors(&ExitSU); 624 625 SchedImpl->registerRoots(); 626 627 // Advance past initial DebugValues. 628 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker"); 629 CurrentTop = nextIfDebug(RegionBegin, RegionEnd); 630 TopRPTracker.setPos(CurrentTop); 631 632 CurrentBottom = RegionEnd; 633 } 634 635 /// Move an instruction and update register pressure. 636 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) { 637 // Move the instruction to its new location in the instruction stream. 638 MachineInstr *MI = SU->getInstr(); 639 640 if (IsTopNode) { 641 assert(SU->isTopReady() && "node still has unscheduled dependencies"); 642 if (&*CurrentTop == MI) 643 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom); 644 else { 645 moveInstruction(MI, CurrentTop); 646 TopRPTracker.setPos(MI); 647 } 648 649 // Update top scheduled pressure. 650 TopRPTracker.advance(); 651 assert(TopRPTracker.getPos() == CurrentTop && "out of sync"); 652 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure); 653 } 654 else { 655 assert(SU->isBottomReady() && "node still has unscheduled dependencies"); 656 MachineBasicBlock::iterator priorII = 657 priorNonDebug(CurrentBottom, CurrentTop); 658 if (&*priorII == MI) 659 CurrentBottom = priorII; 660 else { 661 if (&*CurrentTop == MI) { 662 CurrentTop = nextIfDebug(++CurrentTop, priorII); 663 TopRPTracker.setPos(CurrentTop); 664 } 665 moveInstruction(MI, CurrentBottom); 666 CurrentBottom = MI; 667 } 668 // Update bottom scheduled pressure. 669 BotRPTracker.recede(); 670 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync"); 671 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure); 672 } 673 } 674 675 /// Update scheduler queues after scheduling an instruction. 676 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) { 677 // Release dependent instructions for scheduling. 678 if (IsTopNode) 679 releaseSuccessors(SU); 680 else 681 releasePredecessors(SU); 682 683 SU->isScheduled = true; 684 685 if (DFSResult) { 686 unsigned SubtreeID = DFSResult->getSubtreeID(SU); 687 if (!ScheduledTrees.test(SubtreeID)) { 688 ScheduledTrees.set(SubtreeID); 689 DFSResult->scheduleTree(SubtreeID); 690 SchedImpl->scheduleTree(SubtreeID); 691 } 692 } 693 694 // Notify the scheduling strategy after updating the DAG. 695 SchedImpl->schedNode(SU, IsTopNode); 696 } 697 698 /// Reinsert any remaining debug_values, just like the PostRA scheduler. 699 void ScheduleDAGMI::placeDebugValues() { 700 // If first instruction was a DBG_VALUE then put it back. 701 if (FirstDbgValue) { 702 BB->splice(RegionBegin, BB, FirstDbgValue); 703 RegionBegin = FirstDbgValue; 704 } 705 706 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator 707 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) { 708 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI); 709 MachineInstr *DbgValue = P.first; 710 MachineBasicBlock::iterator OrigPrevMI = P.second; 711 if (&*RegionBegin == DbgValue) 712 ++RegionBegin; 713 BB->splice(++OrigPrevMI, BB, DbgValue); 714 if (OrigPrevMI == llvm::prior(RegionEnd)) 715 RegionEnd = DbgValue; 716 } 717 DbgValues.clear(); 718 FirstDbgValue = NULL; 719 } 720 721 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 722 void ScheduleDAGMI::dumpSchedule() const { 723 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) { 724 if (SUnit *SU = getSUnit(&(*MI))) 725 SU->dump(this); 726 else 727 dbgs() << "Missing SUnit\n"; 728 } 729 } 730 #endif 731 732 //===----------------------------------------------------------------------===// 733 // LoadClusterMutation - DAG post-processing to cluster loads. 734 //===----------------------------------------------------------------------===// 735 736 namespace { 737 /// \brief Post-process the DAG to create cluster edges between neighboring 738 /// loads. 739 class LoadClusterMutation : public ScheduleDAGMutation { 740 struct LoadInfo { 741 SUnit *SU; 742 unsigned BaseReg; 743 unsigned Offset; 744 LoadInfo(SUnit *su, unsigned reg, unsigned ofs) 745 : SU(su), BaseReg(reg), Offset(ofs) {} 746 }; 747 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS, 748 const LoadClusterMutation::LoadInfo &RHS); 749 750 const TargetInstrInfo *TII; 751 const TargetRegisterInfo *TRI; 752 public: 753 LoadClusterMutation(const TargetInstrInfo *tii, 754 const TargetRegisterInfo *tri) 755 : TII(tii), TRI(tri) {} 756 757 virtual void apply(ScheduleDAGMI *DAG); 758 protected: 759 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG); 760 }; 761 } // anonymous 762 763 bool LoadClusterMutation::LoadInfoLess( 764 const LoadClusterMutation::LoadInfo &LHS, 765 const LoadClusterMutation::LoadInfo &RHS) { 766 if (LHS.BaseReg != RHS.BaseReg) 767 return LHS.BaseReg < RHS.BaseReg; 768 return LHS.Offset < RHS.Offset; 769 } 770 771 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads, 772 ScheduleDAGMI *DAG) { 773 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords; 774 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) { 775 SUnit *SU = Loads[Idx]; 776 unsigned BaseReg; 777 unsigned Offset; 778 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI)) 779 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset)); 780 } 781 if (LoadRecords.size() < 2) 782 return; 783 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess); 784 unsigned ClusterLength = 1; 785 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) { 786 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) { 787 ClusterLength = 1; 788 continue; 789 } 790 791 SUnit *SUa = LoadRecords[Idx].SU; 792 SUnit *SUb = LoadRecords[Idx+1].SU; 793 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength) 794 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) { 795 796 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU(" 797 << SUb->NodeNum << ")\n"); 798 // Copy successor edges from SUa to SUb. Interleaving computation 799 // dependent on SUa can prevent load combining due to register reuse. 800 // Predecessor edges do not need to be copied from SUb to SUa since nearby 801 // loads should have effectively the same inputs. 802 for (SUnit::const_succ_iterator 803 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) { 804 if (SI->getSUnit() == SUb) 805 continue; 806 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n"); 807 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial)); 808 } 809 ++ClusterLength; 810 } 811 else 812 ClusterLength = 1; 813 } 814 } 815 816 /// \brief Callback from DAG postProcessing to create cluster edges for loads. 817 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) { 818 // Map DAG NodeNum to store chain ID. 819 DenseMap<unsigned, unsigned> StoreChainIDs; 820 // Map each store chain to a set of dependent loads. 821 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents; 822 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) { 823 SUnit *SU = &DAG->SUnits[Idx]; 824 if (!SU->getInstr()->mayLoad()) 825 continue; 826 unsigned ChainPredID = DAG->SUnits.size(); 827 for (SUnit::const_pred_iterator 828 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) { 829 if (PI->isCtrl()) { 830 ChainPredID = PI->getSUnit()->NodeNum; 831 break; 832 } 833 } 834 // Check if this chain-like pred has been seen 835 // before. ChainPredID==MaxNodeID for loads at the top of the schedule. 836 unsigned NumChains = StoreChainDependents.size(); 837 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result = 838 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains)); 839 if (Result.second) 840 StoreChainDependents.resize(NumChains + 1); 841 StoreChainDependents[Result.first->second].push_back(SU); 842 } 843 // Iterate over the store chains. 844 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx) 845 clusterNeighboringLoads(StoreChainDependents[Idx], DAG); 846 } 847 848 //===----------------------------------------------------------------------===// 849 // MacroFusion - DAG post-processing to encourage fusion of macro ops. 850 //===----------------------------------------------------------------------===// 851 852 namespace { 853 /// \brief Post-process the DAG to create cluster edges between instructions 854 /// that may be fused by the processor into a single operation. 855 class MacroFusion : public ScheduleDAGMutation { 856 const TargetInstrInfo *TII; 857 public: 858 MacroFusion(const TargetInstrInfo *tii): TII(tii) {} 859 860 virtual void apply(ScheduleDAGMI *DAG); 861 }; 862 } // anonymous 863 864 /// \brief Callback from DAG postProcessing to create cluster edges to encourage 865 /// fused operations. 866 void MacroFusion::apply(ScheduleDAGMI *DAG) { 867 // For now, assume targets can only fuse with the branch. 868 MachineInstr *Branch = DAG->ExitSU.getInstr(); 869 if (!Branch) 870 return; 871 872 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) { 873 SUnit *SU = &DAG->SUnits[--Idx]; 874 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch)) 875 continue; 876 877 // Create a single weak edge from SU to ExitSU. The only effect is to cause 878 // bottom-up scheduling to heavily prioritize the clustered SU. There is no 879 // need to copy predecessor edges from ExitSU to SU, since top-down 880 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling 881 // of SU, we could create an artificial edge from the deepest root, but it 882 // hasn't been needed yet. 883 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster)); 884 (void)Success; 885 assert(Success && "No DAG nodes should be reachable from ExitSU"); 886 887 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n"); 888 break; 889 } 890 } 891 892 //===----------------------------------------------------------------------===// 893 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy. 894 //===----------------------------------------------------------------------===// 895 896 namespace { 897 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance 898 /// the schedule. 899 class ConvergingScheduler : public MachineSchedStrategy { 900 public: 901 /// Represent the type of SchedCandidate found within a single queue. 902 /// pickNodeBidirectional depends on these listed by decreasing priority. 903 enum CandReason { 904 NoCand, SingleExcess, SingleCritical, Cluster, 905 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce, 906 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse, 907 NodeOrder}; 908 909 #ifndef NDEBUG 910 static const char *getReasonStr(ConvergingScheduler::CandReason Reason); 911 #endif 912 913 /// Policy for scheduling the next instruction in the candidate's zone. 914 struct CandPolicy { 915 bool ReduceLatency; 916 unsigned ReduceResIdx; 917 unsigned DemandResIdx; 918 919 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {} 920 }; 921 922 /// Status of an instruction's critical resource consumption. 923 struct SchedResourceDelta { 924 // Count critical resources in the scheduled region required by SU. 925 unsigned CritResources; 926 927 // Count critical resources from another region consumed by SU. 928 unsigned DemandedResources; 929 930 SchedResourceDelta(): CritResources(0), DemandedResources(0) {} 931 932 bool operator==(const SchedResourceDelta &RHS) const { 933 return CritResources == RHS.CritResources 934 && DemandedResources == RHS.DemandedResources; 935 } 936 bool operator!=(const SchedResourceDelta &RHS) const { 937 return !operator==(RHS); 938 } 939 }; 940 941 /// Store the state used by ConvergingScheduler heuristics, required for the 942 /// lifetime of one invocation of pickNode(). 943 struct SchedCandidate { 944 CandPolicy Policy; 945 946 // The best SUnit candidate. 947 SUnit *SU; 948 949 // The reason for this candidate. 950 CandReason Reason; 951 952 // Register pressure values for the best candidate. 953 RegPressureDelta RPDelta; 954 955 // Critical resource consumption of the best candidate. 956 SchedResourceDelta ResDelta; 957 958 SchedCandidate(const CandPolicy &policy) 959 : Policy(policy), SU(NULL), Reason(NoCand) {} 960 961 bool isValid() const { return SU; } 962 963 // Copy the status of another candidate without changing policy. 964 void setBest(SchedCandidate &Best) { 965 assert(Best.Reason != NoCand && "uninitialized Sched candidate"); 966 SU = Best.SU; 967 Reason = Best.Reason; 968 RPDelta = Best.RPDelta; 969 ResDelta = Best.ResDelta; 970 } 971 972 void initResourceDelta(const ScheduleDAGMI *DAG, 973 const TargetSchedModel *SchedModel); 974 }; 975 976 /// Summarize the unscheduled region. 977 struct SchedRemainder { 978 // Critical path through the DAG in expected latency. 979 unsigned CriticalPath; 980 981 // Unscheduled resources 982 SmallVector<unsigned, 16> RemainingCounts; 983 // Critical resource for the unscheduled zone. 984 unsigned CritResIdx; 985 // Number of micro-ops left to schedule. 986 unsigned RemainingMicroOps; 987 988 void reset() { 989 CriticalPath = 0; 990 RemainingCounts.clear(); 991 CritResIdx = 0; 992 RemainingMicroOps = 0; 993 } 994 995 SchedRemainder() { reset(); } 996 997 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel); 998 999 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const { 1000 if (!SchedModel->hasInstrSchedModel()) 1001 return 0; 1002 1003 return std::max( 1004 RemainingMicroOps * SchedModel->getMicroOpFactor(), 1005 RemainingCounts[CritResIdx]); 1006 } 1007 }; 1008 1009 /// Each Scheduling boundary is associated with ready queues. It tracks the 1010 /// current cycle in the direction of movement, and maintains the state 1011 /// of "hazards" and other interlocks at the current cycle. 1012 struct SchedBoundary { 1013 ScheduleDAGMI *DAG; 1014 const TargetSchedModel *SchedModel; 1015 SchedRemainder *Rem; 1016 1017 ReadyQueue Available; 1018 ReadyQueue Pending; 1019 bool CheckPending; 1020 1021 // For heuristics, keep a list of the nodes that immediately depend on the 1022 // most recently scheduled node. 1023 SmallPtrSet<const SUnit*, 8> NextSUs; 1024 1025 ScheduleHazardRecognizer *HazardRec; 1026 1027 unsigned CurrCycle; 1028 unsigned IssueCount; 1029 1030 /// MinReadyCycle - Cycle of the soonest available instruction. 1031 unsigned MinReadyCycle; 1032 1033 // The expected latency of the critical path in this scheduled zone. 1034 unsigned ExpectedLatency; 1035 1036 // Resources used in the scheduled zone beyond this boundary. 1037 SmallVector<unsigned, 16> ResourceCounts; 1038 1039 // Cache the critical resources ID in this scheduled zone. 1040 unsigned CritResIdx; 1041 1042 // Is the scheduled region resource limited vs. latency limited. 1043 bool IsResourceLimited; 1044 1045 unsigned ExpectedCount; 1046 1047 #ifndef NDEBUG 1048 // Remember the greatest min operand latency. 1049 unsigned MaxMinLatency; 1050 #endif 1051 1052 void reset() { 1053 Available.clear(); 1054 Pending.clear(); 1055 CheckPending = false; 1056 NextSUs.clear(); 1057 HazardRec = 0; 1058 CurrCycle = 0; 1059 IssueCount = 0; 1060 MinReadyCycle = UINT_MAX; 1061 ExpectedLatency = 0; 1062 ResourceCounts.resize(1); 1063 assert(!ResourceCounts[0] && "nonzero count for bad resource"); 1064 CritResIdx = 0; 1065 IsResourceLimited = false; 1066 ExpectedCount = 0; 1067 #ifndef NDEBUG 1068 MaxMinLatency = 0; 1069 #endif 1070 // Reserve a zero-count for invalid CritResIdx. 1071 ResourceCounts.resize(1); 1072 } 1073 1074 /// Pending queues extend the ready queues with the same ID and the 1075 /// PendingFlag set. 1076 SchedBoundary(unsigned ID, const Twine &Name): 1077 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"), 1078 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") { 1079 reset(); 1080 } 1081 1082 ~SchedBoundary() { delete HazardRec; } 1083 1084 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, 1085 SchedRemainder *rem); 1086 1087 bool isTop() const { 1088 return Available.getID() == ConvergingScheduler::TopQID; 1089 } 1090 1091 unsigned getUnscheduledLatency(SUnit *SU) const { 1092 if (isTop()) 1093 return SU->getHeight(); 1094 return SU->getDepth() + SU->Latency; 1095 } 1096 1097 unsigned getCriticalCount() const { 1098 return ResourceCounts[CritResIdx]; 1099 } 1100 1101 bool checkHazard(SUnit *SU); 1102 1103 void setLatencyPolicy(CandPolicy &Policy); 1104 1105 void releaseNode(SUnit *SU, unsigned ReadyCycle); 1106 1107 void bumpCycle(); 1108 1109 void countResource(unsigned PIdx, unsigned Cycles); 1110 1111 void bumpNode(SUnit *SU); 1112 1113 void releasePending(); 1114 1115 void removeReady(SUnit *SU); 1116 1117 SUnit *pickOnlyChoice(); 1118 }; 1119 1120 private: 1121 ScheduleDAGMI *DAG; 1122 const TargetSchedModel *SchedModel; 1123 const TargetRegisterInfo *TRI; 1124 1125 // State of the top and bottom scheduled instruction boundaries. 1126 SchedRemainder Rem; 1127 SchedBoundary Top; 1128 SchedBoundary Bot; 1129 1130 public: 1131 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both) 1132 enum { 1133 TopQID = 1, 1134 BotQID = 2, 1135 LogMaxQID = 2 1136 }; 1137 1138 ConvergingScheduler(): 1139 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {} 1140 1141 virtual void initialize(ScheduleDAGMI *dag); 1142 1143 virtual SUnit *pickNode(bool &IsTopNode); 1144 1145 virtual void schedNode(SUnit *SU, bool IsTopNode); 1146 1147 virtual void releaseTopNode(SUnit *SU); 1148 1149 virtual void releaseBottomNode(SUnit *SU); 1150 1151 virtual void registerRoots(); 1152 1153 protected: 1154 void balanceZones( 1155 ConvergingScheduler::SchedBoundary &CriticalZone, 1156 ConvergingScheduler::SchedCandidate &CriticalCand, 1157 ConvergingScheduler::SchedBoundary &OppositeZone, 1158 ConvergingScheduler::SchedCandidate &OppositeCand); 1159 1160 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand, 1161 ConvergingScheduler::SchedCandidate &BotCand); 1162 1163 void tryCandidate(SchedCandidate &Cand, 1164 SchedCandidate &TryCand, 1165 SchedBoundary &Zone, 1166 const RegPressureTracker &RPTracker, 1167 RegPressureTracker &TempTracker); 1168 1169 SUnit *pickNodeBidirectional(bool &IsTopNode); 1170 1171 void pickNodeFromQueue(SchedBoundary &Zone, 1172 const RegPressureTracker &RPTracker, 1173 SchedCandidate &Candidate); 1174 1175 #ifndef NDEBUG 1176 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone); 1177 #endif 1178 }; 1179 } // namespace 1180 1181 void ConvergingScheduler::SchedRemainder:: 1182 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) { 1183 reset(); 1184 if (!SchedModel->hasInstrSchedModel()) 1185 return; 1186 RemainingCounts.resize(SchedModel->getNumProcResourceKinds()); 1187 for (std::vector<SUnit>::iterator 1188 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) { 1189 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I); 1190 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC); 1191 for (TargetSchedModel::ProcResIter 1192 PI = SchedModel->getWriteProcResBegin(SC), 1193 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 1194 unsigned PIdx = PI->ProcResourceIdx; 1195 unsigned Factor = SchedModel->getResourceFactor(PIdx); 1196 RemainingCounts[PIdx] += (Factor * PI->Cycles); 1197 } 1198 } 1199 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds(); 1200 PIdx != PEnd; ++PIdx) { 1201 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx]) 1202 >= (int)SchedModel->getLatencyFactor()) { 1203 CritResIdx = PIdx; 1204 } 1205 } 1206 } 1207 1208 void ConvergingScheduler::SchedBoundary:: 1209 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) { 1210 reset(); 1211 DAG = dag; 1212 SchedModel = smodel; 1213 Rem = rem; 1214 if (SchedModel->hasInstrSchedModel()) 1215 ResourceCounts.resize(SchedModel->getNumProcResourceKinds()); 1216 } 1217 1218 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) { 1219 DAG = dag; 1220 SchedModel = DAG->getSchedModel(); 1221 TRI = DAG->TRI; 1222 Rem.init(DAG, SchedModel); 1223 Top.init(DAG, SchedModel, &Rem); 1224 Bot.init(DAG, SchedModel, &Rem); 1225 1226 DAG->computeDFSResult(); 1227 1228 // Initialize resource counts. 1229 1230 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or 1231 // are disabled, then these HazardRecs will be disabled. 1232 const InstrItineraryData *Itin = SchedModel->getInstrItineraries(); 1233 const TargetMachine &TM = DAG->MF.getTarget(); 1234 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG); 1235 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG); 1236 1237 assert((!ForceTopDown || !ForceBottomUp) && 1238 "-misched-topdown incompatible with -misched-bottomup"); 1239 } 1240 1241 void ConvergingScheduler::releaseTopNode(SUnit *SU) { 1242 if (SU->isScheduled) 1243 return; 1244 1245 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); 1246 I != E; ++I) { 1247 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle; 1248 unsigned MinLatency = I->getMinLatency(); 1249 #ifndef NDEBUG 1250 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency); 1251 #endif 1252 if (SU->TopReadyCycle < PredReadyCycle + MinLatency) 1253 SU->TopReadyCycle = PredReadyCycle + MinLatency; 1254 } 1255 Top.releaseNode(SU, SU->TopReadyCycle); 1256 } 1257 1258 void ConvergingScheduler::releaseBottomNode(SUnit *SU) { 1259 if (SU->isScheduled) 1260 return; 1261 1262 assert(SU->getInstr() && "Scheduled SUnit must have instr"); 1263 1264 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end(); 1265 I != E; ++I) { 1266 if (I->isWeak()) 1267 continue; 1268 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle; 1269 unsigned MinLatency = I->getMinLatency(); 1270 #ifndef NDEBUG 1271 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency); 1272 #endif 1273 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency) 1274 SU->BotReadyCycle = SuccReadyCycle + MinLatency; 1275 } 1276 Bot.releaseNode(SU, SU->BotReadyCycle); 1277 } 1278 1279 void ConvergingScheduler::registerRoots() { 1280 Rem.CriticalPath = DAG->ExitSU.getDepth(); 1281 // Some roots may not feed into ExitSU. Check all of them in case. 1282 for (std::vector<SUnit*>::const_iterator 1283 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) { 1284 if ((*I)->getDepth() > Rem.CriticalPath) 1285 Rem.CriticalPath = (*I)->getDepth(); 1286 } 1287 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n'); 1288 } 1289 1290 /// Does this SU have a hazard within the current instruction group. 1291 /// 1292 /// The scheduler supports two modes of hazard recognition. The first is the 1293 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that 1294 /// supports highly complicated in-order reservation tables 1295 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic. 1296 /// 1297 /// The second is a streamlined mechanism that checks for hazards based on 1298 /// simple counters that the scheduler itself maintains. It explicitly checks 1299 /// for instruction dispatch limitations, including the number of micro-ops that 1300 /// can dispatch per cycle. 1301 /// 1302 /// TODO: Also check whether the SU must start a new group. 1303 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) { 1304 if (HazardRec->isEnabled()) 1305 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard; 1306 1307 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr()); 1308 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) { 1309 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops=" 1310 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n'); 1311 return true; 1312 } 1313 return false; 1314 } 1315 1316 /// Compute the remaining latency to determine whether ILP should be increased. 1317 void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) { 1318 // FIXME: compile time. In all, we visit four queues here one we should only 1319 // need to visit the one that was last popped if we cache the result. 1320 unsigned RemLatency = 0; 1321 for (ReadyQueue::iterator I = Available.begin(), E = Available.end(); 1322 I != E; ++I) { 1323 unsigned L = getUnscheduledLatency(*I); 1324 if (L > RemLatency) 1325 RemLatency = L; 1326 } 1327 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end(); 1328 I != E; ++I) { 1329 unsigned L = getUnscheduledLatency(*I); 1330 if (L > RemLatency) 1331 RemLatency = L; 1332 } 1333 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow(); 1334 if (RemLatency + ExpectedLatency >= CriticalPathLimit 1335 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) { 1336 Policy.ReduceLatency = true; 1337 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n'); 1338 } 1339 } 1340 1341 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU, 1342 unsigned ReadyCycle) { 1343 1344 if (ReadyCycle < MinReadyCycle) 1345 MinReadyCycle = ReadyCycle; 1346 1347 // Check for interlocks first. For the purpose of other heuristics, an 1348 // instruction that cannot issue appears as if it's not in the ReadyQueue. 1349 if (ReadyCycle > CurrCycle || checkHazard(SU)) 1350 Pending.push(SU); 1351 else 1352 Available.push(SU); 1353 1354 // Record this node as an immediate dependent of the scheduled node. 1355 NextSUs.insert(SU); 1356 } 1357 1358 /// Move the boundary of scheduled code by one cycle. 1359 void ConvergingScheduler::SchedBoundary::bumpCycle() { 1360 unsigned Width = SchedModel->getIssueWidth(); 1361 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width; 1362 1363 unsigned NextCycle = CurrCycle + 1; 1364 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized"); 1365 if (MinReadyCycle > NextCycle) { 1366 IssueCount = 0; 1367 NextCycle = MinReadyCycle; 1368 } 1369 1370 if (!HazardRec->isEnabled()) { 1371 // Bypass HazardRec virtual calls. 1372 CurrCycle = NextCycle; 1373 } 1374 else { 1375 // Bypass getHazardType calls in case of long latency. 1376 for (; CurrCycle != NextCycle; ++CurrCycle) { 1377 if (isTop()) 1378 HazardRec->AdvanceCycle(); 1379 else 1380 HazardRec->RecedeCycle(); 1381 } 1382 } 1383 CheckPending = true; 1384 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle); 1385 1386 DEBUG(dbgs() << " *** " << Available.getName() << " cycle " 1387 << CurrCycle << '\n'); 1388 } 1389 1390 /// Add the given processor resource to this scheduled zone. 1391 void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx, 1392 unsigned Cycles) { 1393 unsigned Factor = SchedModel->getResourceFactor(PIdx); 1394 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name 1395 << " +(" << Cycles << "x" << Factor 1396 << ") / " << SchedModel->getLatencyFactor() << '\n'); 1397 1398 unsigned Count = Factor * Cycles; 1399 ResourceCounts[PIdx] += Count; 1400 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted"); 1401 Rem->RemainingCounts[PIdx] -= Count; 1402 1403 // Check if this resource exceeds the current critical resource by a full 1404 // cycle. If so, it becomes the critical resource. 1405 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx]) 1406 >= (int)SchedModel->getLatencyFactor()) { 1407 CritResIdx = PIdx; 1408 DEBUG(dbgs() << " *** Critical resource " 1409 << SchedModel->getProcResource(PIdx)->Name << " x" 1410 << ResourceCounts[PIdx] << '\n'); 1411 } 1412 } 1413 1414 /// Move the boundary of scheduled code by one SUnit. 1415 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) { 1416 // Update the reservation table. 1417 if (HazardRec->isEnabled()) { 1418 if (!isTop() && SU->isCall) { 1419 // Calls are scheduled with their preceding instructions. For bottom-up 1420 // scheduling, clear the pipeline state before emitting. 1421 HazardRec->Reset(); 1422 } 1423 HazardRec->EmitInstruction(SU); 1424 } 1425 // Update resource counts and critical resource. 1426 if (SchedModel->hasInstrSchedModel()) { 1427 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 1428 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC); 1429 for (TargetSchedModel::ProcResIter 1430 PI = SchedModel->getWriteProcResBegin(SC), 1431 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 1432 countResource(PI->ProcResourceIdx, PI->Cycles); 1433 } 1434 } 1435 if (isTop()) { 1436 if (SU->getDepth() > ExpectedLatency) 1437 ExpectedLatency = SU->getDepth(); 1438 } 1439 else { 1440 if (SU->getHeight() > ExpectedLatency) 1441 ExpectedLatency = SU->getHeight(); 1442 } 1443 1444 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle); 1445 1446 // Check the instruction group dispatch limit. 1447 // TODO: Check if this SU must end a dispatch group. 1448 IssueCount += SchedModel->getNumMicroOps(SU->getInstr()); 1449 1450 // checkHazard prevents scheduling multiple instructions per cycle that exceed 1451 // issue width. However, we commonly reach the maximum. In this case 1452 // opportunistically bump the cycle to avoid uselessly checking everything in 1453 // the readyQ. Furthermore, a single instruction may produce more than one 1454 // cycle's worth of micro-ops. 1455 if (IssueCount >= SchedModel->getIssueWidth()) { 1456 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n'); 1457 bumpCycle(); 1458 } 1459 } 1460 1461 /// Release pending ready nodes in to the available queue. This makes them 1462 /// visible to heuristics. 1463 void ConvergingScheduler::SchedBoundary::releasePending() { 1464 // If the available queue is empty, it is safe to reset MinReadyCycle. 1465 if (Available.empty()) 1466 MinReadyCycle = UINT_MAX; 1467 1468 // Check to see if any of the pending instructions are ready to issue. If 1469 // so, add them to the available queue. 1470 for (unsigned i = 0, e = Pending.size(); i != e; ++i) { 1471 SUnit *SU = *(Pending.begin()+i); 1472 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle; 1473 1474 if (ReadyCycle < MinReadyCycle) 1475 MinReadyCycle = ReadyCycle; 1476 1477 if (ReadyCycle > CurrCycle) 1478 continue; 1479 1480 if (checkHazard(SU)) 1481 continue; 1482 1483 Available.push(SU); 1484 Pending.remove(Pending.begin()+i); 1485 --i; --e; 1486 } 1487 DEBUG(if (!Pending.empty()) Pending.dump()); 1488 CheckPending = false; 1489 } 1490 1491 /// Remove SU from the ready set for this boundary. 1492 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) { 1493 if (Available.isInQueue(SU)) 1494 Available.remove(Available.find(SU)); 1495 else { 1496 assert(Pending.isInQueue(SU) && "bad ready count"); 1497 Pending.remove(Pending.find(SU)); 1498 } 1499 } 1500 1501 /// If this queue only has one ready candidate, return it. As a side effect, 1502 /// defer any nodes that now hit a hazard, and advance the cycle until at least 1503 /// one node is ready. If multiple instructions are ready, return NULL. 1504 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() { 1505 if (CheckPending) 1506 releasePending(); 1507 1508 if (IssueCount > 0) { 1509 // Defer any ready instrs that now have a hazard. 1510 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) { 1511 if (checkHazard(*I)) { 1512 Pending.push(*I); 1513 I = Available.remove(I); 1514 continue; 1515 } 1516 ++I; 1517 } 1518 } 1519 for (unsigned i = 0; Available.empty(); ++i) { 1520 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) && 1521 "permanent hazard"); (void)i; 1522 bumpCycle(); 1523 releasePending(); 1524 } 1525 if (Available.size() == 1) 1526 return *Available.begin(); 1527 return NULL; 1528 } 1529 1530 /// Record the candidate policy for opposite zones with different critical 1531 /// resources. 1532 /// 1533 /// If the CriticalZone is latency limited, don't force a policy for the 1534 /// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed. 1535 void ConvergingScheduler::balanceZones( 1536 ConvergingScheduler::SchedBoundary &CriticalZone, 1537 ConvergingScheduler::SchedCandidate &CriticalCand, 1538 ConvergingScheduler::SchedBoundary &OppositeZone, 1539 ConvergingScheduler::SchedCandidate &OppositeCand) { 1540 1541 if (!CriticalZone.IsResourceLimited) 1542 return; 1543 assert(SchedModel->hasInstrSchedModel() && "required schedmodel"); 1544 1545 SchedRemainder *Rem = CriticalZone.Rem; 1546 1547 // If the critical zone is overconsuming a resource relative to the 1548 // remainder, try to reduce it. 1549 unsigned RemainingCritCount = 1550 Rem->RemainingCounts[CriticalZone.CritResIdx]; 1551 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount) 1552 > (int)SchedModel->getLatencyFactor()) { 1553 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx; 1554 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce " 1555 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name 1556 << '\n'); 1557 } 1558 // If the other zone is underconsuming a resource relative to the full zone, 1559 // try to increase it. 1560 unsigned OppositeCount = 1561 OppositeZone.ResourceCounts[CriticalZone.CritResIdx]; 1562 if ((int)(OppositeZone.ExpectedCount - OppositeCount) 1563 > (int)SchedModel->getLatencyFactor()) { 1564 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx; 1565 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand " 1566 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name 1567 << '\n'); 1568 } 1569 } 1570 1571 /// Determine if the scheduled zones exceed resource limits or critical path and 1572 /// set each candidate's ReduceHeight policy accordingly. 1573 void ConvergingScheduler::checkResourceLimits( 1574 ConvergingScheduler::SchedCandidate &TopCand, 1575 ConvergingScheduler::SchedCandidate &BotCand) { 1576 1577 // Set ReduceLatency to true if needed. 1578 Bot.setLatencyPolicy(BotCand.Policy); 1579 Top.setLatencyPolicy(TopCand.Policy); 1580 1581 // Handle resource-limited regions. 1582 if (Top.IsResourceLimited && Bot.IsResourceLimited 1583 && Top.CritResIdx == Bot.CritResIdx) { 1584 // If the scheduled critical resource in both zones is no longer the 1585 // critical remaining resource, attempt to reduce resource height both ways. 1586 if (Top.CritResIdx != Rem.CritResIdx) { 1587 TopCand.Policy.ReduceResIdx = Top.CritResIdx; 1588 BotCand.Policy.ReduceResIdx = Bot.CritResIdx; 1589 DEBUG(dbgs() << "Reduce scheduled " 1590 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n'); 1591 } 1592 return; 1593 } 1594 // Handle latency-limited regions. 1595 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) { 1596 // If the total scheduled expected latency exceeds the region's critical 1597 // path then reduce latency both ways. 1598 // 1599 // Just because a zone is not resource limited does not mean it is latency 1600 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle 1601 // to exceed expected latency. 1602 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath) 1603 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) { 1604 TopCand.Policy.ReduceLatency = true; 1605 BotCand.Policy.ReduceLatency = true; 1606 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency 1607 << " + " << Bot.ExpectedLatency << '\n'); 1608 } 1609 return; 1610 } 1611 // The critical resource is different in each zone, so request balancing. 1612 1613 // Compute the cost of each zone. 1614 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle); 1615 Top.ExpectedCount = std::max( 1616 Top.getCriticalCount(), 1617 Top.ExpectedCount * SchedModel->getLatencyFactor()); 1618 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle); 1619 Bot.ExpectedCount = std::max( 1620 Bot.getCriticalCount(), 1621 Bot.ExpectedCount * SchedModel->getLatencyFactor()); 1622 1623 balanceZones(Top, TopCand, Bot, BotCand); 1624 balanceZones(Bot, BotCand, Top, TopCand); 1625 } 1626 1627 void ConvergingScheduler::SchedCandidate:: 1628 initResourceDelta(const ScheduleDAGMI *DAG, 1629 const TargetSchedModel *SchedModel) { 1630 if (!Policy.ReduceResIdx && !Policy.DemandResIdx) 1631 return; 1632 1633 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 1634 for (TargetSchedModel::ProcResIter 1635 PI = SchedModel->getWriteProcResBegin(SC), 1636 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 1637 if (PI->ProcResourceIdx == Policy.ReduceResIdx) 1638 ResDelta.CritResources += PI->Cycles; 1639 if (PI->ProcResourceIdx == Policy.DemandResIdx) 1640 ResDelta.DemandedResources += PI->Cycles; 1641 } 1642 } 1643 1644 /// Return true if this heuristic determines order. 1645 static bool tryLess(unsigned TryVal, unsigned CandVal, 1646 ConvergingScheduler::SchedCandidate &TryCand, 1647 ConvergingScheduler::SchedCandidate &Cand, 1648 ConvergingScheduler::CandReason Reason) { 1649 if (TryVal < CandVal) { 1650 TryCand.Reason = Reason; 1651 return true; 1652 } 1653 if (TryVal > CandVal) { 1654 if (Cand.Reason > Reason) 1655 Cand.Reason = Reason; 1656 return true; 1657 } 1658 return false; 1659 } 1660 1661 static bool tryGreater(unsigned TryVal, unsigned CandVal, 1662 ConvergingScheduler::SchedCandidate &TryCand, 1663 ConvergingScheduler::SchedCandidate &Cand, 1664 ConvergingScheduler::CandReason Reason) { 1665 if (TryVal > CandVal) { 1666 TryCand.Reason = Reason; 1667 return true; 1668 } 1669 if (TryVal < CandVal) { 1670 if (Cand.Reason > Reason) 1671 Cand.Reason = Reason; 1672 return true; 1673 } 1674 return false; 1675 } 1676 1677 static unsigned getWeakLeft(const SUnit *SU, bool isTop) { 1678 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft; 1679 } 1680 1681 /// Apply a set of heursitics to a new candidate. Heuristics are currently 1682 /// hierarchical. This may be more efficient than a graduated cost model because 1683 /// we don't need to evaluate all aspects of the model for each node in the 1684 /// queue. But it's really done to make the heuristics easier to debug and 1685 /// statistically analyze. 1686 /// 1687 /// \param Cand provides the policy and current best candidate. 1688 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized. 1689 /// \param Zone describes the scheduled zone that we are extending. 1690 /// \param RPTracker describes reg pressure within the scheduled zone. 1691 /// \param TempTracker is a scratch pressure tracker to reuse in queries. 1692 void ConvergingScheduler::tryCandidate(SchedCandidate &Cand, 1693 SchedCandidate &TryCand, 1694 SchedBoundary &Zone, 1695 const RegPressureTracker &RPTracker, 1696 RegPressureTracker &TempTracker) { 1697 1698 // Always initialize TryCand's RPDelta. 1699 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta, 1700 DAG->getRegionCriticalPSets(), 1701 DAG->getRegPressure().MaxSetPressure); 1702 1703 // Initialize the candidate if needed. 1704 if (!Cand.isValid()) { 1705 TryCand.Reason = NodeOrder; 1706 return; 1707 } 1708 // Avoid exceeding the target's limit. 1709 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease, 1710 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess)) 1711 return; 1712 if (Cand.Reason == SingleExcess) 1713 Cand.Reason = MultiPressure; 1714 1715 // Avoid increasing the max critical pressure in the scheduled region. 1716 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease, 1717 Cand.RPDelta.CriticalMax.UnitIncrease, 1718 TryCand, Cand, SingleCritical)) 1719 return; 1720 if (Cand.Reason == SingleCritical) 1721 Cand.Reason = MultiPressure; 1722 1723 // Keep clustered nodes together to encourage downstream peephole 1724 // optimizations which may reduce resource requirements. 1725 // 1726 // This is a best effort to set things up for a post-RA pass. Optimizations 1727 // like generating loads of multiple registers should ideally be done within 1728 // the scheduler pass by combining the loads during DAG postprocessing. 1729 const SUnit *NextClusterSU = 1730 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred(); 1731 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU, 1732 TryCand, Cand, Cluster)) 1733 return; 1734 // Currently, weak edges are for clustering, so we hard-code that reason. 1735 // However, deferring the current TryCand will not change Cand's reason. 1736 CandReason OrigReason = Cand.Reason; 1737 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()), 1738 getWeakLeft(Cand.SU, Zone.isTop()), 1739 TryCand, Cand, Cluster)) { 1740 Cand.Reason = OrigReason; 1741 return; 1742 } 1743 // Avoid critical resource consumption and balance the schedule. 1744 TryCand.initResourceDelta(DAG, SchedModel); 1745 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources, 1746 TryCand, Cand, ResourceReduce)) 1747 return; 1748 if (tryGreater(TryCand.ResDelta.DemandedResources, 1749 Cand.ResDelta.DemandedResources, 1750 TryCand, Cand, ResourceDemand)) 1751 return; 1752 1753 // Avoid serializing long latency dependence chains. 1754 if (Cand.Policy.ReduceLatency) { 1755 if (Zone.isTop()) { 1756 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor() 1757 > Zone.ExpectedCount) { 1758 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(), 1759 TryCand, Cand, TopDepthReduce)) 1760 return; 1761 } 1762 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(), 1763 TryCand, Cand, TopPathReduce)) 1764 return; 1765 } 1766 else { 1767 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor() 1768 > Zone.ExpectedCount) { 1769 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(), 1770 TryCand, Cand, BotHeightReduce)) 1771 return; 1772 } 1773 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(), 1774 TryCand, Cand, BotPathReduce)) 1775 return; 1776 } 1777 } 1778 1779 // Avoid increasing the max pressure of the entire region. 1780 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease, 1781 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax)) 1782 return; 1783 if (Cand.Reason == SingleMax) 1784 Cand.Reason = MultiPressure; 1785 1786 // Prefer immediate defs/users of the last scheduled instruction. This is a 1787 // nice pressure avoidance strategy that also conserves the processor's 1788 // register renaming resources and keeps the machine code readable. 1789 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU), 1790 TryCand, Cand, NextDefUse)) 1791 return; 1792 1793 // Fall through to original instruction order. 1794 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum) 1795 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) { 1796 TryCand.Reason = NodeOrder; 1797 } 1798 } 1799 1800 /// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is 1801 /// more desirable than RHS from scheduling standpoint. 1802 static bool compareRPDelta(const RegPressureDelta &LHS, 1803 const RegPressureDelta &RHS) { 1804 // Compare each component of pressure in decreasing order of importance 1805 // without checking if any are valid. Invalid PressureElements are assumed to 1806 // have UnitIncrease==0, so are neutral. 1807 1808 // Avoid increasing the max critical pressure in the scheduled region. 1809 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) { 1810 DEBUG(dbgs() << "RP excess top - bot: " 1811 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n'); 1812 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease; 1813 } 1814 // Avoid increasing the max critical pressure in the scheduled region. 1815 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) { 1816 DEBUG(dbgs() << "RP critical top - bot: " 1817 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease) 1818 << '\n'); 1819 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease; 1820 } 1821 // Avoid increasing the max pressure of the entire region. 1822 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) { 1823 DEBUG(dbgs() << "RP current top - bot: " 1824 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease) 1825 << '\n'); 1826 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease; 1827 } 1828 return false; 1829 } 1830 1831 #ifndef NDEBUG 1832 const char *ConvergingScheduler::getReasonStr( 1833 ConvergingScheduler::CandReason Reason) { 1834 switch (Reason) { 1835 case NoCand: return "NOCAND "; 1836 case SingleExcess: return "REG-EXCESS"; 1837 case SingleCritical: return "REG-CRIT "; 1838 case Cluster: return "CLUSTER "; 1839 case SingleMax: return "REG-MAX "; 1840 case MultiPressure: return "REG-MULTI "; 1841 case ResourceReduce: return "RES-REDUCE"; 1842 case ResourceDemand: return "RES-DEMAND"; 1843 case TopDepthReduce: return "TOP-DEPTH "; 1844 case TopPathReduce: return "TOP-PATH "; 1845 case BotHeightReduce:return "BOT-HEIGHT"; 1846 case BotPathReduce: return "BOT-PATH "; 1847 case NextDefUse: return "DEF-USE "; 1848 case NodeOrder: return "ORDER "; 1849 }; 1850 llvm_unreachable("Unknown reason!"); 1851 } 1852 1853 void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand, 1854 const SchedBoundary &Zone) { 1855 const char *Label = getReasonStr(Cand.Reason); 1856 PressureElement P; 1857 unsigned ResIdx = 0; 1858 unsigned Latency = 0; 1859 switch (Cand.Reason) { 1860 default: 1861 break; 1862 case SingleExcess: 1863 P = Cand.RPDelta.Excess; 1864 break; 1865 case SingleCritical: 1866 P = Cand.RPDelta.CriticalMax; 1867 break; 1868 case SingleMax: 1869 P = Cand.RPDelta.CurrentMax; 1870 break; 1871 case ResourceReduce: 1872 ResIdx = Cand.Policy.ReduceResIdx; 1873 break; 1874 case ResourceDemand: 1875 ResIdx = Cand.Policy.DemandResIdx; 1876 break; 1877 case TopDepthReduce: 1878 Latency = Cand.SU->getDepth(); 1879 break; 1880 case TopPathReduce: 1881 Latency = Cand.SU->getHeight(); 1882 break; 1883 case BotHeightReduce: 1884 Latency = Cand.SU->getHeight(); 1885 break; 1886 case BotPathReduce: 1887 Latency = Cand.SU->getDepth(); 1888 break; 1889 } 1890 dbgs() << Label << " " << Zone.Available.getName() << " "; 1891 if (P.isValid()) 1892 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease 1893 << " "; 1894 else 1895 dbgs() << " "; 1896 if (ResIdx) 1897 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " "; 1898 else 1899 dbgs() << " "; 1900 if (Latency) 1901 dbgs() << Latency << " cycles "; 1902 else 1903 dbgs() << " "; 1904 Cand.SU->dump(DAG); 1905 } 1906 #endif 1907 1908 /// Pick the best candidate from the top queue. 1909 /// 1910 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during 1911 /// DAG building. To adjust for the current scheduling location we need to 1912 /// maintain the number of vreg uses remaining to be top-scheduled. 1913 void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone, 1914 const RegPressureTracker &RPTracker, 1915 SchedCandidate &Cand) { 1916 ReadyQueue &Q = Zone.Available; 1917 1918 DEBUG(Q.dump()); 1919 1920 // getMaxPressureDelta temporarily modifies the tracker. 1921 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker); 1922 1923 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) { 1924 1925 SchedCandidate TryCand(Cand.Policy); 1926 TryCand.SU = *I; 1927 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker); 1928 if (TryCand.Reason != NoCand) { 1929 // Initialize resource delta if needed in case future heuristics query it. 1930 if (TryCand.ResDelta == SchedResourceDelta()) 1931 TryCand.initResourceDelta(DAG, SchedModel); 1932 Cand.setBest(TryCand); 1933 DEBUG(traceCandidate(Cand, Zone)); 1934 } 1935 } 1936 } 1937 1938 static void tracePick(const ConvergingScheduler::SchedCandidate &Cand, 1939 bool IsTop) { 1940 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot") 1941 << " SU(" << Cand.SU->NodeNum << ") " 1942 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n'); 1943 } 1944 1945 /// Pick the best candidate node from either the top or bottom queue. 1946 SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) { 1947 // Schedule as far as possible in the direction of no choice. This is most 1948 // efficient, but also provides the best heuristics for CriticalPSets. 1949 if (SUnit *SU = Bot.pickOnlyChoice()) { 1950 IsTopNode = false; 1951 return SU; 1952 } 1953 if (SUnit *SU = Top.pickOnlyChoice()) { 1954 IsTopNode = true; 1955 return SU; 1956 } 1957 CandPolicy NoPolicy; 1958 SchedCandidate BotCand(NoPolicy); 1959 SchedCandidate TopCand(NoPolicy); 1960 checkResourceLimits(TopCand, BotCand); 1961 1962 // Prefer bottom scheduling when heuristics are silent. 1963 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand); 1964 assert(BotCand.Reason != NoCand && "failed to find the first candidate"); 1965 1966 // If either Q has a single candidate that provides the least increase in 1967 // Excess pressure, we can immediately schedule from that Q. 1968 // 1969 // RegionCriticalPSets summarizes the pressure within the scheduled region and 1970 // affects picking from either Q. If scheduling in one direction must 1971 // increase pressure for one of the excess PSets, then schedule in that 1972 // direction first to provide more freedom in the other direction. 1973 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) { 1974 IsTopNode = false; 1975 tracePick(BotCand, IsTopNode); 1976 return BotCand.SU; 1977 } 1978 // Check if the top Q has a better candidate. 1979 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand); 1980 assert(TopCand.Reason != NoCand && "failed to find the first candidate"); 1981 1982 // If either Q has a single candidate that minimizes pressure above the 1983 // original region's pressure pick it. 1984 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) { 1985 if (TopCand.Reason < BotCand.Reason) { 1986 IsTopNode = true; 1987 tracePick(TopCand, IsTopNode); 1988 return TopCand.SU; 1989 } 1990 IsTopNode = false; 1991 tracePick(BotCand, IsTopNode); 1992 return BotCand.SU; 1993 } 1994 // Check for a salient pressure difference and pick the best from either side. 1995 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) { 1996 IsTopNode = true; 1997 tracePick(TopCand, IsTopNode); 1998 return TopCand.SU; 1999 } 2000 // Otherwise prefer the bottom candidate, in node order if all else failed. 2001 if (TopCand.Reason < BotCand.Reason) { 2002 IsTopNode = true; 2003 tracePick(TopCand, IsTopNode); 2004 return TopCand.SU; 2005 } 2006 IsTopNode = false; 2007 tracePick(BotCand, IsTopNode); 2008 return BotCand.SU; 2009 } 2010 2011 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy. 2012 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) { 2013 if (DAG->top() == DAG->bottom()) { 2014 assert(Top.Available.empty() && Top.Pending.empty() && 2015 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage"); 2016 return NULL; 2017 } 2018 SUnit *SU; 2019 do { 2020 if (ForceTopDown) { 2021 SU = Top.pickOnlyChoice(); 2022 if (!SU) { 2023 CandPolicy NoPolicy; 2024 SchedCandidate TopCand(NoPolicy); 2025 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand); 2026 assert(TopCand.Reason != NoCand && "failed to find the first candidate"); 2027 SU = TopCand.SU; 2028 } 2029 IsTopNode = true; 2030 } 2031 else if (ForceBottomUp) { 2032 SU = Bot.pickOnlyChoice(); 2033 if (!SU) { 2034 CandPolicy NoPolicy; 2035 SchedCandidate BotCand(NoPolicy); 2036 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand); 2037 assert(BotCand.Reason != NoCand && "failed to find the first candidate"); 2038 SU = BotCand.SU; 2039 } 2040 IsTopNode = false; 2041 } 2042 else { 2043 SU = pickNodeBidirectional(IsTopNode); 2044 } 2045 } while (SU->isScheduled); 2046 2047 if (SU->isTopReady()) 2048 Top.removeReady(SU); 2049 if (SU->isBottomReady()) 2050 Bot.removeReady(SU); 2051 2052 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom") 2053 << " Scheduling Instruction in cycle " 2054 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n'; 2055 SU->dump(DAG)); 2056 return SU; 2057 } 2058 2059 /// Update the scheduler's state after scheduling a node. This is the same node 2060 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update 2061 /// it's state based on the current cycle before MachineSchedStrategy does. 2062 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) { 2063 if (IsTopNode) { 2064 SU->TopReadyCycle = Top.CurrCycle; 2065 Top.bumpNode(SU); 2066 } 2067 else { 2068 SU->BotReadyCycle = Bot.CurrCycle; 2069 Bot.bumpNode(SU); 2070 } 2071 } 2072 2073 /// Create the standard converging machine scheduler. This will be used as the 2074 /// default scheduler if the target does not set a default. 2075 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) { 2076 assert((!ForceTopDown || !ForceBottomUp) && 2077 "-misched-topdown incompatible with -misched-bottomup"); 2078 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler()); 2079 // Register DAG post-processors. 2080 if (EnableLoadCluster) 2081 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI)); 2082 if (EnableMacroFusion) 2083 DAG->addMutation(new MacroFusion(DAG->TII)); 2084 return DAG; 2085 } 2086 static MachineSchedRegistry 2087 ConvergingSchedRegistry("converge", "Standard converging scheduler.", 2088 createConvergingSched); 2089 2090 //===----------------------------------------------------------------------===// 2091 // ILP Scheduler. Currently for experimental analysis of heuristics. 2092 //===----------------------------------------------------------------------===// 2093 2094 namespace { 2095 /// \brief Order nodes by the ILP metric. 2096 struct ILPOrder { 2097 const SchedDFSResult *DFSResult; 2098 const BitVector *ScheduledTrees; 2099 bool MaximizeILP; 2100 2101 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {} 2102 2103 /// \brief Apply a less-than relation on node priority. 2104 /// 2105 /// (Return true if A comes after B in the Q.) 2106 bool operator()(const SUnit *A, const SUnit *B) const { 2107 unsigned SchedTreeA = DFSResult->getSubtreeID(A); 2108 unsigned SchedTreeB = DFSResult->getSubtreeID(B); 2109 if (SchedTreeA != SchedTreeB) { 2110 // Unscheduled trees have lower priority. 2111 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB)) 2112 return ScheduledTrees->test(SchedTreeB); 2113 2114 // Trees with shallower connections have have lower priority. 2115 if (DFSResult->getSubtreeLevel(SchedTreeA) 2116 != DFSResult->getSubtreeLevel(SchedTreeB)) { 2117 return DFSResult->getSubtreeLevel(SchedTreeA) 2118 < DFSResult->getSubtreeLevel(SchedTreeB); 2119 } 2120 } 2121 if (MaximizeILP) 2122 return DFSResult->getILP(A) < DFSResult->getILP(B); 2123 else 2124 return DFSResult->getILP(A) > DFSResult->getILP(B); 2125 } 2126 }; 2127 2128 /// \brief Schedule based on the ILP metric. 2129 class ILPScheduler : public MachineSchedStrategy { 2130 /// In case all subtrees are eventually connected to a common root through 2131 /// data dependence (e.g. reduction), place an upper limit on their size. 2132 /// 2133 /// FIXME: A subtree limit is generally good, but in the situation commented 2134 /// above, where multiple similar subtrees feed a common root, we should 2135 /// only split at a point where the resulting subtrees will be balanced. 2136 /// (a motivating test case must be found). 2137 static const unsigned SubtreeLimit = 16; 2138 2139 ScheduleDAGMI *DAG; 2140 ILPOrder Cmp; 2141 2142 std::vector<SUnit*> ReadyQ; 2143 public: 2144 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {} 2145 2146 virtual void initialize(ScheduleDAGMI *dag) { 2147 DAG = dag; 2148 DAG->computeDFSResult(); 2149 Cmp.DFSResult = DAG->getDFSResult(); 2150 Cmp.ScheduledTrees = &DAG->getScheduledTrees(); 2151 ReadyQ.clear(); 2152 } 2153 2154 virtual void registerRoots() { 2155 // Restore the heap in ReadyQ with the updated DFS results. 2156 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 2157 } 2158 2159 /// Implement MachineSchedStrategy interface. 2160 /// ----------------------------------------- 2161 2162 /// Callback to select the highest priority node from the ready Q. 2163 virtual SUnit *pickNode(bool &IsTopNode) { 2164 if (ReadyQ.empty()) return NULL; 2165 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 2166 SUnit *SU = ReadyQ.back(); 2167 ReadyQ.pop_back(); 2168 IsTopNode = false; 2169 DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): " 2170 << *SU->getInstr() 2171 << " ILP: " << DAG->getDFSResult()->getILP(SU) 2172 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @" 2173 << DAG->getDFSResult()->getSubtreeLevel( 2174 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'); 2175 return SU; 2176 } 2177 2178 /// \brief Scheduler callback to notify that a new subtree is scheduled. 2179 virtual void scheduleTree(unsigned SubtreeID) { 2180 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 2181 } 2182 2183 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify 2184 /// DFSResults, and resort the priority Q. 2185 virtual void schedNode(SUnit *SU, bool IsTopNode) { 2186 assert(!IsTopNode && "SchedDFSResult needs bottom-up"); 2187 } 2188 2189 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ } 2190 2191 virtual void releaseBottomNode(SUnit *SU) { 2192 ReadyQ.push_back(SU); 2193 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 2194 } 2195 }; 2196 } // namespace 2197 2198 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) { 2199 return new ScheduleDAGMI(C, new ILPScheduler(true)); 2200 } 2201 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) { 2202 return new ScheduleDAGMI(C, new ILPScheduler(false)); 2203 } 2204 static MachineSchedRegistry ILPMaxRegistry( 2205 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler); 2206 static MachineSchedRegistry ILPMinRegistry( 2207 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler); 2208 2209 //===----------------------------------------------------------------------===// 2210 // Machine Instruction Shuffler for Correctness Testing 2211 //===----------------------------------------------------------------------===// 2212 2213 #ifndef NDEBUG 2214 namespace { 2215 /// Apply a less-than relation on the node order, which corresponds to the 2216 /// instruction order prior to scheduling. IsReverse implements greater-than. 2217 template<bool IsReverse> 2218 struct SUnitOrder { 2219 bool operator()(SUnit *A, SUnit *B) const { 2220 if (IsReverse) 2221 return A->NodeNum > B->NodeNum; 2222 else 2223 return A->NodeNum < B->NodeNum; 2224 } 2225 }; 2226 2227 /// Reorder instructions as much as possible. 2228 class InstructionShuffler : public MachineSchedStrategy { 2229 bool IsAlternating; 2230 bool IsTopDown; 2231 2232 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority 2233 // gives nodes with a higher number higher priority causing the latest 2234 // instructions to be scheduled first. 2235 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> > 2236 TopQ; 2237 // When scheduling bottom-up, use greater-than as the queue priority. 2238 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> > 2239 BottomQ; 2240 public: 2241 InstructionShuffler(bool alternate, bool topdown) 2242 : IsAlternating(alternate), IsTopDown(topdown) {} 2243 2244 virtual void initialize(ScheduleDAGMI *) { 2245 TopQ.clear(); 2246 BottomQ.clear(); 2247 } 2248 2249 /// Implement MachineSchedStrategy interface. 2250 /// ----------------------------------------- 2251 2252 virtual SUnit *pickNode(bool &IsTopNode) { 2253 SUnit *SU; 2254 if (IsTopDown) { 2255 do { 2256 if (TopQ.empty()) return NULL; 2257 SU = TopQ.top(); 2258 TopQ.pop(); 2259 } while (SU->isScheduled); 2260 IsTopNode = true; 2261 } 2262 else { 2263 do { 2264 if (BottomQ.empty()) return NULL; 2265 SU = BottomQ.top(); 2266 BottomQ.pop(); 2267 } while (SU->isScheduled); 2268 IsTopNode = false; 2269 } 2270 if (IsAlternating) 2271 IsTopDown = !IsTopDown; 2272 return SU; 2273 } 2274 2275 virtual void schedNode(SUnit *SU, bool IsTopNode) {} 2276 2277 virtual void releaseTopNode(SUnit *SU) { 2278 TopQ.push(SU); 2279 } 2280 virtual void releaseBottomNode(SUnit *SU) { 2281 BottomQ.push(SU); 2282 } 2283 }; 2284 } // namespace 2285 2286 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) { 2287 bool Alternate = !ForceTopDown && !ForceBottomUp; 2288 bool TopDown = !ForceBottomUp; 2289 assert((TopDown || !ForceTopDown) && 2290 "-misched-topdown incompatible with -misched-bottomup"); 2291 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown)); 2292 } 2293 static MachineSchedRegistry ShufflerRegistry( 2294 "shuffle", "Shuffle machine instructions alternating directions", 2295 createInstructionShuffler); 2296 #endif // !NDEBUG 2297