LLVM 24.0.0git
SystemZHazardRecognizer.cpp
Go to the documentation of this file.
1//=-- SystemZHazardRecognizer.h - SystemZ Hazard Recognizer -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a hazard recognizer for the SystemZ scheduler.
10//
11// This class is used by the SystemZ scheduling strategy to maintain
12// the state during scheduling, and provide cost functions for
13// scheduling candidates. This includes:
14//
15// * Decoder grouping. A decoder group can maximally hold 3 uops, and
16// instructions that always begin a new group should be scheduled when
17// the current decoder group is empty.
18// * Processor resources usage. It is beneficial to balance the use of
19// resources.
20//
21// A goal is to consider all instructions, also those outside of any
22// scheduling region. Such instructions are "advanced" past and include
23// single instructions before a scheduling region, branches etc.
24//
25// A block that has only one predecessor continues scheduling with the state
26// of it (which may be updated by emitting branches).
27//
28// ===---------------------------------------------------------------------===//
29
31#include "llvm/ADT/Statistic.h"
32
33using namespace llvm;
34
35#define DEBUG_TYPE "machine-scheduler"
36
37unsigned SystemZHazardRecognizer::
38getNumDecoderSlots(SUnit *SU) const {
39 const MCSchedClassDesc *SC = getSchedClass(SU);
40 if (!SC->isValid())
41 return 0; // IMPLICIT_DEF / KILL -- will not make impact in output.
42
43 assert((SC->NumMicroOps != 2 || (SC->BeginGroup && !SC->EndGroup)) &&
44 "Only cracked instruction can have 2 uops.");
45 assert((SC->NumMicroOps < 3 || (SC->BeginGroup && SC->EndGroup)) &&
46 "Expanded instructions always group alone.");
47 assert((SC->NumMicroOps < 3 || (SC->NumMicroOps % 3 == 0)) &&
48 "Expanded instructions fill the group(s).");
49
50 return SC->NumMicroOps;
51}
52
53unsigned SystemZHazardRecognizer::getCurrCycleIdx(SUnit *SU) const {
54 unsigned Idx = CurrGroupSize;
55 if (GrpCount % 2)
56 Idx += 3;
57
58 if (SU != nullptr && !fitsIntoCurrentGroup(SU)) {
59 if (Idx == 1 || Idx == 2)
60 Idx = 3;
61 else if (Idx == 4 || Idx == 5)
62 Idx = 0;
63 }
64
65 return Idx;
66}
67
69getHazardType(SUnit *SU, int Stalls) {
70 return (fitsIntoCurrentGroup(SU) ? NoHazard : Hazard);
71}
72
74 CurrGroupSize = 0;
75 CurrGroupHas4RegOps = false;
76 clearProcResCounters();
77 GrpCount = 0;
78 LastFPdOpCycleIdx = UINT_MAX;
79 LastEmittedMI = nullptr;
81}
82
83bool
84SystemZHazardRecognizer::fitsIntoCurrentGroup(SUnit *SU) const {
85 const MCSchedClassDesc *SC = getSchedClass(SU);
86 if (!SC->isValid())
87 return true;
88
89 // A cracked instruction only fits into schedule if the current
90 // group is empty.
91 if (SC->BeginGroup)
92 return (CurrGroupSize == 0);
93
94 // An instruction with 4 register operands will not fit in last slot.
95 assert ((CurrGroupSize < 2 || !CurrGroupHas4RegOps) &&
96 "Current decoder group is already full!");
97 if (CurrGroupSize == 2 && has4RegOps(SU->getInstr()))
98 return false;
99
100 // Since a full group is handled immediately in EmitInstruction(),
101 // SU should fit into current group. NumSlots should be 1 or 0,
102 // since it is not a cracked or expanded instruction.
103 assert ((getNumDecoderSlots(SU) <= 1) && (CurrGroupSize < 3) &&
104 "Expected normal instruction to fit in non-full group!");
105
106 return true;
107}
108
109bool SystemZHazardRecognizer::has4RegOps(const MachineInstr *MI) const {
110 const MCInstrDesc &MID = MI->getDesc();
111 unsigned Count = 0;
112 for (unsigned OpIdx = 0; OpIdx < MID.getNumOperands(); OpIdx++) {
113 const TargetRegisterClass *RC = TII->getRegClass(MID, OpIdx);
114 if (RC == nullptr)
115 continue;
116 if (OpIdx >= MID.getNumDefs() &&
117 MID.getOperandConstraint(OpIdx, MCOI::TIED_TO) != -1)
118 continue;
119 Count++;
120 }
121 return Count >= 4;
122}
123
124void SystemZHazardRecognizer::nextGroup() {
125 if (CurrGroupSize == 0)
126 return;
127
128 LLVM_DEBUG(dumpCurrGroup("Completed decode group"));
129 LLVM_DEBUG(CurGroupDbg = "";);
130
131 int NumGroups = ((CurrGroupSize > 3) ? (CurrGroupSize / 3) : 1);
132 assert((CurrGroupSize <= 3 || CurrGroupSize % 3 == 0) &&
133 "Current decoder group bad.");
134
135 // Reset counter for next group.
136 CurrGroupSize = 0;
137 CurrGroupHas4RegOps = false;
138
139 GrpCount += ((unsigned) NumGroups);
140
141 // Decrease counters for execution units.
142 for (unsigned i = 0; i < SchedModel->getNumProcResourceKinds(); ++i)
143 ProcResourceCounters[i] = ((ProcResourceCounters[i] > NumGroups)
144 ? (ProcResourceCounters[i] - NumGroups)
145 : 0);
146
147 // Clear CriticalResourceIdx if it is now below the threshold.
148 if (CriticalResourceIdx != UINT_MAX &&
149 (ProcResourceCounters[CriticalResourceIdx] <= CLOpts.procres_cost_lim))
150 CriticalResourceIdx = UINT_MAX;
151
153}
154
155#ifndef NDEBUG // Debug output
157 OS << *SU << ":";
158 OS << TII->getName(SU->getInstr()->getOpcode());
159
160 const MCSchedClassDesc *SC = getSchedClass(SU);
161 if (!SC->isValid())
162 return;
163
165 PI = SchedModel->getWriteProcResBegin(SC),
166 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
167 const MCProcResourceDesc &PRD =
168 *SchedModel->getProcResource(PI->ProcResourceIdx);
169 std::string FU(PRD.Name);
170 // trim e.g. Z13_FXaUnit -> FXa
171 FU = FU.substr(FU.find('_') + 1);
172 size_t Pos = FU.find("Unit");
173 if (Pos != std::string::npos)
174 FU.resize(Pos);
175 if (FU == "LS") // LSUnit -> LSU
176 FU = "LSU";
177 OS << "/" << FU;
178
179 if (PI->ReleaseAtCycle> 1)
180 OS << "(" << PI->ReleaseAtCycle << "cyc)";
181 }
182
183 if (SC->NumMicroOps > 1)
184 OS << "/" << SC->NumMicroOps << "uops";
185 if (SC->BeginGroup && SC->EndGroup)
186 OS << "/GroupsAlone";
187 else if (SC->BeginGroup)
188 OS << "/BeginsGroup";
189 else if (SC->EndGroup)
190 OS << "/EndsGroup";
191 if (SU->isUnbuffered)
192 OS << "/Unbuffered";
193 if (has4RegOps(SU->getInstr()))
194 OS << "/4RegOps";
195}
196
198 dbgs() << "++ " << Msg;
199 dbgs() << ": ";
200
201 if (CurGroupDbg.empty())
202 dbgs() << " <empty>\n";
203 else {
204 dbgs() << "{ " << CurGroupDbg << " }";
205 dbgs() << " (" << CurrGroupSize << " decoder slot"
206 << (CurrGroupSize > 1 ? "s":"")
207 << (CurrGroupHas4RegOps ? ", 4RegOps" : "")
208 << ")\n";
209 }
210}
211
213 bool any = false;
214
215 for (unsigned i = 0; i < SchedModel->getNumProcResourceKinds(); ++i)
216 if (ProcResourceCounters[i] > 0) {
217 any = true;
218 break;
219 }
220
221 if (!any)
222 return;
223
224 dbgs() << "++ | Resource counters: ";
225 for (unsigned i = 0; i < SchedModel->getNumProcResourceKinds(); ++i)
226 if (ProcResourceCounters[i] > 0)
227 dbgs() << SchedModel->getProcResource(i)->Name
228 << ":" << ProcResourceCounters[i] << " ";
229 dbgs() << "\n";
230
231 if (CriticalResourceIdx != UINT_MAX)
232 dbgs() << "++ | Critical resource: "
233 << SchedModel->getProcResource(CriticalResourceIdx)->Name
234 << "\n";
235}
236
238 dumpCurrGroup("| Current decoder group");
239 dbgs() << "++ | Current cycle index: "
240 << getCurrCycleIdx() << "\n";
242 if (LastFPdOpCycleIdx != UINT_MAX)
243 dbgs() << "++ | Last FPd cycle index: " << LastFPdOpCycleIdx << "\n";
244}
245
246#endif //NDEBUG
247
248void SystemZHazardRecognizer::clearProcResCounters() {
249 ProcResourceCounters.assign(SchedModel->getNumProcResourceKinds(), 0);
250 CriticalResourceIdx = UINT_MAX;
251}
252
253static inline bool isBranchRetTrap(MachineInstr *MI) {
254 return (MI->isBranch() || MI->isReturn() ||
255 MI->getOpcode() == SystemZ::CondTrap);
256}
257
258// Update state with SU as the next scheduled unit.
261 const MCSchedClassDesc *SC = getSchedClass(SU);
262 LLVM_DEBUG(dbgs() << "++ HazardRecognizer emitting "; dumpSU(SU, dbgs());
263 dbgs() << "\n";);
264 LLVM_DEBUG(dumpCurrGroup("Decode group before emission"););
265
266 // If scheduling an SU that must begin a new decoder group, move on
267 // to next group.
268 if (!fitsIntoCurrentGroup(SU))
269 nextGroup();
270
272 if (CurGroupDbg.length()) cgd << ", "; dumpSU(SU, cgd););
273
274 LastEmittedMI = SU->getInstr();
275
276 // After returning from a call, we don't know much about the state.
277 if (SU->isCall) {
278 LLVM_DEBUG(dbgs() << "++ Clearing state after call.\n";);
279 Reset();
280 LastEmittedMI = SU->getInstr();
281 return;
282 }
283
284 // Increase counter for execution unit(s).
286 PI = SchedModel->getWriteProcResBegin(SC),
287 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
288 // Don't handle FPd together with the other resources.
289 if (SchedModel->getProcResource(PI->ProcResourceIdx)->BufferSize == 1)
290 continue;
291 int &CurrCounter =
292 ProcResourceCounters[PI->ProcResourceIdx];
293 CurrCounter += PI->ReleaseAtCycle;
294 // Check if this is now the new critical resource.
295 if ((CurrCounter > CLOpts.procres_cost_lim) &&
296 (CriticalResourceIdx == UINT_MAX ||
297 (PI->ProcResourceIdx != CriticalResourceIdx &&
298 CurrCounter > ProcResourceCounters[CriticalResourceIdx]))) {
300 dbgs() << "++ New critical resource: "
301 << SchedModel->getProcResource(PI->ProcResourceIdx)->Name
302 << "\n";);
303 CriticalResourceIdx = PI->ProcResourceIdx;
304 }
305 }
306
307 // Make note of an instruction that uses a blocking resource (FPd).
308 if (SU->isUnbuffered) {
309 LastFPdOpCycleIdx = getCurrCycleIdx(SU);
310 LLVM_DEBUG(dbgs() << "++ Last FPd cycle index: " << LastFPdOpCycleIdx
311 << "\n";);
312 }
313
314 // Insert SU into current group by increasing number of slots used
315 // in current group.
316 CurrGroupSize += getNumDecoderSlots(SU);
317 CurrGroupHas4RegOps |= has4RegOps(SU->getInstr());
318 unsigned GroupLim = (CurrGroupHas4RegOps ? 2 : 3);
319 assert((CurrGroupSize <= GroupLim || CurrGroupSize == getNumDecoderSlots(SU))
320 && "SU does not fit into decoder group!");
321
322 // Check if current group is now full/ended. If so, move on to next
323 // group to be ready to evaluate more candidates.
324 if (CurrGroupSize >= GroupLim || SC->EndGroup)
325 nextGroup();
326}
327
329 const MCSchedClassDesc *SC = getSchedClass(SU);
330 if (!SC->isValid())
331 return 0;
332
333 // If SU begins new group, it can either break a current group early
334 // or fit naturally if current group is empty (negative cost).
335 if (SC->BeginGroup) {
336 if (CurrGroupSize)
337 return 3 - CurrGroupSize;
338 return -1;
339 }
340
341 // Similarly, a group-ending SU may either fit well (last in group), or
342 // end the group prematurely.
343 if (SC->EndGroup) {
344 unsigned ResultingGroupSize = (CurrGroupSize + getNumDecoderSlots(SU));
345 if (ResultingGroupSize < 3)
346 return (3 - ResultingGroupSize);
347 return -1;
348 }
349
350 // An instruction with 4 register operands will not fit in last slot.
351 if (CurrGroupSize == 2 && has4RegOps(SU->getInstr()))
352 return 1;
353
354 // Most instructions can be placed in any decoder slot.
355 return 0;
356}
357
358bool SystemZHazardRecognizer::isFPdOpPreferred_distance(SUnit *SU) const {
359 assert (SU->isUnbuffered);
360 // If this is the first FPd op, it should be scheduled high.
361 if (LastFPdOpCycleIdx == UINT_MAX)
362 return true;
363 // If this is not the first PFd op, it should go into the other side
364 // of the processor to use the other FPd unit there. This should
365 // generally happen if two FPd ops are placed with 2 other
366 // instructions between them (modulo 6).
367 unsigned SUCycleIdx = getCurrCycleIdx(SU);
368 if (LastFPdOpCycleIdx > SUCycleIdx)
369 return ((LastFPdOpCycleIdx - SUCycleIdx) == 3);
370 return ((SUCycleIdx - LastFPdOpCycleIdx) == 3);
371}
372
374resourcesCost(SUnit *SU) {
375 int Cost = 0;
376
377 const MCSchedClassDesc *SC = getSchedClass(SU);
378 if (!SC->isValid())
379 return 0;
380
381 // For a FPd op, either return min or max value as indicated by the
382 // distance to any prior FPd op.
383 if (SU->isUnbuffered)
384 Cost = (isFPdOpPreferred_distance(SU) ? INT_MIN : INT_MAX);
385 // For other instructions, give a cost to the use of the critical resource.
386 else if (CriticalResourceIdx != UINT_MAX) {
388 PI = SchedModel->getWriteProcResBegin(SC),
389 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI)
390 if (PI->ProcResourceIdx == CriticalResourceIdx)
391 Cost = PI->ReleaseAtCycle;
392 }
393
394 return Cost;
395}
396
398 bool TakenBranch) {
399 // Make a temporary SUnit.
400 SUnit SU(MI, 0);
401
402 // Set interesting flags.
403 SU.isCall = MI->isCall();
404
405 const MCSchedClassDesc *SC = SchedModel->resolveSchedClass(MI);
406 for (const MCWriteProcResEntry &PRE :
407 make_range(SchedModel->getWriteProcResBegin(SC),
408 SchedModel->getWriteProcResEnd(SC))) {
409 switch (SchedModel->getProcResource(PRE.ProcResourceIdx)->BufferSize) {
410 case 0:
411 SU.hasReservedResource = true;
412 break;
413 case 1:
414 SU.isUnbuffered = true;
415 break;
416 default:
417 break;
418 }
419 }
420
421 unsigned GroupSizeBeforeEmit = CurrGroupSize;
422 EmitInstruction(&SU);
423
424 if (!TakenBranch && isBranchRetTrap(MI)) {
425 // NT Branch on second slot ends group.
426 if (GroupSizeBeforeEmit == 1)
427 nextGroup();
428 }
429
430 if (TakenBranch && CurrGroupSize > 0)
431 nextGroup();
432
433 assert ((!MI->isTerminator() || isBranchRetTrap(MI)) &&
434 "Scheduler: unhandled terminator!");
435}
436
439 // Current decoder group
440 CurrGroupSize = Incoming->CurrGroupSize;
441 LLVM_DEBUG(CurGroupDbg = Incoming->CurGroupDbg;);
442
443 // Processor resources
444 ProcResourceCounters = Incoming->ProcResourceCounters;
445 CriticalResourceIdx = Incoming->CriticalResourceIdx;
446
447 // FPd
448 LastFPdOpCycleIdx = Incoming->LastFPdOpCycleIdx;
449 GrpCount = Incoming->GrpCount;
450}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const char * Msg
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool isBranchRetTrap(MachineInstr *MI)
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specified operand constraint if it is present.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Scheduling unit. This is a node in the scheduling DAG.
bool isCall
Is a function call.
bool isUnbuffered
Uses an unbuffered resource.
bool hasReservedResource
Uses a reserved resource.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
void assign(size_type NumElts, ValueParamT Elt)
int groupingCost(SUnit *SU) const
Return the cost of decoder grouping for SU.
void emitInstruction(MachineInstr *MI, bool TakenBranch=false)
Wrap a non-scheduled instruction in an SU and emit it.
const MCSchedClassDesc * getSchedClass(SUnit *SU) const
Resolves and cache a resolved scheduling class for an SUnit.
void copyState(SystemZHazardRecognizer *Incoming)
Copy counters from end of single predecessor.
void Reset() override
Reset - This callback is invoked when a new block of instructions is about to be schedule.
void dumpSU(SUnit *SU, raw_ostream &OS) const
HazardType getHazardType(SUnit *SU, int Stalls=0) override
getHazardType - Return the hazard type of emitting this node.
void dumpCurrGroup(std::string Msg="") const
int resourcesCost(SUnit *SU)
Return the cost of SU in regards to processor resources usage.
SystemZHazardRecognizer(const SystemZInstrInfo *tii, const TargetSchedModel *SM, const SystemZOptions &CLOpts)
void EmitInstruction(SUnit *SU) override
EmitInstruction - This callback is invoked when an instruction is emitted, to advance the hazard stat...
const MCWriteProcResEntry * ProcResIter
unsigned getNumProcResourceKinds() const
Get the number of kinds of resources for this target.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
This is an optimization pass for GlobalISel generic memory operations.
InstructionCost Cost
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
Define a kind of processor resource that will be modeled by the scheduler.
Definition MCSchedule.h:37
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition MCSchedule.h:124
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
Definition MCSchedule.h:69