1 //===-- SILoadStoreOptimizer.cpp ------------------------------------------===//
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 // This pass tries to fuse DS instructions with close by immediate offsets.
11 // This will fuse operations such as
12 //  ds_read_b32 v0, v2 offset:16
13 //  ds_read_b32 v1, v2 offset:32
14 // ==>
15 //   ds_read2_b32 v[0:1], v2, offset0:4 offset1:8
16 //
17 //
18 // Future improvements:
19 //
20 // - This currently relies on the scheduler to place loads and stores next to
21 //   each other, and then only merges adjacent pairs of instructions. It would
22 //   be good to be more flexible with interleaved instructions, and possibly run
23 //   before scheduling. It currently missing stores of constants because loading
24 //   the constant into the data register is placed between the stores, although
25 //   this is arguably a scheduling problem.
26 //
27 // - Live interval recomputing seems inefficient. This currently only matches
28 //   one pair, and recomputes live intervals and moves on to the next pair. It
29 //   would be better to compute a list of all merges that need to occur.
30 //
31 // - With a list of instructions to process, we can also merge more. If a
32 //   cluster of loads have offsets that are too large to fit in the 8-bit
33 //   offsets, but are close enough to fit in the 8 bits, we can add to the base
34 //   pointer and use the new reduced offsets.
35 //
36 //===----------------------------------------------------------------------===//
37 
38 #include "AMDGPU.h"
39 #include "AMDGPUSubtarget.h"
40 #include "SIInstrInfo.h"
41 #include "SIRegisterInfo.h"
42 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
43 #include "llvm/CodeGen/LiveVariables.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineFunctionPass.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineRegisterInfo.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetMachine.h"
51 
52 using namespace llvm;
53 
54 #define DEBUG_TYPE "si-load-store-opt"
55 
56 namespace {
57 
58 class SILoadStoreOptimizer : public MachineFunctionPass {
59 private:
60   const SIInstrInfo *TII;
61   const SIRegisterInfo *TRI;
62   MachineRegisterInfo *MRI;
63   LiveIntervals *LIS;
64 
65   static bool offsetsCanBeCombined(unsigned Offset0,
66                                    unsigned Offset1,
67                                    unsigned EltSize);
68 
69   MachineBasicBlock::iterator findMatchingDSInst(MachineBasicBlock::iterator I,
70                                                  unsigned EltSize);
71 
72   MachineBasicBlock::iterator mergeRead2Pair(
73     MachineBasicBlock::iterator I,
74     MachineBasicBlock::iterator Paired,
75     unsigned EltSize);
76 
77   MachineBasicBlock::iterator mergeWrite2Pair(
78     MachineBasicBlock::iterator I,
79     MachineBasicBlock::iterator Paired,
80     unsigned EltSize);
81 
82 public:
83   static char ID;
84 
85   SILoadStoreOptimizer()
86       : MachineFunctionPass(ID), TII(nullptr), TRI(nullptr), MRI(nullptr),
87         LIS(nullptr) {}
88 
89   SILoadStoreOptimizer(const TargetMachine &TM_) : MachineFunctionPass(ID) {
90     initializeSILoadStoreOptimizerPass(*PassRegistry::getPassRegistry());
91   }
92 
93   bool optimizeBlock(MachineBasicBlock &MBB);
94 
95   bool runOnMachineFunction(MachineFunction &MF) override;
96 
97   const char *getPassName() const override {
98     return "SI Load / Store Optimizer";
99   }
100 
101   void getAnalysisUsage(AnalysisUsage &AU) const override {
102     AU.setPreservesCFG();
103     AU.addPreserved<SlotIndexes>();
104     AU.addPreserved<LiveIntervals>();
105     AU.addPreserved<LiveVariables>();
106     AU.addRequired<LiveIntervals>();
107 
108     MachineFunctionPass::getAnalysisUsage(AU);
109   }
110 };
111 
112 } // End anonymous namespace.
113 
114 INITIALIZE_PASS_BEGIN(SILoadStoreOptimizer, DEBUG_TYPE,
115                       "SI Load / Store Optimizer", false, false)
116 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
117 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
118 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
119 INITIALIZE_PASS_END(SILoadStoreOptimizer, DEBUG_TYPE,
120                     "SI Load / Store Optimizer", false, false)
121 
122 char SILoadStoreOptimizer::ID = 0;
123 
124 char &llvm::SILoadStoreOptimizerID = SILoadStoreOptimizer::ID;
125 
126 FunctionPass *llvm::createSILoadStoreOptimizerPass(TargetMachine &TM) {
127   return new SILoadStoreOptimizer(TM);
128 }
129 
130 bool SILoadStoreOptimizer::offsetsCanBeCombined(unsigned Offset0,
131                                                 unsigned Offset1,
132                                                 unsigned Size) {
133   // XXX - Would the same offset be OK? Is there any reason this would happen or
134   // be useful?
135   if (Offset0 == Offset1)
136     return false;
137 
138   // This won't be valid if the offset isn't aligned.
139   if ((Offset0 % Size != 0) || (Offset1 % Size != 0))
140     return false;
141 
142   unsigned EltOffset0 = Offset0 / Size;
143   unsigned EltOffset1 = Offset1 / Size;
144 
145   // Check if the new offsets fit in the reduced 8-bit range.
146   if (isUInt<8>(EltOffset0) && isUInt<8>(EltOffset1))
147     return true;
148 
149   // If the offset in elements doesn't fit in 8-bits, we might be able to use
150   // the stride 64 versions.
151   if ((EltOffset0 % 64 != 0) || (EltOffset1 % 64) != 0)
152     return false;
153 
154   return isUInt<8>(EltOffset0 / 64) && isUInt<8>(EltOffset1 / 64);
155 }
156 
157 MachineBasicBlock::iterator
158 SILoadStoreOptimizer::findMatchingDSInst(MachineBasicBlock::iterator I,
159                                          unsigned EltSize){
160   MachineBasicBlock::iterator E = I->getParent()->end();
161   MachineBasicBlock &MBB = *I->getParent();
162   MachineBasicBlock::iterator MBBI = I;
163   ++MBBI;
164 
165   if (MBBI == MBB.end() || MBBI->getOpcode() != I->getOpcode())
166     return E;
167 
168   // Don't merge volatiles.
169   if (MBBI->hasOrderedMemoryRef())
170     return E;
171 
172   int AddrIdx = AMDGPU::getNamedOperandIdx(I->getOpcode(), AMDGPU::OpName::addr);
173   const MachineOperand &AddrReg0 = I->getOperand(AddrIdx);
174   const MachineOperand &AddrReg1 = MBBI->getOperand(AddrIdx);
175 
176   // Check same base pointer. Be careful of subregisters, which can occur with
177   // vectors of pointers.
178   if (AddrReg0.getReg() == AddrReg1.getReg() &&
179       AddrReg0.getSubReg() == AddrReg1.getSubReg()) {
180     int OffsetIdx = AMDGPU::getNamedOperandIdx(I->getOpcode(),
181                                                AMDGPU::OpName::offset);
182     unsigned Offset0 = I->getOperand(OffsetIdx).getImm() & 0xffff;
183     unsigned Offset1 = MBBI->getOperand(OffsetIdx).getImm() & 0xffff;
184 
185     // Check both offsets fit in the reduced range.
186     if (offsetsCanBeCombined(Offset0, Offset1, EltSize))
187       return MBBI;
188   }
189 
190   return E;
191 }
192 
193 MachineBasicBlock::iterator  SILoadStoreOptimizer::mergeRead2Pair(
194   MachineBasicBlock::iterator I,
195   MachineBasicBlock::iterator Paired,
196   unsigned EltSize) {
197   MachineBasicBlock *MBB = I->getParent();
198 
199   // Be careful, since the addresses could be subregisters themselves in weird
200   // cases, like vectors of pointers.
201   const MachineOperand *AddrReg = TII->getNamedOperand(*I, AMDGPU::OpName::addr);
202 
203   const MachineOperand *Dest0 = TII->getNamedOperand(*I, AMDGPU::OpName::vdst);
204   const MachineOperand *Dest1 = TII->getNamedOperand(*Paired, AMDGPU::OpName::vdst);
205 
206   unsigned Offset0
207     = TII->getNamedOperand(*I, AMDGPU::OpName::offset)->getImm() & 0xffff;
208   unsigned Offset1
209     = TII->getNamedOperand(*Paired, AMDGPU::OpName::offset)->getImm() & 0xffff;
210 
211   unsigned NewOffset0 = Offset0 / EltSize;
212   unsigned NewOffset1 = Offset1 / EltSize;
213   unsigned Opc = (EltSize == 4) ? AMDGPU::DS_READ2_B32 : AMDGPU::DS_READ2_B64;
214 
215   // Prefer the st64 form if we can use it, even if we can fit the offset in the
216   // non st64 version. I'm not sure if there's any real reason to do this.
217   bool UseST64 = (NewOffset0 % 64 == 0) && (NewOffset1 % 64 == 0);
218   if (UseST64) {
219     NewOffset0 /= 64;
220     NewOffset1 /= 64;
221     Opc = (EltSize == 4) ? AMDGPU::DS_READ2ST64_B32 : AMDGPU::DS_READ2ST64_B64;
222   }
223 
224   assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
225          (NewOffset0 != NewOffset1) &&
226          "Computed offset doesn't fit");
227 
228   const MCInstrDesc &Read2Desc = TII->get(Opc);
229 
230   const TargetRegisterClass *SuperRC
231     = (EltSize == 4) ? &AMDGPU::VReg_64RegClass : &AMDGPU::VReg_128RegClass;
232   unsigned DestReg = MRI->createVirtualRegister(SuperRC);
233 
234   DebugLoc DL = I->getDebugLoc();
235   MachineInstrBuilder Read2
236     = BuildMI(*MBB, I, DL, Read2Desc, DestReg)
237     .addOperand(*AddrReg) // addr
238     .addImm(NewOffset0) // offset0
239     .addImm(NewOffset1) // offset1
240     .addImm(0) // gds
241     .addMemOperand(*I->memoperands_begin())
242     .addMemOperand(*Paired->memoperands_begin());
243 
244   unsigned SubRegIdx0 = (EltSize == 4) ? AMDGPU::sub0 : AMDGPU::sub0_sub1;
245   unsigned SubRegIdx1 = (EltSize == 4) ? AMDGPU::sub1 : AMDGPU::sub2_sub3;
246 
247   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
248 
249   // Copy to the old destination registers.
250   MachineInstr *Copy0 = BuildMI(*MBB, I, DL, CopyDesc)
251     .addOperand(*Dest0) // Copy to same destination including flags and sub reg.
252     .addReg(DestReg, 0, SubRegIdx0);
253   MachineInstr *Copy1 = BuildMI(*MBB, I, DL, CopyDesc)
254     .addOperand(*Dest1)
255     .addReg(DestReg, RegState::Kill, SubRegIdx1);
256 
257   LIS->InsertMachineInstrInMaps(*Read2);
258 
259   // repairLiveintervalsInRange() doesn't handle physical register, so we have
260   // to update the M0 range manually.
261   SlotIndex PairedIndex = LIS->getInstructionIndex(*Paired);
262   LiveRange &M0Range = LIS->getRegUnit(*MCRegUnitIterator(AMDGPU::M0, TRI));
263   LiveRange::Segment *M0Segment = M0Range.getSegmentContaining(PairedIndex);
264   bool UpdateM0Range = M0Segment->end == PairedIndex.getRegSlot();
265 
266   // The new write to the original destination register is now the copy. Steal
267   // the old SlotIndex.
268   LIS->ReplaceMachineInstrInMaps(*I, *Copy0);
269   LIS->ReplaceMachineInstrInMaps(*Paired, *Copy1);
270 
271   I->eraseFromParent();
272   Paired->eraseFromParent();
273 
274   LiveInterval &AddrRegLI = LIS->getInterval(AddrReg->getReg());
275   LIS->shrinkToUses(&AddrRegLI);
276 
277   LIS->createAndComputeVirtRegInterval(DestReg);
278 
279   if (UpdateM0Range) {
280     SlotIndex Read2Index = LIS->getInstructionIndex(*Read2);
281     M0Segment->end = Read2Index.getRegSlot();
282   }
283 
284   DEBUG(dbgs() << "Inserted read2: " << *Read2 << '\n');
285   return Read2.getInstr();
286 }
287 
288 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeWrite2Pair(
289   MachineBasicBlock::iterator I,
290   MachineBasicBlock::iterator Paired,
291   unsigned EltSize) {
292   MachineBasicBlock *MBB = I->getParent();
293 
294   // Be sure to use .addOperand(), and not .addReg() with these. We want to be
295   // sure we preserve the subregister index and any register flags set on them.
296   const MachineOperand *Addr = TII->getNamedOperand(*I, AMDGPU::OpName::addr);
297   const MachineOperand *Data0 = TII->getNamedOperand(*I, AMDGPU::OpName::data0);
298   const MachineOperand *Data1
299     = TII->getNamedOperand(*Paired, AMDGPU::OpName::data0);
300 
301 
302   unsigned Offset0
303     = TII->getNamedOperand(*I, AMDGPU::OpName::offset)->getImm() & 0xffff;
304   unsigned Offset1
305     = TII->getNamedOperand(*Paired, AMDGPU::OpName::offset)->getImm() & 0xffff;
306 
307   unsigned NewOffset0 = Offset0 / EltSize;
308   unsigned NewOffset1 = Offset1 / EltSize;
309   unsigned Opc = (EltSize == 4) ? AMDGPU::DS_WRITE2_B32 : AMDGPU::DS_WRITE2_B64;
310 
311   // Prefer the st64 form if we can use it, even if we can fit the offset in the
312   // non st64 version. I'm not sure if there's any real reason to do this.
313   bool UseST64 = (NewOffset0 % 64 == 0) && (NewOffset1 % 64 == 0);
314   if (UseST64) {
315     NewOffset0 /= 64;
316     NewOffset1 /= 64;
317     Opc = (EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32 : AMDGPU::DS_WRITE2ST64_B64;
318   }
319 
320   assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
321          (NewOffset0 != NewOffset1) &&
322          "Computed offset doesn't fit");
323 
324   const MCInstrDesc &Write2Desc = TII->get(Opc);
325   DebugLoc DL = I->getDebugLoc();
326 
327   // repairLiveintervalsInRange() doesn't handle physical register, so we have
328   // to update the M0 range manually.
329   SlotIndex PairedIndex = LIS->getInstructionIndex(*Paired);
330   LiveRange &M0Range = LIS->getRegUnit(*MCRegUnitIterator(AMDGPU::M0, TRI));
331   LiveRange::Segment *M0Segment = M0Range.getSegmentContaining(PairedIndex);
332   bool UpdateM0Range = M0Segment->end == PairedIndex.getRegSlot();
333 
334   MachineInstrBuilder Write2
335     = BuildMI(*MBB, I, DL, Write2Desc)
336     .addOperand(*Addr) // addr
337     .addOperand(*Data0) // data0
338     .addOperand(*Data1) // data1
339     .addImm(NewOffset0) // offset0
340     .addImm(NewOffset1) // offset1
341     .addImm(0) // gds
342     .addMemOperand(*I->memoperands_begin())
343     .addMemOperand(*Paired->memoperands_begin());
344 
345   // XXX - How do we express subregisters here?
346   unsigned OrigRegs[] = { Data0->getReg(), Data1->getReg(), Addr->getReg() };
347 
348   LIS->RemoveMachineInstrFromMaps(*I);
349   LIS->RemoveMachineInstrFromMaps(*Paired);
350   I->eraseFromParent();
351   Paired->eraseFromParent();
352 
353   // This doesn't handle physical registers like M0
354   LIS->repairIntervalsInRange(MBB, Write2, Write2, OrigRegs);
355 
356   if (UpdateM0Range) {
357     SlotIndex Write2Index = LIS->getInstructionIndex(*Write2);
358     M0Segment->end = Write2Index.getRegSlot();
359   }
360 
361   DEBUG(dbgs() << "Inserted write2 inst: " << *Write2 << '\n');
362   return Write2.getInstr();
363 }
364 
365 // Scan through looking for adjacent LDS operations with constant offsets from
366 // the same base register. We rely on the scheduler to do the hard work of
367 // clustering nearby loads, and assume these are all adjacent.
368 bool SILoadStoreOptimizer::optimizeBlock(MachineBasicBlock &MBB) {
369   bool Modified = false;
370 
371   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
372     MachineInstr &MI = *I;
373 
374     // Don't combine if volatile.
375     if (MI.hasOrderedMemoryRef()) {
376       ++I;
377       continue;
378     }
379 
380     unsigned Opc = MI.getOpcode();
381     if (Opc == AMDGPU::DS_READ_B32 || Opc == AMDGPU::DS_READ_B64) {
382       unsigned Size = (Opc == AMDGPU::DS_READ_B64) ? 8 : 4;
383       MachineBasicBlock::iterator Match = findMatchingDSInst(I, Size);
384       if (Match != E) {
385         Modified = true;
386         I = mergeRead2Pair(I, Match, Size);
387       } else {
388         ++I;
389       }
390 
391       continue;
392     } else if (Opc == AMDGPU::DS_WRITE_B32 || Opc == AMDGPU::DS_WRITE_B64) {
393       unsigned Size = (Opc == AMDGPU::DS_WRITE_B64) ? 8 : 4;
394       MachineBasicBlock::iterator Match = findMatchingDSInst(I, Size);
395       if (Match != E) {
396         Modified = true;
397         I = mergeWrite2Pair(I, Match, Size);
398       } else {
399         ++I;
400       }
401 
402       continue;
403     }
404 
405     ++I;
406   }
407 
408   return Modified;
409 }
410 
411 bool SILoadStoreOptimizer::runOnMachineFunction(MachineFunction &MF) {
412   if (skipFunction(*MF.getFunction()))
413     return false;
414 
415   const SISubtarget &STM = MF.getSubtarget<SISubtarget>();
416   if (!STM.loadStoreOptEnabled())
417     return false;
418 
419   TII = STM.getInstrInfo();
420   TRI = &TII->getRegisterInfo();
421 
422   MRI = &MF.getRegInfo();
423 
424   LIS = &getAnalysis<LiveIntervals>();
425 
426   DEBUG(dbgs() << "Running SILoadStoreOptimizer\n");
427 
428   assert(!MRI->isSSA());
429 
430   bool Modified = false;
431 
432   for (MachineBasicBlock &MBB : MF)
433     Modified |= optimizeBlock(MBB);
434 
435   return Modified;
436 }
437