1 //===- HexagonMachineScheduler.cpp - MI Scheduler for Hexagon -------------===//
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 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "misched"
17 #include "HexagonMachineScheduler.h"
18 #include "llvm/CodeGen/MachineLoopInfo.h"
19 #include "llvm/IR/Function.h"
23 /// Platform specific modifications to DAG.
24 void VLIWMachineScheduler::postprocessDAG() {
25 SUnit* LastSequentialCall = NULL;
26 // Currently we only catch the situation when compare gets scheduled
27 // before preceding call.
28 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
30 if (SUnits[su].getInstr()->isCall())
31 LastSequentialCall = &(SUnits[su]);
32 // Look for a compare that defines a predicate.
33 else if (SUnits[su].getInstr()->isCompare() && LastSequentialCall)
34 SUnits[su].addPred(SDep(LastSequentialCall, SDep::Barrier));
38 /// Check if scheduling of this SU is possible
39 /// in the current packet.
40 /// It is _not_ precise (statefull), it is more like
41 /// another heuristic. Many corner cases are figured
43 bool VLIWResourceModel::isResourceAvailable(SUnit *SU) {
44 if (!SU || !SU->getInstr())
47 // First see if the pipeline could receive this instruction
48 // in the current cycle.
49 switch (SU->getInstr()->getOpcode()) {
51 if (!ResourcesModel->canReserveResources(SU->getInstr()))
53 case TargetOpcode::EXTRACT_SUBREG:
54 case TargetOpcode::INSERT_SUBREG:
55 case TargetOpcode::SUBREG_TO_REG:
56 case TargetOpcode::REG_SEQUENCE:
57 case TargetOpcode::IMPLICIT_DEF:
58 case TargetOpcode::COPY:
59 case TargetOpcode::INLINEASM:
63 // Now see if there are no other dependencies to instructions already
65 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
66 if (Packet[i]->Succs.size() == 0)
68 for (SUnit::const_succ_iterator I = Packet[i]->Succs.begin(),
69 E = Packet[i]->Succs.end(); I != E; ++I) {
70 // Since we do not add pseudos to packets, might as well
71 // ignore order dependencies.
75 if (I->getSUnit() == SU)
82 /// Keep track of available resources.
83 bool VLIWResourceModel::reserveResources(SUnit *SU) {
84 bool startNewCycle = false;
85 // Artificially reset state.
87 ResourcesModel->clearResources();
92 // If this SU does not fit in the packet
94 if (!isResourceAvailable(SU)) {
95 ResourcesModel->clearResources();
101 switch (SU->getInstr()->getOpcode()) {
103 ResourcesModel->reserveResources(SU->getInstr());
105 case TargetOpcode::EXTRACT_SUBREG:
106 case TargetOpcode::INSERT_SUBREG:
107 case TargetOpcode::SUBREG_TO_REG:
108 case TargetOpcode::REG_SEQUENCE:
109 case TargetOpcode::IMPLICIT_DEF:
110 case TargetOpcode::KILL:
111 case TargetOpcode::PROLOG_LABEL:
112 case TargetOpcode::EH_LABEL:
113 case TargetOpcode::COPY:
114 case TargetOpcode::INLINEASM:
117 Packet.push_back(SU);
120 DEBUG(dbgs() << "Packet[" << TotalPackets << "]:\n");
121 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
122 DEBUG(dbgs() << "\t[" << i << "] SU(");
123 DEBUG(dbgs() << Packet[i]->NodeNum << ")\t");
124 DEBUG(Packet[i]->getInstr()->dump());
128 // If packet is now full, reset the state so in the next cycle
130 if (Packet.size() >= SchedModel->getIssueWidth()) {
131 ResourcesModel->clearResources();
134 startNewCycle = true;
137 return startNewCycle;
140 /// schedule - Called back from MachineScheduler::runOnMachineFunction
141 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
142 /// only includes instructions that have DAG nodes, not scheduling boundaries.
143 void VLIWMachineScheduler::schedule() {
145 << "********** MI Converging Scheduling VLIW BB#" << BB->getNumber()
146 << " " << BB->getName()
147 << " in_func " << BB->getParent()->getFunction()->getName()
148 << " at loop depth " << MLI.getLoopDepth(BB)
151 buildDAGWithRegPressure();
153 // Postprocess the DAG to add platform specific artificial dependencies.
156 SmallVector<SUnit*, 8> TopRoots, BotRoots;
157 findRootsAndBiasEdges(TopRoots, BotRoots);
159 // Initialize the strategy before modifying the DAG.
160 SchedImpl->initialize(this);
162 // To view Height/Depth correctly, they should be accessed at least once.
164 // FIXME: SUnit::dumpAll always recompute depth and height now. The max
165 // depth/height could be computed directly from the roots and leaves.
166 DEBUG(unsigned maxH = 0;
167 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
168 if (SUnits[su].getHeight() > maxH)
169 maxH = SUnits[su].getHeight();
170 dbgs() << "Max Height " << maxH << "\n";);
171 DEBUG(unsigned maxD = 0;
172 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
173 if (SUnits[su].getDepth() > maxD)
174 maxD = SUnits[su].getDepth();
175 dbgs() << "Max Depth " << maxD << "\n";);
176 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
177 SUnits[su].dumpAll(this));
179 initQueues(TopRoots, BotRoots);
181 bool IsTopNode = false;
182 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
183 if (!checkSchedLimit())
186 scheduleMI(SU, IsTopNode);
188 updateQueues(SU, IsTopNode);
190 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
195 void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
196 DAG = static_cast<VLIWMachineScheduler*>(dag);
197 SchedModel = DAG->getSchedModel();
200 Top.init(DAG, SchedModel);
201 Bot.init(DAG, SchedModel);
203 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
204 // are disabled, then these HazardRecs will be disabled.
205 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
206 const TargetMachine &TM = DAG->MF.getTarget();
207 delete Top.HazardRec;
208 delete Bot.HazardRec;
209 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
210 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
212 Top.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
213 Bot.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
215 assert((!llvm::ForceTopDown || !llvm::ForceBottomUp) &&
216 "-misched-topdown incompatible with -misched-bottomup");
219 void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
223 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
225 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
226 unsigned MinLatency = I->getMinLatency();
228 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
230 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
231 SU->TopReadyCycle = PredReadyCycle + MinLatency;
233 Top.releaseNode(SU, SU->TopReadyCycle);
236 void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
240 assert(SU->getInstr() && "Scheduled SUnit must have instr");
242 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
244 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
245 unsigned MinLatency = I->getMinLatency();
247 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
249 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
250 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
252 Bot.releaseNode(SU, SU->BotReadyCycle);
255 /// Does this SU have a hazard within the current instruction group.
257 /// The scheduler supports two modes of hazard recognition. The first is the
258 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
259 /// supports highly complicated in-order reservation tables
260 /// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
262 /// The second is a streamlined mechanism that checks for hazards based on
263 /// simple counters that the scheduler itself maintains. It explicitly checks
264 /// for instruction dispatch limitations, including the number of micro-ops that
265 /// can dispatch per cycle.
267 /// TODO: Also check whether the SU must start a new group.
268 bool ConvergingVLIWScheduler::SchedBoundary::checkHazard(SUnit *SU) {
269 if (HazardRec->isEnabled())
270 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
272 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
273 if (IssueCount + uops > SchedModel->getIssueWidth())
279 void ConvergingVLIWScheduler::SchedBoundary::releaseNode(SUnit *SU,
280 unsigned ReadyCycle) {
281 if (ReadyCycle < MinReadyCycle)
282 MinReadyCycle = ReadyCycle;
284 // Check for interlocks first. For the purpose of other heuristics, an
285 // instruction that cannot issue appears as if it's not in the ReadyQueue.
286 if (ReadyCycle > CurrCycle || checkHazard(SU))
293 /// Move the boundary of scheduled code by one cycle.
294 void ConvergingVLIWScheduler::SchedBoundary::bumpCycle() {
295 unsigned Width = SchedModel->getIssueWidth();
296 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
298 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
299 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
301 if (!HazardRec->isEnabled()) {
302 // Bypass HazardRec virtual calls.
303 CurrCycle = NextCycle;
305 // Bypass getHazardType calls in case of long latency.
306 for (; CurrCycle != NextCycle; ++CurrCycle) {
308 HazardRec->AdvanceCycle();
310 HazardRec->RecedeCycle();
315 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
316 << CurrCycle << '\n');
319 /// Move the boundary of scheduled code by one SUnit.
320 void ConvergingVLIWScheduler::SchedBoundary::bumpNode(SUnit *SU) {
321 bool startNewCycle = false;
323 // Update the reservation table.
324 if (HazardRec->isEnabled()) {
325 if (!isTop() && SU->isCall) {
326 // Calls are scheduled with their preceding instructions. For bottom-up
327 // scheduling, clear the pipeline state before emitting.
330 HazardRec->EmitInstruction(SU);
334 startNewCycle = ResourceModel->reserveResources(SU);
336 // Check the instruction group dispatch limit.
337 // TODO: Check if this SU must end a dispatch group.
338 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
340 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
344 DEBUG(dbgs() << "*** IssueCount " << IssueCount
345 << " at cycle " << CurrCycle << '\n');
348 /// Release pending ready nodes in to the available queue. This makes them
349 /// visible to heuristics.
350 void ConvergingVLIWScheduler::SchedBoundary::releasePending() {
351 // If the available queue is empty, it is safe to reset MinReadyCycle.
352 if (Available.empty())
353 MinReadyCycle = UINT_MAX;
355 // Check to see if any of the pending instructions are ready to issue. If
356 // so, add them to the available queue.
357 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
358 SUnit *SU = *(Pending.begin()+i);
359 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
361 if (ReadyCycle < MinReadyCycle)
362 MinReadyCycle = ReadyCycle;
364 if (ReadyCycle > CurrCycle)
371 Pending.remove(Pending.begin()+i);
374 CheckPending = false;
377 /// Remove SU from the ready set for this boundary.
378 void ConvergingVLIWScheduler::SchedBoundary::removeReady(SUnit *SU) {
379 if (Available.isInQueue(SU))
380 Available.remove(Available.find(SU));
382 assert(Pending.isInQueue(SU) && "bad ready count");
383 Pending.remove(Pending.find(SU));
387 /// If this queue only has one ready candidate, return it. As a side effect,
388 /// advance the cycle until at least one node is ready. If multiple instructions
389 /// are ready, return NULL.
390 SUnit *ConvergingVLIWScheduler::SchedBoundary::pickOnlyChoice() {
394 for (unsigned i = 0; Available.empty(); ++i) {
395 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
396 "permanent hazard"); (void)i;
397 ResourceModel->reserveResources(0);
401 if (Available.size() == 1)
402 return *Available.begin();
407 void ConvergingVLIWScheduler::traceCandidate(const char *Label,
409 SUnit *SU, PressureElement P) {
410 dbgs() << Label << " " << Q.getName() << " ";
412 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
420 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
421 /// of SU, return it, otherwise return null.
422 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
423 SUnit *OnlyAvailablePred = 0;
424 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
426 SUnit &Pred = *I->getSUnit();
427 if (!Pred.isScheduled) {
428 // We found an available, but not scheduled, predecessor. If it's the
429 // only one we have found, keep track of it... otherwise give up.
430 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
432 OnlyAvailablePred = &Pred;
435 return OnlyAvailablePred;
438 /// getSingleUnscheduledSucc - If there is exactly one unscheduled successor
439 /// of SU, return it, otherwise return null.
440 static SUnit *getSingleUnscheduledSucc(SUnit *SU) {
441 SUnit *OnlyAvailableSucc = 0;
442 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
444 SUnit &Succ = *I->getSUnit();
445 if (!Succ.isScheduled) {
446 // We found an available, but not scheduled, successor. If it's the
447 // only one we have found, keep track of it... otherwise give up.
448 if (OnlyAvailableSucc && OnlyAvailableSucc != &Succ)
450 OnlyAvailableSucc = &Succ;
453 return OnlyAvailableSucc;
456 // Constants used to denote relative importance of
457 // heuristic components for cost computation.
458 static const unsigned PriorityOne = 200;
459 static const unsigned PriorityTwo = 100;
460 static const unsigned PriorityThree = 50;
461 static const unsigned PriorityFour = 20;
462 static const unsigned ScaleTwo = 10;
463 static const unsigned FactorOne = 2;
465 /// Single point to compute overall scheduling cost.
466 /// TODO: More heuristics will be used soon.
467 int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
468 SchedCandidate &Candidate,
469 RegPressureDelta &Delta,
471 // Initial trivial priority.
474 // Do not waste time on a node that is already scheduled.
475 if (!SU || SU->isScheduled)
478 // Forced priority is high.
479 if (SU->isScheduleHigh)
480 ResCount += PriorityOne;
482 // Critical path first.
483 if (Q.getID() == TopQID) {
484 ResCount += (SU->getHeight() * ScaleTwo);
486 // If resources are available for it, multiply the
487 // chance of scheduling.
488 if (Top.ResourceModel->isResourceAvailable(SU))
489 ResCount <<= FactorOne;
491 ResCount += (SU->getDepth() * ScaleTwo);
493 // If resources are available for it, multiply the
494 // chance of scheduling.
495 if (Bot.ResourceModel->isResourceAvailable(SU))
496 ResCount <<= FactorOne;
499 unsigned NumNodesBlocking = 0;
500 if (Q.getID() == TopQID) {
501 // How many SUs does it block from scheduling?
502 // Look at all of the successors of this node.
503 // Count the number of nodes that
504 // this node is the sole unscheduled node for.
505 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
507 if (getSingleUnscheduledPred(I->getSUnit()) == SU)
510 // How many unscheduled predecessors block this node?
511 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
513 if (getSingleUnscheduledSucc(I->getSUnit()) == SU)
516 ResCount += (NumNodesBlocking * ScaleTwo);
518 // Factor in reg pressure as a heuristic.
519 ResCount -= (Delta.Excess.UnitIncrease*PriorityThree);
520 ResCount -= (Delta.CriticalMax.UnitIncrease*PriorityThree);
522 DEBUG(if (verbose) dbgs() << " Total(" << ResCount << ")");
527 /// Pick the best candidate from the top queue.
529 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
530 /// DAG building. To adjust for the current scheduling location we need to
531 /// maintain the number of vreg uses remaining to be top-scheduled.
532 ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
533 pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
534 SchedCandidate &Candidate) {
537 // getMaxPressureDelta temporarily modifies the tracker.
538 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
540 // BestSU remains NULL if no top candidates beat the best existing candidate.
541 CandResult FoundCandidate = NoCand;
542 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
543 RegPressureDelta RPDelta;
544 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
545 DAG->getRegionCriticalPSets(),
546 DAG->getRegPressure().MaxSetPressure);
548 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
550 // Initialize the candidate if needed.
553 Candidate.RPDelta = RPDelta;
554 Candidate.SCost = CurrentCost;
555 FoundCandidate = NodeOrder;
560 if (CurrentCost > Candidate.SCost) {
561 DEBUG(traceCandidate("CCAND", Q, *I));
563 Candidate.RPDelta = RPDelta;
564 Candidate.SCost = CurrentCost;
565 FoundCandidate = BestCost;
569 // Fall through to original instruction order.
570 // Only consider node order if Candidate was chosen from this Q.
571 if (FoundCandidate == NoCand)
574 return FoundCandidate;
577 /// Pick the best candidate node from either the top or bottom queue.
578 SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
579 // Schedule as far as possible in the direction of no choice. This is most
580 // efficient, but also provides the best heuristics for CriticalPSets.
581 if (SUnit *SU = Bot.pickOnlyChoice()) {
585 if (SUnit *SU = Top.pickOnlyChoice()) {
589 SchedCandidate BotCand;
590 // Prefer bottom scheduling when heuristics are silent.
591 CandResult BotResult = pickNodeFromQueue(Bot.Available,
592 DAG->getBotRPTracker(), BotCand);
593 assert(BotResult != NoCand && "failed to find the first candidate");
595 // If either Q has a single candidate that provides the least increase in
596 // Excess pressure, we can immediately schedule from that Q.
598 // RegionCriticalPSets summarizes the pressure within the scheduled region and
599 // affects picking from either Q. If scheduling in one direction must
600 // increase pressure for one of the excess PSets, then schedule in that
601 // direction first to provide more freedom in the other direction.
602 if (BotResult == SingleExcess || BotResult == SingleCritical) {
606 // Check if the top Q has a better candidate.
607 SchedCandidate TopCand;
608 CandResult TopResult = pickNodeFromQueue(Top.Available,
609 DAG->getTopRPTracker(), TopCand);
610 assert(TopResult != NoCand && "failed to find the first candidate");
612 if (TopResult == SingleExcess || TopResult == SingleCritical) {
616 // If either Q has a single candidate that minimizes pressure above the
617 // original region's pressure pick it.
618 if (BotResult == SingleMax) {
622 if (TopResult == SingleMax) {
626 if (TopCand.SCost > BotCand.SCost) {
630 // Otherwise prefer the bottom candidate in node order.
635 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
636 SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
637 if (DAG->top() == DAG->bottom()) {
638 assert(Top.Available.empty() && Top.Pending.empty() &&
639 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
643 if (llvm::ForceTopDown) {
644 SU = Top.pickOnlyChoice();
646 SchedCandidate TopCand;
647 CandResult TopResult =
648 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
649 assert(TopResult != NoCand && "failed to find the first candidate");
654 } else if (llvm::ForceBottomUp) {
655 SU = Bot.pickOnlyChoice();
657 SchedCandidate BotCand;
658 CandResult BotResult =
659 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
660 assert(BotResult != NoCand && "failed to find the first candidate");
666 SU = pickNodeBidrectional(IsTopNode);
668 if (SU->isTopReady())
670 if (SU->isBottomReady())
673 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
674 << " Scheduling Instruction in cycle "
675 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
680 /// Update the scheduler's state after scheduling a node. This is the same node
681 /// that was just returned by pickNode(). However, VLIWMachineScheduler needs
682 /// to update it's state based on the current cycle before MachineSchedStrategy
684 void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
686 SU->TopReadyCycle = Top.CurrCycle;
689 SU->BotReadyCycle = Bot.CurrCycle;