1 //===----- ScheduleDAGRRList.cpp - Reg pressure reduction list 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 // This implements bottom-up and top-down register pressure reduction list 11 // schedulers, using standard algorithms. The basic approach uses a priority 12 // queue of available nodes to schedule. One at a time, nodes are taken from 13 // the priority queue (thus in priority order), checked for legality to 14 // schedule, and emitted if legal. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "ScheduleDAGSDNodes.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/CodeGen/ScheduleHazardRecognizer.h" 24 #include "llvm/CodeGen/SchedulerRegistry.h" 25 #include "llvm/CodeGen/SelectionDAGISel.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/InlineAsm.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include "llvm/Target/TargetInstrInfo.h" 32 #include "llvm/Target/TargetLowering.h" 33 #include "llvm/Target/TargetRegisterInfo.h" 34 #include "llvm/Target/TargetSubtargetInfo.h" 35 #include <climits> 36 using namespace llvm; 37 38 #define DEBUG_TYPE "pre-RA-sched" 39 40 STATISTIC(NumBacktracks, "Number of times scheduler backtracked"); 41 STATISTIC(NumUnfolds, "Number of nodes unfolded"); 42 STATISTIC(NumDups, "Number of duplicated nodes"); 43 STATISTIC(NumPRCopies, "Number of physical register copies"); 44 45 static RegisterScheduler 46 burrListDAGScheduler("list-burr", 47 "Bottom-up register reduction list scheduling", 48 createBURRListDAGScheduler); 49 static RegisterScheduler 50 sourceListDAGScheduler("source", 51 "Similar to list-burr but schedules in source " 52 "order when possible", 53 createSourceListDAGScheduler); 54 55 static RegisterScheduler 56 hybridListDAGScheduler("list-hybrid", 57 "Bottom-up register pressure aware list scheduling " 58 "which tries to balance latency and register pressure", 59 createHybridListDAGScheduler); 60 61 static RegisterScheduler 62 ILPListDAGScheduler("list-ilp", 63 "Bottom-up register pressure aware list scheduling " 64 "which tries to balance ILP and register pressure", 65 createILPListDAGScheduler); 66 67 static cl::opt<bool> DisableSchedCycles( 68 "disable-sched-cycles", cl::Hidden, cl::init(false), 69 cl::desc("Disable cycle-level precision during preRA scheduling")); 70 71 // Temporary sched=list-ilp flags until the heuristics are robust. 72 // Some options are also available under sched=list-hybrid. 73 static cl::opt<bool> DisableSchedRegPressure( 74 "disable-sched-reg-pressure", cl::Hidden, cl::init(false), 75 cl::desc("Disable regpressure priority in sched=list-ilp")); 76 static cl::opt<bool> DisableSchedLiveUses( 77 "disable-sched-live-uses", cl::Hidden, cl::init(true), 78 cl::desc("Disable live use priority in sched=list-ilp")); 79 static cl::opt<bool> DisableSchedVRegCycle( 80 "disable-sched-vrcycle", cl::Hidden, cl::init(false), 81 cl::desc("Disable virtual register cycle interference checks")); 82 static cl::opt<bool> DisableSchedPhysRegJoin( 83 "disable-sched-physreg-join", cl::Hidden, cl::init(false), 84 cl::desc("Disable physreg def-use affinity")); 85 static cl::opt<bool> DisableSchedStalls( 86 "disable-sched-stalls", cl::Hidden, cl::init(true), 87 cl::desc("Disable no-stall priority in sched=list-ilp")); 88 static cl::opt<bool> DisableSchedCriticalPath( 89 "disable-sched-critical-path", cl::Hidden, cl::init(false), 90 cl::desc("Disable critical path priority in sched=list-ilp")); 91 static cl::opt<bool> DisableSchedHeight( 92 "disable-sched-height", cl::Hidden, cl::init(false), 93 cl::desc("Disable scheduled-height priority in sched=list-ilp")); 94 static cl::opt<bool> Disable2AddrHack( 95 "disable-2addr-hack", cl::Hidden, cl::init(true), 96 cl::desc("Disable scheduler's two-address hack")); 97 98 static cl::opt<int> MaxReorderWindow( 99 "max-sched-reorder", cl::Hidden, cl::init(6), 100 cl::desc("Number of instructions to allow ahead of the critical path " 101 "in sched=list-ilp")); 102 103 static cl::opt<unsigned> AvgIPC( 104 "sched-avg-ipc", cl::Hidden, cl::init(1), 105 cl::desc("Average inst/cycle whan no target itinerary exists.")); 106 107 namespace { 108 //===----------------------------------------------------------------------===// 109 /// ScheduleDAGRRList - The actual register reduction list scheduler 110 /// implementation. This supports both top-down and bottom-up scheduling. 111 /// 112 class ScheduleDAGRRList : public ScheduleDAGSDNodes { 113 private: 114 /// NeedLatency - True if the scheduler will make use of latency information. 115 /// 116 bool NeedLatency; 117 118 /// AvailableQueue - The priority queue to use for the available SUnits. 119 SchedulingPriorityQueue *AvailableQueue; 120 121 /// PendingQueue - This contains all of the instructions whose operands have 122 /// been issued, but their results are not ready yet (due to the latency of 123 /// the operation). Once the operands becomes available, the instruction is 124 /// added to the AvailableQueue. 125 std::vector<SUnit*> PendingQueue; 126 127 /// HazardRec - The hazard recognizer to use. 128 ScheduleHazardRecognizer *HazardRec; 129 130 /// CurCycle - The current scheduler state corresponds to this cycle. 131 unsigned CurCycle; 132 133 /// MinAvailableCycle - Cycle of the soonest available instruction. 134 unsigned MinAvailableCycle; 135 136 /// IssueCount - Count instructions issued in this cycle 137 /// Currently valid only for bottom-up scheduling. 138 unsigned IssueCount; 139 140 /// LiveRegDefs - A set of physical registers and their definition 141 /// that are "live". These nodes must be scheduled before any other nodes that 142 /// modifies the registers can be scheduled. 143 unsigned NumLiveRegs; 144 std::unique_ptr<SUnit*[]> LiveRegDefs; 145 std::unique_ptr<SUnit*[]> LiveRegGens; 146 147 // Collect interferences between physical register use/defs. 148 // Each interference is an SUnit and set of physical registers. 149 SmallVector<SUnit*, 4> Interferences; 150 typedef DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMapT; 151 LRegsMapT LRegsMap; 152 153 /// Topo - A topological ordering for SUnits which permits fast IsReachable 154 /// and similar queries. 155 ScheduleDAGTopologicalSort Topo; 156 157 // Hack to keep track of the inverse of FindCallSeqStart without more crazy 158 // DAG crawling. 159 DenseMap<SUnit*, SUnit*> CallSeqEndForStart; 160 161 public: 162 ScheduleDAGRRList(MachineFunction &mf, bool needlatency, 163 SchedulingPriorityQueue *availqueue, 164 CodeGenOpt::Level OptLevel) 165 : ScheduleDAGSDNodes(mf), 166 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0), 167 Topo(SUnits, nullptr) { 168 169 const TargetSubtargetInfo &STI = mf.getSubtarget(); 170 if (DisableSchedCycles || !NeedLatency) 171 HazardRec = new ScheduleHazardRecognizer(); 172 else 173 HazardRec = STI.getInstrInfo()->CreateTargetHazardRecognizer(&STI, this); 174 } 175 176 ~ScheduleDAGRRList() override { 177 delete HazardRec; 178 delete AvailableQueue; 179 } 180 181 void Schedule() override; 182 183 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; } 184 185 /// IsReachable - Checks if SU is reachable from TargetSU. 186 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) { 187 return Topo.IsReachable(SU, TargetSU); 188 } 189 190 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will 191 /// create a cycle. 192 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) { 193 return Topo.WillCreateCycle(SU, TargetSU); 194 } 195 196 /// AddPred - adds a predecessor edge to SUnit SU. 197 /// This returns true if this is a new predecessor. 198 /// Updates the topological ordering if required. 199 void AddPred(SUnit *SU, const SDep &D) { 200 Topo.AddPred(SU, D.getSUnit()); 201 SU->addPred(D); 202 } 203 204 /// RemovePred - removes a predecessor edge from SUnit SU. 205 /// This returns true if an edge was removed. 206 /// Updates the topological ordering if required. 207 void RemovePred(SUnit *SU, const SDep &D) { 208 Topo.RemovePred(SU, D.getSUnit()); 209 SU->removePred(D); 210 } 211 212 private: 213 bool isReady(SUnit *SU) { 214 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() || 215 AvailableQueue->isReady(SU); 216 } 217 218 void ReleasePred(SUnit *SU, const SDep *PredEdge); 219 void ReleasePredecessors(SUnit *SU); 220 void ReleasePending(); 221 void AdvanceToCycle(unsigned NextCycle); 222 void AdvancePastStalls(SUnit *SU); 223 void EmitNode(SUnit *SU); 224 void ScheduleNodeBottomUp(SUnit*); 225 void CapturePred(SDep *PredEdge); 226 void UnscheduleNodeBottomUp(SUnit*); 227 void RestoreHazardCheckerBottomUp(); 228 void BacktrackBottomUp(SUnit*, SUnit*); 229 SUnit *TryUnfoldSU(SUnit *); 230 SUnit *CopyAndMoveSuccessors(SUnit*); 231 void InsertCopiesAndMoveSuccs(SUnit*, unsigned, 232 const TargetRegisterClass*, 233 const TargetRegisterClass*, 234 SmallVectorImpl<SUnit*>&); 235 bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&); 236 237 void releaseInterferences(unsigned Reg = 0); 238 239 SUnit *PickNodeToScheduleBottomUp(); 240 void ListScheduleBottomUp(); 241 242 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it. 243 /// Updates the topological ordering if required. 244 SUnit *CreateNewSUnit(SDNode *N) { 245 unsigned NumSUnits = SUnits.size(); 246 SUnit *NewNode = newSUnit(N); 247 // Update the topological ordering. 248 if (NewNode->NodeNum >= NumSUnits) 249 Topo.InitDAGTopologicalSorting(); 250 return NewNode; 251 } 252 253 /// CreateClone - Creates a new SUnit from an existing one. 254 /// Updates the topological ordering if required. 255 SUnit *CreateClone(SUnit *N) { 256 unsigned NumSUnits = SUnits.size(); 257 SUnit *NewNode = Clone(N); 258 // Update the topological ordering. 259 if (NewNode->NodeNum >= NumSUnits) 260 Topo.InitDAGTopologicalSorting(); 261 return NewNode; 262 } 263 264 /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't 265 /// need actual latency information but the hybrid scheduler does. 266 bool forceUnitLatencies() const override { 267 return !NeedLatency; 268 } 269 }; 270 } // end anonymous namespace 271 272 /// GetCostForDef - Looks up the register class and cost for a given definition. 273 /// Typically this just means looking up the representative register class, 274 /// but for untyped values (MVT::Untyped) it means inspecting the node's 275 /// opcode to determine what register class is being generated. 276 static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos, 277 const TargetLowering *TLI, 278 const TargetInstrInfo *TII, 279 const TargetRegisterInfo *TRI, 280 unsigned &RegClass, unsigned &Cost, 281 const MachineFunction &MF) { 282 MVT VT = RegDefPos.GetValue(); 283 284 // Special handling for untyped values. These values can only come from 285 // the expansion of custom DAG-to-DAG patterns. 286 if (VT == MVT::Untyped) { 287 const SDNode *Node = RegDefPos.GetNode(); 288 289 // Special handling for CopyFromReg of untyped values. 290 if (!Node->isMachineOpcode() && Node->getOpcode() == ISD::CopyFromReg) { 291 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg(); 292 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(Reg); 293 RegClass = RC->getID(); 294 Cost = 1; 295 return; 296 } 297 298 unsigned Opcode = Node->getMachineOpcode(); 299 if (Opcode == TargetOpcode::REG_SEQUENCE) { 300 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue(); 301 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx); 302 RegClass = RC->getID(); 303 Cost = 1; 304 return; 305 } 306 307 unsigned Idx = RegDefPos.GetIdx(); 308 const MCInstrDesc Desc = TII->get(Opcode); 309 const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI, MF); 310 RegClass = RC->getID(); 311 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a 312 // better way to determine it. 313 Cost = 1; 314 } else { 315 RegClass = TLI->getRepRegClassFor(VT)->getID(); 316 Cost = TLI->getRepRegClassCostFor(VT); 317 } 318 } 319 320 /// Schedule - Schedule the DAG using list scheduling. 321 void ScheduleDAGRRList::Schedule() { 322 DEBUG(dbgs() 323 << "********** List Scheduling BB#" << BB->getNumber() 324 << " '" << BB->getName() << "' **********\n"); 325 326 CurCycle = 0; 327 IssueCount = 0; 328 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX; 329 NumLiveRegs = 0; 330 // Allocate slots for each physical register, plus one for a special register 331 // to track the virtual resource of a calling sequence. 332 LiveRegDefs.reset(new SUnit*[TRI->getNumRegs() + 1]()); 333 LiveRegGens.reset(new SUnit*[TRI->getNumRegs() + 1]()); 334 CallSeqEndForStart.clear(); 335 assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences"); 336 337 // Build the scheduling graph. 338 BuildSchedGraph(nullptr); 339 340 DEBUG(for (SUnit &SU : SUnits) 341 SU.dumpAll(this)); 342 Topo.InitDAGTopologicalSorting(); 343 344 AvailableQueue->initNodes(SUnits); 345 346 HazardRec->Reset(); 347 348 // Execute the actual scheduling loop. 349 ListScheduleBottomUp(); 350 351 AvailableQueue->releaseState(); 352 353 DEBUG({ 354 dbgs() << "*** Final schedule ***\n"; 355 dumpSchedule(); 356 dbgs() << '\n'; 357 }); 358 } 359 360 //===----------------------------------------------------------------------===// 361 // Bottom-Up Scheduling 362 //===----------------------------------------------------------------------===// 363 364 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to 365 /// the AvailableQueue if the count reaches zero. Also update its cycle bound. 366 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) { 367 SUnit *PredSU = PredEdge->getSUnit(); 368 369 #ifndef NDEBUG 370 if (PredSU->NumSuccsLeft == 0) { 371 dbgs() << "*** Scheduling failed! ***\n"; 372 PredSU->dump(this); 373 dbgs() << " has been released too many times!\n"; 374 llvm_unreachable(nullptr); 375 } 376 #endif 377 --PredSU->NumSuccsLeft; 378 379 if (!forceUnitLatencies()) { 380 // Updating predecessor's height. This is now the cycle when the 381 // predecessor can be scheduled without causing a pipeline stall. 382 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency()); 383 } 384 385 // If all the node's successors are scheduled, this node is ready 386 // to be scheduled. Ignore the special EntrySU node. 387 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) { 388 PredSU->isAvailable = true; 389 390 unsigned Height = PredSU->getHeight(); 391 if (Height < MinAvailableCycle) 392 MinAvailableCycle = Height; 393 394 if (isReady(PredSU)) { 395 AvailableQueue->push(PredSU); 396 } 397 // CapturePred and others may have left the node in the pending queue, avoid 398 // adding it twice. 399 else if (!PredSU->isPending) { 400 PredSU->isPending = true; 401 PendingQueue.push_back(PredSU); 402 } 403 } 404 } 405 406 /// IsChainDependent - Test if Outer is reachable from Inner through 407 /// chain dependencies. 408 static bool IsChainDependent(SDNode *Outer, SDNode *Inner, 409 unsigned NestLevel, 410 const TargetInstrInfo *TII) { 411 SDNode *N = Outer; 412 for (;;) { 413 if (N == Inner) 414 return true; 415 // For a TokenFactor, examine each operand. There may be multiple ways 416 // to get to the CALLSEQ_BEGIN, but we need to find the path with the 417 // most nesting in order to ensure that we find the corresponding match. 418 if (N->getOpcode() == ISD::TokenFactor) { 419 for (const SDValue &Op : N->op_values()) 420 if (IsChainDependent(Op.getNode(), Inner, NestLevel, TII)) 421 return true; 422 return false; 423 } 424 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END. 425 if (N->isMachineOpcode()) { 426 if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) { 427 ++NestLevel; 428 } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) { 429 if (NestLevel == 0) 430 return false; 431 --NestLevel; 432 } 433 } 434 // Otherwise, find the chain and continue climbing. 435 for (const SDValue &Op : N->op_values()) 436 if (Op.getValueType() == MVT::Other) { 437 N = Op.getNode(); 438 goto found_chain_operand; 439 } 440 return false; 441 found_chain_operand:; 442 if (N->getOpcode() == ISD::EntryToken) 443 return false; 444 } 445 } 446 447 /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate 448 /// the corresponding (lowered) CALLSEQ_BEGIN node. 449 /// 450 /// NestLevel and MaxNested are used in recursion to indcate the current level 451 /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum 452 /// level seen so far. 453 /// 454 /// TODO: It would be better to give CALLSEQ_END an explicit operand to point 455 /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it. 456 static SDNode * 457 FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest, 458 const TargetInstrInfo *TII) { 459 for (;;) { 460 // For a TokenFactor, examine each operand. There may be multiple ways 461 // to get to the CALLSEQ_BEGIN, but we need to find the path with the 462 // most nesting in order to ensure that we find the corresponding match. 463 if (N->getOpcode() == ISD::TokenFactor) { 464 SDNode *Best = nullptr; 465 unsigned BestMaxNest = MaxNest; 466 for (const SDValue &Op : N->op_values()) { 467 unsigned MyNestLevel = NestLevel; 468 unsigned MyMaxNest = MaxNest; 469 if (SDNode *New = FindCallSeqStart(Op.getNode(), 470 MyNestLevel, MyMaxNest, TII)) 471 if (!Best || (MyMaxNest > BestMaxNest)) { 472 Best = New; 473 BestMaxNest = MyMaxNest; 474 } 475 } 476 assert(Best); 477 MaxNest = BestMaxNest; 478 return Best; 479 } 480 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END. 481 if (N->isMachineOpcode()) { 482 if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) { 483 ++NestLevel; 484 MaxNest = std::max(MaxNest, NestLevel); 485 } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) { 486 assert(NestLevel != 0); 487 --NestLevel; 488 if (NestLevel == 0) 489 return N; 490 } 491 } 492 // Otherwise, find the chain and continue climbing. 493 for (const SDValue &Op : N->op_values()) 494 if (Op.getValueType() == MVT::Other) { 495 N = Op.getNode(); 496 goto found_chain_operand; 497 } 498 return nullptr; 499 found_chain_operand:; 500 if (N->getOpcode() == ISD::EntryToken) 501 return nullptr; 502 } 503 } 504 505 /// Call ReleasePred for each predecessor, then update register live def/gen. 506 /// Always update LiveRegDefs for a register dependence even if the current SU 507 /// also defines the register. This effectively create one large live range 508 /// across a sequence of two-address node. This is important because the 509 /// entire chain must be scheduled together. Example: 510 /// 511 /// flags = (3) add 512 /// flags = (2) addc flags 513 /// flags = (1) addc flags 514 /// 515 /// results in 516 /// 517 /// LiveRegDefs[flags] = 3 518 /// LiveRegGens[flags] = 1 519 /// 520 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid 521 /// interference on flags. 522 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) { 523 // Bottom up: release predecessors 524 for (SDep &Pred : SU->Preds) { 525 ReleasePred(SU, &Pred); 526 if (Pred.isAssignedRegDep()) { 527 // This is a physical register dependency and it's impossible or 528 // expensive to copy the register. Make sure nothing that can 529 // clobber the register is scheduled between the predecessor and 530 // this node. 531 SUnit *RegDef = LiveRegDefs[Pred.getReg()]; (void)RegDef; 532 assert((!RegDef || RegDef == SU || RegDef == Pred.getSUnit()) && 533 "interference on register dependence"); 534 LiveRegDefs[Pred.getReg()] = Pred.getSUnit(); 535 if (!LiveRegGens[Pred.getReg()]) { 536 ++NumLiveRegs; 537 LiveRegGens[Pred.getReg()] = SU; 538 } 539 } 540 } 541 542 // If we're scheduling a lowered CALLSEQ_END, find the corresponding 543 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between 544 // these nodes, to prevent other calls from being interscheduled with them. 545 unsigned CallResource = TRI->getNumRegs(); 546 if (!LiveRegDefs[CallResource]) 547 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) 548 if (Node->isMachineOpcode() && 549 Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) { 550 unsigned NestLevel = 0; 551 unsigned MaxNest = 0; 552 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII); 553 assert(N && "Must find call sequence start"); 554 555 SUnit *Def = &SUnits[N->getNodeId()]; 556 CallSeqEndForStart[Def] = SU; 557 558 ++NumLiveRegs; 559 LiveRegDefs[CallResource] = Def; 560 LiveRegGens[CallResource] = SU; 561 break; 562 } 563 } 564 565 /// Check to see if any of the pending instructions are ready to issue. If 566 /// so, add them to the available queue. 567 void ScheduleDAGRRList::ReleasePending() { 568 if (DisableSchedCycles) { 569 assert(PendingQueue.empty() && "pending instrs not allowed in this mode"); 570 return; 571 } 572 573 // If the available queue is empty, it is safe to reset MinAvailableCycle. 574 if (AvailableQueue->empty()) 575 MinAvailableCycle = UINT_MAX; 576 577 // Check to see if any of the pending instructions are ready to issue. If 578 // so, add them to the available queue. 579 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) { 580 unsigned ReadyCycle = PendingQueue[i]->getHeight(); 581 if (ReadyCycle < MinAvailableCycle) 582 MinAvailableCycle = ReadyCycle; 583 584 if (PendingQueue[i]->isAvailable) { 585 if (!isReady(PendingQueue[i])) 586 continue; 587 AvailableQueue->push(PendingQueue[i]); 588 } 589 PendingQueue[i]->isPending = false; 590 PendingQueue[i] = PendingQueue.back(); 591 PendingQueue.pop_back(); 592 --i; --e; 593 } 594 } 595 596 /// Move the scheduler state forward by the specified number of Cycles. 597 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) { 598 if (NextCycle <= CurCycle) 599 return; 600 601 IssueCount = 0; 602 AvailableQueue->setCurCycle(NextCycle); 603 if (!HazardRec->isEnabled()) { 604 // Bypass lots of virtual calls in case of long latency. 605 CurCycle = NextCycle; 606 } 607 else { 608 for (; CurCycle != NextCycle; ++CurCycle) { 609 HazardRec->RecedeCycle(); 610 } 611 } 612 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the 613 // available Q to release pending nodes at least once before popping. 614 ReleasePending(); 615 } 616 617 /// Move the scheduler state forward until the specified node's dependents are 618 /// ready and can be scheduled with no resource conflicts. 619 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) { 620 if (DisableSchedCycles) 621 return; 622 623 // FIXME: Nodes such as CopyFromReg probably should not advance the current 624 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node 625 // has predecessors the cycle will be advanced when they are scheduled. 626 // But given the crude nature of modeling latency though such nodes, we 627 // currently need to treat these nodes like real instructions. 628 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return; 629 630 unsigned ReadyCycle = SU->getHeight(); 631 632 // Bump CurCycle to account for latency. We assume the latency of other 633 // available instructions may be hidden by the stall (not a full pipe stall). 634 // This updates the hazard recognizer's cycle before reserving resources for 635 // this instruction. 636 AdvanceToCycle(ReadyCycle); 637 638 // Calls are scheduled in their preceding cycle, so don't conflict with 639 // hazards from instructions after the call. EmitNode will reset the 640 // scoreboard state before emitting the call. 641 if (SU->isCall) 642 return; 643 644 // FIXME: For resource conflicts in very long non-pipelined stages, we 645 // should probably skip ahead here to avoid useless scoreboard checks. 646 int Stalls = 0; 647 while (true) { 648 ScheduleHazardRecognizer::HazardType HT = 649 HazardRec->getHazardType(SU, -Stalls); 650 651 if (HT == ScheduleHazardRecognizer::NoHazard) 652 break; 653 654 ++Stalls; 655 } 656 AdvanceToCycle(CurCycle + Stalls); 657 } 658 659 /// Record this SUnit in the HazardRecognizer. 660 /// Does not update CurCycle. 661 void ScheduleDAGRRList::EmitNode(SUnit *SU) { 662 if (!HazardRec->isEnabled()) 663 return; 664 665 // Check for phys reg copy. 666 if (!SU->getNode()) 667 return; 668 669 switch (SU->getNode()->getOpcode()) { 670 default: 671 assert(SU->getNode()->isMachineOpcode() && 672 "This target-independent node should not be scheduled."); 673 break; 674 case ISD::MERGE_VALUES: 675 case ISD::TokenFactor: 676 case ISD::LIFETIME_START: 677 case ISD::LIFETIME_END: 678 case ISD::CopyToReg: 679 case ISD::CopyFromReg: 680 case ISD::EH_LABEL: 681 // Noops don't affect the scoreboard state. Copies are likely to be 682 // removed. 683 return; 684 case ISD::INLINEASM: 685 // For inline asm, clear the pipeline state. 686 HazardRec->Reset(); 687 return; 688 } 689 if (SU->isCall) { 690 // Calls are scheduled with their preceding instructions. For bottom-up 691 // scheduling, clear the pipeline state before emitting. 692 HazardRec->Reset(); 693 } 694 695 HazardRec->EmitInstruction(SU); 696 } 697 698 static void resetVRegCycle(SUnit *SU); 699 700 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending 701 /// count of its predecessors. If a predecessor pending count is zero, add it to 702 /// the Available queue. 703 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) { 704 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: "); 705 DEBUG(SU->dump(this)); 706 707 #ifndef NDEBUG 708 if (CurCycle < SU->getHeight()) 709 DEBUG(dbgs() << " Height [" << SU->getHeight() 710 << "] pipeline stall!\n"); 711 #endif 712 713 // FIXME: Do not modify node height. It may interfere with 714 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the 715 // node its ready cycle can aid heuristics, and after scheduling it can 716 // indicate the scheduled cycle. 717 SU->setHeightToAtLeast(CurCycle); 718 719 // Reserve resources for the scheduled instruction. 720 EmitNode(SU); 721 722 Sequence.push_back(SU); 723 724 AvailableQueue->scheduledNode(SU); 725 726 // If HazardRec is disabled, and each inst counts as one cycle, then 727 // advance CurCycle before ReleasePredecessors to avoid useless pushes to 728 // PendingQueue for schedulers that implement HasReadyFilter. 729 if (!HazardRec->isEnabled() && AvgIPC < 2) 730 AdvanceToCycle(CurCycle + 1); 731 732 // Update liveness of predecessors before successors to avoid treating a 733 // two-address node as a live range def. 734 ReleasePredecessors(SU); 735 736 // Release all the implicit physical register defs that are live. 737 for (SDep &Succ : SU->Succs) { 738 // LiveRegDegs[Succ.getReg()] != SU when SU is a two-address node. 739 if (Succ.isAssignedRegDep() && LiveRegDefs[Succ.getReg()] == SU) { 740 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!"); 741 --NumLiveRegs; 742 LiveRegDefs[Succ.getReg()] = nullptr; 743 LiveRegGens[Succ.getReg()] = nullptr; 744 releaseInterferences(Succ.getReg()); 745 } 746 } 747 // Release the special call resource dependence, if this is the beginning 748 // of a call. 749 unsigned CallResource = TRI->getNumRegs(); 750 if (LiveRegDefs[CallResource] == SU) 751 for (const SDNode *SUNode = SU->getNode(); SUNode; 752 SUNode = SUNode->getGluedNode()) { 753 if (SUNode->isMachineOpcode() && 754 SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) { 755 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!"); 756 --NumLiveRegs; 757 LiveRegDefs[CallResource] = nullptr; 758 LiveRegGens[CallResource] = nullptr; 759 releaseInterferences(CallResource); 760 } 761 } 762 763 resetVRegCycle(SU); 764 765 SU->isScheduled = true; 766 767 // Conditions under which the scheduler should eagerly advance the cycle: 768 // (1) No available instructions 769 // (2) All pipelines full, so available instructions must have hazards. 770 // 771 // If HazardRec is disabled, the cycle was pre-advanced before calling 772 // ReleasePredecessors. In that case, IssueCount should remain 0. 773 // 774 // Check AvailableQueue after ReleasePredecessors in case of zero latency. 775 if (HazardRec->isEnabled() || AvgIPC > 1) { 776 if (SU->getNode() && SU->getNode()->isMachineOpcode()) 777 ++IssueCount; 778 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit()) 779 || (!HazardRec->isEnabled() && IssueCount == AvgIPC)) 780 AdvanceToCycle(CurCycle + 1); 781 } 782 } 783 784 /// CapturePred - This does the opposite of ReleasePred. Since SU is being 785 /// unscheduled, increase the succ left count of its predecessors. Remove 786 /// them from AvailableQueue if necessary. 787 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) { 788 SUnit *PredSU = PredEdge->getSUnit(); 789 if (PredSU->isAvailable) { 790 PredSU->isAvailable = false; 791 if (!PredSU->isPending) 792 AvailableQueue->remove(PredSU); 793 } 794 795 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!"); 796 ++PredSU->NumSuccsLeft; 797 } 798 799 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and 800 /// its predecessor states to reflect the change. 801 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) { 802 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: "); 803 DEBUG(SU->dump(this)); 804 805 for (SDep &Pred : SU->Preds) { 806 CapturePred(&Pred); 807 if (Pred.isAssignedRegDep() && SU == LiveRegGens[Pred.getReg()]){ 808 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!"); 809 assert(LiveRegDefs[Pred.getReg()] == Pred.getSUnit() && 810 "Physical register dependency violated?"); 811 --NumLiveRegs; 812 LiveRegDefs[Pred.getReg()] = nullptr; 813 LiveRegGens[Pred.getReg()] = nullptr; 814 releaseInterferences(Pred.getReg()); 815 } 816 } 817 818 // Reclaim the special call resource dependence, if this is the beginning 819 // of a call. 820 unsigned CallResource = TRI->getNumRegs(); 821 for (const SDNode *SUNode = SU->getNode(); SUNode; 822 SUNode = SUNode->getGluedNode()) { 823 if (SUNode->isMachineOpcode() && 824 SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) { 825 SUnit *SeqEnd = CallSeqEndForStart[SU]; 826 assert(SeqEnd && "Call sequence start/end must be known"); 827 assert(!LiveRegDefs[CallResource]); 828 assert(!LiveRegGens[CallResource]); 829 ++NumLiveRegs; 830 LiveRegDefs[CallResource] = SU; 831 LiveRegGens[CallResource] = SeqEnd; 832 } 833 } 834 835 // Release the special call resource dependence, if this is the end 836 // of a call. 837 if (LiveRegGens[CallResource] == SU) 838 for (const SDNode *SUNode = SU->getNode(); SUNode; 839 SUNode = SUNode->getGluedNode()) { 840 if (SUNode->isMachineOpcode() && 841 SUNode->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) { 842 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!"); 843 assert(LiveRegDefs[CallResource]); 844 assert(LiveRegGens[CallResource]); 845 --NumLiveRegs; 846 LiveRegDefs[CallResource] = nullptr; 847 LiveRegGens[CallResource] = nullptr; 848 releaseInterferences(CallResource); 849 } 850 } 851 852 for (auto &Succ : SU->Succs) { 853 if (Succ.isAssignedRegDep()) { 854 auto Reg = Succ.getReg(); 855 if (!LiveRegDefs[Reg]) 856 ++NumLiveRegs; 857 // This becomes the nearest def. Note that an earlier def may still be 858 // pending if this is a two-address node. 859 LiveRegDefs[Reg] = SU; 860 861 // Update LiveRegGen only if was empty before this unscheduling. 862 // This is to avoid incorrect updating LiveRegGen set in previous run. 863 if (!LiveRegGens[Reg]) { 864 // Find the successor with the lowest height. 865 LiveRegGens[Reg] = Succ.getSUnit(); 866 for (auto &Succ2 : SU->Succs) { 867 if (Succ2.isAssignedRegDep() && Succ2.getReg() == Reg && 868 Succ2.getSUnit()->getHeight() < LiveRegGens[Reg]->getHeight()) 869 LiveRegGens[Reg] = Succ2.getSUnit(); 870 } 871 } 872 } 873 } 874 if (SU->getHeight() < MinAvailableCycle) 875 MinAvailableCycle = SU->getHeight(); 876 877 SU->setHeightDirty(); 878 SU->isScheduled = false; 879 SU->isAvailable = true; 880 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) { 881 // Don't make available until backtracking is complete. 882 SU->isPending = true; 883 PendingQueue.push_back(SU); 884 } 885 else { 886 AvailableQueue->push(SU); 887 } 888 AvailableQueue->unscheduledNode(SU); 889 } 890 891 /// After backtracking, the hazard checker needs to be restored to a state 892 /// corresponding the current cycle. 893 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() { 894 HazardRec->Reset(); 895 896 unsigned LookAhead = std::min((unsigned)Sequence.size(), 897 HazardRec->getMaxLookAhead()); 898 if (LookAhead == 0) 899 return; 900 901 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead); 902 unsigned HazardCycle = (*I)->getHeight(); 903 for (auto E = Sequence.end(); I != E; ++I) { 904 SUnit *SU = *I; 905 for (; SU->getHeight() > HazardCycle; ++HazardCycle) { 906 HazardRec->RecedeCycle(); 907 } 908 EmitNode(SU); 909 } 910 } 911 912 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in 913 /// BTCycle in order to schedule a specific node. 914 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) { 915 SUnit *OldSU = Sequence.back(); 916 while (true) { 917 Sequence.pop_back(); 918 // FIXME: use ready cycle instead of height 919 CurCycle = OldSU->getHeight(); 920 UnscheduleNodeBottomUp(OldSU); 921 AvailableQueue->setCurCycle(CurCycle); 922 if (OldSU == BtSU) 923 break; 924 OldSU = Sequence.back(); 925 } 926 927 assert(!SU->isSucc(OldSU) && "Something is wrong!"); 928 929 RestoreHazardCheckerBottomUp(); 930 931 ReleasePending(); 932 933 ++NumBacktracks; 934 } 935 936 static bool isOperandOf(const SUnit *SU, SDNode *N) { 937 for (const SDNode *SUNode = SU->getNode(); SUNode; 938 SUNode = SUNode->getGluedNode()) { 939 if (SUNode->isOperandOf(N)) 940 return true; 941 } 942 return false; 943 } 944 945 /// TryUnfold - Attempt to unfold 946 SUnit *ScheduleDAGRRList::TryUnfoldSU(SUnit *SU) { 947 SDNode *N = SU->getNode(); 948 // Use while over if to ease fall through. 949 SmallVector<SDNode *, 2> NewNodes; 950 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes)) 951 return nullptr; 952 953 // unfolding an x86 DEC64m operation results in store, dec, load which 954 // can't be handled here so quit 955 if (NewNodes.size() == 3) 956 return nullptr; 957 958 assert(NewNodes.size() == 2 && "Expected a load folding node!"); 959 960 N = NewNodes[1]; 961 SDNode *LoadNode = NewNodes[0]; 962 unsigned NumVals = N->getNumValues(); 963 unsigned OldNumVals = SU->getNode()->getNumValues(); 964 965 // LoadNode may already exist. This can happen when there is another 966 // load from the same location and producing the same type of value 967 // but it has different alignment or volatileness. 968 bool isNewLoad = true; 969 SUnit *LoadSU; 970 if (LoadNode->getNodeId() != -1) { 971 LoadSU = &SUnits[LoadNode->getNodeId()]; 972 // If LoadSU has already been scheduled, we should clone it but 973 // this would negate the benefit to unfolding so just return SU. 974 if (LoadSU->isScheduled) 975 return SU; 976 isNewLoad = false; 977 } else { 978 LoadSU = CreateNewSUnit(LoadNode); 979 LoadNode->setNodeId(LoadSU->NodeNum); 980 981 InitNumRegDefsLeft(LoadSU); 982 computeLatency(LoadSU); 983 } 984 985 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n"); 986 987 // Now that we are committed to unfolding replace DAG Uses. 988 for (unsigned i = 0; i != NumVals; ++i) 989 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i)); 990 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals - 1), 991 SDValue(LoadNode, 1)); 992 993 SUnit *NewSU = CreateNewSUnit(N); 994 assert(N->getNodeId() == -1 && "Node already inserted!"); 995 N->setNodeId(NewSU->NodeNum); 996 997 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 998 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) { 999 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) { 1000 NewSU->isTwoAddress = true; 1001 break; 1002 } 1003 } 1004 if (MCID.isCommutable()) 1005 NewSU->isCommutable = true; 1006 1007 InitNumRegDefsLeft(NewSU); 1008 computeLatency(NewSU); 1009 1010 // Record all the edges to and from the old SU, by category. 1011 SmallVector<SDep, 4> ChainPreds; 1012 SmallVector<SDep, 4> ChainSuccs; 1013 SmallVector<SDep, 4> LoadPreds; 1014 SmallVector<SDep, 4> NodePreds; 1015 SmallVector<SDep, 4> NodeSuccs; 1016 for (SDep &Pred : SU->Preds) { 1017 if (Pred.isCtrl()) 1018 ChainPreds.push_back(Pred); 1019 else if (isOperandOf(Pred.getSUnit(), LoadNode)) 1020 LoadPreds.push_back(Pred); 1021 else 1022 NodePreds.push_back(Pred); 1023 } 1024 for (SDep &Succ : SU->Succs) { 1025 if (Succ.isCtrl()) 1026 ChainSuccs.push_back(Succ); 1027 else 1028 NodeSuccs.push_back(Succ); 1029 } 1030 1031 // Now assign edges to the newly-created nodes. 1032 for (const SDep &Pred : ChainPreds) { 1033 RemovePred(SU, Pred); 1034 if (isNewLoad) 1035 AddPred(LoadSU, Pred); 1036 } 1037 for (const SDep &Pred : LoadPreds) { 1038 RemovePred(SU, Pred); 1039 if (isNewLoad) 1040 AddPred(LoadSU, Pred); 1041 } 1042 for (const SDep &Pred : NodePreds) { 1043 RemovePred(SU, Pred); 1044 AddPred(NewSU, Pred); 1045 } 1046 for (SDep D : NodeSuccs) { 1047 SUnit *SuccDep = D.getSUnit(); 1048 D.setSUnit(SU); 1049 RemovePred(SuccDep, D); 1050 D.setSUnit(NewSU); 1051 AddPred(SuccDep, D); 1052 // Balance register pressure. 1053 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled && 1054 !D.isCtrl() && NewSU->NumRegDefsLeft > 0) 1055 --NewSU->NumRegDefsLeft; 1056 } 1057 for (SDep D : ChainSuccs) { 1058 SUnit *SuccDep = D.getSUnit(); 1059 D.setSUnit(SU); 1060 RemovePred(SuccDep, D); 1061 if (isNewLoad) { 1062 D.setSUnit(LoadSU); 1063 AddPred(SuccDep, D); 1064 } 1065 } 1066 1067 // Add a data dependency to reflect that NewSU reads the value defined 1068 // by LoadSU. 1069 SDep D(LoadSU, SDep::Data, 0); 1070 D.setLatency(LoadSU->Latency); 1071 AddPred(NewSU, D); 1072 1073 if (isNewLoad) 1074 AvailableQueue->addNode(LoadSU); 1075 AvailableQueue->addNode(NewSU); 1076 1077 ++NumUnfolds; 1078 1079 if (NewSU->NumSuccsLeft == 0) 1080 NewSU->isAvailable = true; 1081 1082 return NewSU; 1083 } 1084 1085 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled 1086 /// successors to the newly created node. 1087 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) { 1088 SDNode *N = SU->getNode(); 1089 if (!N) 1090 return nullptr; 1091 1092 if (SU->getNode()->getGluedNode()) 1093 return nullptr; 1094 1095 SUnit *NewSU; 1096 bool TryUnfold = false; 1097 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) { 1098 MVT VT = N->getSimpleValueType(i); 1099 if (VT == MVT::Glue) 1100 return nullptr; 1101 else if (VT == MVT::Other) 1102 TryUnfold = true; 1103 } 1104 for (const SDValue &Op : N->op_values()) { 1105 MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo()); 1106 if (VT == MVT::Glue) 1107 return nullptr; 1108 } 1109 1110 // If possible unfold instruction. 1111 if (TryUnfold) { 1112 SUnit *UnfoldSU = TryUnfoldSU(SU); 1113 if (!UnfoldSU) 1114 return nullptr; 1115 SU = UnfoldSU; 1116 N = SU->getNode(); 1117 // If this can be scheduled don't bother duplicating and just return 1118 if (SU->NumSuccsLeft == 0) 1119 return SU; 1120 } 1121 1122 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n"); 1123 NewSU = CreateClone(SU); 1124 1125 // New SUnit has the exact same predecessors. 1126 for (SDep &Pred : SU->Preds) 1127 if (!Pred.isArtificial()) 1128 AddPred(NewSU, Pred); 1129 1130 // Only copy scheduled successors. Cut them from old node's successor 1131 // list and move them over. 1132 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps; 1133 for (SDep &Succ : SU->Succs) { 1134 if (Succ.isArtificial()) 1135 continue; 1136 SUnit *SuccSU = Succ.getSUnit(); 1137 if (SuccSU->isScheduled) { 1138 SDep D = Succ; 1139 D.setSUnit(NewSU); 1140 AddPred(SuccSU, D); 1141 D.setSUnit(SU); 1142 DelDeps.push_back(std::make_pair(SuccSU, D)); 1143 } 1144 } 1145 for (auto &DelDep : DelDeps) 1146 RemovePred(DelDep.first, DelDep.second); 1147 1148 AvailableQueue->updateNode(SU); 1149 AvailableQueue->addNode(NewSU); 1150 1151 ++NumDups; 1152 return NewSU; 1153 } 1154 1155 /// InsertCopiesAndMoveSuccs - Insert register copies and move all 1156 /// scheduled successors of the given SUnit to the last copy. 1157 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg, 1158 const TargetRegisterClass *DestRC, 1159 const TargetRegisterClass *SrcRC, 1160 SmallVectorImpl<SUnit*> &Copies) { 1161 SUnit *CopyFromSU = CreateNewSUnit(nullptr); 1162 CopyFromSU->CopySrcRC = SrcRC; 1163 CopyFromSU->CopyDstRC = DestRC; 1164 1165 SUnit *CopyToSU = CreateNewSUnit(nullptr); 1166 CopyToSU->CopySrcRC = DestRC; 1167 CopyToSU->CopyDstRC = SrcRC; 1168 1169 // Only copy scheduled successors. Cut them from old node's successor 1170 // list and move them over. 1171 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps; 1172 for (SDep &Succ : SU->Succs) { 1173 if (Succ.isArtificial()) 1174 continue; 1175 SUnit *SuccSU = Succ.getSUnit(); 1176 if (SuccSU->isScheduled) { 1177 SDep D = Succ; 1178 D.setSUnit(CopyToSU); 1179 AddPred(SuccSU, D); 1180 DelDeps.push_back(std::make_pair(SuccSU, Succ)); 1181 } 1182 else { 1183 // Avoid scheduling the def-side copy before other successors. Otherwise 1184 // we could introduce another physreg interference on the copy and 1185 // continue inserting copies indefinitely. 1186 AddPred(SuccSU, SDep(CopyFromSU, SDep::Artificial)); 1187 } 1188 } 1189 for (auto &DelDep : DelDeps) 1190 RemovePred(DelDep.first, DelDep.second); 1191 1192 SDep FromDep(SU, SDep::Data, Reg); 1193 FromDep.setLatency(SU->Latency); 1194 AddPred(CopyFromSU, FromDep); 1195 SDep ToDep(CopyFromSU, SDep::Data, 0); 1196 ToDep.setLatency(CopyFromSU->Latency); 1197 AddPred(CopyToSU, ToDep); 1198 1199 AvailableQueue->updateNode(SU); 1200 AvailableQueue->addNode(CopyFromSU); 1201 AvailableQueue->addNode(CopyToSU); 1202 Copies.push_back(CopyFromSU); 1203 Copies.push_back(CopyToSU); 1204 1205 ++NumPRCopies; 1206 } 1207 1208 /// getPhysicalRegisterVT - Returns the ValueType of the physical register 1209 /// definition of the specified node. 1210 /// FIXME: Move to SelectionDAG? 1211 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg, 1212 const TargetInstrInfo *TII) { 1213 unsigned NumRes; 1214 if (N->getOpcode() == ISD::CopyFromReg) { 1215 // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type. 1216 NumRes = 1; 1217 } else { 1218 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1219 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!"); 1220 NumRes = MCID.getNumDefs(); 1221 for (const MCPhysReg *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) { 1222 if (Reg == *ImpDef) 1223 break; 1224 ++NumRes; 1225 } 1226 } 1227 return N->getSimpleValueType(NumRes); 1228 } 1229 1230 /// CheckForLiveRegDef - Return true and update live register vector if the 1231 /// specified register def of the specified SUnit clobbers any "live" registers. 1232 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg, 1233 SUnit **LiveRegDefs, 1234 SmallSet<unsigned, 4> &RegAdded, 1235 SmallVectorImpl<unsigned> &LRegs, 1236 const TargetRegisterInfo *TRI) { 1237 for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) { 1238 1239 // Check if Ref is live. 1240 if (!LiveRegDefs[*AliasI]) continue; 1241 1242 // Allow multiple uses of the same def. 1243 if (LiveRegDefs[*AliasI] == SU) continue; 1244 1245 // Add Reg to the set of interfering live regs. 1246 if (RegAdded.insert(*AliasI).second) { 1247 LRegs.push_back(*AliasI); 1248 } 1249 } 1250 } 1251 1252 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered 1253 /// by RegMask, and add them to LRegs. 1254 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask, 1255 ArrayRef<SUnit*> LiveRegDefs, 1256 SmallSet<unsigned, 4> &RegAdded, 1257 SmallVectorImpl<unsigned> &LRegs) { 1258 // Look at all live registers. Skip Reg0 and the special CallResource. 1259 for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) { 1260 if (!LiveRegDefs[i]) continue; 1261 if (LiveRegDefs[i] == SU) continue; 1262 if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue; 1263 if (RegAdded.insert(i).second) 1264 LRegs.push_back(i); 1265 } 1266 } 1267 1268 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any. 1269 static const uint32_t *getNodeRegMask(const SDNode *N) { 1270 for (const SDValue &Op : N->op_values()) 1271 if (const auto *RegOp = dyn_cast<RegisterMaskSDNode>(Op.getNode())) 1272 return RegOp->getRegMask(); 1273 return nullptr; 1274 } 1275 1276 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay 1277 /// scheduling of the given node to satisfy live physical register dependencies. 1278 /// If the specific node is the last one that's available to schedule, do 1279 /// whatever is necessary (i.e. backtracking or cloning) to make it possible. 1280 bool ScheduleDAGRRList:: 1281 DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) { 1282 if (NumLiveRegs == 0) 1283 return false; 1284 1285 SmallSet<unsigned, 4> RegAdded; 1286 // If this node would clobber any "live" register, then it's not ready. 1287 // 1288 // If SU is the currently live definition of the same register that it uses, 1289 // then we are free to schedule it. 1290 for (SDep &Pred : SU->Preds) { 1291 if (Pred.isAssignedRegDep() && LiveRegDefs[Pred.getReg()] != SU) 1292 CheckForLiveRegDef(Pred.getSUnit(), Pred.getReg(), LiveRegDefs.get(), 1293 RegAdded, LRegs, TRI); 1294 } 1295 1296 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) { 1297 if (Node->getOpcode() == ISD::INLINEASM) { 1298 // Inline asm can clobber physical defs. 1299 unsigned NumOps = Node->getNumOperands(); 1300 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue) 1301 --NumOps; // Ignore the glue operand. 1302 1303 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 1304 unsigned Flags = 1305 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue(); 1306 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 1307 1308 ++i; // Skip the ID value. 1309 if (InlineAsm::isRegDefKind(Flags) || 1310 InlineAsm::isRegDefEarlyClobberKind(Flags) || 1311 InlineAsm::isClobberKind(Flags)) { 1312 // Check for def of register or earlyclobber register. 1313 for (; NumVals; --NumVals, ++i) { 1314 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg(); 1315 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 1316 CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI); 1317 } 1318 } else 1319 i += NumVals; 1320 } 1321 continue; 1322 } 1323 1324 if (!Node->isMachineOpcode()) 1325 continue; 1326 // If we're in the middle of scheduling a call, don't begin scheduling 1327 // another call. Also, don't allow any physical registers to be live across 1328 // the call. 1329 if (Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) { 1330 // Check the special calling-sequence resource. 1331 unsigned CallResource = TRI->getNumRegs(); 1332 if (LiveRegDefs[CallResource]) { 1333 SDNode *Gen = LiveRegGens[CallResource]->getNode(); 1334 while (SDNode *Glued = Gen->getGluedNode()) 1335 Gen = Glued; 1336 if (!IsChainDependent(Gen, Node, 0, TII) && 1337 RegAdded.insert(CallResource).second) 1338 LRegs.push_back(CallResource); 1339 } 1340 } 1341 if (const uint32_t *RegMask = getNodeRegMask(Node)) 1342 CheckForLiveRegDefMasked(SU, RegMask, 1343 makeArrayRef(LiveRegDefs.get(), TRI->getNumRegs()), 1344 RegAdded, LRegs); 1345 1346 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode()); 1347 if (MCID.hasOptionalDef()) { 1348 // Most ARM instructions have an OptionalDef for CPSR, to model the S-bit. 1349 // This operand can be either a def of CPSR, if the S bit is set; or a use 1350 // of %noreg. When the OptionalDef is set to a valid register, we need to 1351 // handle it in the same way as an ImplicitDef. 1352 for (unsigned i = 0; i < MCID.getNumDefs(); ++i) 1353 if (MCID.OpInfo[i].isOptionalDef()) { 1354 const SDValue &OptionalDef = Node->getOperand(i - Node->getNumValues()); 1355 unsigned Reg = cast<RegisterSDNode>(OptionalDef)->getReg(); 1356 CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI); 1357 } 1358 } 1359 if (!MCID.ImplicitDefs) 1360 continue; 1361 for (const MCPhysReg *Reg = MCID.getImplicitDefs(); *Reg; ++Reg) 1362 CheckForLiveRegDef(SU, *Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI); 1363 } 1364 1365 return !LRegs.empty(); 1366 } 1367 1368 void ScheduleDAGRRList::releaseInterferences(unsigned Reg) { 1369 // Add the nodes that aren't ready back onto the available list. 1370 for (unsigned i = Interferences.size(); i > 0; --i) { 1371 SUnit *SU = Interferences[i-1]; 1372 LRegsMapT::iterator LRegsPos = LRegsMap.find(SU); 1373 if (Reg) { 1374 SmallVectorImpl<unsigned> &LRegs = LRegsPos->second; 1375 if (!is_contained(LRegs, Reg)) 1376 continue; 1377 } 1378 SU->isPending = false; 1379 // The interfering node may no longer be available due to backtracking. 1380 // Furthermore, it may have been made available again, in which case it is 1381 // now already in the AvailableQueue. 1382 if (SU->isAvailable && !SU->NodeQueueId) { 1383 DEBUG(dbgs() << " Repushing SU #" << SU->NodeNum << '\n'); 1384 AvailableQueue->push(SU); 1385 } 1386 if (i < Interferences.size()) 1387 Interferences[i-1] = Interferences.back(); 1388 Interferences.pop_back(); 1389 LRegsMap.erase(LRegsPos); 1390 } 1391 } 1392 1393 /// Return a node that can be scheduled in this cycle. Requirements: 1394 /// (1) Ready: latency has been satisfied 1395 /// (2) No Hazards: resources are available 1396 /// (3) No Interferences: may unschedule to break register interferences. 1397 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() { 1398 SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop(); 1399 auto FindAvailableNode = [&]() { 1400 while (CurSU) { 1401 SmallVector<unsigned, 4> LRegs; 1402 if (!DelayForLiveRegsBottomUp(CurSU, LRegs)) 1403 break; 1404 DEBUG(dbgs() << " Interfering reg " << 1405 (LRegs[0] == TRI->getNumRegs() ? "CallResource" 1406 : TRI->getName(LRegs[0])) 1407 << " SU #" << CurSU->NodeNum << '\n'); 1408 std::pair<LRegsMapT::iterator, bool> LRegsPair = 1409 LRegsMap.insert(std::make_pair(CurSU, LRegs)); 1410 if (LRegsPair.second) { 1411 CurSU->isPending = true; // This SU is not in AvailableQueue right now. 1412 Interferences.push_back(CurSU); 1413 } 1414 else { 1415 assert(CurSU->isPending && "Interferences are pending"); 1416 // Update the interference with current live regs. 1417 LRegsPair.first->second = LRegs; 1418 } 1419 CurSU = AvailableQueue->pop(); 1420 } 1421 }; 1422 FindAvailableNode(); 1423 if (CurSU) 1424 return CurSU; 1425 1426 // All candidates are delayed due to live physical reg dependencies. 1427 // Try backtracking, code duplication, or inserting cross class copies 1428 // to resolve it. 1429 for (SUnit *TrySU : Interferences) { 1430 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU]; 1431 1432 // Try unscheduling up to the point where it's safe to schedule 1433 // this node. 1434 SUnit *BtSU = nullptr; 1435 unsigned LiveCycle = UINT_MAX; 1436 for (unsigned Reg : LRegs) { 1437 if (LiveRegGens[Reg]->getHeight() < LiveCycle) { 1438 BtSU = LiveRegGens[Reg]; 1439 LiveCycle = BtSU->getHeight(); 1440 } 1441 } 1442 if (!WillCreateCycle(TrySU, BtSU)) { 1443 // BacktrackBottomUp mutates Interferences! 1444 BacktrackBottomUp(TrySU, BtSU); 1445 1446 // Force the current node to be scheduled before the node that 1447 // requires the physical reg dep. 1448 if (BtSU->isAvailable) { 1449 BtSU->isAvailable = false; 1450 if (!BtSU->isPending) 1451 AvailableQueue->remove(BtSU); 1452 } 1453 DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum << ") to SU(" 1454 << TrySU->NodeNum << ")\n"); 1455 AddPred(TrySU, SDep(BtSU, SDep::Artificial)); 1456 1457 // If one or more successors has been unscheduled, then the current 1458 // node is no longer available. 1459 if (!TrySU->isAvailable || !TrySU->NodeQueueId) { 1460 DEBUG(dbgs() << "TrySU not available; choosing node from queue\n"); 1461 CurSU = AvailableQueue->pop(); 1462 } else { 1463 DEBUG(dbgs() << "TrySU available\n"); 1464 // Available and in AvailableQueue 1465 AvailableQueue->remove(TrySU); 1466 CurSU = TrySU; 1467 } 1468 FindAvailableNode(); 1469 // Interferences has been mutated. We must break. 1470 break; 1471 } 1472 } 1473 1474 if (!CurSU) { 1475 // Can't backtrack. If it's too expensive to copy the value, then try 1476 // duplicate the nodes that produces these "too expensive to copy" 1477 // values to break the dependency. In case even that doesn't work, 1478 // insert cross class copies. 1479 // If it's not too expensive, i.e. cost != -1, issue copies. 1480 SUnit *TrySU = Interferences[0]; 1481 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU]; 1482 assert(LRegs.size() == 1 && "Can't handle this yet!"); 1483 unsigned Reg = LRegs[0]; 1484 SUnit *LRDef = LiveRegDefs[Reg]; 1485 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII); 1486 const TargetRegisterClass *RC = 1487 TRI->getMinimalPhysRegClass(Reg, VT); 1488 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC); 1489 1490 // If cross copy register class is the same as RC, then it must be possible 1491 // copy the value directly. Do not try duplicate the def. 1492 // If cross copy register class is not the same as RC, then it's possible to 1493 // copy the value but it require cross register class copies and it is 1494 // expensive. 1495 // If cross copy register class is null, then it's not possible to copy 1496 // the value at all. 1497 SUnit *NewDef = nullptr; 1498 if (DestRC != RC) { 1499 NewDef = CopyAndMoveSuccessors(LRDef); 1500 if (!DestRC && !NewDef) 1501 report_fatal_error("Can't handle live physical register dependency!"); 1502 } 1503 if (!NewDef) { 1504 // Issue copies, these can be expensive cross register class copies. 1505 SmallVector<SUnit*, 2> Copies; 1506 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies); 1507 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum 1508 << " to SU #" << Copies.front()->NodeNum << "\n"); 1509 AddPred(TrySU, SDep(Copies.front(), SDep::Artificial)); 1510 NewDef = Copies.back(); 1511 } 1512 1513 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum 1514 << " to SU #" << TrySU->NodeNum << "\n"); 1515 LiveRegDefs[Reg] = NewDef; 1516 AddPred(NewDef, SDep(TrySU, SDep::Artificial)); 1517 TrySU->isAvailable = false; 1518 CurSU = NewDef; 1519 } 1520 assert(CurSU && "Unable to resolve live physical register dependencies!"); 1521 return CurSU; 1522 } 1523 1524 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up 1525 /// schedulers. 1526 void ScheduleDAGRRList::ListScheduleBottomUp() { 1527 // Release any predecessors of the special Exit node. 1528 ReleasePredecessors(&ExitSU); 1529 1530 // Add root to Available queue. 1531 if (!SUnits.empty()) { 1532 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()]; 1533 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!"); 1534 RootSU->isAvailable = true; 1535 AvailableQueue->push(RootSU); 1536 } 1537 1538 // While Available queue is not empty, grab the node with the highest 1539 // priority. If it is not ready put it back. Schedule the node. 1540 Sequence.reserve(SUnits.size()); 1541 while (!AvailableQueue->empty() || !Interferences.empty()) { 1542 DEBUG(dbgs() << "\nExamining Available:\n"; 1543 AvailableQueue->dump(this)); 1544 1545 // Pick the best node to schedule taking all constraints into 1546 // consideration. 1547 SUnit *SU = PickNodeToScheduleBottomUp(); 1548 1549 AdvancePastStalls(SU); 1550 1551 ScheduleNodeBottomUp(SU); 1552 1553 while (AvailableQueue->empty() && !PendingQueue.empty()) { 1554 // Advance the cycle to free resources. Skip ahead to the next ready SU. 1555 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized"); 1556 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle)); 1557 } 1558 } 1559 1560 // Reverse the order if it is bottom up. 1561 std::reverse(Sequence.begin(), Sequence.end()); 1562 1563 #ifndef NDEBUG 1564 VerifyScheduledSequence(/*isBottomUp=*/true); 1565 #endif 1566 } 1567 1568 //===----------------------------------------------------------------------===// 1569 // RegReductionPriorityQueue Definition 1570 //===----------------------------------------------------------------------===// 1571 // 1572 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers 1573 // to reduce register pressure. 1574 // 1575 namespace { 1576 class RegReductionPQBase; 1577 1578 struct queue_sort { 1579 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; } 1580 }; 1581 1582 #ifndef NDEBUG 1583 template<class SF> 1584 struct reverse_sort : public queue_sort { 1585 SF &SortFunc; 1586 reverse_sort(SF &sf) : SortFunc(sf) {} 1587 1588 bool operator()(SUnit* left, SUnit* right) const { 1589 // reverse left/right rather than simply !SortFunc(left, right) 1590 // to expose different paths in the comparison logic. 1591 return SortFunc(right, left); 1592 } 1593 }; 1594 #endif // NDEBUG 1595 1596 /// bu_ls_rr_sort - Priority function for bottom up register pressure 1597 // reduction scheduler. 1598 struct bu_ls_rr_sort : public queue_sort { 1599 enum { 1600 IsBottomUp = true, 1601 HasReadyFilter = false 1602 }; 1603 1604 RegReductionPQBase *SPQ; 1605 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {} 1606 1607 bool operator()(SUnit* left, SUnit* right) const; 1608 }; 1609 1610 // src_ls_rr_sort - Priority function for source order scheduler. 1611 struct src_ls_rr_sort : public queue_sort { 1612 enum { 1613 IsBottomUp = true, 1614 HasReadyFilter = false 1615 }; 1616 1617 RegReductionPQBase *SPQ; 1618 src_ls_rr_sort(RegReductionPQBase *spq) 1619 : SPQ(spq) {} 1620 1621 bool operator()(SUnit* left, SUnit* right) const; 1622 }; 1623 1624 // hybrid_ls_rr_sort - Priority function for hybrid scheduler. 1625 struct hybrid_ls_rr_sort : public queue_sort { 1626 enum { 1627 IsBottomUp = true, 1628 HasReadyFilter = false 1629 }; 1630 1631 RegReductionPQBase *SPQ; 1632 hybrid_ls_rr_sort(RegReductionPQBase *spq) 1633 : SPQ(spq) {} 1634 1635 bool isReady(SUnit *SU, unsigned CurCycle) const; 1636 1637 bool operator()(SUnit* left, SUnit* right) const; 1638 }; 1639 1640 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism) 1641 // scheduler. 1642 struct ilp_ls_rr_sort : public queue_sort { 1643 enum { 1644 IsBottomUp = true, 1645 HasReadyFilter = false 1646 }; 1647 1648 RegReductionPQBase *SPQ; 1649 ilp_ls_rr_sort(RegReductionPQBase *spq) 1650 : SPQ(spq) {} 1651 1652 bool isReady(SUnit *SU, unsigned CurCycle) const; 1653 1654 bool operator()(SUnit* left, SUnit* right) const; 1655 }; 1656 1657 class RegReductionPQBase : public SchedulingPriorityQueue { 1658 protected: 1659 std::vector<SUnit*> Queue; 1660 unsigned CurQueueId; 1661 bool TracksRegPressure; 1662 bool SrcOrder; 1663 1664 // SUnits - The SUnits for the current graph. 1665 std::vector<SUnit> *SUnits; 1666 1667 MachineFunction &MF; 1668 const TargetInstrInfo *TII; 1669 const TargetRegisterInfo *TRI; 1670 const TargetLowering *TLI; 1671 ScheduleDAGRRList *scheduleDAG; 1672 1673 // SethiUllmanNumbers - The SethiUllman number for each node. 1674 std::vector<unsigned> SethiUllmanNumbers; 1675 1676 /// RegPressure - Tracking current reg pressure per register class. 1677 /// 1678 std::vector<unsigned> RegPressure; 1679 1680 /// RegLimit - Tracking the number of allocatable registers per register 1681 /// class. 1682 std::vector<unsigned> RegLimit; 1683 1684 public: 1685 RegReductionPQBase(MachineFunction &mf, 1686 bool hasReadyFilter, 1687 bool tracksrp, 1688 bool srcorder, 1689 const TargetInstrInfo *tii, 1690 const TargetRegisterInfo *tri, 1691 const TargetLowering *tli) 1692 : SchedulingPriorityQueue(hasReadyFilter), 1693 CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder), 1694 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(nullptr) { 1695 if (TracksRegPressure) { 1696 unsigned NumRC = TRI->getNumRegClasses(); 1697 RegLimit.resize(NumRC); 1698 RegPressure.resize(NumRC); 1699 std::fill(RegLimit.begin(), RegLimit.end(), 0); 1700 std::fill(RegPressure.begin(), RegPressure.end(), 0); 1701 for (const TargetRegisterClass *RC : TRI->regclasses()) 1702 RegLimit[RC->getID()] = tri->getRegPressureLimit(RC, MF); 1703 } 1704 } 1705 1706 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) { 1707 scheduleDAG = scheduleDag; 1708 } 1709 1710 ScheduleHazardRecognizer* getHazardRec() { 1711 return scheduleDAG->getHazardRec(); 1712 } 1713 1714 void initNodes(std::vector<SUnit> &sunits) override; 1715 1716 void addNode(const SUnit *SU) override; 1717 1718 void updateNode(const SUnit *SU) override; 1719 1720 void releaseState() override { 1721 SUnits = nullptr; 1722 SethiUllmanNumbers.clear(); 1723 std::fill(RegPressure.begin(), RegPressure.end(), 0); 1724 } 1725 1726 unsigned getNodePriority(const SUnit *SU) const; 1727 1728 unsigned getNodeOrdering(const SUnit *SU) const { 1729 if (!SU->getNode()) return 0; 1730 1731 return SU->getNode()->getIROrder(); 1732 } 1733 1734 bool empty() const override { return Queue.empty(); } 1735 1736 void push(SUnit *U) override { 1737 assert(!U->NodeQueueId && "Node in the queue already"); 1738 U->NodeQueueId = ++CurQueueId; 1739 Queue.push_back(U); 1740 } 1741 1742 void remove(SUnit *SU) override { 1743 assert(!Queue.empty() && "Queue is empty!"); 1744 assert(SU->NodeQueueId != 0 && "Not in queue!"); 1745 std::vector<SUnit *>::iterator I = find(Queue, SU); 1746 if (I != std::prev(Queue.end())) 1747 std::swap(*I, Queue.back()); 1748 Queue.pop_back(); 1749 SU->NodeQueueId = 0; 1750 } 1751 1752 bool tracksRegPressure() const override { return TracksRegPressure; } 1753 1754 void dumpRegPressure() const; 1755 1756 bool HighRegPressure(const SUnit *SU) const; 1757 1758 bool MayReduceRegPressure(SUnit *SU) const; 1759 1760 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const; 1761 1762 void scheduledNode(SUnit *SU) override; 1763 1764 void unscheduledNode(SUnit *SU) override; 1765 1766 protected: 1767 bool canClobber(const SUnit *SU, const SUnit *Op); 1768 void AddPseudoTwoAddrDeps(); 1769 void PrescheduleNodesWithMultipleUses(); 1770 void CalculateSethiUllmanNumbers(); 1771 }; 1772 1773 template<class SF> 1774 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) { 1775 std::vector<SUnit *>::iterator Best = Q.begin(); 1776 for (auto I = std::next(Q.begin()), E = Q.end(); I != E; ++I) 1777 if (Picker(*Best, *I)) 1778 Best = I; 1779 SUnit *V = *Best; 1780 if (Best != std::prev(Q.end())) 1781 std::swap(*Best, Q.back()); 1782 Q.pop_back(); 1783 return V; 1784 } 1785 1786 template<class SF> 1787 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) { 1788 #ifndef NDEBUG 1789 if (DAG->StressSched) { 1790 reverse_sort<SF> RPicker(Picker); 1791 return popFromQueueImpl(Q, RPicker); 1792 } 1793 #endif 1794 (void)DAG; 1795 return popFromQueueImpl(Q, Picker); 1796 } 1797 1798 template<class SF> 1799 class RegReductionPriorityQueue : public RegReductionPQBase { 1800 SF Picker; 1801 1802 public: 1803 RegReductionPriorityQueue(MachineFunction &mf, 1804 bool tracksrp, 1805 bool srcorder, 1806 const TargetInstrInfo *tii, 1807 const TargetRegisterInfo *tri, 1808 const TargetLowering *tli) 1809 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder, 1810 tii, tri, tli), 1811 Picker(this) {} 1812 1813 bool isBottomUp() const override { return SF::IsBottomUp; } 1814 1815 bool isReady(SUnit *U) const override { 1816 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle()); 1817 } 1818 1819 SUnit *pop() override { 1820 if (Queue.empty()) return nullptr; 1821 1822 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG); 1823 V->NodeQueueId = 0; 1824 return V; 1825 } 1826 1827 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1828 LLVM_DUMP_METHOD void dump(ScheduleDAG *DAG) const override { 1829 // Emulate pop() without clobbering NodeQueueIds. 1830 std::vector<SUnit*> DumpQueue = Queue; 1831 SF DumpPicker = Picker; 1832 while (!DumpQueue.empty()) { 1833 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG); 1834 dbgs() << "Height " << SU->getHeight() << ": "; 1835 SU->dump(DAG); 1836 } 1837 } 1838 #endif 1839 }; 1840 1841 typedef RegReductionPriorityQueue<bu_ls_rr_sort> 1842 BURegReductionPriorityQueue; 1843 1844 typedef RegReductionPriorityQueue<src_ls_rr_sort> 1845 SrcRegReductionPriorityQueue; 1846 1847 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort> 1848 HybridBURRPriorityQueue; 1849 1850 typedef RegReductionPriorityQueue<ilp_ls_rr_sort> 1851 ILPBURRPriorityQueue; 1852 } // end anonymous namespace 1853 1854 //===----------------------------------------------------------------------===// 1855 // Static Node Priority for Register Pressure Reduction 1856 //===----------------------------------------------------------------------===// 1857 1858 // Check for special nodes that bypass scheduling heuristics. 1859 // Currently this pushes TokenFactor nodes down, but may be used for other 1860 // pseudo-ops as well. 1861 // 1862 // Return -1 to schedule right above left, 1 for left above right. 1863 // Return 0 if no bias exists. 1864 static int checkSpecialNodes(const SUnit *left, const SUnit *right) { 1865 bool LSchedLow = left->isScheduleLow; 1866 bool RSchedLow = right->isScheduleLow; 1867 if (LSchedLow != RSchedLow) 1868 return LSchedLow < RSchedLow ? 1 : -1; 1869 return 0; 1870 } 1871 1872 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number. 1873 /// Smaller number is the higher priority. 1874 static unsigned 1875 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) { 1876 if (SUNumbers[SU->NodeNum] != 0) 1877 return SUNumbers[SU->NodeNum]; 1878 1879 // Use WorkList to avoid stack overflow on excessively large IRs. 1880 struct WorkState { 1881 WorkState(const SUnit *SU) : SU(SU) {} 1882 const SUnit *SU; 1883 unsigned PredsProcessed = 0; 1884 }; 1885 1886 SmallVector<WorkState, 16> WorkList; 1887 WorkList.push_back(SU); 1888 while (!WorkList.empty()) { 1889 auto &Temp = WorkList.back(); 1890 auto *TempSU = Temp.SU; 1891 bool AllPredsKnown = true; 1892 // Try to find a non-evaluated pred and push it into the processing stack. 1893 for (unsigned P = Temp.PredsProcessed; P < TempSU->Preds.size(); ++P) { 1894 auto &Pred = TempSU->Preds[P]; 1895 if (Pred.isCtrl()) continue; // ignore chain preds 1896 SUnit *PredSU = Pred.getSUnit(); 1897 if (SUNumbers[PredSU->NodeNum] == 0) { 1898 #ifndef NDEBUG 1899 // In debug mode, check that we don't have such element in the stack. 1900 for (auto It : WorkList) 1901 assert(It.SU != PredSU && "Trying to push an element twice?"); 1902 #endif 1903 // Next time start processing this one starting from the next pred. 1904 Temp.PredsProcessed = P + 1; 1905 WorkList.push_back(PredSU); 1906 AllPredsKnown = false; 1907 break; 1908 } 1909 } 1910 1911 if (!AllPredsKnown) 1912 continue; 1913 1914 // Once all preds are known, we can calculate the answer for this one. 1915 unsigned SethiUllmanNumber = 0; 1916 unsigned Extra = 0; 1917 for (const SDep &Pred : TempSU->Preds) { 1918 if (Pred.isCtrl()) continue; // ignore chain preds 1919 SUnit *PredSU = Pred.getSUnit(); 1920 unsigned PredSethiUllman = SUNumbers[PredSU->NodeNum]; 1921 assert(PredSethiUllman > 0 && "We should have evaluated this pred!"); 1922 if (PredSethiUllman > SethiUllmanNumber) { 1923 SethiUllmanNumber = PredSethiUllman; 1924 Extra = 0; 1925 } else if (PredSethiUllman == SethiUllmanNumber) 1926 ++Extra; 1927 } 1928 1929 SethiUllmanNumber += Extra; 1930 if (SethiUllmanNumber == 0) 1931 SethiUllmanNumber = 1; 1932 SUNumbers[TempSU->NodeNum] = SethiUllmanNumber; 1933 WorkList.pop_back(); 1934 } 1935 1936 assert(SUNumbers[SU->NodeNum] > 0 && "SethiUllman should never be zero!"); 1937 return SUNumbers[SU->NodeNum]; 1938 } 1939 1940 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all 1941 /// scheduling units. 1942 void RegReductionPQBase::CalculateSethiUllmanNumbers() { 1943 SethiUllmanNumbers.assign(SUnits->size(), 0); 1944 1945 for (const SUnit &SU : *SUnits) 1946 CalcNodeSethiUllmanNumber(&SU, SethiUllmanNumbers); 1947 } 1948 1949 void RegReductionPQBase::addNode(const SUnit *SU) { 1950 unsigned SUSize = SethiUllmanNumbers.size(); 1951 if (SUnits->size() > SUSize) 1952 SethiUllmanNumbers.resize(SUSize*2, 0); 1953 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers); 1954 } 1955 1956 void RegReductionPQBase::updateNode(const SUnit *SU) { 1957 SethiUllmanNumbers[SU->NodeNum] = 0; 1958 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers); 1959 } 1960 1961 // Lower priority means schedule further down. For bottom-up scheduling, lower 1962 // priority SUs are scheduled before higher priority SUs. 1963 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const { 1964 assert(SU->NodeNum < SethiUllmanNumbers.size()); 1965 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0; 1966 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg) 1967 // CopyToReg should be close to its uses to facilitate coalescing and 1968 // avoid spilling. 1969 return 0; 1970 if (Opc == TargetOpcode::EXTRACT_SUBREG || 1971 Opc == TargetOpcode::SUBREG_TO_REG || 1972 Opc == TargetOpcode::INSERT_SUBREG) 1973 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be 1974 // close to their uses to facilitate coalescing. 1975 return 0; 1976 if (SU->NumSuccs == 0 && SU->NumPreds != 0) 1977 // If SU does not have a register use, i.e. it doesn't produce a value 1978 // that would be consumed (e.g. store), then it terminates a chain of 1979 // computation. Give it a large SethiUllman number so it will be 1980 // scheduled right before its predecessors that it doesn't lengthen 1981 // their live ranges. 1982 return 0xffff; 1983 if (SU->NumPreds == 0 && SU->NumSuccs != 0) 1984 // If SU does not have a register def, schedule it close to its uses 1985 // because it does not lengthen any live ranges. 1986 return 0; 1987 #if 1 1988 return SethiUllmanNumbers[SU->NodeNum]; 1989 #else 1990 unsigned Priority = SethiUllmanNumbers[SU->NodeNum]; 1991 if (SU->isCallOp) { 1992 // FIXME: This assumes all of the defs are used as call operands. 1993 int NP = (int)Priority - SU->getNode()->getNumValues(); 1994 return (NP > 0) ? NP : 0; 1995 } 1996 return Priority; 1997 #endif 1998 } 1999 2000 //===----------------------------------------------------------------------===// 2001 // Register Pressure Tracking 2002 //===----------------------------------------------------------------------===// 2003 2004 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2005 LLVM_DUMP_METHOD void RegReductionPQBase::dumpRegPressure() const { 2006 for (const TargetRegisterClass *RC : TRI->regclasses()) { 2007 unsigned Id = RC->getID(); 2008 unsigned RP = RegPressure[Id]; 2009 if (!RP) continue; 2010 DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / " 2011 << RegLimit[Id] << '\n'); 2012 } 2013 } 2014 #endif 2015 2016 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const { 2017 if (!TLI) 2018 return false; 2019 2020 for (const SDep &Pred : SU->Preds) { 2021 if (Pred.isCtrl()) 2022 continue; 2023 SUnit *PredSU = Pred.getSUnit(); 2024 // NumRegDefsLeft is zero when enough uses of this node have been scheduled 2025 // to cover the number of registers defined (they are all live). 2026 if (PredSU->NumRegDefsLeft == 0) { 2027 continue; 2028 } 2029 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG); 2030 RegDefPos.IsValid(); RegDefPos.Advance()) { 2031 unsigned RCId, Cost; 2032 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF); 2033 2034 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId]) 2035 return true; 2036 } 2037 } 2038 return false; 2039 } 2040 2041 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const { 2042 const SDNode *N = SU->getNode(); 2043 2044 if (!N->isMachineOpcode() || !SU->NumSuccs) 2045 return false; 2046 2047 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs(); 2048 for (unsigned i = 0; i != NumDefs; ++i) { 2049 MVT VT = N->getSimpleValueType(i); 2050 if (!N->hasAnyUseOfValue(i)) 2051 continue; 2052 unsigned RCId = TLI->getRepRegClassFor(VT)->getID(); 2053 if (RegPressure[RCId] >= RegLimit[RCId]) 2054 return true; 2055 } 2056 return false; 2057 } 2058 2059 // Compute the register pressure contribution by this instruction by count up 2060 // for uses that are not live and down for defs. Only count register classes 2061 // that are already under high pressure. As a side effect, compute the number of 2062 // uses of registers that are already live. 2063 // 2064 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure 2065 // so could probably be factored. 2066 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const { 2067 LiveUses = 0; 2068 int PDiff = 0; 2069 for (const SDep &Pred : SU->Preds) { 2070 if (Pred.isCtrl()) 2071 continue; 2072 SUnit *PredSU = Pred.getSUnit(); 2073 // NumRegDefsLeft is zero when enough uses of this node have been scheduled 2074 // to cover the number of registers defined (they are all live). 2075 if (PredSU->NumRegDefsLeft == 0) { 2076 if (PredSU->getNode()->isMachineOpcode()) 2077 ++LiveUses; 2078 continue; 2079 } 2080 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG); 2081 RegDefPos.IsValid(); RegDefPos.Advance()) { 2082 MVT VT = RegDefPos.GetValue(); 2083 unsigned RCId = TLI->getRepRegClassFor(VT)->getID(); 2084 if (RegPressure[RCId] >= RegLimit[RCId]) 2085 ++PDiff; 2086 } 2087 } 2088 const SDNode *N = SU->getNode(); 2089 2090 if (!N || !N->isMachineOpcode() || !SU->NumSuccs) 2091 return PDiff; 2092 2093 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs(); 2094 for (unsigned i = 0; i != NumDefs; ++i) { 2095 MVT VT = N->getSimpleValueType(i); 2096 if (!N->hasAnyUseOfValue(i)) 2097 continue; 2098 unsigned RCId = TLI->getRepRegClassFor(VT)->getID(); 2099 if (RegPressure[RCId] >= RegLimit[RCId]) 2100 --PDiff; 2101 } 2102 return PDiff; 2103 } 2104 2105 void RegReductionPQBase::scheduledNode(SUnit *SU) { 2106 if (!TracksRegPressure) 2107 return; 2108 2109 if (!SU->getNode()) 2110 return; 2111 2112 for (const SDep &Pred : SU->Preds) { 2113 if (Pred.isCtrl()) 2114 continue; 2115 SUnit *PredSU = Pred.getSUnit(); 2116 // NumRegDefsLeft is zero when enough uses of this node have been scheduled 2117 // to cover the number of registers defined (they are all live). 2118 if (PredSU->NumRegDefsLeft == 0) { 2119 continue; 2120 } 2121 // FIXME: The ScheduleDAG currently loses information about which of a 2122 // node's values is consumed by each dependence. Consequently, if the node 2123 // defines multiple register classes, we don't know which to pressurize 2124 // here. Instead the following loop consumes the register defs in an 2125 // arbitrary order. At least it handles the common case of clustered loads 2126 // to the same class. For precise liveness, each SDep needs to indicate the 2127 // result number. But that tightly couples the ScheduleDAG with the 2128 // SelectionDAG making updates tricky. A simpler hack would be to attach a 2129 // value type or register class to SDep. 2130 // 2131 // The most important aspect of register tracking is balancing the increase 2132 // here with the reduction further below. Note that this SU may use multiple 2133 // defs in PredSU. The can't be determined here, but we've already 2134 // compensated by reducing NumRegDefsLeft in PredSU during 2135 // ScheduleDAGSDNodes::AddSchedEdges. 2136 --PredSU->NumRegDefsLeft; 2137 unsigned SkipRegDefs = PredSU->NumRegDefsLeft; 2138 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG); 2139 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) { 2140 if (SkipRegDefs) 2141 continue; 2142 2143 unsigned RCId, Cost; 2144 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF); 2145 RegPressure[RCId] += Cost; 2146 break; 2147 } 2148 } 2149 2150 // We should have this assert, but there may be dead SDNodes that never 2151 // materialize as SUnits, so they don't appear to generate liveness. 2152 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses"); 2153 int SkipRegDefs = (int)SU->NumRegDefsLeft; 2154 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG); 2155 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) { 2156 if (SkipRegDefs > 0) 2157 continue; 2158 unsigned RCId, Cost; 2159 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF); 2160 if (RegPressure[RCId] < Cost) { 2161 // Register pressure tracking is imprecise. This can happen. But we try 2162 // hard not to let it happen because it likely results in poor scheduling. 2163 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n"); 2164 RegPressure[RCId] = 0; 2165 } 2166 else { 2167 RegPressure[RCId] -= Cost; 2168 } 2169 } 2170 DEBUG(dumpRegPressure()); 2171 } 2172 2173 void RegReductionPQBase::unscheduledNode(SUnit *SU) { 2174 if (!TracksRegPressure) 2175 return; 2176 2177 const SDNode *N = SU->getNode(); 2178 if (!N) return; 2179 2180 if (!N->isMachineOpcode()) { 2181 if (N->getOpcode() != ISD::CopyToReg) 2182 return; 2183 } else { 2184 unsigned Opc = N->getMachineOpcode(); 2185 if (Opc == TargetOpcode::EXTRACT_SUBREG || 2186 Opc == TargetOpcode::INSERT_SUBREG || 2187 Opc == TargetOpcode::SUBREG_TO_REG || 2188 Opc == TargetOpcode::REG_SEQUENCE || 2189 Opc == TargetOpcode::IMPLICIT_DEF) 2190 return; 2191 } 2192 2193 for (const SDep &Pred : SU->Preds) { 2194 if (Pred.isCtrl()) 2195 continue; 2196 SUnit *PredSU = Pred.getSUnit(); 2197 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only 2198 // counts data deps. 2199 if (PredSU->NumSuccsLeft != PredSU->Succs.size()) 2200 continue; 2201 const SDNode *PN = PredSU->getNode(); 2202 if (!PN->isMachineOpcode()) { 2203 if (PN->getOpcode() == ISD::CopyFromReg) { 2204 MVT VT = PN->getSimpleValueType(0); 2205 unsigned RCId = TLI->getRepRegClassFor(VT)->getID(); 2206 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT); 2207 } 2208 continue; 2209 } 2210 unsigned POpc = PN->getMachineOpcode(); 2211 if (POpc == TargetOpcode::IMPLICIT_DEF) 2212 continue; 2213 if (POpc == TargetOpcode::EXTRACT_SUBREG || 2214 POpc == TargetOpcode::INSERT_SUBREG || 2215 POpc == TargetOpcode::SUBREG_TO_REG) { 2216 MVT VT = PN->getSimpleValueType(0); 2217 unsigned RCId = TLI->getRepRegClassFor(VT)->getID(); 2218 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT); 2219 continue; 2220 } 2221 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs(); 2222 for (unsigned i = 0; i != NumDefs; ++i) { 2223 MVT VT = PN->getSimpleValueType(i); 2224 if (!PN->hasAnyUseOfValue(i)) 2225 continue; 2226 unsigned RCId = TLI->getRepRegClassFor(VT)->getID(); 2227 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT)) 2228 // Register pressure tracking is imprecise. This can happen. 2229 RegPressure[RCId] = 0; 2230 else 2231 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT); 2232 } 2233 } 2234 2235 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses() 2236 // may transfer data dependencies to CopyToReg. 2237 if (SU->NumSuccs && N->isMachineOpcode()) { 2238 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs(); 2239 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) { 2240 MVT VT = N->getSimpleValueType(i); 2241 if (VT == MVT::Glue || VT == MVT::Other) 2242 continue; 2243 if (!N->hasAnyUseOfValue(i)) 2244 continue; 2245 unsigned RCId = TLI->getRepRegClassFor(VT)->getID(); 2246 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT); 2247 } 2248 } 2249 2250 DEBUG(dumpRegPressure()); 2251 } 2252 2253 //===----------------------------------------------------------------------===// 2254 // Dynamic Node Priority for Register Pressure Reduction 2255 //===----------------------------------------------------------------------===// 2256 2257 /// closestSucc - Returns the scheduled cycle of the successor which is 2258 /// closest to the current cycle. 2259 static unsigned closestSucc(const SUnit *SU) { 2260 unsigned MaxHeight = 0; 2261 for (const SDep &Succ : SU->Succs) { 2262 if (Succ.isCtrl()) continue; // ignore chain succs 2263 unsigned Height = Succ.getSUnit()->getHeight(); 2264 // If there are bunch of CopyToRegs stacked up, they should be considered 2265 // to be at the same position. 2266 if (Succ.getSUnit()->getNode() && 2267 Succ.getSUnit()->getNode()->getOpcode() == ISD::CopyToReg) 2268 Height = closestSucc(Succ.getSUnit())+1; 2269 if (Height > MaxHeight) 2270 MaxHeight = Height; 2271 } 2272 return MaxHeight; 2273 } 2274 2275 /// calcMaxScratches - Returns an cost estimate of the worse case requirement 2276 /// for scratch registers, i.e. number of data dependencies. 2277 static unsigned calcMaxScratches(const SUnit *SU) { 2278 unsigned Scratches = 0; 2279 for (const SDep &Pred : SU->Preds) { 2280 if (Pred.isCtrl()) continue; // ignore chain preds 2281 Scratches++; 2282 } 2283 return Scratches; 2284 } 2285 2286 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are 2287 /// CopyFromReg from a virtual register. 2288 static bool hasOnlyLiveInOpers(const SUnit *SU) { 2289 bool RetVal = false; 2290 for (const SDep &Pred : SU->Preds) { 2291 if (Pred.isCtrl()) continue; 2292 const SUnit *PredSU = Pred.getSUnit(); 2293 if (PredSU->getNode() && 2294 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) { 2295 unsigned Reg = 2296 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg(); 2297 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 2298 RetVal = true; 2299 continue; 2300 } 2301 } 2302 return false; 2303 } 2304 return RetVal; 2305 } 2306 2307 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are 2308 /// CopyToReg to a virtual register. This SU def is probably a liveout and 2309 /// it has no other use. It should be scheduled closer to the terminator. 2310 static bool hasOnlyLiveOutUses(const SUnit *SU) { 2311 bool RetVal = false; 2312 for (const SDep &Succ : SU->Succs) { 2313 if (Succ.isCtrl()) continue; 2314 const SUnit *SuccSU = Succ.getSUnit(); 2315 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) { 2316 unsigned Reg = 2317 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg(); 2318 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 2319 RetVal = true; 2320 continue; 2321 } 2322 } 2323 return false; 2324 } 2325 return RetVal; 2326 } 2327 2328 // Set isVRegCycle for a node with only live in opers and live out uses. Also 2329 // set isVRegCycle for its CopyFromReg operands. 2330 // 2331 // This is only relevant for single-block loops, in which case the VRegCycle 2332 // node is likely an induction variable in which the operand and target virtual 2333 // registers should be coalesced (e.g. pre/post increment values). Setting the 2334 // isVRegCycle flag helps the scheduler prioritize other uses of the same 2335 // CopyFromReg so that this node becomes the virtual register "kill". This 2336 // avoids interference between the values live in and out of the block and 2337 // eliminates a copy inside the loop. 2338 static void initVRegCycle(SUnit *SU) { 2339 if (DisableSchedVRegCycle) 2340 return; 2341 2342 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU)) 2343 return; 2344 2345 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n"); 2346 2347 SU->isVRegCycle = true; 2348 2349 for (const SDep &Pred : SU->Preds) { 2350 if (Pred.isCtrl()) continue; 2351 Pred.getSUnit()->isVRegCycle = true; 2352 } 2353 } 2354 2355 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of 2356 // CopyFromReg operands. We should no longer penalize other uses of this VReg. 2357 static void resetVRegCycle(SUnit *SU) { 2358 if (!SU->isVRegCycle) 2359 return; 2360 2361 for (const SDep &Pred : SU->Preds) { 2362 if (Pred.isCtrl()) continue; // ignore chain preds 2363 SUnit *PredSU = Pred.getSUnit(); 2364 if (PredSU->isVRegCycle) { 2365 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg && 2366 "VRegCycle def must be CopyFromReg"); 2367 Pred.getSUnit()->isVRegCycle = false; 2368 } 2369 } 2370 } 2371 2372 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This 2373 // means a node that defines the VRegCycle has not been scheduled yet. 2374 static bool hasVRegCycleUse(const SUnit *SU) { 2375 // If this SU also defines the VReg, don't hoist it as a "use". 2376 if (SU->isVRegCycle) 2377 return false; 2378 2379 for (const SDep &Pred : SU->Preds) { 2380 if (Pred.isCtrl()) continue; // ignore chain preds 2381 if (Pred.getSUnit()->isVRegCycle && 2382 Pred.getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) { 2383 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n"); 2384 return true; 2385 } 2386 } 2387 return false; 2388 } 2389 2390 // Check for either a dependence (latency) or resource (hazard) stall. 2391 // 2392 // Note: The ScheduleHazardRecognizer interface requires a non-const SU. 2393 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) { 2394 if ((int)SPQ->getCurCycle() < Height) return true; 2395 if (SPQ->getHazardRec()->getHazardType(SU, 0) 2396 != ScheduleHazardRecognizer::NoHazard) 2397 return true; 2398 return false; 2399 } 2400 2401 // Return -1 if left has higher priority, 1 if right has higher priority. 2402 // Return 0 if latency-based priority is equivalent. 2403 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref, 2404 RegReductionPQBase *SPQ) { 2405 // Scheduling an instruction that uses a VReg whose postincrement has not yet 2406 // been scheduled will induce a copy. Model this as an extra cycle of latency. 2407 int LPenalty = hasVRegCycleUse(left) ? 1 : 0; 2408 int RPenalty = hasVRegCycleUse(right) ? 1 : 0; 2409 int LHeight = (int)left->getHeight() + LPenalty; 2410 int RHeight = (int)right->getHeight() + RPenalty; 2411 2412 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) && 2413 BUHasStall(left, LHeight, SPQ); 2414 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) && 2415 BUHasStall(right, RHeight, SPQ); 2416 2417 // If scheduling one of the node will cause a pipeline stall, delay it. 2418 // If scheduling either one of the node will cause a pipeline stall, sort 2419 // them according to their height. 2420 if (LStall) { 2421 if (!RStall) 2422 return 1; 2423 if (LHeight != RHeight) 2424 return LHeight > RHeight ? 1 : -1; 2425 } else if (RStall) 2426 return -1; 2427 2428 // If either node is scheduling for latency, sort them by height/depth 2429 // and latency. 2430 if (!checkPref || (left->SchedulingPref == Sched::ILP || 2431 right->SchedulingPref == Sched::ILP)) { 2432 // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer 2433 // is enabled, grouping instructions by cycle, then its height is already 2434 // covered so only its depth matters. We also reach this point if both stall 2435 // but have the same height. 2436 if (!SPQ->getHazardRec()->isEnabled()) { 2437 if (LHeight != RHeight) 2438 return LHeight > RHeight ? 1 : -1; 2439 } 2440 int LDepth = left->getDepth() - LPenalty; 2441 int RDepth = right->getDepth() - RPenalty; 2442 if (LDepth != RDepth) { 2443 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum 2444 << ") depth " << LDepth << " vs SU (" << right->NodeNum 2445 << ") depth " << RDepth << "\n"); 2446 return LDepth < RDepth ? 1 : -1; 2447 } 2448 if (left->Latency != right->Latency) 2449 return left->Latency > right->Latency ? 1 : -1; 2450 } 2451 return 0; 2452 } 2453 2454 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) { 2455 // Schedule physical register definitions close to their use. This is 2456 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as 2457 // long as shortening physreg live ranges is generally good, we can defer 2458 // creating a subtarget hook. 2459 if (!DisableSchedPhysRegJoin) { 2460 bool LHasPhysReg = left->hasPhysRegDefs; 2461 bool RHasPhysReg = right->hasPhysRegDefs; 2462 if (LHasPhysReg != RHasPhysReg) { 2463 #ifndef NDEBUG 2464 static const char *const PhysRegMsg[] = { " has no physreg", 2465 " defines a physreg" }; 2466 #endif 2467 DEBUG(dbgs() << " SU (" << left->NodeNum << ") " 2468 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") " 2469 << PhysRegMsg[RHasPhysReg] << "\n"); 2470 return LHasPhysReg < RHasPhysReg; 2471 } 2472 } 2473 2474 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down. 2475 unsigned LPriority = SPQ->getNodePriority(left); 2476 unsigned RPriority = SPQ->getNodePriority(right); 2477 2478 // Be really careful about hoisting call operands above previous calls. 2479 // Only allows it if it would reduce register pressure. 2480 if (left->isCall && right->isCallOp) { 2481 unsigned RNumVals = right->getNode()->getNumValues(); 2482 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0; 2483 } 2484 if (right->isCall && left->isCallOp) { 2485 unsigned LNumVals = left->getNode()->getNumValues(); 2486 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0; 2487 } 2488 2489 if (LPriority != RPriority) 2490 return LPriority > RPriority; 2491 2492 // One or both of the nodes are calls and their sethi-ullman numbers are the 2493 // same, then keep source order. 2494 if (left->isCall || right->isCall) { 2495 unsigned LOrder = SPQ->getNodeOrdering(left); 2496 unsigned ROrder = SPQ->getNodeOrdering(right); 2497 2498 // Prefer an ordering where the lower the non-zero order number, the higher 2499 // the preference. 2500 if ((LOrder || ROrder) && LOrder != ROrder) 2501 return LOrder != 0 && (LOrder < ROrder || ROrder == 0); 2502 } 2503 2504 // Try schedule def + use closer when Sethi-Ullman numbers are the same. 2505 // e.g. 2506 // t1 = op t2, c1 2507 // t3 = op t4, c2 2508 // 2509 // and the following instructions are both ready. 2510 // t2 = op c3 2511 // t4 = op c4 2512 // 2513 // Then schedule t2 = op first. 2514 // i.e. 2515 // t4 = op c4 2516 // t2 = op c3 2517 // t1 = op t2, c1 2518 // t3 = op t4, c2 2519 // 2520 // This creates more short live intervals. 2521 unsigned LDist = closestSucc(left); 2522 unsigned RDist = closestSucc(right); 2523 if (LDist != RDist) 2524 return LDist < RDist; 2525 2526 // How many registers becomes live when the node is scheduled. 2527 unsigned LScratch = calcMaxScratches(left); 2528 unsigned RScratch = calcMaxScratches(right); 2529 if (LScratch != RScratch) 2530 return LScratch > RScratch; 2531 2532 // Comparing latency against a call makes little sense unless the node 2533 // is register pressure-neutral. 2534 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0)) 2535 return (left->NodeQueueId > right->NodeQueueId); 2536 2537 // Do not compare latencies when one or both of the nodes are calls. 2538 if (!DisableSchedCycles && 2539 !(left->isCall || right->isCall)) { 2540 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ); 2541 if (result != 0) 2542 return result > 0; 2543 } 2544 else { 2545 if (left->getHeight() != right->getHeight()) 2546 return left->getHeight() > right->getHeight(); 2547 2548 if (left->getDepth() != right->getDepth()) 2549 return left->getDepth() < right->getDepth(); 2550 } 2551 2552 assert(left->NodeQueueId && right->NodeQueueId && 2553 "NodeQueueId cannot be zero"); 2554 return (left->NodeQueueId > right->NodeQueueId); 2555 } 2556 2557 // Bottom up 2558 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const { 2559 if (int res = checkSpecialNodes(left, right)) 2560 return res > 0; 2561 2562 return BURRSort(left, right, SPQ); 2563 } 2564 2565 // Source order, otherwise bottom up. 2566 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const { 2567 if (int res = checkSpecialNodes(left, right)) 2568 return res > 0; 2569 2570 unsigned LOrder = SPQ->getNodeOrdering(left); 2571 unsigned ROrder = SPQ->getNodeOrdering(right); 2572 2573 // Prefer an ordering where the lower the non-zero order number, the higher 2574 // the preference. 2575 if ((LOrder || ROrder) && LOrder != ROrder) 2576 return LOrder != 0 && (LOrder < ROrder || ROrder == 0); 2577 2578 return BURRSort(left, right, SPQ); 2579 } 2580 2581 // If the time between now and when the instruction will be ready can cover 2582 // the spill code, then avoid adding it to the ready queue. This gives long 2583 // stalls highest priority and allows hoisting across calls. It should also 2584 // speed up processing the available queue. 2585 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const { 2586 static const unsigned ReadyDelay = 3; 2587 2588 if (SPQ->MayReduceRegPressure(SU)) return true; 2589 2590 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false; 2591 2592 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay) 2593 != ScheduleHazardRecognizer::NoHazard) 2594 return false; 2595 2596 return true; 2597 } 2598 2599 // Return true if right should be scheduled with higher priority than left. 2600 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const { 2601 if (int res = checkSpecialNodes(left, right)) 2602 return res > 0; 2603 2604 if (left->isCall || right->isCall) 2605 // No way to compute latency of calls. 2606 return BURRSort(left, right, SPQ); 2607 2608 bool LHigh = SPQ->HighRegPressure(left); 2609 bool RHigh = SPQ->HighRegPressure(right); 2610 // Avoid causing spills. If register pressure is high, schedule for 2611 // register pressure reduction. 2612 if (LHigh && !RHigh) { 2613 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU(" 2614 << right->NodeNum << ")\n"); 2615 return true; 2616 } 2617 else if (!LHigh && RHigh) { 2618 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU(" 2619 << left->NodeNum << ")\n"); 2620 return false; 2621 } 2622 if (!LHigh && !RHigh) { 2623 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ); 2624 if (result != 0) 2625 return result > 0; 2626 } 2627 return BURRSort(left, right, SPQ); 2628 } 2629 2630 // Schedule as many instructions in each cycle as possible. So don't make an 2631 // instruction available unless it is ready in the current cycle. 2632 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const { 2633 if (SU->getHeight() > CurCycle) return false; 2634 2635 if (SPQ->getHazardRec()->getHazardType(SU, 0) 2636 != ScheduleHazardRecognizer::NoHazard) 2637 return false; 2638 2639 return true; 2640 } 2641 2642 static bool canEnableCoalescing(SUnit *SU) { 2643 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0; 2644 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg) 2645 // CopyToReg should be close to its uses to facilitate coalescing and 2646 // avoid spilling. 2647 return true; 2648 2649 if (Opc == TargetOpcode::EXTRACT_SUBREG || 2650 Opc == TargetOpcode::SUBREG_TO_REG || 2651 Opc == TargetOpcode::INSERT_SUBREG) 2652 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be 2653 // close to their uses to facilitate coalescing. 2654 return true; 2655 2656 if (SU->NumPreds == 0 && SU->NumSuccs != 0) 2657 // If SU does not have a register def, schedule it close to its uses 2658 // because it does not lengthen any live ranges. 2659 return true; 2660 2661 return false; 2662 } 2663 2664 // list-ilp is currently an experimental scheduler that allows various 2665 // heuristics to be enabled prior to the normal register reduction logic. 2666 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const { 2667 if (int res = checkSpecialNodes(left, right)) 2668 return res > 0; 2669 2670 if (left->isCall || right->isCall) 2671 // No way to compute latency of calls. 2672 return BURRSort(left, right, SPQ); 2673 2674 unsigned LLiveUses = 0, RLiveUses = 0; 2675 int LPDiff = 0, RPDiff = 0; 2676 if (!DisableSchedRegPressure || !DisableSchedLiveUses) { 2677 LPDiff = SPQ->RegPressureDiff(left, LLiveUses); 2678 RPDiff = SPQ->RegPressureDiff(right, RLiveUses); 2679 } 2680 if (!DisableSchedRegPressure && LPDiff != RPDiff) { 2681 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff 2682 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n"); 2683 return LPDiff > RPDiff; 2684 } 2685 2686 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) { 2687 bool LReduce = canEnableCoalescing(left); 2688 bool RReduce = canEnableCoalescing(right); 2689 if (LReduce && !RReduce) return false; 2690 if (RReduce && !LReduce) return true; 2691 } 2692 2693 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) { 2694 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses 2695 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n"); 2696 return LLiveUses < RLiveUses; 2697 } 2698 2699 if (!DisableSchedStalls) { 2700 bool LStall = BUHasStall(left, left->getHeight(), SPQ); 2701 bool RStall = BUHasStall(right, right->getHeight(), SPQ); 2702 if (LStall != RStall) 2703 return left->getHeight() > right->getHeight(); 2704 } 2705 2706 if (!DisableSchedCriticalPath) { 2707 int spread = (int)left->getDepth() - (int)right->getDepth(); 2708 if (std::abs(spread) > MaxReorderWindow) { 2709 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): " 2710 << left->getDepth() << " != SU(" << right->NodeNum << "): " 2711 << right->getDepth() << "\n"); 2712 return left->getDepth() < right->getDepth(); 2713 } 2714 } 2715 2716 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) { 2717 int spread = (int)left->getHeight() - (int)right->getHeight(); 2718 if (std::abs(spread) > MaxReorderWindow) 2719 return left->getHeight() > right->getHeight(); 2720 } 2721 2722 return BURRSort(left, right, SPQ); 2723 } 2724 2725 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) { 2726 SUnits = &sunits; 2727 // Add pseudo dependency edges for two-address nodes. 2728 if (!Disable2AddrHack) 2729 AddPseudoTwoAddrDeps(); 2730 // Reroute edges to nodes with multiple uses. 2731 if (!TracksRegPressure && !SrcOrder) 2732 PrescheduleNodesWithMultipleUses(); 2733 // Calculate node priorities. 2734 CalculateSethiUllmanNumbers(); 2735 2736 // For single block loops, mark nodes that look like canonical IV increments. 2737 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) 2738 for (SUnit &SU : sunits) 2739 initVRegCycle(&SU); 2740 } 2741 2742 //===----------------------------------------------------------------------===// 2743 // Preschedule for Register Pressure 2744 //===----------------------------------------------------------------------===// 2745 2746 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) { 2747 if (SU->isTwoAddress) { 2748 unsigned Opc = SU->getNode()->getMachineOpcode(); 2749 const MCInstrDesc &MCID = TII->get(Opc); 2750 unsigned NumRes = MCID.getNumDefs(); 2751 unsigned NumOps = MCID.getNumOperands() - NumRes; 2752 for (unsigned i = 0; i != NumOps; ++i) { 2753 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) { 2754 SDNode *DU = SU->getNode()->getOperand(i).getNode(); 2755 if (DU->getNodeId() != -1 && 2756 Op->OrigNode == &(*SUnits)[DU->getNodeId()]) 2757 return true; 2758 } 2759 } 2760 } 2761 return false; 2762 } 2763 2764 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's 2765 /// successor's explicit physregs whose definition can reach DepSU. 2766 /// i.e. DepSU should not be scheduled above SU. 2767 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU, 2768 ScheduleDAGRRList *scheduleDAG, 2769 const TargetInstrInfo *TII, 2770 const TargetRegisterInfo *TRI) { 2771 const MCPhysReg *ImpDefs 2772 = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs(); 2773 const uint32_t *RegMask = getNodeRegMask(SU->getNode()); 2774 if(!ImpDefs && !RegMask) 2775 return false; 2776 2777 for (const SDep &Succ : SU->Succs) { 2778 SUnit *SuccSU = Succ.getSUnit(); 2779 for (const SDep &SuccPred : SuccSU->Preds) { 2780 if (!SuccPred.isAssignedRegDep()) 2781 continue; 2782 2783 if (RegMask && 2784 MachineOperand::clobbersPhysReg(RegMask, SuccPred.getReg()) && 2785 scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit())) 2786 return true; 2787 2788 if (ImpDefs) 2789 for (const MCPhysReg *ImpDef = ImpDefs; *ImpDef; ++ImpDef) 2790 // Return true if SU clobbers this physical register use and the 2791 // definition of the register reaches from DepSU. IsReachable queries 2792 // a topological forward sort of the DAG (following the successors). 2793 if (TRI->regsOverlap(*ImpDef, SuccPred.getReg()) && 2794 scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit())) 2795 return true; 2796 } 2797 } 2798 return false; 2799 } 2800 2801 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's 2802 /// physical register defs. 2803 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU, 2804 const TargetInstrInfo *TII, 2805 const TargetRegisterInfo *TRI) { 2806 SDNode *N = SuccSU->getNode(); 2807 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs(); 2808 const MCPhysReg *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs(); 2809 assert(ImpDefs && "Caller should check hasPhysRegDefs"); 2810 for (const SDNode *SUNode = SU->getNode(); SUNode; 2811 SUNode = SUNode->getGluedNode()) { 2812 if (!SUNode->isMachineOpcode()) 2813 continue; 2814 const MCPhysReg *SUImpDefs = 2815 TII->get(SUNode->getMachineOpcode()).getImplicitDefs(); 2816 const uint32_t *SURegMask = getNodeRegMask(SUNode); 2817 if (!SUImpDefs && !SURegMask) 2818 continue; 2819 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) { 2820 MVT VT = N->getSimpleValueType(i); 2821 if (VT == MVT::Glue || VT == MVT::Other) 2822 continue; 2823 if (!N->hasAnyUseOfValue(i)) 2824 continue; 2825 unsigned Reg = ImpDefs[i - NumDefs]; 2826 if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg)) 2827 return true; 2828 if (!SUImpDefs) 2829 continue; 2830 for (;*SUImpDefs; ++SUImpDefs) { 2831 unsigned SUReg = *SUImpDefs; 2832 if (TRI->regsOverlap(Reg, SUReg)) 2833 return true; 2834 } 2835 } 2836 } 2837 return false; 2838 } 2839 2840 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses 2841 /// are not handled well by the general register pressure reduction 2842 /// heuristics. When presented with code like this: 2843 /// 2844 /// N 2845 /// / | 2846 /// / | 2847 /// U store 2848 /// | 2849 /// ... 2850 /// 2851 /// the heuristics tend to push the store up, but since the 2852 /// operand of the store has another use (U), this would increase 2853 /// the length of that other use (the U->N edge). 2854 /// 2855 /// This function transforms code like the above to route U's 2856 /// dependence through the store when possible, like this: 2857 /// 2858 /// N 2859 /// || 2860 /// || 2861 /// store 2862 /// | 2863 /// U 2864 /// | 2865 /// ... 2866 /// 2867 /// This results in the store being scheduled immediately 2868 /// after N, which shortens the U->N live range, reducing 2869 /// register pressure. 2870 /// 2871 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() { 2872 // Visit all the nodes in topological order, working top-down. 2873 for (SUnit &SU : *SUnits) { 2874 // For now, only look at nodes with no data successors, such as stores. 2875 // These are especially important, due to the heuristics in 2876 // getNodePriority for nodes with no data successors. 2877 if (SU.NumSuccs != 0) 2878 continue; 2879 // For now, only look at nodes with exactly one data predecessor. 2880 if (SU.NumPreds != 1) 2881 continue; 2882 // Avoid prescheduling copies to virtual registers, which don't behave 2883 // like other nodes from the perspective of scheduling heuristics. 2884 if (SDNode *N = SU.getNode()) 2885 if (N->getOpcode() == ISD::CopyToReg && 2886 TargetRegisterInfo::isVirtualRegister 2887 (cast<RegisterSDNode>(N->getOperand(1))->getReg())) 2888 continue; 2889 2890 // Locate the single data predecessor. 2891 SUnit *PredSU = nullptr; 2892 for (const SDep &Pred : SU.Preds) 2893 if (!Pred.isCtrl()) { 2894 PredSU = Pred.getSUnit(); 2895 break; 2896 } 2897 assert(PredSU); 2898 2899 // Don't rewrite edges that carry physregs, because that requires additional 2900 // support infrastructure. 2901 if (PredSU->hasPhysRegDefs) 2902 continue; 2903 // Short-circuit the case where SU is PredSU's only data successor. 2904 if (PredSU->NumSuccs == 1) 2905 continue; 2906 // Avoid prescheduling to copies from virtual registers, which don't behave 2907 // like other nodes from the perspective of scheduling heuristics. 2908 if (SDNode *N = SU.getNode()) 2909 if (N->getOpcode() == ISD::CopyFromReg && 2910 TargetRegisterInfo::isVirtualRegister 2911 (cast<RegisterSDNode>(N->getOperand(1))->getReg())) 2912 continue; 2913 2914 // Perform checks on the successors of PredSU. 2915 for (const SDep &PredSucc : PredSU->Succs) { 2916 SUnit *PredSuccSU = PredSucc.getSUnit(); 2917 if (PredSuccSU == &SU) continue; 2918 // If PredSU has another successor with no data successors, for 2919 // now don't attempt to choose either over the other. 2920 if (PredSuccSU->NumSuccs == 0) 2921 goto outer_loop_continue; 2922 // Don't break physical register dependencies. 2923 if (SU.hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs) 2924 if (canClobberPhysRegDefs(PredSuccSU, &SU, TII, TRI)) 2925 goto outer_loop_continue; 2926 // Don't introduce graph cycles. 2927 if (scheduleDAG->IsReachable(&SU, PredSuccSU)) 2928 goto outer_loop_continue; 2929 } 2930 2931 // Ok, the transformation is safe and the heuristics suggest it is 2932 // profitable. Update the graph. 2933 DEBUG(dbgs() << " Prescheduling SU #" << SU.NodeNum 2934 << " next to PredSU #" << PredSU->NodeNum 2935 << " to guide scheduling in the presence of multiple uses\n"); 2936 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) { 2937 SDep Edge = PredSU->Succs[i]; 2938 assert(!Edge.isAssignedRegDep()); 2939 SUnit *SuccSU = Edge.getSUnit(); 2940 if (SuccSU != &SU) { 2941 Edge.setSUnit(PredSU); 2942 scheduleDAG->RemovePred(SuccSU, Edge); 2943 scheduleDAG->AddPred(&SU, Edge); 2944 Edge.setSUnit(&SU); 2945 scheduleDAG->AddPred(SuccSU, Edge); 2946 --i; 2947 } 2948 } 2949 outer_loop_continue:; 2950 } 2951 } 2952 2953 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses 2954 /// it as a def&use operand. Add a pseudo control edge from it to the other 2955 /// node (if it won't create a cycle) so the two-address one will be scheduled 2956 /// first (lower in the schedule). If both nodes are two-address, favor the 2957 /// one that has a CopyToReg use (more likely to be a loop induction update). 2958 /// If both are two-address, but one is commutable while the other is not 2959 /// commutable, favor the one that's not commutable. 2960 void RegReductionPQBase::AddPseudoTwoAddrDeps() { 2961 for (SUnit &SU : *SUnits) { 2962 if (!SU.isTwoAddress) 2963 continue; 2964 2965 SDNode *Node = SU.getNode(); 2966 if (!Node || !Node->isMachineOpcode() || SU.getNode()->getGluedNode()) 2967 continue; 2968 2969 bool isLiveOut = hasOnlyLiveOutUses(&SU); 2970 unsigned Opc = Node->getMachineOpcode(); 2971 const MCInstrDesc &MCID = TII->get(Opc); 2972 unsigned NumRes = MCID.getNumDefs(); 2973 unsigned NumOps = MCID.getNumOperands() - NumRes; 2974 for (unsigned j = 0; j != NumOps; ++j) { 2975 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1) 2976 continue; 2977 SDNode *DU = SU.getNode()->getOperand(j).getNode(); 2978 if (DU->getNodeId() == -1) 2979 continue; 2980 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()]; 2981 if (!DUSU) 2982 continue; 2983 for (const SDep &Succ : DUSU->Succs) { 2984 if (Succ.isCtrl()) 2985 continue; 2986 SUnit *SuccSU = Succ.getSUnit(); 2987 if (SuccSU == &SU) 2988 continue; 2989 // Be conservative. Ignore if nodes aren't at roughly the same 2990 // depth and height. 2991 if (SuccSU->getHeight() < SU.getHeight() && 2992 (SU.getHeight() - SuccSU->getHeight()) > 1) 2993 continue; 2994 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge 2995 // constrains whatever is using the copy, instead of the copy 2996 // itself. In the case that the copy is coalesced, this 2997 // preserves the intent of the pseudo two-address heurietics. 2998 while (SuccSU->Succs.size() == 1 && 2999 SuccSU->getNode()->isMachineOpcode() && 3000 SuccSU->getNode()->getMachineOpcode() == 3001 TargetOpcode::COPY_TO_REGCLASS) 3002 SuccSU = SuccSU->Succs.front().getSUnit(); 3003 // Don't constrain non-instruction nodes. 3004 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode()) 3005 continue; 3006 // Don't constrain nodes with physical register defs if the 3007 // predecessor can clobber them. 3008 if (SuccSU->hasPhysRegDefs && SU.hasPhysRegClobbers) { 3009 if (canClobberPhysRegDefs(SuccSU, &SU, TII, TRI)) 3010 continue; 3011 } 3012 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG; 3013 // these may be coalesced away. We want them close to their uses. 3014 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode(); 3015 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG || 3016 SuccOpc == TargetOpcode::INSERT_SUBREG || 3017 SuccOpc == TargetOpcode::SUBREG_TO_REG) 3018 continue; 3019 if (!canClobberReachingPhysRegUse(SuccSU, &SU, scheduleDAG, TII, TRI) && 3020 (!canClobber(SuccSU, DUSU) || 3021 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) || 3022 (!SU.isCommutable && SuccSU->isCommutable)) && 3023 !scheduleDAG->IsReachable(SuccSU, &SU)) { 3024 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #" 3025 << SU.NodeNum << " to SU #" << SuccSU->NodeNum << "\n"); 3026 scheduleDAG->AddPred(&SU, SDep(SuccSU, SDep::Artificial)); 3027 } 3028 } 3029 } 3030 } 3031 } 3032 3033 //===----------------------------------------------------------------------===// 3034 // Public Constructor Functions 3035 //===----------------------------------------------------------------------===// 3036 3037 llvm::ScheduleDAGSDNodes * 3038 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS, 3039 CodeGenOpt::Level OptLevel) { 3040 const TargetSubtargetInfo &STI = IS->MF->getSubtarget(); 3041 const TargetInstrInfo *TII = STI.getInstrInfo(); 3042 const TargetRegisterInfo *TRI = STI.getRegisterInfo(); 3043 3044 BURegReductionPriorityQueue *PQ = 3045 new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr); 3046 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel); 3047 PQ->setScheduleDAG(SD); 3048 return SD; 3049 } 3050 3051 llvm::ScheduleDAGSDNodes * 3052 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS, 3053 CodeGenOpt::Level OptLevel) { 3054 const TargetSubtargetInfo &STI = IS->MF->getSubtarget(); 3055 const TargetInstrInfo *TII = STI.getInstrInfo(); 3056 const TargetRegisterInfo *TRI = STI.getRegisterInfo(); 3057 3058 SrcRegReductionPriorityQueue *PQ = 3059 new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr); 3060 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel); 3061 PQ->setScheduleDAG(SD); 3062 return SD; 3063 } 3064 3065 llvm::ScheduleDAGSDNodes * 3066 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS, 3067 CodeGenOpt::Level OptLevel) { 3068 const TargetSubtargetInfo &STI = IS->MF->getSubtarget(); 3069 const TargetInstrInfo *TII = STI.getInstrInfo(); 3070 const TargetRegisterInfo *TRI = STI.getRegisterInfo(); 3071 const TargetLowering *TLI = IS->TLI; 3072 3073 HybridBURRPriorityQueue *PQ = 3074 new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI); 3075 3076 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel); 3077 PQ->setScheduleDAG(SD); 3078 return SD; 3079 } 3080 3081 llvm::ScheduleDAGSDNodes * 3082 llvm::createILPListDAGScheduler(SelectionDAGISel *IS, 3083 CodeGenOpt::Level OptLevel) { 3084 const TargetSubtargetInfo &STI = IS->MF->getSubtarget(); 3085 const TargetInstrInfo *TII = STI.getInstrInfo(); 3086 const TargetRegisterInfo *TRI = STI.getRegisterInfo(); 3087 const TargetLowering *TLI = IS->TLI; 3088 3089 ILPBURRPriorityQueue *PQ = 3090 new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI); 3091 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel); 3092 PQ->setScheduleDAG(SD); 3093 return SD; 3094 } 3095