blob: 97c626fdf7af1f36354e33aadfe9b10b03d3e55f [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
Sergei Larin4d8986a2012-09-04 14:49:56 +000015#include "HexagonMachineScheduler.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000016#include "llvm/CodeGen/MachineLoopInfo.h"
17#include "llvm/IR/Function.h"
Sergei Larin4d8986a2012-09-04 14:49:56 +000018
19using namespace llvm;
20
Chandler Carruth84e68b22014-04-22 02:41:26 +000021#define DEBUG_TYPE "misched"
22
Alp Tokercf218752014-06-30 18:57:16 +000023/// Platform-specific modifications to DAG.
Sergei Larin2db64a72012-09-14 15:07:59 +000024void VLIWMachineScheduler::postprocessDAG() {
Craig Topper062a2ba2014-04-25 05:30:21 +000025 SUnit* LastSequentialCall = nullptr;
Sergei Larin2db64a72012-09-14 15:07:59 +000026 // 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:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000111 case TargetOpcode::CFI_INSTRUCTION:
Sergei Larin4d8986a2012-09-04 14:49:56 +0000112 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()
Alexey Samsonov8968e6d2014-08-20 19:36:05 +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
Alp Tokercf218752014-06-30 18:57:16 +0000153 // Postprocess the DAG to add platform-specific artificial dependencies.
Sergei Larin2db64a72012-09-14 15:07:59 +0000154 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);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000189
190 // Notify the scheduling strategy after updating the DAG.
191 SchedImpl->schedNode(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000192 }
193 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
194
Sergei Larin4d8986a2012-09-04 14:49:56 +0000195 placeDebugValues();
196}
197
Andrew Trick7a8e1002012-09-11 00:39:15 +0000198void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
199 DAG = static_cast<VLIWMachineScheduler*>(dag);
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000200 SchedModel = DAG->getSchedModel();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000201
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000202 Top.init(DAG, SchedModel);
203 Bot.init(DAG, SchedModel);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000204
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000205 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
206 // are disabled, then these HazardRecs will be disabled.
207 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000208 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000209 delete Top.HazardRec;
210 delete Bot.HazardRec;
Eric Christopherd9134482014-08-04 21:25:23 +0000211 Top.HazardRec =
212 TM.getSubtargetImpl()->getInstrInfo()->CreateTargetMIHazardRecognizer(
213 Itin, DAG);
214 Bot.HazardRec =
215 TM.getSubtargetImpl()->getInstrInfo()->CreateTargetMIHazardRecognizer(
216 Itin, DAG);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000217
Chandler Carruthc18e39c2013-07-27 10:48:45 +0000218 delete Top.ResourceModel;
219 delete Bot.ResourceModel;
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000220 Top.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
221 Bot.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
Sergei Larinef4cc112012-09-10 17:31:34 +0000222
Andrew Trick7a8e1002012-09-11 00:39:15 +0000223 assert((!llvm::ForceTopDown || !llvm::ForceBottomUp) &&
Sergei Larin4d8986a2012-09-04 14:49:56 +0000224 "-misched-topdown incompatible with -misched-bottomup");
225}
226
227void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
228 if (SU->isScheduled)
229 return;
230
231 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
232 I != E; ++I) {
233 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickde2109e2013-06-15 04:49:57 +0000234 unsigned MinLatency = I->getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000235#ifndef NDEBUG
236 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
237#endif
238 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
239 SU->TopReadyCycle = PredReadyCycle + MinLatency;
240 }
241 Top.releaseNode(SU, SU->TopReadyCycle);
242}
243
244void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
245 if (SU->isScheduled)
246 return;
247
248 assert(SU->getInstr() && "Scheduled SUnit must have instr");
249
250 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
251 I != E; ++I) {
252 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickde2109e2013-06-15 04:49:57 +0000253 unsigned MinLatency = I->getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000254#ifndef NDEBUG
255 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
256#endif
257 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
258 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
259 }
260 Bot.releaseNode(SU, SU->BotReadyCycle);
261}
262
263/// Does this SU have a hazard within the current instruction group.
264///
265/// The scheduler supports two modes of hazard recognition. The first is the
266/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
267/// supports highly complicated in-order reservation tables
268/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
269///
270/// The second is a streamlined mechanism that checks for hazards based on
271/// simple counters that the scheduler itself maintains. It explicitly checks
272/// for instruction dispatch limitations, including the number of micro-ops that
273/// can dispatch per cycle.
274///
275/// TODO: Also check whether the SU must start a new group.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000276bool ConvergingVLIWScheduler::VLIWSchedBoundary::checkHazard(SUnit *SU) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000277 if (HazardRec->isEnabled())
278 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
279
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000280 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
281 if (IssueCount + uops > SchedModel->getIssueWidth())
Sergei Larin4d8986a2012-09-04 14:49:56 +0000282 return true;
283
284 return false;
285}
286
Andrew Trickd7f890e2013-12-28 21:56:47 +0000287void ConvergingVLIWScheduler::VLIWSchedBoundary::releaseNode(SUnit *SU,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000288 unsigned ReadyCycle) {
289 if (ReadyCycle < MinReadyCycle)
290 MinReadyCycle = ReadyCycle;
291
292 // Check for interlocks first. For the purpose of other heuristics, an
293 // instruction that cannot issue appears as if it's not in the ReadyQueue.
294 if (ReadyCycle > CurrCycle || checkHazard(SU))
295
296 Pending.push(SU);
297 else
298 Available.push(SU);
299}
300
301/// Move the boundary of scheduled code by one cycle.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000302void ConvergingVLIWScheduler::VLIWSchedBoundary::bumpCycle() {
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000303 unsigned Width = SchedModel->getIssueWidth();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000304 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
305
306 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
307 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
308
309 if (!HazardRec->isEnabled()) {
310 // Bypass HazardRec virtual calls.
311 CurrCycle = NextCycle;
Sergei Larinef4cc112012-09-10 17:31:34 +0000312 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000313 // Bypass getHazardType calls in case of long latency.
314 for (; CurrCycle != NextCycle; ++CurrCycle) {
315 if (isTop())
316 HazardRec->AdvanceCycle();
317 else
318 HazardRec->RecedeCycle();
319 }
320 }
321 CheckPending = true;
322
323 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
324 << CurrCycle << '\n');
325}
326
327/// Move the boundary of scheduled code by one SUnit.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000328void ConvergingVLIWScheduler::VLIWSchedBoundary::bumpNode(SUnit *SU) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000329 bool startNewCycle = false;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000330
331 // Update the reservation table.
332 if (HazardRec->isEnabled()) {
333 if (!isTop() && SU->isCall) {
334 // Calls are scheduled with their preceding instructions. For bottom-up
335 // scheduling, clear the pipeline state before emitting.
336 HazardRec->Reset();
337 }
338 HazardRec->EmitInstruction(SU);
339 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000340
341 // Update DFA model.
342 startNewCycle = ResourceModel->reserveResources(SU);
343
Sergei Larin4d8986a2012-09-04 14:49:56 +0000344 // Check the instruction group dispatch limit.
345 // TODO: Check if this SU must end a dispatch group.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000346 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Sergei Larinef4cc112012-09-10 17:31:34 +0000347 if (startNewCycle) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000348 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
349 bumpCycle();
350 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000351 else
352 DEBUG(dbgs() << "*** IssueCount " << IssueCount
353 << " at cycle " << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000354}
355
356/// Release pending ready nodes in to the available queue. This makes them
357/// visible to heuristics.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000358void ConvergingVLIWScheduler::VLIWSchedBoundary::releasePending() {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000359 // If the available queue is empty, it is safe to reset MinReadyCycle.
360 if (Available.empty())
361 MinReadyCycle = UINT_MAX;
362
363 // Check to see if any of the pending instructions are ready to issue. If
364 // so, add them to the available queue.
365 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
366 SUnit *SU = *(Pending.begin()+i);
367 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
368
369 if (ReadyCycle < MinReadyCycle)
370 MinReadyCycle = ReadyCycle;
371
372 if (ReadyCycle > CurrCycle)
373 continue;
374
375 if (checkHazard(SU))
376 continue;
377
378 Available.push(SU);
379 Pending.remove(Pending.begin()+i);
380 --i; --e;
381 }
382 CheckPending = false;
383}
384
385/// Remove SU from the ready set for this boundary.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000386void ConvergingVLIWScheduler::VLIWSchedBoundary::removeReady(SUnit *SU) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000387 if (Available.isInQueue(SU))
388 Available.remove(Available.find(SU));
389 else {
390 assert(Pending.isInQueue(SU) && "bad ready count");
391 Pending.remove(Pending.find(SU));
392 }
393}
394
395/// If this queue only has one ready candidate, return it. As a side effect,
396/// advance the cycle until at least one node is ready. If multiple instructions
397/// are ready, return NULL.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000398SUnit *ConvergingVLIWScheduler::VLIWSchedBoundary::pickOnlyChoice() {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000399 if (CheckPending)
400 releasePending();
401
402 for (unsigned i = 0; Available.empty(); ++i) {
403 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
404 "permanent hazard"); (void)i;
Craig Topper062a2ba2014-04-25 05:30:21 +0000405 ResourceModel->reserveResources(nullptr);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000406 bumpCycle();
407 releasePending();
408 }
409 if (Available.size() == 1)
410 return *Available.begin();
Craig Topper062a2ba2014-04-25 05:30:21 +0000411 return nullptr;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000412}
413
414#ifndef NDEBUG
Sergei Larinef4cc112012-09-10 17:31:34 +0000415void ConvergingVLIWScheduler::traceCandidate(const char *Label,
416 const ReadyQueue &Q,
Andrew Trick1a831342013-08-30 03:49:48 +0000417 SUnit *SU, PressureChange P) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000418 dbgs() << Label << " " << Q.getName() << " ";
419 if (P.isValid())
Andrew Trick1a831342013-08-30 03:49:48 +0000420 dbgs() << DAG->TRI->getRegPressureSetName(P.getPSet()) << ":"
421 << P.getUnitInc() << " ";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000422 else
423 dbgs() << " ";
424 SU->dump(DAG);
425}
426#endif
427
Sergei Larinef4cc112012-09-10 17:31:34 +0000428/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
429/// of SU, return it, otherwise return null.
430static SUnit *getSingleUnscheduledPred(SUnit *SU) {
Craig Topper062a2ba2014-04-25 05:30:21 +0000431 SUnit *OnlyAvailablePred = nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000432 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
433 I != E; ++I) {
434 SUnit &Pred = *I->getSUnit();
435 if (!Pred.isScheduled) {
436 // We found an available, but not scheduled, predecessor. If it's the
437 // only one we have found, keep track of it... otherwise give up.
438 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
Craig Topper062a2ba2014-04-25 05:30:21 +0000439 return nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000440 OnlyAvailablePred = &Pred;
441 }
442 }
443 return OnlyAvailablePred;
444}
445
446/// getSingleUnscheduledSucc - If there is exactly one unscheduled successor
447/// of SU, return it, otherwise return null.
448static SUnit *getSingleUnscheduledSucc(SUnit *SU) {
Craig Topper062a2ba2014-04-25 05:30:21 +0000449 SUnit *OnlyAvailableSucc = nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000450 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
451 I != E; ++I) {
452 SUnit &Succ = *I->getSUnit();
453 if (!Succ.isScheduled) {
454 // We found an available, but not scheduled, successor. If it's the
455 // only one we have found, keep track of it... otherwise give up.
456 if (OnlyAvailableSucc && OnlyAvailableSucc != &Succ)
Craig Topper062a2ba2014-04-25 05:30:21 +0000457 return nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000458 OnlyAvailableSucc = &Succ;
459 }
460 }
461 return OnlyAvailableSucc;
462}
463
Sergei Larin4d8986a2012-09-04 14:49:56 +0000464// Constants used to denote relative importance of
465// heuristic components for cost computation.
466static const unsigned PriorityOne = 200;
Eli Friedman8f06d552013-09-11 00:41:02 +0000467static const unsigned PriorityTwo = 50;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000468static const unsigned ScaleTwo = 10;
469static const unsigned FactorOne = 2;
470
471/// Single point to compute overall scheduling cost.
472/// TODO: More heuristics will be used soon.
473int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
474 SchedCandidate &Candidate,
475 RegPressureDelta &Delta,
476 bool verbose) {
477 // Initial trivial priority.
478 int ResCount = 1;
479
480 // Do not waste time on a node that is already scheduled.
481 if (!SU || SU->isScheduled)
482 return ResCount;
483
484 // Forced priority is high.
485 if (SU->isScheduleHigh)
486 ResCount += PriorityOne;
487
488 // Critical path first.
Sergei Larinef4cc112012-09-10 17:31:34 +0000489 if (Q.getID() == TopQID) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000490 ResCount += (SU->getHeight() * ScaleTwo);
Sergei Larinef4cc112012-09-10 17:31:34 +0000491
492 // If resources are available for it, multiply the
493 // chance of scheduling.
494 if (Top.ResourceModel->isResourceAvailable(SU))
495 ResCount <<= FactorOne;
496 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000497 ResCount += (SU->getDepth() * ScaleTwo);
498
Sergei Larinef4cc112012-09-10 17:31:34 +0000499 // If resources are available for it, multiply the
500 // chance of scheduling.
501 if (Bot.ResourceModel->isResourceAvailable(SU))
502 ResCount <<= FactorOne;
503 }
504
505 unsigned NumNodesBlocking = 0;
506 if (Q.getID() == TopQID) {
507 // How many SUs does it block from scheduling?
508 // Look at all of the successors of this node.
509 // Count the number of nodes that
510 // this node is the sole unscheduled node for.
511 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
512 I != E; ++I)
513 if (getSingleUnscheduledPred(I->getSUnit()) == SU)
514 ++NumNodesBlocking;
515 } else {
516 // How many unscheduled predecessors block this node?
517 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
518 I != E; ++I)
519 if (getSingleUnscheduledSucc(I->getSUnit()) == SU)
520 ++NumNodesBlocking;
521 }
522 ResCount += (NumNodesBlocking * ScaleTwo);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000523
524 // Factor in reg pressure as a heuristic.
Eli Friedman8f06d552013-09-11 00:41:02 +0000525 ResCount -= (Delta.Excess.getUnitInc()*PriorityTwo);
526 ResCount -= (Delta.CriticalMax.getUnitInc()*PriorityTwo);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000527
528 DEBUG(if (verbose) dbgs() << " Total(" << ResCount << ")");
529
530 return ResCount;
531}
532
533/// Pick the best candidate from the top queue.
534///
535/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
536/// DAG building. To adjust for the current scheduling location we need to
537/// maintain the number of vreg uses remaining to be top-scheduled.
538ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
539pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
540 SchedCandidate &Candidate) {
541 DEBUG(Q.dump());
542
543 // getMaxPressureDelta temporarily modifies the tracker.
544 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
545
546 // BestSU remains NULL if no top candidates beat the best existing candidate.
547 CandResult FoundCandidate = NoCand;
548 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
549 RegPressureDelta RPDelta;
550 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
551 DAG->getRegionCriticalPSets(),
552 DAG->getRegPressure().MaxSetPressure);
553
554 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
555
556 // Initialize the candidate if needed.
557 if (!Candidate.SU) {
558 Candidate.SU = *I;
559 Candidate.RPDelta = RPDelta;
560 Candidate.SCost = CurrentCost;
561 FoundCandidate = NodeOrder;
562 continue;
563 }
564
Sergei Larin4d8986a2012-09-04 14:49:56 +0000565 // Best cost.
566 if (CurrentCost > Candidate.SCost) {
567 DEBUG(traceCandidate("CCAND", Q, *I));
568 Candidate.SU = *I;
569 Candidate.RPDelta = RPDelta;
570 Candidate.SCost = CurrentCost;
571 FoundCandidate = BestCost;
572 continue;
573 }
574
575 // Fall through to original instruction order.
576 // Only consider node order if Candidate was chosen from this Q.
577 if (FoundCandidate == NoCand)
578 continue;
579 }
580 return FoundCandidate;
581}
582
583/// Pick the best candidate node from either the top or bottom queue.
584SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
585 // Schedule as far as possible in the direction of no choice. This is most
586 // efficient, but also provides the best heuristics for CriticalPSets.
587 if (SUnit *SU = Bot.pickOnlyChoice()) {
588 IsTopNode = false;
589 return SU;
590 }
591 if (SUnit *SU = Top.pickOnlyChoice()) {
592 IsTopNode = true;
593 return SU;
594 }
595 SchedCandidate BotCand;
596 // Prefer bottom scheduling when heuristics are silent.
597 CandResult BotResult = pickNodeFromQueue(Bot.Available,
598 DAG->getBotRPTracker(), BotCand);
599 assert(BotResult != NoCand && "failed to find the first candidate");
600
601 // If either Q has a single candidate that provides the least increase in
602 // Excess pressure, we can immediately schedule from that Q.
603 //
604 // RegionCriticalPSets summarizes the pressure within the scheduled region and
605 // affects picking from either Q. If scheduling in one direction must
606 // increase pressure for one of the excess PSets, then schedule in that
607 // direction first to provide more freedom in the other direction.
608 if (BotResult == SingleExcess || BotResult == SingleCritical) {
609 IsTopNode = false;
610 return BotCand.SU;
611 }
612 // Check if the top Q has a better candidate.
613 SchedCandidate TopCand;
614 CandResult TopResult = pickNodeFromQueue(Top.Available,
615 DAG->getTopRPTracker(), TopCand);
616 assert(TopResult != NoCand && "failed to find the first candidate");
617
618 if (TopResult == SingleExcess || TopResult == SingleCritical) {
619 IsTopNode = true;
620 return TopCand.SU;
621 }
622 // If either Q has a single candidate that minimizes pressure above the
623 // original region's pressure pick it.
624 if (BotResult == SingleMax) {
625 IsTopNode = false;
626 return BotCand.SU;
627 }
628 if (TopResult == SingleMax) {
629 IsTopNode = true;
630 return TopCand.SU;
631 }
632 if (TopCand.SCost > BotCand.SCost) {
633 IsTopNode = true;
634 return TopCand.SU;
635 }
636 // Otherwise prefer the bottom candidate in node order.
637 IsTopNode = false;
638 return BotCand.SU;
639}
640
641/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
642SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
643 if (DAG->top() == DAG->bottom()) {
644 assert(Top.Available.empty() && Top.Pending.empty() &&
645 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topper062a2ba2014-04-25 05:30:21 +0000646 return nullptr;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000647 }
648 SUnit *SU;
Andrew Trick7a8e1002012-09-11 00:39:15 +0000649 if (llvm::ForceTopDown) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000650 SU = Top.pickOnlyChoice();
651 if (!SU) {
652 SchedCandidate TopCand;
653 CandResult TopResult =
654 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
655 assert(TopResult != NoCand && "failed to find the first candidate");
656 (void)TopResult;
657 SU = TopCand.SU;
658 }
659 IsTopNode = true;
Andrew Trick7a8e1002012-09-11 00:39:15 +0000660 } else if (llvm::ForceBottomUp) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000661 SU = Bot.pickOnlyChoice();
662 if (!SU) {
663 SchedCandidate BotCand;
664 CandResult BotResult =
665 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
666 assert(BotResult != NoCand && "failed to find the first candidate");
667 (void)BotResult;
668 SU = BotCand.SU;
669 }
670 IsTopNode = false;
671 } else {
672 SU = pickNodeBidrectional(IsTopNode);
673 }
674 if (SU->isTopReady())
675 Top.removeReady(SU);
676 if (SU->isBottomReady())
677 Bot.removeReady(SU);
678
679 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
680 << " Scheduling Instruction in cycle "
681 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
682 SU->dump(DAG));
683 return SU;
684}
685
686/// Update the scheduler's state after scheduling a node. This is the same node
Sergei Larinef4cc112012-09-10 17:31:34 +0000687/// that was just returned by pickNode(). However, VLIWMachineScheduler needs
688/// to update it's state based on the current cycle before MachineSchedStrategy
689/// does.
Sergei Larin4d8986a2012-09-04 14:49:56 +0000690void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
691 if (IsTopNode) {
692 SU->TopReadyCycle = Top.CurrCycle;
693 Top.bumpNode(SU);
Sergei Larinef4cc112012-09-10 17:31:34 +0000694 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000695 SU->BotReadyCycle = Bot.CurrCycle;
696 Bot.bumpNode(SU);
697 }
698}