1 //===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "pre-RA-sched"
19 #include "ScheduleDAGSDNodes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/CodeGen/SchedulerRegistry.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
38 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
39 STATISTIC(NumUnfolds, "Number of nodes unfolded");
40 STATISTIC(NumDups, "Number of duplicated nodes");
41 STATISTIC(NumPRCopies, "Number of physical register copies");
43 static RegisterScheduler
44 burrListDAGScheduler("list-burr",
45 "Bottom-up register reduction list scheduling",
46 createBURRListDAGScheduler);
47 static RegisterScheduler
48 tdrListrDAGScheduler("list-tdrr",
49 "Top-down register reduction list scheduling",
50 createTDRRListDAGScheduler);
51 static RegisterScheduler
52 sourceListDAGScheduler("source",
53 "Similar to list-burr but schedules in source "
54 "order when possible",
55 createSourceListDAGScheduler);
57 static RegisterScheduler
58 hybridListDAGScheduler("list-hybrid",
59 "Bottom-up register pressure aware list scheduling "
60 "which tries to balance latency and register pressure",
61 createHybridListDAGScheduler);
63 static RegisterScheduler
64 ILPListDAGScheduler("list-ilp",
65 "Bottom-up register pressure aware list scheduling "
66 "which tries to balance ILP and register pressure",
67 createILPListDAGScheduler);
69 static cl::opt<bool> DisableSchedCycles(
70 "disable-sched-cycles", cl::Hidden, cl::init(false),
71 cl::desc("Disable cycle-level precision during preRA scheduling"));
73 // Temporary sched=list-ilp flags until the heuristics are robust.
74 static cl::opt<bool> DisableSchedRegPressure(
75 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
76 cl::desc("Disable regpressure priority in sched=list-ilp"));
77 static cl::opt<bool> DisableSchedLiveUses(
78 "disable-sched-live-uses", cl::Hidden, cl::init(true),
79 cl::desc("Disable live use priority in sched=list-ilp"));
80 static cl::opt<bool> DisableSchedStalls(
81 "disable-sched-stalls", cl::Hidden, cl::init(true),
82 cl::desc("Disable no-stall priority in sched=list-ilp"));
83 static cl::opt<bool> DisableSchedCriticalPath(
84 "disable-sched-critical-path", cl::Hidden, cl::init(false),
85 cl::desc("Disable critical path priority in sched=list-ilp"));
86 static cl::opt<bool> DisableSchedHeight(
87 "disable-sched-height", cl::Hidden, cl::init(false),
88 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
90 static cl::opt<int> MaxReorderWindow(
91 "max-sched-reorder", cl::Hidden, cl::init(6),
92 cl::desc("Number of instructions to allow ahead of the critical path "
93 "in sched=list-ilp"));
95 static cl::opt<unsigned> AvgIPC(
96 "sched-avg-ipc", cl::Hidden, cl::init(1),
97 cl::desc("Average inst/cycle whan no target itinerary exists."));
101 // For sched=list-ilp, Count the number of times each factor comes into play.
102 enum { FactPressureDiff, FactRegUses, FactHeight, FactDepth, FactStatic,
103 FactOther, NumFactors };
105 static const char *FactorName[NumFactors] =
106 {"PressureDiff", "RegUses", "Height", "Depth","Static", "Other"};
107 static int FactorCount[NumFactors];
111 //===----------------------------------------------------------------------===//
112 /// ScheduleDAGRRList - The actual register reduction list scheduler
113 /// implementation. This supports both top-down and bottom-up scheduling.
115 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
117 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
121 /// NeedLatency - True if the scheduler will make use of latency information.
125 /// AvailableQueue - The priority queue to use for the available SUnits.
126 SchedulingPriorityQueue *AvailableQueue;
128 /// PendingQueue - This contains all of the instructions whose operands have
129 /// been issued, but their results are not ready yet (due to the latency of
130 /// the operation). Once the operands becomes available, the instruction is
131 /// added to the AvailableQueue.
132 std::vector<SUnit*> PendingQueue;
134 /// HazardRec - The hazard recognizer to use.
135 ScheduleHazardRecognizer *HazardRec;
137 /// CurCycle - The current scheduler state corresponds to this cycle.
140 /// MinAvailableCycle - Cycle of the soonest available instruction.
141 unsigned MinAvailableCycle;
143 /// IssueCount - Count instructions issued in this cycle
144 /// Currently valid only for bottom-up scheduling.
147 /// LiveRegDefs - A set of physical registers and their definition
148 /// that are "live". These nodes must be scheduled before any other nodes that
149 /// modifies the registers can be scheduled.
150 unsigned NumLiveRegs;
151 std::vector<SUnit*> LiveRegDefs;
152 std::vector<SUnit*> LiveRegGens;
154 /// Topo - A topological ordering for SUnits which permits fast IsReachable
155 /// and similar queries.
156 ScheduleDAGTopologicalSort Topo;
159 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
160 SchedulingPriorityQueue *availqueue,
161 CodeGenOpt::Level OptLevel)
162 : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
163 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
166 const TargetMachine &tm = mf.getTarget();
167 if (DisableSchedCycles || !NeedLatency)
168 HazardRec = new ScheduleHazardRecognizer();
170 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
173 ~ScheduleDAGRRList() {
175 delete AvailableQueue;
180 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
182 /// IsReachable - Checks if SU is reachable from TargetSU.
183 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
184 return Topo.IsReachable(SU, TargetSU);
187 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
189 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
190 return Topo.WillCreateCycle(SU, TargetSU);
193 /// AddPred - adds a predecessor edge to SUnit SU.
194 /// This returns true if this is a new predecessor.
195 /// Updates the topological ordering if required.
196 void AddPred(SUnit *SU, const SDep &D) {
197 Topo.AddPred(SU, D.getSUnit());
201 /// RemovePred - removes a predecessor edge from SUnit SU.
202 /// This returns true if an edge was removed.
203 /// Updates the topological ordering if required.
204 void RemovePred(SUnit *SU, const SDep &D) {
205 Topo.RemovePred(SU, D.getSUnit());
210 bool isReady(SUnit *SU) {
211 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
212 AvailableQueue->isReady(SU);
215 void ReleasePred(SUnit *SU, const SDep *PredEdge);
216 void ReleasePredecessors(SUnit *SU);
217 void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
218 void ReleaseSuccessors(SUnit *SU);
219 void ReleasePending();
220 void AdvanceToCycle(unsigned NextCycle);
221 void AdvancePastStalls(SUnit *SU);
222 void EmitNode(SUnit *SU);
223 void ScheduleNodeBottomUp(SUnit*);
224 void CapturePred(SDep *PredEdge);
225 void UnscheduleNodeBottomUp(SUnit*);
226 void RestoreHazardCheckerBottomUp();
227 void BacktrackBottomUp(SUnit*, SUnit*);
228 SUnit *CopyAndMoveSuccessors(SUnit*);
229 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
230 const TargetRegisterClass*,
231 const TargetRegisterClass*,
232 SmallVector<SUnit*, 2>&);
233 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
235 SUnit *PickNodeToScheduleBottomUp();
236 void ListScheduleBottomUp();
238 void ScheduleNodeTopDown(SUnit*);
239 void ListScheduleTopDown();
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();
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();
264 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
265 /// need actual latency information but the hybrid scheduler does.
266 bool ForceUnitLatencies() const {
270 } // end anonymous namespace
273 /// Schedule - Schedule the DAG using list scheduling.
274 void ScheduleDAGRRList::Schedule() {
276 << "********** List Scheduling BB#" << BB->getNumber()
277 << " '" << BB->getName() << "' **********\n");
279 for (int i = 0; i < NumFactors; ++i) {
286 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
288 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
289 LiveRegGens.resize(TRI->getNumRegs(), NULL);
291 // Build the scheduling graph.
292 BuildSchedGraph(NULL);
294 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
295 SUnits[su].dumpAll(this));
296 Topo.InitDAGTopologicalSorting();
298 AvailableQueue->initNodes(SUnits);
302 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
304 ListScheduleBottomUp();
306 ListScheduleTopDown();
309 for (int i = 0; i < NumFactors; ++i) {
310 DEBUG(dbgs() << FactorName[i] << "\t" << FactorCount[i] << "\n");
313 AvailableQueue->releaseState();
316 //===----------------------------------------------------------------------===//
317 // Bottom-Up Scheduling
318 //===----------------------------------------------------------------------===//
320 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
321 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
322 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
323 SUnit *PredSU = PredEdge->getSUnit();
326 if (PredSU->NumSuccsLeft == 0) {
327 dbgs() << "*** Scheduling failed! ***\n";
329 dbgs() << " has been released too many times!\n";
333 --PredSU->NumSuccsLeft;
335 if (!ForceUnitLatencies()) {
336 // Updating predecessor's height. This is now the cycle when the
337 // predecessor can be scheduled without causing a pipeline stall.
338 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
341 // If all the node's successors are scheduled, this node is ready
342 // to be scheduled. Ignore the special EntrySU node.
343 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
344 PredSU->isAvailable = true;
346 unsigned Height = PredSU->getHeight();
347 if (Height < MinAvailableCycle)
348 MinAvailableCycle = Height;
350 if (isReady(PredSU)) {
351 AvailableQueue->push(PredSU);
353 // CapturePred and others may have left the node in the pending queue, avoid
355 else if (!PredSU->isPending) {
356 PredSU->isPending = true;
357 PendingQueue.push_back(PredSU);
362 /// Call ReleasePred for each predecessor, then update register live def/gen.
363 /// Always update LiveRegDefs for a register dependence even if the current SU
364 /// also defines the register. This effectively create one large live range
365 /// across a sequence of two-address node. This is important because the
366 /// entire chain must be scheduled together. Example:
369 /// flags = (2) addc flags
370 /// flags = (1) addc flags
374 /// LiveRegDefs[flags] = 3
375 /// LiveRegGens[flags] = 1
377 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
378 /// interference on flags.
379 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
380 // Bottom up: release predecessors
381 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
383 ReleasePred(SU, &*I);
384 if (I->isAssignedRegDep()) {
385 // This is a physical register dependency and it's impossible or
386 // expensive to copy the register. Make sure nothing that can
387 // clobber the register is scheduled between the predecessor and
389 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
390 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
391 "interference on register dependence");
392 LiveRegDefs[I->getReg()] = I->getSUnit();
393 if (!LiveRegGens[I->getReg()]) {
395 LiveRegGens[I->getReg()] = SU;
401 /// Check to see if any of the pending instructions are ready to issue. If
402 /// so, add them to the available queue.
403 void ScheduleDAGRRList::ReleasePending() {
404 if (DisableSchedCycles) {
405 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
409 // If the available queue is empty, it is safe to reset MinAvailableCycle.
410 if (AvailableQueue->empty())
411 MinAvailableCycle = UINT_MAX;
413 // Check to see if any of the pending instructions are ready to issue. If
414 // so, add them to the available queue.
415 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
416 unsigned ReadyCycle =
417 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
418 if (ReadyCycle < MinAvailableCycle)
419 MinAvailableCycle = ReadyCycle;
421 if (PendingQueue[i]->isAvailable) {
422 if (!isReady(PendingQueue[i]))
424 AvailableQueue->push(PendingQueue[i]);
426 PendingQueue[i]->isPending = false;
427 PendingQueue[i] = PendingQueue.back();
428 PendingQueue.pop_back();
433 /// Move the scheduler state forward by the specified number of Cycles.
434 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
435 if (NextCycle <= CurCycle)
439 AvailableQueue->setCurCycle(NextCycle);
440 if (!HazardRec->isEnabled()) {
441 // Bypass lots of virtual calls in case of long latency.
442 CurCycle = NextCycle;
445 for (; CurCycle != NextCycle; ++CurCycle) {
447 HazardRec->RecedeCycle();
449 HazardRec->AdvanceCycle();
452 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
453 // available Q to release pending nodes at least once before popping.
457 /// Move the scheduler state forward until the specified node's dependents are
458 /// ready and can be scheduled with no resource conflicts.
459 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
460 if (DisableSchedCycles)
463 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
465 // Bump CurCycle to account for latency. We assume the latency of other
466 // available instructions may be hidden by the stall (not a full pipe stall).
467 // This updates the hazard recognizer's cycle before reserving resources for
469 AdvanceToCycle(ReadyCycle);
471 // Calls are scheduled in their preceding cycle, so don't conflict with
472 // hazards from instructions after the call. EmitNode will reset the
473 // scoreboard state before emitting the call.
474 if (isBottomUp && SU->isCall)
477 // FIXME: For resource conflicts in very long non-pipelined stages, we
478 // should probably skip ahead here to avoid useless scoreboard checks.
481 ScheduleHazardRecognizer::HazardType HT =
482 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
484 if (HT == ScheduleHazardRecognizer::NoHazard)
489 AdvanceToCycle(CurCycle + Stalls);
492 /// Record this SUnit in the HazardRecognizer.
493 /// Does not update CurCycle.
494 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
495 if (!HazardRec->isEnabled())
498 // Check for phys reg copy.
502 switch (SU->getNode()->getOpcode()) {
504 assert(SU->getNode()->isMachineOpcode() &&
505 "This target-independent node should not be scheduled.");
507 case ISD::MERGE_VALUES:
508 case ISD::TokenFactor:
510 case ISD::CopyFromReg:
512 // Noops don't affect the scoreboard state. Copies are likely to be
516 // For inline asm, clear the pipeline state.
520 if (isBottomUp && SU->isCall) {
521 // Calls are scheduled with their preceding instructions. For bottom-up
522 // scheduling, clear the pipeline state before emitting.
526 HazardRec->EmitInstruction(SU);
528 if (!isBottomUp && SU->isCall) {
533 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
534 /// count of its predecessors. If a predecessor pending count is zero, add it to
535 /// the Available queue.
536 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
537 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
538 DEBUG(SU->dump(this));
541 if (CurCycle < SU->getHeight())
542 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
545 // FIXME: Do not modify node height. It may interfere with
546 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
547 // node it's ready cycle can aid heuristics, and after scheduling it can
548 // indicate the scheduled cycle.
549 SU->setHeightToAtLeast(CurCycle);
551 // Reserve resources for the scheduled intruction.
554 Sequence.push_back(SU);
556 AvailableQueue->ScheduledNode(SU);
558 // If HazardRec is disabled, and each inst counts as one cycle, then
559 // advance CurCycle before ReleasePredecessors to avoid useles pushed to
560 // PendingQueue for schedulers that implement HasReadyFilter.
561 if (!HazardRec->isEnabled() && AvgIPC < 2)
562 AdvanceToCycle(CurCycle + 1);
564 // Update liveness of predecessors before successors to avoid treating a
565 // two-address node as a live range def.
566 ReleasePredecessors(SU);
568 // Release all the implicit physical register defs that are live.
569 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
571 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
572 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
573 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
575 LiveRegDefs[I->getReg()] = NULL;
576 LiveRegGens[I->getReg()] = NULL;
580 SU->isScheduled = true;
582 // Conditions under which the scheduler should eagerly advance the cycle:
583 // (1) No available instructions
584 // (2) All pipelines full, so available instructions must have hazards.
586 // If HazardRec is disabled, the cycle was advanced earlier.
588 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
590 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
591 || (!HazardRec->isEnabled() && AvgIPC > 1 && IssueCount == AvgIPC)
592 || AvailableQueue->empty())
593 AdvanceToCycle(CurCycle + 1);
596 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
597 /// unscheduled, incrcease the succ left count of its predecessors. Remove
598 /// them from AvailableQueue if necessary.
599 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
600 SUnit *PredSU = PredEdge->getSUnit();
601 if (PredSU->isAvailable) {
602 PredSU->isAvailable = false;
603 if (!PredSU->isPending)
604 AvailableQueue->remove(PredSU);
607 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
608 ++PredSU->NumSuccsLeft;
611 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
612 /// its predecessor states to reflect the change.
613 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
614 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
615 DEBUG(SU->dump(this));
617 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
620 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
621 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
622 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
623 "Physical register dependency violated?");
625 LiveRegDefs[I->getReg()] = NULL;
626 LiveRegGens[I->getReg()] = NULL;
630 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
632 if (I->isAssignedRegDep()) {
633 // This becomes the nearest def. Note that an earlier def may still be
634 // pending if this is a two-address node.
635 LiveRegDefs[I->getReg()] = SU;
636 if (!LiveRegDefs[I->getReg()]) {
639 if (LiveRegGens[I->getReg()] == NULL ||
640 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
641 LiveRegGens[I->getReg()] = I->getSUnit();
644 if (SU->getHeight() < MinAvailableCycle)
645 MinAvailableCycle = SU->getHeight();
647 SU->setHeightDirty();
648 SU->isScheduled = false;
649 SU->isAvailable = true;
650 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
651 // Don't make available until backtracking is complete.
652 SU->isPending = true;
653 PendingQueue.push_back(SU);
656 AvailableQueue->push(SU);
658 AvailableQueue->UnscheduledNode(SU);
661 /// After backtracking, the hazard checker needs to be restored to a state
662 /// corresponding the the current cycle.
663 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
666 unsigned LookAhead = std::min((unsigned)Sequence.size(),
667 HazardRec->getMaxLookAhead());
671 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
672 unsigned HazardCycle = (*I)->getHeight();
673 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
675 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
676 HazardRec->RecedeCycle();
682 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
683 /// BTCycle in order to schedule a specific node.
684 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
685 SUnit *OldSU = Sequence.back();
688 if (SU->isSucc(OldSU))
689 // Don't try to remove SU from AvailableQueue.
690 SU->isAvailable = false;
691 // FIXME: use ready cycle instead of height
692 CurCycle = OldSU->getHeight();
693 UnscheduleNodeBottomUp(OldSU);
694 AvailableQueue->setCurCycle(CurCycle);
697 OldSU = Sequence.back();
700 assert(!SU->isSucc(OldSU) && "Something is wrong!");
702 RestoreHazardCheckerBottomUp();
709 static bool isOperandOf(const SUnit *SU, SDNode *N) {
710 for (const SDNode *SUNode = SU->getNode(); SUNode;
711 SUNode = SUNode->getGluedNode()) {
712 if (SUNode->isOperandOf(N))
718 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
719 /// successors to the newly created node.
720 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
721 SDNode *N = SU->getNode();
725 if (SU->getNode()->getGluedNode())
729 bool TryUnfold = false;
730 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
731 EVT VT = N->getValueType(i);
734 else if (VT == MVT::Other)
737 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
738 const SDValue &Op = N->getOperand(i);
739 EVT VT = Op.getNode()->getValueType(Op.getResNo());
745 SmallVector<SDNode*, 2> NewNodes;
746 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
749 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
750 assert(NewNodes.size() == 2 && "Expected a load folding node!");
753 SDNode *LoadNode = NewNodes[0];
754 unsigned NumVals = N->getNumValues();
755 unsigned OldNumVals = SU->getNode()->getNumValues();
756 for (unsigned i = 0; i != NumVals; ++i)
757 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
758 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
759 SDValue(LoadNode, 1));
761 // LoadNode may already exist. This can happen when there is another
762 // load from the same location and producing the same type of value
763 // but it has different alignment or volatileness.
764 bool isNewLoad = true;
766 if (LoadNode->getNodeId() != -1) {
767 LoadSU = &SUnits[LoadNode->getNodeId()];
770 LoadSU = CreateNewSUnit(LoadNode);
771 LoadNode->setNodeId(LoadSU->NodeNum);
773 InitNumRegDefsLeft(LoadSU);
774 ComputeLatency(LoadSU);
777 SUnit *NewSU = CreateNewSUnit(N);
778 assert(N->getNodeId() == -1 && "Node already inserted!");
779 N->setNodeId(NewSU->NodeNum);
781 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
782 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
783 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
784 NewSU->isTwoAddress = true;
788 if (TID.isCommutable())
789 NewSU->isCommutable = true;
791 InitNumRegDefsLeft(NewSU);
792 ComputeLatency(NewSU);
794 // Record all the edges to and from the old SU, by category.
795 SmallVector<SDep, 4> ChainPreds;
796 SmallVector<SDep, 4> ChainSuccs;
797 SmallVector<SDep, 4> LoadPreds;
798 SmallVector<SDep, 4> NodePreds;
799 SmallVector<SDep, 4> NodeSuccs;
800 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
803 ChainPreds.push_back(*I);
804 else if (isOperandOf(I->getSUnit(), LoadNode))
805 LoadPreds.push_back(*I);
807 NodePreds.push_back(*I);
809 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
812 ChainSuccs.push_back(*I);
814 NodeSuccs.push_back(*I);
817 // Now assign edges to the newly-created nodes.
818 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
819 const SDep &Pred = ChainPreds[i];
820 RemovePred(SU, Pred);
822 AddPred(LoadSU, Pred);
824 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
825 const SDep &Pred = LoadPreds[i];
826 RemovePred(SU, Pred);
828 AddPred(LoadSU, Pred);
830 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
831 const SDep &Pred = NodePreds[i];
832 RemovePred(SU, Pred);
833 AddPred(NewSU, Pred);
835 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
836 SDep D = NodeSuccs[i];
837 SUnit *SuccDep = D.getSUnit();
839 RemovePred(SuccDep, D);
842 // Balance register pressure.
843 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
844 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
845 --NewSU->NumRegDefsLeft;
847 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
848 SDep D = ChainSuccs[i];
849 SUnit *SuccDep = D.getSUnit();
851 RemovePred(SuccDep, D);
858 // Add a data dependency to reflect that NewSU reads the value defined
860 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
863 AvailableQueue->addNode(LoadSU);
864 AvailableQueue->addNode(NewSU);
868 if (NewSU->NumSuccsLeft == 0) {
869 NewSU->isAvailable = true;
875 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
876 NewSU = CreateClone(SU);
878 // New SUnit has the exact same predecessors.
879 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
881 if (!I->isArtificial())
884 // Only copy scheduled successors. Cut them from old node's successor
885 // list and move them over.
886 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
887 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
889 if (I->isArtificial())
891 SUnit *SuccSU = I->getSUnit();
892 if (SuccSU->isScheduled) {
897 DelDeps.push_back(std::make_pair(SuccSU, D));
900 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
901 RemovePred(DelDeps[i].first, DelDeps[i].second);
903 AvailableQueue->updateNode(SU);
904 AvailableQueue->addNode(NewSU);
910 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
911 /// scheduled successors of the given SUnit to the last copy.
912 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
913 const TargetRegisterClass *DestRC,
914 const TargetRegisterClass *SrcRC,
915 SmallVector<SUnit*, 2> &Copies) {
916 SUnit *CopyFromSU = CreateNewSUnit(NULL);
917 CopyFromSU->CopySrcRC = SrcRC;
918 CopyFromSU->CopyDstRC = DestRC;
920 SUnit *CopyToSU = CreateNewSUnit(NULL);
921 CopyToSU->CopySrcRC = DestRC;
922 CopyToSU->CopyDstRC = SrcRC;
924 // Only copy scheduled successors. Cut them from old node's successor
925 // list and move them over.
926 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
927 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
929 if (I->isArtificial())
931 SUnit *SuccSU = I->getSUnit();
932 if (SuccSU->isScheduled) {
934 D.setSUnit(CopyToSU);
936 DelDeps.push_back(std::make_pair(SuccSU, *I));
939 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
940 RemovePred(DelDeps[i].first, DelDeps[i].second);
942 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
943 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
945 AvailableQueue->updateNode(SU);
946 AvailableQueue->addNode(CopyFromSU);
947 AvailableQueue->addNode(CopyToSU);
948 Copies.push_back(CopyFromSU);
949 Copies.push_back(CopyToSU);
954 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
955 /// definition of the specified node.
956 /// FIXME: Move to SelectionDAG?
957 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
958 const TargetInstrInfo *TII) {
959 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
960 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
961 unsigned NumRes = TID.getNumDefs();
962 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
967 return N->getValueType(NumRes);
970 /// CheckForLiveRegDef - Return true and update live register vector if the
971 /// specified register def of the specified SUnit clobbers any "live" registers.
972 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
973 std::vector<SUnit*> &LiveRegDefs,
974 SmallSet<unsigned, 4> &RegAdded,
975 SmallVector<unsigned, 4> &LRegs,
976 const TargetRegisterInfo *TRI) {
977 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
979 // Check if Ref is live.
980 if (!LiveRegDefs[Reg]) continue;
982 // Allow multiple uses of the same def.
983 if (LiveRegDefs[Reg] == SU) continue;
985 // Add Reg to the set of interfering live regs.
986 if (RegAdded.insert(Reg))
987 LRegs.push_back(Reg);
991 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
992 /// scheduling of the given node to satisfy live physical register dependencies.
993 /// If the specific node is the last one that's available to schedule, do
994 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
995 bool ScheduleDAGRRList::
996 DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
997 if (NumLiveRegs == 0)
1000 SmallSet<unsigned, 4> RegAdded;
1001 // If this node would clobber any "live" register, then it's not ready.
1003 // If SU is the currently live definition of the same register that it uses,
1004 // then we are free to schedule it.
1005 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1007 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
1008 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1009 RegAdded, LRegs, TRI);
1012 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
1013 if (Node->getOpcode() == ISD::INLINEASM) {
1014 // Inline asm can clobber physical defs.
1015 unsigned NumOps = Node->getNumOperands();
1016 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1017 --NumOps; // Ignore the glue operand.
1019 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1021 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
1022 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
1024 ++i; // Skip the ID value.
1025 if (InlineAsm::isRegDefKind(Flags) ||
1026 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
1027 // Check for def of register or earlyclobber register.
1028 for (; NumVals; --NumVals, ++i) {
1029 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1030 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1031 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1039 if (!Node->isMachineOpcode())
1041 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
1042 if (!TID.ImplicitDefs)
1044 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
1045 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1048 return !LRegs.empty();
1051 /// Return a node that can be scheduled in this cycle. Requirements:
1052 /// (1) Ready: latency has been satisfied
1053 /// (2) No Hazards: resources are available
1054 /// (3) No Interferences: may unschedule to break register interferences.
1055 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1056 SmallVector<SUnit*, 4> Interferences;
1057 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1059 SUnit *CurSU = AvailableQueue->pop();
1061 SmallVector<unsigned, 4> LRegs;
1062 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1064 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1066 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1067 Interferences.push_back(CurSU);
1068 CurSU = AvailableQueue->pop();
1071 // Add the nodes that aren't ready back onto the available list.
1072 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1073 Interferences[i]->isPending = false;
1074 assert(Interferences[i]->isAvailable && "must still be available");
1075 AvailableQueue->push(Interferences[i]);
1080 // All candidates are delayed due to live physical reg dependencies.
1081 // Try backtracking, code duplication, or inserting cross class copies
1083 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1084 SUnit *TrySU = Interferences[i];
1085 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1087 // Try unscheduling up to the point where it's safe to schedule
1090 unsigned LiveCycle = UINT_MAX;
1091 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1092 unsigned Reg = LRegs[j];
1093 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1094 BtSU = LiveRegGens[Reg];
1095 LiveCycle = BtSU->getHeight();
1098 if (!WillCreateCycle(TrySU, BtSU)) {
1099 BacktrackBottomUp(TrySU, BtSU);
1101 // Force the current node to be scheduled before the node that
1102 // requires the physical reg dep.
1103 if (BtSU->isAvailable) {
1104 BtSU->isAvailable = false;
1105 if (!BtSU->isPending)
1106 AvailableQueue->remove(BtSU);
1108 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
1109 /*Reg=*/0, /*isNormalMemory=*/false,
1110 /*isMustAlias=*/false, /*isArtificial=*/true));
1112 // If one or more successors has been unscheduled, then the current
1113 // node is no longer avaialable. Schedule a successor that's now
1114 // available instead.
1115 if (!TrySU->isAvailable) {
1116 CurSU = AvailableQueue->pop();
1120 TrySU->isPending = false;
1121 Interferences.erase(Interferences.begin()+i);
1128 // Can't backtrack. If it's too expensive to copy the value, then try
1129 // duplicate the nodes that produces these "too expensive to copy"
1130 // values to break the dependency. In case even that doesn't work,
1131 // insert cross class copies.
1132 // If it's not too expensive, i.e. cost != -1, issue copies.
1133 SUnit *TrySU = Interferences[0];
1134 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1135 assert(LRegs.size() == 1 && "Can't handle this yet!");
1136 unsigned Reg = LRegs[0];
1137 SUnit *LRDef = LiveRegDefs[Reg];
1138 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1139 const TargetRegisterClass *RC =
1140 TRI->getMinimalPhysRegClass(Reg, VT);
1141 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1143 // If cross copy register class is the same as RC, then it must be possible
1144 // copy the value directly. Do not try duplicate the def.
1145 // If cross copy register class is not the same as RC, then it's possible to
1146 // copy the value but it require cross register class copies and it is
1148 // If cross copy register class is null, then it's not possible to copy
1149 // the value at all.
1152 NewDef = CopyAndMoveSuccessors(LRDef);
1153 if (!DestRC && !NewDef)
1154 report_fatal_error("Can't handle live physical register dependency!");
1157 // Issue copies, these can be expensive cross register class copies.
1158 SmallVector<SUnit*, 2> Copies;
1159 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1160 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1161 << " to SU #" << Copies.front()->NodeNum << "\n");
1162 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1163 /*Reg=*/0, /*isNormalMemory=*/false,
1164 /*isMustAlias=*/false,
1165 /*isArtificial=*/true));
1166 NewDef = Copies.back();
1169 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1170 << " to SU #" << TrySU->NodeNum << "\n");
1171 LiveRegDefs[Reg] = NewDef;
1172 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1173 /*Reg=*/0, /*isNormalMemory=*/false,
1174 /*isMustAlias=*/false,
1175 /*isArtificial=*/true));
1176 TrySU->isAvailable = false;
1180 assert(CurSU && "Unable to resolve live physical register dependencies!");
1182 // Add the nodes that aren't ready back onto the available list.
1183 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1184 Interferences[i]->isPending = false;
1185 // May no longer be available due to backtracking.
1186 if (Interferences[i]->isAvailable) {
1187 AvailableQueue->push(Interferences[i]);
1193 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1195 void ScheduleDAGRRList::ListScheduleBottomUp() {
1196 // Release any predecessors of the special Exit node.
1197 ReleasePredecessors(&ExitSU);
1199 // Add root to Available queue.
1200 if (!SUnits.empty()) {
1201 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1202 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1203 RootSU->isAvailable = true;
1204 AvailableQueue->push(RootSU);
1207 // While Available queue is not empty, grab the node with the highest
1208 // priority. If it is not ready put it back. Schedule the node.
1209 Sequence.reserve(SUnits.size());
1210 while (!AvailableQueue->empty()) {
1211 DEBUG(dbgs() << "\n*** Examining Available\n";
1212 AvailableQueue->dump(this));
1214 // Pick the best node to schedule taking all constraints into
1216 SUnit *SU = PickNodeToScheduleBottomUp();
1218 AdvancePastStalls(SU);
1220 ScheduleNodeBottomUp(SU);
1222 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1223 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1224 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1225 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1229 // Reverse the order if it is bottom up.
1230 std::reverse(Sequence.begin(), Sequence.end());
1233 VerifySchedule(isBottomUp);
1237 //===----------------------------------------------------------------------===//
1238 // Top-Down Scheduling
1239 //===----------------------------------------------------------------------===//
1241 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1242 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1243 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
1244 SUnit *SuccSU = SuccEdge->getSUnit();
1247 if (SuccSU->NumPredsLeft == 0) {
1248 dbgs() << "*** Scheduling failed! ***\n";
1250 dbgs() << " has been released too many times!\n";
1251 llvm_unreachable(0);
1254 --SuccSU->NumPredsLeft;
1256 // If all the node's predecessors are scheduled, this node is ready
1257 // to be scheduled. Ignore the special ExitSU node.
1258 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
1259 SuccSU->isAvailable = true;
1260 AvailableQueue->push(SuccSU);
1264 void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1265 // Top down: release successors
1266 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1268 assert(!I->isAssignedRegDep() &&
1269 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1271 ReleaseSucc(SU, &*I);
1275 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1276 /// count of its successors. If a successor pending count is zero, add it to
1277 /// the Available queue.
1278 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
1279 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
1280 DEBUG(SU->dump(this));
1282 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1283 SU->setDepthToAtLeast(CurCycle);
1284 Sequence.push_back(SU);
1286 ReleaseSuccessors(SU);
1287 SU->isScheduled = true;
1288 AvailableQueue->ScheduledNode(SU);
1291 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1293 void ScheduleDAGRRList::ListScheduleTopDown() {
1294 AvailableQueue->setCurCycle(CurCycle);
1296 // Release any successors of the special Entry node.
1297 ReleaseSuccessors(&EntrySU);
1299 // All leaves to Available queue.
1300 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1301 // It is available if it has no predecessors.
1302 if (SUnits[i].Preds.empty()) {
1303 AvailableQueue->push(&SUnits[i]);
1304 SUnits[i].isAvailable = true;
1308 // While Available queue is not empty, grab the node with the highest
1309 // priority. If it is not ready put it back. Schedule the node.
1310 Sequence.reserve(SUnits.size());
1311 while (!AvailableQueue->empty()) {
1312 SUnit *CurSU = AvailableQueue->pop();
1315 ScheduleNodeTopDown(CurSU);
1317 AvailableQueue->setCurCycle(CurCycle);
1321 VerifySchedule(isBottomUp);
1326 //===----------------------------------------------------------------------===//
1327 // RegReductionPriorityQueue Definition
1328 //===----------------------------------------------------------------------===//
1330 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1331 // to reduce register pressure.
1334 class RegReductionPQBase;
1336 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1337 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1340 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1341 // reduction scheduler.
1342 struct bu_ls_rr_sort : public queue_sort {
1345 HasReadyFilter = false
1348 RegReductionPQBase *SPQ;
1349 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1350 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1352 bool operator()(SUnit* left, SUnit* right) const;
1355 // td_ls_rr_sort - Priority function for top down register pressure reduction
1357 struct td_ls_rr_sort : public queue_sort {
1360 HasReadyFilter = false
1363 RegReductionPQBase *SPQ;
1364 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1365 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1367 bool operator()(const SUnit* left, const SUnit* right) const;
1370 // src_ls_rr_sort - Priority function for source order scheduler.
1371 struct src_ls_rr_sort : public queue_sort {
1374 HasReadyFilter = false
1377 RegReductionPQBase *SPQ;
1378 src_ls_rr_sort(RegReductionPQBase *spq)
1380 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1383 bool operator()(SUnit* left, SUnit* right) const;
1386 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1387 struct hybrid_ls_rr_sort : public queue_sort {
1390 HasReadyFilter = false
1393 RegReductionPQBase *SPQ;
1394 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1396 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1399 bool isReady(SUnit *SU, unsigned CurCycle) const;
1401 bool operator()(SUnit* left, SUnit* right) const;
1404 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1406 struct ilp_ls_rr_sort : public queue_sort {
1409 HasReadyFilter = false
1412 RegReductionPQBase *SPQ;
1413 ilp_ls_rr_sort(RegReductionPQBase *spq)
1415 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1418 bool isReady(SUnit *SU, unsigned CurCycle) const;
1420 bool operator()(SUnit* left, SUnit* right) const;
1423 class RegReductionPQBase : public SchedulingPriorityQueue {
1425 std::vector<SUnit*> Queue;
1426 unsigned CurQueueId;
1427 bool TracksRegPressure;
1429 // SUnits - The SUnits for the current graph.
1430 std::vector<SUnit> *SUnits;
1432 MachineFunction &MF;
1433 const TargetInstrInfo *TII;
1434 const TargetRegisterInfo *TRI;
1435 const TargetLowering *TLI;
1436 ScheduleDAGRRList *scheduleDAG;
1438 // SethiUllmanNumbers - The SethiUllman number for each node.
1439 std::vector<unsigned> SethiUllmanNumbers;
1441 /// RegPressure - Tracking current reg pressure per register class.
1443 std::vector<unsigned> RegPressure;
1445 /// RegLimit - Tracking the number of allocatable registers per register
1447 std::vector<unsigned> RegLimit;
1450 RegReductionPQBase(MachineFunction &mf,
1451 bool hasReadyFilter,
1453 const TargetInstrInfo *tii,
1454 const TargetRegisterInfo *tri,
1455 const TargetLowering *tli)
1456 : SchedulingPriorityQueue(hasReadyFilter),
1457 CurQueueId(0), TracksRegPressure(tracksrp),
1458 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1459 if (TracksRegPressure) {
1460 unsigned NumRC = TRI->getNumRegClasses();
1461 RegLimit.resize(NumRC);
1462 RegPressure.resize(NumRC);
1463 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1464 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1465 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1466 E = TRI->regclass_end(); I != E; ++I)
1467 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
1471 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1472 scheduleDAG = scheduleDag;
1475 ScheduleHazardRecognizer* getHazardRec() {
1476 return scheduleDAG->getHazardRec();
1479 void initNodes(std::vector<SUnit> &sunits);
1481 void addNode(const SUnit *SU);
1483 void updateNode(const SUnit *SU);
1485 void releaseState() {
1487 SethiUllmanNumbers.clear();
1488 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1491 unsigned getNodePriority(const SUnit *SU) const;
1493 unsigned getNodeOrdering(const SUnit *SU) const {
1494 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1497 bool empty() const { return Queue.empty(); }
1499 void push(SUnit *U) {
1500 assert(!U->NodeQueueId && "Node in the queue already");
1501 U->NodeQueueId = ++CurQueueId;
1505 void remove(SUnit *SU) {
1506 assert(!Queue.empty() && "Queue is empty!");
1507 assert(SU->NodeQueueId != 0 && "Not in queue!");
1508 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1510 if (I != prior(Queue.end()))
1511 std::swap(*I, Queue.back());
1513 SU->NodeQueueId = 0;
1516 bool tracksRegPressure() const { return TracksRegPressure; }
1518 void dumpRegPressure() const;
1520 bool HighRegPressure(const SUnit *SU) const;
1522 bool MayReduceRegPressure(SUnit *SU) const;
1524 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
1526 void ScheduledNode(SUnit *SU);
1528 void UnscheduledNode(SUnit *SU);
1531 bool canClobber(const SUnit *SU, const SUnit *Op);
1532 void AddPseudoTwoAddrDeps();
1533 void PrescheduleNodesWithMultipleUses();
1534 void CalculateSethiUllmanNumbers();
1538 class RegReductionPriorityQueue : public RegReductionPQBase {
1539 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1540 std::vector<SUnit *>::iterator Best = Q.begin();
1541 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1542 E = Q.end(); I != E; ++I)
1543 if (Picker(*Best, *I))
1546 if (Best != prior(Q.end()))
1547 std::swap(*Best, Q.back());
1555 RegReductionPriorityQueue(MachineFunction &mf,
1557 const TargetInstrInfo *tii,
1558 const TargetRegisterInfo *tri,
1559 const TargetLowering *tli)
1560 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1563 bool isBottomUp() const { return SF::IsBottomUp; }
1565 bool isReady(SUnit *U) const {
1566 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1570 if (Queue.empty()) return NULL;
1572 SUnit *V = popFromQueue(Queue, Picker);
1577 void dump(ScheduleDAG *DAG) const {
1578 // Emulate pop() without clobbering NodeQueueIds.
1579 std::vector<SUnit*> DumpQueue = Queue;
1580 SF DumpPicker = Picker;
1581 while (!DumpQueue.empty()) {
1582 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1584 dbgs() << "Height " << SU->getHeight() << ": ";
1586 dbgs() << "Depth " << SU->getDepth() << ": ";
1592 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1593 BURegReductionPriorityQueue;
1595 typedef RegReductionPriorityQueue<td_ls_rr_sort>
1596 TDRegReductionPriorityQueue;
1598 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1599 SrcRegReductionPriorityQueue;
1601 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1602 HybridBURRPriorityQueue;
1604 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1605 ILPBURRPriorityQueue;
1606 } // end anonymous namespace
1608 //===----------------------------------------------------------------------===//
1609 // Static Node Priority for Register Pressure Reduction
1610 //===----------------------------------------------------------------------===//
1612 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1613 /// Smaller number is the higher priority.
1615 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1616 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1617 if (SethiUllmanNumber != 0)
1618 return SethiUllmanNumber;
1621 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1623 if (I->isCtrl()) continue; // ignore chain preds
1624 SUnit *PredSU = I->getSUnit();
1625 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1626 if (PredSethiUllman > SethiUllmanNumber) {
1627 SethiUllmanNumber = PredSethiUllman;
1629 } else if (PredSethiUllman == SethiUllmanNumber)
1633 SethiUllmanNumber += Extra;
1635 if (SethiUllmanNumber == 0)
1636 SethiUllmanNumber = 1;
1638 return SethiUllmanNumber;
1641 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1642 /// scheduling units.
1643 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1644 SethiUllmanNumbers.assign(SUnits->size(), 0);
1646 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1647 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1650 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1652 // Add pseudo dependency edges for two-address nodes.
1653 AddPseudoTwoAddrDeps();
1654 // Reroute edges to nodes with multiple uses.
1655 if (!TracksRegPressure)
1656 PrescheduleNodesWithMultipleUses();
1657 // Calculate node priorities.
1658 CalculateSethiUllmanNumbers();
1661 void RegReductionPQBase::addNode(const SUnit *SU) {
1662 unsigned SUSize = SethiUllmanNumbers.size();
1663 if (SUnits->size() > SUSize)
1664 SethiUllmanNumbers.resize(SUSize*2, 0);
1665 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1668 void RegReductionPQBase::updateNode(const SUnit *SU) {
1669 SethiUllmanNumbers[SU->NodeNum] = 0;
1670 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1673 // Lower priority means schedule further down. For bottom-up scheduling, lower
1674 // priority SUs are scheduled before higher priority SUs.
1675 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1676 assert(SU->NodeNum < SethiUllmanNumbers.size());
1677 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1678 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1679 // CopyToReg should be close to its uses to facilitate coalescing and
1682 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1683 Opc == TargetOpcode::SUBREG_TO_REG ||
1684 Opc == TargetOpcode::INSERT_SUBREG)
1685 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1686 // close to their uses to facilitate coalescing.
1688 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1689 // If SU does not have a register use, i.e. it doesn't produce a value
1690 // that would be consumed (e.g. store), then it terminates a chain of
1691 // computation. Give it a large SethiUllman number so it will be
1692 // scheduled right before its predecessors that it doesn't lengthen
1693 // their live ranges.
1695 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1696 // If SU does not have a register def, schedule it close to its uses
1697 // because it does not lengthen any live ranges.
1699 return SethiUllmanNumbers[SU->NodeNum];
1702 //===----------------------------------------------------------------------===//
1703 // Register Pressure Tracking
1704 //===----------------------------------------------------------------------===//
1706 void RegReductionPQBase::dumpRegPressure() const {
1707 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1708 E = TRI->regclass_end(); I != E; ++I) {
1709 const TargetRegisterClass *RC = *I;
1710 unsigned Id = RC->getID();
1711 unsigned RP = RegPressure[Id];
1713 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1718 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1722 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1726 SUnit *PredSU = I->getSUnit();
1727 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1728 // to cover the number of registers defined (they are all live).
1729 if (PredSU->NumRegDefsLeft == 0) {
1732 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1733 RegDefPos.IsValid(); RegDefPos.Advance()) {
1734 EVT VT = RegDefPos.GetValue();
1735 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1736 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1737 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1744 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
1745 const SDNode *N = SU->getNode();
1747 if (!N->isMachineOpcode() || !SU->NumSuccs)
1750 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1751 for (unsigned i = 0; i != NumDefs; ++i) {
1752 EVT VT = N->getValueType(i);
1753 if (!N->hasAnyUseOfValue(i))
1755 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1756 if (RegPressure[RCId] >= RegLimit[RCId])
1762 // Compute the register pressure contribution by this instruction by count up
1763 // for uses that are not live and down for defs. Only count register classes
1764 // that are already under high pressure. As a side effect, compute the number of
1765 // uses of registers that are already live.
1767 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1768 // so could probably be factored.
1769 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1772 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1776 SUnit *PredSU = I->getSUnit();
1777 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1778 // to cover the number of registers defined (they are all live).
1779 if (PredSU->NumRegDefsLeft == 0) {
1780 if (PredSU->getNode()->isMachineOpcode())
1784 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1785 RegDefPos.IsValid(); RegDefPos.Advance()) {
1786 EVT VT = RegDefPos.GetValue();
1787 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1788 if (RegPressure[RCId] >= RegLimit[RCId])
1792 const SDNode *N = SU->getNode();
1794 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
1797 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1798 for (unsigned i = 0; i != NumDefs; ++i) {
1799 EVT VT = N->getValueType(i);
1800 if (!N->hasAnyUseOfValue(i))
1802 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1803 if (RegPressure[RCId] >= RegLimit[RCId])
1809 void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1810 if (!TracksRegPressure)
1816 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1820 SUnit *PredSU = I->getSUnit();
1821 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1822 // to cover the number of registers defined (they are all live).
1823 if (PredSU->NumRegDefsLeft == 0) {
1826 // FIXME: The ScheduleDAG currently loses information about which of a
1827 // node's values is consumed by each dependence. Consequently, if the node
1828 // defines multiple register classes, we don't know which to pressurize
1829 // here. Instead the following loop consumes the register defs in an
1830 // arbitrary order. At least it handles the common case of clustered loads
1831 // to the same class. For precise liveness, each SDep needs to indicate the
1832 // result number. But that tightly couples the ScheduleDAG with the
1833 // SelectionDAG making updates tricky. A simpler hack would be to attach a
1834 // value type or register class to SDep.
1836 // The most important aspect of register tracking is balancing the increase
1837 // here with the reduction further below. Note that this SU may use multiple
1838 // defs in PredSU. The can't be determined here, but we've already
1839 // compensated by reducing NumRegDefsLeft in PredSU during
1840 // ScheduleDAGSDNodes::AddSchedEdges.
1841 --PredSU->NumRegDefsLeft;
1842 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1843 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1844 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1847 EVT VT = RegDefPos.GetValue();
1848 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1849 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1854 // We should have this assert, but there may be dead SDNodes that never
1855 // materialize as SUnits, so they don't appear to generate liveness.
1856 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
1857 int SkipRegDefs = (int)SU->NumRegDefsLeft;
1858 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
1859 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1860 if (SkipRegDefs > 0)
1862 EVT VT = RegDefPos.GetValue();
1863 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1864 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT)) {
1865 // Register pressure tracking is imprecise. This can happen. But we try
1866 // hard not to let it happen because it likely results in poor scheduling.
1867 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
1868 RegPressure[RCId] = 0;
1871 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1877 void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1878 if (!TracksRegPressure)
1881 const SDNode *N = SU->getNode();
1884 if (!N->isMachineOpcode()) {
1885 if (N->getOpcode() != ISD::CopyToReg)
1888 unsigned Opc = N->getMachineOpcode();
1889 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1890 Opc == TargetOpcode::INSERT_SUBREG ||
1891 Opc == TargetOpcode::SUBREG_TO_REG ||
1892 Opc == TargetOpcode::REG_SEQUENCE ||
1893 Opc == TargetOpcode::IMPLICIT_DEF)
1897 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1901 SUnit *PredSU = I->getSUnit();
1902 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1903 // counts data deps.
1904 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
1906 const SDNode *PN = PredSU->getNode();
1907 if (!PN->isMachineOpcode()) {
1908 if (PN->getOpcode() == ISD::CopyFromReg) {
1909 EVT VT = PN->getValueType(0);
1910 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1911 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1915 unsigned POpc = PN->getMachineOpcode();
1916 if (POpc == TargetOpcode::IMPLICIT_DEF)
1918 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1919 EVT VT = PN->getOperand(0).getValueType();
1920 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1921 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1923 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1924 POpc == TargetOpcode::SUBREG_TO_REG) {
1925 EVT VT = PN->getValueType(0);
1926 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1927 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1930 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1931 for (unsigned i = 0; i != NumDefs; ++i) {
1932 EVT VT = PN->getValueType(i);
1933 if (!PN->hasAnyUseOfValue(i))
1935 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1936 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1937 // Register pressure tracking is imprecise. This can happen.
1938 RegPressure[RCId] = 0;
1940 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1944 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1945 // may transfer data dependencies to CopyToReg.
1946 if (SU->NumSuccs && N->isMachineOpcode()) {
1947 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1948 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1949 EVT VT = N->getValueType(i);
1950 if (VT == MVT::Glue || VT == MVT::Other)
1952 if (!N->hasAnyUseOfValue(i))
1954 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1955 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1962 //===----------------------------------------------------------------------===//
1963 // Dynamic Node Priority for Register Pressure Reduction
1964 //===----------------------------------------------------------------------===//
1966 /// closestSucc - Returns the scheduled cycle of the successor which is
1967 /// closest to the current cycle.
1968 static unsigned closestSucc(const SUnit *SU) {
1969 unsigned MaxHeight = 0;
1970 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1972 if (I->isCtrl()) continue; // ignore chain succs
1973 unsigned Height = I->getSUnit()->getHeight();
1974 // If there are bunch of CopyToRegs stacked up, they should be considered
1975 // to be at the same position.
1976 if (I->getSUnit()->getNode() &&
1977 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
1978 Height = closestSucc(I->getSUnit())+1;
1979 if (Height > MaxHeight)
1985 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1986 /// for scratch registers, i.e. number of data dependencies.
1987 static unsigned calcMaxScratches(const SUnit *SU) {
1988 unsigned Scratches = 0;
1989 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1991 if (I->isCtrl()) continue; // ignore chain preds
1997 /// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1998 /// CopyToReg to a virtual register. This SU def is probably a liveout and
1999 /// it has no other use. It should be scheduled closer to the terminator.
2000 static bool hasOnlyLiveOutUses(const SUnit *SU) {
2001 bool RetVal = false;
2002 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2004 if (I->isCtrl()) continue;
2005 const SUnit *SuccSU = I->getSUnit();
2006 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2008 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2009 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2019 /// UnitsSharePred - Return true if the two scheduling units share a common
2020 /// data predecessor.
2021 static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
2022 SmallSet<const SUnit*, 4> Preds;
2023 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
2025 if (I->isCtrl()) continue; // ignore chain preds
2026 Preds.insert(I->getSUnit());
2028 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
2030 if (I->isCtrl()) continue; // ignore chain preds
2031 if (Preds.count(I->getSUnit()))
2037 // Check for either a dependence (latency) or resource (hazard) stall.
2039 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2040 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2041 if ((int)SPQ->getCurCycle() < Height) return true;
2042 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2043 != ScheduleHazardRecognizer::NoHazard)
2048 // Return -1 if left has higher priority, 1 if right has higher priority.
2049 // Return 0 if latency-based priority is equivalent.
2050 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2051 RegReductionPQBase *SPQ) {
2052 // If the two nodes share an operand and one of them has a single
2053 // use that is a live out copy, favor the one that is live out. Otherwise
2054 // it will be difficult to eliminate the copy if the instruction is a
2055 // loop induction variable update. e.g.
2062 bool SharePred = UnitsSharePred(left, right);
2063 // FIXME: Only adjust if BB is a loop back edge.
2064 // FIXME: What's the cost of a copy?
2065 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
2066 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
2067 int LHeight = (int)left->getHeight() - LBonus;
2068 int RHeight = (int)right->getHeight() - RBonus;
2070 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
2071 BUHasStall(left, LHeight, SPQ);
2072 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
2073 BUHasStall(right, RHeight, SPQ);
2075 // If scheduling one of the node will cause a pipeline stall, delay it.
2076 // If scheduling either one of the node will cause a pipeline stall, sort
2077 // them according to their height.
2081 if (LHeight != RHeight)
2082 return LHeight > RHeight ? 1 : -1;
2086 // If either node is scheduling for latency, sort them by height/depth
2088 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2089 right->SchedulingPref == Sched::Latency)) {
2090 if (DisableSchedCycles) {
2091 if (LHeight != RHeight)
2092 return LHeight > RHeight ? 1 : -1;
2095 // If neither instruction stalls (!LStall && !RStall) then
2096 // its height is already covered so only its depth matters. We also reach
2097 // this if both stall but have the same height.
2098 unsigned LDepth = left->getDepth();
2099 unsigned RDepth = right->getDepth();
2100 if (LDepth != RDepth) {
2101 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2102 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2103 << ") depth " << RDepth << "\n");
2104 return LDepth < RDepth ? 1 : -1;
2107 if (left->Latency != right->Latency)
2108 return left->Latency > right->Latency ? 1 : -1;
2113 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2114 unsigned LPriority = SPQ->getNodePriority(left);
2115 unsigned RPriority = SPQ->getNodePriority(right);
2116 if (LPriority != RPriority) {
2117 DEBUG(++FactorCount[FactStatic]);
2118 return LPriority > RPriority;
2120 DEBUG(++FactorCount[FactOther]);
2122 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2127 // and the following instructions are both ready.
2131 // Then schedule t2 = op first.
2138 // This creates more short live intervals.
2139 unsigned LDist = closestSucc(left);
2140 unsigned RDist = closestSucc(right);
2142 return LDist < RDist;
2144 // How many registers becomes live when the node is scheduled.
2145 unsigned LScratch = calcMaxScratches(left);
2146 unsigned RScratch = calcMaxScratches(right);
2147 if (LScratch != RScratch)
2148 return LScratch > RScratch;
2150 if (!DisableSchedCycles) {
2151 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2156 if (left->getHeight() != right->getHeight())
2157 return left->getHeight() > right->getHeight();
2159 if (left->getDepth() != right->getDepth())
2160 return left->getDepth() < right->getDepth();
2163 assert(left->NodeQueueId && right->NodeQueueId &&
2164 "NodeQueueId cannot be zero");
2165 return (left->NodeQueueId > right->NodeQueueId);
2169 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2170 return BURRSort(left, right, SPQ);
2173 // Source order, otherwise bottom up.
2174 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2175 unsigned LOrder = SPQ->getNodeOrdering(left);
2176 unsigned ROrder = SPQ->getNodeOrdering(right);
2178 // Prefer an ordering where the lower the non-zero order number, the higher
2180 if ((LOrder || ROrder) && LOrder != ROrder)
2181 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2183 return BURRSort(left, right, SPQ);
2186 // If the time between now and when the instruction will be ready can cover
2187 // the spill code, then avoid adding it to the ready queue. This gives long
2188 // stalls highest priority and allows hoisting across calls. It should also
2189 // speed up processing the available queue.
2190 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2191 static const unsigned ReadyDelay = 3;
2193 if (SPQ->MayReduceRegPressure(SU)) return true;
2195 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2197 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2198 != ScheduleHazardRecognizer::NoHazard)
2204 // Return true if right should be scheduled with higher priority than left.
2205 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2206 if (left->isCall || right->isCall)
2207 // No way to compute latency of calls.
2208 return BURRSort(left, right, SPQ);
2210 bool LHigh = SPQ->HighRegPressure(left);
2211 bool RHigh = SPQ->HighRegPressure(right);
2212 // Avoid causing spills. If register pressure is high, schedule for
2213 // register pressure reduction.
2214 if (LHigh && !RHigh) {
2215 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2216 << right->NodeNum << ")\n");
2219 else if (!LHigh && RHigh) {
2220 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2221 << left->NodeNum << ")\n");
2224 else if (!LHigh && !RHigh) {
2225 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2229 return BURRSort(left, right, SPQ);
2232 // Schedule as many instructions in each cycle as possible. So don't make an
2233 // instruction available unless it is ready in the current cycle.
2234 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2235 if (SU->getHeight() > CurCycle) return false;
2237 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2238 != ScheduleHazardRecognizer::NoHazard)
2244 static bool canEnableCoalescing(SUnit *SU) {
2245 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2246 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2247 // CopyToReg should be close to its uses to facilitate coalescing and
2251 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2252 Opc == TargetOpcode::SUBREG_TO_REG ||
2253 Opc == TargetOpcode::INSERT_SUBREG)
2254 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2255 // close to their uses to facilitate coalescing.
2258 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2259 // If SU does not have a register def, schedule it close to its uses
2260 // because it does not lengthen any live ranges.
2266 // list-ilp is currently an experimental scheduler that allows various
2267 // heuristics to be enabled prior to the normal register reduction logic.
2268 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2269 if (left->isCall || right->isCall)
2270 // No way to compute latency of calls.
2271 return BURRSort(left, right, SPQ);
2273 unsigned LLiveUses = 0, RLiveUses = 0;
2274 int LPDiff = 0, RPDiff = 0;
2275 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2276 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2277 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2279 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2280 DEBUG(++FactorCount[FactPressureDiff]);
2281 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2282 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
2283 return LPDiff > RPDiff;
2286 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
2287 bool LReduce = canEnableCoalescing(left);
2288 bool RReduce = canEnableCoalescing(right);
2289 DEBUG(if (LReduce != RReduce) ++FactorCount[FactPressureDiff]);
2290 if (LReduce && !RReduce) return false;
2291 if (RReduce && !LReduce) return true;
2294 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2295 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2296 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
2297 DEBUG(++FactorCount[FactRegUses]);
2298 return LLiveUses < RLiveUses;
2301 if (!DisableSchedStalls) {
2302 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2303 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2304 if (LStall != RStall) {
2305 DEBUG(++FactorCount[FactHeight]);
2306 return left->getHeight() > right->getHeight();
2310 if (!DisableSchedCriticalPath) {
2311 int spread = (int)left->getDepth() - (int)right->getDepth();
2312 if (std::abs(spread) > MaxReorderWindow) {
2313 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2314 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2315 << right->getDepth() << "\n");
2316 DEBUG(++FactorCount[FactDepth]);
2317 return left->getDepth() < right->getDepth();
2321 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
2322 int spread = (int)left->getHeight() - (int)right->getHeight();
2323 if (std::abs(spread) > MaxReorderWindow) {
2324 DEBUG(++FactorCount[FactHeight]);
2325 return left->getHeight() > right->getHeight();
2329 return BURRSort(left, right, SPQ);
2332 //===----------------------------------------------------------------------===//
2333 // Preschedule for Register Pressure
2334 //===----------------------------------------------------------------------===//
2336 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2337 if (SU->isTwoAddress) {
2338 unsigned Opc = SU->getNode()->getMachineOpcode();
2339 const TargetInstrDesc &TID = TII->get(Opc);
2340 unsigned NumRes = TID.getNumDefs();
2341 unsigned NumOps = TID.getNumOperands() - NumRes;
2342 for (unsigned i = 0; i != NumOps; ++i) {
2343 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
2344 SDNode *DU = SU->getNode()->getOperand(i).getNode();
2345 if (DU->getNodeId() != -1 &&
2346 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2354 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2355 /// physical register defs.
2356 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2357 const TargetInstrInfo *TII,
2358 const TargetRegisterInfo *TRI) {
2359 SDNode *N = SuccSU->getNode();
2360 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2361 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2362 assert(ImpDefs && "Caller should check hasPhysRegDefs");
2363 for (const SDNode *SUNode = SU->getNode(); SUNode;
2364 SUNode = SUNode->getGluedNode()) {
2365 if (!SUNode->isMachineOpcode())
2367 const unsigned *SUImpDefs =
2368 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2371 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2372 EVT VT = N->getValueType(i);
2373 if (VT == MVT::Glue || VT == MVT::Other)
2375 if (!N->hasAnyUseOfValue(i))
2377 unsigned Reg = ImpDefs[i - NumDefs];
2378 for (;*SUImpDefs; ++SUImpDefs) {
2379 unsigned SUReg = *SUImpDefs;
2380 if (TRI->regsOverlap(Reg, SUReg))
2388 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2389 /// are not handled well by the general register pressure reduction
2390 /// heuristics. When presented with code like this:
2399 /// the heuristics tend to push the store up, but since the
2400 /// operand of the store has another use (U), this would increase
2401 /// the length of that other use (the U->N edge).
2403 /// This function transforms code like the above to route U's
2404 /// dependence through the store when possible, like this:
2415 /// This results in the store being scheduled immediately
2416 /// after N, which shortens the U->N live range, reducing
2417 /// register pressure.
2419 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2420 // Visit all the nodes in topological order, working top-down.
2421 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2422 SUnit *SU = &(*SUnits)[i];
2423 // For now, only look at nodes with no data successors, such as stores.
2424 // These are especially important, due to the heuristics in
2425 // getNodePriority for nodes with no data successors.
2426 if (SU->NumSuccs != 0)
2428 // For now, only look at nodes with exactly one data predecessor.
2429 if (SU->NumPreds != 1)
2431 // Avoid prescheduling copies to virtual registers, which don't behave
2432 // like other nodes from the perspective of scheduling heuristics.
2433 if (SDNode *N = SU->getNode())
2434 if (N->getOpcode() == ISD::CopyToReg &&
2435 TargetRegisterInfo::isVirtualRegister
2436 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2439 // Locate the single data predecessor.
2441 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2442 EE = SU->Preds.end(); II != EE; ++II)
2443 if (!II->isCtrl()) {
2444 PredSU = II->getSUnit();
2449 // Don't rewrite edges that carry physregs, because that requires additional
2450 // support infrastructure.
2451 if (PredSU->hasPhysRegDefs)
2453 // Short-circuit the case where SU is PredSU's only data successor.
2454 if (PredSU->NumSuccs == 1)
2456 // Avoid prescheduling to copies from virtual registers, which don't behave
2457 // like other nodes from the perspective of scheduling heuristics.
2458 if (SDNode *N = SU->getNode())
2459 if (N->getOpcode() == ISD::CopyFromReg &&
2460 TargetRegisterInfo::isVirtualRegister
2461 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2464 // Perform checks on the successors of PredSU.
2465 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2466 EE = PredSU->Succs.end(); II != EE; ++II) {
2467 SUnit *PredSuccSU = II->getSUnit();
2468 if (PredSuccSU == SU) continue;
2469 // If PredSU has another successor with no data successors, for
2470 // now don't attempt to choose either over the other.
2471 if (PredSuccSU->NumSuccs == 0)
2472 goto outer_loop_continue;
2473 // Don't break physical register dependencies.
2474 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2475 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2476 goto outer_loop_continue;
2477 // Don't introduce graph cycles.
2478 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2479 goto outer_loop_continue;
2482 // Ok, the transformation is safe and the heuristics suggest it is
2483 // profitable. Update the graph.
2484 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2485 << " next to PredSU #" << PredSU->NodeNum
2486 << " to guide scheduling in the presence of multiple uses\n");
2487 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2488 SDep Edge = PredSU->Succs[i];
2489 assert(!Edge.isAssignedRegDep());
2490 SUnit *SuccSU = Edge.getSUnit();
2492 Edge.setSUnit(PredSU);
2493 scheduleDAG->RemovePred(SuccSU, Edge);
2494 scheduleDAG->AddPred(SU, Edge);
2496 scheduleDAG->AddPred(SuccSU, Edge);
2500 outer_loop_continue:;
2504 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2505 /// it as a def&use operand. Add a pseudo control edge from it to the other
2506 /// node (if it won't create a cycle) so the two-address one will be scheduled
2507 /// first (lower in the schedule). If both nodes are two-address, favor the
2508 /// one that has a CopyToReg use (more likely to be a loop induction update).
2509 /// If both are two-address, but one is commutable while the other is not
2510 /// commutable, favor the one that's not commutable.
2511 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2512 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2513 SUnit *SU = &(*SUnits)[i];
2514 if (!SU->isTwoAddress)
2517 SDNode *Node = SU->getNode();
2518 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
2521 bool isLiveOut = hasOnlyLiveOutUses(SU);
2522 unsigned Opc = Node->getMachineOpcode();
2523 const TargetInstrDesc &TID = TII->get(Opc);
2524 unsigned NumRes = TID.getNumDefs();
2525 unsigned NumOps = TID.getNumOperands() - NumRes;
2526 for (unsigned j = 0; j != NumOps; ++j) {
2527 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2529 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2530 if (DU->getNodeId() == -1)
2532 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2533 if (!DUSU) continue;
2534 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2535 E = DUSU->Succs.end(); I != E; ++I) {
2536 if (I->isCtrl()) continue;
2537 SUnit *SuccSU = I->getSUnit();
2540 // Be conservative. Ignore if nodes aren't at roughly the same
2541 // depth and height.
2542 if (SuccSU->getHeight() < SU->getHeight() &&
2543 (SU->getHeight() - SuccSU->getHeight()) > 1)
2545 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2546 // constrains whatever is using the copy, instead of the copy
2547 // itself. In the case that the copy is coalesced, this
2548 // preserves the intent of the pseudo two-address heurietics.
2549 while (SuccSU->Succs.size() == 1 &&
2550 SuccSU->getNode()->isMachineOpcode() &&
2551 SuccSU->getNode()->getMachineOpcode() ==
2552 TargetOpcode::COPY_TO_REGCLASS)
2553 SuccSU = SuccSU->Succs.front().getSUnit();
2554 // Don't constrain non-instruction nodes.
2555 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2557 // Don't constrain nodes with physical register defs if the
2558 // predecessor can clobber them.
2559 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
2560 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
2563 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2564 // these may be coalesced away. We want them close to their uses.
2565 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2566 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2567 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2568 SuccOpc == TargetOpcode::SUBREG_TO_REG)
2570 if ((!canClobber(SuccSU, DUSU) ||
2571 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2572 (!SU->isCommutable && SuccSU->isCommutable)) &&
2573 !scheduleDAG->IsReachable(SuccSU, SU)) {
2574 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
2575 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2576 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
2577 /*Reg=*/0, /*isNormalMemory=*/false,
2578 /*isMustAlias=*/false,
2579 /*isArtificial=*/true));
2586 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
2587 /// predecessors of the successors of the SUnit SU. Stop when the provided
2588 /// limit is exceeded.
2589 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
2592 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2594 const SUnit *SuccSU = I->getSUnit();
2595 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2596 EE = SuccSU->Preds.end(); II != EE; ++II) {
2597 SUnit *PredSU = II->getSUnit();
2598 if (!PredSU->isScheduled)
2608 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
2609 unsigned LPriority = SPQ->getNodePriority(left);
2610 unsigned RPriority = SPQ->getNodePriority(right);
2611 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2612 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
2613 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2614 bool RIsFloater = RIsTarget && right->NumPreds == 0;
2615 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2616 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
2618 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2620 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2627 if (left->NumSuccs == 1)
2629 if (right->NumSuccs == 1)
2632 if (LPriority+LBonus != RPriority+RBonus)
2633 return LPriority+LBonus < RPriority+RBonus;
2635 if (left->getDepth() != right->getDepth())
2636 return left->getDepth() < right->getDepth();
2638 if (left->NumSuccsLeft != right->NumSuccsLeft)
2639 return left->NumSuccsLeft > right->NumSuccsLeft;
2641 assert(left->NodeQueueId && right->NodeQueueId &&
2642 "NodeQueueId cannot be zero");
2643 return (left->NodeQueueId > right->NodeQueueId);
2646 //===----------------------------------------------------------------------===//
2647 // Public Constructor Functions
2648 //===----------------------------------------------------------------------===//
2650 llvm::ScheduleDAGSDNodes *
2651 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2652 CodeGenOpt::Level OptLevel) {
2653 const TargetMachine &TM = IS->TM;
2654 const TargetInstrInfo *TII = TM.getInstrInfo();
2655 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2657 BURegReductionPriorityQueue *PQ =
2658 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2659 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2660 PQ->setScheduleDAG(SD);
2664 llvm::ScheduleDAGSDNodes *
2665 llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2666 CodeGenOpt::Level OptLevel) {
2667 const TargetMachine &TM = IS->TM;
2668 const TargetInstrInfo *TII = TM.getInstrInfo();
2669 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2671 TDRegReductionPriorityQueue *PQ =
2672 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2673 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2674 PQ->setScheduleDAG(SD);
2678 llvm::ScheduleDAGSDNodes *
2679 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2680 CodeGenOpt::Level OptLevel) {
2681 const TargetMachine &TM = IS->TM;
2682 const TargetInstrInfo *TII = TM.getInstrInfo();
2683 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2685 SrcRegReductionPriorityQueue *PQ =
2686 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2687 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2688 PQ->setScheduleDAG(SD);
2692 llvm::ScheduleDAGSDNodes *
2693 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2694 CodeGenOpt::Level OptLevel) {
2695 const TargetMachine &TM = IS->TM;
2696 const TargetInstrInfo *TII = TM.getInstrInfo();
2697 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2698 const TargetLowering *TLI = &IS->getTargetLowering();
2700 HybridBURRPriorityQueue *PQ =
2701 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2703 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2704 PQ->setScheduleDAG(SD);
2708 llvm::ScheduleDAGSDNodes *
2709 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2710 CodeGenOpt::Level OptLevel) {
2711 const TargetMachine &TM = IS->TM;
2712 const TargetInstrInfo *TII = TM.getInstrInfo();
2713 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2714 const TargetLowering *TLI = &IS->getTargetLowering();
2716 ILPBURRPriorityQueue *PQ =
2717 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2718 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2719 PQ->setScheduleDAG(SD);