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 EVT VT = RegDefPos.GetValue();
272 // Special handling for untyped values. These values can only come from
273 // the expansion of custom DAG-to-DAG patterns.
274 if (VT == MVT::Untyped) {
275 const SDNode *Node = RegDefPos.GetNode();
276 unsigned Opcode = Node->getMachineOpcode();
278 if (Opcode == TargetOpcode::REG_SEQUENCE) {
279 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
280 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
281 RegClass = RC->getID();
286 unsigned Idx = RegDefPos.GetIdx();
287 const MCInstrDesc Desc = TII->get(Opcode);
288 const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI);
289 RegClass = RC->getID();
290 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
291 // better way to determine it.
294 RegClass = TLI->getRepRegClassFor(VT)->getID();
295 Cost = TLI->getRepRegClassCostFor(VT);
299 /// Schedule - Schedule the DAG using list scheduling.
300 void ScheduleDAGRRList::Schedule() {
302 << "********** List Scheduling BB#" << BB->getNumber()
303 << " '" << BB->getName() << "' **********\n");
307 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
309 // Allocate slots for each physical register, plus one for a special register
310 // to track the virtual resource of a calling sequence.
311 LiveRegDefs.resize(TRI->getNumRegs() + 1, NULL);
312 LiveRegGens.resize(TRI->getNumRegs() + 1, NULL);
313 CallSeqEndForStart.clear();
315 // Build the scheduling graph.
316 BuildSchedGraph(NULL);
318 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
319 SUnits[su].dumpAll(this));
320 Topo.InitDAGTopologicalSorting();
322 AvailableQueue->initNodes(SUnits);
326 // Execute the actual scheduling loop.
327 ListScheduleBottomUp();
329 AvailableQueue->releaseState();
332 dbgs() << "*** Final schedule ***\n";
338 //===----------------------------------------------------------------------===//
339 // Bottom-Up Scheduling
340 //===----------------------------------------------------------------------===//
342 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
343 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
344 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
345 SUnit *PredSU = PredEdge->getSUnit();
348 if (PredSU->NumSuccsLeft == 0) {
349 dbgs() << "*** Scheduling failed! ***\n";
351 dbgs() << " has been released too many times!\n";
355 --PredSU->NumSuccsLeft;
357 if (!forceUnitLatencies()) {
358 // Updating predecessor's height. This is now the cycle when the
359 // predecessor can be scheduled without causing a pipeline stall.
360 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
363 // If all the node's successors are scheduled, this node is ready
364 // to be scheduled. Ignore the special EntrySU node.
365 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
366 PredSU->isAvailable = true;
368 unsigned Height = PredSU->getHeight();
369 if (Height < MinAvailableCycle)
370 MinAvailableCycle = Height;
372 if (isReady(PredSU)) {
373 AvailableQueue->push(PredSU);
375 // CapturePred and others may have left the node in the pending queue, avoid
377 else if (!PredSU->isPending) {
378 PredSU->isPending = true;
379 PendingQueue.push_back(PredSU);
384 /// IsChainDependent - Test if Outer is reachable from Inner through
385 /// chain dependencies.
386 static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
388 const TargetInstrInfo *TII) {
393 // For a TokenFactor, examine each operand. There may be multiple ways
394 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
395 // most nesting in order to ensure that we find the corresponding match.
396 if (N->getOpcode() == ISD::TokenFactor) {
397 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
398 if (IsChainDependent(N->getOperand(i).getNode(), Inner, NestLevel, TII))
402 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
403 if (N->isMachineOpcode()) {
404 if (N->getMachineOpcode() ==
405 (unsigned)TII->getCallFrameDestroyOpcode()) {
407 } else if (N->getMachineOpcode() ==
408 (unsigned)TII->getCallFrameSetupOpcode()) {
414 // Otherwise, find the chain and continue climbing.
415 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
416 if (N->getOperand(i).getValueType() == MVT::Other) {
417 N = N->getOperand(i).getNode();
418 goto found_chain_operand;
421 found_chain_operand:;
422 if (N->getOpcode() == ISD::EntryToken)
427 /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
428 /// the corresponding (lowered) CALLSEQ_BEGIN node.
430 /// NestLevel and MaxNested are used in recursion to indcate the current level
431 /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
432 /// level seen so far.
434 /// TODO: It would be better to give CALLSEQ_END an explicit operand to point
435 /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
437 FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
438 const TargetInstrInfo *TII) {
440 // For a TokenFactor, examine each operand. There may be multiple ways
441 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
442 // most nesting in order to ensure that we find the corresponding match.
443 if (N->getOpcode() == ISD::TokenFactor) {
445 unsigned BestMaxNest = MaxNest;
446 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
447 unsigned MyNestLevel = NestLevel;
448 unsigned MyMaxNest = MaxNest;
449 if (SDNode *New = FindCallSeqStart(N->getOperand(i).getNode(),
450 MyNestLevel, MyMaxNest, TII))
451 if (!Best || (MyMaxNest > BestMaxNest)) {
453 BestMaxNest = MyMaxNest;
457 MaxNest = BestMaxNest;
460 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
461 if (N->isMachineOpcode()) {
462 if (N->getMachineOpcode() ==
463 (unsigned)TII->getCallFrameDestroyOpcode()) {
465 MaxNest = std::max(MaxNest, NestLevel);
466 } else if (N->getMachineOpcode() ==
467 (unsigned)TII->getCallFrameSetupOpcode()) {
468 assert(NestLevel != 0);
474 // Otherwise, find the chain and continue climbing.
475 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
476 if (N->getOperand(i).getValueType() == MVT::Other) {
477 N = N->getOperand(i).getNode();
478 goto found_chain_operand;
481 found_chain_operand:;
482 if (N->getOpcode() == ISD::EntryToken)
487 /// Call ReleasePred for each predecessor, then update register live def/gen.
488 /// Always update LiveRegDefs for a register dependence even if the current SU
489 /// also defines the register. This effectively create one large live range
490 /// across a sequence of two-address node. This is important because the
491 /// entire chain must be scheduled together. Example:
494 /// flags = (2) addc flags
495 /// flags = (1) addc flags
499 /// LiveRegDefs[flags] = 3
500 /// LiveRegGens[flags] = 1
502 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
503 /// interference on flags.
504 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
505 // Bottom up: release predecessors
506 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
508 ReleasePred(SU, &*I);
509 if (I->isAssignedRegDep()) {
510 // This is a physical register dependency and it's impossible or
511 // expensive to copy the register. Make sure nothing that can
512 // clobber the register is scheduled between the predecessor and
514 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
515 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
516 "interference on register dependence");
517 LiveRegDefs[I->getReg()] = I->getSUnit();
518 if (!LiveRegGens[I->getReg()]) {
520 LiveRegGens[I->getReg()] = SU;
525 // If we're scheduling a lowered CALLSEQ_END, find the corresponding
526 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
527 // these nodes, to prevent other calls from being interscheduled with them.
528 unsigned CallResource = TRI->getNumRegs();
529 if (!LiveRegDefs[CallResource])
530 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
531 if (Node->isMachineOpcode() &&
532 Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
533 unsigned NestLevel = 0;
534 unsigned MaxNest = 0;
535 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
537 SUnit *Def = &SUnits[N->getNodeId()];
538 CallSeqEndForStart[Def] = SU;
541 LiveRegDefs[CallResource] = Def;
542 LiveRegGens[CallResource] = SU;
547 /// Check to see if any of the pending instructions are ready to issue. If
548 /// so, add them to the available queue.
549 void ScheduleDAGRRList::ReleasePending() {
550 if (DisableSchedCycles) {
551 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
555 // If the available queue is empty, it is safe to reset MinAvailableCycle.
556 if (AvailableQueue->empty())
557 MinAvailableCycle = UINT_MAX;
559 // Check to see if any of the pending instructions are ready to issue. If
560 // so, add them to the available queue.
561 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
562 unsigned ReadyCycle = PendingQueue[i]->getHeight();
563 if (ReadyCycle < MinAvailableCycle)
564 MinAvailableCycle = ReadyCycle;
566 if (PendingQueue[i]->isAvailable) {
567 if (!isReady(PendingQueue[i]))
569 AvailableQueue->push(PendingQueue[i]);
571 PendingQueue[i]->isPending = false;
572 PendingQueue[i] = PendingQueue.back();
573 PendingQueue.pop_back();
578 /// Move the scheduler state forward by the specified number of Cycles.
579 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
580 if (NextCycle <= CurCycle)
584 AvailableQueue->setCurCycle(NextCycle);
585 if (!HazardRec->isEnabled()) {
586 // Bypass lots of virtual calls in case of long latency.
587 CurCycle = NextCycle;
590 for (; CurCycle != NextCycle; ++CurCycle) {
591 HazardRec->RecedeCycle();
594 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
595 // available Q to release pending nodes at least once before popping.
599 /// Move the scheduler state forward until the specified node's dependents are
600 /// ready and can be scheduled with no resource conflicts.
601 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
602 if (DisableSchedCycles)
605 // FIXME: Nodes such as CopyFromReg probably should not advance the current
606 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
607 // has predecessors the cycle will be advanced when they are scheduled.
608 // But given the crude nature of modeling latency though such nodes, we
609 // currently need to treat these nodes like real instructions.
610 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
612 unsigned ReadyCycle = SU->getHeight();
614 // Bump CurCycle to account for latency. We assume the latency of other
615 // available instructions may be hidden by the stall (not a full pipe stall).
616 // This updates the hazard recognizer's cycle before reserving resources for
618 AdvanceToCycle(ReadyCycle);
620 // Calls are scheduled in their preceding cycle, so don't conflict with
621 // hazards from instructions after the call. EmitNode will reset the
622 // scoreboard state before emitting the call.
626 // FIXME: For resource conflicts in very long non-pipelined stages, we
627 // should probably skip ahead here to avoid useless scoreboard checks.
630 ScheduleHazardRecognizer::HazardType HT =
631 HazardRec->getHazardType(SU, -Stalls);
633 if (HT == ScheduleHazardRecognizer::NoHazard)
638 AdvanceToCycle(CurCycle + Stalls);
641 /// Record this SUnit in the HazardRecognizer.
642 /// Does not update CurCycle.
643 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
644 if (!HazardRec->isEnabled())
647 // Check for phys reg copy.
651 switch (SU->getNode()->getOpcode()) {
653 assert(SU->getNode()->isMachineOpcode() &&
654 "This target-independent node should not be scheduled.");
656 case ISD::MERGE_VALUES:
657 case ISD::TokenFactor:
659 case ISD::CopyFromReg:
661 // Noops don't affect the scoreboard state. Copies are likely to be
665 // For inline asm, clear the pipeline state.
670 // Calls are scheduled with their preceding instructions. For bottom-up
671 // scheduling, clear the pipeline state before emitting.
675 HazardRec->EmitInstruction(SU);
678 static void resetVRegCycle(SUnit *SU);
680 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
681 /// count of its predecessors. If a predecessor pending count is zero, add it to
682 /// the Available queue.
683 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
684 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
685 DEBUG(SU->dump(this));
688 if (CurCycle < SU->getHeight())
689 DEBUG(dbgs() << " Height [" << SU->getHeight()
690 << "] pipeline stall!\n");
693 // FIXME: Do not modify node height. It may interfere with
694 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
695 // node its ready cycle can aid heuristics, and after scheduling it can
696 // indicate the scheduled cycle.
697 SU->setHeightToAtLeast(CurCycle);
699 // Reserve resources for the scheduled intruction.
702 Sequence.push_back(SU);
704 AvailableQueue->scheduledNode(SU);
706 // If HazardRec is disabled, and each inst counts as one cycle, then
707 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
708 // PendingQueue for schedulers that implement HasReadyFilter.
709 if (!HazardRec->isEnabled() && AvgIPC < 2)
710 AdvanceToCycle(CurCycle + 1);
712 // Update liveness of predecessors before successors to avoid treating a
713 // two-address node as a live range def.
714 ReleasePredecessors(SU);
716 // Release all the implicit physical register defs that are live.
717 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
719 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
720 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
721 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
723 LiveRegDefs[I->getReg()] = NULL;
724 LiveRegGens[I->getReg()] = NULL;
727 // Release the special call resource dependence, if this is the beginning
729 unsigned CallResource = TRI->getNumRegs();
730 if (LiveRegDefs[CallResource] == SU)
731 for (const SDNode *SUNode = SU->getNode(); SUNode;
732 SUNode = SUNode->getGluedNode()) {
733 if (SUNode->isMachineOpcode() &&
734 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
735 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
737 LiveRegDefs[CallResource] = NULL;
738 LiveRegGens[CallResource] = NULL;
744 SU->isScheduled = true;
746 // Conditions under which the scheduler should eagerly advance the cycle:
747 // (1) No available instructions
748 // (2) All pipelines full, so available instructions must have hazards.
750 // If HazardRec is disabled, the cycle was pre-advanced before calling
751 // ReleasePredecessors. In that case, IssueCount should remain 0.
753 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
754 if (HazardRec->isEnabled() || AvgIPC > 1) {
755 if (SU->getNode() && SU->getNode()->isMachineOpcode())
757 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
758 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
759 AdvanceToCycle(CurCycle + 1);
763 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
764 /// unscheduled, incrcease the succ left count of its predecessors. Remove
765 /// them from AvailableQueue if necessary.
766 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
767 SUnit *PredSU = PredEdge->getSUnit();
768 if (PredSU->isAvailable) {
769 PredSU->isAvailable = false;
770 if (!PredSU->isPending)
771 AvailableQueue->remove(PredSU);
774 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
775 ++PredSU->NumSuccsLeft;
778 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
779 /// its predecessor states to reflect the change.
780 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
781 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
782 DEBUG(SU->dump(this));
784 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
787 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
788 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
789 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
790 "Physical register dependency violated?");
792 LiveRegDefs[I->getReg()] = NULL;
793 LiveRegGens[I->getReg()] = NULL;
797 // Reclaim the special call resource dependence, if this is the beginning
799 unsigned CallResource = TRI->getNumRegs();
800 for (const SDNode *SUNode = SU->getNode(); SUNode;
801 SUNode = SUNode->getGluedNode()) {
802 if (SUNode->isMachineOpcode() &&
803 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
805 LiveRegDefs[CallResource] = SU;
806 LiveRegGens[CallResource] = CallSeqEndForStart[SU];
810 // Release the special call resource dependence, if this is the end
812 if (LiveRegGens[CallResource] == SU)
813 for (const SDNode *SUNode = SU->getNode(); SUNode;
814 SUNode = SUNode->getGluedNode()) {
815 if (SUNode->isMachineOpcode() &&
816 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
817 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
819 LiveRegDefs[CallResource] = NULL;
820 LiveRegGens[CallResource] = NULL;
824 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
826 if (I->isAssignedRegDep()) {
827 if (!LiveRegDefs[I->getReg()])
829 // This becomes the nearest def. Note that an earlier def may still be
830 // pending if this is a two-address node.
831 LiveRegDefs[I->getReg()] = SU;
832 if (LiveRegGens[I->getReg()] == NULL ||
833 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
834 LiveRegGens[I->getReg()] = I->getSUnit();
837 if (SU->getHeight() < MinAvailableCycle)
838 MinAvailableCycle = SU->getHeight();
840 SU->setHeightDirty();
841 SU->isScheduled = false;
842 SU->isAvailable = true;
843 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
844 // Don't make available until backtracking is complete.
845 SU->isPending = true;
846 PendingQueue.push_back(SU);
849 AvailableQueue->push(SU);
851 AvailableQueue->unscheduledNode(SU);
854 /// After backtracking, the hazard checker needs to be restored to a state
855 /// corresponding the the current cycle.
856 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
859 unsigned LookAhead = std::min((unsigned)Sequence.size(),
860 HazardRec->getMaxLookAhead());
864 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
865 unsigned HazardCycle = (*I)->getHeight();
866 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
868 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
869 HazardRec->RecedeCycle();
875 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
876 /// BTCycle in order to schedule a specific node.
877 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
878 SUnit *OldSU = Sequence.back();
881 if (SU->isSucc(OldSU))
882 // Don't try to remove SU from AvailableQueue.
883 SU->isAvailable = false;
884 // FIXME: use ready cycle instead of height
885 CurCycle = OldSU->getHeight();
886 UnscheduleNodeBottomUp(OldSU);
887 AvailableQueue->setCurCycle(CurCycle);
890 OldSU = Sequence.back();
893 assert(!SU->isSucc(OldSU) && "Something is wrong!");
895 RestoreHazardCheckerBottomUp();
902 static bool isOperandOf(const SUnit *SU, SDNode *N) {
903 for (const SDNode *SUNode = SU->getNode(); SUNode;
904 SUNode = SUNode->getGluedNode()) {
905 if (SUNode->isOperandOf(N))
911 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
912 /// successors to the newly created node.
913 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
914 SDNode *N = SU->getNode();
918 if (SU->getNode()->getGluedNode())
922 bool TryUnfold = false;
923 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
924 EVT VT = N->getValueType(i);
927 else if (VT == MVT::Other)
930 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
931 const SDValue &Op = N->getOperand(i);
932 EVT VT = Op.getNode()->getValueType(Op.getResNo());
938 SmallVector<SDNode*, 2> NewNodes;
939 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
942 // unfolding an x86 DEC64m operation results in store, dec, load which
943 // can't be handled here so quit
944 if (NewNodes.size() == 3)
947 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
948 assert(NewNodes.size() == 2 && "Expected a load folding node!");
951 SDNode *LoadNode = NewNodes[0];
952 unsigned NumVals = N->getNumValues();
953 unsigned OldNumVals = SU->getNode()->getNumValues();
954 for (unsigned i = 0; i != NumVals; ++i)
955 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
956 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
957 SDValue(LoadNode, 1));
959 // LoadNode may already exist. This can happen when there is another
960 // load from the same location and producing the same type of value
961 // but it has different alignment or volatileness.
962 bool isNewLoad = true;
964 if (LoadNode->getNodeId() != -1) {
965 LoadSU = &SUnits[LoadNode->getNodeId()];
968 LoadSU = CreateNewSUnit(LoadNode);
969 LoadNode->setNodeId(LoadSU->NodeNum);
971 InitNumRegDefsLeft(LoadSU);
972 computeLatency(LoadSU);
975 SUnit *NewSU = CreateNewSUnit(N);
976 assert(N->getNodeId() == -1 && "Node already inserted!");
977 N->setNodeId(NewSU->NodeNum);
979 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
980 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
981 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
982 NewSU->isTwoAddress = true;
986 if (MCID.isCommutable())
987 NewSU->isCommutable = true;
989 InitNumRegDefsLeft(NewSU);
990 computeLatency(NewSU);
992 // Record all the edges to and from the old SU, by category.
993 SmallVector<SDep, 4> ChainPreds;
994 SmallVector<SDep, 4> ChainSuccs;
995 SmallVector<SDep, 4> LoadPreds;
996 SmallVector<SDep, 4> NodePreds;
997 SmallVector<SDep, 4> NodeSuccs;
998 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1001 ChainPreds.push_back(*I);
1002 else if (isOperandOf(I->getSUnit(), LoadNode))
1003 LoadPreds.push_back(*I);
1005 NodePreds.push_back(*I);
1007 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1010 ChainSuccs.push_back(*I);
1012 NodeSuccs.push_back(*I);
1015 // Now assign edges to the newly-created nodes.
1016 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
1017 const SDep &Pred = ChainPreds[i];
1018 RemovePred(SU, Pred);
1020 AddPred(LoadSU, Pred);
1022 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
1023 const SDep &Pred = LoadPreds[i];
1024 RemovePred(SU, Pred);
1026 AddPred(LoadSU, Pred);
1028 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
1029 const SDep &Pred = NodePreds[i];
1030 RemovePred(SU, Pred);
1031 AddPred(NewSU, Pred);
1033 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
1034 SDep D = NodeSuccs[i];
1035 SUnit *SuccDep = D.getSUnit();
1037 RemovePred(SuccDep, D);
1039 AddPred(SuccDep, D);
1040 // Balance register pressure.
1041 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1042 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1043 --NewSU->NumRegDefsLeft;
1045 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
1046 SDep D = ChainSuccs[i];
1047 SUnit *SuccDep = D.getSUnit();
1049 RemovePred(SuccDep, D);
1052 AddPred(SuccDep, D);
1056 // Add a data dependency to reflect that NewSU reads the value defined
1058 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
1061 AvailableQueue->addNode(LoadSU);
1062 AvailableQueue->addNode(NewSU);
1066 if (NewSU->NumSuccsLeft == 0) {
1067 NewSU->isAvailable = true;
1073 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
1074 NewSU = CreateClone(SU);
1076 // New SUnit has the exact same predecessors.
1077 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1079 if (!I->isArtificial())
1082 // Only copy scheduled successors. Cut them from old node's successor
1083 // list and move them over.
1084 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1085 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1087 if (I->isArtificial())
1089 SUnit *SuccSU = I->getSUnit();
1090 if (SuccSU->isScheduled) {
1095 DelDeps.push_back(std::make_pair(SuccSU, D));
1098 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
1099 RemovePred(DelDeps[i].first, DelDeps[i].second);
1101 AvailableQueue->updateNode(SU);
1102 AvailableQueue->addNode(NewSU);
1108 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
1109 /// scheduled successors of the given SUnit to the last copy.
1110 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
1111 const TargetRegisterClass *DestRC,
1112 const TargetRegisterClass *SrcRC,
1113 SmallVector<SUnit*, 2> &Copies) {
1114 SUnit *CopyFromSU = CreateNewSUnit(NULL);
1115 CopyFromSU->CopySrcRC = SrcRC;
1116 CopyFromSU->CopyDstRC = DestRC;
1118 SUnit *CopyToSU = CreateNewSUnit(NULL);
1119 CopyToSU->CopySrcRC = DestRC;
1120 CopyToSU->CopyDstRC = SrcRC;
1122 // Only copy scheduled successors. Cut them from old node's successor
1123 // list and move them over.
1124 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
1125 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1127 if (I->isArtificial())
1129 SUnit *SuccSU = I->getSUnit();
1130 if (SuccSU->isScheduled) {
1132 D.setSUnit(CopyToSU);
1134 DelDeps.push_back(std::make_pair(SuccSU, *I));
1137 // Avoid scheduling the def-side copy before other successors. Otherwise
1138 // we could introduce another physreg interference on the copy and
1139 // continue inserting copies indefinitely.
1140 SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
1141 /*Reg=*/0, /*isNormalMemory=*/false,
1142 /*isMustAlias=*/false, /*isArtificial=*/true);
1146 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
1147 RemovePred(DelDeps[i].first, DelDeps[i].second);
1149 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
1150 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
1152 AvailableQueue->updateNode(SU);
1153 AvailableQueue->addNode(CopyFromSU);
1154 AvailableQueue->addNode(CopyToSU);
1155 Copies.push_back(CopyFromSU);
1156 Copies.push_back(CopyToSU);
1161 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
1162 /// definition of the specified node.
1163 /// FIXME: Move to SelectionDAG?
1164 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
1165 const TargetInstrInfo *TII) {
1166 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1167 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1168 unsigned NumRes = MCID.getNumDefs();
1169 for (const uint16_t *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
1174 return N->getValueType(NumRes);
1177 /// CheckForLiveRegDef - Return true and update live register vector if the
1178 /// specified register def of the specified SUnit clobbers any "live" registers.
1179 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
1180 std::vector<SUnit*> &LiveRegDefs,
1181 SmallSet<unsigned, 4> &RegAdded,
1182 SmallVector<unsigned, 4> &LRegs,
1183 const TargetRegisterInfo *TRI) {
1184 for (const uint16_t *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
1186 // Check if Ref is live.
1187 if (!LiveRegDefs[*AliasI]) continue;
1189 // Allow multiple uses of the same def.
1190 if (LiveRegDefs[*AliasI] == SU) continue;
1192 // Add Reg to the set of interfering live regs.
1193 if (RegAdded.insert(*AliasI)) {
1194 LRegs.push_back(*AliasI);
1199 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1200 /// by RegMask, and add them to LRegs.
1201 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
1202 std::vector<SUnit*> &LiveRegDefs,
1203 SmallSet<unsigned, 4> &RegAdded,
1204 SmallVector<unsigned, 4> &LRegs) {
1205 // Look at all live registers. Skip Reg0 and the special CallResource.
1206 for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
1207 if (!LiveRegDefs[i]) continue;
1208 if (LiveRegDefs[i] == SU) continue;
1209 if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
1210 if (RegAdded.insert(i))
1215 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1216 static const uint32_t *getNodeRegMask(const SDNode *N) {
1217 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1218 if (const RegisterMaskSDNode *Op =
1219 dyn_cast<RegisterMaskSDNode>(N->getOperand(i).getNode()))
1220 return Op->getRegMask();
1224 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1225 /// scheduling of the given node to satisfy live physical register dependencies.
1226 /// If the specific node is the last one that's available to schedule, do
1227 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
1228 bool ScheduleDAGRRList::
1229 DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
1230 if (NumLiveRegs == 0)
1233 SmallSet<unsigned, 4> RegAdded;
1234 // If this node would clobber any "live" register, then it's not ready.
1236 // If SU is the currently live definition of the same register that it uses,
1237 // then we are free to schedule it.
1238 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1240 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
1241 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1242 RegAdded, LRegs, TRI);
1245 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
1246 if (Node->getOpcode() == ISD::INLINEASM) {
1247 // Inline asm can clobber physical defs.
1248 unsigned NumOps = Node->getNumOperands();
1249 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1250 --NumOps; // Ignore the glue operand.
1252 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1254 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
1255 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
1257 ++i; // Skip the ID value.
1258 if (InlineAsm::isRegDefKind(Flags) ||
1259 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1260 InlineAsm::isClobberKind(Flags)) {
1261 // Check for def of register or earlyclobber register.
1262 for (; NumVals; --NumVals, ++i) {
1263 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1264 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1265 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1273 if (!Node->isMachineOpcode())
1275 // If we're in the middle of scheduling a call, don't begin scheduling
1276 // another call. Also, don't allow any physical registers to be live across
1278 if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
1279 // Check the special calling-sequence resource.
1280 unsigned CallResource = TRI->getNumRegs();
1281 if (LiveRegDefs[CallResource]) {
1282 SDNode *Gen = LiveRegGens[CallResource]->getNode();
1283 while (SDNode *Glued = Gen->getGluedNode())
1285 if (!IsChainDependent(Gen, Node, 0, TII) && RegAdded.insert(CallResource))
1286 LRegs.push_back(CallResource);
1289 if (const uint32_t *RegMask = getNodeRegMask(Node))
1290 CheckForLiveRegDefMasked(SU, RegMask, LiveRegDefs, RegAdded, LRegs);
1292 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1293 if (!MCID.ImplicitDefs)
1295 for (const uint16_t *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
1296 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1299 return !LRegs.empty();
1302 /// Return a node that can be scheduled in this cycle. Requirements:
1303 /// (1) Ready: latency has been satisfied
1304 /// (2) No Hazards: resources are available
1305 /// (3) No Interferences: may unschedule to break register interferences.
1306 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1307 SmallVector<SUnit*, 4> Interferences;
1308 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1310 SUnit *CurSU = AvailableQueue->pop();
1312 SmallVector<unsigned, 4> LRegs;
1313 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1315 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1317 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1318 Interferences.push_back(CurSU);
1319 CurSU = AvailableQueue->pop();
1322 // Add the nodes that aren't ready back onto the available list.
1323 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1324 Interferences[i]->isPending = false;
1325 assert(Interferences[i]->isAvailable && "must still be available");
1326 AvailableQueue->push(Interferences[i]);
1331 // All candidates are delayed due to live physical reg dependencies.
1332 // Try backtracking, code duplication, or inserting cross class copies
1334 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1335 SUnit *TrySU = Interferences[i];
1336 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1338 // Try unscheduling up to the point where it's safe to schedule
1341 unsigned LiveCycle = UINT_MAX;
1342 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1343 unsigned Reg = LRegs[j];
1344 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1345 BtSU = LiveRegGens[Reg];
1346 LiveCycle = BtSU->getHeight();
1349 if (!WillCreateCycle(TrySU, BtSU)) {
1350 BacktrackBottomUp(TrySU, BtSU);
1352 // Force the current node to be scheduled before the node that
1353 // requires the physical reg dep.
1354 if (BtSU->isAvailable) {
1355 BtSU->isAvailable = false;
1356 if (!BtSU->isPending)
1357 AvailableQueue->remove(BtSU);
1359 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
1360 /*Reg=*/0, /*isNormalMemory=*/false,
1361 /*isMustAlias=*/false, /*isArtificial=*/true));
1363 // If one or more successors has been unscheduled, then the current
1364 // node is no longer avaialable. Schedule a successor that's now
1365 // available instead.
1366 if (!TrySU->isAvailable) {
1367 CurSU = AvailableQueue->pop();
1371 TrySU->isPending = false;
1372 Interferences.erase(Interferences.begin()+i);
1379 // Can't backtrack. If it's too expensive to copy the value, then try
1380 // duplicate the nodes that produces these "too expensive to copy"
1381 // values to break the dependency. In case even that doesn't work,
1382 // insert cross class copies.
1383 // If it's not too expensive, i.e. cost != -1, issue copies.
1384 SUnit *TrySU = Interferences[0];
1385 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1386 assert(LRegs.size() == 1 && "Can't handle this yet!");
1387 unsigned Reg = LRegs[0];
1388 SUnit *LRDef = LiveRegDefs[Reg];
1389 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1390 const TargetRegisterClass *RC =
1391 TRI->getMinimalPhysRegClass(Reg, VT);
1392 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1394 // If cross copy register class is the same as RC, then it must be possible
1395 // copy the value directly. Do not try duplicate the def.
1396 // If cross copy register class is not the same as RC, then it's possible to
1397 // copy the value but it require cross register class copies and it is
1399 // If cross copy register class is null, then it's not possible to copy
1400 // the value at all.
1403 NewDef = CopyAndMoveSuccessors(LRDef);
1404 if (!DestRC && !NewDef)
1405 report_fatal_error("Can't handle live physical register dependency!");
1408 // Issue copies, these can be expensive cross register class copies.
1409 SmallVector<SUnit*, 2> Copies;
1410 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1411 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1412 << " to SU #" << Copies.front()->NodeNum << "\n");
1413 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1414 /*Reg=*/0, /*isNormalMemory=*/false,
1415 /*isMustAlias=*/false,
1416 /*isArtificial=*/true));
1417 NewDef = Copies.back();
1420 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1421 << " to SU #" << TrySU->NodeNum << "\n");
1422 LiveRegDefs[Reg] = NewDef;
1423 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1424 /*Reg=*/0, /*isNormalMemory=*/false,
1425 /*isMustAlias=*/false,
1426 /*isArtificial=*/true));
1427 TrySU->isAvailable = false;
1431 assert(CurSU && "Unable to resolve live physical register dependencies!");
1433 // Add the nodes that aren't ready back onto the available list.
1434 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1435 Interferences[i]->isPending = false;
1436 // May no longer be available due to backtracking.
1437 if (Interferences[i]->isAvailable) {
1438 AvailableQueue->push(Interferences[i]);
1444 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1446 void ScheduleDAGRRList::ListScheduleBottomUp() {
1447 // Release any predecessors of the special Exit node.
1448 ReleasePredecessors(&ExitSU);
1450 // Add root to Available queue.
1451 if (!SUnits.empty()) {
1452 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1453 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1454 RootSU->isAvailable = true;
1455 AvailableQueue->push(RootSU);
1458 // While Available queue is not empty, grab the node with the highest
1459 // priority. If it is not ready put it back. Schedule the node.
1460 Sequence.reserve(SUnits.size());
1461 while (!AvailableQueue->empty()) {
1462 DEBUG(dbgs() << "\nExamining Available:\n";
1463 AvailableQueue->dump(this));
1465 // Pick the best node to schedule taking all constraints into
1467 SUnit *SU = PickNodeToScheduleBottomUp();
1469 AdvancePastStalls(SU);
1471 ScheduleNodeBottomUp(SU);
1473 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1474 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1475 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1476 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1480 // Reverse the order if it is bottom up.
1481 std::reverse(Sequence.begin(), Sequence.end());
1484 VerifyScheduledSequence(/*isBottomUp=*/true);
1488 //===----------------------------------------------------------------------===//
1489 // RegReductionPriorityQueue Definition
1490 //===----------------------------------------------------------------------===//
1492 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1493 // to reduce register pressure.
1496 class RegReductionPQBase;
1498 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1499 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1504 struct reverse_sort : public queue_sort {
1506 reverse_sort(SF &sf) : SortFunc(sf) {}
1507 reverse_sort(const reverse_sort &RHS) : SortFunc(RHS.SortFunc) {}
1509 bool operator()(SUnit* left, SUnit* right) const {
1510 // reverse left/right rather than simply !SortFunc(left, right)
1511 // to expose different paths in the comparison logic.
1512 return SortFunc(right, left);
1517 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1518 // reduction scheduler.
1519 struct bu_ls_rr_sort : public queue_sort {
1522 HasReadyFilter = false
1525 RegReductionPQBase *SPQ;
1526 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1527 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1529 bool operator()(SUnit* left, SUnit* right) const;
1532 // src_ls_rr_sort - Priority function for source order scheduler.
1533 struct src_ls_rr_sort : public queue_sort {
1536 HasReadyFilter = false
1539 RegReductionPQBase *SPQ;
1540 src_ls_rr_sort(RegReductionPQBase *spq)
1542 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1545 bool operator()(SUnit* left, SUnit* right) const;
1548 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1549 struct hybrid_ls_rr_sort : public queue_sort {
1552 HasReadyFilter = false
1555 RegReductionPQBase *SPQ;
1556 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1558 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1561 bool isReady(SUnit *SU, unsigned CurCycle) const;
1563 bool operator()(SUnit* left, SUnit* right) const;
1566 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1568 struct ilp_ls_rr_sort : public queue_sort {
1571 HasReadyFilter = false
1574 RegReductionPQBase *SPQ;
1575 ilp_ls_rr_sort(RegReductionPQBase *spq)
1577 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1580 bool isReady(SUnit *SU, unsigned CurCycle) const;
1582 bool operator()(SUnit* left, SUnit* right) const;
1585 class RegReductionPQBase : public SchedulingPriorityQueue {
1587 std::vector<SUnit*> Queue;
1588 unsigned CurQueueId;
1589 bool TracksRegPressure;
1591 // SUnits - The SUnits for the current graph.
1592 std::vector<SUnit> *SUnits;
1594 MachineFunction &MF;
1595 const TargetInstrInfo *TII;
1596 const TargetRegisterInfo *TRI;
1597 const TargetLowering *TLI;
1598 ScheduleDAGRRList *scheduleDAG;
1600 // SethiUllmanNumbers - The SethiUllman number for each node.
1601 std::vector<unsigned> SethiUllmanNumbers;
1603 /// RegPressure - Tracking current reg pressure per register class.
1605 std::vector<unsigned> RegPressure;
1607 /// RegLimit - Tracking the number of allocatable registers per register
1609 std::vector<unsigned> RegLimit;
1612 RegReductionPQBase(MachineFunction &mf,
1613 bool hasReadyFilter,
1615 const TargetInstrInfo *tii,
1616 const TargetRegisterInfo *tri,
1617 const TargetLowering *tli)
1618 : SchedulingPriorityQueue(hasReadyFilter),
1619 CurQueueId(0), TracksRegPressure(tracksrp),
1620 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1621 if (TracksRegPressure) {
1622 unsigned NumRC = TRI->getNumRegClasses();
1623 RegLimit.resize(NumRC);
1624 RegPressure.resize(NumRC);
1625 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1626 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1627 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1628 E = TRI->regclass_end(); I != E; ++I)
1629 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
1633 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1634 scheduleDAG = scheduleDag;
1637 ScheduleHazardRecognizer* getHazardRec() {
1638 return scheduleDAG->getHazardRec();
1641 void initNodes(std::vector<SUnit> &sunits);
1643 void addNode(const SUnit *SU);
1645 void updateNode(const SUnit *SU);
1647 void releaseState() {
1649 SethiUllmanNumbers.clear();
1650 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1653 unsigned getNodePriority(const SUnit *SU) const;
1655 unsigned getNodeOrdering(const SUnit *SU) const {
1656 if (!SU->getNode()) return 0;
1658 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1661 bool empty() const { return Queue.empty(); }
1663 void push(SUnit *U) {
1664 assert(!U->NodeQueueId && "Node in the queue already");
1665 U->NodeQueueId = ++CurQueueId;
1669 void remove(SUnit *SU) {
1670 assert(!Queue.empty() && "Queue is empty!");
1671 assert(SU->NodeQueueId != 0 && "Not in queue!");
1672 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1674 if (I != prior(Queue.end()))
1675 std::swap(*I, Queue.back());
1677 SU->NodeQueueId = 0;
1680 bool tracksRegPressure() const { return TracksRegPressure; }
1682 void dumpRegPressure() const;
1684 bool HighRegPressure(const SUnit *SU) const;
1686 bool MayReduceRegPressure(SUnit *SU) const;
1688 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
1690 void scheduledNode(SUnit *SU);
1692 void unscheduledNode(SUnit *SU);
1695 bool canClobber(const SUnit *SU, const SUnit *Op);
1696 void AddPseudoTwoAddrDeps();
1697 void PrescheduleNodesWithMultipleUses();
1698 void CalculateSethiUllmanNumbers();
1702 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1703 std::vector<SUnit *>::iterator Best = Q.begin();
1704 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1705 E = Q.end(); I != E; ++I)
1706 if (Picker(*Best, *I))
1709 if (Best != prior(Q.end()))
1710 std::swap(*Best, Q.back());
1716 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1718 if (DAG->StressSched) {
1719 reverse_sort<SF> RPicker(Picker);
1720 return popFromQueueImpl(Q, RPicker);
1724 return popFromQueueImpl(Q, Picker);
1728 class RegReductionPriorityQueue : public RegReductionPQBase {
1732 RegReductionPriorityQueue(MachineFunction &mf,
1734 const TargetInstrInfo *tii,
1735 const TargetRegisterInfo *tri,
1736 const TargetLowering *tli)
1737 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1740 bool isBottomUp() const { return SF::IsBottomUp; }
1742 bool isReady(SUnit *U) const {
1743 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1747 if (Queue.empty()) return NULL;
1749 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
1754 void dump(ScheduleDAG *DAG) const {
1755 // Emulate pop() without clobbering NodeQueueIds.
1756 std::vector<SUnit*> DumpQueue = Queue;
1757 SF DumpPicker = Picker;
1758 while (!DumpQueue.empty()) {
1759 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
1760 dbgs() << "Height " << SU->getHeight() << ": ";
1766 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1767 BURegReductionPriorityQueue;
1769 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1770 SrcRegReductionPriorityQueue;
1772 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1773 HybridBURRPriorityQueue;
1775 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1776 ILPBURRPriorityQueue;
1777 } // end anonymous namespace
1779 //===----------------------------------------------------------------------===//
1780 // Static Node Priority for Register Pressure Reduction
1781 //===----------------------------------------------------------------------===//
1783 // Check for special nodes that bypass scheduling heuristics.
1784 // Currently this pushes TokenFactor nodes down, but may be used for other
1785 // pseudo-ops as well.
1787 // Return -1 to schedule right above left, 1 for left above right.
1788 // Return 0 if no bias exists.
1789 static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1790 bool LSchedLow = left->isScheduleLow;
1791 bool RSchedLow = right->isScheduleLow;
1792 if (LSchedLow != RSchedLow)
1793 return LSchedLow < RSchedLow ? 1 : -1;
1797 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1798 /// Smaller number is the higher priority.
1800 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1801 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1802 if (SethiUllmanNumber != 0)
1803 return SethiUllmanNumber;
1806 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1808 if (I->isCtrl()) continue; // ignore chain preds
1809 SUnit *PredSU = I->getSUnit();
1810 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1811 if (PredSethiUllman > SethiUllmanNumber) {
1812 SethiUllmanNumber = PredSethiUllman;
1814 } else if (PredSethiUllman == SethiUllmanNumber)
1818 SethiUllmanNumber += Extra;
1820 if (SethiUllmanNumber == 0)
1821 SethiUllmanNumber = 1;
1823 return SethiUllmanNumber;
1826 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1827 /// scheduling units.
1828 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1829 SethiUllmanNumbers.assign(SUnits->size(), 0);
1831 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1832 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1835 void RegReductionPQBase::addNode(const SUnit *SU) {
1836 unsigned SUSize = SethiUllmanNumbers.size();
1837 if (SUnits->size() > SUSize)
1838 SethiUllmanNumbers.resize(SUSize*2, 0);
1839 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1842 void RegReductionPQBase::updateNode(const SUnit *SU) {
1843 SethiUllmanNumbers[SU->NodeNum] = 0;
1844 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1847 // Lower priority means schedule further down. For bottom-up scheduling, lower
1848 // priority SUs are scheduled before higher priority SUs.
1849 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1850 assert(SU->NodeNum < SethiUllmanNumbers.size());
1851 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1852 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1853 // CopyToReg should be close to its uses to facilitate coalescing and
1856 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1857 Opc == TargetOpcode::SUBREG_TO_REG ||
1858 Opc == TargetOpcode::INSERT_SUBREG)
1859 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1860 // close to their uses to facilitate coalescing.
1862 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1863 // If SU does not have a register use, i.e. it doesn't produce a value
1864 // that would be consumed (e.g. store), then it terminates a chain of
1865 // computation. Give it a large SethiUllman number so it will be
1866 // scheduled right before its predecessors that it doesn't lengthen
1867 // their live ranges.
1869 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1870 // If SU does not have a register def, schedule it close to its uses
1871 // because it does not lengthen any live ranges.
1874 return SethiUllmanNumbers[SU->NodeNum];
1876 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1878 // FIXME: This assumes all of the defs are used as call operands.
1879 int NP = (int)Priority - SU->getNode()->getNumValues();
1880 return (NP > 0) ? NP : 0;
1886 //===----------------------------------------------------------------------===//
1887 // Register Pressure Tracking
1888 //===----------------------------------------------------------------------===//
1890 void RegReductionPQBase::dumpRegPressure() const {
1891 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1892 E = TRI->regclass_end(); I != E; ++I) {
1893 const TargetRegisterClass *RC = *I;
1894 unsigned Id = RC->getID();
1895 unsigned RP = RegPressure[Id];
1897 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1902 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1906 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1910 SUnit *PredSU = I->getSUnit();
1911 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1912 // to cover the number of registers defined (they are all live).
1913 if (PredSU->NumRegDefsLeft == 0) {
1916 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1917 RegDefPos.IsValid(); RegDefPos.Advance()) {
1918 unsigned RCId, Cost;
1919 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1921 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1928 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
1929 const SDNode *N = SU->getNode();
1931 if (!N->isMachineOpcode() || !SU->NumSuccs)
1934 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1935 for (unsigned i = 0; i != NumDefs; ++i) {
1936 EVT VT = N->getValueType(i);
1937 if (!N->hasAnyUseOfValue(i))
1939 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1940 if (RegPressure[RCId] >= RegLimit[RCId])
1946 // Compute the register pressure contribution by this instruction by count up
1947 // for uses that are not live and down for defs. Only count register classes
1948 // that are already under high pressure. As a side effect, compute the number of
1949 // uses of registers that are already live.
1951 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1952 // so could probably be factored.
1953 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1956 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1960 SUnit *PredSU = I->getSUnit();
1961 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1962 // to cover the number of registers defined (they are all live).
1963 if (PredSU->NumRegDefsLeft == 0) {
1964 if (PredSU->getNode()->isMachineOpcode())
1968 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1969 RegDefPos.IsValid(); RegDefPos.Advance()) {
1970 EVT VT = RegDefPos.GetValue();
1971 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1972 if (RegPressure[RCId] >= RegLimit[RCId])
1976 const SDNode *N = SU->getNode();
1978 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
1981 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1982 for (unsigned i = 0; i != NumDefs; ++i) {
1983 EVT VT = N->getValueType(i);
1984 if (!N->hasAnyUseOfValue(i))
1986 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1987 if (RegPressure[RCId] >= RegLimit[RCId])
1993 void RegReductionPQBase::scheduledNode(SUnit *SU) {
1994 if (!TracksRegPressure)
2000 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2004 SUnit *PredSU = I->getSUnit();
2005 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2006 // to cover the number of registers defined (they are all live).
2007 if (PredSU->NumRegDefsLeft == 0) {
2010 // FIXME: The ScheduleDAG currently loses information about which of a
2011 // node's values is consumed by each dependence. Consequently, if the node
2012 // defines multiple register classes, we don't know which to pressurize
2013 // here. Instead the following loop consumes the register defs in an
2014 // arbitrary order. At least it handles the common case of clustered loads
2015 // to the same class. For precise liveness, each SDep needs to indicate the
2016 // result number. But that tightly couples the ScheduleDAG with the
2017 // SelectionDAG making updates tricky. A simpler hack would be to attach a
2018 // value type or register class to SDep.
2020 // The most important aspect of register tracking is balancing the increase
2021 // here with the reduction further below. Note that this SU may use multiple
2022 // defs in PredSU. The can't be determined here, but we've already
2023 // compensated by reducing NumRegDefsLeft in PredSU during
2024 // ScheduleDAGSDNodes::AddSchedEdges.
2025 --PredSU->NumRegDefsLeft;
2026 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2027 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2028 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2032 unsigned RCId, Cost;
2033 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
2034 RegPressure[RCId] += Cost;
2039 // We should have this assert, but there may be dead SDNodes that never
2040 // materialize as SUnits, so they don't appear to generate liveness.
2041 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2042 int SkipRegDefs = (int)SU->NumRegDefsLeft;
2043 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2044 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2045 if (SkipRegDefs > 0)
2047 unsigned RCId, Cost;
2048 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
2049 if (RegPressure[RCId] < Cost) {
2050 // Register pressure tracking is imprecise. This can happen. But we try
2051 // hard not to let it happen because it likely results in poor scheduling.
2052 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
2053 RegPressure[RCId] = 0;
2056 RegPressure[RCId] -= Cost;
2062 void RegReductionPQBase::unscheduledNode(SUnit *SU) {
2063 if (!TracksRegPressure)
2066 const SDNode *N = SU->getNode();
2069 if (!N->isMachineOpcode()) {
2070 if (N->getOpcode() != ISD::CopyToReg)
2073 unsigned Opc = N->getMachineOpcode();
2074 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2075 Opc == TargetOpcode::INSERT_SUBREG ||
2076 Opc == TargetOpcode::SUBREG_TO_REG ||
2077 Opc == TargetOpcode::REG_SEQUENCE ||
2078 Opc == TargetOpcode::IMPLICIT_DEF)
2082 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2086 SUnit *PredSU = I->getSUnit();
2087 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2088 // counts data deps.
2089 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
2091 const SDNode *PN = PredSU->getNode();
2092 if (!PN->isMachineOpcode()) {
2093 if (PN->getOpcode() == ISD::CopyFromReg) {
2094 EVT VT = PN->getValueType(0);
2095 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2096 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2100 unsigned POpc = PN->getMachineOpcode();
2101 if (POpc == TargetOpcode::IMPLICIT_DEF)
2103 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2104 POpc == TargetOpcode::INSERT_SUBREG ||
2105 POpc == TargetOpcode::SUBREG_TO_REG) {
2106 EVT VT = PN->getValueType(0);
2107 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2108 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2111 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2112 for (unsigned i = 0; i != NumDefs; ++i) {
2113 EVT VT = PN->getValueType(i);
2114 if (!PN->hasAnyUseOfValue(i))
2116 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2117 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2118 // Register pressure tracking is imprecise. This can happen.
2119 RegPressure[RCId] = 0;
2121 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2125 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2126 // may transfer data dependencies to CopyToReg.
2127 if (SU->NumSuccs && N->isMachineOpcode()) {
2128 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2129 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2130 EVT VT = N->getValueType(i);
2131 if (VT == MVT::Glue || VT == MVT::Other)
2133 if (!N->hasAnyUseOfValue(i))
2135 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2136 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2143 //===----------------------------------------------------------------------===//
2144 // Dynamic Node Priority for Register Pressure Reduction
2145 //===----------------------------------------------------------------------===//
2147 /// closestSucc - Returns the scheduled cycle of the successor which is
2148 /// closest to the current cycle.
2149 static unsigned closestSucc(const SUnit *SU) {
2150 unsigned MaxHeight = 0;
2151 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2153 if (I->isCtrl()) continue; // ignore chain succs
2154 unsigned Height = I->getSUnit()->getHeight();
2155 // If there are bunch of CopyToRegs stacked up, they should be considered
2156 // to be at the same position.
2157 if (I->getSUnit()->getNode() &&
2158 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
2159 Height = closestSucc(I->getSUnit())+1;
2160 if (Height > MaxHeight)
2166 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
2167 /// for scratch registers, i.e. number of data dependencies.
2168 static unsigned calcMaxScratches(const SUnit *SU) {
2169 unsigned Scratches = 0;
2170 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2172 if (I->isCtrl()) continue; // ignore chain preds
2178 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2179 /// CopyFromReg from a virtual register.
2180 static bool hasOnlyLiveInOpers(const SUnit *SU) {
2181 bool RetVal = false;
2182 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2184 if (I->isCtrl()) continue;
2185 const SUnit *PredSU = I->getSUnit();
2186 if (PredSU->getNode() &&
2187 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2189 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2190 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2200 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
2201 /// CopyToReg to a virtual register. This SU def is probably a liveout and
2202 /// it has no other use. It should be scheduled closer to the terminator.
2203 static bool hasOnlyLiveOutUses(const SUnit *SU) {
2204 bool RetVal = false;
2205 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2207 if (I->isCtrl()) continue;
2208 const SUnit *SuccSU = I->getSUnit();
2209 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2211 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2212 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2222 // Set isVRegCycle for a node with only live in opers and live out uses. Also
2223 // set isVRegCycle for its CopyFromReg operands.
2225 // This is only relevant for single-block loops, in which case the VRegCycle
2226 // node is likely an induction variable in which the operand and target virtual
2227 // registers should be coalesced (e.g. pre/post increment values). Setting the
2228 // isVRegCycle flag helps the scheduler prioritize other uses of the same
2229 // CopyFromReg so that this node becomes the virtual register "kill". This
2230 // avoids interference between the values live in and out of the block and
2231 // eliminates a copy inside the loop.
2232 static void initVRegCycle(SUnit *SU) {
2233 if (DisableSchedVRegCycle)
2236 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2239 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2241 SU->isVRegCycle = true;
2243 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2245 if (I->isCtrl()) continue;
2246 I->getSUnit()->isVRegCycle = true;
2250 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2251 // CopyFromReg operands. We should no longer penalize other uses of this VReg.
2252 static void resetVRegCycle(SUnit *SU) {
2253 if (!SU->isVRegCycle)
2256 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2258 if (I->isCtrl()) continue; // ignore chain preds
2259 SUnit *PredSU = I->getSUnit();
2260 if (PredSU->isVRegCycle) {
2261 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2262 "VRegCycle def must be CopyFromReg");
2263 I->getSUnit()->isVRegCycle = 0;
2268 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2269 // means a node that defines the VRegCycle has not been scheduled yet.
2270 static bool hasVRegCycleUse(const SUnit *SU) {
2271 // If this SU also defines the VReg, don't hoist it as a "use".
2272 if (SU->isVRegCycle)
2275 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2277 if (I->isCtrl()) continue; // ignore chain preds
2278 if (I->getSUnit()->isVRegCycle &&
2279 I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2280 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2287 // Check for either a dependence (latency) or resource (hazard) stall.
2289 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2290 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2291 if ((int)SPQ->getCurCycle() < Height) return true;
2292 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2293 != ScheduleHazardRecognizer::NoHazard)
2298 // Return -1 if left has higher priority, 1 if right has higher priority.
2299 // Return 0 if latency-based priority is equivalent.
2300 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2301 RegReductionPQBase *SPQ) {
2302 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2303 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2304 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2305 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2306 int LHeight = (int)left->getHeight() + LPenalty;
2307 int RHeight = (int)right->getHeight() + RPenalty;
2309 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
2310 BUHasStall(left, LHeight, SPQ);
2311 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
2312 BUHasStall(right, RHeight, SPQ);
2314 // If scheduling one of the node will cause a pipeline stall, delay it.
2315 // If scheduling either one of the node will cause a pipeline stall, sort
2316 // them according to their height.
2320 if (LHeight != RHeight)
2321 return LHeight > RHeight ? 1 : -1;
2325 // If either node is scheduling for latency, sort them by height/depth
2327 if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2328 right->SchedulingPref == Sched::ILP)) {
2329 if (DisableSchedCycles) {
2330 if (LHeight != RHeight)
2331 return LHeight > RHeight ? 1 : -1;
2334 // If neither instruction stalls (!LStall && !RStall) then
2335 // its height is already covered so only its depth matters. We also reach
2336 // this if both stall but have the same height.
2337 int LDepth = left->getDepth() - LPenalty;
2338 int RDepth = right->getDepth() - RPenalty;
2339 if (LDepth != RDepth) {
2340 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2341 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2342 << ") depth " << RDepth << "\n");
2343 return LDepth < RDepth ? 1 : -1;
2346 if (left->Latency != right->Latency)
2347 return left->Latency > right->Latency ? 1 : -1;
2352 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2353 // Schedule physical register definitions close to their use. This is
2354 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2355 // long as shortening physreg live ranges is generally good, we can defer
2356 // creating a subtarget hook.
2357 if (!DisableSchedPhysRegJoin) {
2358 bool LHasPhysReg = left->hasPhysRegDefs;
2359 bool RHasPhysReg = right->hasPhysRegDefs;
2360 if (LHasPhysReg != RHasPhysReg) {
2362 const char *PhysRegMsg[] = {" has no physreg", " defines a physreg"};
2364 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2365 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2366 << PhysRegMsg[RHasPhysReg] << "\n");
2367 return LHasPhysReg < RHasPhysReg;
2371 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
2372 unsigned LPriority = SPQ->getNodePriority(left);
2373 unsigned RPriority = SPQ->getNodePriority(right);
2375 // Be really careful about hoisting call operands above previous calls.
2376 // Only allows it if it would reduce register pressure.
2377 if (left->isCall && right->isCallOp) {
2378 unsigned RNumVals = right->getNode()->getNumValues();
2379 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2381 if (right->isCall && left->isCallOp) {
2382 unsigned LNumVals = left->getNode()->getNumValues();
2383 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2386 if (LPriority != RPriority)
2387 return LPriority > RPriority;
2389 // One or both of the nodes are calls and their sethi-ullman numbers are the
2390 // same, then keep source order.
2391 if (left->isCall || right->isCall) {
2392 unsigned LOrder = SPQ->getNodeOrdering(left);
2393 unsigned ROrder = SPQ->getNodeOrdering(right);
2395 // Prefer an ordering where the lower the non-zero order number, the higher
2397 if ((LOrder || ROrder) && LOrder != ROrder)
2398 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2401 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2406 // and the following instructions are both ready.
2410 // Then schedule t2 = op first.
2417 // This creates more short live intervals.
2418 unsigned LDist = closestSucc(left);
2419 unsigned RDist = closestSucc(right);
2421 return LDist < RDist;
2423 // How many registers becomes live when the node is scheduled.
2424 unsigned LScratch = calcMaxScratches(left);
2425 unsigned RScratch = calcMaxScratches(right);
2426 if (LScratch != RScratch)
2427 return LScratch > RScratch;
2429 // Comparing latency against a call makes little sense unless the node
2430 // is register pressure-neutral.
2431 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2432 return (left->NodeQueueId > right->NodeQueueId);
2434 // Do not compare latencies when one or both of the nodes are calls.
2435 if (!DisableSchedCycles &&
2436 !(left->isCall || right->isCall)) {
2437 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2442 if (left->getHeight() != right->getHeight())
2443 return left->getHeight() > right->getHeight();
2445 if (left->getDepth() != right->getDepth())
2446 return left->getDepth() < right->getDepth();
2449 assert(left->NodeQueueId && right->NodeQueueId &&
2450 "NodeQueueId cannot be zero");
2451 return (left->NodeQueueId > right->NodeQueueId);
2455 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2456 if (int res = checkSpecialNodes(left, right))
2459 return BURRSort(left, right, SPQ);
2462 // Source order, otherwise bottom up.
2463 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2464 if (int res = checkSpecialNodes(left, right))
2467 unsigned LOrder = SPQ->getNodeOrdering(left);
2468 unsigned ROrder = SPQ->getNodeOrdering(right);
2470 // Prefer an ordering where the lower the non-zero order number, the higher
2472 if ((LOrder || ROrder) && LOrder != ROrder)
2473 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2475 return BURRSort(left, right, SPQ);
2478 // If the time between now and when the instruction will be ready can cover
2479 // the spill code, then avoid adding it to the ready queue. This gives long
2480 // stalls highest priority and allows hoisting across calls. It should also
2481 // speed up processing the available queue.
2482 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2483 static const unsigned ReadyDelay = 3;
2485 if (SPQ->MayReduceRegPressure(SU)) return true;
2487 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2489 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2490 != ScheduleHazardRecognizer::NoHazard)
2496 // Return true if right should be scheduled with higher priority than left.
2497 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2498 if (int res = checkSpecialNodes(left, right))
2501 if (left->isCall || right->isCall)
2502 // No way to compute latency of calls.
2503 return BURRSort(left, right, SPQ);
2505 bool LHigh = SPQ->HighRegPressure(left);
2506 bool RHigh = SPQ->HighRegPressure(right);
2507 // Avoid causing spills. If register pressure is high, schedule for
2508 // register pressure reduction.
2509 if (LHigh && !RHigh) {
2510 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2511 << right->NodeNum << ")\n");
2514 else if (!LHigh && RHigh) {
2515 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2516 << left->NodeNum << ")\n");
2519 if (!LHigh && !RHigh) {
2520 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2524 return BURRSort(left, right, SPQ);
2527 // Schedule as many instructions in each cycle as possible. So don't make an
2528 // instruction available unless it is ready in the current cycle.
2529 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2530 if (SU->getHeight() > CurCycle) return false;
2532 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2533 != ScheduleHazardRecognizer::NoHazard)
2539 static bool canEnableCoalescing(SUnit *SU) {
2540 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2541 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2542 // CopyToReg should be close to its uses to facilitate coalescing and
2546 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2547 Opc == TargetOpcode::SUBREG_TO_REG ||
2548 Opc == TargetOpcode::INSERT_SUBREG)
2549 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2550 // close to their uses to facilitate coalescing.
2553 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2554 // If SU does not have a register def, schedule it close to its uses
2555 // because it does not lengthen any live ranges.
2561 // list-ilp is currently an experimental scheduler that allows various
2562 // heuristics to be enabled prior to the normal register reduction logic.
2563 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2564 if (int res = checkSpecialNodes(left, right))
2567 if (left->isCall || right->isCall)
2568 // No way to compute latency of calls.
2569 return BURRSort(left, right, SPQ);
2571 unsigned LLiveUses = 0, RLiveUses = 0;
2572 int LPDiff = 0, RPDiff = 0;
2573 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2574 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2575 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2577 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2578 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2579 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
2580 return LPDiff > RPDiff;
2583 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
2584 bool LReduce = canEnableCoalescing(left);
2585 bool RReduce = canEnableCoalescing(right);
2586 if (LReduce && !RReduce) return false;
2587 if (RReduce && !LReduce) return true;
2590 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2591 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2592 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
2593 return LLiveUses < RLiveUses;
2596 if (!DisableSchedStalls) {
2597 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2598 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2599 if (LStall != RStall)
2600 return left->getHeight() > right->getHeight();
2603 if (!DisableSchedCriticalPath) {
2604 int spread = (int)left->getDepth() - (int)right->getDepth();
2605 if (std::abs(spread) > MaxReorderWindow) {
2606 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2607 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2608 << right->getDepth() << "\n");
2609 return left->getDepth() < right->getDepth();
2613 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
2614 int spread = (int)left->getHeight() - (int)right->getHeight();
2615 if (std::abs(spread) > MaxReorderWindow)
2616 return left->getHeight() > right->getHeight();
2619 return BURRSort(left, right, SPQ);
2622 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2624 // Add pseudo dependency edges for two-address nodes.
2625 if (!Disable2AddrHack)
2626 AddPseudoTwoAddrDeps();
2627 // Reroute edges to nodes with multiple uses.
2628 if (!TracksRegPressure)
2629 PrescheduleNodesWithMultipleUses();
2630 // Calculate node priorities.
2631 CalculateSethiUllmanNumbers();
2633 // For single block loops, mark nodes that look like canonical IV increments.
2634 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
2635 for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
2636 initVRegCycle(&sunits[i]);
2641 //===----------------------------------------------------------------------===//
2642 // Preschedule for Register Pressure
2643 //===----------------------------------------------------------------------===//
2645 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2646 if (SU->isTwoAddress) {
2647 unsigned Opc = SU->getNode()->getMachineOpcode();
2648 const MCInstrDesc &MCID = TII->get(Opc);
2649 unsigned NumRes = MCID.getNumDefs();
2650 unsigned NumOps = MCID.getNumOperands() - NumRes;
2651 for (unsigned i = 0; i != NumOps; ++i) {
2652 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
2653 SDNode *DU = SU->getNode()->getOperand(i).getNode();
2654 if (DU->getNodeId() != -1 &&
2655 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2663 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2664 /// successor's explicit physregs whose definition can reach DepSU.
2665 /// i.e. DepSU should not be scheduled above SU.
2666 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2667 ScheduleDAGRRList *scheduleDAG,
2668 const TargetInstrInfo *TII,
2669 const TargetRegisterInfo *TRI) {
2670 const uint16_t *ImpDefs
2671 = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
2672 const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2673 if(!ImpDefs && !RegMask)
2676 for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
2678 SUnit *SuccSU = SI->getSUnit();
2679 for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
2680 PE = SuccSU->Preds.end(); PI != PE; ++PI) {
2681 if (!PI->isAssignedRegDep())
2684 if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()) &&
2685 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2689 for (const uint16_t *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
2690 // Return true if SU clobbers this physical register use and the
2691 // definition of the register reaches from DepSU. IsReachable queries
2692 // a topological forward sort of the DAG (following the successors).
2693 if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
2694 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2701 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2702 /// physical register defs.
2703 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2704 const TargetInstrInfo *TII,
2705 const TargetRegisterInfo *TRI) {
2706 SDNode *N = SuccSU->getNode();
2707 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2708 const uint16_t *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2709 assert(ImpDefs && "Caller should check hasPhysRegDefs");
2710 for (const SDNode *SUNode = SU->getNode(); SUNode;
2711 SUNode = SUNode->getGluedNode()) {
2712 if (!SUNode->isMachineOpcode())
2714 const uint16_t *SUImpDefs =
2715 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2716 const uint32_t *SURegMask = getNodeRegMask(SUNode);
2717 if (!SUImpDefs && !SURegMask)
2719 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2720 EVT VT = N->getValueType(i);
2721 if (VT == MVT::Glue || VT == MVT::Other)
2723 if (!N->hasAnyUseOfValue(i))
2725 unsigned Reg = ImpDefs[i - NumDefs];
2726 if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2730 for (;*SUImpDefs; ++SUImpDefs) {
2731 unsigned SUReg = *SUImpDefs;
2732 if (TRI->regsOverlap(Reg, SUReg))
2740 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2741 /// are not handled well by the general register pressure reduction
2742 /// heuristics. When presented with code like this:
2751 /// the heuristics tend to push the store up, but since the
2752 /// operand of the store has another use (U), this would increase
2753 /// the length of that other use (the U->N edge).
2755 /// This function transforms code like the above to route U's
2756 /// dependence through the store when possible, like this:
2767 /// This results in the store being scheduled immediately
2768 /// after N, which shortens the U->N live range, reducing
2769 /// register pressure.
2771 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2772 // Visit all the nodes in topological order, working top-down.
2773 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2774 SUnit *SU = &(*SUnits)[i];
2775 // For now, only look at nodes with no data successors, such as stores.
2776 // These are especially important, due to the heuristics in
2777 // getNodePriority for nodes with no data successors.
2778 if (SU->NumSuccs != 0)
2780 // For now, only look at nodes with exactly one data predecessor.
2781 if (SU->NumPreds != 1)
2783 // Avoid prescheduling copies to virtual registers, which don't behave
2784 // like other nodes from the perspective of scheduling heuristics.
2785 if (SDNode *N = SU->getNode())
2786 if (N->getOpcode() == ISD::CopyToReg &&
2787 TargetRegisterInfo::isVirtualRegister
2788 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2791 // Locate the single data predecessor.
2793 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2794 EE = SU->Preds.end(); II != EE; ++II)
2795 if (!II->isCtrl()) {
2796 PredSU = II->getSUnit();
2801 // Don't rewrite edges that carry physregs, because that requires additional
2802 // support infrastructure.
2803 if (PredSU->hasPhysRegDefs)
2805 // Short-circuit the case where SU is PredSU's only data successor.
2806 if (PredSU->NumSuccs == 1)
2808 // Avoid prescheduling to copies from virtual registers, which don't behave
2809 // like other nodes from the perspective of scheduling heuristics.
2810 if (SDNode *N = SU->getNode())
2811 if (N->getOpcode() == ISD::CopyFromReg &&
2812 TargetRegisterInfo::isVirtualRegister
2813 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2816 // Perform checks on the successors of PredSU.
2817 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2818 EE = PredSU->Succs.end(); II != EE; ++II) {
2819 SUnit *PredSuccSU = II->getSUnit();
2820 if (PredSuccSU == SU) continue;
2821 // If PredSU has another successor with no data successors, for
2822 // now don't attempt to choose either over the other.
2823 if (PredSuccSU->NumSuccs == 0)
2824 goto outer_loop_continue;
2825 // Don't break physical register dependencies.
2826 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2827 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2828 goto outer_loop_continue;
2829 // Don't introduce graph cycles.
2830 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2831 goto outer_loop_continue;
2834 // Ok, the transformation is safe and the heuristics suggest it is
2835 // profitable. Update the graph.
2836 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2837 << " next to PredSU #" << PredSU->NodeNum
2838 << " to guide scheduling in the presence of multiple uses\n");
2839 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2840 SDep Edge = PredSU->Succs[i];
2841 assert(!Edge.isAssignedRegDep());
2842 SUnit *SuccSU = Edge.getSUnit();
2844 Edge.setSUnit(PredSU);
2845 scheduleDAG->RemovePred(SuccSU, Edge);
2846 scheduleDAG->AddPred(SU, Edge);
2848 scheduleDAG->AddPred(SuccSU, Edge);
2852 outer_loop_continue:;
2856 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2857 /// it as a def&use operand. Add a pseudo control edge from it to the other
2858 /// node (if it won't create a cycle) so the two-address one will be scheduled
2859 /// first (lower in the schedule). If both nodes are two-address, favor the
2860 /// one that has a CopyToReg use (more likely to be a loop induction update).
2861 /// If both are two-address, but one is commutable while the other is not
2862 /// commutable, favor the one that's not commutable.
2863 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2864 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2865 SUnit *SU = &(*SUnits)[i];
2866 if (!SU->isTwoAddress)
2869 SDNode *Node = SU->getNode();
2870 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
2873 bool isLiveOut = hasOnlyLiveOutUses(SU);
2874 unsigned Opc = Node->getMachineOpcode();
2875 const MCInstrDesc &MCID = TII->get(Opc);
2876 unsigned NumRes = MCID.getNumDefs();
2877 unsigned NumOps = MCID.getNumOperands() - NumRes;
2878 for (unsigned j = 0; j != NumOps; ++j) {
2879 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
2881 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2882 if (DU->getNodeId() == -1)
2884 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2885 if (!DUSU) continue;
2886 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2887 E = DUSU->Succs.end(); I != E; ++I) {
2888 if (I->isCtrl()) continue;
2889 SUnit *SuccSU = I->getSUnit();
2892 // Be conservative. Ignore if nodes aren't at roughly the same
2893 // depth and height.
2894 if (SuccSU->getHeight() < SU->getHeight() &&
2895 (SU->getHeight() - SuccSU->getHeight()) > 1)
2897 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2898 // constrains whatever is using the copy, instead of the copy
2899 // itself. In the case that the copy is coalesced, this
2900 // preserves the intent of the pseudo two-address heurietics.
2901 while (SuccSU->Succs.size() == 1 &&
2902 SuccSU->getNode()->isMachineOpcode() &&
2903 SuccSU->getNode()->getMachineOpcode() ==
2904 TargetOpcode::COPY_TO_REGCLASS)
2905 SuccSU = SuccSU->Succs.front().getSUnit();
2906 // Don't constrain non-instruction nodes.
2907 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2909 // Don't constrain nodes with physical register defs if the
2910 // predecessor can clobber them.
2911 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
2912 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
2915 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2916 // these may be coalesced away. We want them close to their uses.
2917 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2918 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2919 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2920 SuccOpc == TargetOpcode::SUBREG_TO_REG)
2922 if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
2923 (!canClobber(SuccSU, DUSU) ||
2924 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2925 (!SU->isCommutable && SuccSU->isCommutable)) &&
2926 !scheduleDAG->IsReachable(SuccSU, SU)) {
2927 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
2928 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2929 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
2930 /*Reg=*/0, /*isNormalMemory=*/false,
2931 /*isMustAlias=*/false,
2932 /*isArtificial=*/true));
2939 //===----------------------------------------------------------------------===//
2940 // Public Constructor Functions
2941 //===----------------------------------------------------------------------===//
2943 llvm::ScheduleDAGSDNodes *
2944 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2945 CodeGenOpt::Level OptLevel) {
2946 const TargetMachine &TM = IS->TM;
2947 const TargetInstrInfo *TII = TM.getInstrInfo();
2948 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2950 BURegReductionPriorityQueue *PQ =
2951 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2952 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2953 PQ->setScheduleDAG(SD);
2957 llvm::ScheduleDAGSDNodes *
2958 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2959 CodeGenOpt::Level OptLevel) {
2960 const TargetMachine &TM = IS->TM;
2961 const TargetInstrInfo *TII = TM.getInstrInfo();
2962 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2964 SrcRegReductionPriorityQueue *PQ =
2965 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2966 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2967 PQ->setScheduleDAG(SD);
2971 llvm::ScheduleDAGSDNodes *
2972 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2973 CodeGenOpt::Level OptLevel) {
2974 const TargetMachine &TM = IS->TM;
2975 const TargetInstrInfo *TII = TM.getInstrInfo();
2976 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2977 const TargetLowering *TLI = &IS->getTargetLowering();
2979 HybridBURRPriorityQueue *PQ =
2980 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2982 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2983 PQ->setScheduleDAG(SD);
2987 llvm::ScheduleDAGSDNodes *
2988 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2989 CodeGenOpt::Level OptLevel) {
2990 const TargetMachine &TM = IS->TM;
2991 const TargetInstrInfo *TII = TM.getInstrInfo();
2992 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2993 const TargetLowering *TLI = &IS->getTargetLowering();
2995 ILPBURRPriorityQueue *PQ =
2996 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2997 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2998 PQ->setScheduleDAG(SD);