R600/SI: Add load / store machine optimizer pass.
[oota-llvm.git] / lib / Target / R600 / SILoadStoreOptimizer.cpp
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 "SIInstrInfo.h"
40 #include "SIRegisterInfo.h"
41 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
42 #include "llvm/CodeGen/LiveVariables.h"
43 #include "llvm/CodeGen/MachineFunction.h"
44 #include "llvm/CodeGen/MachineFunctionPass.h"
45 #include "llvm/CodeGen/MachineInstrBuilder.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Target/TargetMachine.h"
49
50 using namespace llvm;
51
52 #define DEBUG_TYPE "si-load-store-opt"
53
54 namespace {
55
56 class SILoadStoreOptimizer : public MachineFunctionPass {
57 private:
58   const TargetMachine *TM;
59   const SIInstrInfo *TII;
60   const SIRegisterInfo *TRI;
61   MachineRegisterInfo *MRI;
62   LiveIntervals *LIS;
63
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   void updateRegDefsUses(unsigned SrcReg,
73                          unsigned DstReg,
74                          unsigned SubIdx);
75
76   MachineBasicBlock::iterator mergeRead2Pair(
77     MachineBasicBlock::iterator I,
78     MachineBasicBlock::iterator Paired,
79     unsigned EltSize,
80     const MCInstrDesc &Read2InstDesc);
81
82   MachineBasicBlock::iterator mergeWrite2Pair(
83     MachineBasicBlock::iterator I,
84     MachineBasicBlock::iterator Paired,
85     unsigned EltSize,
86     const MCInstrDesc &Write2InstDesc);
87
88 public:
89   static char ID;
90
91   SILoadStoreOptimizer() :
92     MachineFunctionPass(ID),
93     TM(nullptr),
94     TII(nullptr),
95     TRI(nullptr),
96     MRI(nullptr),
97     LIS(nullptr) {
98
99   }
100
101   SILoadStoreOptimizer(const TargetMachine &TM_) :
102     MachineFunctionPass(ID),
103     TM(&TM_),
104     TII(static_cast<const SIInstrInfo*>(TM->getSubtargetImpl()->getInstrInfo())) {
105     initializeSILoadStoreOptimizerPass(*PassRegistry::getPassRegistry());
106   }
107
108   bool optimizeBlock(MachineBasicBlock &MBB);
109
110   bool runOnMachineFunction(MachineFunction &MF) override;
111
112   const char *getPassName() const override {
113     return "SI Load / Store Optimizer";
114   }
115
116   void getAnalysisUsage(AnalysisUsage &AU) const override {
117     AU.setPreservesCFG();
118     AU.addPreserved<SlotIndexes>();
119     AU.addPreserved<LiveIntervals>();
120     AU.addPreserved<LiveVariables>();
121     AU.addRequired<LiveIntervals>();
122
123     MachineFunctionPass::getAnalysisUsage(AU);
124   }
125 };
126
127 } // End anonymous namespace.
128
129 INITIALIZE_PASS_BEGIN(SILoadStoreOptimizer, DEBUG_TYPE,
130                       "SI Load / Store Optimizer", false, false)
131 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
132 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
133 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
134 INITIALIZE_PASS_END(SILoadStoreOptimizer, DEBUG_TYPE,
135                     "SI Load / Store Optimizer", false, false)
136
137 char SILoadStoreOptimizer::ID = 0;
138
139 char &llvm::SILoadStoreOptimizerID = SILoadStoreOptimizer::ID;
140
141 FunctionPass *llvm::createSILoadStoreOptimizerPass(TargetMachine &TM) {
142   return new SILoadStoreOptimizer(TM);
143 }
144
145 bool SILoadStoreOptimizer::offsetsCanBeCombined(unsigned Offset0,
146                                                 unsigned Offset1,
147                                                 unsigned EltSize) {
148   // XXX - Would the same offset be OK? Is there any reason this would happen or
149   // be useful?
150   return (Offset0 != Offset1) &&
151     isUInt<8>(Offset0 / EltSize) &&
152     isUInt<8>(Offset1 / EltSize);
153 }
154
155 MachineBasicBlock::iterator
156 SILoadStoreOptimizer::findMatchingDSInst(MachineBasicBlock::iterator I,
157                                          unsigned EltSize){
158   MachineBasicBlock::iterator E = I->getParent()->end();
159   MachineBasicBlock::iterator MBBI = I;
160   ++MBBI;
161
162   if (MBBI->getOpcode() != I->getOpcode())
163     return E;
164
165   // Don't merge volatiles.
166   if (MBBI->hasOrderedMemoryRef())
167     return E;
168
169   int AddrIdx = AMDGPU::getNamedOperandIdx(I->getOpcode(), AMDGPU::OpName::addr);
170   const MachineOperand &AddrReg0 = I->getOperand(AddrIdx);
171   const MachineOperand &AddrReg1 = MBBI->getOperand(AddrIdx);
172
173   // Check same base pointer. Be careful of subregisters, which can occur with
174   // vectors of pointers.
175   if (AddrReg0.getReg() == AddrReg1.getReg() &&
176       AddrReg0.getSubReg() == AddrReg1.getSubReg()) {
177     int OffsetIdx = AMDGPU::getNamedOperandIdx(I->getOpcode(),
178                                                AMDGPU::OpName::offset);
179     unsigned Offset0 = I->getOperand(OffsetIdx).getImm();
180     unsigned Offset1 = MBBI->getOperand(OffsetIdx).getImm();
181
182     // Check both offsets fit in the reduced range.
183     if (offsetsCanBeCombined(Offset0, Offset1, EltSize))
184       return MBBI;
185   }
186
187   return E;
188 }
189
190 void SILoadStoreOptimizer::updateRegDefsUses(unsigned SrcReg,
191                                              unsigned DstReg,
192                                              unsigned SubIdx) {
193   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg),
194          E = MRI->reg_end(); I != E; ) {
195     MachineOperand &O = *I;
196     ++I;
197     O.substVirtReg(DstReg, SubIdx, *TRI);
198   }
199 }
200
201 MachineBasicBlock::iterator  SILoadStoreOptimizer::mergeRead2Pair(
202   MachineBasicBlock::iterator I,
203   MachineBasicBlock::iterator Paired,
204   unsigned EltSize,
205   const MCInstrDesc &Read2InstDesc) {
206   MachineBasicBlock *MBB = I->getParent();
207
208   // Be careful, since the addresses could be subregisters themselves in weird
209   // cases, like vectors of pointers.
210   const MachineOperand *AddrReg = TII->getNamedOperand(*I, AMDGPU::OpName::addr);
211
212   unsigned DestReg0 = TII->getNamedOperand(*I, AMDGPU::OpName::vdst)->getReg();
213   unsigned DestReg1
214     = TII->getNamedOperand(*Paired, AMDGPU::OpName::vdst)->getReg();
215
216   unsigned Offset0 = TII->getNamedOperand(*I, AMDGPU::OpName::offset)->getImm();
217   unsigned Offset1
218     = TII->getNamedOperand(*Paired, AMDGPU::OpName::offset)->getImm();
219
220   const TargetRegisterClass *SuperRC
221     = (EltSize == 4) ? &AMDGPU::VReg_64RegClass : &AMDGPU::VReg_128RegClass;
222   unsigned DestReg = MRI->createVirtualRegister(SuperRC);
223
224   DebugLoc DL = I->getDebugLoc();
225   MachineInstrBuilder Read2
226     = BuildMI(*MBB, I, DL, Read2InstDesc, DestReg)
227     .addImm(0) // gds
228     .addOperand(*AddrReg) // addr
229     .addImm(Offset0 / EltSize) // offset0
230     .addImm(Offset1 / EltSize) // offset1
231     .addMemOperand(*I->memoperands_begin())
232     .addMemOperand(*Paired->memoperands_begin());
233
234   LIS->InsertMachineInstrInMaps(Read2);
235
236   unsigned SubRegIdx0 = (EltSize == 4) ? AMDGPU::sub0 : AMDGPU::sub0_sub1;
237   unsigned SubRegIdx1 = (EltSize == 4) ? AMDGPU::sub1 : AMDGPU::sub2_sub3;
238   updateRegDefsUses(DestReg0, DestReg, SubRegIdx0);
239   updateRegDefsUses(DestReg1, DestReg, SubRegIdx1);
240
241   LIS->RemoveMachineInstrFromMaps(I);
242   LIS->RemoveMachineInstrFromMaps(Paired);
243   I->eraseFromParent();
244   Paired->eraseFromParent();
245
246   LiveInterval &AddrRegLI = LIS->getInterval(AddrReg->getReg());
247   LIS->shrinkToUses(&AddrRegLI);
248
249   LIS->getInterval(DestReg); // Create new LI
250
251   DEBUG(dbgs() << "Inserted read2: " << *Read2 << '\n');
252   return Read2;
253 }
254
255 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeWrite2Pair(
256   MachineBasicBlock::iterator I,
257   MachineBasicBlock::iterator Paired,
258   unsigned EltSize,
259   const MCInstrDesc &Write2InstDesc) {
260   MachineBasicBlock *MBB = I->getParent();
261
262   // Be sure to use .addOperand(), and not .addReg() with these. We want to be
263   // sure we preserve the subregister index and any register flags set on them.
264   const MachineOperand *Addr = TII->getNamedOperand(*I, AMDGPU::OpName::addr);
265   const MachineOperand *Data0 = TII->getNamedOperand(*I, AMDGPU::OpName::data0);
266   const MachineOperand *Data1
267     = TII->getNamedOperand(*Paired, AMDGPU::OpName::data0);
268
269   unsigned Offset0 = TII->getNamedOperand(*I, AMDGPU::OpName::offset)->getImm();
270   unsigned Offset1
271     = TII->getNamedOperand(*Paired, AMDGPU::OpName::offset)->getImm();
272
273   DebugLoc DL = I->getDebugLoc();
274   MachineInstrBuilder Write2
275     = BuildMI(*MBB, I, DL, Write2InstDesc)
276     .addImm(0) // gds
277     .addOperand(*Addr) // addr
278     .addOperand(*Data0) // data0
279     .addOperand(*Data1) // data1
280     .addImm(Offset0 / EltSize) // offset0
281     .addImm(Offset1 / EltSize) // offset1
282     .addMemOperand(*I->memoperands_begin())
283     .addMemOperand(*Paired->memoperands_begin());
284
285   // XXX - How do we express subregisters here?
286   unsigned OrigRegs[] = { Data0->getReg(), Data1->getReg(), Addr->getReg() };
287
288   LIS->RemoveMachineInstrFromMaps(I);
289   LIS->RemoveMachineInstrFromMaps(Paired);
290   I->eraseFromParent();
291   Paired->eraseFromParent();
292
293   LIS->repairIntervalsInRange(MBB, Write2, Write2, OrigRegs);
294
295   DEBUG(dbgs() << "Inserted write2 inst: " << *Write2 << '\n');
296   return Write2;
297 }
298
299 // Scan through looking for adjacent LDS operations with constant offsets from
300 // the same base register. We rely on the scheduler to do the hard work of
301 // clustering nearby loads, and assume these are all adjacent.
302 bool SILoadStoreOptimizer::optimizeBlock(MachineBasicBlock &MBB) {
303   const MCInstrDesc &Read2B32Desc = TII->get(AMDGPU::DS_READ2_B32);
304   const MCInstrDesc &Read2B64Desc = TII->get(AMDGPU::DS_READ2_B64);
305   const MCInstrDesc &Write2B32Desc = TII->get(AMDGPU::DS_WRITE2_B32);
306   const MCInstrDesc &Write2B64Desc = TII->get(AMDGPU::DS_WRITE2_B64);
307
308   bool Modified = false;
309
310   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
311     MachineInstr &MI = *I;
312
313     // Don't combine if volatile.
314     if (MI.hasOrderedMemoryRef()) {
315       ++I;
316       continue;
317     }
318
319     unsigned Opc = MI.getOpcode();
320     if (Opc == AMDGPU::DS_READ_B32 || Opc == AMDGPU::DS_READ_B64) {
321       unsigned Size = (Opc == AMDGPU::DS_READ_B64) ? 8 : 4;
322       MachineBasicBlock::iterator Match = findMatchingDSInst(I, Size);
323       if (Match != E) {
324         Modified = true;
325
326         const MCInstrDesc &Read2Desc
327           = (Opc == AMDGPU::DS_READ_B64) ? Read2B64Desc : Read2B32Desc;
328         I = mergeRead2Pair(I, Match, Size, Read2Desc);
329       } else {
330         ++I;
331       }
332
333       continue;
334     } else if (Opc == AMDGPU::DS_WRITE_B32 || Opc == AMDGPU::DS_WRITE_B64) {
335       unsigned Size = (Opc == AMDGPU::DS_WRITE_B64) ? 8 : 4;
336       MachineBasicBlock::iterator Match = findMatchingDSInst(I, Size);
337       if (Match != E) {
338         Modified = true;
339
340         const MCInstrDesc &Write2Desc
341           = (Opc == AMDGPU::DS_WRITE_B64) ? Write2B64Desc : Write2B32Desc;
342
343         I = mergeWrite2Pair(I, Match, Size, Write2Desc);
344       } else {
345         ++I;
346       }
347
348       continue;
349     }
350
351     ++I;
352   }
353
354   return Modified;
355 }
356
357 bool SILoadStoreOptimizer::runOnMachineFunction(MachineFunction &MF) {
358   const TargetSubtargetInfo *STM = MF.getTarget().getSubtargetImpl();
359   TRI = static_cast<const SIRegisterInfo*>(STM->getRegisterInfo());
360   TII = static_cast<const SIInstrInfo*>(STM->getInstrInfo());
361   MRI = &MF.getRegInfo();
362
363   LIS = &getAnalysis<LiveIntervals>();
364
365   DEBUG(dbgs() << "Running SILoadStoreOptimizer\n");
366
367   assert(!MRI->isSSA());
368
369   bool Modified = false;
370
371   for (MachineBasicBlock &MBB : MF)
372     Modified |= optimizeBlock(MBB);
373
374   return Modified;
375 }