blob: 4376a30fdd9854cc5304b800def6150cf79c00fc [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"
Eugene Zelenko3b873362017-09-28 22:27:31 +000016#include "HexagonInstrInfo.h"
Krzysztof Parzyszek9be66732016-07-15 17:48:09 +000017#include "HexagonSubtarget.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/CodeGen/DFAPacketizer.h"
20#include "llvm/CodeGen/MachineBasicBlock.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstr.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +000024#include "llvm/CodeGen/RegisterClassInfo.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000025#include "llvm/CodeGen/RegisterPressure.h"
26#include "llvm/CodeGen/ScheduleDAG.h"
27#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000028#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000029#include "llvm/CodeGen/TargetOpcodes.h"
30#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000031#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000032#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000033#include "llvm/IR/Function.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/raw_ostream.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000037#include <algorithm>
38#include <cassert>
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +000039#include <iomanip>
Eugene Zelenko3b873362017-09-28 22:27:31 +000040#include <limits>
41#include <memory>
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +000042#include <sstream>
43
Eugene Zelenko3b873362017-09-28 22:27:31 +000044using namespace llvm;
45
46#define DEBUG_TYPE "machine-scheduler"
47
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +000048static cl::opt<bool> IgnoreBBRegPressure("ignore-bb-reg-pressure",
49 cl::Hidden, cl::ZeroOrMore, cl::init(false));
50
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +000051static cl::opt<bool> UseNewerCandidate("use-newer-candidate",
52 cl::Hidden, cl::ZeroOrMore, cl::init(true));
53
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +000054static cl::opt<unsigned> SchedDebugVerboseLevel("misched-verbose-level",
55 cl::Hidden, cl::ZeroOrMore, cl::init(1));
56
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +000057// Check if the scheduler should penalize instructions that are available to
58// early due to a zero-latency dependence.
59static cl::opt<bool> CheckEarlyAvail("check-early-avail", cl::Hidden,
60 cl::ZeroOrMore, cl::init(true));
61
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +000062// This value is used to determine if a register class is a high pressure set.
63// We compute the maximum number of registers needed and divided by the total
64// available. Then, we compare the result to this value.
65static cl::opt<float> RPThreshold("hexagon-reg-pressure", cl::Hidden,
66 cl::init(0.75f), cl::desc("High register pressure threhold."));
67
68/// Return true if there is a dependence between SUd and SUu.
69static bool hasDependence(const SUnit *SUd, const SUnit *SUu,
70 const HexagonInstrInfo &QII) {
71 if (SUd->Succs.size() == 0)
72 return false;
73
74 // Enable .cur formation.
75 if (QII.mayBeCurLoad(*SUd->getInstr()))
76 return false;
77
78 if (QII.canExecuteInBundle(*SUd->getInstr(), *SUu->getInstr()))
79 return false;
80
81 for (const auto &S : SUd->Succs) {
82 // Since we do not add pseudos to packets, might as well
83 // ignore order dependencies.
84 if (S.isCtrl())
85 continue;
86
87 if (S.getSUnit() == SUu && S.getLatency() > 0)
88 return true;
89 }
90 return false;
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +000091}
92
Sergei Larin4d8986a2012-09-04 14:49:56 +000093/// Check if scheduling of this SU is possible
94/// in the current packet.
95/// It is _not_ precise (statefull), it is more like
96/// another heuristic. Many corner cases are figured
97/// empirically.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +000098bool VLIWResourceModel::isResourceAvailable(SUnit *SU, bool IsTop) {
Sergei Larin4d8986a2012-09-04 14:49:56 +000099 if (!SU || !SU->getInstr())
100 return false;
101
102 // First see if the pipeline could receive this instruction
103 // in the current cycle.
104 switch (SU->getInstr()->getOpcode()) {
105 default:
Duncan P. N. Exon Smith57022872016-02-27 19:09:00 +0000106 if (!ResourcesModel->canReserveResources(*SU->getInstr()))
Sergei Larin4d8986a2012-09-04 14:49:56 +0000107 return false;
108 case TargetOpcode::EXTRACT_SUBREG:
109 case TargetOpcode::INSERT_SUBREG:
110 case TargetOpcode::SUBREG_TO_REG:
111 case TargetOpcode::REG_SEQUENCE:
112 case TargetOpcode::IMPLICIT_DEF:
113 case TargetOpcode::COPY:
114 case TargetOpcode::INLINEASM:
115 break;
116 }
117
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000118 MachineBasicBlock *MBB = SU->getInstr()->getParent();
119 auto &QST = MBB->getParent()->getSubtarget<HexagonSubtarget>();
120 const auto &QII = *QST.getInstrInfo();
Krzysztof Parzyszek786333f2016-07-18 16:05:27 +0000121
Sergei Larin4d8986a2012-09-04 14:49:56 +0000122 // Now see if there are no other dependencies to instructions already
123 // in the packet.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000124 if (IsTop) {
125 for (unsigned i = 0, e = Packet.size(); i != e; ++i)
126 if (hasDependence(Packet[i], SU, QII))
Sergei Larin4d8986a2012-09-04 14:49:56 +0000127 return false;
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000128 } else {
129 for (unsigned i = 0, e = Packet.size(); i != e; ++i)
130 if (hasDependence(SU, Packet[i], QII))
131 return false;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000132 }
133 return true;
134}
135
136/// Keep track of available resources.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000137bool VLIWResourceModel::reserveResources(SUnit *SU, bool IsTop) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000138 bool startNewCycle = false;
Sergei Larin2db64a72012-09-14 15:07:59 +0000139 // Artificially reset state.
140 if (!SU) {
141 ResourcesModel->clearResources();
142 Packet.clear();
143 TotalPackets++;
144 return false;
145 }
Krzysztof Parzyszek4c6b65f2018-03-20 17:03:27 +0000146 // If this SU does not fit in the packet or the packet is now full
Sergei Larin4d8986a2012-09-04 14:49:56 +0000147 // start a new one.
Krzysztof Parzyszek4c6b65f2018-03-20 17:03:27 +0000148 if (!isResourceAvailable(SU, IsTop) ||
149 Packet.size() >= SchedModel->getIssueWidth()) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000150 ResourcesModel->clearResources();
151 Packet.clear();
152 TotalPackets++;
Sergei Larinef4cc112012-09-10 17:31:34 +0000153 startNewCycle = true;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000154 }
155
156 switch (SU->getInstr()->getOpcode()) {
157 default:
Duncan P. N. Exon Smith57022872016-02-27 19:09:00 +0000158 ResourcesModel->reserveResources(*SU->getInstr());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000159 break;
160 case TargetOpcode::EXTRACT_SUBREG:
161 case TargetOpcode::INSERT_SUBREG:
162 case TargetOpcode::SUBREG_TO_REG:
163 case TargetOpcode::REG_SEQUENCE:
164 case TargetOpcode::IMPLICIT_DEF:
165 case TargetOpcode::KILL:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000166 case TargetOpcode::CFI_INSTRUCTION:
Sergei Larin4d8986a2012-09-04 14:49:56 +0000167 case TargetOpcode::EH_LABEL:
168 case TargetOpcode::COPY:
169 case TargetOpcode::INLINEASM:
170 break;
171 }
172 Packet.push_back(SU);
173
174#ifndef NDEBUG
175 DEBUG(dbgs() << "Packet[" << TotalPackets << "]:\n");
176 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
177 DEBUG(dbgs() << "\t[" << i << "] SU(");
Sergei Larinef4cc112012-09-10 17:31:34 +0000178 DEBUG(dbgs() << Packet[i]->NodeNum << ")\t");
179 DEBUG(Packet[i]->getInstr()->dump());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000180 }
181#endif
182
Sergei Larinef4cc112012-09-10 17:31:34 +0000183 return startNewCycle;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000184}
185
Sergei Larin4d8986a2012-09-04 14:49:56 +0000186/// schedule - Called back from MachineScheduler::runOnMachineFunction
187/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
188/// only includes instructions that have DAG nodes, not scheduling boundaries.
189void VLIWMachineScheduler::schedule() {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000190 DEBUG(dbgs() << "********** MI Converging Scheduling VLIW "
191 << printMBBReference(*BB) << " " << BB->getName() << " in_func "
Matthias Braunf1caa282017-12-15 22:22:58 +0000192 << BB->getParent()->getName() << " at loop depth "
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000193 << MLI->getLoopDepth(BB) << " \n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000194
Andrew Trick7a8e1002012-09-11 00:39:15 +0000195 buildDAGWithRegPressure();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000196
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000197 Topo.InitDAGTopologicalSorting();
198
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000199 // Postprocess the DAG to add platform-specific artificial dependencies.
200 postprocessDAG();
201
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000202 SmallVector<SUnit*, 8> TopRoots, BotRoots;
203 findRootsAndBiasEdges(TopRoots, BotRoots);
204
205 // Initialize the strategy before modifying the DAG.
206 SchedImpl->initialize(this);
207
Sergei Larinef4cc112012-09-10 17:31:34 +0000208 DEBUG(unsigned maxH = 0;
209 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
210 if (SUnits[su].getHeight() > maxH)
211 maxH = SUnits[su].getHeight();
212 dbgs() << "Max Height " << maxH << "\n";);
213 DEBUG(unsigned maxD = 0;
214 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
215 if (SUnits[su].getDepth() > maxD)
216 maxD = SUnits[su].getDepth();
217 dbgs() << "Max Depth " << maxD << "\n";);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000218 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
219 SUnits[su].dumpAll(this));
220
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000221 initQueues(TopRoots, BotRoots);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000222
Sergei Larin4d8986a2012-09-04 14:49:56 +0000223 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000224 while (true) {
225 DEBUG(dbgs() << "** VLIWMachineScheduler::schedule picking next node\n");
226 SUnit *SU = SchedImpl->pickNode(IsTopNode);
227 if (!SU) break;
228
Sergei Larin4d8986a2012-09-04 14:49:56 +0000229 if (!checkSchedLimit())
230 break;
231
Andrew Trick7a8e1002012-09-11 00:39:15 +0000232 scheduleMI(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000233
Andrew Trickd7f890e2013-12-28 21:56:47 +0000234 // Notify the scheduling strategy after updating the DAG.
235 SchedImpl->schedNode(SU, IsTopNode);
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000236
237 updateQueues(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000238 }
239 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
240
Sergei Larin4d8986a2012-09-04 14:49:56 +0000241 placeDebugValues();
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000242
243 DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000244 dbgs() << "*** Final schedule for "
245 << printMBBReference(*begin()->getParent()) << " ***\n";
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000246 dumpSchedule();
247 dbgs() << '\n';
248 });
Sergei Larin4d8986a2012-09-04 14:49:56 +0000249}
250
Andrew Trick7a8e1002012-09-11 00:39:15 +0000251void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
252 DAG = static_cast<VLIWMachineScheduler*>(dag);
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000253 SchedModel = DAG->getSchedModel();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000254
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000255 Top.init(DAG, SchedModel);
256 Bot.init(DAG, SchedModel);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000257
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000258 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
259 // are disabled, then these HazardRecs will be disabled.
260 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000261 const TargetSubtargetInfo &STI = DAG->MF.getSubtarget();
262 const TargetInstrInfo *TII = STI.getInstrInfo();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000263 delete Top.HazardRec;
264 delete Bot.HazardRec;
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000265 Top.HazardRec = TII->CreateTargetMIHazardRecognizer(Itin, DAG);
266 Bot.HazardRec = TII->CreateTargetMIHazardRecognizer(Itin, DAG);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000267
Chandler Carruthc18e39c2013-07-27 10:48:45 +0000268 delete Top.ResourceModel;
269 delete Bot.ResourceModel;
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000270 Top.ResourceModel = new VLIWResourceModel(STI, DAG->getSchedModel());
271 Bot.ResourceModel = new VLIWResourceModel(STI, DAG->getSchedModel());
Sergei Larinef4cc112012-09-10 17:31:34 +0000272
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000273 const std::vector<unsigned> &MaxPressure =
274 DAG->getRegPressure().MaxSetPressure;
275 HighPressureSets.assign(MaxPressure.size(), 0);
276 for (unsigned i = 0, e = MaxPressure.size(); i < e; ++i) {
277 unsigned Limit = DAG->getRegClassInfo()->getRegPressureSetLimit(i);
278 HighPressureSets[i] =
Krzysztof Parzyszek2c4231d2018-03-20 13:28:46 +0000279 ((float) MaxPressure[i] > ((float) Limit * RPThreshold));
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000280 }
281
Eugene Zelenko3b873362017-09-28 22:27:31 +0000282 assert((!ForceTopDown || !ForceBottomUp) &&
Sergei Larin4d8986a2012-09-04 14:49:56 +0000283 "-misched-topdown incompatible with -misched-bottomup");
284}
285
286void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
287 if (SU->isScheduled)
288 return;
289
Krzysztof Parzyszek2be7ead2016-07-18 16:15:15 +0000290 for (const SDep &PI : SU->Preds) {
291 unsigned PredReadyCycle = PI.getSUnit()->TopReadyCycle;
292 unsigned MinLatency = PI.getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000293#ifndef NDEBUG
294 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
295#endif
296 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
297 SU->TopReadyCycle = PredReadyCycle + MinLatency;
298 }
299 Top.releaseNode(SU, SU->TopReadyCycle);
300}
301
302void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
303 if (SU->isScheduled)
304 return;
305
306 assert(SU->getInstr() && "Scheduled SUnit must have instr");
307
308 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
309 I != E; ++I) {
310 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickde2109e2013-06-15 04:49:57 +0000311 unsigned MinLatency = I->getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000312#ifndef NDEBUG
313 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
314#endif
315 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
316 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
317 }
318 Bot.releaseNode(SU, SU->BotReadyCycle);
319}
320
321/// Does this SU have a hazard within the current instruction group.
322///
323/// The scheduler supports two modes of hazard recognition. The first is the
324/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
325/// supports highly complicated in-order reservation tables
326/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
327///
328/// The second is a streamlined mechanism that checks for hazards based on
329/// simple counters that the scheduler itself maintains. It explicitly checks
330/// for instruction dispatch limitations, including the number of micro-ops that
331/// can dispatch per cycle.
332///
333/// TODO: Also check whether the SU must start a new group.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000334bool ConvergingVLIWScheduler::VLIWSchedBoundary::checkHazard(SUnit *SU) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000335 if (HazardRec->isEnabled())
336 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
337
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000338 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
339 if (IssueCount + uops > SchedModel->getIssueWidth())
Sergei Larin4d8986a2012-09-04 14:49:56 +0000340 return true;
341
342 return false;
343}
344
Andrew Trickd7f890e2013-12-28 21:56:47 +0000345void ConvergingVLIWScheduler::VLIWSchedBoundary::releaseNode(SUnit *SU,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000346 unsigned ReadyCycle) {
347 if (ReadyCycle < MinReadyCycle)
348 MinReadyCycle = ReadyCycle;
349
350 // Check for interlocks first. For the purpose of other heuristics, an
351 // instruction that cannot issue appears as if it's not in the ReadyQueue.
352 if (ReadyCycle > CurrCycle || checkHazard(SU))
353
354 Pending.push(SU);
355 else
356 Available.push(SU);
357}
358
359/// Move the boundary of scheduled code by one cycle.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000360void ConvergingVLIWScheduler::VLIWSchedBoundary::bumpCycle() {
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000361 unsigned Width = SchedModel->getIssueWidth();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000362 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
363
Eugene Zelenko3b873362017-09-28 22:27:31 +0000364 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
365 "MinReadyCycle uninitialized");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000366 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
367
368 if (!HazardRec->isEnabled()) {
369 // Bypass HazardRec virtual calls.
370 CurrCycle = NextCycle;
Sergei Larinef4cc112012-09-10 17:31:34 +0000371 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000372 // Bypass getHazardType calls in case of long latency.
373 for (; CurrCycle != NextCycle; ++CurrCycle) {
374 if (isTop())
375 HazardRec->AdvanceCycle();
376 else
377 HazardRec->RecedeCycle();
378 }
379 }
380 CheckPending = true;
381
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000382 DEBUG(dbgs() << "*** Next cycle " << Available.getName() << " cycle "
383 << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000384}
385
386/// Move the boundary of scheduled code by one SUnit.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000387void ConvergingVLIWScheduler::VLIWSchedBoundary::bumpNode(SUnit *SU) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000388 bool startNewCycle = false;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000389
390 // Update the reservation table.
391 if (HazardRec->isEnabled()) {
392 if (!isTop() && SU->isCall) {
393 // Calls are scheduled with their preceding instructions. For bottom-up
394 // scheduling, clear the pipeline state before emitting.
395 HazardRec->Reset();
396 }
397 HazardRec->EmitInstruction(SU);
398 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000399
400 // Update DFA model.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000401 startNewCycle = ResourceModel->reserveResources(SU, isTop());
Sergei Larinef4cc112012-09-10 17:31:34 +0000402
Sergei Larin4d8986a2012-09-04 14:49:56 +0000403 // Check the instruction group dispatch limit.
404 // TODO: Check if this SU must end a dispatch group.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000405 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Sergei Larinef4cc112012-09-10 17:31:34 +0000406 if (startNewCycle) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000407 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
408 bumpCycle();
409 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000410 else
411 DEBUG(dbgs() << "*** IssueCount " << IssueCount
412 << " at cycle " << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000413}
414
415/// Release pending ready nodes in to the available queue. This makes them
416/// visible to heuristics.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000417void ConvergingVLIWScheduler::VLIWSchedBoundary::releasePending() {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000418 // If the available queue is empty, it is safe to reset MinReadyCycle.
419 if (Available.empty())
Eugene Zelenko3b873362017-09-28 22:27:31 +0000420 MinReadyCycle = std::numeric_limits<unsigned>::max();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000421
422 // Check to see if any of the pending instructions are ready to issue. If
423 // so, add them to the available queue.
424 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
425 SUnit *SU = *(Pending.begin()+i);
426 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
427
428 if (ReadyCycle < MinReadyCycle)
429 MinReadyCycle = ReadyCycle;
430
431 if (ReadyCycle > CurrCycle)
432 continue;
433
434 if (checkHazard(SU))
435 continue;
436
437 Available.push(SU);
438 Pending.remove(Pending.begin()+i);
439 --i; --e;
440 }
441 CheckPending = false;
442}
443
444/// Remove SU from the ready set for this boundary.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000445void ConvergingVLIWScheduler::VLIWSchedBoundary::removeReady(SUnit *SU) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000446 if (Available.isInQueue(SU))
447 Available.remove(Available.find(SU));
448 else {
449 assert(Pending.isInQueue(SU) && "bad ready count");
450 Pending.remove(Pending.find(SU));
451 }
452}
453
454/// If this queue only has one ready candidate, return it. As a side effect,
455/// advance the cycle until at least one node is ready. If multiple instructions
456/// are ready, return NULL.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000457SUnit *ConvergingVLIWScheduler::VLIWSchedBoundary::pickOnlyChoice() {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000458 if (CheckPending)
459 releasePending();
460
Krzysztof Parzyszek73be83d2018-03-20 16:22:06 +0000461 auto AdvanceCycle = [this]() {
462 if (Available.empty())
463 return true;
464 if (Available.size() == 1 && Pending.size() > 0)
465 return !ResourceModel->isResourceAvailable(*Available.begin(), isTop()) ||
466 getWeakLeft(*Available.begin(), isTop()) != 0;
467 return false;
468 };
469 for (unsigned i = 0; AdvanceCycle(); ++i) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000470 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
471 "permanent hazard"); (void)i;
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000472 ResourceModel->reserveResources(nullptr, isTop());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000473 bumpCycle();
474 releasePending();
475 }
476 if (Available.size() == 1)
477 return *Available.begin();
Craig Topper062a2ba2014-04-25 05:30:21 +0000478 return nullptr;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000479}
480
481#ifndef NDEBUG
Sergei Larinef4cc112012-09-10 17:31:34 +0000482void ConvergingVLIWScheduler::traceCandidate(const char *Label,
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000483 const ReadyQueue &Q, SUnit *SU, int Cost, PressureChange P) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000484 dbgs() << Label << " " << Q.getName() << " ";
485 if (P.isValid())
Andrew Trick1a831342013-08-30 03:49:48 +0000486 dbgs() << DAG->TRI->getRegPressureSetName(P.getPSet()) << ":"
487 << P.getUnitInc() << " ";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000488 else
489 dbgs() << " ";
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000490 dbgs() << "cost(" << Cost << ")\t";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000491 SU->dump(DAG);
492}
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000493
494// Very detailed queue dump, to be used with higher verbosity levels.
495void ConvergingVLIWScheduler::readyQueueVerboseDump(
496 const RegPressureTracker &RPTracker, SchedCandidate &Candidate,
497 ReadyQueue &Q) {
498 RegPressureTracker &TempTracker = const_cast<RegPressureTracker &>(RPTracker);
499
500 dbgs() << ">>> " << Q.getName() << "\n";
501 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
502 RegPressureDelta RPDelta;
503 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
504 DAG->getRegionCriticalPSets(),
505 DAG->getRegPressure().MaxSetPressure);
506 std::stringstream dbgstr;
507 dbgstr << "SU(" << std::setw(3) << (*I)->NodeNum << ")";
508 dbgs() << dbgstr.str();
509 SchedulingCost(Q, *I, Candidate, RPDelta, true);
510 dbgs() << "\t";
511 (*I)->getInstr()->dump();
512 }
513 dbgs() << "\n";
514}
Sergei Larin4d8986a2012-09-04 14:49:56 +0000515#endif
516
Nirav Dave6a38cc62017-06-08 18:49:25 +0000517/// isSingleUnscheduledPred - If SU2 is the only unscheduled predecessor
518/// of SU, return true (we may have duplicates)
519static inline bool isSingleUnscheduledPred(SUnit *SU, SUnit *SU2) {
520 if (SU->NumPredsLeft == 0)
521 return false;
522
523 for (auto &Pred : SU->Preds) {
524 // We found an available, but not scheduled, predecessor.
525 if (!Pred.getSUnit()->isScheduled && (Pred.getSUnit() != SU2))
526 return false;
Sergei Larinef4cc112012-09-10 17:31:34 +0000527 }
Nirav Dave6a38cc62017-06-08 18:49:25 +0000528
529 return true;
Sergei Larinef4cc112012-09-10 17:31:34 +0000530}
531
Nirav Dave6a38cc62017-06-08 18:49:25 +0000532/// isSingleUnscheduledSucc - If SU2 is the only unscheduled successor
533/// of SU, return true (we may have duplicates)
534static inline bool isSingleUnscheduledSucc(SUnit *SU, SUnit *SU2) {
535 if (SU->NumSuccsLeft == 0)
536 return false;
537
538 for (auto &Succ : SU->Succs) {
539 // We found an available, but not scheduled, successor.
540 if (!Succ.getSUnit()->isScheduled && (Succ.getSUnit() != SU2))
541 return false;
Sergei Larinef4cc112012-09-10 17:31:34 +0000542 }
Nirav Dave6a38cc62017-06-08 18:49:25 +0000543 return true;
Sergei Larinef4cc112012-09-10 17:31:34 +0000544}
545
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000546/// Check if the instruction changes the register pressure of a register in the
547/// high pressure set. The function returns a negative value if the pressure
548/// decreases and a positive value is the pressure increases. If the instruction
549/// doesn't use a high pressure register or doesn't change the register
550/// pressure, then return 0.
551int ConvergingVLIWScheduler::pressureChange(const SUnit *SU, bool isBotUp) {
552 PressureDiff &PD = DAG->getPressureDiff(SU);
553 for (auto &P : PD) {
554 if (!P.isValid())
555 continue;
556 // The pressure differences are computed bottom-up, so the comparision for
557 // an increase is positive in the bottom direction, but negative in the
558 // top-down direction.
559 if (HighPressureSets[P.getPSet()])
560 return (isBotUp ? P.getUnitInc() : -P.getUnitInc());
561 }
562 return 0;
563}
564
Sergei Larin4d8986a2012-09-04 14:49:56 +0000565// Constants used to denote relative importance of
566// heuristic components for cost computation.
567static const unsigned PriorityOne = 200;
Eli Friedman8f06d552013-09-11 00:41:02 +0000568static const unsigned PriorityTwo = 50;
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000569static const unsigned PriorityThree = 75;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000570static const unsigned ScaleTwo = 10;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000571
572/// Single point to compute overall scheduling cost.
573/// TODO: More heuristics will be used soon.
574int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
575 SchedCandidate &Candidate,
576 RegPressureDelta &Delta,
577 bool verbose) {
578 // Initial trivial priority.
579 int ResCount = 1;
580
581 // Do not waste time on a node that is already scheduled.
582 if (!SU || SU->isScheduled)
583 return ResCount;
584
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000585 DEBUG(if (verbose) dbgs() << ((Q.getID() == TopQID) ? "(top|" : "(bot|"));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000586 // Forced priority is high.
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000587 if (SU->isScheduleHigh) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000588 ResCount += PriorityOne;
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000589 DEBUG(dbgs() << "H|");
590 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000591
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000592 unsigned IsAvailableAmt = 0;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000593 // Critical path first.
Sergei Larinef4cc112012-09-10 17:31:34 +0000594 if (Q.getID() == TopQID) {
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000595 if (Top.isLatencyBound(SU)) {
596 DEBUG(if (verbose) dbgs() << "LB|");
597 ResCount += (SU->getHeight() * ScaleTwo);
598 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000599
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000600 DEBUG(if (verbose) {
601 std::stringstream dbgstr;
602 dbgstr << "h" << std::setw(3) << SU->getHeight() << "|";
603 dbgs() << dbgstr.str();
604 });
605
Sergei Larinef4cc112012-09-10 17:31:34 +0000606 // If resources are available for it, multiply the
607 // chance of scheduling.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000608 if (Top.ResourceModel->isResourceAvailable(SU, true)) {
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000609 IsAvailableAmt = (PriorityTwo + PriorityThree);
610 ResCount += IsAvailableAmt;
611 DEBUG(if (verbose) dbgs() << "A|");
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000612 } else
613 DEBUG(if (verbose) dbgs() << " |");
Sergei Larinef4cc112012-09-10 17:31:34 +0000614 } else {
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000615 if (Bot.isLatencyBound(SU)) {
616 DEBUG(if (verbose) dbgs() << "LB|");
617 ResCount += (SU->getDepth() * ScaleTwo);
618 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000619
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000620 DEBUG(if (verbose) {
621 std::stringstream dbgstr;
622 dbgstr << "d" << std::setw(3) << SU->getDepth() << "|";
623 dbgs() << dbgstr.str();
624 });
625
Sergei Larinef4cc112012-09-10 17:31:34 +0000626 // If resources are available for it, multiply the
627 // chance of scheduling.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000628 if (Bot.ResourceModel->isResourceAvailable(SU, false)) {
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000629 IsAvailableAmt = (PriorityTwo + PriorityThree);
630 ResCount += IsAvailableAmt;
631 DEBUG(if (verbose) dbgs() << "A|");
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000632 } else
633 DEBUG(if (verbose) dbgs() << " |");
Sergei Larinef4cc112012-09-10 17:31:34 +0000634 }
635
636 unsigned NumNodesBlocking = 0;
637 if (Q.getID() == TopQID) {
638 // How many SUs does it block from scheduling?
639 // Look at all of the successors of this node.
640 // Count the number of nodes that
641 // this node is the sole unscheduled node for.
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000642 if (Top.isLatencyBound(SU))
643 for (const SDep &SI : SU->Succs)
644 if (isSingleUnscheduledPred(SI.getSUnit(), SU))
645 ++NumNodesBlocking;
Sergei Larinef4cc112012-09-10 17:31:34 +0000646 } else {
647 // How many unscheduled predecessors block this node?
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000648 if (Bot.isLatencyBound(SU))
649 for (const SDep &PI : SU->Preds)
650 if (isSingleUnscheduledSucc(PI.getSUnit(), SU))
651 ++NumNodesBlocking;
Sergei Larinef4cc112012-09-10 17:31:34 +0000652 }
653 ResCount += (NumNodesBlocking * ScaleTwo);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000654
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000655 DEBUG(if (verbose) {
656 std::stringstream dbgstr;
657 dbgstr << "blk " << std::setw(2) << NumNodesBlocking << ")|";
658 dbgs() << dbgstr.str();
659 });
660
Sergei Larin4d8986a2012-09-04 14:49:56 +0000661 // Factor in reg pressure as a heuristic.
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000662 if (!IgnoreBBRegPressure) {
663 // Decrease priority by the amount that register pressure exceeds the limit.
664 ResCount -= (Delta.Excess.getUnitInc()*PriorityOne);
665 // Decrease priority if register pressure exceeds the limit.
666 ResCount -= (Delta.CriticalMax.getUnitInc()*PriorityOne);
667 // Decrease priority slightly if register pressure would increase over the
668 // current maximum.
669 ResCount -= (Delta.CurrentMax.getUnitInc()*PriorityTwo);
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000670 // If there are register pressure issues, then we remove the value added for
671 // the instruction being available. The rationale is that we really don't
672 // want to schedule an instruction that causes a spill.
673 if (IsAvailableAmt && pressureChange(SU, Q.getID() != TopQID) > 0 &&
674 (Delta.Excess.getUnitInc() || Delta.CriticalMax.getUnitInc() ||
675 Delta.CurrentMax.getUnitInc()))
676 ResCount -= IsAvailableAmt;
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000677 DEBUG(if (verbose) {
678 dbgs() << "RP " << Delta.Excess.getUnitInc() << "/"
679 << Delta.CriticalMax.getUnitInc() <<"/"
680 << Delta.CurrentMax.getUnitInc() << ")|";
681 });
682 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000683
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000684 // Give a little extra priority to a .cur instruction if there is a resource
685 // available for it.
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000686 auto &QST = DAG->MF.getSubtarget<HexagonSubtarget>();
687 auto &QII = *QST.getInstrInfo();
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +0000688 if (SU->isInstr() && QII.mayBeCurLoad(*SU->getInstr())) {
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000689 if (Q.getID() == TopQID &&
690 Top.ResourceModel->isResourceAvailable(SU, true)) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000691 ResCount += PriorityTwo;
692 DEBUG(if (verbose) dbgs() << "C|");
693 } else if (Q.getID() == BotQID &&
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000694 Bot.ResourceModel->isResourceAvailable(SU, false)) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000695 ResCount += PriorityTwo;
696 DEBUG(if (verbose) dbgs() << "C|");
697 }
698 }
699
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000700 // Give preference to a zero latency instruction if the dependent
701 // instruction is in the current packet.
Krzysztof Parzyszek5ffd8082018-03-20 14:54:01 +0000702 if (Q.getID() == TopQID && getWeakLeft(SU, true) == 0) {
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000703 for (const SDep &PI : SU->Preds) {
704 if (!PI.getSUnit()->getInstr()->isPseudo() && PI.isAssignedRegDep() &&
705 PI.getLatency() == 0 &&
706 Top.ResourceModel->isInPacket(PI.getSUnit())) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000707 ResCount += PriorityThree;
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000708 DEBUG(if (verbose) dbgs() << "Z|");
709 }
710 }
Krzysztof Parzyszek5ffd8082018-03-20 14:54:01 +0000711 } else if (Q.getID() == BotQID && getWeakLeft(SU, false) == 0) {
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000712 for (const SDep &SI : SU->Succs) {
713 if (!SI.getSUnit()->getInstr()->isPseudo() && SI.isAssignedRegDep() &&
714 SI.getLatency() == 0 &&
715 Bot.ResourceModel->isInPacket(SI.getSUnit())) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000716 ResCount += PriorityThree;
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000717 DEBUG(if (verbose) dbgs() << "Z|");
718 }
719 }
720 }
721
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000722 // If the instruction has a non-zero latency dependence with an instruction in
723 // the current packet, then it should not be scheduled yet. The case occurs
724 // when the dependent instruction is scheduled in a new packet, so the
725 // scheduler updates the current cycle and pending instructions become
726 // available.
727 if (CheckEarlyAvail) {
728 if (Q.getID() == TopQID) {
729 for (const auto &PI : SU->Preds) {
730 if (PI.getLatency() > 0 &&
731 Top.ResourceModel->isInPacket(PI.getSUnit())) {
732 ResCount -= PriorityOne;
733 DEBUG(if (verbose) dbgs() << "D|");
734 }
735 }
736 } else {
737 for (const auto &SI : SU->Succs) {
738 if (SI.getLatency() > 0 &&
739 Bot.ResourceModel->isInPacket(SI.getSUnit())) {
740 ResCount -= PriorityOne;
741 DEBUG(if (verbose) dbgs() << "D|");
742 }
743 }
744 }
745 }
746
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000747 DEBUG(if (verbose) {
748 std::stringstream dbgstr;
749 dbgstr << "Total " << std::setw(4) << ResCount << ")";
750 dbgs() << dbgstr.str();
751 });
Sergei Larin4d8986a2012-09-04 14:49:56 +0000752
753 return ResCount;
754}
755
756/// Pick the best candidate from the top queue.
757///
758/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
759/// DAG building. To adjust for the current scheduling location we need to
760/// maintain the number of vreg uses remaining to be top-scheduled.
761ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000762pickNodeFromQueue(VLIWSchedBoundary &Zone, const RegPressureTracker &RPTracker,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000763 SchedCandidate &Candidate) {
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000764 ReadyQueue &Q = Zone.Available;
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000765 DEBUG(if (SchedDebugVerboseLevel > 1)
766 readyQueueVerboseDump(RPTracker, Candidate, Q);
767 else Q.dump(););
Sergei Larin4d8986a2012-09-04 14:49:56 +0000768
769 // getMaxPressureDelta temporarily modifies the tracker.
770 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
771
772 // BestSU remains NULL if no top candidates beat the best existing candidate.
773 CandResult FoundCandidate = NoCand;
774 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
775 RegPressureDelta RPDelta;
776 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
777 DAG->getRegionCriticalPSets(),
778 DAG->getRegPressure().MaxSetPressure);
779
780 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
781
782 // Initialize the candidate if needed.
783 if (!Candidate.SU) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000784 DEBUG(traceCandidate("DCAND", Q, *I, CurrentCost));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000785 Candidate.SU = *I;
786 Candidate.RPDelta = RPDelta;
787 Candidate.SCost = CurrentCost;
788 FoundCandidate = NodeOrder;
789 continue;
790 }
791
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000792 // Choose node order for negative cost candidates. There is no good
793 // candidate in this case.
794 if (CurrentCost < 0 && Candidate.SCost < 0) {
795 if ((Q.getID() == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)
796 || (Q.getID() == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
797 DEBUG(traceCandidate("NCAND", Q, *I, CurrentCost));
798 Candidate.SU = *I;
799 Candidate.RPDelta = RPDelta;
800 Candidate.SCost = CurrentCost;
801 FoundCandidate = NodeOrder;
802 }
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000803 continue;
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000804 }
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000805
Sergei Larin4d8986a2012-09-04 14:49:56 +0000806 // Best cost.
807 if (CurrentCost > Candidate.SCost) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000808 DEBUG(traceCandidate("CCAND", Q, *I, CurrentCost));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000809 Candidate.SU = *I;
810 Candidate.RPDelta = RPDelta;
811 Candidate.SCost = CurrentCost;
812 FoundCandidate = BestCost;
813 continue;
814 }
815
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000816 // Choose an instruction that does not depend on an artificial edge.
817 unsigned CurrWeak = getWeakLeft(*I, (Q.getID() == TopQID));
818 unsigned CandWeak = getWeakLeft(Candidate.SU, (Q.getID() == TopQID));
819 if (CurrWeak != CandWeak) {
820 if (CurrWeak < CandWeak) {
821 DEBUG(traceCandidate("WCAND", Q, *I, CurrentCost));
822 Candidate.SU = *I;
823 Candidate.RPDelta = RPDelta;
824 Candidate.SCost = CurrentCost;
825 FoundCandidate = Weak;
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000826 }
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000827 continue;
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000828 }
829
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000830 if (CurrentCost == Candidate.SCost && Zone.isLatencyBound(*I)) {
831 unsigned CurrSize, CandSize;
832 if (Q.getID() == TopQID) {
833 CurrSize = (*I)->Succs.size();
834 CandSize = Candidate.SU->Succs.size();
835 } else {
836 CurrSize = (*I)->Preds.size();
837 CandSize = Candidate.SU->Preds.size();
838 }
839 if (CurrSize > CandSize) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000840 DEBUG(traceCandidate("SPCAND", Q, *I, CurrentCost));
841 Candidate.SU = *I;
842 Candidate.RPDelta = RPDelta;
843 Candidate.SCost = CurrentCost;
844 FoundCandidate = BestCost;
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000845 }
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000846 // Keep the old candidate if it's a better candidate. That is, don't use
847 // the subsequent tie breaker.
848 if (CurrSize != CandSize)
849 continue;
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000850 }
851
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000852 // Tie breaker.
853 // To avoid scheduling indeterminism, we need a tie breaker
854 // for the case when cost is identical for two nodes.
855 if (UseNewerCandidate && CurrentCost == Candidate.SCost) {
856 if ((Q.getID() == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)
857 || (Q.getID() == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
858 DEBUG(traceCandidate("TCAND", Q, *I, CurrentCost));
859 Candidate.SU = *I;
860 Candidate.RPDelta = RPDelta;
861 Candidate.SCost = CurrentCost;
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000862 FoundCandidate = NodeOrder;
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000863 continue;
864 }
865 }
866
Sergei Larin4d8986a2012-09-04 14:49:56 +0000867 // Fall through to original instruction order.
868 // Only consider node order if Candidate was chosen from this Q.
869 if (FoundCandidate == NoCand)
870 continue;
871 }
872 return FoundCandidate;
873}
874
875/// Pick the best candidate node from either the top or bottom queue.
876SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
877 // Schedule as far as possible in the direction of no choice. This is most
878 // efficient, but also provides the best heuristics for CriticalPSets.
879 if (SUnit *SU = Bot.pickOnlyChoice()) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000880 DEBUG(dbgs() << "Picked only Bottom\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000881 IsTopNode = false;
882 return SU;
883 }
884 if (SUnit *SU = Top.pickOnlyChoice()) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000885 DEBUG(dbgs() << "Picked only Top\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000886 IsTopNode = true;
887 return SU;
888 }
889 SchedCandidate BotCand;
890 // Prefer bottom scheduling when heuristics are silent.
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000891 CandResult BotResult = pickNodeFromQueue(Bot,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000892 DAG->getBotRPTracker(), BotCand);
893 assert(BotResult != NoCand && "failed to find the first candidate");
894
895 // If either Q has a single candidate that provides the least increase in
896 // Excess pressure, we can immediately schedule from that Q.
897 //
898 // RegionCriticalPSets summarizes the pressure within the scheduled region and
899 // affects picking from either Q. If scheduling in one direction must
900 // increase pressure for one of the excess PSets, then schedule in that
901 // direction first to provide more freedom in the other direction.
902 if (BotResult == SingleExcess || BotResult == SingleCritical) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000903 DEBUG(dbgs() << "Prefered Bottom Node\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000904 IsTopNode = false;
905 return BotCand.SU;
906 }
907 // Check if the top Q has a better candidate.
908 SchedCandidate TopCand;
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000909 CandResult TopResult = pickNodeFromQueue(Top,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000910 DAG->getTopRPTracker(), TopCand);
911 assert(TopResult != NoCand && "failed to find the first candidate");
912
913 if (TopResult == SingleExcess || TopResult == SingleCritical) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000914 DEBUG(dbgs() << "Prefered Top Node\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000915 IsTopNode = true;
916 return TopCand.SU;
917 }
918 // If either Q has a single candidate that minimizes pressure above the
919 // original region's pressure pick it.
920 if (BotResult == SingleMax) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000921 DEBUG(dbgs() << "Prefered Bottom Node SingleMax\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000922 IsTopNode = false;
923 return BotCand.SU;
924 }
925 if (TopResult == SingleMax) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000926 DEBUG(dbgs() << "Prefered Top Node SingleMax\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000927 IsTopNode = true;
928 return TopCand.SU;
929 }
930 if (TopCand.SCost > BotCand.SCost) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000931 DEBUG(dbgs() << "Prefered Top Node Cost\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000932 IsTopNode = true;
933 return TopCand.SU;
934 }
935 // Otherwise prefer the bottom candidate in node order.
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000936 DEBUG(dbgs() << "Prefered Bottom in Node order\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000937 IsTopNode = false;
938 return BotCand.SU;
939}
940
941/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
942SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
943 if (DAG->top() == DAG->bottom()) {
944 assert(Top.Available.empty() && Top.Pending.empty() &&
945 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topper062a2ba2014-04-25 05:30:21 +0000946 return nullptr;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000947 }
948 SUnit *SU;
Eugene Zelenko3b873362017-09-28 22:27:31 +0000949 if (ForceTopDown) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000950 SU = Top.pickOnlyChoice();
951 if (!SU) {
952 SchedCandidate TopCand;
953 CandResult TopResult =
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000954 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000955 assert(TopResult != NoCand && "failed to find the first candidate");
956 (void)TopResult;
957 SU = TopCand.SU;
958 }
959 IsTopNode = true;
Eugene Zelenko3b873362017-09-28 22:27:31 +0000960 } else if (ForceBottomUp) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000961 SU = Bot.pickOnlyChoice();
962 if (!SU) {
963 SchedCandidate BotCand;
964 CandResult BotResult =
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000965 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000966 assert(BotResult != NoCand && "failed to find the first candidate");
967 (void)BotResult;
968 SU = BotCand.SU;
969 }
970 IsTopNode = false;
971 } else {
972 SU = pickNodeBidrectional(IsTopNode);
973 }
974 if (SU->isTopReady())
975 Top.removeReady(SU);
976 if (SU->isBottomReady())
977 Bot.removeReady(SU);
978
979 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000980 << " Scheduling instruction in cycle "
981 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << " (" <<
982 reportPackets() << ")\n";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000983 SU->dump(DAG));
984 return SU;
985}
986
987/// Update the scheduler's state after scheduling a node. This is the same node
Sergei Larinef4cc112012-09-10 17:31:34 +0000988/// that was just returned by pickNode(). However, VLIWMachineScheduler needs
989/// to update it's state based on the current cycle before MachineSchedStrategy
990/// does.
Sergei Larin4d8986a2012-09-04 14:49:56 +0000991void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
992 if (IsTopNode) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000993 Top.bumpNode(SU);
Krzysztof Parzyszek4c6b65f2018-03-20 17:03:27 +0000994 SU->TopReadyCycle = Top.CurrCycle;
Sergei Larinef4cc112012-09-10 17:31:34 +0000995 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000996 Bot.bumpNode(SU);
Krzysztof Parzyszek4c6b65f2018-03-20 17:03:27 +0000997 SU->BotReadyCycle = Bot.CurrCycle;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000998 }
999}