ScheduleDAG.cpp revision 239462
1//===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This implements the ScheduleDAG class, which is a base class used by 11// scheduling implementation classes. 12// 13//===----------------------------------------------------------------------===// 14 15#define DEBUG_TYPE "pre-RA-sched" 16#include "llvm/CodeGen/ScheduleDAG.h" 17#include "llvm/CodeGen/ScheduleHazardRecognizer.h" 18#include "llvm/CodeGen/SelectionDAGNodes.h" 19#include "llvm/Target/TargetMachine.h" 20#include "llvm/Target/TargetInstrInfo.h" 21#include "llvm/Target/TargetRegisterInfo.h" 22#include "llvm/Support/CommandLine.h" 23#include "llvm/Support/Debug.h" 24#include "llvm/Support/raw_ostream.h" 25#include <climits> 26using namespace llvm; 27 28#ifndef NDEBUG 29static cl::opt<bool> StressSchedOpt( 30 "stress-sched", cl::Hidden, cl::init(false), 31 cl::desc("Stress test instruction scheduling")); 32#endif 33 34void SchedulingPriorityQueue::anchor() { } 35 36ScheduleDAG::ScheduleDAG(MachineFunction &mf) 37 : TM(mf.getTarget()), 38 TII(TM.getInstrInfo()), 39 TRI(TM.getRegisterInfo()), 40 MF(mf), MRI(mf.getRegInfo()), 41 EntrySU(), ExitSU() { 42#ifndef NDEBUG 43 StressSched = StressSchedOpt; 44#endif 45} 46 47ScheduleDAG::~ScheduleDAG() {} 48 49/// Clear the DAG state (e.g. between scheduling regions). 50void ScheduleDAG::clearDAG() { 51 SUnits.clear(); 52 EntrySU = SUnit(); 53 ExitSU = SUnit(); 54} 55 56/// getInstrDesc helper to handle SDNodes. 57const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const { 58 if (!Node || !Node->isMachineOpcode()) return NULL; 59 return &TII->get(Node->getMachineOpcode()); 60} 61 62/// addPred - This adds the specified edge as a pred of the current node if 63/// not already. It also adds the current node as a successor of the 64/// specified node. 65bool SUnit::addPred(const SDep &D) { 66 // If this node already has this depenence, don't add a redundant one. 67 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end(); 68 I != E; ++I) { 69 if (I->overlaps(D)) { 70 // Extend the latency if needed. Equivalent to removePred(I) + addPred(D). 71 if (I->getLatency() < D.getLatency()) { 72 SUnit *PredSU = I->getSUnit(); 73 // Find the corresponding successor in N. 74 SDep ForwardD = *I; 75 ForwardD.setSUnit(this); 76 for (SmallVector<SDep, 4>::iterator II = PredSU->Succs.begin(), 77 EE = PredSU->Succs.end(); II != EE; ++II) { 78 if (*II == ForwardD) { 79 II->setLatency(D.getLatency()); 80 break; 81 } 82 } 83 I->setLatency(D.getLatency()); 84 } 85 return false; 86 } 87 } 88 // Now add a corresponding succ to N. 89 SDep P = D; 90 P.setSUnit(this); 91 SUnit *N = D.getSUnit(); 92 // Update the bookkeeping. 93 if (D.getKind() == SDep::Data) { 94 assert(NumPreds < UINT_MAX && "NumPreds will overflow!"); 95 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!"); 96 ++NumPreds; 97 ++N->NumSuccs; 98 } 99 if (!N->isScheduled) { 100 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!"); 101 ++NumPredsLeft; 102 } 103 if (!isScheduled) { 104 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!"); 105 ++N->NumSuccsLeft; 106 } 107 Preds.push_back(D); 108 N->Succs.push_back(P); 109 if (P.getLatency() != 0) { 110 this->setDepthDirty(); 111 N->setHeightDirty(); 112 } 113 return true; 114} 115 116/// removePred - This removes the specified edge as a pred of the current 117/// node if it exists. It also removes the current node as a successor of 118/// the specified node. 119void SUnit::removePred(const SDep &D) { 120 // Find the matching predecessor. 121 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end(); 122 I != E; ++I) 123 if (*I == D) { 124 bool FoundSucc = false; 125 // Find the corresponding successor in N. 126 SDep P = D; 127 P.setSUnit(this); 128 SUnit *N = D.getSUnit(); 129 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(), 130 EE = N->Succs.end(); II != EE; ++II) 131 if (*II == P) { 132 FoundSucc = true; 133 N->Succs.erase(II); 134 break; 135 } 136 assert(FoundSucc && "Mismatching preds / succs lists!"); 137 (void)FoundSucc; 138 Preds.erase(I); 139 // Update the bookkeeping. 140 if (P.getKind() == SDep::Data) { 141 assert(NumPreds > 0 && "NumPreds will underflow!"); 142 assert(N->NumSuccs > 0 && "NumSuccs will underflow!"); 143 --NumPreds; 144 --N->NumSuccs; 145 } 146 if (!N->isScheduled) { 147 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!"); 148 --NumPredsLeft; 149 } 150 if (!isScheduled) { 151 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!"); 152 --N->NumSuccsLeft; 153 } 154 if (P.getLatency() != 0) { 155 this->setDepthDirty(); 156 N->setHeightDirty(); 157 } 158 return; 159 } 160} 161 162void SUnit::setDepthDirty() { 163 if (!isDepthCurrent) return; 164 SmallVector<SUnit*, 8> WorkList; 165 WorkList.push_back(this); 166 do { 167 SUnit *SU = WorkList.pop_back_val(); 168 SU->isDepthCurrent = false; 169 for (SUnit::const_succ_iterator I = SU->Succs.begin(), 170 E = SU->Succs.end(); I != E; ++I) { 171 SUnit *SuccSU = I->getSUnit(); 172 if (SuccSU->isDepthCurrent) 173 WorkList.push_back(SuccSU); 174 } 175 } while (!WorkList.empty()); 176} 177 178void SUnit::setHeightDirty() { 179 if (!isHeightCurrent) return; 180 SmallVector<SUnit*, 8> WorkList; 181 WorkList.push_back(this); 182 do { 183 SUnit *SU = WorkList.pop_back_val(); 184 SU->isHeightCurrent = false; 185 for (SUnit::const_pred_iterator I = SU->Preds.begin(), 186 E = SU->Preds.end(); I != E; ++I) { 187 SUnit *PredSU = I->getSUnit(); 188 if (PredSU->isHeightCurrent) 189 WorkList.push_back(PredSU); 190 } 191 } while (!WorkList.empty()); 192} 193 194/// setDepthToAtLeast - Update this node's successors to reflect the 195/// fact that this node's depth just increased. 196/// 197void SUnit::setDepthToAtLeast(unsigned NewDepth) { 198 if (NewDepth <= getDepth()) 199 return; 200 setDepthDirty(); 201 Depth = NewDepth; 202 isDepthCurrent = true; 203} 204 205/// setHeightToAtLeast - Update this node's predecessors to reflect the 206/// fact that this node's height just increased. 207/// 208void SUnit::setHeightToAtLeast(unsigned NewHeight) { 209 if (NewHeight <= getHeight()) 210 return; 211 setHeightDirty(); 212 Height = NewHeight; 213 isHeightCurrent = true; 214} 215 216/// ComputeDepth - Calculate the maximal path from the node to the exit. 217/// 218void SUnit::ComputeDepth() { 219 SmallVector<SUnit*, 8> WorkList; 220 WorkList.push_back(this); 221 do { 222 SUnit *Cur = WorkList.back(); 223 224 bool Done = true; 225 unsigned MaxPredDepth = 0; 226 for (SUnit::const_pred_iterator I = Cur->Preds.begin(), 227 E = Cur->Preds.end(); I != E; ++I) { 228 SUnit *PredSU = I->getSUnit(); 229 if (PredSU->isDepthCurrent) 230 MaxPredDepth = std::max(MaxPredDepth, 231 PredSU->Depth + I->getLatency()); 232 else { 233 Done = false; 234 WorkList.push_back(PredSU); 235 } 236 } 237 238 if (Done) { 239 WorkList.pop_back(); 240 if (MaxPredDepth != Cur->Depth) { 241 Cur->setDepthDirty(); 242 Cur->Depth = MaxPredDepth; 243 } 244 Cur->isDepthCurrent = true; 245 } 246 } while (!WorkList.empty()); 247} 248 249/// ComputeHeight - Calculate the maximal path from the node to the entry. 250/// 251void SUnit::ComputeHeight() { 252 SmallVector<SUnit*, 8> WorkList; 253 WorkList.push_back(this); 254 do { 255 SUnit *Cur = WorkList.back(); 256 257 bool Done = true; 258 unsigned MaxSuccHeight = 0; 259 for (SUnit::const_succ_iterator I = Cur->Succs.begin(), 260 E = Cur->Succs.end(); I != E; ++I) { 261 SUnit *SuccSU = I->getSUnit(); 262 if (SuccSU->isHeightCurrent) 263 MaxSuccHeight = std::max(MaxSuccHeight, 264 SuccSU->Height + I->getLatency()); 265 else { 266 Done = false; 267 WorkList.push_back(SuccSU); 268 } 269 } 270 271 if (Done) { 272 WorkList.pop_back(); 273 if (MaxSuccHeight != Cur->Height) { 274 Cur->setHeightDirty(); 275 Cur->Height = MaxSuccHeight; 276 } 277 Cur->isHeightCurrent = true; 278 } 279 } while (!WorkList.empty()); 280} 281 282/// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or 283/// a group of nodes flagged together. 284void SUnit::dump(const ScheduleDAG *G) const { 285 dbgs() << "SU(" << NodeNum << "): "; 286 G->dumpNode(this); 287} 288 289void SUnit::dumpAll(const ScheduleDAG *G) const { 290 dump(G); 291 292 dbgs() << " # preds left : " << NumPredsLeft << "\n"; 293 dbgs() << " # succs left : " << NumSuccsLeft << "\n"; 294 dbgs() << " # rdefs left : " << NumRegDefsLeft << "\n"; 295 dbgs() << " Latency : " << Latency << "\n"; 296 dbgs() << " Depth : " << Depth << "\n"; 297 dbgs() << " Height : " << Height << "\n"; 298 299 if (Preds.size() != 0) { 300 dbgs() << " Predecessors:\n"; 301 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end(); 302 I != E; ++I) { 303 dbgs() << " "; 304 switch (I->getKind()) { 305 case SDep::Data: dbgs() << "val "; break; 306 case SDep::Anti: dbgs() << "anti"; break; 307 case SDep::Output: dbgs() << "out "; break; 308 case SDep::Order: dbgs() << "ch "; break; 309 } 310 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")"; 311 if (I->isArtificial()) 312 dbgs() << " *"; 313 dbgs() << ": Latency=" << I->getLatency(); 314 if (I->isAssignedRegDep()) 315 dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI); 316 dbgs() << "\n"; 317 } 318 } 319 if (Succs.size() != 0) { 320 dbgs() << " Successors:\n"; 321 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end(); 322 I != E; ++I) { 323 dbgs() << " "; 324 switch (I->getKind()) { 325 case SDep::Data: dbgs() << "val "; break; 326 case SDep::Anti: dbgs() << "anti"; break; 327 case SDep::Output: dbgs() << "out "; break; 328 case SDep::Order: dbgs() << "ch "; break; 329 } 330 dbgs() << "SU(" << I->getSUnit()->NodeNum << ")"; 331 if (I->isArtificial()) 332 dbgs() << " *"; 333 dbgs() << ": Latency=" << I->getLatency(); 334 dbgs() << "\n"; 335 } 336 } 337 dbgs() << "\n"; 338} 339 340#ifndef NDEBUG 341/// VerifyScheduledDAG - Verify that all SUnits were scheduled and that 342/// their state is consistent. Return the number of scheduled nodes. 343/// 344unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) { 345 bool AnyNotSched = false; 346 unsigned DeadNodes = 0; 347 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) { 348 if (!SUnits[i].isScheduled) { 349 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) { 350 ++DeadNodes; 351 continue; 352 } 353 if (!AnyNotSched) 354 dbgs() << "*** Scheduling failed! ***\n"; 355 SUnits[i].dump(this); 356 dbgs() << "has not been scheduled!\n"; 357 AnyNotSched = true; 358 } 359 if (SUnits[i].isScheduled && 360 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) > 361 unsigned(INT_MAX)) { 362 if (!AnyNotSched) 363 dbgs() << "*** Scheduling failed! ***\n"; 364 SUnits[i].dump(this); 365 dbgs() << "has an unexpected " 366 << (isBottomUp ? "Height" : "Depth") << " value!\n"; 367 AnyNotSched = true; 368 } 369 if (isBottomUp) { 370 if (SUnits[i].NumSuccsLeft != 0) { 371 if (!AnyNotSched) 372 dbgs() << "*** Scheduling failed! ***\n"; 373 SUnits[i].dump(this); 374 dbgs() << "has successors left!\n"; 375 AnyNotSched = true; 376 } 377 } else { 378 if (SUnits[i].NumPredsLeft != 0) { 379 if (!AnyNotSched) 380 dbgs() << "*** Scheduling failed! ***\n"; 381 SUnits[i].dump(this); 382 dbgs() << "has predecessors left!\n"; 383 AnyNotSched = true; 384 } 385 } 386 } 387 assert(!AnyNotSched); 388 return SUnits.size() - DeadNodes; 389} 390#endif 391 392/// InitDAGTopologicalSorting - create the initial topological 393/// ordering from the DAG to be scheduled. 394/// 395/// The idea of the algorithm is taken from 396/// "Online algorithms for managing the topological order of 397/// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly 398/// This is the MNR algorithm, which was first introduced by 399/// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in 400/// "Maintaining a topological order under edge insertions". 401/// 402/// Short description of the algorithm: 403/// 404/// Topological ordering, ord, of a DAG maps each node to a topological 405/// index so that for all edges X->Y it is the case that ord(X) < ord(Y). 406/// 407/// This means that if there is a path from the node X to the node Z, 408/// then ord(X) < ord(Z). 409/// 410/// This property can be used to check for reachability of nodes: 411/// if Z is reachable from X, then an insertion of the edge Z->X would 412/// create a cycle. 413/// 414/// The algorithm first computes a topological ordering for the DAG by 415/// initializing the Index2Node and Node2Index arrays and then tries to keep 416/// the ordering up-to-date after edge insertions by reordering the DAG. 417/// 418/// On insertion of the edge X->Y, the algorithm first marks by calling DFS 419/// the nodes reachable from Y, and then shifts them using Shift to lie 420/// immediately after X in Index2Node. 421void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() { 422 unsigned DAGSize = SUnits.size(); 423 std::vector<SUnit*> WorkList; 424 WorkList.reserve(DAGSize); 425 426 Index2Node.resize(DAGSize); 427 Node2Index.resize(DAGSize); 428 429 // Initialize the data structures. 430 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 431 SUnit *SU = &SUnits[i]; 432 int NodeNum = SU->NodeNum; 433 unsigned Degree = SU->Succs.size(); 434 // Temporarily use the Node2Index array as scratch space for degree counts. 435 Node2Index[NodeNum] = Degree; 436 437 // Is it a node without dependencies? 438 if (Degree == 0) { 439 assert(SU->Succs.empty() && "SUnit should have no successors"); 440 // Collect leaf nodes. 441 WorkList.push_back(SU); 442 } 443 } 444 445 int Id = DAGSize; 446 while (!WorkList.empty()) { 447 SUnit *SU = WorkList.back(); 448 WorkList.pop_back(); 449 Allocate(SU->NodeNum, --Id); 450 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); 451 I != E; ++I) { 452 SUnit *SU = I->getSUnit(); 453 if (!--Node2Index[SU->NodeNum]) 454 // If all dependencies of the node are processed already, 455 // then the node can be computed now. 456 WorkList.push_back(SU); 457 } 458 } 459 460 Visited.resize(DAGSize); 461 462#ifndef NDEBUG 463 // Check correctness of the ordering 464 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 465 SUnit *SU = &SUnits[i]; 466 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); 467 I != E; ++I) { 468 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] && 469 "Wrong topological sorting"); 470 } 471 } 472#endif 473} 474 475/// AddPred - Updates the topological ordering to accommodate an edge 476/// to be added from SUnit X to SUnit Y. 477void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) { 478 int UpperBound, LowerBound; 479 LowerBound = Node2Index[Y->NodeNum]; 480 UpperBound = Node2Index[X->NodeNum]; 481 bool HasLoop = false; 482 // Is Ord(X) < Ord(Y) ? 483 if (LowerBound < UpperBound) { 484 // Update the topological order. 485 Visited.reset(); 486 DFS(Y, UpperBound, HasLoop); 487 assert(!HasLoop && "Inserted edge creates a loop!"); 488 // Recompute topological indexes. 489 Shift(Visited, LowerBound, UpperBound); 490 } 491} 492 493/// RemovePred - Updates the topological ordering to accommodate an 494/// an edge to be removed from the specified node N from the predecessors 495/// of the current node M. 496void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) { 497 // InitDAGTopologicalSorting(); 498} 499 500/// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark 501/// all nodes affected by the edge insertion. These nodes will later get new 502/// topological indexes by means of the Shift method. 503void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound, 504 bool &HasLoop) { 505 std::vector<const SUnit*> WorkList; 506 WorkList.reserve(SUnits.size()); 507 508 WorkList.push_back(SU); 509 do { 510 SU = WorkList.back(); 511 WorkList.pop_back(); 512 Visited.set(SU->NodeNum); 513 for (int I = SU->Succs.size()-1; I >= 0; --I) { 514 int s = SU->Succs[I].getSUnit()->NodeNum; 515 if (Node2Index[s] == UpperBound) { 516 HasLoop = true; 517 return; 518 } 519 // Visit successors if not already and in affected region. 520 if (!Visited.test(s) && Node2Index[s] < UpperBound) { 521 WorkList.push_back(SU->Succs[I].getSUnit()); 522 } 523 } 524 } while (!WorkList.empty()); 525} 526 527/// Shift - Renumber the nodes so that the topological ordering is 528/// preserved. 529void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound, 530 int UpperBound) { 531 std::vector<int> L; 532 int shift = 0; 533 int i; 534 535 for (i = LowerBound; i <= UpperBound; ++i) { 536 // w is node at topological index i. 537 int w = Index2Node[i]; 538 if (Visited.test(w)) { 539 // Unmark. 540 Visited.reset(w); 541 L.push_back(w); 542 shift = shift + 1; 543 } else { 544 Allocate(w, i - shift); 545 } 546 } 547 548 for (unsigned j = 0; j < L.size(); ++j) { 549 Allocate(L[j], i - shift); 550 i = i + 1; 551 } 552} 553 554 555/// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will 556/// create a cycle. 557bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) { 558 if (IsReachable(TargetSU, SU)) 559 return true; 560 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); 561 I != E; ++I) 562 if (I->isAssignedRegDep() && 563 IsReachable(TargetSU, I->getSUnit())) 564 return true; 565 return false; 566} 567 568/// IsReachable - Checks if SU is reachable from TargetSU. 569bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU, 570 const SUnit *TargetSU) { 571 // If insertion of the edge SU->TargetSU would create a cycle 572 // then there is a path from TargetSU to SU. 573 int UpperBound, LowerBound; 574 LowerBound = Node2Index[TargetSU->NodeNum]; 575 UpperBound = Node2Index[SU->NodeNum]; 576 bool HasLoop = false; 577 // Is Ord(TargetSU) < Ord(SU) ? 578 if (LowerBound < UpperBound) { 579 Visited.reset(); 580 // There may be a path from TargetSU to SU. Check for it. 581 DFS(TargetSU, UpperBound, HasLoop); 582 } 583 return HasLoop; 584} 585 586/// Allocate - assign the topological index to the node n. 587void ScheduleDAGTopologicalSort::Allocate(int n, int index) { 588 Node2Index[n] = index; 589 Index2Node[index] = n; 590} 591 592ScheduleDAGTopologicalSort:: 593ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits) : SUnits(sunits) {} 594 595ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {} 596