1 //===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Insert wait instructions for memory reads and writes.
13 /// Memory reads and writes are issued asynchronously, so we need to insert
14 /// S_WAITCNT instructions when we want to access any of their results or
15 /// overwrite any register that's used asynchronously.
17 //===----------------------------------------------------------------------===//
20 #include "AMDGPUSubtarget.h"
21 #include "SIDefines.h"
22 #include "SIInstrInfo.h"
23 #include "SIMachineFunctionInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 /// \brief One variable for each of the hardware counters
50 typedef Counters RegCounters[512];
51 typedef std::pair<unsigned, unsigned> RegInterval;
53 class SIInsertWaits : public MachineFunctionPass {
57 const SIInstrInfo *TII;
58 const SIRegisterInfo *TRI;
59 const MachineRegisterInfo *MRI;
61 /// \brief Constant hardware limits
62 static const Counters WaitCounts;
64 /// \brief Constant zero value
65 static const Counters ZeroCounts;
67 /// \brief Counter values we have already waited on.
70 /// \brief Counter values for last instruction issued.
73 /// \brief Registers used by async instructions.
76 /// \brief Registers defined by async instructions.
77 RegCounters DefinedRegs;
79 /// \brief Different export instruction types seen since last wait.
80 unsigned ExpInstrTypesSeen;
82 /// \brief Type of the last opcode.
83 InstType LastOpcodeType;
85 /// \brief Get increment/decrement amount for this instruction.
86 Counters getHwCounts(MachineInstr &MI);
88 /// \brief Is operand relevant for async execution?
89 bool isOpRelevant(MachineOperand &Op);
91 /// \brief Get register interval an operand affects.
92 RegInterval getRegInterval(MachineOperand &Op);
94 /// \brief Handle instructions async components
95 void pushInstruction(MachineBasicBlock &MBB,
96 MachineBasicBlock::iterator I);
98 /// \brief Insert the actual wait instruction
99 bool insertWait(MachineBasicBlock &MBB,
100 MachineBasicBlock::iterator I,
101 const Counters &Counts);
103 /// \brief Do we need def2def checks?
104 bool unorderedDefines(MachineInstr &MI);
106 /// \brief Resolve all operand dependencies to counter requirements
107 Counters handleOperands(MachineInstr &MI);
110 SIInsertWaits(TargetMachine &tm) :
111 MachineFunctionPass(ID),
114 ExpInstrTypesSeen(0) { }
116 bool runOnMachineFunction(MachineFunction &MF) override;
118 const char *getPassName() const override {
119 return "SI insert wait instructions";
124 } // End anonymous namespace
126 char SIInsertWaits::ID = 0;
128 const Counters SIInsertWaits::WaitCounts = { { 15, 7, 7 } };
129 const Counters SIInsertWaits::ZeroCounts = { { 0, 0, 0 } };
131 FunctionPass *llvm::createSIInsertWaits(TargetMachine &tm) {
132 return new SIInsertWaits(tm);
135 Counters SIInsertWaits::getHwCounts(MachineInstr &MI) {
137 uint64_t TSFlags = TII->get(MI.getOpcode()).TSFlags;
140 Result.Named.VM = !!(TSFlags & SIInstrFlags::VM_CNT);
142 // Only consider stores or EXP for EXP_CNT
143 Result.Named.EXP = !!(TSFlags & SIInstrFlags::EXP_CNT &&
144 (MI.getOpcode() == AMDGPU::EXP || MI.getDesc().mayStore()));
146 // LGKM may uses larger values
147 if (TSFlags & SIInstrFlags::LGKM_CNT) {
149 if (TII->isSMRD(MI.getOpcode())) {
151 MachineOperand &Op = MI.getOperand(0);
152 assert(Op.isReg() && "First LGKM operand must be a register!");
154 unsigned Reg = Op.getReg();
155 unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
156 Result.Named.LGKM = Size > 4 ? 2 : 1;
160 Result.Named.LGKM = 1;
164 Result.Named.LGKM = 0;
170 bool SIInsertWaits::isOpRelevant(MachineOperand &Op) {
172 // Constants are always irrelevant
176 // Defines are always relevant
180 // For exports all registers are relevant
181 MachineInstr &MI = *Op.getParent();
182 if (MI.getOpcode() == AMDGPU::EXP)
185 // For stores the stored value is also relevant
186 if (!MI.getDesc().mayStore())
189 for (MachineInstr::mop_iterator I = MI.operands_begin(),
190 E = MI.operands_end(); I != E; ++I) {
192 if (I->isReg() && I->isUse())
193 return Op.isIdenticalTo(*I);
199 RegInterval SIInsertWaits::getRegInterval(MachineOperand &Op) {
201 if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()))
202 return std::make_pair(0, 0);
204 unsigned Reg = Op.getReg();
205 unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
210 Result.first = TRI->getEncodingValue(Reg);
211 Result.second = Result.first + Size / 4;
216 void SIInsertWaits::pushInstruction(MachineBasicBlock &MBB,
217 MachineBasicBlock::iterator I) {
219 // Get the hardware counter increments and sum them up
220 Counters Increment = getHwCounts(*I);
223 for (unsigned i = 0; i < 3; ++i) {
224 LastIssued.Array[i] += Increment.Array[i];
225 Sum += Increment.Array[i];
228 // If we don't increase anything then that's it
230 LastOpcodeType = OTHER;
234 if (TRI->ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
235 // Any occurence of consecutive VMEM or SMEM instructions forms a VMEM
236 // or SMEM clause, respectively.
238 // The temporary workaround is to break the clauses with S_NOP.
240 // The proper solution would be to allocate registers such that all source
241 // and destination registers don't overlap, e.g. this is illegal:
244 if ((LastOpcodeType == SMEM && TII->isSMRD(I->getOpcode())) ||
245 (LastOpcodeType == VMEM && Increment.Named.VM)) {
246 // Insert a NOP to break the clause.
247 BuildMI(MBB, I, DebugLoc(), TII->get(AMDGPU::S_NOP))
251 if (TII->isSMRD(I->getOpcode()))
252 LastOpcodeType = SMEM;
253 else if (Increment.Named.VM)
254 LastOpcodeType = VMEM;
257 // Remember which export instructions we have seen
258 if (Increment.Named.EXP) {
259 ExpInstrTypesSeen |= I->getOpcode() == AMDGPU::EXP ? 1 : 2;
262 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
264 MachineOperand &Op = I->getOperand(i);
265 if (!isOpRelevant(Op))
268 RegInterval Interval = getRegInterval(Op);
269 for (unsigned j = Interval.first; j < Interval.second; ++j) {
271 // Remember which registers we define
273 DefinedRegs[j] = LastIssued;
275 // and which one we are using
277 UsedRegs[j] = LastIssued;
282 bool SIInsertWaits::insertWait(MachineBasicBlock &MBB,
283 MachineBasicBlock::iterator I,
284 const Counters &Required) {
286 // End of program? No need to wait on anything
287 if (I != MBB.end() && I->getOpcode() == AMDGPU::S_ENDPGM)
290 // Figure out if the async instructions execute in order
293 // VM_CNT is always ordered
296 // EXP_CNT is unordered if we have both EXP & VM-writes
297 Ordered[1] = ExpInstrTypesSeen == 3;
299 // LGKM_CNT is handled as always unordered. TODO: Handle LDS and GDS
302 // The values we are going to put into the S_WAITCNT instruction
303 Counters Counts = WaitCounts;
305 // Do we really need to wait?
306 bool NeedWait = false;
308 for (unsigned i = 0; i < 3; ++i) {
310 if (Required.Array[i] <= WaitedOn.Array[i])
316 unsigned Value = LastIssued.Array[i] - Required.Array[i];
318 // Adjust the value to the real hardware possibilities.
319 Counts.Array[i] = std::min(Value, WaitCounts.Array[i]);
324 // Remember on what we have waited on.
325 WaitedOn.Array[i] = LastIssued.Array[i] - Counts.Array[i];
331 // Reset EXP_CNT instruction types
332 if (Counts.Named.EXP == 0)
333 ExpInstrTypesSeen = 0;
335 // Build the wait instruction
336 BuildMI(MBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
337 .addImm((Counts.Named.VM & 0xF) |
338 ((Counts.Named.EXP & 0x7) << 4) |
339 ((Counts.Named.LGKM & 0x7) << 8));
341 LastOpcodeType = OTHER;
345 /// \brief helper function for handleOperands
346 static void increaseCounters(Counters &Dst, const Counters &Src) {
348 for (unsigned i = 0; i < 3; ++i)
349 Dst.Array[i] = std::max(Dst.Array[i], Src.Array[i]);
352 Counters SIInsertWaits::handleOperands(MachineInstr &MI) {
354 Counters Result = ZeroCounts;
356 // S_SENDMSG implicitly waits for all outstanding LGKM transfers to finish,
357 // but we also want to wait for any other outstanding transfers before
358 // signalling other hardware blocks
359 if (MI.getOpcode() == AMDGPU::S_SENDMSG)
362 // For each register affected by this
363 // instruction increase the result sequence
364 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
366 MachineOperand &Op = MI.getOperand(i);
367 RegInterval Interval = getRegInterval(Op);
368 for (unsigned j = Interval.first; j < Interval.second; ++j) {
371 increaseCounters(Result, UsedRegs[j]);
372 increaseCounters(Result, DefinedRegs[j]);
376 increaseCounters(Result, DefinedRegs[j]);
383 // FIXME: Insert waits listed in Table 4.2 "Required User-Inserted Wait States"
384 // around other non-memory instructions.
385 bool SIInsertWaits::runOnMachineFunction(MachineFunction &MF) {
386 bool Changes = false;
388 TII = static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo());
390 static_cast<const SIRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
392 MRI = &MF.getRegInfo();
394 WaitedOn = ZeroCounts;
395 LastIssued = ZeroCounts;
396 LastOpcodeType = OTHER;
398 memset(&UsedRegs, 0, sizeof(UsedRegs));
399 memset(&DefinedRegs, 0, sizeof(DefinedRegs));
401 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
404 MachineBasicBlock &MBB = *BI;
405 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
408 Changes |= insertWait(MBB, I, handleOperands(*I));
409 pushInstruction(MBB, I);
412 // Wait for everything at the end of the MBB
413 Changes |= insertWait(MBB, MBB.getFirstTerminator(), LastIssued);