blob: 22c485f51c4ce547c13b91aee75c605db63ac6c2 [file] [log] [blame]
Sergei Larin4d8986a2012-09-04 14:49:56 +00001//===- HexagonMachineScheduler.cpp - MI Scheduler for Hexagon -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "misched"
16
17#include "HexagonMachineScheduler.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000018#include "llvm/CodeGen/MachineLoopInfo.h"
19#include "llvm/IR/Function.h"
Sergei Larin4d8986a2012-09-04 14:49:56 +000020
21using namespace llvm;
22
Sergei Larin2db64a72012-09-14 15:07:59 +000023/// Platform specific modifications to DAG.
24void 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) {
29 // Remember the call.
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)
Andrew Trickbaeaabb2012-11-06 03:13:46 +000034 SUnits[su].addPred(SDep(LastSequentialCall, SDep::Barrier));
Sergei Larin2db64a72012-09-14 15:07:59 +000035 }
36}
37
Sergei Larin4d8986a2012-09-04 14:49:56 +000038/// 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
42/// empirically.
43bool VLIWResourceModel::isResourceAvailable(SUnit *SU) {
44 if (!SU || !SU->getInstr())
45 return false;
46
47 // First see if the pipeline could receive this instruction
48 // in the current cycle.
49 switch (SU->getInstr()->getOpcode()) {
50 default:
51 if (!ResourcesModel->canReserveResources(SU->getInstr()))
52 return false;
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:
60 break;
61 }
62
63 // Now see if there are no other dependencies to instructions already
64 // in the packet.
65 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
66 if (Packet[i]->Succs.size() == 0)
67 continue;
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.
72 if (I->isCtrl())
73 continue;
74
75 if (I->getSUnit() == SU)
76 return false;
77 }
78 }
79 return true;
80}
81
82/// Keep track of available resources.
Sergei Larinef4cc112012-09-10 17:31:34 +000083bool VLIWResourceModel::reserveResources(SUnit *SU) {
84 bool startNewCycle = false;
Sergei Larin2db64a72012-09-14 15:07:59 +000085 // Artificially reset state.
86 if (!SU) {
87 ResourcesModel->clearResources();
88 Packet.clear();
89 TotalPackets++;
90 return false;
91 }
Sergei Larin4d8986a2012-09-04 14:49:56 +000092 // If this SU does not fit in the packet
93 // start a new one.
94 if (!isResourceAvailable(SU)) {
95 ResourcesModel->clearResources();
96 Packet.clear();
97 TotalPackets++;
Sergei Larinef4cc112012-09-10 17:31:34 +000098 startNewCycle = true;
Sergei Larin4d8986a2012-09-04 14:49:56 +000099 }
100
101 switch (SU->getInstr()->getOpcode()) {
102 default:
103 ResourcesModel->reserveResources(SU->getInstr());
104 break;
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:
115 break;
116 }
117 Packet.push_back(SU);
118
119#ifndef NDEBUG
120 DEBUG(dbgs() << "Packet[" << TotalPackets << "]:\n");
121 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
122 DEBUG(dbgs() << "\t[" << i << "] SU(");
Sergei Larinef4cc112012-09-10 17:31:34 +0000123 DEBUG(dbgs() << Packet[i]->NodeNum << ")\t");
124 DEBUG(Packet[i]->getInstr()->dump());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000125 }
126#endif
127
128 // If packet is now full, reset the state so in the next cycle
129 // we start fresh.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000130 if (Packet.size() >= SchedModel->getIssueWidth()) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000131 ResourcesModel->clearResources();
132 Packet.clear();
133 TotalPackets++;
Sergei Larinef4cc112012-09-10 17:31:34 +0000134 startNewCycle = true;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000135 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000136
137 return startNewCycle;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000138}
139
Sergei Larin4d8986a2012-09-04 14:49:56 +0000140/// 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.
143void VLIWMachineScheduler::schedule() {
144 DEBUG(dbgs()
145 << "********** MI Converging Scheduling VLIW BB#" << BB->getNumber()
146 << " " << BB->getName()
147 << " in_func " << BB->getParent()->getFunction()->getName()
Benjamin Kramer61f67082012-09-14 12:19:58 +0000148 << " at loop depth " << MLI.getLoopDepth(BB)
Sergei Larin4d8986a2012-09-04 14:49:56 +0000149 << " \n");
150
Andrew Trick7a8e1002012-09-11 00:39:15 +0000151 buildDAGWithRegPressure();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000152
Sergei Larin2db64a72012-09-14 15:07:59 +0000153 // Postprocess the DAG to add platform specific artificial dependencies.
154 postprocessDAG();
155
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000156 SmallVector<SUnit*, 8> TopRoots, BotRoots;
157 findRootsAndBiasEdges(TopRoots, BotRoots);
158
159 // Initialize the strategy before modifying the DAG.
160 SchedImpl->initialize(this);
161
Sergei Larinef4cc112012-09-10 17:31:34 +0000162 // To view Height/Depth correctly, they should be accessed at least once.
Andrew Trick63474622013-03-02 01:43:08 +0000163 //
164 // FIXME: SUnit::dumpAll always recompute depth and height now. The max
165 // depth/height could be computed directly from the roots and leaves.
Sergei Larinef4cc112012-09-10 17:31:34 +0000166 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";);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000176 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
177 SUnits[su].dumpAll(this));
178
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000179 initQueues(TopRoots, BotRoots);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000180
Sergei Larin4d8986a2012-09-04 14:49:56 +0000181 bool IsTopNode = false;
182 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
183 if (!checkSchedLimit())
184 break;
185
Andrew Trick7a8e1002012-09-11 00:39:15 +0000186 scheduleMI(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000187
Andrew Trick7a8e1002012-09-11 00:39:15 +0000188 updateQueues(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000189 }
190 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
191
Sergei Larin4d8986a2012-09-04 14:49:56 +0000192 placeDebugValues();
193}
194
Andrew Trick7a8e1002012-09-11 00:39:15 +0000195void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
196 DAG = static_cast<VLIWMachineScheduler*>(dag);
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000197 SchedModel = DAG->getSchedModel();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000198
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000199 Top.init(DAG, SchedModel);
200 Bot.init(DAG, SchedModel);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000201
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000202 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
203 // are disabled, then these HazardRecs will be disabled.
204 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000205 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000206 delete Top.HazardRec;
207 delete Bot.HazardRec;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000208 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
209 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
210
Chandler Carruthc18e39c2013-07-27 10:48:45 +0000211 delete Top.ResourceModel;
212 delete Bot.ResourceModel;
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000213 Top.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
214 Bot.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
Sergei Larinef4cc112012-09-10 17:31:34 +0000215
Andrew Trick7a8e1002012-09-11 00:39:15 +0000216 assert((!llvm::ForceTopDown || !llvm::ForceBottomUp) &&
Sergei Larin4d8986a2012-09-04 14:49:56 +0000217 "-misched-topdown incompatible with -misched-bottomup");
218}
219
220void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
221 if (SU->isScheduled)
222 return;
223
224 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
225 I != E; ++I) {
226 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickde2109e2013-06-15 04:49:57 +0000227 unsigned MinLatency = I->getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000228#ifndef NDEBUG
229 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
230#endif
231 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
232 SU->TopReadyCycle = PredReadyCycle + MinLatency;
233 }
234 Top.releaseNode(SU, SU->TopReadyCycle);
235}
236
237void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
238 if (SU->isScheduled)
239 return;
240
241 assert(SU->getInstr() && "Scheduled SUnit must have instr");
242
243 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
244 I != E; ++I) {
245 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickde2109e2013-06-15 04:49:57 +0000246 unsigned MinLatency = I->getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000247#ifndef NDEBUG
248 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
249#endif
250 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
251 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
252 }
253 Bot.releaseNode(SU, SU->BotReadyCycle);
254}
255
256/// Does this SU have a hazard within the current instruction group.
257///
258/// The scheduler supports two modes of hazard recognition. The first is the
259/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
260/// supports highly complicated in-order reservation tables
261/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
262///
263/// The second is a streamlined mechanism that checks for hazards based on
264/// simple counters that the scheduler itself maintains. It explicitly checks
265/// for instruction dispatch limitations, including the number of micro-ops that
266/// can dispatch per cycle.
267///
268/// TODO: Also check whether the SU must start a new group.
269bool ConvergingVLIWScheduler::SchedBoundary::checkHazard(SUnit *SU) {
270 if (HazardRec->isEnabled())
271 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
272
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000273 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
274 if (IssueCount + uops > SchedModel->getIssueWidth())
Sergei Larin4d8986a2012-09-04 14:49:56 +0000275 return true;
276
277 return false;
278}
279
280void ConvergingVLIWScheduler::SchedBoundary::releaseNode(SUnit *SU,
281 unsigned ReadyCycle) {
282 if (ReadyCycle < MinReadyCycle)
283 MinReadyCycle = ReadyCycle;
284
285 // Check for interlocks first. For the purpose of other heuristics, an
286 // instruction that cannot issue appears as if it's not in the ReadyQueue.
287 if (ReadyCycle > CurrCycle || checkHazard(SU))
288
289 Pending.push(SU);
290 else
291 Available.push(SU);
292}
293
294/// Move the boundary of scheduled code by one cycle.
295void ConvergingVLIWScheduler::SchedBoundary::bumpCycle() {
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000296 unsigned Width = SchedModel->getIssueWidth();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000297 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
298
299 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
300 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
301
302 if (!HazardRec->isEnabled()) {
303 // Bypass HazardRec virtual calls.
304 CurrCycle = NextCycle;
Sergei Larinef4cc112012-09-10 17:31:34 +0000305 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000306 // Bypass getHazardType calls in case of long latency.
307 for (; CurrCycle != NextCycle; ++CurrCycle) {
308 if (isTop())
309 HazardRec->AdvanceCycle();
310 else
311 HazardRec->RecedeCycle();
312 }
313 }
314 CheckPending = true;
315
316 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
317 << CurrCycle << '\n');
318}
319
320/// Move the boundary of scheduled code by one SUnit.
321void ConvergingVLIWScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000322 bool startNewCycle = false;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000323
324 // Update the reservation table.
325 if (HazardRec->isEnabled()) {
326 if (!isTop() && SU->isCall) {
327 // Calls are scheduled with their preceding instructions. For bottom-up
328 // scheduling, clear the pipeline state before emitting.
329 HazardRec->Reset();
330 }
331 HazardRec->EmitInstruction(SU);
332 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000333
334 // Update DFA model.
335 startNewCycle = ResourceModel->reserveResources(SU);
336
Sergei Larin4d8986a2012-09-04 14:49:56 +0000337 // Check the instruction group dispatch limit.
338 // TODO: Check if this SU must end a dispatch group.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000339 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Sergei Larinef4cc112012-09-10 17:31:34 +0000340 if (startNewCycle) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000341 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
342 bumpCycle();
343 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000344 else
345 DEBUG(dbgs() << "*** IssueCount " << IssueCount
346 << " at cycle " << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000347}
348
349/// Release pending ready nodes in to the available queue. This makes them
350/// visible to heuristics.
351void ConvergingVLIWScheduler::SchedBoundary::releasePending() {
352 // If the available queue is empty, it is safe to reset MinReadyCycle.
353 if (Available.empty())
354 MinReadyCycle = UINT_MAX;
355
356 // Check to see if any of the pending instructions are ready to issue. If
357 // so, add them to the available queue.
358 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
359 SUnit *SU = *(Pending.begin()+i);
360 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
361
362 if (ReadyCycle < MinReadyCycle)
363 MinReadyCycle = ReadyCycle;
364
365 if (ReadyCycle > CurrCycle)
366 continue;
367
368 if (checkHazard(SU))
369 continue;
370
371 Available.push(SU);
372 Pending.remove(Pending.begin()+i);
373 --i; --e;
374 }
375 CheckPending = false;
376}
377
378/// Remove SU from the ready set for this boundary.
379void ConvergingVLIWScheduler::SchedBoundary::removeReady(SUnit *SU) {
380 if (Available.isInQueue(SU))
381 Available.remove(Available.find(SU));
382 else {
383 assert(Pending.isInQueue(SU) && "bad ready count");
384 Pending.remove(Pending.find(SU));
385 }
386}
387
388/// If this queue only has one ready candidate, return it. As a side effect,
389/// advance the cycle until at least one node is ready. If multiple instructions
390/// are ready, return NULL.
391SUnit *ConvergingVLIWScheduler::SchedBoundary::pickOnlyChoice() {
392 if (CheckPending)
393 releasePending();
394
395 for (unsigned i = 0; Available.empty(); ++i) {
396 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
397 "permanent hazard"); (void)i;
Sergei Larin2db64a72012-09-14 15:07:59 +0000398 ResourceModel->reserveResources(0);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000399 bumpCycle();
400 releasePending();
401 }
402 if (Available.size() == 1)
403 return *Available.begin();
404 return NULL;
405}
406
407#ifndef NDEBUG
Sergei Larinef4cc112012-09-10 17:31:34 +0000408void ConvergingVLIWScheduler::traceCandidate(const char *Label,
409 const ReadyQueue &Q,
Andrew Trick1a831342013-08-30 03:49:48 +0000410 SUnit *SU, PressureChange P) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000411 dbgs() << Label << " " << Q.getName() << " ";
412 if (P.isValid())
Andrew Trick1a831342013-08-30 03:49:48 +0000413 dbgs() << DAG->TRI->getRegPressureSetName(P.getPSet()) << ":"
414 << P.getUnitInc() << " ";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000415 else
416 dbgs() << " ";
417 SU->dump(DAG);
418}
419#endif
420
Sergei Larinef4cc112012-09-10 17:31:34 +0000421/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
422/// of SU, return it, otherwise return null.
423static SUnit *getSingleUnscheduledPred(SUnit *SU) {
424 SUnit *OnlyAvailablePred = 0;
425 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
426 I != E; ++I) {
427 SUnit &Pred = *I->getSUnit();
428 if (!Pred.isScheduled) {
429 // We found an available, but not scheduled, predecessor. If it's the
430 // only one we have found, keep track of it... otherwise give up.
431 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
432 return 0;
433 OnlyAvailablePred = &Pred;
434 }
435 }
436 return OnlyAvailablePred;
437}
438
439/// getSingleUnscheduledSucc - If there is exactly one unscheduled successor
440/// of SU, return it, otherwise return null.
441static SUnit *getSingleUnscheduledSucc(SUnit *SU) {
442 SUnit *OnlyAvailableSucc = 0;
443 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
444 I != E; ++I) {
445 SUnit &Succ = *I->getSUnit();
446 if (!Succ.isScheduled) {
447 // We found an available, but not scheduled, successor. If it's the
448 // only one we have found, keep track of it... otherwise give up.
449 if (OnlyAvailableSucc && OnlyAvailableSucc != &Succ)
450 return 0;
451 OnlyAvailableSucc = &Succ;
452 }
453 }
454 return OnlyAvailableSucc;
455}
456
Sergei Larin4d8986a2012-09-04 14:49:56 +0000457// Constants used to denote relative importance of
458// heuristic components for cost computation.
459static const unsigned PriorityOne = 200;
Sergei Larinef4cc112012-09-10 17:31:34 +0000460static const unsigned PriorityTwo = 100;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000461static const unsigned PriorityThree = 50;
Sergei Larinef4cc112012-09-10 17:31:34 +0000462static const unsigned PriorityFour = 20;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000463static const unsigned ScaleTwo = 10;
464static const unsigned FactorOne = 2;
465
466/// Single point to compute overall scheduling cost.
467/// TODO: More heuristics will be used soon.
468int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
469 SchedCandidate &Candidate,
470 RegPressureDelta &Delta,
471 bool verbose) {
472 // Initial trivial priority.
473 int ResCount = 1;
474
475 // Do not waste time on a node that is already scheduled.
476 if (!SU || SU->isScheduled)
477 return ResCount;
478
479 // Forced priority is high.
480 if (SU->isScheduleHigh)
481 ResCount += PriorityOne;
482
483 // Critical path first.
Sergei Larinef4cc112012-09-10 17:31:34 +0000484 if (Q.getID() == TopQID) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000485 ResCount += (SU->getHeight() * ScaleTwo);
Sergei Larinef4cc112012-09-10 17:31:34 +0000486
487 // If resources are available for it, multiply the
488 // chance of scheduling.
489 if (Top.ResourceModel->isResourceAvailable(SU))
490 ResCount <<= FactorOne;
491 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000492 ResCount += (SU->getDepth() * ScaleTwo);
493
Sergei Larinef4cc112012-09-10 17:31:34 +0000494 // If resources are available for it, multiply the
495 // chance of scheduling.
496 if (Bot.ResourceModel->isResourceAvailable(SU))
497 ResCount <<= FactorOne;
498 }
499
500 unsigned NumNodesBlocking = 0;
501 if (Q.getID() == TopQID) {
502 // How many SUs does it block from scheduling?
503 // Look at all of the successors of this node.
504 // Count the number of nodes that
505 // this node is the sole unscheduled node for.
506 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
507 I != E; ++I)
508 if (getSingleUnscheduledPred(I->getSUnit()) == SU)
509 ++NumNodesBlocking;
510 } else {
511 // How many unscheduled predecessors block this node?
512 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
513 I != E; ++I)
514 if (getSingleUnscheduledSucc(I->getSUnit()) == SU)
515 ++NumNodesBlocking;
516 }
517 ResCount += (NumNodesBlocking * ScaleTwo);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000518
519 // Factor in reg pressure as a heuristic.
Andrew Trick1a831342013-08-30 03:49:48 +0000520 ResCount -= (Delta.Excess.getUnitInc()*PriorityThree);
521 ResCount -= (Delta.CriticalMax.getUnitInc()*PriorityThree);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000522
523 DEBUG(if (verbose) dbgs() << " Total(" << ResCount << ")");
524
525 return ResCount;
526}
527
528/// Pick the best candidate from the top queue.
529///
530/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
531/// DAG building. To adjust for the current scheduling location we need to
532/// maintain the number of vreg uses remaining to be top-scheduled.
533ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
534pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
535 SchedCandidate &Candidate) {
536 DEBUG(Q.dump());
537
538 // getMaxPressureDelta temporarily modifies the tracker.
539 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
540
541 // BestSU remains NULL if no top candidates beat the best existing candidate.
542 CandResult FoundCandidate = NoCand;
543 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
544 RegPressureDelta RPDelta;
545 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
546 DAG->getRegionCriticalPSets(),
547 DAG->getRegPressure().MaxSetPressure);
548
549 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
550
551 // Initialize the candidate if needed.
552 if (!Candidate.SU) {
553 Candidate.SU = *I;
554 Candidate.RPDelta = RPDelta;
555 Candidate.SCost = CurrentCost;
556 FoundCandidate = NodeOrder;
557 continue;
558 }
559
Sergei Larin4d8986a2012-09-04 14:49:56 +0000560 // Best cost.
561 if (CurrentCost > Candidate.SCost) {
562 DEBUG(traceCandidate("CCAND", Q, *I));
563 Candidate.SU = *I;
564 Candidate.RPDelta = RPDelta;
565 Candidate.SCost = CurrentCost;
566 FoundCandidate = BestCost;
567 continue;
568 }
569
570 // Fall through to original instruction order.
571 // Only consider node order if Candidate was chosen from this Q.
572 if (FoundCandidate == NoCand)
573 continue;
574 }
575 return FoundCandidate;
576}
577
578/// Pick the best candidate node from either the top or bottom queue.
579SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
580 // Schedule as far as possible in the direction of no choice. This is most
581 // efficient, but also provides the best heuristics for CriticalPSets.
582 if (SUnit *SU = Bot.pickOnlyChoice()) {
583 IsTopNode = false;
584 return SU;
585 }
586 if (SUnit *SU = Top.pickOnlyChoice()) {
587 IsTopNode = true;
588 return SU;
589 }
590 SchedCandidate BotCand;
591 // Prefer bottom scheduling when heuristics are silent.
592 CandResult BotResult = pickNodeFromQueue(Bot.Available,
593 DAG->getBotRPTracker(), BotCand);
594 assert(BotResult != NoCand && "failed to find the first candidate");
595
596 // If either Q has a single candidate that provides the least increase in
597 // Excess pressure, we can immediately schedule from that Q.
598 //
599 // RegionCriticalPSets summarizes the pressure within the scheduled region and
600 // affects picking from either Q. If scheduling in one direction must
601 // increase pressure for one of the excess PSets, then schedule in that
602 // direction first to provide more freedom in the other direction.
603 if (BotResult == SingleExcess || BotResult == SingleCritical) {
604 IsTopNode = false;
605 return BotCand.SU;
606 }
607 // Check if the top Q has a better candidate.
608 SchedCandidate TopCand;
609 CandResult TopResult = pickNodeFromQueue(Top.Available,
610 DAG->getTopRPTracker(), TopCand);
611 assert(TopResult != NoCand && "failed to find the first candidate");
612
613 if (TopResult == SingleExcess || TopResult == SingleCritical) {
614 IsTopNode = true;
615 return TopCand.SU;
616 }
617 // If either Q has a single candidate that minimizes pressure above the
618 // original region's pressure pick it.
619 if (BotResult == SingleMax) {
620 IsTopNode = false;
621 return BotCand.SU;
622 }
623 if (TopResult == SingleMax) {
624 IsTopNode = true;
625 return TopCand.SU;
626 }
627 if (TopCand.SCost > BotCand.SCost) {
628 IsTopNode = true;
629 return TopCand.SU;
630 }
631 // Otherwise prefer the bottom candidate in node order.
632 IsTopNode = false;
633 return BotCand.SU;
634}
635
636/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
637SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
638 if (DAG->top() == DAG->bottom()) {
639 assert(Top.Available.empty() && Top.Pending.empty() &&
640 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
641 return NULL;
642 }
643 SUnit *SU;
Andrew Trick7a8e1002012-09-11 00:39:15 +0000644 if (llvm::ForceTopDown) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000645 SU = Top.pickOnlyChoice();
646 if (!SU) {
647 SchedCandidate TopCand;
648 CandResult TopResult =
649 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
650 assert(TopResult != NoCand && "failed to find the first candidate");
651 (void)TopResult;
652 SU = TopCand.SU;
653 }
654 IsTopNode = true;
Andrew Trick7a8e1002012-09-11 00:39:15 +0000655 } else if (llvm::ForceBottomUp) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000656 SU = Bot.pickOnlyChoice();
657 if (!SU) {
658 SchedCandidate BotCand;
659 CandResult BotResult =
660 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
661 assert(BotResult != NoCand && "failed to find the first candidate");
662 (void)BotResult;
663 SU = BotCand.SU;
664 }
665 IsTopNode = false;
666 } else {
667 SU = pickNodeBidrectional(IsTopNode);
668 }
669 if (SU->isTopReady())
670 Top.removeReady(SU);
671 if (SU->isBottomReady())
672 Bot.removeReady(SU);
673
674 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
675 << " Scheduling Instruction in cycle "
676 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
677 SU->dump(DAG));
678 return SU;
679}
680
681/// Update the scheduler's state after scheduling a node. This is the same node
Sergei Larinef4cc112012-09-10 17:31:34 +0000682/// that was just returned by pickNode(). However, VLIWMachineScheduler needs
683/// to update it's state based on the current cycle before MachineSchedStrategy
684/// does.
Sergei Larin4d8986a2012-09-04 14:49:56 +0000685void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
686 if (IsTopNode) {
687 SU->TopReadyCycle = Top.CurrCycle;
688 Top.bumpNode(SU);
Sergei Larinef4cc112012-09-10 17:31:34 +0000689 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000690 SU->BotReadyCycle = Bot.CurrCycle;
691 Bot.bumpNode(SU);
692 }
693}