Have MachineFunction cache a pointer to the subtarget to make lookups
[oota-llvm.git] / lib / Target / R600 / SIInsertWaits.cpp
1 //===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===//
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 /// \file
11 /// \brief Insert wait instructions for memory reads and writes.
12 ///
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.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "AMDGPU.h"
20 #include "AMDGPUSubtarget.h"
21 #include "SIInstrInfo.h"
22 #include "SIMachineFunctionInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27
28 using namespace llvm;
29
30 namespace {
31
32 /// \brief One variable for each of the hardware counters
33 typedef union {
34   struct {
35     unsigned VM;
36     unsigned EXP;
37     unsigned LGKM;
38   } Named;
39   unsigned Array[3];
40
41 } Counters;
42
43 typedef Counters RegCounters[512];
44 typedef std::pair<unsigned, unsigned> RegInterval;
45
46 class SIInsertWaits : public MachineFunctionPass {
47
48 private:
49   static char ID;
50   const SIInstrInfo *TII;
51   const SIRegisterInfo *TRI;
52   const MachineRegisterInfo *MRI;
53
54   /// \brief Constant hardware limits
55   static const Counters WaitCounts;
56
57   /// \brief Constant zero value
58   static const Counters ZeroCounts;
59
60   /// \brief Counter values we have already waited on.
61   Counters WaitedOn;
62
63   /// \brief Counter values for last instruction issued.
64   Counters LastIssued;
65
66   /// \brief Registers used by async instructions.
67   RegCounters UsedRegs;
68
69   /// \brief Registers defined by async instructions.
70   RegCounters DefinedRegs;
71
72   /// \brief Different export instruction types seen since last wait.
73   unsigned ExpInstrTypesSeen;
74
75   /// \brief Get increment/decrement amount for this instruction.
76   Counters getHwCounts(MachineInstr &MI);
77
78   /// \brief Is operand relevant for async execution?
79   bool isOpRelevant(MachineOperand &Op);
80
81   /// \brief Get register interval an operand affects.
82   RegInterval getRegInterval(MachineOperand &Op);
83
84   /// \brief Handle instructions async components
85   void pushInstruction(MachineInstr &MI);
86
87   /// \brief Insert the actual wait instruction
88   bool insertWait(MachineBasicBlock &MBB,
89                   MachineBasicBlock::iterator I,
90                   const Counters &Counts);
91
92   /// \brief Do we need def2def checks?
93   bool unorderedDefines(MachineInstr &MI);
94
95   /// \brief Resolve all operand dependencies to counter requirements
96   Counters handleOperands(MachineInstr &MI);
97
98 public:
99   SIInsertWaits(TargetMachine &tm) :
100     MachineFunctionPass(ID),
101     TII(nullptr),
102     TRI(nullptr),
103     ExpInstrTypesSeen(0) { }
104
105   bool runOnMachineFunction(MachineFunction &MF) override;
106
107   const char *getPassName() const override {
108     return "SI insert wait  instructions";
109   }
110
111 };
112
113 } // End anonymous namespace
114
115 char SIInsertWaits::ID = 0;
116
117 const Counters SIInsertWaits::WaitCounts = { { 15, 7, 7 } };
118 const Counters SIInsertWaits::ZeroCounts = { { 0, 0, 0 } };
119
120 FunctionPass *llvm::createSIInsertWaits(TargetMachine &tm) {
121   return new SIInsertWaits(tm);
122 }
123
124 Counters SIInsertWaits::getHwCounts(MachineInstr &MI) {
125
126   uint64_t TSFlags = TII->get(MI.getOpcode()).TSFlags;
127   Counters Result;
128
129   Result.Named.VM = !!(TSFlags & SIInstrFlags::VM_CNT);
130
131   // Only consider stores or EXP for EXP_CNT
132   Result.Named.EXP = !!(TSFlags & SIInstrFlags::EXP_CNT &&
133       (MI.getOpcode() == AMDGPU::EXP || MI.getDesc().mayStore()));
134
135   // LGKM may uses larger values
136   if (TSFlags & SIInstrFlags::LGKM_CNT) {
137
138     if (TII->isSMRD(MI.getOpcode())) {
139
140       MachineOperand &Op = MI.getOperand(0);
141       assert(Op.isReg() && "First LGKM operand must be a register!");
142
143       unsigned Reg = Op.getReg();
144       unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
145       Result.Named.LGKM = Size > 4 ? 2 : 1;
146
147     } else {
148       // DS
149       Result.Named.LGKM = 1;
150     }
151
152   } else {
153     Result.Named.LGKM = 0;
154   }
155
156   return Result;
157 }
158
159 bool SIInsertWaits::isOpRelevant(MachineOperand &Op) {
160
161   // Constants are always irrelevant
162   if (!Op.isReg())
163     return false;
164
165   // Defines are always relevant
166   if (Op.isDef())
167     return true;
168
169   // For exports all registers are relevant
170   MachineInstr &MI = *Op.getParent();
171   if (MI.getOpcode() == AMDGPU::EXP)
172     return true;
173
174   // For stores the stored value is also relevant
175   if (!MI.getDesc().mayStore())
176     return false;
177
178   for (MachineInstr::mop_iterator I = MI.operands_begin(),
179        E = MI.operands_end(); I != E; ++I) {
180
181     if (I->isReg() && I->isUse())
182       return Op.isIdenticalTo(*I);
183   }
184
185   return false;
186 }
187
188 RegInterval SIInsertWaits::getRegInterval(MachineOperand &Op) {
189
190   if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()))
191     return std::make_pair(0, 0);
192
193   unsigned Reg = Op.getReg();
194   unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
195
196   assert(Size >= 4);
197
198   RegInterval Result;
199   Result.first = TRI->getEncodingValue(Reg);
200   Result.second = Result.first + Size / 4;
201
202   return Result;
203 }
204
205 void SIInsertWaits::pushInstruction(MachineInstr &MI) {
206
207   // Get the hardware counter increments and sum them up
208   Counters Increment = getHwCounts(MI);
209   unsigned Sum = 0;
210
211   for (unsigned i = 0; i < 3; ++i) {
212     LastIssued.Array[i] += Increment.Array[i];
213     Sum += Increment.Array[i];
214   }
215
216   // If we don't increase anything then that's it
217   if (Sum == 0)
218     return;
219
220   // Remember which export instructions we have seen
221   if (Increment.Named.EXP) {
222     ExpInstrTypesSeen |= MI.getOpcode() == AMDGPU::EXP ? 1 : 2;
223   }
224
225   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
226
227     MachineOperand &Op = MI.getOperand(i);
228     if (!isOpRelevant(Op))
229       continue;
230
231     RegInterval Interval = getRegInterval(Op);
232     for (unsigned j = Interval.first; j < Interval.second; ++j) {
233
234       // Remember which registers we define
235       if (Op.isDef())
236         DefinedRegs[j] = LastIssued;
237
238       // and which one we are using
239       if (Op.isUse())
240         UsedRegs[j] = LastIssued;
241     }
242   }
243 }
244
245 bool SIInsertWaits::insertWait(MachineBasicBlock &MBB,
246                                MachineBasicBlock::iterator I,
247                                const Counters &Required) {
248
249   // End of program? No need to wait on anything
250   if (I != MBB.end() && I->getOpcode() == AMDGPU::S_ENDPGM)
251     return false;
252
253   // Figure out if the async instructions execute in order
254   bool Ordered[3];
255
256   // VM_CNT is always ordered
257   Ordered[0] = true;
258
259   // EXP_CNT is unordered if we have both EXP & VM-writes
260   Ordered[1] = ExpInstrTypesSeen == 3;
261
262   // LGKM_CNT is handled as always unordered. TODO: Handle LDS and GDS
263   Ordered[2] = false;
264
265   // The values we are going to put into the S_WAITCNT instruction
266   Counters Counts = WaitCounts;
267
268   // Do we really need to wait?
269   bool NeedWait = false;
270
271   for (unsigned i = 0; i < 3; ++i) {
272
273     if (Required.Array[i] <= WaitedOn.Array[i])
274       continue;
275
276     NeedWait = true;
277
278     if (Ordered[i]) {
279       unsigned Value = LastIssued.Array[i] - Required.Array[i];
280
281       // Adjust the value to the real hardware possibilities.
282       Counts.Array[i] = std::min(Value, WaitCounts.Array[i]);
283
284     } else
285       Counts.Array[i] = 0;
286
287     // Remember on what we have waited on.
288     WaitedOn.Array[i] = LastIssued.Array[i] - Counts.Array[i];
289   }
290
291   if (!NeedWait)
292     return false;
293
294   // Reset EXP_CNT instruction types
295   if (Counts.Named.EXP == 0)
296     ExpInstrTypesSeen = 0;
297
298   // Build the wait instruction
299   BuildMI(MBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
300           .addImm((Counts.Named.VM & 0xF) |
301                   ((Counts.Named.EXP & 0x7) << 4) |
302                   ((Counts.Named.LGKM & 0x7) << 8));
303
304   return true;
305 }
306
307 /// \brief helper function for handleOperands
308 static void increaseCounters(Counters &Dst, const Counters &Src) {
309
310   for (unsigned i = 0; i < 3; ++i)
311     Dst.Array[i] = std::max(Dst.Array[i], Src.Array[i]);
312 }
313
314 Counters SIInsertWaits::handleOperands(MachineInstr &MI) {
315
316   Counters Result = ZeroCounts;
317
318   // S_SENDMSG implicitly waits for all outstanding LGKM transfers to finish,
319   // but we also want to wait for any other outstanding transfers before
320   // signalling other hardware blocks
321   if (MI.getOpcode() == AMDGPU::S_SENDMSG)
322     return LastIssued;
323
324   // For each register affected by this
325   // instruction increase the result sequence
326   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
327
328     MachineOperand &Op = MI.getOperand(i);
329     RegInterval Interval = getRegInterval(Op);
330     for (unsigned j = Interval.first; j < Interval.second; ++j) {
331
332       if (Op.isDef()) {
333         increaseCounters(Result, UsedRegs[j]);
334         increaseCounters(Result, DefinedRegs[j]);
335       }
336
337       if (Op.isUse())
338         increaseCounters(Result, DefinedRegs[j]);
339     }
340   }
341
342   return Result;
343 }
344
345 // FIXME: Insert waits listed in Table 4.2 "Required User-Inserted Wait States"
346 // around other non-memory instructions.
347 bool SIInsertWaits::runOnMachineFunction(MachineFunction &MF) {
348   bool Changes = false;
349
350   TII = static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo());
351   TRI =
352       static_cast<const SIRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
353
354   MRI = &MF.getRegInfo();
355
356   WaitedOn = ZeroCounts;
357   LastIssued = ZeroCounts;
358
359   memset(&UsedRegs, 0, sizeof(UsedRegs));
360   memset(&DefinedRegs, 0, sizeof(DefinedRegs));
361
362   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
363        BI != BE; ++BI) {
364
365     MachineBasicBlock &MBB = *BI;
366     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
367          I != E; ++I) {
368
369       Changes |= insertWait(MBB, I, handleOperands(*I));
370       pushInstruction(*I);
371     }
372
373     // Wait for everything at the end of the MBB
374     Changes |= insertWait(MBB, MBB.getFirstTerminator(), LastIssued);
375   }
376
377   return Changes;
378 }