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 SmallVector<SUnit*, 8> TopRoots, BotRoots;
156 findRootsAndBiasEdges(TopRoots, BotRoots);
158 // Initialize the strategy before modifying the DAG.
159 SchedImpl->initialize(this);
161 // To view Height/Depth correctly, they should be accessed at least once.
162 DEBUG(unsigned maxH = 0;
163 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
164 if (SUnits[su].getHeight() > maxH)
165 maxH = SUnits[su].getHeight();
166 dbgs() << "Max Height " << maxH << "\n";);
167 DEBUG(unsigned maxD = 0;
168 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
169 if (SUnits[su].getDepth() > maxD)
170 maxD = SUnits[su].getDepth();
171 dbgs() << "Max Depth " << maxD << "\n";);
172 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
173 SUnits[su].dumpAll(this));
175 initQueues(TopRoots, BotRoots);
177 bool IsTopNode = false;
178 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
179 if (!checkSchedLimit())
182 scheduleMI(SU, IsTopNode);
184 updateQueues(SU, IsTopNode);
186 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
191 void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
192 DAG = static_cast<VLIWMachineScheduler*>(dag);
193 SchedModel = DAG->getSchedModel();
196 Top.init(DAG, SchedModel);
197 Bot.init(DAG, SchedModel);
199 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
200 // are disabled, then these HazardRecs will be disabled.
201 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
202 const TargetMachine &TM = DAG->MF.getTarget();
203 delete Top.HazardRec;
204 delete Bot.HazardRec;
205 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
206 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
208 Top.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
209 Bot.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
211 assert((!llvm::ForceTopDown || !llvm::ForceBottomUp) &&
212 "-misched-topdown incompatible with -misched-bottomup");
215 void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
219 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
221 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
222 unsigned MinLatency = I->getMinLatency();
224 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
226 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
227 SU->TopReadyCycle = PredReadyCycle + MinLatency;
229 Top.releaseNode(SU, SU->TopReadyCycle);
232 void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
236 assert(SU->getInstr() && "Scheduled SUnit must have instr");
238 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
240 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
241 unsigned MinLatency = I->getMinLatency();
243 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
245 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
246 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
248 Bot.releaseNode(SU, SU->BotReadyCycle);
251 /// Does this SU have a hazard within the current instruction group.
253 /// The scheduler supports two modes of hazard recognition. The first is the
254 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
255 /// supports highly complicated in-order reservation tables
256 /// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
258 /// The second is a streamlined mechanism that checks for hazards based on
259 /// simple counters that the scheduler itself maintains. It explicitly checks
260 /// for instruction dispatch limitations, including the number of micro-ops that
261 /// can dispatch per cycle.
263 /// TODO: Also check whether the SU must start a new group.
264 bool ConvergingVLIWScheduler::SchedBoundary::checkHazard(SUnit *SU) {
265 if (HazardRec->isEnabled())
266 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
268 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
269 if (IssueCount + uops > SchedModel->getIssueWidth())
275 void ConvergingVLIWScheduler::SchedBoundary::releaseNode(SUnit *SU,
276 unsigned ReadyCycle) {
277 if (ReadyCycle < MinReadyCycle)
278 MinReadyCycle = ReadyCycle;
280 // Check for interlocks first. For the purpose of other heuristics, an
281 // instruction that cannot issue appears as if it's not in the ReadyQueue.
282 if (ReadyCycle > CurrCycle || checkHazard(SU))
289 /// Move the boundary of scheduled code by one cycle.
290 void ConvergingVLIWScheduler::SchedBoundary::bumpCycle() {
291 unsigned Width = SchedModel->getIssueWidth();
292 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
294 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
295 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
297 if (!HazardRec->isEnabled()) {
298 // Bypass HazardRec virtual calls.
299 CurrCycle = NextCycle;
301 // Bypass getHazardType calls in case of long latency.
302 for (; CurrCycle != NextCycle; ++CurrCycle) {
304 HazardRec->AdvanceCycle();
306 HazardRec->RecedeCycle();
311 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
312 << CurrCycle << '\n');
315 /// Move the boundary of scheduled code by one SUnit.
316 void ConvergingVLIWScheduler::SchedBoundary::bumpNode(SUnit *SU) {
317 bool startNewCycle = false;
319 // Update the reservation table.
320 if (HazardRec->isEnabled()) {
321 if (!isTop() && SU->isCall) {
322 // Calls are scheduled with their preceding instructions. For bottom-up
323 // scheduling, clear the pipeline state before emitting.
326 HazardRec->EmitInstruction(SU);
330 startNewCycle = ResourceModel->reserveResources(SU);
332 // Check the instruction group dispatch limit.
333 // TODO: Check if this SU must end a dispatch group.
334 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
336 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
340 DEBUG(dbgs() << "*** IssueCount " << IssueCount
341 << " at cycle " << CurrCycle << '\n');
344 /// Release pending ready nodes in to the available queue. This makes them
345 /// visible to heuristics.
346 void ConvergingVLIWScheduler::SchedBoundary::releasePending() {
347 // If the available queue is empty, it is safe to reset MinReadyCycle.
348 if (Available.empty())
349 MinReadyCycle = UINT_MAX;
351 // Check to see if any of the pending instructions are ready to issue. If
352 // so, add them to the available queue.
353 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
354 SUnit *SU = *(Pending.begin()+i);
355 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
357 if (ReadyCycle < MinReadyCycle)
358 MinReadyCycle = ReadyCycle;
360 if (ReadyCycle > CurrCycle)
367 Pending.remove(Pending.begin()+i);
370 CheckPending = false;
373 /// Remove SU from the ready set for this boundary.
374 void ConvergingVLIWScheduler::SchedBoundary::removeReady(SUnit *SU) {
375 if (Available.isInQueue(SU))
376 Available.remove(Available.find(SU));
378 assert(Pending.isInQueue(SU) && "bad ready count");
379 Pending.remove(Pending.find(SU));
383 /// If this queue only has one ready candidate, return it. As a side effect,
384 /// advance the cycle until at least one node is ready. If multiple instructions
385 /// are ready, return NULL.
386 SUnit *ConvergingVLIWScheduler::SchedBoundary::pickOnlyChoice() {
390 for (unsigned i = 0; Available.empty(); ++i) {
391 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
392 "permanent hazard"); (void)i;
393 ResourceModel->reserveResources(0);
397 if (Available.size() == 1)
398 return *Available.begin();
403 void ConvergingVLIWScheduler::traceCandidate(const char *Label,
405 SUnit *SU, PressureElement P) {
406 dbgs() << Label << " " << Q.getName() << " ";
408 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
416 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
417 /// of SU, return it, otherwise return null.
418 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
419 SUnit *OnlyAvailablePred = 0;
420 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
422 SUnit &Pred = *I->getSUnit();
423 if (!Pred.isScheduled) {
424 // We found an available, but not scheduled, predecessor. If it's the
425 // only one we have found, keep track of it... otherwise give up.
426 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
428 OnlyAvailablePred = &Pred;
431 return OnlyAvailablePred;
434 /// getSingleUnscheduledSucc - If there is exactly one unscheduled successor
435 /// of SU, return it, otherwise return null.
436 static SUnit *getSingleUnscheduledSucc(SUnit *SU) {
437 SUnit *OnlyAvailableSucc = 0;
438 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
440 SUnit &Succ = *I->getSUnit();
441 if (!Succ.isScheduled) {
442 // We found an available, but not scheduled, successor. If it's the
443 // only one we have found, keep track of it... otherwise give up.
444 if (OnlyAvailableSucc && OnlyAvailableSucc != &Succ)
446 OnlyAvailableSucc = &Succ;
449 return OnlyAvailableSucc;
452 // Constants used to denote relative importance of
453 // heuristic components for cost computation.
454 static const unsigned PriorityOne = 200;
455 static const unsigned PriorityTwo = 100;
456 static const unsigned PriorityThree = 50;
457 static const unsigned PriorityFour = 20;
458 static const unsigned ScaleTwo = 10;
459 static const unsigned FactorOne = 2;
461 /// Single point to compute overall scheduling cost.
462 /// TODO: More heuristics will be used soon.
463 int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
464 SchedCandidate &Candidate,
465 RegPressureDelta &Delta,
467 // Initial trivial priority.
470 // Do not waste time on a node that is already scheduled.
471 if (!SU || SU->isScheduled)
474 // Forced priority is high.
475 if (SU->isScheduleHigh)
476 ResCount += PriorityOne;
478 // Critical path first.
479 if (Q.getID() == TopQID) {
480 ResCount += (SU->getHeight() * ScaleTwo);
482 // If resources are available for it, multiply the
483 // chance of scheduling.
484 if (Top.ResourceModel->isResourceAvailable(SU))
485 ResCount <<= FactorOne;
487 ResCount += (SU->getDepth() * ScaleTwo);
489 // If resources are available for it, multiply the
490 // chance of scheduling.
491 if (Bot.ResourceModel->isResourceAvailable(SU))
492 ResCount <<= FactorOne;
495 unsigned NumNodesBlocking = 0;
496 if (Q.getID() == TopQID) {
497 // How many SUs does it block from scheduling?
498 // Look at all of the successors of this node.
499 // Count the number of nodes that
500 // this node is the sole unscheduled node for.
501 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
503 if (getSingleUnscheduledPred(I->getSUnit()) == SU)
506 // How many unscheduled predecessors block this node?
507 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
509 if (getSingleUnscheduledSucc(I->getSUnit()) == SU)
512 ResCount += (NumNodesBlocking * ScaleTwo);
514 // Factor in reg pressure as a heuristic.
515 ResCount -= (Delta.Excess.UnitIncrease*PriorityThree);
516 ResCount -= (Delta.CriticalMax.UnitIncrease*PriorityThree);
518 DEBUG(if (verbose) dbgs() << " Total(" << ResCount << ")");
523 /// Pick the best candidate from the top queue.
525 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
526 /// DAG building. To adjust for the current scheduling location we need to
527 /// maintain the number of vreg uses remaining to be top-scheduled.
528 ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
529 pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
530 SchedCandidate &Candidate) {
533 // getMaxPressureDelta temporarily modifies the tracker.
534 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
536 // BestSU remains NULL if no top candidates beat the best existing candidate.
537 CandResult FoundCandidate = NoCand;
538 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
539 RegPressureDelta RPDelta;
540 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
541 DAG->getRegionCriticalPSets(),
542 DAG->getRegPressure().MaxSetPressure);
544 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
546 // Initialize the candidate if needed.
549 Candidate.RPDelta = RPDelta;
550 Candidate.SCost = CurrentCost;
551 FoundCandidate = NodeOrder;
556 if (CurrentCost > Candidate.SCost) {
557 DEBUG(traceCandidate("CCAND", Q, *I));
559 Candidate.RPDelta = RPDelta;
560 Candidate.SCost = CurrentCost;
561 FoundCandidate = BestCost;
565 // Fall through to original instruction order.
566 // Only consider node order if Candidate was chosen from this Q.
567 if (FoundCandidate == NoCand)
570 return FoundCandidate;
573 /// Pick the best candidate node from either the top or bottom queue.
574 SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
575 // Schedule as far as possible in the direction of no choice. This is most
576 // efficient, but also provides the best heuristics for CriticalPSets.
577 if (SUnit *SU = Bot.pickOnlyChoice()) {
581 if (SUnit *SU = Top.pickOnlyChoice()) {
585 SchedCandidate BotCand;
586 // Prefer bottom scheduling when heuristics are silent.
587 CandResult BotResult = pickNodeFromQueue(Bot.Available,
588 DAG->getBotRPTracker(), BotCand);
589 assert(BotResult != NoCand && "failed to find the first candidate");
591 // If either Q has a single candidate that provides the least increase in
592 // Excess pressure, we can immediately schedule from that Q.
594 // RegionCriticalPSets summarizes the pressure within the scheduled region and
595 // affects picking from either Q. If scheduling in one direction must
596 // increase pressure for one of the excess PSets, then schedule in that
597 // direction first to provide more freedom in the other direction.
598 if (BotResult == SingleExcess || BotResult == SingleCritical) {
602 // Check if the top Q has a better candidate.
603 SchedCandidate TopCand;
604 CandResult TopResult = pickNodeFromQueue(Top.Available,
605 DAG->getTopRPTracker(), TopCand);
606 assert(TopResult != NoCand && "failed to find the first candidate");
608 if (TopResult == SingleExcess || TopResult == SingleCritical) {
612 // If either Q has a single candidate that minimizes pressure above the
613 // original region's pressure pick it.
614 if (BotResult == SingleMax) {
618 if (TopResult == SingleMax) {
622 if (TopCand.SCost > BotCand.SCost) {
626 // Otherwise prefer the bottom candidate in node order.
631 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
632 SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
633 if (DAG->top() == DAG->bottom()) {
634 assert(Top.Available.empty() && Top.Pending.empty() &&
635 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
639 if (llvm::ForceTopDown) {
640 SU = Top.pickOnlyChoice();
642 SchedCandidate TopCand;
643 CandResult TopResult =
644 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
645 assert(TopResult != NoCand && "failed to find the first candidate");
650 } else if (llvm::ForceBottomUp) {
651 SU = Bot.pickOnlyChoice();
653 SchedCandidate BotCand;
654 CandResult BotResult =
655 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
656 assert(BotResult != NoCand && "failed to find the first candidate");
662 SU = pickNodeBidrectional(IsTopNode);
664 if (SU->isTopReady())
666 if (SU->isBottomReady())
669 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
670 << " Scheduling Instruction in cycle "
671 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
676 /// Update the scheduler's state after scheduling a node. This is the same node
677 /// that was just returned by pickNode(). However, VLIWMachineScheduler needs
678 /// to update it's state based on the current cycle before MachineSchedStrategy
680 void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
682 SU->TopReadyCycle = Top.CurrCycle;
685 SU->BotReadyCycle = Bot.CurrCycle;