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"
22 /// Platform specific modifications to DAG.
23 void VLIWMachineScheduler::postprocessDAG() {
24 SUnit* LastSequentialCall = NULL;
25 // Currently we only catch the situation when compare gets scheduled
26 // before preceding call.
27 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
29 if (SUnits[su].getInstr()->isCall())
30 LastSequentialCall = &(SUnits[su]);
31 // Look for a compare that defines a predicate.
32 else if (SUnits[su].getInstr()->isCompare() && LastSequentialCall)
33 SUnits[su].addPred(SDep(LastSequentialCall, SDep::Barrier));
37 /// Check if scheduling of this SU is possible
38 /// in the current packet.
39 /// It is _not_ precise (statefull), it is more like
40 /// another heuristic. Many corner cases are figured
42 bool VLIWResourceModel::isResourceAvailable(SUnit *SU) {
43 if (!SU || !SU->getInstr())
46 // First see if the pipeline could receive this instruction
47 // in the current cycle.
48 switch (SU->getInstr()->getOpcode()) {
50 if (!ResourcesModel->canReserveResources(SU->getInstr()))
52 case TargetOpcode::EXTRACT_SUBREG:
53 case TargetOpcode::INSERT_SUBREG:
54 case TargetOpcode::SUBREG_TO_REG:
55 case TargetOpcode::REG_SEQUENCE:
56 case TargetOpcode::IMPLICIT_DEF:
57 case TargetOpcode::COPY:
58 case TargetOpcode::INLINEASM:
62 // Now see if there are no other dependencies to instructions already
64 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
65 if (Packet[i]->Succs.size() == 0)
67 for (SUnit::const_succ_iterator I = Packet[i]->Succs.begin(),
68 E = Packet[i]->Succs.end(); I != E; ++I) {
69 // Since we do not add pseudos to packets, might as well
70 // ignore order dependencies.
74 if (I->getSUnit() == SU)
81 /// Keep track of available resources.
82 bool VLIWResourceModel::reserveResources(SUnit *SU) {
83 bool startNewCycle = false;
84 // Artificially reset state.
86 ResourcesModel->clearResources();
91 // If this SU does not fit in the packet
93 if (!isResourceAvailable(SU)) {
94 ResourcesModel->clearResources();
100 switch (SU->getInstr()->getOpcode()) {
102 ResourcesModel->reserveResources(SU->getInstr());
104 case TargetOpcode::EXTRACT_SUBREG:
105 case TargetOpcode::INSERT_SUBREG:
106 case TargetOpcode::SUBREG_TO_REG:
107 case TargetOpcode::REG_SEQUENCE:
108 case TargetOpcode::IMPLICIT_DEF:
109 case TargetOpcode::KILL:
110 case TargetOpcode::PROLOG_LABEL:
111 case TargetOpcode::EH_LABEL:
112 case TargetOpcode::COPY:
113 case TargetOpcode::INLINEASM:
116 Packet.push_back(SU);
119 DEBUG(dbgs() << "Packet[" << TotalPackets << "]:\n");
120 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
121 DEBUG(dbgs() << "\t[" << i << "] SU(");
122 DEBUG(dbgs() << Packet[i]->NodeNum << ")\t");
123 DEBUG(Packet[i]->getInstr()->dump());
127 // If packet is now full, reset the state so in the next cycle
129 if (Packet.size() >= SchedModel->getIssueWidth()) {
130 ResourcesModel->clearResources();
133 startNewCycle = true;
136 return startNewCycle;
139 /// schedule - Called back from MachineScheduler::runOnMachineFunction
140 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
141 /// only includes instructions that have DAG nodes, not scheduling boundaries.
142 void VLIWMachineScheduler::schedule() {
144 << "********** MI Converging Scheduling VLIW BB#" << BB->getNumber()
145 << " " << BB->getName()
146 << " in_func " << BB->getParent()->getFunction()->getName()
147 << " at loop depth " << MLI.getLoopDepth(BB)
150 buildDAGWithRegPressure();
152 // Postprocess the DAG to add platform specific artificial dependencies.
155 // To view Height/Depth correctly, they should be accessed at least once.
156 DEBUG(unsigned maxH = 0;
157 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
158 if (SUnits[su].getHeight() > maxH)
159 maxH = SUnits[su].getHeight();
160 dbgs() << "Max Height " << maxH << "\n";);
161 DEBUG(unsigned maxD = 0;
162 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
163 if (SUnits[su].getDepth() > maxD)
164 maxD = SUnits[su].getDepth();
165 dbgs() << "Max Depth " << maxD << "\n";);
166 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
167 SUnits[su].dumpAll(this));
171 bool IsTopNode = false;
172 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
173 if (!checkSchedLimit())
176 scheduleMI(SU, IsTopNode);
178 updateQueues(SU, IsTopNode);
180 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
185 void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
186 DAG = static_cast<VLIWMachineScheduler*>(dag);
187 SchedModel = DAG->getSchedModel();
189 Top.init(DAG, SchedModel);
190 Bot.init(DAG, SchedModel);
192 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
193 // are disabled, then these HazardRecs will be disabled.
194 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
195 const TargetMachine &TM = DAG->MF.getTarget();
196 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
197 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
199 Top.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
200 Bot.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
202 assert((!llvm::ForceTopDown || !llvm::ForceBottomUp) &&
203 "-misched-topdown incompatible with -misched-bottomup");
206 void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
210 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
212 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
213 unsigned MinLatency = I->getMinLatency();
215 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
217 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
218 SU->TopReadyCycle = PredReadyCycle + MinLatency;
220 Top.releaseNode(SU, SU->TopReadyCycle);
223 void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
227 assert(SU->getInstr() && "Scheduled SUnit must have instr");
229 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
231 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
232 unsigned MinLatency = I->getMinLatency();
234 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
236 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
237 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
239 Bot.releaseNode(SU, SU->BotReadyCycle);
242 /// Does this SU have a hazard within the current instruction group.
244 /// The scheduler supports two modes of hazard recognition. The first is the
245 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
246 /// supports highly complicated in-order reservation tables
247 /// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
249 /// The second is a streamlined mechanism that checks for hazards based on
250 /// simple counters that the scheduler itself maintains. It explicitly checks
251 /// for instruction dispatch limitations, including the number of micro-ops that
252 /// can dispatch per cycle.
254 /// TODO: Also check whether the SU must start a new group.
255 bool ConvergingVLIWScheduler::SchedBoundary::checkHazard(SUnit *SU) {
256 if (HazardRec->isEnabled())
257 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
259 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
260 if (IssueCount + uops > SchedModel->getIssueWidth())
266 void ConvergingVLIWScheduler::SchedBoundary::releaseNode(SUnit *SU,
267 unsigned ReadyCycle) {
268 if (ReadyCycle < MinReadyCycle)
269 MinReadyCycle = ReadyCycle;
271 // Check for interlocks first. For the purpose of other heuristics, an
272 // instruction that cannot issue appears as if it's not in the ReadyQueue.
273 if (ReadyCycle > CurrCycle || checkHazard(SU))
280 /// Move the boundary of scheduled code by one cycle.
281 void ConvergingVLIWScheduler::SchedBoundary::bumpCycle() {
282 unsigned Width = SchedModel->getIssueWidth();
283 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
285 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
286 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
288 if (!HazardRec->isEnabled()) {
289 // Bypass HazardRec virtual calls.
290 CurrCycle = NextCycle;
292 // Bypass getHazardType calls in case of long latency.
293 for (; CurrCycle != NextCycle; ++CurrCycle) {
295 HazardRec->AdvanceCycle();
297 HazardRec->RecedeCycle();
302 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
303 << CurrCycle << '\n');
306 /// Move the boundary of scheduled code by one SUnit.
307 void ConvergingVLIWScheduler::SchedBoundary::bumpNode(SUnit *SU) {
308 bool startNewCycle = false;
310 // Update the reservation table.
311 if (HazardRec->isEnabled()) {
312 if (!isTop() && SU->isCall) {
313 // Calls are scheduled with their preceding instructions. For bottom-up
314 // scheduling, clear the pipeline state before emitting.
317 HazardRec->EmitInstruction(SU);
321 startNewCycle = ResourceModel->reserveResources(SU);
323 // Check the instruction group dispatch limit.
324 // TODO: Check if this SU must end a dispatch group.
325 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
327 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
331 DEBUG(dbgs() << "*** IssueCount " << IssueCount
332 << " at cycle " << CurrCycle << '\n');
335 /// Release pending ready nodes in to the available queue. This makes them
336 /// visible to heuristics.
337 void ConvergingVLIWScheduler::SchedBoundary::releasePending() {
338 // If the available queue is empty, it is safe to reset MinReadyCycle.
339 if (Available.empty())
340 MinReadyCycle = UINT_MAX;
342 // Check to see if any of the pending instructions are ready to issue. If
343 // so, add them to the available queue.
344 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
345 SUnit *SU = *(Pending.begin()+i);
346 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
348 if (ReadyCycle < MinReadyCycle)
349 MinReadyCycle = ReadyCycle;
351 if (ReadyCycle > CurrCycle)
358 Pending.remove(Pending.begin()+i);
361 CheckPending = false;
364 /// Remove SU from the ready set for this boundary.
365 void ConvergingVLIWScheduler::SchedBoundary::removeReady(SUnit *SU) {
366 if (Available.isInQueue(SU))
367 Available.remove(Available.find(SU));
369 assert(Pending.isInQueue(SU) && "bad ready count");
370 Pending.remove(Pending.find(SU));
374 /// If this queue only has one ready candidate, return it. As a side effect,
375 /// advance the cycle until at least one node is ready. If multiple instructions
376 /// are ready, return NULL.
377 SUnit *ConvergingVLIWScheduler::SchedBoundary::pickOnlyChoice() {
381 for (unsigned i = 0; Available.empty(); ++i) {
382 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
383 "permanent hazard"); (void)i;
384 ResourceModel->reserveResources(0);
388 if (Available.size() == 1)
389 return *Available.begin();
394 void ConvergingVLIWScheduler::traceCandidate(const char *Label,
396 SUnit *SU, PressureElement P) {
397 dbgs() << Label << " " << Q.getName() << " ";
399 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
407 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
408 /// of SU, return it, otherwise return null.
409 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
410 SUnit *OnlyAvailablePred = 0;
411 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
413 SUnit &Pred = *I->getSUnit();
414 if (!Pred.isScheduled) {
415 // We found an available, but not scheduled, predecessor. If it's the
416 // only one we have found, keep track of it... otherwise give up.
417 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
419 OnlyAvailablePred = &Pred;
422 return OnlyAvailablePred;
425 /// getSingleUnscheduledSucc - If there is exactly one unscheduled successor
426 /// of SU, return it, otherwise return null.
427 static SUnit *getSingleUnscheduledSucc(SUnit *SU) {
428 SUnit *OnlyAvailableSucc = 0;
429 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
431 SUnit &Succ = *I->getSUnit();
432 if (!Succ.isScheduled) {
433 // We found an available, but not scheduled, successor. If it's the
434 // only one we have found, keep track of it... otherwise give up.
435 if (OnlyAvailableSucc && OnlyAvailableSucc != &Succ)
437 OnlyAvailableSucc = &Succ;
440 return OnlyAvailableSucc;
443 // Constants used to denote relative importance of
444 // heuristic components for cost computation.
445 static const unsigned PriorityOne = 200;
446 static const unsigned PriorityTwo = 100;
447 static const unsigned PriorityThree = 50;
448 static const unsigned PriorityFour = 20;
449 static const unsigned ScaleTwo = 10;
450 static const unsigned FactorOne = 2;
452 /// Single point to compute overall scheduling cost.
453 /// TODO: More heuristics will be used soon.
454 int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
455 SchedCandidate &Candidate,
456 RegPressureDelta &Delta,
458 // Initial trivial priority.
461 // Do not waste time on a node that is already scheduled.
462 if (!SU || SU->isScheduled)
465 // Forced priority is high.
466 if (SU->isScheduleHigh)
467 ResCount += PriorityOne;
469 // Critical path first.
470 if (Q.getID() == TopQID) {
471 ResCount += (SU->getHeight() * ScaleTwo);
473 // If resources are available for it, multiply the
474 // chance of scheduling.
475 if (Top.ResourceModel->isResourceAvailable(SU))
476 ResCount <<= FactorOne;
478 ResCount += (SU->getDepth() * ScaleTwo);
480 // If resources are available for it, multiply the
481 // chance of scheduling.
482 if (Bot.ResourceModel->isResourceAvailable(SU))
483 ResCount <<= FactorOne;
486 unsigned NumNodesBlocking = 0;
487 if (Q.getID() == TopQID) {
488 // How many SUs does it block from scheduling?
489 // Look at all of the successors of this node.
490 // Count the number of nodes that
491 // this node is the sole unscheduled node for.
492 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
494 if (getSingleUnscheduledPred(I->getSUnit()) == SU)
497 // How many unscheduled predecessors block this node?
498 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
500 if (getSingleUnscheduledSucc(I->getSUnit()) == SU)
503 ResCount += (NumNodesBlocking * ScaleTwo);
505 // Factor in reg pressure as a heuristic.
506 ResCount -= (Delta.Excess.UnitIncrease*PriorityThree);
507 ResCount -= (Delta.CriticalMax.UnitIncrease*PriorityThree);
509 DEBUG(if (verbose) dbgs() << " Total(" << ResCount << ")");
514 /// Pick the best candidate from the top queue.
516 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
517 /// DAG building. To adjust for the current scheduling location we need to
518 /// maintain the number of vreg uses remaining to be top-scheduled.
519 ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
520 pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
521 SchedCandidate &Candidate) {
524 // getMaxPressureDelta temporarily modifies the tracker.
525 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
527 // BestSU remains NULL if no top candidates beat the best existing candidate.
528 CandResult FoundCandidate = NoCand;
529 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
530 RegPressureDelta RPDelta;
531 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
532 DAG->getRegionCriticalPSets(),
533 DAG->getRegPressure().MaxSetPressure);
535 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
537 // Initialize the candidate if needed.
540 Candidate.RPDelta = RPDelta;
541 Candidate.SCost = CurrentCost;
542 FoundCandidate = NodeOrder;
547 if (CurrentCost > Candidate.SCost) {
548 DEBUG(traceCandidate("CCAND", Q, *I));
550 Candidate.RPDelta = RPDelta;
551 Candidate.SCost = CurrentCost;
552 FoundCandidate = BestCost;
556 // Fall through to original instruction order.
557 // Only consider node order if Candidate was chosen from this Q.
558 if (FoundCandidate == NoCand)
561 return FoundCandidate;
564 /// Pick the best candidate node from either the top or bottom queue.
565 SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
566 // Schedule as far as possible in the direction of no choice. This is most
567 // efficient, but also provides the best heuristics for CriticalPSets.
568 if (SUnit *SU = Bot.pickOnlyChoice()) {
572 if (SUnit *SU = Top.pickOnlyChoice()) {
576 SchedCandidate BotCand;
577 // Prefer bottom scheduling when heuristics are silent.
578 CandResult BotResult = pickNodeFromQueue(Bot.Available,
579 DAG->getBotRPTracker(), BotCand);
580 assert(BotResult != NoCand && "failed to find the first candidate");
582 // If either Q has a single candidate that provides the least increase in
583 // Excess pressure, we can immediately schedule from that Q.
585 // RegionCriticalPSets summarizes the pressure within the scheduled region and
586 // affects picking from either Q. If scheduling in one direction must
587 // increase pressure for one of the excess PSets, then schedule in that
588 // direction first to provide more freedom in the other direction.
589 if (BotResult == SingleExcess || BotResult == SingleCritical) {
593 // Check if the top Q has a better candidate.
594 SchedCandidate TopCand;
595 CandResult TopResult = pickNodeFromQueue(Top.Available,
596 DAG->getTopRPTracker(), TopCand);
597 assert(TopResult != NoCand && "failed to find the first candidate");
599 if (TopResult == SingleExcess || TopResult == SingleCritical) {
603 // If either Q has a single candidate that minimizes pressure above the
604 // original region's pressure pick it.
605 if (BotResult == SingleMax) {
609 if (TopResult == SingleMax) {
613 if (TopCand.SCost > BotCand.SCost) {
617 // Otherwise prefer the bottom candidate in node order.
622 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
623 SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
624 if (DAG->top() == DAG->bottom()) {
625 assert(Top.Available.empty() && Top.Pending.empty() &&
626 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
630 if (llvm::ForceTopDown) {
631 SU = Top.pickOnlyChoice();
633 SchedCandidate TopCand;
634 CandResult TopResult =
635 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
636 assert(TopResult != NoCand && "failed to find the first candidate");
641 } else if (llvm::ForceBottomUp) {
642 SU = Bot.pickOnlyChoice();
644 SchedCandidate BotCand;
645 CandResult BotResult =
646 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
647 assert(BotResult != NoCand && "failed to find the first candidate");
653 SU = pickNodeBidrectional(IsTopNode);
655 if (SU->isTopReady())
657 if (SU->isBottomReady())
660 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
661 << " Scheduling Instruction in cycle "
662 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
667 /// Update the scheduler's state after scheduling a node. This is the same node
668 /// that was just returned by pickNode(). However, VLIWMachineScheduler needs
669 /// to update it's state based on the current cycle before MachineSchedStrategy
671 void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
673 SU->TopReadyCycle = Top.CurrCycle;
676 SU->BotReadyCycle = Bot.CurrCycle;