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