blob: 89f0a1c4dcbd03c6af6fc1a93a097ea365a94cfa [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"
Krzysztof Parzyszek9be66732016-07-15 17:48:09 +000016#include "HexagonSubtarget.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000017#include "llvm/CodeGen/MachineLoopInfo.h"
Krzysztof Parzyszek9be66732016-07-15 17:48:09 +000018#include "llvm/CodeGen/ScheduleDAGMutation.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000019#include "llvm/IR/Function.h"
Sergei Larin4d8986a2012-09-04 14:49:56 +000020
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +000021#include <iomanip>
22#include <sstream>
23
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +000024static cl::opt<bool> IgnoreBBRegPressure("ignore-bb-reg-pressure",
25 cl::Hidden, cl::ZeroOrMore, cl::init(false));
26
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000027static cl::opt<bool> SchedPredsCloser("sched-preds-closer",
28 cl::Hidden, cl::ZeroOrMore, cl::init(true));
29
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +000030static cl::opt<unsigned> SchedDebugVerboseLevel("misched-verbose-level",
31 cl::Hidden, cl::ZeroOrMore, cl::init(1));
32
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +000033static cl::opt<bool> TopUseShorterTie("top-use-shorter-tie",
34 cl::Hidden, cl::ZeroOrMore, cl::init(false));
35
36static cl::opt<bool> BotUseShorterTie("bot-use-shorter-tie",
37 cl::Hidden, cl::ZeroOrMore, cl::init(false));
38
39static cl::opt<bool> DisableTCTie("disable-tc-tie",
40 cl::Hidden, cl::ZeroOrMore, cl::init(false));
41
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000042static cl::opt<bool> SchedRetvalOptimization("sched-retval-optimization",
43 cl::Hidden, cl::ZeroOrMore, cl::init(true));
44
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +000045// Check if the scheduler should penalize instructions that are available to
46// early due to a zero-latency dependence.
47static cl::opt<bool> CheckEarlyAvail("check-early-avail", cl::Hidden,
48 cl::ZeroOrMore, cl::init(true));
49
Sergei Larin4d8986a2012-09-04 14:49:56 +000050using namespace llvm;
51
Chandler Carruth84e68b22014-04-22 02:41:26 +000052#define DEBUG_TYPE "misched"
53
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000054class HexagonCallMutation : public ScheduleDAGMutation {
55public:
56 void apply(ScheduleDAGInstrs *DAG) override;
57private:
58 bool shouldTFRICallBind(const HexagonInstrInfo &HII,
59 const SUnit &Inst1, const SUnit &Inst2) const;
60};
61
62// Check if a call and subsequent A2_tfrpi instructions should maintain
63// scheduling affinity. We are looking for the TFRI to be consumed in
64// the next instruction. This should help reduce the instances of
65// double register pairs being allocated and scheduled before a call
66// when not used until after the call. This situation is exacerbated
67// by the fact that we allocate the pair from the callee saves list,
68// leading to excess spills and restores.
69bool HexagonCallMutation::shouldTFRICallBind(const HexagonInstrInfo &HII,
70 const SUnit &Inst1, const SUnit &Inst2) const {
71 if (Inst1.getInstr()->getOpcode() != Hexagon::A2_tfrpi)
72 return false;
73
74 // TypeXTYPE are 64 bit operations.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +000075 if (HII.getType(*Inst2.getInstr()) == HexagonII::TypeXTYPE)
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000076 return true;
77 return false;
78}
79
80void HexagonCallMutation::apply(ScheduleDAGInstrs *DAG) {
Craig Topper062a2ba2014-04-25 05:30:21 +000081 SUnit* LastSequentialCall = nullptr;
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000082 unsigned VRegHoldingRet = 0;
83 unsigned RetRegister;
84 SUnit* LastUseOfRet = nullptr;
85 auto &TRI = *DAG->MF.getSubtarget().getRegisterInfo();
86 auto &HII = *DAG->MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
87
Sergei Larin2db64a72012-09-14 15:07:59 +000088 // Currently we only catch the situation when compare gets scheduled
89 // before preceding call.
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000090 for (unsigned su = 0, e = DAG->SUnits.size(); su != e; ++su) {
Sergei Larin2db64a72012-09-14 15:07:59 +000091 // Remember the call.
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000092 if (DAG->SUnits[su].getInstr()->isCall())
93 LastSequentialCall = &DAG->SUnits[su];
Sergei Larin2db64a72012-09-14 15:07:59 +000094 // Look for a compare that defines a predicate.
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000095 else if (DAG->SUnits[su].getInstr()->isCompare() && LastSequentialCall)
96 DAG->SUnits[su].addPred(SDep(LastSequentialCall, SDep::Barrier));
97 // Look for call and tfri* instructions.
98 else if (SchedPredsCloser && LastSequentialCall && su > 1 && su < e-1 &&
99 shouldTFRICallBind(HII, DAG->SUnits[su], DAG->SUnits[su+1]))
100 DAG->SUnits[su].addPred(SDep(&DAG->SUnits[su-1], SDep::Barrier));
101 // Prevent redundant register copies between two calls, which are caused by
102 // both the return value and the argument for the next call being in %R0.
103 // Example:
104 // 1: <call1>
105 // 2: %VregX = COPY %R0
106 // 3: <use of %VregX>
107 // 4: %R0 = ...
108 // 5: <call2>
109 // The scheduler would often swap 3 and 4, so an additional register is
110 // needed. This code inserts a Barrier dependence between 3 & 4 to prevent
111 // this. The same applies for %D0 and %V0/%W0, which are also handled.
112 else if (SchedRetvalOptimization) {
113 const MachineInstr *MI = DAG->SUnits[su].getInstr();
114 if (MI->isCopy() && (MI->readsRegister(Hexagon::R0, &TRI) ||
115 MI->readsRegister(Hexagon::V0, &TRI))) {
116 // %vregX = COPY %R0
117 VRegHoldingRet = MI->getOperand(0).getReg();
118 RetRegister = MI->getOperand(1).getReg();
119 LastUseOfRet = nullptr;
120 } else if (VRegHoldingRet && MI->readsVirtualRegister(VRegHoldingRet))
121 // <use of %vregX>
122 LastUseOfRet = &DAG->SUnits[su];
123 else if (LastUseOfRet && MI->definesRegister(RetRegister, &TRI))
124 // %R0 = ...
125 DAG->SUnits[su].addPred(SDep(LastUseOfRet, SDep::Barrier));
126 }
Sergei Larin2db64a72012-09-14 15:07:59 +0000127 }
128}
129
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +0000130
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000131/// Save the last formed packet
132void VLIWResourceModel::savePacket() {
133 OldPacket = Packet;
134}
135
Sergei Larin4d8986a2012-09-04 14:49:56 +0000136/// Check if scheduling of this SU is possible
137/// in the current packet.
138/// It is _not_ precise (statefull), it is more like
139/// another heuristic. Many corner cases are figured
140/// empirically.
141bool VLIWResourceModel::isResourceAvailable(SUnit *SU) {
142 if (!SU || !SU->getInstr())
143 return false;
144
145 // First see if the pipeline could receive this instruction
146 // in the current cycle.
147 switch (SU->getInstr()->getOpcode()) {
148 default:
Duncan P. N. Exon Smith57022872016-02-27 19:09:00 +0000149 if (!ResourcesModel->canReserveResources(*SU->getInstr()))
Sergei Larin4d8986a2012-09-04 14:49:56 +0000150 return false;
151 case TargetOpcode::EXTRACT_SUBREG:
152 case TargetOpcode::INSERT_SUBREG:
153 case TargetOpcode::SUBREG_TO_REG:
154 case TargetOpcode::REG_SEQUENCE:
155 case TargetOpcode::IMPLICIT_DEF:
156 case TargetOpcode::COPY:
157 case TargetOpcode::INLINEASM:
158 break;
159 }
160
Krzysztof Parzyszek786333f2016-07-18 16:05:27 +0000161 MachineFunction &MF = *SU->getInstr()->getParent()->getParent();
162 auto &QII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
163
Sergei Larin4d8986a2012-09-04 14:49:56 +0000164 // Now see if there are no other dependencies to instructions already
165 // in the packet.
166 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
167 if (Packet[i]->Succs.size() == 0)
168 continue;
Krzysztof Parzyszek786333f2016-07-18 16:05:27 +0000169
170 // Enable .cur formation.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +0000171 if (QII.mayBeCurLoad(*Packet[i]->getInstr()))
Krzysztof Parzyszek786333f2016-07-18 16:05:27 +0000172 continue;
173
Sergei Larin4d8986a2012-09-04 14:49:56 +0000174 for (SUnit::const_succ_iterator I = Packet[i]->Succs.begin(),
175 E = Packet[i]->Succs.end(); I != E; ++I) {
176 // Since we do not add pseudos to packets, might as well
177 // ignore order dependencies.
178 if (I->isCtrl())
179 continue;
180
181 if (I->getSUnit() == SU)
182 return false;
183 }
184 }
185 return true;
186}
187
188/// Keep track of available resources.
Sergei Larinef4cc112012-09-10 17:31:34 +0000189bool VLIWResourceModel::reserveResources(SUnit *SU) {
190 bool startNewCycle = false;
Sergei Larin2db64a72012-09-14 15:07:59 +0000191 // Artificially reset state.
192 if (!SU) {
193 ResourcesModel->clearResources();
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000194 savePacket();
Sergei Larin2db64a72012-09-14 15:07:59 +0000195 Packet.clear();
196 TotalPackets++;
197 return false;
198 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000199 // If this SU does not fit in the packet
200 // start a new one.
201 if (!isResourceAvailable(SU)) {
202 ResourcesModel->clearResources();
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000203 savePacket();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000204 Packet.clear();
205 TotalPackets++;
Sergei Larinef4cc112012-09-10 17:31:34 +0000206 startNewCycle = true;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000207 }
208
209 switch (SU->getInstr()->getOpcode()) {
210 default:
Duncan P. N. Exon Smith57022872016-02-27 19:09:00 +0000211 ResourcesModel->reserveResources(*SU->getInstr());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000212 break;
213 case TargetOpcode::EXTRACT_SUBREG:
214 case TargetOpcode::INSERT_SUBREG:
215 case TargetOpcode::SUBREG_TO_REG:
216 case TargetOpcode::REG_SEQUENCE:
217 case TargetOpcode::IMPLICIT_DEF:
218 case TargetOpcode::KILL:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000219 case TargetOpcode::CFI_INSTRUCTION:
Sergei Larin4d8986a2012-09-04 14:49:56 +0000220 case TargetOpcode::EH_LABEL:
221 case TargetOpcode::COPY:
222 case TargetOpcode::INLINEASM:
223 break;
224 }
225 Packet.push_back(SU);
226
227#ifndef NDEBUG
228 DEBUG(dbgs() << "Packet[" << TotalPackets << "]:\n");
229 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
230 DEBUG(dbgs() << "\t[" << i << "] SU(");
Sergei Larinef4cc112012-09-10 17:31:34 +0000231 DEBUG(dbgs() << Packet[i]->NodeNum << ")\t");
232 DEBUG(Packet[i]->getInstr()->dump());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000233 }
234#endif
235
236 // If packet is now full, reset the state so in the next cycle
237 // we start fresh.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000238 if (Packet.size() >= SchedModel->getIssueWidth()) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000239 ResourcesModel->clearResources();
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000240 savePacket();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000241 Packet.clear();
242 TotalPackets++;
Sergei Larinef4cc112012-09-10 17:31:34 +0000243 startNewCycle = true;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000244 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000245
246 return startNewCycle;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000247}
248
Sergei Larin4d8986a2012-09-04 14:49:56 +0000249/// schedule - Called back from MachineScheduler::runOnMachineFunction
250/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
251/// only includes instructions that have DAG nodes, not scheduling boundaries.
252void VLIWMachineScheduler::schedule() {
253 DEBUG(dbgs()
254 << "********** MI Converging Scheduling VLIW BB#" << BB->getNumber()
255 << " " << BB->getName()
256 << " in_func " << BB->getParent()->getFunction()->getName()
Alexey Samsonov8968e6d2014-08-20 19:36:05 +0000257 << " at loop depth " << MLI->getLoopDepth(BB)
Sergei Larin4d8986a2012-09-04 14:49:56 +0000258 << " \n");
259
Andrew Trick7a8e1002012-09-11 00:39:15 +0000260 buildDAGWithRegPressure();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000261
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000262 SmallVector<SUnit*, 8> TopRoots, BotRoots;
263 findRootsAndBiasEdges(TopRoots, BotRoots);
264
265 // Initialize the strategy before modifying the DAG.
266 SchedImpl->initialize(this);
267
Sergei Larinef4cc112012-09-10 17:31:34 +0000268 DEBUG(unsigned maxH = 0;
269 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
270 if (SUnits[su].getHeight() > maxH)
271 maxH = SUnits[su].getHeight();
272 dbgs() << "Max Height " << maxH << "\n";);
273 DEBUG(unsigned maxD = 0;
274 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
275 if (SUnits[su].getDepth() > maxD)
276 maxD = SUnits[su].getDepth();
277 dbgs() << "Max Depth " << maxD << "\n";);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000278 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
279 SUnits[su].dumpAll(this));
280
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000281 initQueues(TopRoots, BotRoots);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000282
Sergei Larin4d8986a2012-09-04 14:49:56 +0000283 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000284 while (true) {
285 DEBUG(dbgs() << "** VLIWMachineScheduler::schedule picking next node\n");
286 SUnit *SU = SchedImpl->pickNode(IsTopNode);
287 if (!SU) break;
288
Sergei Larin4d8986a2012-09-04 14:49:56 +0000289 if (!checkSchedLimit())
290 break;
291
Andrew Trick7a8e1002012-09-11 00:39:15 +0000292 scheduleMI(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000293
Andrew Trick7a8e1002012-09-11 00:39:15 +0000294 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000295
296 // Notify the scheduling strategy after updating the DAG.
297 SchedImpl->schedNode(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000298 }
299 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
300
Sergei Larin4d8986a2012-09-04 14:49:56 +0000301 placeDebugValues();
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000302
303 DEBUG({
304 unsigned BBNum = begin()->getParent()->getNumber();
305 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
306 dumpSchedule();
307 dbgs() << '\n';
308 });
Sergei Larin4d8986a2012-09-04 14:49:56 +0000309}
310
Andrew Trick7a8e1002012-09-11 00:39:15 +0000311void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
312 DAG = static_cast<VLIWMachineScheduler*>(dag);
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000313 SchedModel = DAG->getSchedModel();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000314
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000315 Top.init(DAG, SchedModel);
316 Bot.init(DAG, SchedModel);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000317
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000318 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
319 // are disabled, then these HazardRecs will be disabled.
320 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000321 const TargetSubtargetInfo &STI = DAG->MF.getSubtarget();
322 const TargetInstrInfo *TII = STI.getInstrInfo();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000323 delete Top.HazardRec;
324 delete Bot.HazardRec;
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000325 Top.HazardRec = TII->CreateTargetMIHazardRecognizer(Itin, DAG);
326 Bot.HazardRec = TII->CreateTargetMIHazardRecognizer(Itin, DAG);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000327
Chandler Carruthc18e39c2013-07-27 10:48:45 +0000328 delete Top.ResourceModel;
329 delete Bot.ResourceModel;
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000330 Top.ResourceModel = new VLIWResourceModel(STI, DAG->getSchedModel());
331 Bot.ResourceModel = new VLIWResourceModel(STI, DAG->getSchedModel());
Sergei Larinef4cc112012-09-10 17:31:34 +0000332
Andrew Trick7a8e1002012-09-11 00:39:15 +0000333 assert((!llvm::ForceTopDown || !llvm::ForceBottomUp) &&
Sergei Larin4d8986a2012-09-04 14:49:56 +0000334 "-misched-topdown incompatible with -misched-bottomup");
Krzysztof Parzyszek9be66732016-07-15 17:48:09 +0000335
336 DAG->addMutation(make_unique<HexagonSubtarget::HexagonDAGMutation>());
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +0000337 DAG->addMutation(make_unique<HexagonCallMutation>());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000338}
339
340void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
341 if (SU->isScheduled)
342 return;
343
Krzysztof Parzyszek2be7ead2016-07-18 16:15:15 +0000344 for (const SDep &PI : SU->Preds) {
345 unsigned PredReadyCycle = PI.getSUnit()->TopReadyCycle;
346 unsigned MinLatency = PI.getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000347#ifndef NDEBUG
348 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
349#endif
350 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
351 SU->TopReadyCycle = PredReadyCycle + MinLatency;
352 }
353 Top.releaseNode(SU, SU->TopReadyCycle);
354}
355
356void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
357 if (SU->isScheduled)
358 return;
359
360 assert(SU->getInstr() && "Scheduled SUnit must have instr");
361
362 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
363 I != E; ++I) {
364 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickde2109e2013-06-15 04:49:57 +0000365 unsigned MinLatency = I->getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000366#ifndef NDEBUG
367 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
368#endif
369 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
370 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
371 }
372 Bot.releaseNode(SU, SU->BotReadyCycle);
373}
374
375/// Does this SU have a hazard within the current instruction group.
376///
377/// The scheduler supports two modes of hazard recognition. The first is the
378/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
379/// supports highly complicated in-order reservation tables
380/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
381///
382/// The second is a streamlined mechanism that checks for hazards based on
383/// simple counters that the scheduler itself maintains. It explicitly checks
384/// for instruction dispatch limitations, including the number of micro-ops that
385/// can dispatch per cycle.
386///
387/// TODO: Also check whether the SU must start a new group.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000388bool ConvergingVLIWScheduler::VLIWSchedBoundary::checkHazard(SUnit *SU) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000389 if (HazardRec->isEnabled())
390 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
391
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000392 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
393 if (IssueCount + uops > SchedModel->getIssueWidth())
Sergei Larin4d8986a2012-09-04 14:49:56 +0000394 return true;
395
396 return false;
397}
398
Andrew Trickd7f890e2013-12-28 21:56:47 +0000399void ConvergingVLIWScheduler::VLIWSchedBoundary::releaseNode(SUnit *SU,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000400 unsigned ReadyCycle) {
401 if (ReadyCycle < MinReadyCycle)
402 MinReadyCycle = ReadyCycle;
403
404 // Check for interlocks first. For the purpose of other heuristics, an
405 // instruction that cannot issue appears as if it's not in the ReadyQueue.
406 if (ReadyCycle > CurrCycle || checkHazard(SU))
407
408 Pending.push(SU);
409 else
410 Available.push(SU);
411}
412
413/// Move the boundary of scheduled code by one cycle.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000414void ConvergingVLIWScheduler::VLIWSchedBoundary::bumpCycle() {
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000415 unsigned Width = SchedModel->getIssueWidth();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000416 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
417
418 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
419 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
420
421 if (!HazardRec->isEnabled()) {
422 // Bypass HazardRec virtual calls.
423 CurrCycle = NextCycle;
Sergei Larinef4cc112012-09-10 17:31:34 +0000424 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000425 // Bypass getHazardType calls in case of long latency.
426 for (; CurrCycle != NextCycle; ++CurrCycle) {
427 if (isTop())
428 HazardRec->AdvanceCycle();
429 else
430 HazardRec->RecedeCycle();
431 }
432 }
433 CheckPending = true;
434
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000435 DEBUG(dbgs() << "*** Next cycle " << Available.getName() << " cycle "
436 << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000437}
438
439/// Move the boundary of scheduled code by one SUnit.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000440void ConvergingVLIWScheduler::VLIWSchedBoundary::bumpNode(SUnit *SU) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000441 bool startNewCycle = false;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000442
443 // Update the reservation table.
444 if (HazardRec->isEnabled()) {
445 if (!isTop() && SU->isCall) {
446 // Calls are scheduled with their preceding instructions. For bottom-up
447 // scheduling, clear the pipeline state before emitting.
448 HazardRec->Reset();
449 }
450 HazardRec->EmitInstruction(SU);
451 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000452
453 // Update DFA model.
454 startNewCycle = ResourceModel->reserveResources(SU);
455
Sergei Larin4d8986a2012-09-04 14:49:56 +0000456 // Check the instruction group dispatch limit.
457 // TODO: Check if this SU must end a dispatch group.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000458 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Sergei Larinef4cc112012-09-10 17:31:34 +0000459 if (startNewCycle) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000460 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
461 bumpCycle();
462 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000463 else
464 DEBUG(dbgs() << "*** IssueCount " << IssueCount
465 << " at cycle " << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000466}
467
468/// Release pending ready nodes in to the available queue. This makes them
469/// visible to heuristics.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000470void ConvergingVLIWScheduler::VLIWSchedBoundary::releasePending() {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000471 // If the available queue is empty, it is safe to reset MinReadyCycle.
472 if (Available.empty())
473 MinReadyCycle = UINT_MAX;
474
475 // Check to see if any of the pending instructions are ready to issue. If
476 // so, add them to the available queue.
477 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
478 SUnit *SU = *(Pending.begin()+i);
479 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
480
481 if (ReadyCycle < MinReadyCycle)
482 MinReadyCycle = ReadyCycle;
483
484 if (ReadyCycle > CurrCycle)
485 continue;
486
487 if (checkHazard(SU))
488 continue;
489
490 Available.push(SU);
491 Pending.remove(Pending.begin()+i);
492 --i; --e;
493 }
494 CheckPending = false;
495}
496
497/// Remove SU from the ready set for this boundary.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000498void ConvergingVLIWScheduler::VLIWSchedBoundary::removeReady(SUnit *SU) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000499 if (Available.isInQueue(SU))
500 Available.remove(Available.find(SU));
501 else {
502 assert(Pending.isInQueue(SU) && "bad ready count");
503 Pending.remove(Pending.find(SU));
504 }
505}
506
507/// If this queue only has one ready candidate, return it. As a side effect,
508/// advance the cycle until at least one node is ready. If multiple instructions
509/// are ready, return NULL.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000510SUnit *ConvergingVLIWScheduler::VLIWSchedBoundary::pickOnlyChoice() {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000511 if (CheckPending)
512 releasePending();
513
514 for (unsigned i = 0; Available.empty(); ++i) {
515 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
516 "permanent hazard"); (void)i;
Craig Topper062a2ba2014-04-25 05:30:21 +0000517 ResourceModel->reserveResources(nullptr);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000518 bumpCycle();
519 releasePending();
520 }
521 if (Available.size() == 1)
522 return *Available.begin();
Craig Topper062a2ba2014-04-25 05:30:21 +0000523 return nullptr;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000524}
525
526#ifndef NDEBUG
Sergei Larinef4cc112012-09-10 17:31:34 +0000527void ConvergingVLIWScheduler::traceCandidate(const char *Label,
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000528 const ReadyQueue &Q, SUnit *SU, int Cost, PressureChange P) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000529 dbgs() << Label << " " << Q.getName() << " ";
530 if (P.isValid())
Andrew Trick1a831342013-08-30 03:49:48 +0000531 dbgs() << DAG->TRI->getRegPressureSetName(P.getPSet()) << ":"
532 << P.getUnitInc() << " ";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000533 else
534 dbgs() << " ";
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000535 dbgs() << "cost(" << Cost << ")\t";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000536 SU->dump(DAG);
537}
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000538
539// Very detailed queue dump, to be used with higher verbosity levels.
540void ConvergingVLIWScheduler::readyQueueVerboseDump(
541 const RegPressureTracker &RPTracker, SchedCandidate &Candidate,
542 ReadyQueue &Q) {
543 RegPressureTracker &TempTracker = const_cast<RegPressureTracker &>(RPTracker);
544
545 dbgs() << ">>> " << Q.getName() << "\n";
546 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
547 RegPressureDelta RPDelta;
548 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
549 DAG->getRegionCriticalPSets(),
550 DAG->getRegPressure().MaxSetPressure);
551 std::stringstream dbgstr;
552 dbgstr << "SU(" << std::setw(3) << (*I)->NodeNum << ")";
553 dbgs() << dbgstr.str();
554 SchedulingCost(Q, *I, Candidate, RPDelta, true);
555 dbgs() << "\t";
556 (*I)->getInstr()->dump();
557 }
558 dbgs() << "\n";
559}
Sergei Larin4d8986a2012-09-04 14:49:56 +0000560#endif
561
Sergei Larinef4cc112012-09-10 17:31:34 +0000562/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
563/// of SU, return it, otherwise return null.
564static SUnit *getSingleUnscheduledPred(SUnit *SU) {
Craig Topper062a2ba2014-04-25 05:30:21 +0000565 SUnit *OnlyAvailablePred = nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000566 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
567 I != E; ++I) {
568 SUnit &Pred = *I->getSUnit();
569 if (!Pred.isScheduled) {
570 // We found an available, but not scheduled, predecessor. If it's the
571 // only one we have found, keep track of it... otherwise give up.
572 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
Craig Topper062a2ba2014-04-25 05:30:21 +0000573 return nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000574 OnlyAvailablePred = &Pred;
575 }
576 }
577 return OnlyAvailablePred;
578}
579
580/// getSingleUnscheduledSucc - If there is exactly one unscheduled successor
581/// of SU, return it, otherwise return null.
582static SUnit *getSingleUnscheduledSucc(SUnit *SU) {
Craig Topper062a2ba2014-04-25 05:30:21 +0000583 SUnit *OnlyAvailableSucc = nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000584 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
585 I != E; ++I) {
586 SUnit &Succ = *I->getSUnit();
587 if (!Succ.isScheduled) {
588 // We found an available, but not scheduled, successor. If it's the
589 // only one we have found, keep track of it... otherwise give up.
590 if (OnlyAvailableSucc && OnlyAvailableSucc != &Succ)
Craig Topper062a2ba2014-04-25 05:30:21 +0000591 return nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000592 OnlyAvailableSucc = &Succ;
593 }
594 }
595 return OnlyAvailableSucc;
596}
597
Sergei Larin4d8986a2012-09-04 14:49:56 +0000598// Constants used to denote relative importance of
599// heuristic components for cost computation.
600static const unsigned PriorityOne = 200;
Eli Friedman8f06d552013-09-11 00:41:02 +0000601static const unsigned PriorityTwo = 50;
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000602static const unsigned PriorityThree = 75;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000603static const unsigned ScaleTwo = 10;
604static const unsigned FactorOne = 2;
605
606/// Single point to compute overall scheduling cost.
607/// TODO: More heuristics will be used soon.
608int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
609 SchedCandidate &Candidate,
610 RegPressureDelta &Delta,
611 bool verbose) {
612 // Initial trivial priority.
613 int ResCount = 1;
614
615 // Do not waste time on a node that is already scheduled.
616 if (!SU || SU->isScheduled)
617 return ResCount;
618
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +0000619 MachineInstr &Instr = *SU->getInstr();
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000620
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000621 DEBUG(if (verbose) dbgs() << ((Q.getID() == TopQID) ? "(top|" : "(bot|"));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000622 // Forced priority is high.
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000623 if (SU->isScheduleHigh) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000624 ResCount += PriorityOne;
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000625 DEBUG(dbgs() << "H|");
626 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000627
628 // Critical path first.
Sergei Larinef4cc112012-09-10 17:31:34 +0000629 if (Q.getID() == TopQID) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000630 ResCount += (SU->getHeight() * ScaleTwo);
Sergei Larinef4cc112012-09-10 17:31:34 +0000631
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000632 DEBUG(if (verbose) {
633 std::stringstream dbgstr;
634 dbgstr << "h" << std::setw(3) << SU->getHeight() << "|";
635 dbgs() << dbgstr.str();
636 });
637
Sergei Larinef4cc112012-09-10 17:31:34 +0000638 // If resources are available for it, multiply the
639 // chance of scheduling.
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000640 if (Top.ResourceModel->isResourceAvailable(SU)) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000641 ResCount <<= FactorOne;
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000642 ResCount += PriorityThree;
643 DEBUG(if (verbose) dbgs() << "A|");
644 } else
645 DEBUG(if (verbose) dbgs() << " |");
Sergei Larinef4cc112012-09-10 17:31:34 +0000646 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000647 ResCount += (SU->getDepth() * ScaleTwo);
648
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000649 DEBUG(if (verbose) {
650 std::stringstream dbgstr;
651 dbgstr << "d" << std::setw(3) << SU->getDepth() << "|";
652 dbgs() << dbgstr.str();
653 });
654
Sergei Larinef4cc112012-09-10 17:31:34 +0000655 // If resources are available for it, multiply the
656 // chance of scheduling.
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000657 if (Bot.ResourceModel->isResourceAvailable(SU)) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000658 ResCount <<= FactorOne;
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000659 ResCount += PriorityThree;
660 DEBUG(if (verbose) dbgs() << "A|");
661 } else
662 DEBUG(if (verbose) dbgs() << " |");
Sergei Larinef4cc112012-09-10 17:31:34 +0000663 }
664
665 unsigned NumNodesBlocking = 0;
666 if (Q.getID() == TopQID) {
667 // How many SUs does it block from scheduling?
668 // Look at all of the successors of this node.
669 // Count the number of nodes that
670 // this node is the sole unscheduled node for.
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000671 for (const SDep &SI : SU->Succs)
672 if (getSingleUnscheduledPred(SI.getSUnit()) == SU)
Sergei Larinef4cc112012-09-10 17:31:34 +0000673 ++NumNodesBlocking;
674 } else {
675 // How many unscheduled predecessors block this node?
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000676 for (const SDep &PI : SU->Preds)
677 if (getSingleUnscheduledSucc(PI.getSUnit()) == SU)
Sergei Larinef4cc112012-09-10 17:31:34 +0000678 ++NumNodesBlocking;
679 }
680 ResCount += (NumNodesBlocking * ScaleTwo);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000681
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000682 DEBUG(if (verbose) {
683 std::stringstream dbgstr;
684 dbgstr << "blk " << std::setw(2) << NumNodesBlocking << ")|";
685 dbgs() << dbgstr.str();
686 });
687
Sergei Larin4d8986a2012-09-04 14:49:56 +0000688 // Factor in reg pressure as a heuristic.
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000689 if (!IgnoreBBRegPressure) {
690 // Decrease priority by the amount that register pressure exceeds the limit.
691 ResCount -= (Delta.Excess.getUnitInc()*PriorityOne);
692 // Decrease priority if register pressure exceeds the limit.
693 ResCount -= (Delta.CriticalMax.getUnitInc()*PriorityOne);
694 // Decrease priority slightly if register pressure would increase over the
695 // current maximum.
696 ResCount -= (Delta.CurrentMax.getUnitInc()*PriorityTwo);
697 DEBUG(if (verbose) {
698 dbgs() << "RP " << Delta.Excess.getUnitInc() << "/"
699 << Delta.CriticalMax.getUnitInc() <<"/"
700 << Delta.CurrentMax.getUnitInc() << ")|";
701 });
702 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000703
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000704 // Give a little extra priority to a .cur instruction if there is a resource
705 // available for it.
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000706 auto &QST = DAG->MF.getSubtarget<HexagonSubtarget>();
707 auto &QII = *QST.getInstrInfo();
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +0000708 if (SU->isInstr() && QII.mayBeCurLoad(*SU->getInstr())) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000709 if (Q.getID() == TopQID && Top.ResourceModel->isResourceAvailable(SU)) {
710 ResCount += PriorityTwo;
711 DEBUG(if (verbose) dbgs() << "C|");
712 } else if (Q.getID() == BotQID &&
713 Bot.ResourceModel->isResourceAvailable(SU)) {
714 ResCount += PriorityTwo;
715 DEBUG(if (verbose) dbgs() << "C|");
716 }
717 }
718
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000719 // Give preference to a zero latency instruction if the dependent
720 // instruction is in the current packet.
721 if (Q.getID() == TopQID) {
722 for (const SDep &PI : SU->Preds) {
723 if (!PI.getSUnit()->getInstr()->isPseudo() && PI.isAssignedRegDep() &&
724 PI.getLatency() == 0 &&
725 Top.ResourceModel->isInPacket(PI.getSUnit())) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000726 ResCount += PriorityThree;
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000727 DEBUG(if (verbose) dbgs() << "Z|");
728 }
729 }
730 } else {
731 for (const SDep &SI : SU->Succs) {
732 if (!SI.getSUnit()->getInstr()->isPseudo() && SI.isAssignedRegDep() &&
733 SI.getLatency() == 0 &&
734 Bot.ResourceModel->isInPacket(SI.getSUnit())) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000735 ResCount += PriorityThree;
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000736 DEBUG(if (verbose) dbgs() << "Z|");
737 }
738 }
739 }
740
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000741 // Give less preference to an instruction that will cause a stall with
742 // an instruction in the previous packet.
743 if (QII.isV60VectorInstruction(Instr)) {
744 // Check for stalls in the previous packet.
745 if (Q.getID() == TopQID) {
746 for (auto J : Top.ResourceModel->OldPacket)
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +0000747 if (QII.producesStall(*J->getInstr(), Instr))
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000748 ResCount -= PriorityOne;
749 } else {
750 for (auto J : Bot.ResourceModel->OldPacket)
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +0000751 if (QII.producesStall(Instr, *J->getInstr()))
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000752 ResCount -= PriorityOne;
753 }
754 }
755
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000756 // If the instruction has a non-zero latency dependence with an instruction in
757 // the current packet, then it should not be scheduled yet. The case occurs
758 // when the dependent instruction is scheduled in a new packet, so the
759 // scheduler updates the current cycle and pending instructions become
760 // available.
761 if (CheckEarlyAvail) {
762 if (Q.getID() == TopQID) {
763 for (const auto &PI : SU->Preds) {
764 if (PI.getLatency() > 0 &&
765 Top.ResourceModel->isInPacket(PI.getSUnit())) {
766 ResCount -= PriorityOne;
767 DEBUG(if (verbose) dbgs() << "D|");
768 }
769 }
770 } else {
771 for (const auto &SI : SU->Succs) {
772 if (SI.getLatency() > 0 &&
773 Bot.ResourceModel->isInPacket(SI.getSUnit())) {
774 ResCount -= PriorityOne;
775 DEBUG(if (verbose) dbgs() << "D|");
776 }
777 }
778 }
779 }
780
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000781 DEBUG(if (verbose) {
782 std::stringstream dbgstr;
783 dbgstr << "Total " << std::setw(4) << ResCount << ")";
784 dbgs() << dbgstr.str();
785 });
Sergei Larin4d8986a2012-09-04 14:49:56 +0000786
787 return ResCount;
788}
789
790/// Pick the best candidate from the top queue.
791///
792/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
793/// DAG building. To adjust for the current scheduling location we need to
794/// maintain the number of vreg uses remaining to be top-scheduled.
795ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
796pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
797 SchedCandidate &Candidate) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000798 DEBUG(if (SchedDebugVerboseLevel > 1)
799 readyQueueVerboseDump(RPTracker, Candidate, Q);
800 else Q.dump(););
Sergei Larin4d8986a2012-09-04 14:49:56 +0000801
802 // getMaxPressureDelta temporarily modifies the tracker.
803 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
804
805 // BestSU remains NULL if no top candidates beat the best existing candidate.
806 CandResult FoundCandidate = NoCand;
807 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
808 RegPressureDelta RPDelta;
809 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
810 DAG->getRegionCriticalPSets(),
811 DAG->getRegPressure().MaxSetPressure);
812
813 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
814
815 // Initialize the candidate if needed.
816 if (!Candidate.SU) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000817 DEBUG(traceCandidate("DCAND", Q, *I, CurrentCost));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000818 Candidate.SU = *I;
819 Candidate.RPDelta = RPDelta;
820 Candidate.SCost = CurrentCost;
821 FoundCandidate = NodeOrder;
822 continue;
823 }
824
Sergei Larin4d8986a2012-09-04 14:49:56 +0000825 // Best cost.
826 if (CurrentCost > Candidate.SCost) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000827 DEBUG(traceCandidate("CCAND", Q, *I, CurrentCost));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000828 Candidate.SU = *I;
829 Candidate.RPDelta = RPDelta;
830 Candidate.SCost = CurrentCost;
831 FoundCandidate = BestCost;
832 continue;
833 }
834
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000835 // Tie breaker using Timing Class.
836 if (!DisableTCTie) {
837 auto &QST = DAG->MF.getSubtarget<HexagonSubtarget>();
838 auto &QII = *QST.getInstrInfo();
839
840 const MachineInstr *MI = (*I)->getInstr();
841 const MachineInstr *CandI = Candidate.SU->getInstr();
842 const InstrItineraryData *InstrItins = QST.getInstrItineraryData();
843
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +0000844 unsigned InstrLatency = QII.getInstrTimingClassLatency(InstrItins, *MI);
845 unsigned CandLatency = QII.getInstrTimingClassLatency(InstrItins, *CandI);
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000846 DEBUG(dbgs() << "TC Tie Breaker Cand: "
847 << CandLatency << " Instr:" << InstrLatency << "\n"
848 << *MI << *CandI << "\n");
849 if (Q.getID() == TopQID && CurrentCost == Candidate.SCost) {
850 if (InstrLatency < CandLatency && TopUseShorterTie) {
851 Candidate.SU = *I;
852 Candidate.RPDelta = RPDelta;
853 Candidate.SCost = CurrentCost;
854 FoundCandidate = BestCost;
855 DEBUG(dbgs() << "Used top shorter tie breaker\n");
856 continue;
857 } else if (InstrLatency > CandLatency && !TopUseShorterTie) {
858 Candidate.SU = *I;
859 Candidate.RPDelta = RPDelta;
860 Candidate.SCost = CurrentCost;
861 FoundCandidate = BestCost;
862 DEBUG(dbgs() << "Used top longer tie breaker\n");
863 continue;
864 }
865 } else if (Q.getID() == BotQID && CurrentCost == Candidate.SCost) {
866 if (InstrLatency < CandLatency && BotUseShorterTie) {
867 Candidate.SU = *I;
868 Candidate.RPDelta = RPDelta;
869 Candidate.SCost = CurrentCost;
870 FoundCandidate = BestCost;
871 DEBUG(dbgs() << "Used Bot shorter tie breaker\n");
872 continue;
873 } else if (InstrLatency > CandLatency && !BotUseShorterTie) {
874 Candidate.SU = *I;
875 Candidate.RPDelta = RPDelta;
876 Candidate.SCost = CurrentCost;
877 FoundCandidate = BestCost;
878 DEBUG(dbgs() << "Used Bot longer tie breaker\n");
879 continue;
880 }
881 }
882 }
883
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000884 if (CurrentCost == Candidate.SCost) {
885 if ((Q.getID() == TopQID &&
886 (*I)->Succs.size() > Candidate.SU->Succs.size()) ||
887 (Q.getID() == BotQID &&
888 (*I)->Preds.size() < Candidate.SU->Preds.size())) {
889 DEBUG(traceCandidate("SPCAND", Q, *I, CurrentCost));
890 Candidate.SU = *I;
891 Candidate.RPDelta = RPDelta;
892 Candidate.SCost = CurrentCost;
893 FoundCandidate = BestCost;
894 continue;
895 }
896 }
897
Sergei Larin4d8986a2012-09-04 14:49:56 +0000898 // Fall through to original instruction order.
899 // Only consider node order if Candidate was chosen from this Q.
900 if (FoundCandidate == NoCand)
901 continue;
902 }
903 return FoundCandidate;
904}
905
906/// Pick the best candidate node from either the top or bottom queue.
907SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
908 // Schedule as far as possible in the direction of no choice. This is most
909 // efficient, but also provides the best heuristics for CriticalPSets.
910 if (SUnit *SU = Bot.pickOnlyChoice()) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000911 DEBUG(dbgs() << "Picked only Bottom\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000912 IsTopNode = false;
913 return SU;
914 }
915 if (SUnit *SU = Top.pickOnlyChoice()) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000916 DEBUG(dbgs() << "Picked only Top\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000917 IsTopNode = true;
918 return SU;
919 }
920 SchedCandidate BotCand;
921 // Prefer bottom scheduling when heuristics are silent.
922 CandResult BotResult = pickNodeFromQueue(Bot.Available,
923 DAG->getBotRPTracker(), BotCand);
924 assert(BotResult != NoCand && "failed to find the first candidate");
925
926 // If either Q has a single candidate that provides the least increase in
927 // Excess pressure, we can immediately schedule from that Q.
928 //
929 // RegionCriticalPSets summarizes the pressure within the scheduled region and
930 // affects picking from either Q. If scheduling in one direction must
931 // increase pressure for one of the excess PSets, then schedule in that
932 // direction first to provide more freedom in the other direction.
933 if (BotResult == SingleExcess || BotResult == SingleCritical) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000934 DEBUG(dbgs() << "Prefered Bottom Node\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000935 IsTopNode = false;
936 return BotCand.SU;
937 }
938 // Check if the top Q has a better candidate.
939 SchedCandidate TopCand;
940 CandResult TopResult = pickNodeFromQueue(Top.Available,
941 DAG->getTopRPTracker(), TopCand);
942 assert(TopResult != NoCand && "failed to find the first candidate");
943
944 if (TopResult == SingleExcess || TopResult == SingleCritical) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000945 DEBUG(dbgs() << "Prefered Top Node\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000946 IsTopNode = true;
947 return TopCand.SU;
948 }
949 // If either Q has a single candidate that minimizes pressure above the
950 // original region's pressure pick it.
951 if (BotResult == SingleMax) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000952 DEBUG(dbgs() << "Prefered Bottom Node SingleMax\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000953 IsTopNode = false;
954 return BotCand.SU;
955 }
956 if (TopResult == SingleMax) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000957 DEBUG(dbgs() << "Prefered Top Node SingleMax\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000958 IsTopNode = true;
959 return TopCand.SU;
960 }
961 if (TopCand.SCost > BotCand.SCost) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000962 DEBUG(dbgs() << "Prefered Top Node Cost\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000963 IsTopNode = true;
964 return TopCand.SU;
965 }
966 // Otherwise prefer the bottom candidate in node order.
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000967 DEBUG(dbgs() << "Prefered Bottom in Node order\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000968 IsTopNode = false;
969 return BotCand.SU;
970}
971
972/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
973SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
974 if (DAG->top() == DAG->bottom()) {
975 assert(Top.Available.empty() && Top.Pending.empty() &&
976 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topper062a2ba2014-04-25 05:30:21 +0000977 return nullptr;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000978 }
979 SUnit *SU;
Andrew Trick7a8e1002012-09-11 00:39:15 +0000980 if (llvm::ForceTopDown) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000981 SU = Top.pickOnlyChoice();
982 if (!SU) {
983 SchedCandidate TopCand;
984 CandResult TopResult =
985 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
986 assert(TopResult != NoCand && "failed to find the first candidate");
987 (void)TopResult;
988 SU = TopCand.SU;
989 }
990 IsTopNode = true;
Andrew Trick7a8e1002012-09-11 00:39:15 +0000991 } else if (llvm::ForceBottomUp) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000992 SU = Bot.pickOnlyChoice();
993 if (!SU) {
994 SchedCandidate BotCand;
995 CandResult BotResult =
996 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
997 assert(BotResult != NoCand && "failed to find the first candidate");
998 (void)BotResult;
999 SU = BotCand.SU;
1000 }
1001 IsTopNode = false;
1002 } else {
1003 SU = pickNodeBidrectional(IsTopNode);
1004 }
1005 if (SU->isTopReady())
1006 Top.removeReady(SU);
1007 if (SU->isBottomReady())
1008 Bot.removeReady(SU);
1009
1010 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
1011 << " Scheduling Instruction in cycle "
1012 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
1013 SU->dump(DAG));
1014 return SU;
1015}
1016
1017/// Update the scheduler's state after scheduling a node. This is the same node
Sergei Larinef4cc112012-09-10 17:31:34 +00001018/// that was just returned by pickNode(). However, VLIWMachineScheduler needs
1019/// to update it's state based on the current cycle before MachineSchedStrategy
1020/// does.
Sergei Larin4d8986a2012-09-04 14:49:56 +00001021void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
1022 if (IsTopNode) {
1023 SU->TopReadyCycle = Top.CurrCycle;
1024 Top.bumpNode(SU);
Sergei Larinef4cc112012-09-10 17:31:34 +00001025 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +00001026 SU->BotReadyCycle = Bot.CurrCycle;
1027 Bot.bumpNode(SU);
1028 }
1029}