1 //===- ResourcePriorityQueue.cpp - A DFA-oriented priority queue -*- C++ -*-==//
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 file implements the ResourcePriorityQueue class, which is a
11 // SchedulingPriorityQueue that prioritizes instructions using DFA state to
12 // reduce the length of the critical path through the basic block
14 // The scheduler is basically a top-down adaptable list scheduler with DFA
15 // resource tracking added to the cost function.
16 // DFA is queried as a state machine to model "packets/bundles" during
17 // schedule. Currently packets/bundles are discarded at the end of
18 // scheduling, affecting only order of instructions.
20 //===----------------------------------------------------------------------===//
22 #include "llvm/CodeGen/ResourcePriorityQueue.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/SelectionDAGNodes.h"
25 #include "llvm/CodeGen/TargetLowering.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetMachine.h"
34 #define DEBUG_TYPE "scheduler"
36 static cl::opt<bool> DisableDFASched("disable-dfa-sched", cl::Hidden,
37 cl::ZeroOrMore, cl::init(false),
38 cl::desc("Disable use of DFA during scheduling"));
40 static cl::opt<int> RegPressureThreshold(
41 "dfa-sched-reg-pressure-threshold", cl::Hidden, cl::ZeroOrMore, cl::init(5),
42 cl::desc("Track reg pressure and switch priority to in-depth"));
44 ResourcePriorityQueue::ResourcePriorityQueue(SelectionDAGISel *IS)
45 : Picker(this), InstrItins(IS->MF->getSubtarget().getInstrItineraryData()) {
46 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
47 TRI = STI.getRegisterInfo();
49 TII = STI.getInstrInfo();
50 ResourcesModel.reset(TII->CreateTargetScheduleState(STI));
51 // This hard requirement could be relaxed, but for now
52 // do not let it proceed.
53 assert(ResourcesModel && "Unimplemented CreateTargetScheduleState.");
55 unsigned NumRC = TRI->getNumRegClasses();
56 RegLimit.resize(NumRC);
57 RegPressure.resize(NumRC);
58 std::fill(RegLimit.begin(), RegLimit.end(), 0);
59 std::fill(RegPressure.begin(), RegPressure.end(), 0);
60 for (const TargetRegisterClass *RC : TRI->regclasses())
61 RegLimit[RC->getID()] = TRI->getRegPressureLimit(RC, *IS->MF);
63 ParallelLiveRanges = 0;
64 HorizontalVerticalBalance = 0;
68 ResourcePriorityQueue::numberRCValPredInSU(SUnit *SU, unsigned RCId) {
69 unsigned NumberDeps = 0;
70 for (SDep &Pred : SU->Preds) {
74 SUnit *PredSU = Pred.getSUnit();
75 const SDNode *ScegN = PredSU->getNode();
80 // If value is passed to CopyToReg, it is probably
82 switch (ScegN->getOpcode()) {
84 case ISD::TokenFactor: break;
85 case ISD::CopyFromReg: NumberDeps++; break;
86 case ISD::CopyToReg: break;
87 case ISD::INLINEASM: break;
89 if (!ScegN->isMachineOpcode())
92 for (unsigned i = 0, e = ScegN->getNumValues(); i != e; ++i) {
93 MVT VT = ScegN->getSimpleValueType(i);
94 if (TLI->isTypeLegal(VT)
95 && (TLI->getRegClassFor(VT)->getID() == RCId)) {
104 unsigned ResourcePriorityQueue::numberRCValSuccInSU(SUnit *SU,
106 unsigned NumberDeps = 0;
107 for (const SDep &Succ : SU->Succs) {
111 SUnit *SuccSU = Succ.getSUnit();
112 const SDNode *ScegN = SuccSU->getNode();
116 // If value is passed to CopyToReg, it is probably
118 switch (ScegN->getOpcode()) {
120 case ISD::TokenFactor: break;
121 case ISD::CopyFromReg: break;
122 case ISD::CopyToReg: NumberDeps++; break;
123 case ISD::INLINEASM: break;
125 if (!ScegN->isMachineOpcode())
128 for (unsigned i = 0, e = ScegN->getNumOperands(); i != e; ++i) {
129 const SDValue &Op = ScegN->getOperand(i);
130 MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
131 if (TLI->isTypeLegal(VT)
132 && (TLI->getRegClassFor(VT)->getID() == RCId)) {
141 static unsigned numberCtrlDepsInSU(SUnit *SU) {
142 unsigned NumberDeps = 0;
143 for (const SDep &Succ : SU->Succs)
150 static unsigned numberCtrlPredInSU(SUnit *SU) {
151 unsigned NumberDeps = 0;
152 for (SDep &Pred : SU->Preds)
160 /// Initialize nodes.
162 void ResourcePriorityQueue::initNodes(std::vector<SUnit> &sunits) {
164 NumNodesSolelyBlocking.resize(SUnits->size(), 0);
166 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
167 SUnit *SU = &(*SUnits)[i];
168 initNumRegDefsLeft(SU);
173 /// This heuristic is used if DFA scheduling is not desired
174 /// for some VLIW platform.
175 bool resource_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
176 // The isScheduleHigh flag allows nodes with wraparound dependencies that
177 // cannot easily be modeled as edges with latencies to be scheduled as
178 // soon as possible in a top-down schedule.
179 if (LHS->isScheduleHigh && !RHS->isScheduleHigh)
182 if (!LHS->isScheduleHigh && RHS->isScheduleHigh)
185 unsigned LHSNum = LHS->NodeNum;
186 unsigned RHSNum = RHS->NodeNum;
188 // The most important heuristic is scheduling the critical path.
189 unsigned LHSLatency = PQ->getLatency(LHSNum);
190 unsigned RHSLatency = PQ->getLatency(RHSNum);
191 if (LHSLatency < RHSLatency) return true;
192 if (LHSLatency > RHSLatency) return false;
194 // After that, if two nodes have identical latencies, look to see if one will
195 // unblock more other nodes than the other.
196 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
197 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
198 if (LHSBlocked < RHSBlocked) return true;
199 if (LHSBlocked > RHSBlocked) return false;
201 // Finally, just to provide a stable ordering, use the node number as a
203 return LHSNum < RHSNum;
207 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
208 /// of SU, return it, otherwise return null.
209 SUnit *ResourcePriorityQueue::getSingleUnscheduledPred(SUnit *SU) {
210 SUnit *OnlyAvailablePred = nullptr;
211 for (const SDep &Pred : SU->Preds) {
212 SUnit &PredSU = *Pred.getSUnit();
213 if (!PredSU.isScheduled) {
214 // We found an available, but not scheduled, predecessor. If it's the
215 // only one we have found, keep track of it... otherwise give up.
216 if (OnlyAvailablePred && OnlyAvailablePred != &PredSU)
218 OnlyAvailablePred = &PredSU;
221 return OnlyAvailablePred;
224 void ResourcePriorityQueue::push(SUnit *SU) {
225 // Look at all of the successors of this node. Count the number of nodes that
226 // this node is the sole unscheduled node for.
227 unsigned NumNodesBlocking = 0;
228 for (const SDep &Succ : SU->Succs)
229 if (getSingleUnscheduledPred(Succ.getSUnit()) == SU)
232 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
236 /// Check if scheduling of this SU is possible
237 /// in the current packet.
238 bool ResourcePriorityQueue::isResourceAvailable(SUnit *SU) {
239 if (!SU || !SU->getNode())
242 // If this is a compound instruction,
243 // it is likely to be a call. Do not delay it.
244 if (SU->getNode()->getGluedNode())
247 // First see if the pipeline could receive this instruction
248 // in the current cycle.
249 if (SU->getNode()->isMachineOpcode())
250 switch (SU->getNode()->getMachineOpcode()) {
252 if (!ResourcesModel->canReserveResources(&TII->get(
253 SU->getNode()->getMachineOpcode())))
255 case TargetOpcode::EXTRACT_SUBREG:
256 case TargetOpcode::INSERT_SUBREG:
257 case TargetOpcode::SUBREG_TO_REG:
258 case TargetOpcode::REG_SEQUENCE:
259 case TargetOpcode::IMPLICIT_DEF:
263 // Now see if there are no other dependencies
264 // to instructions already in the packet.
265 for (unsigned i = 0, e = Packet.size(); i != e; ++i)
266 for (const SDep &Succ : Packet[i]->Succs) {
267 // Since we do not add pseudos to packets, might as well
268 // ignore order deps.
272 if (Succ.getSUnit() == SU)
279 /// Keep track of available resources.
280 void ResourcePriorityQueue::reserveResources(SUnit *SU) {
281 // If this SU does not fit in the packet
283 if (!isResourceAvailable(SU) || SU->getNode()->getGluedNode()) {
284 ResourcesModel->clearResources();
288 if (SU->getNode() && SU->getNode()->isMachineOpcode()) {
289 switch (SU->getNode()->getMachineOpcode()) {
291 ResourcesModel->reserveResources(&TII->get(
292 SU->getNode()->getMachineOpcode()));
294 case TargetOpcode::EXTRACT_SUBREG:
295 case TargetOpcode::INSERT_SUBREG:
296 case TargetOpcode::SUBREG_TO_REG:
297 case TargetOpcode::REG_SEQUENCE:
298 case TargetOpcode::IMPLICIT_DEF:
301 Packet.push_back(SU);
303 // Forcefully end packet for PseudoOps.
305 ResourcesModel->clearResources();
309 // If packet is now full, reset the state so in the next cycle
311 if (Packet.size() >= InstrItins->SchedModel.IssueWidth) {
312 ResourcesModel->clearResources();
317 int ResourcePriorityQueue::rawRegPressureDelta(SUnit *SU, unsigned RCId) {
320 if (!SU || !SU->getNode() || !SU->getNode()->isMachineOpcode())
324 for (unsigned i = 0, e = SU->getNode()->getNumValues(); i != e; ++i) {
325 MVT VT = SU->getNode()->getSimpleValueType(i);
326 if (TLI->isTypeLegal(VT)
327 && TLI->getRegClassFor(VT)
328 && TLI->getRegClassFor(VT)->getID() == RCId)
329 RegBalance += numberRCValSuccInSU(SU, RCId);
332 for (unsigned i = 0, e = SU->getNode()->getNumOperands(); i != e; ++i) {
333 const SDValue &Op = SU->getNode()->getOperand(i);
334 MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
335 if (isa<ConstantSDNode>(Op.getNode()))
338 if (TLI->isTypeLegal(VT) && TLI->getRegClassFor(VT)
339 && TLI->getRegClassFor(VT)->getID() == RCId)
340 RegBalance -= numberRCValPredInSU(SU, RCId);
345 /// Estimates change in reg pressure from this SU.
346 /// It is achieved by trivial tracking of defined
347 /// and used vregs in dependent instructions.
348 /// The RawPressure flag makes this function to ignore
349 /// existing reg file sizes, and report raw def/use
351 int ResourcePriorityQueue::regPressureDelta(SUnit *SU, bool RawPressure) {
354 if (!SU || !SU->getNode() || !SU->getNode()->isMachineOpcode())
358 for (const TargetRegisterClass *RC : TRI->regclasses())
359 RegBalance += rawRegPressureDelta(SU, RC->getID());
362 for (const TargetRegisterClass *RC : TRI->regclasses()) {
363 if ((RegPressure[RC->getID()] +
364 rawRegPressureDelta(SU, RC->getID()) > 0) &&
365 (RegPressure[RC->getID()] +
366 rawRegPressureDelta(SU, RC->getID()) >= RegLimit[RC->getID()]))
367 RegBalance += rawRegPressureDelta(SU, RC->getID());
374 // Constants used to denote relative importance of
375 // heuristic components for cost computation.
376 static const unsigned PriorityOne = 200;
377 static const unsigned PriorityTwo = 50;
378 static const unsigned PriorityThree = 15;
379 static const unsigned PriorityFour = 5;
380 static const unsigned ScaleOne = 20;
381 static const unsigned ScaleTwo = 10;
382 static const unsigned ScaleThree = 5;
383 static const unsigned FactorOne = 2;
385 /// Returns single number reflecting benefit of scheduling SU
386 /// in the current cycle.
387 int ResourcePriorityQueue::SUSchedulingCost(SUnit *SU) {
388 // Initial trivial priority.
391 // Do not waste time on a node that is already scheduled.
395 // Forced priority is high.
396 if (SU->isScheduleHigh)
397 ResCount += PriorityOne;
399 // Adaptable scheduling
400 // A small, but very parallel
401 // region, where reg pressure is an issue.
402 if (HorizontalVerticalBalance > RegPressureThreshold) {
403 // Critical path first
404 ResCount += (SU->getHeight() * ScaleTwo);
405 // If resources are available for it, multiply the
406 // chance of scheduling.
407 if (isResourceAvailable(SU))
408 ResCount <<= FactorOne;
410 // Consider change to reg pressure from scheduling
412 ResCount -= (regPressureDelta(SU,true) * ScaleOne);
414 // Default heuristic, greeady and
415 // critical path driven.
417 // Critical path first.
418 ResCount += (SU->getHeight() * ScaleTwo);
419 // Now see how many instructions is blocked by this SU.
420 ResCount += (NumNodesSolelyBlocking[SU->NodeNum] * ScaleTwo);
421 // If resources are available for it, multiply the
422 // chance of scheduling.
423 if (isResourceAvailable(SU))
424 ResCount <<= FactorOne;
426 ResCount -= (regPressureDelta(SU) * ScaleTwo);
429 // These are platform-specific things.
430 // Will need to go into the back end
431 // and accessed from here via a hook.
432 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
433 if (N->isMachineOpcode()) {
434 const MCInstrDesc &TID = TII->get(N->getMachineOpcode());
436 ResCount += (PriorityTwo + (ScaleThree*N->getNumValues()));
439 switch (N->getOpcode()) {
441 case ISD::TokenFactor:
442 case ISD::CopyFromReg:
444 ResCount += PriorityFour;
448 ResCount += PriorityThree;
456 /// Main resource tracking point.
457 void ResourcePriorityQueue::scheduledNode(SUnit *SU) {
458 // Use NULL entry as an event marker to reset
461 ResourcesModel->clearResources();
466 const SDNode *ScegN = SU->getNode();
467 // Update reg pressure tracking.
468 // First update current node.
469 if (ScegN->isMachineOpcode()) {
470 // Estimate generated regs.
471 for (unsigned i = 0, e = ScegN->getNumValues(); i != e; ++i) {
472 MVT VT = ScegN->getSimpleValueType(i);
474 if (TLI->isTypeLegal(VT)) {
475 const TargetRegisterClass *RC = TLI->getRegClassFor(VT);
477 RegPressure[RC->getID()] += numberRCValSuccInSU(SU, RC->getID());
480 // Estimate killed regs.
481 for (unsigned i = 0, e = ScegN->getNumOperands(); i != e; ++i) {
482 const SDValue &Op = ScegN->getOperand(i);
483 MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
485 if (TLI->isTypeLegal(VT)) {
486 const TargetRegisterClass *RC = TLI->getRegClassFor(VT);
488 if (RegPressure[RC->getID()] >
489 (numberRCValPredInSU(SU, RC->getID())))
490 RegPressure[RC->getID()] -= numberRCValPredInSU(SU, RC->getID());
491 else RegPressure[RC->getID()] = 0;
495 for (SDep &Pred : SU->Preds) {
496 if (Pred.isCtrl() || (Pred.getSUnit()->NumRegDefsLeft == 0))
498 --Pred.getSUnit()->NumRegDefsLeft;
502 // Reserve resources for this SU.
503 reserveResources(SU);
505 // Adjust number of parallel live ranges.
506 // Heuristic is simple - node with no data successors reduces
507 // number of live ranges. All others, increase it.
508 unsigned NumberNonControlDeps = 0;
510 for (const SDep &Succ : SU->Succs) {
511 adjustPriorityOfUnscheduledPreds(Succ.getSUnit());
513 NumberNonControlDeps++;
516 if (!NumberNonControlDeps) {
517 if (ParallelLiveRanges >= SU->NumPreds)
518 ParallelLiveRanges -= SU->NumPreds;
520 ParallelLiveRanges = 0;
524 ParallelLiveRanges += SU->NumRegDefsLeft;
526 // Track parallel live chains.
527 HorizontalVerticalBalance += (SU->Succs.size() - numberCtrlDepsInSU(SU));
528 HorizontalVerticalBalance -= (SU->Preds.size() - numberCtrlPredInSU(SU));
531 void ResourcePriorityQueue::initNumRegDefsLeft(SUnit *SU) {
532 unsigned NodeNumDefs = 0;
533 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
534 if (N->isMachineOpcode()) {
535 const MCInstrDesc &TID = TII->get(N->getMachineOpcode());
536 // No register need be allocated for this.
537 if (N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
541 NodeNumDefs = std::min(N->getNumValues(), TID.getNumDefs());
544 switch(N->getOpcode()) {
546 case ISD::CopyFromReg:
554 SU->NumRegDefsLeft = NodeNumDefs;
557 /// adjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
558 /// scheduled. If SU is not itself available, then there is at least one
559 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
560 /// unscheduled predecessor, we want to increase its priority: it getting
561 /// scheduled will make this node available, so it is better than some other
562 /// node of the same priority that will not make a node available.
563 void ResourcePriorityQueue::adjustPriorityOfUnscheduledPreds(SUnit *SU) {
564 if (SU->isAvailable) return; // All preds scheduled.
566 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
567 if (!OnlyAvailablePred || !OnlyAvailablePred->isAvailable)
570 // Okay, we found a single predecessor that is available, but not scheduled.
571 // Since it is available, it must be in the priority queue. First remove it.
572 remove(OnlyAvailablePred);
574 // Reinsert the node into the priority queue, which recomputes its
575 // NumNodesSolelyBlocking value.
576 push(OnlyAvailablePred);
580 /// Main access point - returns next instructions
581 /// to be placed in scheduling sequence.
582 SUnit *ResourcePriorityQueue::pop() {
586 std::vector<SUnit *>::iterator Best = Queue.begin();
587 if (!DisableDFASched) {
588 int BestCost = SUSchedulingCost(*Best);
589 for (auto I = std::next(Queue.begin()), E = Queue.end(); I != E; ++I) {
591 if (SUSchedulingCost(*I) > BestCost) {
592 BestCost = SUSchedulingCost(*I);
597 // Use default TD scheduling mechanism.
599 for (auto I = std::next(Queue.begin()), E = Queue.end(); I != E; ++I)
600 if (Picker(*Best, *I))
605 if (Best != std::prev(Queue.end()))
606 std::swap(*Best, Queue.back());
614 void ResourcePriorityQueue::remove(SUnit *SU) {
615 assert(!Queue.empty() && "Queue is empty!");
616 std::vector<SUnit *>::iterator I = find(Queue, SU);
617 if (I != std::prev(Queue.end()))
618 std::swap(*I, Queue.back());