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 sourceListDAGScheduler("source",
49 "Similar to list-burr but schedules in source "
50 "order when possible",
51 createSourceListDAGScheduler);
53 static RegisterScheduler
54 hybridListDAGScheduler("list-hybrid",
55 "Bottom-up register pressure aware list scheduling "
56 "which tries to balance latency and register pressure",
57 createHybridListDAGScheduler);
59 static RegisterScheduler
60 ILPListDAGScheduler("list-ilp",
61 "Bottom-up register pressure aware list scheduling "
62 "which tries to balance ILP and register pressure",
63 createILPListDAGScheduler);
65 static cl::opt<bool> DisableSchedCycles(
66 "disable-sched-cycles", cl::Hidden, cl::init(false),
67 cl::desc("Disable cycle-level precision during preRA scheduling"));
69 // Temporary sched=list-ilp flags until the heuristics are robust.
70 // Some options are also available under sched=list-hybrid.
71 static cl::opt<bool> DisableSchedRegPressure(
72 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
73 cl::desc("Disable regpressure priority in sched=list-ilp"));
74 static cl::opt<bool> DisableSchedLiveUses(
75 "disable-sched-live-uses", cl::Hidden, cl::init(true),
76 cl::desc("Disable live use priority in sched=list-ilp"));
77 static cl::opt<bool> DisableSchedVRegCycle(
78 "disable-sched-vrcycle", cl::Hidden, cl::init(false),
79 cl::desc("Disable virtual register cycle interference checks"));
80 static cl::opt<bool> DisableSchedPhysRegJoin(
81 "disable-sched-physreg-join", cl::Hidden, cl::init(false),
82 cl::desc("Disable physreg def-use affinity"));
83 static cl::opt<bool> DisableSchedStalls(
84 "disable-sched-stalls", cl::Hidden, cl::init(true),
85 cl::desc("Disable no-stall priority in sched=list-ilp"));
86 static cl::opt<bool> DisableSchedCriticalPath(
87 "disable-sched-critical-path", cl::Hidden, cl::init(false),
88 cl::desc("Disable critical path priority in sched=list-ilp"));
89 static cl::opt<bool> DisableSchedHeight(
90 "disable-sched-height", cl::Hidden, cl::init(false),
91 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
92 static cl::opt<bool> Disable2AddrHack(
93 "disable-2addr-hack", cl::Hidden, cl::init(true),
94 cl::desc("Disable scheduler's two-address hack"));
96 static cl::opt<int> MaxReorderWindow(
97 "max-sched-reorder", cl::Hidden, cl::init(6),
98 cl::desc("Number of instructions to allow ahead of the critical path "
99 "in sched=list-ilp"));
101 static cl::opt<unsigned> AvgIPC(
102 "sched-avg-ipc", cl::Hidden, cl::init(1),
103 cl::desc("Average inst/cycle whan no target itinerary exists."));
106 //===----------------------------------------------------------------------===//
107 /// ScheduleDAGRRList - The actual register reduction list scheduler
108 /// implementation. This supports both top-down and bottom-up scheduling.
110 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
112 /// NeedLatency - True if the scheduler will make use of latency information.
116 /// AvailableQueue - The priority queue to use for the available SUnits.
117 SchedulingPriorityQueue *AvailableQueue;
119 /// PendingQueue - This contains all of the instructions whose operands have
120 /// been issued, but their results are not ready yet (due to the latency of
121 /// the operation). Once the operands becomes available, the instruction is
122 /// added to the AvailableQueue.
123 std::vector<SUnit*> PendingQueue;
125 /// HazardRec - The hazard recognizer to use.
126 ScheduleHazardRecognizer *HazardRec;
128 /// CurCycle - The current scheduler state corresponds to this cycle.
131 /// MinAvailableCycle - Cycle of the soonest available instruction.
132 unsigned MinAvailableCycle;
134 /// IssueCount - Count instructions issued in this cycle
135 /// Currently valid only for bottom-up scheduling.
138 /// LiveRegDefs - A set of physical registers and their definition
139 /// that are "live". These nodes must be scheduled before any other nodes that
140 /// modifies the registers can be scheduled.
141 unsigned NumLiveRegs;
142 std::vector<SUnit*> LiveRegDefs;
143 std::vector<SUnit*> LiveRegGens;
145 /// Topo - A topological ordering for SUnits which permits fast IsReachable
146 /// and similar queries.
147 ScheduleDAGTopologicalSort Topo;
149 // Hack to keep track of the inverse of FindCallSeqStart without more crazy
151 DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
154 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
155 SchedulingPriorityQueue *availqueue,
156 CodeGenOpt::Level OptLevel)
157 : ScheduleDAGSDNodes(mf),
158 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
161 const TargetMachine &tm = mf.getTarget();
162 if (DisableSchedCycles || !NeedLatency)
163 HazardRec = new ScheduleHazardRecognizer();
165 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
168 ~ScheduleDAGRRList() {
170 delete AvailableQueue;
175 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
177 /// IsReachable - Checks if SU is reachable from TargetSU.
178 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
179 return Topo.IsReachable(SU, TargetSU);
182 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
184 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
185 return Topo.WillCreateCycle(SU, TargetSU);
188 /// AddPred - adds a predecessor edge to SUnit SU.
189 /// This returns true if this is a new predecessor.
190 /// Updates the topological ordering if required.
191 void AddPred(SUnit *SU, const SDep &D) {
192 Topo.AddPred(SU, D.getSUnit());
196 /// RemovePred - removes a predecessor edge from SUnit SU.
197 /// This returns true if an edge was removed.
198 /// Updates the topological ordering if required.
199 void RemovePred(SUnit *SU, const SDep &D) {
200 Topo.RemovePred(SU, D.getSUnit());
205 bool isReady(SUnit *SU) {
206 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
207 AvailableQueue->isReady(SU);
210 void ReleasePred(SUnit *SU, const SDep *PredEdge);
211 void ReleasePredecessors(SUnit *SU);
212 void ReleasePending();
213 void AdvanceToCycle(unsigned NextCycle);
214 void AdvancePastStalls(SUnit *SU);
215 void EmitNode(SUnit *SU);
216 void ScheduleNodeBottomUp(SUnit*);
217 void CapturePred(SDep *PredEdge);
218 void UnscheduleNodeBottomUp(SUnit*);
219 void RestoreHazardCheckerBottomUp();
220 void BacktrackBottomUp(SUnit*, SUnit*);
221 SUnit *CopyAndMoveSuccessors(SUnit*);
222 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
223 const TargetRegisterClass*,
224 const TargetRegisterClass*,
225 SmallVector<SUnit*, 2>&);
226 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
228 SUnit *PickNodeToScheduleBottomUp();
229 void ListScheduleBottomUp();
231 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
232 /// Updates the topological ordering if required.
233 SUnit *CreateNewSUnit(SDNode *N) {
234 unsigned NumSUnits = SUnits.size();
235 SUnit *NewNode = newSUnit(N);
236 // Update the topological ordering.
237 if (NewNode->NodeNum >= NumSUnits)
238 Topo.InitDAGTopologicalSorting();
242 /// CreateClone - Creates a new SUnit from an existing one.
243 /// Updates the topological ordering if required.
244 SUnit *CreateClone(SUnit *N) {
245 unsigned NumSUnits = SUnits.size();
246 SUnit *NewNode = Clone(N);
247 // Update the topological ordering.
248 if (NewNode->NodeNum >= NumSUnits)
249 Topo.InitDAGTopologicalSorting();
253 /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
254 /// need actual latency information but the hybrid scheduler does.
255 bool forceUnitLatencies() const {
259 } // end anonymous namespace
261 /// GetCostForDef - Looks up the register class and cost for a given definition.
262 /// Typically this just means looking up the representative register class,
263 /// but for untyped values (MVT::Untyped) it means inspecting the node's
264 /// opcode to determine what register class is being generated.
265 static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
266 const TargetLowering *TLI,
267 const TargetInstrInfo *TII,
268 const TargetRegisterInfo *TRI,
269 unsigned &RegClass, unsigned &Cost,
270 const MachineFunction &MF) {
271 EVT VT = RegDefPos.GetValue();
273 // Special handling for untyped values. These values can only come from
274 // the expansion of custom DAG-to-DAG patterns.
275 if (VT == MVT::Untyped) {
276 const SDNode *Node = RegDefPos.GetNode();
277 unsigned Opcode = Node->getMachineOpcode();
279 if (Opcode == TargetOpcode::REG_SEQUENCE) {
280 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
281 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
282 RegClass = RC->getID();
287 unsigned Idx = RegDefPos.GetIdx();
288 const MCInstrDesc Desc = TII->get(Opcode);
289 const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI, MF);
290 RegClass = RC->getID();
291 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
292 // better way to determine it.
295 RegClass = TLI->getRepRegClassFor(VT)->getID();
296 Cost = TLI->getRepRegClassCostFor(VT);
300 /// Schedule - Schedule the DAG using list scheduling.
301 void ScheduleDAGRRList::Schedule() {
303 << "********** List Scheduling BB#" << BB->getNumber()
304 << " '" << BB->getName() << "' **********\n");
308 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
310 // Allocate slots for each physical register, plus one for a special register
311 // to track the virtual resource of a calling sequence.
312 LiveRegDefs.resize(TRI->getNumRegs() + 1, NULL);
313 LiveRegGens.resize(TRI->getNumRegs() + 1, NULL);
314 CallSeqEndForStart.clear();
316 // Build the scheduling graph.
317 BuildSchedGraph(NULL);
319 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
320 SUnits[su].dumpAll(this));
321 Topo.InitDAGTopologicalSorting();
323 AvailableQueue->initNodes(SUnits);
327 // Execute the actual scheduling loop.
328 ListScheduleBottomUp();
330 AvailableQueue->releaseState();
333 dbgs() << "*** Final schedule ***\n";
339 //===----------------------------------------------------------------------===//
340 // Bottom-Up Scheduling
341 //===----------------------------------------------------------------------===//
343 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
344 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
345 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
346 SUnit *PredSU = PredEdge->getSUnit();
349 if (PredSU->NumSuccsLeft == 0) {
350 dbgs() << "*** Scheduling failed! ***\n";
352 dbgs() << " has been released too many times!\n";
356 --PredSU->NumSuccsLeft;
358 if (!forceUnitLatencies()) {
359 // Updating predecessor's height. This is now the cycle when the
360 // predecessor can be scheduled without causing a pipeline stall.
361 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
364 // If all the node's successors are scheduled, this node is ready
365 // to be scheduled. Ignore the special EntrySU node.
366 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
367 PredSU->isAvailable = true;
369 unsigned Height = PredSU->getHeight();
370 if (Height < MinAvailableCycle)
371 MinAvailableCycle = Height;
373 if (isReady(PredSU)) {
374 AvailableQueue->push(PredSU);
376 // CapturePred and others may have left the node in the pending queue, avoid
378 else if (!PredSU->isPending) {
379 PredSU->isPending = true;
380 PendingQueue.push_back(PredSU);
385 /// IsChainDependent - Test if Outer is reachable from Inner through
386 /// chain dependencies.
387 static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
389 const TargetInstrInfo *TII) {
394 // For a TokenFactor, examine each operand. There may be multiple ways
395 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
396 // most nesting in order to ensure that we find the corresponding match.
397 if (N->getOpcode() == ISD::TokenFactor) {
398 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
399 if (IsChainDependent(N->getOperand(i).getNode(), Inner, NestLevel, TII))
403 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
404 if (N->isMachineOpcode()) {
405 if (N->getMachineOpcode() ==
406 (unsigned)TII->getCallFrameDestroyOpcode()) {
408 } else if (N->getMachineOpcode() ==
409 (unsigned)TII->getCallFrameSetupOpcode()) {
415 // Otherwise, find the chain and continue climbing.
416 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
417 if (N->getOperand(i).getValueType() == MVT::Other) {
418 N = N->getOperand(i).getNode();
419 goto found_chain_operand;
422 found_chain_operand:;
423 if (N->getOpcode() == ISD::EntryToken)
428 /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
429 /// the corresponding (lowered) CALLSEQ_BEGIN node.
431 /// NestLevel and MaxNested are used in recursion to indcate the current level
432 /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
433 /// level seen so far.
435 /// TODO: It would be better to give CALLSEQ_END an explicit operand to point
436 /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
438 FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
439 const TargetInstrInfo *TII) {
441 // For a TokenFactor, examine each operand. There may be multiple ways
442 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
443 // most nesting in order to ensure that we find the corresponding match.
444 if (N->getOpcode() == ISD::TokenFactor) {
446 unsigned BestMaxNest = MaxNest;
447 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
448 unsigned MyNestLevel = NestLevel;
449 unsigned MyMaxNest = MaxNest;
450 if (SDNode *New = FindCallSeqStart(N->getOperand(i).getNode(),
451 MyNestLevel, MyMaxNest, TII))
452 if (!Best || (MyMaxNest > BestMaxNest)) {
454 BestMaxNest = MyMaxNest;
458 MaxNest = BestMaxNest;
461 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
462 if (N->isMachineOpcode()) {
463 if (N->getMachineOpcode() ==
464 (unsigned)TII->getCallFrameDestroyOpcode()) {
466 MaxNest = std::max(MaxNest, NestLevel);
467 } else if (N->getMachineOpcode() ==
468 (unsigned)TII->getCallFrameSetupOpcode()) {
469 assert(NestLevel != 0);
475 // Otherwise, find the chain and continue climbing.
476 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
477 if (N->getOperand(i).getValueType() == MVT::Other) {
478 N = N->getOperand(i).getNode();
479 goto found_chain_operand;
482 found_chain_operand:;
483 if (N->getOpcode() == ISD::EntryToken)
488 /// Call ReleasePred for each predecessor, then update register live def/gen.
489 /// Always update LiveRegDefs for a register dependence even if the current SU
490 /// also defines the register. This effectively create one large live range
491 /// across a sequence of two-address node. This is important because the
492 /// entire chain must be scheduled together. Example:
495 /// flags = (2) addc flags
496 /// flags = (1) addc flags
500 /// LiveRegDefs[flags] = 3
501 /// LiveRegGens[flags] = 1
503 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
504 /// interference on flags.
505 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
506 // Bottom up: release predecessors
507 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
509 ReleasePred(SU, &*I);
510 if (I->isAssignedRegDep()) {
511 // This is a physical register dependency and it's impossible or
512 // expensive to copy the register. Make sure nothing that can
513 // clobber the register is scheduled between the predecessor and
515 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
516 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
517 "interference on register dependence");
518 LiveRegDefs[I->getReg()] = I->getSUnit();
519 if (!LiveRegGens[I->getReg()]) {
521 LiveRegGens[I->getReg()] = SU;
526 // If we're scheduling a lowered CALLSEQ_END, find the corresponding
527 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
528 // these nodes, to prevent other calls from being interscheduled with them.
529 unsigned CallResource = TRI->getNumRegs();
530 if (!LiveRegDefs[CallResource])
531 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
532 if (Node->isMachineOpcode() &&
533 Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
534 unsigned NestLevel = 0;
535 unsigned MaxNest = 0;
536 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
538 SUnit *Def = &SUnits[N->getNodeId()];
539 CallSeqEndForStart[Def] = SU;
542 LiveRegDefs[CallResource] = Def;
543 LiveRegGens[CallResource] = SU;
548 /// Check to see if any of the pending instructions are ready to issue. If
549 /// so, add them to the available queue.
550 void ScheduleDAGRRList::ReleasePending() {
551 if (DisableSchedCycles) {
552 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
556 // If the available queue is empty, it is safe to reset MinAvailableCycle.
557 if (AvailableQueue->empty())
558 MinAvailableCycle = UINT_MAX;
560 // Check to see if any of the pending instructions are ready to issue. If
561 // so, add them to the available queue.
562 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
563 unsigned ReadyCycle = PendingQueue[i]->getHeight();
564 if (ReadyCycle < MinAvailableCycle)
565 MinAvailableCycle = ReadyCycle;
567 if (PendingQueue[i]->isAvailable) {
568 if (!isReady(PendingQueue[i]))
570 AvailableQueue->push(PendingQueue[i]);
572 PendingQueue[i]->isPending = false;
573 PendingQueue[i] = PendingQueue.back();
574 PendingQueue.pop_back();
579 /// Move the scheduler state forward by the specified number of Cycles.
580 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
581 if (NextCycle <= CurCycle)
585 AvailableQueue->setCurCycle(NextCycle);
586 if (!HazardRec->isEnabled()) {
587 // Bypass lots of virtual calls in case of long latency.
588 CurCycle = NextCycle;
591 for (; CurCycle != NextCycle; ++CurCycle) {
592 HazardRec->RecedeCycle();
595 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
596 // available Q to release pending nodes at least once before popping.
600 /// Move the scheduler state forward until the specified node's dependents are
601 /// ready and can be scheduled with no resource conflicts.
602 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
603 if (DisableSchedCycles)
606 // FIXME: Nodes such as CopyFromReg probably should not advance the current
607 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
608 // has predecessors the cycle will be advanced when they are scheduled.
609 // But given the crude nature of modeling latency though such nodes, we
610 // currently need to treat these nodes like real instructions.
611 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
613 unsigned ReadyCycle = SU->getHeight();
615 // Bump CurCycle to account for latency. We assume the latency of other
616 // available instructions may be hidden by the stall (not a full pipe stall).
617 // This updates the hazard recognizer's cycle before reserving resources for
619 AdvanceToCycle(ReadyCycle);
621 // Calls are scheduled in their preceding cycle, so don't conflict with
622 // hazards from instructions after the call. EmitNode will reset the
623 // scoreboard state before emitting the call.
627 // FIXME: For resource conflicts in very long non-pipelined stages, we
628 // should probably skip ahead here to avoid useless scoreboard checks.
631 ScheduleHazardRecognizer::HazardType HT =
632 HazardRec->getHazardType(SU, -Stalls);
634 if (HT == ScheduleHazardRecognizer::NoHazard)
639 AdvanceToCycle(CurCycle + Stalls);
642 /// Record this SUnit in the HazardRecognizer.
643 /// Does not update CurCycle.
644 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
645 if (!HazardRec->isEnabled())
648 // Check for phys reg copy.
652 switch (SU->getNode()->getOpcode()) {
654 assert(SU->getNode()->isMachineOpcode() &&
655 "This target-independent node should not be scheduled.");
657 case ISD::MERGE_VALUES:
658 case ISD::TokenFactor:
660 case ISD::CopyFromReg:
662 // Noops don't affect the scoreboard state. Copies are likely to be
666 // For inline asm, clear the pipeline state.
671 // Calls are scheduled with their preceding instructions. For bottom-up
672 // scheduling, clear the pipeline state before emitting.
676 HazardRec->EmitInstruction(SU);
679 static void resetVRegCycle(SUnit *SU);
681 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
682 /// count of its predecessors. If a predecessor pending count is zero, add it to
683 /// the Available queue.
684 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
685 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
686 DEBUG(SU->dump(this));
689 if (CurCycle < SU->getHeight())
690 DEBUG(dbgs() << " Height [" << SU->getHeight()
691 << "] pipeline stall!\n");
694 // FIXME: Do not modify node height. It may interfere with
695 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
696 // node its ready cycle can aid heuristics, and after scheduling it can
697 // indicate the scheduled cycle.
698 SU->setHeightToAtLeast(CurCycle);
700 // Reserve resources for the scheduled intruction.
703 Sequence.push_back(SU);
705 AvailableQueue->scheduledNode(SU);
707 // If HazardRec is disabled, and each inst counts as one cycle, then
708 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
709 // PendingQueue for schedulers that implement HasReadyFilter.
710 if (!HazardRec->isEnabled() && AvgIPC < 2)
711 AdvanceToCycle(CurCycle + 1);
713 // Update liveness of predecessors before successors to avoid treating a
714 // two-address node as a live range def.
715 ReleasePredecessors(SU);
717 // Release all the implicit physical register defs that are live.
718 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
720 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
721 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
722 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
724 LiveRegDefs[I->getReg()] = NULL;
725 LiveRegGens[I->getReg()] = NULL;
728 // Release the special call resource dependence, if this is the beginning
730 unsigned CallResource = TRI->getNumRegs();
731 if (LiveRegDefs[CallResource] == SU)
732 for (const SDNode *SUNode = SU->getNode(); SUNode;
733 SUNode = SUNode->getGluedNode()) {
734 if (SUNode->isMachineOpcode() &&
735 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
736 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
738 LiveRegDefs[CallResource] = NULL;
739 LiveRegGens[CallResource] = NULL;
745 SU->isScheduled = true;
747 // Conditions under which the scheduler should eagerly advance the cycle:
748 // (1) No available instructions
749 // (2) All pipelines full, so available instructions must have hazards.
751 // If HazardRec is disabled, the cycle was pre-advanced before calling
752 // ReleasePredecessors. In that case, IssueCount should remain 0.
754 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
755 if (HazardRec->isEnabled() || AvgIPC > 1) {
756 if (SU->getNode() && SU->getNode()->isMachineOpcode())
758 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
759 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
760 AdvanceToCycle(CurCycle + 1);
764 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
765 /// unscheduled, incrcease the succ left count of its predecessors. Remove
766 /// them from AvailableQueue if necessary.
767 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
768 SUnit *PredSU = PredEdge->getSUnit();
769 if (PredSU->isAvailable) {
770 PredSU->isAvailable = false;
771 if (!PredSU->isPending)
772 AvailableQueue->remove(PredSU);
775 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
776 ++PredSU->NumSuccsLeft;
779 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
780 /// its predecessor states to reflect the change.
781 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
782 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
783 DEBUG(SU->dump(this));
785 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
788 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
789 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
790 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
791 "Physical register dependency violated?");
793 LiveRegDefs[I->getReg()] = NULL;
794 LiveRegGens[I->getReg()] = NULL;
798 // Reclaim the special call resource dependence, if this is the beginning
800 unsigned CallResource = TRI->getNumRegs();
801 for (const SDNode *SUNode = SU->getNode(); SUNode;
802 SUNode = SUNode->getGluedNode()) {
803 if (SUNode->isMachineOpcode() &&
804 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
806 LiveRegDefs[CallResource] = SU;
807 LiveRegGens[CallResource] = CallSeqEndForStart[SU];
811 // Release the special call resource dependence, if this is the end
813 if (LiveRegGens[CallResource] == SU)
814 for (const SDNode *SUNode = SU->getNode(); SUNode;
815 SUNode = SUNode->getGluedNode()) {
816 if (SUNode->isMachineOpcode() &&
817 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
818 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
820 LiveRegDefs[CallResource] = NULL;
821 LiveRegGens[CallResource] = NULL;
825 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
827 if (I->isAssignedRegDep()) {
828 if (!LiveRegDefs[I->getReg()])
830 // This becomes the nearest def. Note that an earlier def may still be
831 // pending if this is a two-address node.
832 LiveRegDefs[I->getReg()] = SU;
833 if (LiveRegGens[I->getReg()] == NULL ||
834 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
835 LiveRegGens[I->getReg()] = I->getSUnit();
838 if (SU->getHeight() < MinAvailableCycle)
839 MinAvailableCycle = SU->getHeight();
841 SU->setHeightDirty();
842 SU->isScheduled = false;
843 SU->isAvailable = true;
844 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
845 // Don't make available until backtracking is complete.
846 SU->isPending = true;
847 PendingQueue.push_back(SU);
850 AvailableQueue->push(SU);
852 AvailableQueue->unscheduledNode(SU);
855 /// After backtracking, the hazard checker needs to be restored to a state
856 /// corresponding the current cycle.
857 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
860 unsigned LookAhead = std::min((unsigned)Sequence.size(),
861 HazardRec->getMaxLookAhead());
865 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
866 unsigned HazardCycle = (*I)->getHeight();
867 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
869 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
870 HazardRec->RecedeCycle();
876 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
877 /// BTCycle in order to schedule a specific node.
878 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
879 SUnit *OldSU = Sequence.back();
882 if (SU->isSucc(OldSU))
883 // Don't try to remove SU from AvailableQueue.
884 SU->isAvailable = false;
885 // FIXME: use ready cycle instead of height
886 CurCycle = OldSU->getHeight();
887 UnscheduleNodeBottomUp(OldSU);
888 AvailableQueue->setCurCycle(CurCycle);
891 OldSU = Sequence.back();
894 assert(!SU->isSucc(OldSU) && "Something is wrong!");
896 RestoreHazardCheckerBottomUp();
903 static bool isOperandOf(const SUnit *SU, SDNode *N) {
904 for (const SDNode *SUNode = SU->getNode(); SUNode;
905 SUNode = SUNode->getGluedNode()) {
906 if (SUNode->isOperandOf(N))
912 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
913 /// successors to the newly created node.
914 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
915 SDNode *N = SU->getNode();
919 if (SU->getNode()->getGluedNode())
923 bool TryUnfold = false;
924 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
925 EVT VT = N->getValueType(i);
928 else if (VT == MVT::Other)
931 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
932 const SDValue &Op = N->getOperand(i);
933 EVT VT = Op.getNode()->getValueType(Op.getResNo());
939 SmallVector<SDNode*, 2> NewNodes;
940 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
943 // unfolding an x86 DEC64m operation results in store, dec, load which
944 // can't be handled here so quit
945 if (NewNodes.size() == 3)
948 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
949 assert(NewNodes.size() == 2 && "Expected a load folding node!");
952 SDNode *LoadNode = NewNodes[0];
953 unsigned NumVals = N->getNumValues();
954 unsigned OldNumVals = SU->getNode()->getNumValues();
955 for (unsigned i = 0; i != NumVals; ++i)
956 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
957 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
958 SDValue(LoadNode, 1));
960 // LoadNode may already exist. This can happen when there is another
961 // load from the same location and producing the same type of value
962 // but it has different alignment or volatileness.
963 bool isNewLoad = true;
965 if (LoadNode->getNodeId() != -1) {
966 LoadSU = &SUnits[LoadNode->getNodeId()];
969 LoadSU = CreateNewSUnit(LoadNode);
970 LoadNode->setNodeId(LoadSU->NodeNum);
972 InitNumRegDefsLeft(LoadSU);
973 computeLatency(LoadSU);
976 SUnit *NewSU = CreateNewSUnit(N);
977 assert(N->getNodeId() == -1 && "Node already inserted!");
978 N->setNodeId(NewSU->NodeNum);
980 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
981 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
982 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
983 NewSU->isTwoAddress = true;
987 if (MCID.isCommutable())
988 NewSU->isCommutable = true;
990 InitNumRegDefsLeft(NewSU);
991 computeLatency(NewSU);
993 // Record all the edges to and from the old SU, by category.
994 SmallVector<SDep, 4> ChainPreds;
995 SmallVector<SDep, 4> ChainSuccs;
996 SmallVector<SDep, 4> LoadPreds;
997 SmallVector<SDep, 4> NodePreds;
998 SmallVector<SDep, 4> NodeSuccs;
999 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1002 ChainPreds.push_back(*I);
1003 else if (isOperandOf(I->getSUnit(), LoadNode))
1004 LoadPreds.push_back(*I);
1006 NodePreds.push_back(*I);
1008 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1011 ChainSuccs.push_back(*I);
1013 NodeSuccs.push_back(*I);
1016 // Now assign edges to the newly-created nodes.
1017 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
1018 const SDep &Pred = ChainPreds[i];
1019 RemovePred(SU, Pred);
1021 AddPred(LoadSU, Pred);
1023 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
1024 const SDep &Pred = LoadPreds[i];
1025 RemovePred(SU, Pred);
1027 AddPred(LoadSU, Pred);
1029 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
1030 const SDep &Pred = NodePreds[i];
1031 RemovePred(SU, Pred);
1032 AddPred(NewSU, Pred);
1034 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
1035 SDep D = NodeSuccs[i];
1036 SUnit *SuccDep = D.getSUnit();
1038 RemovePred(SuccDep, D);
1040 AddPred(SuccDep, D);
1041 // Balance register pressure.
1042 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1043 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1044 --NewSU->NumRegDefsLeft;
1046 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
1047 SDep D = ChainSuccs[i];
1048 SUnit *SuccDep = D.getSUnit();
1050 RemovePred(SuccDep, D);
1053 AddPred(SuccDep, D);
1057 // Add a data dependency to reflect that NewSU reads the value defined
1059 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
1062 AvailableQueue->addNode(LoadSU);
1063 AvailableQueue->addNode(NewSU);
1067 if (NewSU->NumSuccsLeft == 0) {
1068 NewSU->isAvailable = true;
1074 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
1075 NewSU = CreateClone(SU);
1077 // New SUnit has the exact same predecessors.
1078 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1080 if (!I->isArtificial())
1083 // Only copy scheduled successors. Cut them from old node's successor
1084 // list and move them over.
1085 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1086 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1088 if (I->isArtificial())
1090 SUnit *SuccSU = I->getSUnit();
1091 if (SuccSU->isScheduled) {
1096 DelDeps.push_back(std::make_pair(SuccSU, D));
1099 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
1100 RemovePred(DelDeps[i].first, DelDeps[i].second);
1102 AvailableQueue->updateNode(SU);
1103 AvailableQueue->addNode(NewSU);
1109 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
1110 /// scheduled successors of the given SUnit to the last copy.
1111 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
1112 const TargetRegisterClass *DestRC,
1113 const TargetRegisterClass *SrcRC,
1114 SmallVector<SUnit*, 2> &Copies) {
1115 SUnit *CopyFromSU = CreateNewSUnit(NULL);
1116 CopyFromSU->CopySrcRC = SrcRC;
1117 CopyFromSU->CopyDstRC = DestRC;
1119 SUnit *CopyToSU = CreateNewSUnit(NULL);
1120 CopyToSU->CopySrcRC = DestRC;
1121 CopyToSU->CopyDstRC = SrcRC;
1123 // Only copy scheduled successors. Cut them from old node's successor
1124 // list and move them over.
1125 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1126 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1128 if (I->isArtificial())
1130 SUnit *SuccSU = I->getSUnit();
1131 if (SuccSU->isScheduled) {
1133 D.setSUnit(CopyToSU);
1135 DelDeps.push_back(std::make_pair(SuccSU, *I));
1138 // Avoid scheduling the def-side copy before other successors. Otherwise
1139 // we could introduce another physreg interference on the copy and
1140 // continue inserting copies indefinitely.
1141 SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
1142 /*Reg=*/0, /*isNormalMemory=*/false,
1143 /*isMustAlias=*/false, /*isArtificial=*/true);
1147 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
1148 RemovePred(DelDeps[i].first, DelDeps[i].second);
1150 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
1151 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
1153 AvailableQueue->updateNode(SU);
1154 AvailableQueue->addNode(CopyFromSU);
1155 AvailableQueue->addNode(CopyToSU);
1156 Copies.push_back(CopyFromSU);
1157 Copies.push_back(CopyToSU);
1162 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
1163 /// definition of the specified node.
1164 /// FIXME: Move to SelectionDAG?
1165 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
1166 const TargetInstrInfo *TII) {
1167 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1168 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1169 unsigned NumRes = MCID.getNumDefs();
1170 for (const uint16_t *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
1175 return N->getValueType(NumRes);
1178 /// CheckForLiveRegDef - Return true and update live register vector if the
1179 /// specified register def of the specified SUnit clobbers any "live" registers.
1180 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
1181 std::vector<SUnit*> &LiveRegDefs,
1182 SmallSet<unsigned, 4> &RegAdded,
1183 SmallVector<unsigned, 4> &LRegs,
1184 const TargetRegisterInfo *TRI) {
1185 for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
1187 // Check if Ref is live.
1188 if (!LiveRegDefs[*AliasI]) continue;
1190 // Allow multiple uses of the same def.
1191 if (LiveRegDefs[*AliasI] == SU) continue;
1193 // Add Reg to the set of interfering live regs.
1194 if (RegAdded.insert(*AliasI)) {
1195 LRegs.push_back(*AliasI);
1200 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1201 /// by RegMask, and add them to LRegs.
1202 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
1203 std::vector<SUnit*> &LiveRegDefs,
1204 SmallSet<unsigned, 4> &RegAdded,
1205 SmallVector<unsigned, 4> &LRegs) {
1206 // Look at all live registers. Skip Reg0 and the special CallResource.
1207 for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
1208 if (!LiveRegDefs[i]) continue;
1209 if (LiveRegDefs[i] == SU) continue;
1210 if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
1211 if (RegAdded.insert(i))
1216 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1217 static const uint32_t *getNodeRegMask(const SDNode *N) {
1218 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1219 if (const RegisterMaskSDNode *Op =
1220 dyn_cast<RegisterMaskSDNode>(N->getOperand(i).getNode()))
1221 return Op->getRegMask();
1225 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1226 /// scheduling of the given node to satisfy live physical register dependencies.
1227 /// If the specific node is the last one that's available to schedule, do
1228 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
1229 bool ScheduleDAGRRList::
1230 DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
1231 if (NumLiveRegs == 0)
1234 SmallSet<unsigned, 4> RegAdded;
1235 // If this node would clobber any "live" register, then it's not ready.
1237 // If SU is the currently live definition of the same register that it uses,
1238 // then we are free to schedule it.
1239 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1241 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
1242 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1243 RegAdded, LRegs, TRI);
1246 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
1247 if (Node->getOpcode() == ISD::INLINEASM) {
1248 // Inline asm can clobber physical defs.
1249 unsigned NumOps = Node->getNumOperands();
1250 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1251 --NumOps; // Ignore the glue operand.
1253 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1255 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
1256 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
1258 ++i; // Skip the ID value.
1259 if (InlineAsm::isRegDefKind(Flags) ||
1260 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1261 InlineAsm::isClobberKind(Flags)) {
1262 // Check for def of register or earlyclobber register.
1263 for (; NumVals; --NumVals, ++i) {
1264 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1265 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1266 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1274 if (!Node->isMachineOpcode())
1276 // If we're in the middle of scheduling a call, don't begin scheduling
1277 // another call. Also, don't allow any physical registers to be live across
1279 if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
1280 // Check the special calling-sequence resource.
1281 unsigned CallResource = TRI->getNumRegs();
1282 if (LiveRegDefs[CallResource]) {
1283 SDNode *Gen = LiveRegGens[CallResource]->getNode();
1284 while (SDNode *Glued = Gen->getGluedNode())
1286 if (!IsChainDependent(Gen, Node, 0, TII) && RegAdded.insert(CallResource))
1287 LRegs.push_back(CallResource);
1290 if (const uint32_t *RegMask = getNodeRegMask(Node))
1291 CheckForLiveRegDefMasked(SU, RegMask, LiveRegDefs, RegAdded, LRegs);
1293 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1294 if (!MCID.ImplicitDefs)
1296 for (const uint16_t *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
1297 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1300 return !LRegs.empty();
1303 /// Return a node that can be scheduled in this cycle. Requirements:
1304 /// (1) Ready: latency has been satisfied
1305 /// (2) No Hazards: resources are available
1306 /// (3) No Interferences: may unschedule to break register interferences.
1307 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1308 SmallVector<SUnit*, 4> Interferences;
1309 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1311 SUnit *CurSU = AvailableQueue->pop();
1313 SmallVector<unsigned, 4> LRegs;
1314 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1316 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1318 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1319 Interferences.push_back(CurSU);
1320 CurSU = AvailableQueue->pop();
1323 // Add the nodes that aren't ready back onto the available list.
1324 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1325 Interferences[i]->isPending = false;
1326 assert(Interferences[i]->isAvailable && "must still be available");
1327 AvailableQueue->push(Interferences[i]);
1332 // All candidates are delayed due to live physical reg dependencies.
1333 // Try backtracking, code duplication, or inserting cross class copies
1335 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1336 SUnit *TrySU = Interferences[i];
1337 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1339 // Try unscheduling up to the point where it's safe to schedule
1342 unsigned LiveCycle = UINT_MAX;
1343 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1344 unsigned Reg = LRegs[j];
1345 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1346 BtSU = LiveRegGens[Reg];
1347 LiveCycle = BtSU->getHeight();
1350 if (!WillCreateCycle(TrySU, BtSU)) {
1351 BacktrackBottomUp(TrySU, BtSU);
1353 // Force the current node to be scheduled before the node that
1354 // requires the physical reg dep.
1355 if (BtSU->isAvailable) {
1356 BtSU->isAvailable = false;
1357 if (!BtSU->isPending)
1358 AvailableQueue->remove(BtSU);
1360 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
1361 /*Reg=*/0, /*isNormalMemory=*/false,
1362 /*isMustAlias=*/false, /*isArtificial=*/true));
1364 // If one or more successors has been unscheduled, then the current
1365 // node is no longer avaialable. Schedule a successor that's now
1366 // available instead.
1367 if (!TrySU->isAvailable) {
1368 CurSU = AvailableQueue->pop();
1372 TrySU->isPending = false;
1373 Interferences.erase(Interferences.begin()+i);
1380 // Can't backtrack. If it's too expensive to copy the value, then try
1381 // duplicate the nodes that produces these "too expensive to copy"
1382 // values to break the dependency. In case even that doesn't work,
1383 // insert cross class copies.
1384 // If it's not too expensive, i.e. cost != -1, issue copies.
1385 SUnit *TrySU = Interferences[0];
1386 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1387 assert(LRegs.size() == 1 && "Can't handle this yet!");
1388 unsigned Reg = LRegs[0];
1389 SUnit *LRDef = LiveRegDefs[Reg];
1390 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1391 const TargetRegisterClass *RC =
1392 TRI->getMinimalPhysRegClass(Reg, VT);
1393 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1395 // If cross copy register class is the same as RC, then it must be possible
1396 // copy the value directly. Do not try duplicate the def.
1397 // If cross copy register class is not the same as RC, then it's possible to
1398 // copy the value but it require cross register class copies and it is
1400 // If cross copy register class is null, then it's not possible to copy
1401 // the value at all.
1404 NewDef = CopyAndMoveSuccessors(LRDef);
1405 if (!DestRC && !NewDef)
1406 report_fatal_error("Can't handle live physical register dependency!");
1409 // Issue copies, these can be expensive cross register class copies.
1410 SmallVector<SUnit*, 2> Copies;
1411 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1412 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1413 << " to SU #" << Copies.front()->NodeNum << "\n");
1414 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1415 /*Reg=*/0, /*isNormalMemory=*/false,
1416 /*isMustAlias=*/false,
1417 /*isArtificial=*/true));
1418 NewDef = Copies.back();
1421 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1422 << " to SU #" << TrySU->NodeNum << "\n");
1423 LiveRegDefs[Reg] = NewDef;
1424 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1425 /*Reg=*/0, /*isNormalMemory=*/false,
1426 /*isMustAlias=*/false,
1427 /*isArtificial=*/true));
1428 TrySU->isAvailable = false;
1432 assert(CurSU && "Unable to resolve live physical register dependencies!");
1434 // Add the nodes that aren't ready back onto the available list.
1435 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1436 Interferences[i]->isPending = false;
1437 // May no longer be available due to backtracking.
1438 if (Interferences[i]->isAvailable) {
1439 AvailableQueue->push(Interferences[i]);
1445 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1447 void ScheduleDAGRRList::ListScheduleBottomUp() {
1448 // Release any predecessors of the special Exit node.
1449 ReleasePredecessors(&ExitSU);
1451 // Add root to Available queue.
1452 if (!SUnits.empty()) {
1453 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1454 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1455 RootSU->isAvailable = true;
1456 AvailableQueue->push(RootSU);
1459 // While Available queue is not empty, grab the node with the highest
1460 // priority. If it is not ready put it back. Schedule the node.
1461 Sequence.reserve(SUnits.size());
1462 while (!AvailableQueue->empty()) {
1463 DEBUG(dbgs() << "\nExamining Available:\n";
1464 AvailableQueue->dump(this));
1466 // Pick the best node to schedule taking all constraints into
1468 SUnit *SU = PickNodeToScheduleBottomUp();
1470 AdvancePastStalls(SU);
1472 ScheduleNodeBottomUp(SU);
1474 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1475 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1476 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1477 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1481 // Reverse the order if it is bottom up.
1482 std::reverse(Sequence.begin(), Sequence.end());
1485 VerifyScheduledSequence(/*isBottomUp=*/true);
1489 //===----------------------------------------------------------------------===//
1490 // RegReductionPriorityQueue Definition
1491 //===----------------------------------------------------------------------===//
1493 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1494 // to reduce register pressure.
1497 class RegReductionPQBase;
1499 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1500 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1505 struct reverse_sort : public queue_sort {
1507 reverse_sort(SF &sf) : SortFunc(sf) {}
1508 reverse_sort(const reverse_sort &RHS) : SortFunc(RHS.SortFunc) {}
1510 bool operator()(SUnit* left, SUnit* right) const {
1511 // reverse left/right rather than simply !SortFunc(left, right)
1512 // to expose different paths in the comparison logic.
1513 return SortFunc(right, left);
1518 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1519 // reduction scheduler.
1520 struct bu_ls_rr_sort : public queue_sort {
1523 HasReadyFilter = false
1526 RegReductionPQBase *SPQ;
1527 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1528 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1530 bool operator()(SUnit* left, SUnit* right) const;
1533 // src_ls_rr_sort - Priority function for source order scheduler.
1534 struct src_ls_rr_sort : public queue_sort {
1537 HasReadyFilter = false
1540 RegReductionPQBase *SPQ;
1541 src_ls_rr_sort(RegReductionPQBase *spq)
1543 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1546 bool operator()(SUnit* left, SUnit* right) const;
1549 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1550 struct hybrid_ls_rr_sort : public queue_sort {
1553 HasReadyFilter = false
1556 RegReductionPQBase *SPQ;
1557 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1559 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1562 bool isReady(SUnit *SU, unsigned CurCycle) const;
1564 bool operator()(SUnit* left, SUnit* right) const;
1567 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1569 struct ilp_ls_rr_sort : public queue_sort {
1572 HasReadyFilter = false
1575 RegReductionPQBase *SPQ;
1576 ilp_ls_rr_sort(RegReductionPQBase *spq)
1578 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1581 bool isReady(SUnit *SU, unsigned CurCycle) const;
1583 bool operator()(SUnit* left, SUnit* right) const;
1586 class RegReductionPQBase : public SchedulingPriorityQueue {
1588 std::vector<SUnit*> Queue;
1589 unsigned CurQueueId;
1590 bool TracksRegPressure;
1593 // SUnits - The SUnits for the current graph.
1594 std::vector<SUnit> *SUnits;
1596 MachineFunction &MF;
1597 const TargetInstrInfo *TII;
1598 const TargetRegisterInfo *TRI;
1599 const TargetLowering *TLI;
1600 ScheduleDAGRRList *scheduleDAG;
1602 // SethiUllmanNumbers - The SethiUllman number for each node.
1603 std::vector<unsigned> SethiUllmanNumbers;
1605 /// RegPressure - Tracking current reg pressure per register class.
1607 std::vector<unsigned> RegPressure;
1609 /// RegLimit - Tracking the number of allocatable registers per register
1611 std::vector<unsigned> RegLimit;
1614 RegReductionPQBase(MachineFunction &mf,
1615 bool hasReadyFilter,
1618 const TargetInstrInfo *tii,
1619 const TargetRegisterInfo *tri,
1620 const TargetLowering *tli)
1621 : SchedulingPriorityQueue(hasReadyFilter),
1622 CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
1623 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1624 if (TracksRegPressure) {
1625 unsigned NumRC = TRI->getNumRegClasses();
1626 RegLimit.resize(NumRC);
1627 RegPressure.resize(NumRC);
1628 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1629 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1630 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1631 E = TRI->regclass_end(); I != E; ++I)
1632 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
1636 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1637 scheduleDAG = scheduleDag;
1640 ScheduleHazardRecognizer* getHazardRec() {
1641 return scheduleDAG->getHazardRec();
1644 void initNodes(std::vector<SUnit> &sunits);
1646 void addNode(const SUnit *SU);
1648 void updateNode(const SUnit *SU);
1650 void releaseState() {
1652 SethiUllmanNumbers.clear();
1653 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1656 unsigned getNodePriority(const SUnit *SU) const;
1658 unsigned getNodeOrdering(const SUnit *SU) const {
1659 if (!SU->getNode()) return 0;
1661 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1664 bool empty() const { return Queue.empty(); }
1666 void push(SUnit *U) {
1667 assert(!U->NodeQueueId && "Node in the queue already");
1668 U->NodeQueueId = ++CurQueueId;
1672 void remove(SUnit *SU) {
1673 assert(!Queue.empty() && "Queue is empty!");
1674 assert(SU->NodeQueueId != 0 && "Not in queue!");
1675 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1677 if (I != prior(Queue.end()))
1678 std::swap(*I, Queue.back());
1680 SU->NodeQueueId = 0;
1683 bool tracksRegPressure() const { return TracksRegPressure; }
1685 void dumpRegPressure() const;
1687 bool HighRegPressure(const SUnit *SU) const;
1689 bool MayReduceRegPressure(SUnit *SU) const;
1691 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
1693 void scheduledNode(SUnit *SU);
1695 void unscheduledNode(SUnit *SU);
1698 bool canClobber(const SUnit *SU, const SUnit *Op);
1699 void AddPseudoTwoAddrDeps();
1700 void PrescheduleNodesWithMultipleUses();
1701 void CalculateSethiUllmanNumbers();
1705 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1706 std::vector<SUnit *>::iterator Best = Q.begin();
1707 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1708 E = Q.end(); I != E; ++I)
1709 if (Picker(*Best, *I))
1712 if (Best != prior(Q.end()))
1713 std::swap(*Best, Q.back());
1719 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1721 if (DAG->StressSched) {
1722 reverse_sort<SF> RPicker(Picker);
1723 return popFromQueueImpl(Q, RPicker);
1727 return popFromQueueImpl(Q, Picker);
1731 class RegReductionPriorityQueue : public RegReductionPQBase {
1735 RegReductionPriorityQueue(MachineFunction &mf,
1738 const TargetInstrInfo *tii,
1739 const TargetRegisterInfo *tri,
1740 const TargetLowering *tli)
1741 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
1745 bool isBottomUp() const { return SF::IsBottomUp; }
1747 bool isReady(SUnit *U) const {
1748 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1752 if (Queue.empty()) return NULL;
1754 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
1759 void dump(ScheduleDAG *DAG) const {
1760 // Emulate pop() without clobbering NodeQueueIds.
1761 std::vector<SUnit*> DumpQueue = Queue;
1762 SF DumpPicker = Picker;
1763 while (!DumpQueue.empty()) {
1764 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
1765 dbgs() << "Height " << SU->getHeight() << ": ";
1771 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1772 BURegReductionPriorityQueue;
1774 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1775 SrcRegReductionPriorityQueue;
1777 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1778 HybridBURRPriorityQueue;
1780 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1781 ILPBURRPriorityQueue;
1782 } // end anonymous namespace
1784 //===----------------------------------------------------------------------===//
1785 // Static Node Priority for Register Pressure Reduction
1786 //===----------------------------------------------------------------------===//
1788 // Check for special nodes that bypass scheduling heuristics.
1789 // Currently this pushes TokenFactor nodes down, but may be used for other
1790 // pseudo-ops as well.
1792 // Return -1 to schedule right above left, 1 for left above right.
1793 // Return 0 if no bias exists.
1794 static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1795 bool LSchedLow = left->isScheduleLow;
1796 bool RSchedLow = right->isScheduleLow;
1797 if (LSchedLow != RSchedLow)
1798 return LSchedLow < RSchedLow ? 1 : -1;
1802 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1803 /// Smaller number is the higher priority.
1805 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1806 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1807 if (SethiUllmanNumber != 0)
1808 return SethiUllmanNumber;
1811 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1813 if (I->isCtrl()) continue; // ignore chain preds
1814 SUnit *PredSU = I->getSUnit();
1815 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1816 if (PredSethiUllman > SethiUllmanNumber) {
1817 SethiUllmanNumber = PredSethiUllman;
1819 } else if (PredSethiUllman == SethiUllmanNumber)
1823 SethiUllmanNumber += Extra;
1825 if (SethiUllmanNumber == 0)
1826 SethiUllmanNumber = 1;
1828 return SethiUllmanNumber;
1831 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1832 /// scheduling units.
1833 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1834 SethiUllmanNumbers.assign(SUnits->size(), 0);
1836 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1837 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1840 void RegReductionPQBase::addNode(const SUnit *SU) {
1841 unsigned SUSize = SethiUllmanNumbers.size();
1842 if (SUnits->size() > SUSize)
1843 SethiUllmanNumbers.resize(SUSize*2, 0);
1844 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1847 void RegReductionPQBase::updateNode(const SUnit *SU) {
1848 SethiUllmanNumbers[SU->NodeNum] = 0;
1849 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1852 // Lower priority means schedule further down. For bottom-up scheduling, lower
1853 // priority SUs are scheduled before higher priority SUs.
1854 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1855 assert(SU->NodeNum < SethiUllmanNumbers.size());
1856 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1857 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1858 // CopyToReg should be close to its uses to facilitate coalescing and
1861 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1862 Opc == TargetOpcode::SUBREG_TO_REG ||
1863 Opc == TargetOpcode::INSERT_SUBREG)
1864 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1865 // close to their uses to facilitate coalescing.
1867 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1868 // If SU does not have a register use, i.e. it doesn't produce a value
1869 // that would be consumed (e.g. store), then it terminates a chain of
1870 // computation. Give it a large SethiUllman number so it will be
1871 // scheduled right before its predecessors that it doesn't lengthen
1872 // their live ranges.
1874 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1875 // If SU does not have a register def, schedule it close to its uses
1876 // because it does not lengthen any live ranges.
1879 return SethiUllmanNumbers[SU->NodeNum];
1881 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1883 // FIXME: This assumes all of the defs are used as call operands.
1884 int NP = (int)Priority - SU->getNode()->getNumValues();
1885 return (NP > 0) ? NP : 0;
1891 //===----------------------------------------------------------------------===//
1892 // Register Pressure Tracking
1893 //===----------------------------------------------------------------------===//
1895 void RegReductionPQBase::dumpRegPressure() const {
1896 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1897 E = TRI->regclass_end(); I != E; ++I) {
1898 const TargetRegisterClass *RC = *I;
1899 unsigned Id = RC->getID();
1900 unsigned RP = RegPressure[Id];
1902 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1907 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1911 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1915 SUnit *PredSU = I->getSUnit();
1916 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1917 // to cover the number of registers defined (they are all live).
1918 if (PredSU->NumRegDefsLeft == 0) {
1921 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1922 RegDefPos.IsValid(); RegDefPos.Advance()) {
1923 unsigned RCId, Cost;
1924 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
1926 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1933 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
1934 const SDNode *N = SU->getNode();
1936 if (!N->isMachineOpcode() || !SU->NumSuccs)
1939 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1940 for (unsigned i = 0; i != NumDefs; ++i) {
1941 EVT VT = N->getValueType(i);
1942 if (!N->hasAnyUseOfValue(i))
1944 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1945 if (RegPressure[RCId] >= RegLimit[RCId])
1951 // Compute the register pressure contribution by this instruction by count up
1952 // for uses that are not live and down for defs. Only count register classes
1953 // that are already under high pressure. As a side effect, compute the number of
1954 // uses of registers that are already live.
1956 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1957 // so could probably be factored.
1958 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1961 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1965 SUnit *PredSU = I->getSUnit();
1966 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1967 // to cover the number of registers defined (they are all live).
1968 if (PredSU->NumRegDefsLeft == 0) {
1969 if (PredSU->getNode()->isMachineOpcode())
1973 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1974 RegDefPos.IsValid(); RegDefPos.Advance()) {
1975 EVT VT = RegDefPos.GetValue();
1976 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1977 if (RegPressure[RCId] >= RegLimit[RCId])
1981 const SDNode *N = SU->getNode();
1983 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
1986 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1987 for (unsigned i = 0; i != NumDefs; ++i) {
1988 EVT VT = N->getValueType(i);
1989 if (!N->hasAnyUseOfValue(i))
1991 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1992 if (RegPressure[RCId] >= RegLimit[RCId])
1998 void RegReductionPQBase::scheduledNode(SUnit *SU) {
1999 if (!TracksRegPressure)
2005 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2009 SUnit *PredSU = I->getSUnit();
2010 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2011 // to cover the number of registers defined (they are all live).
2012 if (PredSU->NumRegDefsLeft == 0) {
2015 // FIXME: The ScheduleDAG currently loses information about which of a
2016 // node's values is consumed by each dependence. Consequently, if the node
2017 // defines multiple register classes, we don't know which to pressurize
2018 // here. Instead the following loop consumes the register defs in an
2019 // arbitrary order. At least it handles the common case of clustered loads
2020 // to the same class. For precise liveness, each SDep needs to indicate the
2021 // result number. But that tightly couples the ScheduleDAG with the
2022 // SelectionDAG making updates tricky. A simpler hack would be to attach a
2023 // value type or register class to SDep.
2025 // The most important aspect of register tracking is balancing the increase
2026 // here with the reduction further below. Note that this SU may use multiple
2027 // defs in PredSU. The can't be determined here, but we've already
2028 // compensated by reducing NumRegDefsLeft in PredSU during
2029 // ScheduleDAGSDNodes::AddSchedEdges.
2030 --PredSU->NumRegDefsLeft;
2031 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2032 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2033 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2037 unsigned RCId, Cost;
2038 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2039 RegPressure[RCId] += Cost;
2044 // We should have this assert, but there may be dead SDNodes that never
2045 // materialize as SUnits, so they don't appear to generate liveness.
2046 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2047 int SkipRegDefs = (int)SU->NumRegDefsLeft;
2048 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2049 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2050 if (SkipRegDefs > 0)
2052 unsigned RCId, Cost;
2053 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2054 if (RegPressure[RCId] < Cost) {
2055 // Register pressure tracking is imprecise. This can happen. But we try
2056 // hard not to let it happen because it likely results in poor scheduling.
2057 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
2058 RegPressure[RCId] = 0;
2061 RegPressure[RCId] -= Cost;
2067 void RegReductionPQBase::unscheduledNode(SUnit *SU) {
2068 if (!TracksRegPressure)
2071 const SDNode *N = SU->getNode();
2074 if (!N->isMachineOpcode()) {
2075 if (N->getOpcode() != ISD::CopyToReg)
2078 unsigned Opc = N->getMachineOpcode();
2079 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2080 Opc == TargetOpcode::INSERT_SUBREG ||
2081 Opc == TargetOpcode::SUBREG_TO_REG ||
2082 Opc == TargetOpcode::REG_SEQUENCE ||
2083 Opc == TargetOpcode::IMPLICIT_DEF)
2087 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2091 SUnit *PredSU = I->getSUnit();
2092 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2093 // counts data deps.
2094 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
2096 const SDNode *PN = PredSU->getNode();
2097 if (!PN->isMachineOpcode()) {
2098 if (PN->getOpcode() == ISD::CopyFromReg) {
2099 EVT VT = PN->getValueType(0);
2100 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2101 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2105 unsigned POpc = PN->getMachineOpcode();
2106 if (POpc == TargetOpcode::IMPLICIT_DEF)
2108 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2109 POpc == TargetOpcode::INSERT_SUBREG ||
2110 POpc == TargetOpcode::SUBREG_TO_REG) {
2111 EVT VT = PN->getValueType(0);
2112 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2113 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2116 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2117 for (unsigned i = 0; i != NumDefs; ++i) {
2118 EVT VT = PN->getValueType(i);
2119 if (!PN->hasAnyUseOfValue(i))
2121 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2122 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2123 // Register pressure tracking is imprecise. This can happen.
2124 RegPressure[RCId] = 0;
2126 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2130 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2131 // may transfer data dependencies to CopyToReg.
2132 if (SU->NumSuccs && N->isMachineOpcode()) {
2133 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2134 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2135 EVT VT = N->getValueType(i);
2136 if (VT == MVT::Glue || VT == MVT::Other)
2138 if (!N->hasAnyUseOfValue(i))
2140 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2141 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2148 //===----------------------------------------------------------------------===//
2149 // Dynamic Node Priority for Register Pressure Reduction
2150 //===----------------------------------------------------------------------===//
2152 /// closestSucc - Returns the scheduled cycle of the successor which is
2153 /// closest to the current cycle.
2154 static unsigned closestSucc(const SUnit *SU) {
2155 unsigned MaxHeight = 0;
2156 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2158 if (I->isCtrl()) continue; // ignore chain succs
2159 unsigned Height = I->getSUnit()->getHeight();
2160 // If there are bunch of CopyToRegs stacked up, they should be considered
2161 // to be at the same position.
2162 if (I->getSUnit()->getNode() &&
2163 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
2164 Height = closestSucc(I->getSUnit())+1;
2165 if (Height > MaxHeight)
2171 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
2172 /// for scratch registers, i.e. number of data dependencies.
2173 static unsigned calcMaxScratches(const SUnit *SU) {
2174 unsigned Scratches = 0;
2175 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2177 if (I->isCtrl()) continue; // ignore chain preds
2183 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2184 /// CopyFromReg from a virtual register.
2185 static bool hasOnlyLiveInOpers(const SUnit *SU) {
2186 bool RetVal = false;
2187 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2189 if (I->isCtrl()) continue;
2190 const SUnit *PredSU = I->getSUnit();
2191 if (PredSU->getNode() &&
2192 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2194 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2195 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2205 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
2206 /// CopyToReg to a virtual register. This SU def is probably a liveout and
2207 /// it has no other use. It should be scheduled closer to the terminator.
2208 static bool hasOnlyLiveOutUses(const SUnit *SU) {
2209 bool RetVal = false;
2210 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2212 if (I->isCtrl()) continue;
2213 const SUnit *SuccSU = I->getSUnit();
2214 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2216 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2217 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2227 // Set isVRegCycle for a node with only live in opers and live out uses. Also
2228 // set isVRegCycle for its CopyFromReg operands.
2230 // This is only relevant for single-block loops, in which case the VRegCycle
2231 // node is likely an induction variable in which the operand and target virtual
2232 // registers should be coalesced (e.g. pre/post increment values). Setting the
2233 // isVRegCycle flag helps the scheduler prioritize other uses of the same
2234 // CopyFromReg so that this node becomes the virtual register "kill". This
2235 // avoids interference between the values live in and out of the block and
2236 // eliminates a copy inside the loop.
2237 static void initVRegCycle(SUnit *SU) {
2238 if (DisableSchedVRegCycle)
2241 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2244 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2246 SU->isVRegCycle = true;
2248 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2250 if (I->isCtrl()) continue;
2251 I->getSUnit()->isVRegCycle = true;
2255 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2256 // CopyFromReg operands. We should no longer penalize other uses of this VReg.
2257 static void resetVRegCycle(SUnit *SU) {
2258 if (!SU->isVRegCycle)
2261 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2263 if (I->isCtrl()) continue; // ignore chain preds
2264 SUnit *PredSU = I->getSUnit();
2265 if (PredSU->isVRegCycle) {
2266 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2267 "VRegCycle def must be CopyFromReg");
2268 I->getSUnit()->isVRegCycle = 0;
2273 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2274 // means a node that defines the VRegCycle has not been scheduled yet.
2275 static bool hasVRegCycleUse(const SUnit *SU) {
2276 // If this SU also defines the VReg, don't hoist it as a "use".
2277 if (SU->isVRegCycle)
2280 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2282 if (I->isCtrl()) continue; // ignore chain preds
2283 if (I->getSUnit()->isVRegCycle &&
2284 I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2285 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2292 // Check for either a dependence (latency) or resource (hazard) stall.
2294 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2295 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2296 if ((int)SPQ->getCurCycle() < Height) return true;
2297 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2298 != ScheduleHazardRecognizer::NoHazard)
2303 // Return -1 if left has higher priority, 1 if right has higher priority.
2304 // Return 0 if latency-based priority is equivalent.
2305 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2306 RegReductionPQBase *SPQ) {
2307 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2308 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2309 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2310 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2311 int LHeight = (int)left->getHeight() + LPenalty;
2312 int RHeight = (int)right->getHeight() + RPenalty;
2314 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
2315 BUHasStall(left, LHeight, SPQ);
2316 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
2317 BUHasStall(right, RHeight, SPQ);
2319 // If scheduling one of the node will cause a pipeline stall, delay it.
2320 // If scheduling either one of the node will cause a pipeline stall, sort
2321 // them according to their height.
2325 if (LHeight != RHeight)
2326 return LHeight > RHeight ? 1 : -1;
2330 // If either node is scheduling for latency, sort them by height/depth
2332 if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2333 right->SchedulingPref == Sched::ILP)) {
2334 // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
2335 // is enabled, grouping instructions by cycle, then its height is already
2336 // covered so only its depth matters. We also reach this point if both stall
2337 // but have the same height.
2338 if (!SPQ->getHazardRec()->isEnabled()) {
2339 if (LHeight != RHeight)
2340 return LHeight > RHeight ? 1 : -1;
2342 int LDepth = left->getDepth() - LPenalty;
2343 int RDepth = right->getDepth() - RPenalty;
2344 if (LDepth != RDepth) {
2345 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2346 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2347 << ") depth " << RDepth << "\n");
2348 return LDepth < RDepth ? 1 : -1;
2350 if (left->Latency != right->Latency)
2351 return left->Latency > right->Latency ? 1 : -1;
2356 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2357 // Schedule physical register definitions close to their use. This is
2358 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2359 // long as shortening physreg live ranges is generally good, we can defer
2360 // creating a subtarget hook.
2361 if (!DisableSchedPhysRegJoin) {
2362 bool LHasPhysReg = left->hasPhysRegDefs;
2363 bool RHasPhysReg = right->hasPhysRegDefs;
2364 if (LHasPhysReg != RHasPhysReg) {
2366 const char *const PhysRegMsg[] = {" has no physreg"," defines a physreg"};
2368 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2369 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2370 << PhysRegMsg[RHasPhysReg] << "\n");
2371 return LHasPhysReg < RHasPhysReg;
2375 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
2376 unsigned LPriority = SPQ->getNodePriority(left);
2377 unsigned RPriority = SPQ->getNodePriority(right);
2379 // Be really careful about hoisting call operands above previous calls.
2380 // Only allows it if it would reduce register pressure.
2381 if (left->isCall && right->isCallOp) {
2382 unsigned RNumVals = right->getNode()->getNumValues();
2383 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2385 if (right->isCall && left->isCallOp) {
2386 unsigned LNumVals = left->getNode()->getNumValues();
2387 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2390 if (LPriority != RPriority)
2391 return LPriority > RPriority;
2393 // One or both of the nodes are calls and their sethi-ullman numbers are the
2394 // same, then keep source order.
2395 if (left->isCall || right->isCall) {
2396 unsigned LOrder = SPQ->getNodeOrdering(left);
2397 unsigned ROrder = SPQ->getNodeOrdering(right);
2399 // Prefer an ordering where the lower the non-zero order number, the higher
2401 if ((LOrder || ROrder) && LOrder != ROrder)
2402 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2405 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2410 // and the following instructions are both ready.
2414 // Then schedule t2 = op first.
2421 // This creates more short live intervals.
2422 unsigned LDist = closestSucc(left);
2423 unsigned RDist = closestSucc(right);
2425 return LDist < RDist;
2427 // How many registers becomes live when the node is scheduled.
2428 unsigned LScratch = calcMaxScratches(left);
2429 unsigned RScratch = calcMaxScratches(right);
2430 if (LScratch != RScratch)
2431 return LScratch > RScratch;
2433 // Comparing latency against a call makes little sense unless the node
2434 // is register pressure-neutral.
2435 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2436 return (left->NodeQueueId > right->NodeQueueId);
2438 // Do not compare latencies when one or both of the nodes are calls.
2439 if (!DisableSchedCycles &&
2440 !(left->isCall || right->isCall)) {
2441 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2446 if (left->getHeight() != right->getHeight())
2447 return left->getHeight() > right->getHeight();
2449 if (left->getDepth() != right->getDepth())
2450 return left->getDepth() < right->getDepth();
2453 assert(left->NodeQueueId && right->NodeQueueId &&
2454 "NodeQueueId cannot be zero");
2455 return (left->NodeQueueId > right->NodeQueueId);
2459 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2460 if (int res = checkSpecialNodes(left, right))
2463 return BURRSort(left, right, SPQ);
2466 // Source order, otherwise bottom up.
2467 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2468 if (int res = checkSpecialNodes(left, right))
2471 unsigned LOrder = SPQ->getNodeOrdering(left);
2472 unsigned ROrder = SPQ->getNodeOrdering(right);
2474 // Prefer an ordering where the lower the non-zero order number, the higher
2476 if ((LOrder || ROrder) && LOrder != ROrder)
2477 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2479 return BURRSort(left, right, SPQ);
2482 // If the time between now and when the instruction will be ready can cover
2483 // the spill code, then avoid adding it to the ready queue. This gives long
2484 // stalls highest priority and allows hoisting across calls. It should also
2485 // speed up processing the available queue.
2486 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2487 static const unsigned ReadyDelay = 3;
2489 if (SPQ->MayReduceRegPressure(SU)) return true;
2491 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2493 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2494 != ScheduleHazardRecognizer::NoHazard)
2500 // Return true if right should be scheduled with higher priority than left.
2501 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2502 if (int res = checkSpecialNodes(left, right))
2505 if (left->isCall || right->isCall)
2506 // No way to compute latency of calls.
2507 return BURRSort(left, right, SPQ);
2509 bool LHigh = SPQ->HighRegPressure(left);
2510 bool RHigh = SPQ->HighRegPressure(right);
2511 // Avoid causing spills. If register pressure is high, schedule for
2512 // register pressure reduction.
2513 if (LHigh && !RHigh) {
2514 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2515 << right->NodeNum << ")\n");
2518 else if (!LHigh && RHigh) {
2519 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2520 << left->NodeNum << ")\n");
2523 if (!LHigh && !RHigh) {
2524 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2528 return BURRSort(left, right, SPQ);
2531 // Schedule as many instructions in each cycle as possible. So don't make an
2532 // instruction available unless it is ready in the current cycle.
2533 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2534 if (SU->getHeight() > CurCycle) return false;
2536 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2537 != ScheduleHazardRecognizer::NoHazard)
2543 static bool canEnableCoalescing(SUnit *SU) {
2544 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2545 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2546 // CopyToReg should be close to its uses to facilitate coalescing and
2550 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2551 Opc == TargetOpcode::SUBREG_TO_REG ||
2552 Opc == TargetOpcode::INSERT_SUBREG)
2553 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2554 // close to their uses to facilitate coalescing.
2557 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2558 // If SU does not have a register def, schedule it close to its uses
2559 // because it does not lengthen any live ranges.
2565 // list-ilp is currently an experimental scheduler that allows various
2566 // heuristics to be enabled prior to the normal register reduction logic.
2567 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2568 if (int res = checkSpecialNodes(left, right))
2571 if (left->isCall || right->isCall)
2572 // No way to compute latency of calls.
2573 return BURRSort(left, right, SPQ);
2575 unsigned LLiveUses = 0, RLiveUses = 0;
2576 int LPDiff = 0, RPDiff = 0;
2577 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2578 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2579 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2581 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2582 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2583 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
2584 return LPDiff > RPDiff;
2587 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
2588 bool LReduce = canEnableCoalescing(left);
2589 bool RReduce = canEnableCoalescing(right);
2590 if (LReduce && !RReduce) return false;
2591 if (RReduce && !LReduce) return true;
2594 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2595 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2596 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
2597 return LLiveUses < RLiveUses;
2600 if (!DisableSchedStalls) {
2601 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2602 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2603 if (LStall != RStall)
2604 return left->getHeight() > right->getHeight();
2607 if (!DisableSchedCriticalPath) {
2608 int spread = (int)left->getDepth() - (int)right->getDepth();
2609 if (std::abs(spread) > MaxReorderWindow) {
2610 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2611 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2612 << right->getDepth() << "\n");
2613 return left->getDepth() < right->getDepth();
2617 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
2618 int spread = (int)left->getHeight() - (int)right->getHeight();
2619 if (std::abs(spread) > MaxReorderWindow)
2620 return left->getHeight() > right->getHeight();
2623 return BURRSort(left, right, SPQ);
2626 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2628 // Add pseudo dependency edges for two-address nodes.
2629 if (!Disable2AddrHack)
2630 AddPseudoTwoAddrDeps();
2631 // Reroute edges to nodes with multiple uses.
2632 if (!TracksRegPressure && !SrcOrder)
2633 PrescheduleNodesWithMultipleUses();
2634 // Calculate node priorities.
2635 CalculateSethiUllmanNumbers();
2637 // For single block loops, mark nodes that look like canonical IV increments.
2638 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
2639 for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
2640 initVRegCycle(&sunits[i]);
2645 //===----------------------------------------------------------------------===//
2646 // Preschedule for Register Pressure
2647 //===----------------------------------------------------------------------===//
2649 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2650 if (SU->isTwoAddress) {
2651 unsigned Opc = SU->getNode()->getMachineOpcode();
2652 const MCInstrDesc &MCID = TII->get(Opc);
2653 unsigned NumRes = MCID.getNumDefs();
2654 unsigned NumOps = MCID.getNumOperands() - NumRes;
2655 for (unsigned i = 0; i != NumOps; ++i) {
2656 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
2657 SDNode *DU = SU->getNode()->getOperand(i).getNode();
2658 if (DU->getNodeId() != -1 &&
2659 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2667 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2668 /// successor's explicit physregs whose definition can reach DepSU.
2669 /// i.e. DepSU should not be scheduled above SU.
2670 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2671 ScheduleDAGRRList *scheduleDAG,
2672 const TargetInstrInfo *TII,
2673 const TargetRegisterInfo *TRI) {
2674 const uint16_t *ImpDefs
2675 = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
2676 const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2677 if(!ImpDefs && !RegMask)
2680 for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
2682 SUnit *SuccSU = SI->getSUnit();
2683 for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
2684 PE = SuccSU->Preds.end(); PI != PE; ++PI) {
2685 if (!PI->isAssignedRegDep())
2688 if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()) &&
2689 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2693 for (const uint16_t *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
2694 // Return true if SU clobbers this physical register use and the
2695 // definition of the register reaches from DepSU. IsReachable queries
2696 // a topological forward sort of the DAG (following the successors).
2697 if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
2698 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2705 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2706 /// physical register defs.
2707 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2708 const TargetInstrInfo *TII,
2709 const TargetRegisterInfo *TRI) {
2710 SDNode *N = SuccSU->getNode();
2711 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2712 const uint16_t *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2713 assert(ImpDefs && "Caller should check hasPhysRegDefs");
2714 for (const SDNode *SUNode = SU->getNode(); SUNode;
2715 SUNode = SUNode->getGluedNode()) {
2716 if (!SUNode->isMachineOpcode())
2718 const uint16_t *SUImpDefs =
2719 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2720 const uint32_t *SURegMask = getNodeRegMask(SUNode);
2721 if (!SUImpDefs && !SURegMask)
2723 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2724 EVT VT = N->getValueType(i);
2725 if (VT == MVT::Glue || VT == MVT::Other)
2727 if (!N->hasAnyUseOfValue(i))
2729 unsigned Reg = ImpDefs[i - NumDefs];
2730 if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2734 for (;*SUImpDefs; ++SUImpDefs) {
2735 unsigned SUReg = *SUImpDefs;
2736 if (TRI->regsOverlap(Reg, SUReg))
2744 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2745 /// are not handled well by the general register pressure reduction
2746 /// heuristics. When presented with code like this:
2755 /// the heuristics tend to push the store up, but since the
2756 /// operand of the store has another use (U), this would increase
2757 /// the length of that other use (the U->N edge).
2759 /// This function transforms code like the above to route U's
2760 /// dependence through the store when possible, like this:
2771 /// This results in the store being scheduled immediately
2772 /// after N, which shortens the U->N live range, reducing
2773 /// register pressure.
2775 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2776 // Visit all the nodes in topological order, working top-down.
2777 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2778 SUnit *SU = &(*SUnits)[i];
2779 // For now, only look at nodes with no data successors, such as stores.
2780 // These are especially important, due to the heuristics in
2781 // getNodePriority for nodes with no data successors.
2782 if (SU->NumSuccs != 0)
2784 // For now, only look at nodes with exactly one data predecessor.
2785 if (SU->NumPreds != 1)
2787 // Avoid prescheduling copies to virtual registers, which don't behave
2788 // like other nodes from the perspective of scheduling heuristics.
2789 if (SDNode *N = SU->getNode())
2790 if (N->getOpcode() == ISD::CopyToReg &&
2791 TargetRegisterInfo::isVirtualRegister
2792 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2795 // Locate the single data predecessor.
2797 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2798 EE = SU->Preds.end(); II != EE; ++II)
2799 if (!II->isCtrl()) {
2800 PredSU = II->getSUnit();
2805 // Don't rewrite edges that carry physregs, because that requires additional
2806 // support infrastructure.
2807 if (PredSU->hasPhysRegDefs)
2809 // Short-circuit the case where SU is PredSU's only data successor.
2810 if (PredSU->NumSuccs == 1)
2812 // Avoid prescheduling to copies from virtual registers, which don't behave
2813 // like other nodes from the perspective of scheduling heuristics.
2814 if (SDNode *N = SU->getNode())
2815 if (N->getOpcode() == ISD::CopyFromReg &&
2816 TargetRegisterInfo::isVirtualRegister
2817 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2820 // Perform checks on the successors of PredSU.
2821 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2822 EE = PredSU->Succs.end(); II != EE; ++II) {
2823 SUnit *PredSuccSU = II->getSUnit();
2824 if (PredSuccSU == SU) continue;
2825 // If PredSU has another successor with no data successors, for
2826 // now don't attempt to choose either over the other.
2827 if (PredSuccSU->NumSuccs == 0)
2828 goto outer_loop_continue;
2829 // Don't break physical register dependencies.
2830 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2831 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2832 goto outer_loop_continue;
2833 // Don't introduce graph cycles.
2834 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2835 goto outer_loop_continue;
2838 // Ok, the transformation is safe and the heuristics suggest it is
2839 // profitable. Update the graph.
2840 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2841 << " next to PredSU #" << PredSU->NodeNum
2842 << " to guide scheduling in the presence of multiple uses\n");
2843 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2844 SDep Edge = PredSU->Succs[i];
2845 assert(!Edge.isAssignedRegDep());
2846 SUnit *SuccSU = Edge.getSUnit();
2848 Edge.setSUnit(PredSU);
2849 scheduleDAG->RemovePred(SuccSU, Edge);
2850 scheduleDAG->AddPred(SU, Edge);
2852 scheduleDAG->AddPred(SuccSU, Edge);
2856 outer_loop_continue:;
2860 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2861 /// it as a def&use operand. Add a pseudo control edge from it to the other
2862 /// node (if it won't create a cycle) so the two-address one will be scheduled
2863 /// first (lower in the schedule). If both nodes are two-address, favor the
2864 /// one that has a CopyToReg use (more likely to be a loop induction update).
2865 /// If both are two-address, but one is commutable while the other is not
2866 /// commutable, favor the one that's not commutable.
2867 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2868 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2869 SUnit *SU = &(*SUnits)[i];
2870 if (!SU->isTwoAddress)
2873 SDNode *Node = SU->getNode();
2874 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
2877 bool isLiveOut = hasOnlyLiveOutUses(SU);
2878 unsigned Opc = Node->getMachineOpcode();
2879 const MCInstrDesc &MCID = TII->get(Opc);
2880 unsigned NumRes = MCID.getNumDefs();
2881 unsigned NumOps = MCID.getNumOperands() - NumRes;
2882 for (unsigned j = 0; j != NumOps; ++j) {
2883 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
2885 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2886 if (DU->getNodeId() == -1)
2888 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2889 if (!DUSU) continue;
2890 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2891 E = DUSU->Succs.end(); I != E; ++I) {
2892 if (I->isCtrl()) continue;
2893 SUnit *SuccSU = I->getSUnit();
2896 // Be conservative. Ignore if nodes aren't at roughly the same
2897 // depth and height.
2898 if (SuccSU->getHeight() < SU->getHeight() &&
2899 (SU->getHeight() - SuccSU->getHeight()) > 1)
2901 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2902 // constrains whatever is using the copy, instead of the copy
2903 // itself. In the case that the copy is coalesced, this
2904 // preserves the intent of the pseudo two-address heurietics.
2905 while (SuccSU->Succs.size() == 1 &&
2906 SuccSU->getNode()->isMachineOpcode() &&
2907 SuccSU->getNode()->getMachineOpcode() ==
2908 TargetOpcode::COPY_TO_REGCLASS)
2909 SuccSU = SuccSU->Succs.front().getSUnit();
2910 // Don't constrain non-instruction nodes.
2911 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2913 // Don't constrain nodes with physical register defs if the
2914 // predecessor can clobber them.
2915 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
2916 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
2919 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2920 // these may be coalesced away. We want them close to their uses.
2921 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2922 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2923 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2924 SuccOpc == TargetOpcode::SUBREG_TO_REG)
2926 if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
2927 (!canClobber(SuccSU, DUSU) ||
2928 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2929 (!SU->isCommutable && SuccSU->isCommutable)) &&
2930 !scheduleDAG->IsReachable(SuccSU, SU)) {
2931 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
2932 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2933 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
2934 /*Reg=*/0, /*isNormalMemory=*/false,
2935 /*isMustAlias=*/false,
2936 /*isArtificial=*/true));
2943 //===----------------------------------------------------------------------===//
2944 // Public Constructor Functions
2945 //===----------------------------------------------------------------------===//
2947 llvm::ScheduleDAGSDNodes *
2948 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2949 CodeGenOpt::Level OptLevel) {
2950 const TargetMachine &TM = IS->TM;
2951 const TargetInstrInfo *TII = TM.getInstrInfo();
2952 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2954 BURegReductionPriorityQueue *PQ =
2955 new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, 0);
2956 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2957 PQ->setScheduleDAG(SD);
2961 llvm::ScheduleDAGSDNodes *
2962 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2963 CodeGenOpt::Level OptLevel) {
2964 const TargetMachine &TM = IS->TM;
2965 const TargetInstrInfo *TII = TM.getInstrInfo();
2966 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2968 SrcRegReductionPriorityQueue *PQ =
2969 new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, 0);
2970 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2971 PQ->setScheduleDAG(SD);
2975 llvm::ScheduleDAGSDNodes *
2976 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2977 CodeGenOpt::Level OptLevel) {
2978 const TargetMachine &TM = IS->TM;
2979 const TargetInstrInfo *TII = TM.getInstrInfo();
2980 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2981 const TargetLowering *TLI = &IS->getTargetLowering();
2983 HybridBURRPriorityQueue *PQ =
2984 new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
2986 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2987 PQ->setScheduleDAG(SD);
2991 llvm::ScheduleDAGSDNodes *
2992 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2993 CodeGenOpt::Level OptLevel) {
2994 const TargetMachine &TM = IS->TM;
2995 const TargetInstrInfo *TII = TM.getInstrInfo();
2996 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2997 const TargetLowering *TLI = &IS->getTargetLowering();
2999 ILPBURRPriorityQueue *PQ =
3000 new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
3001 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
3002 PQ->setScheduleDAG(SD);