1 //===- SILoadStoreOptimizer.cpp -------------------------------------------===//
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 pass tries to fuse DS instructions with close by immediate offsets.
10 // This will fuse operations such as
11 //  ds_read_b32 v0, v2 offset:16
12 //  ds_read_b32 v1, v2 offset:32
13 // ==>
14 //   ds_read2_b32 v[0:1], v2, offset0:4 offset1:8
15 //
16 // The same is done for certain SMEM and VMEM opcodes, e.g.:
17 //  s_buffer_load_dword s4, s[0:3], 4
18 //  s_buffer_load_dword s5, s[0:3], 8
19 // ==>
20 //  s_buffer_load_dwordx2 s[4:5], s[0:3], 4
21 //
22 // This pass also tries to promote constant offset to the immediate by
23 // adjusting the base. It tries to use a base from the nearby instructions that
24 // allows it to have a 13bit constant offset and then promotes the 13bit offset
25 // to the immediate.
26 // E.g.
27 //  s_movk_i32 s0, 0x1800
28 //  v_add_co_u32_e32 v0, vcc, s0, v2
29 //  v_addc_co_u32_e32 v1, vcc, 0, v6, vcc
30 //
31 //  s_movk_i32 s0, 0x1000
32 //  v_add_co_u32_e32 v5, vcc, s0, v2
33 //  v_addc_co_u32_e32 v6, vcc, 0, v6, vcc
34 //  global_load_dwordx2 v[5:6], v[5:6], off
35 //  global_load_dwordx2 v[0:1], v[0:1], off
36 // =>
37 //  s_movk_i32 s0, 0x1000
38 //  v_add_co_u32_e32 v5, vcc, s0, v2
39 //  v_addc_co_u32_e32 v6, vcc, 0, v6, vcc
40 //  global_load_dwordx2 v[5:6], v[5:6], off
41 //  global_load_dwordx2 v[0:1], v[5:6], off offset:2048
42 //
43 // Future improvements:
44 //
45 // - This is currently missing stores of constants because loading
46 //   the constant into the data register is placed between the stores, although
47 //   this is arguably a scheduling problem.
48 //
49 // - Live interval recomputing seems inefficient. This currently only matches
50 //   one pair, and recomputes live intervals and moves on to the next pair. It
51 //   would be better to compute a list of all merges that need to occur.
52 //
53 // - With a list of instructions to process, we can also merge more. If a
54 //   cluster of loads have offsets that are too large to fit in the 8-bit
55 //   offsets, but are close enough to fit in the 8 bits, we can add to the base
56 //   pointer and use the new reduced offsets.
57 //
58 //===----------------------------------------------------------------------===//
59 
60 #include "AMDGPU.h"
61 #include "GCNSubtarget.h"
62 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
63 #include "llvm/Analysis/AliasAnalysis.h"
64 #include "llvm/CodeGen/MachineFunctionPass.h"
65 #include "llvm/InitializePasses.h"
66 
67 using namespace llvm;
68 
69 #define DEBUG_TYPE "si-load-store-opt"
70 
71 namespace {
72 enum InstClassEnum {
73   UNKNOWN,
74   DS_READ,
75   DS_WRITE,
76   S_BUFFER_LOAD_IMM,
77   BUFFER_LOAD,
78   BUFFER_STORE,
79   MIMG,
80   TBUFFER_LOAD,
81   TBUFFER_STORE,
82 };
83 
84 struct AddressRegs {
85   unsigned char NumVAddrs = 0;
86   bool SBase = false;
87   bool SRsrc = false;
88   bool SOffset = false;
89   bool VAddr = false;
90   bool Addr = false;
91   bool SSamp = false;
92 };
93 
94 // GFX10 image_sample instructions can have 12 vaddrs + srsrc + ssamp.
95 const unsigned MaxAddressRegs = 12 + 1 + 1;
96 
97 class SILoadStoreOptimizer : public MachineFunctionPass {
98   struct CombineInfo {
99     MachineBasicBlock::iterator I;
100     unsigned EltSize;
101     unsigned Offset;
102     unsigned Width;
103     unsigned Format;
104     unsigned BaseOff;
105     unsigned DMask;
106     InstClassEnum InstClass;
107     unsigned CPol = 0;
108     bool IsAGPR;
109     bool UseST64;
110     int AddrIdx[MaxAddressRegs];
111     const MachineOperand *AddrReg[MaxAddressRegs];
112     unsigned NumAddresses;
113     unsigned Order;
114 
115     bool hasSameBaseAddress(const MachineInstr &MI) {
116       for (unsigned i = 0; i < NumAddresses; i++) {
117         const MachineOperand &AddrRegNext = MI.getOperand(AddrIdx[i]);
118 
119         if (AddrReg[i]->isImm() || AddrRegNext.isImm()) {
120           if (AddrReg[i]->isImm() != AddrRegNext.isImm() ||
121               AddrReg[i]->getImm() != AddrRegNext.getImm()) {
122             return false;
123           }
124           continue;
125         }
126 
127         // Check same base pointer. Be careful of subregisters, which can occur
128         // with vectors of pointers.
129         if (AddrReg[i]->getReg() != AddrRegNext.getReg() ||
130             AddrReg[i]->getSubReg() != AddrRegNext.getSubReg()) {
131          return false;
132         }
133       }
134       return true;
135     }
136 
137     bool hasMergeableAddress(const MachineRegisterInfo &MRI) {
138       for (unsigned i = 0; i < NumAddresses; ++i) {
139         const MachineOperand *AddrOp = AddrReg[i];
140         // Immediates are always OK.
141         if (AddrOp->isImm())
142           continue;
143 
144         // Don't try to merge addresses that aren't either immediates or registers.
145         // TODO: Should be possible to merge FrameIndexes and maybe some other
146         // non-register
147         if (!AddrOp->isReg())
148           return false;
149 
150         // TODO: We should be able to merge physical reg addresses.
151         if (AddrOp->getReg().isPhysical())
152           return false;
153 
154         // If an address has only one use then there will be on other
155         // instructions with the same address, so we can't merge this one.
156         if (MRI.hasOneNonDBGUse(AddrOp->getReg()))
157           return false;
158       }
159       return true;
160     }
161 
162     void setMI(MachineBasicBlock::iterator MI, const SILoadStoreOptimizer &LSO);
163   };
164 
165   struct BaseRegisters {
166     Register LoReg;
167     Register HiReg;
168 
169     unsigned LoSubReg = 0;
170     unsigned HiSubReg = 0;
171   };
172 
173   struct MemAddress {
174     BaseRegisters Base;
175     int64_t Offset = 0;
176   };
177 
178   using MemInfoMap = DenseMap<MachineInstr *, MemAddress>;
179 
180 private:
181   const GCNSubtarget *STM = nullptr;
182   const SIInstrInfo *TII = nullptr;
183   const SIRegisterInfo *TRI = nullptr;
184   MachineRegisterInfo *MRI = nullptr;
185   AliasAnalysis *AA = nullptr;
186   bool OptimizeAgain;
187 
188   static bool dmasksCanBeCombined(const CombineInfo &CI,
189                                   const SIInstrInfo &TII,
190                                   const CombineInfo &Paired);
191   static bool offsetsCanBeCombined(CombineInfo &CI, const GCNSubtarget &STI,
192                                    CombineInfo &Paired, bool Modify = false);
193   static bool widthsFit(const GCNSubtarget &STI, const CombineInfo &CI,
194                         const CombineInfo &Paired);
195   static unsigned getNewOpcode(const CombineInfo &CI, const CombineInfo &Paired);
196   static std::pair<unsigned, unsigned> getSubRegIdxs(const CombineInfo &CI,
197                                                      const CombineInfo &Paired);
198   const TargetRegisterClass *getTargetRegisterClass(const CombineInfo &CI,
199                                                     const CombineInfo &Paired);
200   const TargetRegisterClass *getDataRegClass(const MachineInstr &MI) const;
201 
202   bool checkAndPrepareMerge(CombineInfo &CI, CombineInfo &Paired,
203                             SmallVectorImpl<MachineInstr *> &InstsToMove);
204 
205   unsigned read2Opcode(unsigned EltSize) const;
206   unsigned read2ST64Opcode(unsigned EltSize) const;
207   MachineBasicBlock::iterator mergeRead2Pair(CombineInfo &CI,
208                                              CombineInfo &Paired,
209                   const SmallVectorImpl<MachineInstr *> &InstsToMove);
210 
211   unsigned write2Opcode(unsigned EltSize) const;
212   unsigned write2ST64Opcode(unsigned EltSize) const;
213   MachineBasicBlock::iterator
214   mergeWrite2Pair(CombineInfo &CI, CombineInfo &Paired,
215                   const SmallVectorImpl<MachineInstr *> &InstsToMove);
216   MachineBasicBlock::iterator
217   mergeImagePair(CombineInfo &CI, CombineInfo &Paired,
218                  const SmallVectorImpl<MachineInstr *> &InstsToMove);
219   MachineBasicBlock::iterator
220   mergeSBufferLoadImmPair(CombineInfo &CI, CombineInfo &Paired,
221                           const SmallVectorImpl<MachineInstr *> &InstsToMove);
222   MachineBasicBlock::iterator
223   mergeBufferLoadPair(CombineInfo &CI, CombineInfo &Paired,
224                       const SmallVectorImpl<MachineInstr *> &InstsToMove);
225   MachineBasicBlock::iterator
226   mergeBufferStorePair(CombineInfo &CI, CombineInfo &Paired,
227                        const SmallVectorImpl<MachineInstr *> &InstsToMove);
228   MachineBasicBlock::iterator
229   mergeTBufferLoadPair(CombineInfo &CI, CombineInfo &Paired,
230                        const SmallVectorImpl<MachineInstr *> &InstsToMove);
231   MachineBasicBlock::iterator
232   mergeTBufferStorePair(CombineInfo &CI, CombineInfo &Paired,
233                         const SmallVectorImpl<MachineInstr *> &InstsToMove);
234 
235   void updateBaseAndOffset(MachineInstr &I, Register NewBase,
236                            int32_t NewOffset) const;
237   Register computeBase(MachineInstr &MI, const MemAddress &Addr) const;
238   MachineOperand createRegOrImm(int32_t Val, MachineInstr &MI) const;
239   Optional<int32_t> extractConstOffset(const MachineOperand &Op) const;
240   void processBaseWithConstOffset(const MachineOperand &Base, MemAddress &Addr) const;
241   /// Promotes constant offset to the immediate by adjusting the base. It
242   /// tries to use a base from the nearby instructions that allows it to have
243   /// a 13bit constant offset which gets promoted to the immediate.
244   bool promoteConstantOffsetToImm(MachineInstr &CI,
245                                   MemInfoMap &Visited,
246                                   SmallPtrSet<MachineInstr *, 4> &Promoted) const;
247   void addInstToMergeableList(const CombineInfo &CI,
248                   std::list<std::list<CombineInfo> > &MergeableInsts) const;
249 
250   std::pair<MachineBasicBlock::iterator, bool> collectMergeableInsts(
251       MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End,
252       MemInfoMap &Visited, SmallPtrSet<MachineInstr *, 4> &AnchorList,
253       std::list<std::list<CombineInfo>> &MergeableInsts) const;
254 
255 public:
256   static char ID;
257 
258   SILoadStoreOptimizer() : MachineFunctionPass(ID) {
259     initializeSILoadStoreOptimizerPass(*PassRegistry::getPassRegistry());
260   }
261 
262   bool optimizeInstsWithSameBaseAddr(std::list<CombineInfo> &MergeList,
263                                      bool &OptimizeListAgain);
264   bool optimizeBlock(std::list<std::list<CombineInfo> > &MergeableInsts);
265 
266   bool runOnMachineFunction(MachineFunction &MF) override;
267 
268   StringRef getPassName() const override { return "SI Load Store Optimizer"; }
269 
270   void getAnalysisUsage(AnalysisUsage &AU) const override {
271     AU.setPreservesCFG();
272     AU.addRequired<AAResultsWrapperPass>();
273 
274     MachineFunctionPass::getAnalysisUsage(AU);
275   }
276 
277   MachineFunctionProperties getRequiredProperties() const override {
278     return MachineFunctionProperties()
279       .set(MachineFunctionProperties::Property::IsSSA);
280   }
281 };
282 
283 static unsigned getOpcodeWidth(const MachineInstr &MI, const SIInstrInfo &TII) {
284   const unsigned Opc = MI.getOpcode();
285 
286   if (TII.isMUBUF(Opc)) {
287     // FIXME: Handle d16 correctly
288     return AMDGPU::getMUBUFElements(Opc);
289   }
290   if (TII.isMIMG(MI)) {
291     uint64_t DMaskImm =
292         TII.getNamedOperand(MI, AMDGPU::OpName::dmask)->getImm();
293     return countPopulation(DMaskImm);
294   }
295   if (TII.isMTBUF(Opc)) {
296     return AMDGPU::getMTBUFElements(Opc);
297   }
298 
299   switch (Opc) {
300   case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
301     return 1;
302   case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
303     return 2;
304   case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
305     return 4;
306   case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM:
307     return 8;
308   case AMDGPU::DS_READ_B32:      LLVM_FALLTHROUGH;
309   case AMDGPU::DS_READ_B32_gfx9: LLVM_FALLTHROUGH;
310   case AMDGPU::DS_WRITE_B32:     LLVM_FALLTHROUGH;
311   case AMDGPU::DS_WRITE_B32_gfx9:
312     return 1;
313   case AMDGPU::DS_READ_B64:      LLVM_FALLTHROUGH;
314   case AMDGPU::DS_READ_B64_gfx9: LLVM_FALLTHROUGH;
315   case AMDGPU::DS_WRITE_B64:     LLVM_FALLTHROUGH;
316   case AMDGPU::DS_WRITE_B64_gfx9:
317     return 2;
318   default:
319     return 0;
320   }
321 }
322 
323 /// Maps instruction opcode to enum InstClassEnum.
324 static InstClassEnum getInstClass(unsigned Opc, const SIInstrInfo &TII) {
325   switch (Opc) {
326   default:
327     if (TII.isMUBUF(Opc)) {
328       switch (AMDGPU::getMUBUFBaseOpcode(Opc)) {
329       default:
330         return UNKNOWN;
331       case AMDGPU::BUFFER_LOAD_DWORD_OFFEN:
332       case AMDGPU::BUFFER_LOAD_DWORD_OFFEN_exact:
333       case AMDGPU::BUFFER_LOAD_DWORD_OFFSET:
334       case AMDGPU::BUFFER_LOAD_DWORD_OFFSET_exact:
335         return BUFFER_LOAD;
336       case AMDGPU::BUFFER_STORE_DWORD_OFFEN:
337       case AMDGPU::BUFFER_STORE_DWORD_OFFEN_exact:
338       case AMDGPU::BUFFER_STORE_DWORD_OFFSET:
339       case AMDGPU::BUFFER_STORE_DWORD_OFFSET_exact:
340         return BUFFER_STORE;
341       }
342     }
343     if (TII.isMIMG(Opc)) {
344       // Ignore instructions encoded without vaddr.
345       if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr) == -1 &&
346           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0) == -1)
347         return UNKNOWN;
348       // Ignore BVH instructions
349       if (AMDGPU::getMIMGBaseOpcode(Opc)->BVH)
350         return UNKNOWN;
351       // TODO: Support IMAGE_GET_RESINFO and IMAGE_GET_LOD.
352       if (TII.get(Opc).mayStore() || !TII.get(Opc).mayLoad() ||
353           TII.isGather4(Opc))
354         return UNKNOWN;
355       return MIMG;
356     }
357     if (TII.isMTBUF(Opc)) {
358       switch (AMDGPU::getMTBUFBaseOpcode(Opc)) {
359       default:
360         return UNKNOWN;
361       case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFEN:
362       case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFEN_exact:
363       case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFSET:
364       case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFSET_exact:
365         return TBUFFER_LOAD;
366       case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFEN:
367       case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFEN_exact:
368       case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFSET:
369       case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFSET_exact:
370         return TBUFFER_STORE;
371       }
372     }
373     return UNKNOWN;
374   case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
375   case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
376   case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
377   case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM:
378     return S_BUFFER_LOAD_IMM;
379   case AMDGPU::DS_READ_B32:
380   case AMDGPU::DS_READ_B32_gfx9:
381   case AMDGPU::DS_READ_B64:
382   case AMDGPU::DS_READ_B64_gfx9:
383     return DS_READ;
384   case AMDGPU::DS_WRITE_B32:
385   case AMDGPU::DS_WRITE_B32_gfx9:
386   case AMDGPU::DS_WRITE_B64:
387   case AMDGPU::DS_WRITE_B64_gfx9:
388     return DS_WRITE;
389   }
390 }
391 
392 /// Determines instruction subclass from opcode. Only instructions
393 /// of the same subclass can be merged together.
394 static unsigned getInstSubclass(unsigned Opc, const SIInstrInfo &TII) {
395   switch (Opc) {
396   default:
397     if (TII.isMUBUF(Opc))
398       return AMDGPU::getMUBUFBaseOpcode(Opc);
399     if (TII.isMIMG(Opc)) {
400       const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opc);
401       assert(Info);
402       return Info->BaseOpcode;
403     }
404     if (TII.isMTBUF(Opc))
405       return AMDGPU::getMTBUFBaseOpcode(Opc);
406     return -1;
407   case AMDGPU::DS_READ_B32:
408   case AMDGPU::DS_READ_B32_gfx9:
409   case AMDGPU::DS_READ_B64:
410   case AMDGPU::DS_READ_B64_gfx9:
411   case AMDGPU::DS_WRITE_B32:
412   case AMDGPU::DS_WRITE_B32_gfx9:
413   case AMDGPU::DS_WRITE_B64:
414   case AMDGPU::DS_WRITE_B64_gfx9:
415     return Opc;
416   case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
417   case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
418   case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
419   case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM:
420     return AMDGPU::S_BUFFER_LOAD_DWORD_IMM;
421   }
422 }
423 
424 static AddressRegs getRegs(unsigned Opc, const SIInstrInfo &TII) {
425   AddressRegs Result;
426 
427   if (TII.isMUBUF(Opc)) {
428     if (AMDGPU::getMUBUFHasVAddr(Opc))
429       Result.VAddr = true;
430     if (AMDGPU::getMUBUFHasSrsrc(Opc))
431       Result.SRsrc = true;
432     if (AMDGPU::getMUBUFHasSoffset(Opc))
433       Result.SOffset = true;
434 
435     return Result;
436   }
437 
438   if (TII.isMIMG(Opc)) {
439     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
440     if (VAddr0Idx >= 0) {
441       int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
442       Result.NumVAddrs = SRsrcIdx - VAddr0Idx;
443     } else {
444       Result.VAddr = true;
445     }
446     Result.SRsrc = true;
447     const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opc);
448     if (Info && AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode)->Sampler)
449       Result.SSamp = true;
450 
451     return Result;
452   }
453   if (TII.isMTBUF(Opc)) {
454     if (AMDGPU::getMTBUFHasVAddr(Opc))
455       Result.VAddr = true;
456     if (AMDGPU::getMTBUFHasSrsrc(Opc))
457       Result.SRsrc = true;
458     if (AMDGPU::getMTBUFHasSoffset(Opc))
459       Result.SOffset = true;
460 
461     return Result;
462   }
463 
464   switch (Opc) {
465   default:
466     return Result;
467   case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
468   case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
469   case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
470   case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM:
471     Result.SBase = true;
472     return Result;
473   case AMDGPU::DS_READ_B32:
474   case AMDGPU::DS_READ_B64:
475   case AMDGPU::DS_READ_B32_gfx9:
476   case AMDGPU::DS_READ_B64_gfx9:
477   case AMDGPU::DS_WRITE_B32:
478   case AMDGPU::DS_WRITE_B64:
479   case AMDGPU::DS_WRITE_B32_gfx9:
480   case AMDGPU::DS_WRITE_B64_gfx9:
481     Result.Addr = true;
482     return Result;
483   }
484 }
485 
486 void SILoadStoreOptimizer::CombineInfo::setMI(MachineBasicBlock::iterator MI,
487                                               const SILoadStoreOptimizer &LSO) {
488   I = MI;
489   unsigned Opc = MI->getOpcode();
490   InstClass = getInstClass(Opc, *LSO.TII);
491 
492   if (InstClass == UNKNOWN)
493     return;
494 
495   IsAGPR = LSO.TRI->hasAGPRs(LSO.getDataRegClass(*MI));
496 
497   switch (InstClass) {
498   case DS_READ:
499    EltSize =
500           (Opc == AMDGPU::DS_READ_B64 || Opc == AMDGPU::DS_READ_B64_gfx9) ? 8
501                                                                           : 4;
502    break;
503   case DS_WRITE:
504     EltSize =
505           (Opc == AMDGPU::DS_WRITE_B64 || Opc == AMDGPU::DS_WRITE_B64_gfx9) ? 8
506                                                                             : 4;
507     break;
508   case S_BUFFER_LOAD_IMM:
509     EltSize = AMDGPU::convertSMRDOffsetUnits(*LSO.STM, 4);
510     break;
511   default:
512     EltSize = 4;
513     break;
514   }
515 
516   if (InstClass == MIMG) {
517     DMask = LSO.TII->getNamedOperand(*I, AMDGPU::OpName::dmask)->getImm();
518     // Offset is not considered for MIMG instructions.
519     Offset = 0;
520   } else {
521     int OffsetIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::offset);
522     Offset = I->getOperand(OffsetIdx).getImm();
523   }
524 
525   if (InstClass == TBUFFER_LOAD || InstClass == TBUFFER_STORE)
526     Format = LSO.TII->getNamedOperand(*I, AMDGPU::OpName::format)->getImm();
527 
528   Width = getOpcodeWidth(*I, *LSO.TII);
529 
530   if ((InstClass == DS_READ) || (InstClass == DS_WRITE)) {
531     Offset &= 0xffff;
532   } else if (InstClass != MIMG) {
533     CPol = LSO.TII->getNamedOperand(*I, AMDGPU::OpName::cpol)->getImm();
534   }
535 
536   AddressRegs Regs = getRegs(Opc, *LSO.TII);
537 
538   NumAddresses = 0;
539   for (unsigned J = 0; J < Regs.NumVAddrs; J++)
540     AddrIdx[NumAddresses++] =
541         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0) + J;
542   if (Regs.Addr)
543     AddrIdx[NumAddresses++] =
544         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::addr);
545   if (Regs.SBase)
546     AddrIdx[NumAddresses++] =
547         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::sbase);
548   if (Regs.SRsrc)
549     AddrIdx[NumAddresses++] =
550         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
551   if (Regs.SOffset)
552     AddrIdx[NumAddresses++] =
553         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::soffset);
554   if (Regs.VAddr)
555     AddrIdx[NumAddresses++] =
556         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
557   if (Regs.SSamp)
558     AddrIdx[NumAddresses++] =
559         AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::ssamp);
560   assert(NumAddresses <= MaxAddressRegs);
561 
562   for (unsigned J = 0; J < NumAddresses; J++)
563     AddrReg[J] = &I->getOperand(AddrIdx[J]);
564 }
565 
566 } // end anonymous namespace.
567 
568 INITIALIZE_PASS_BEGIN(SILoadStoreOptimizer, DEBUG_TYPE,
569                       "SI Load Store Optimizer", false, false)
570 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
571 INITIALIZE_PASS_END(SILoadStoreOptimizer, DEBUG_TYPE, "SI Load Store Optimizer",
572                     false, false)
573 
574 char SILoadStoreOptimizer::ID = 0;
575 
576 char &llvm::SILoadStoreOptimizerID = SILoadStoreOptimizer::ID;
577 
578 FunctionPass *llvm::createSILoadStoreOptimizerPass() {
579   return new SILoadStoreOptimizer();
580 }
581 
582 static void moveInstsAfter(MachineBasicBlock::iterator I,
583                            ArrayRef<MachineInstr *> InstsToMove) {
584   MachineBasicBlock *MBB = I->getParent();
585   ++I;
586   for (MachineInstr *MI : InstsToMove) {
587     MI->removeFromParent();
588     MBB->insert(I, MI);
589   }
590 }
591 
592 static void addDefsUsesToList(const MachineInstr &MI,
593                               DenseSet<Register> &RegDefs,
594                               DenseSet<Register> &PhysRegUses) {
595   for (const MachineOperand &Op : MI.operands()) {
596     if (Op.isReg()) {
597       if (Op.isDef())
598         RegDefs.insert(Op.getReg());
599       else if (Op.readsReg() && Op.getReg().isPhysical())
600         PhysRegUses.insert(Op.getReg());
601     }
602   }
603 }
604 
605 static bool memAccessesCanBeReordered(MachineBasicBlock::iterator A,
606                                       MachineBasicBlock::iterator B,
607                                       AliasAnalysis *AA) {
608   // RAW or WAR - cannot reorder
609   // WAW - cannot reorder
610   // RAR - safe to reorder
611   return !(A->mayStore() || B->mayStore()) || !A->mayAlias(AA, *B, true);
612 }
613 
614 // Add MI and its defs to the lists if MI reads one of the defs that are
615 // already in the list. Returns true in that case.
616 static bool addToListsIfDependent(MachineInstr &MI, DenseSet<Register> &RegDefs,
617                                   DenseSet<Register> &PhysRegUses,
618                                   SmallVectorImpl<MachineInstr *> &Insts) {
619   for (MachineOperand &Use : MI.operands()) {
620     // If one of the defs is read, then there is a use of Def between I and the
621     // instruction that I will potentially be merged with. We will need to move
622     // this instruction after the merged instructions.
623     //
624     // Similarly, if there is a def which is read by an instruction that is to
625     // be moved for merging, then we need to move the def-instruction as well.
626     // This can only happen for physical registers such as M0; virtual
627     // registers are in SSA form.
628     if (Use.isReg() && ((Use.readsReg() && RegDefs.count(Use.getReg())) ||
629                         (Use.isDef() && RegDefs.count(Use.getReg())) ||
630                         (Use.isDef() && Use.getReg().isPhysical() &&
631                          PhysRegUses.count(Use.getReg())))) {
632       Insts.push_back(&MI);
633       addDefsUsesToList(MI, RegDefs, PhysRegUses);
634       return true;
635     }
636   }
637 
638   return false;
639 }
640 
641 static bool canMoveInstsAcrossMemOp(MachineInstr &MemOp,
642                                     ArrayRef<MachineInstr *> InstsToMove,
643                                     AliasAnalysis *AA) {
644   assert(MemOp.mayLoadOrStore());
645 
646   for (MachineInstr *InstToMove : InstsToMove) {
647     if (!InstToMove->mayLoadOrStore())
648       continue;
649     if (!memAccessesCanBeReordered(MemOp, *InstToMove, AA))
650       return false;
651   }
652   return true;
653 }
654 
655 // This function assumes that \p A and \p B have are identical except for
656 // size and offset, and they reference adjacent memory.
657 static MachineMemOperand *combineKnownAdjacentMMOs(MachineFunction &MF,
658                                                    const MachineMemOperand *A,
659                                                    const MachineMemOperand *B) {
660   unsigned MinOffset = std::min(A->getOffset(), B->getOffset());
661   unsigned Size = A->getSize() + B->getSize();
662   // This function adds the offset parameter to the existing offset for A,
663   // so we pass 0 here as the offset and then manually set it to the correct
664   // value after the call.
665   MachineMemOperand *MMO = MF.getMachineMemOperand(A, 0, Size);
666   MMO->setOffset(MinOffset);
667   return MMO;
668 }
669 
670 bool SILoadStoreOptimizer::dmasksCanBeCombined(const CombineInfo &CI,
671                                                const SIInstrInfo &TII,
672                                                const CombineInfo &Paired) {
673   assert(CI.InstClass == MIMG);
674 
675   // Ignore instructions with tfe/lwe set.
676   const auto *TFEOp = TII.getNamedOperand(*CI.I, AMDGPU::OpName::tfe);
677   const auto *LWEOp = TII.getNamedOperand(*CI.I, AMDGPU::OpName::lwe);
678 
679   if ((TFEOp && TFEOp->getImm()) || (LWEOp && LWEOp->getImm()))
680     return false;
681 
682   // Check other optional immediate operands for equality.
683   unsigned OperandsToMatch[] = {AMDGPU::OpName::cpol, AMDGPU::OpName::d16,
684                                 AMDGPU::OpName::unorm, AMDGPU::OpName::da,
685                                 AMDGPU::OpName::r128, AMDGPU::OpName::a16};
686 
687   for (auto op : OperandsToMatch) {
688     int Idx = AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), op);
689     if (AMDGPU::getNamedOperandIdx(Paired.I->getOpcode(), op) != Idx)
690       return false;
691     if (Idx != -1 &&
692         CI.I->getOperand(Idx).getImm() != Paired.I->getOperand(Idx).getImm())
693       return false;
694   }
695 
696   // Check DMask for overlaps.
697   unsigned MaxMask = std::max(CI.DMask, Paired.DMask);
698   unsigned MinMask = std::min(CI.DMask, Paired.DMask);
699 
700   unsigned AllowedBitsForMin = llvm::countTrailingZeros(MaxMask);
701   if ((1u << AllowedBitsForMin) <= MinMask)
702     return false;
703 
704   return true;
705 }
706 
707 static unsigned getBufferFormatWithCompCount(unsigned OldFormat,
708                                        unsigned ComponentCount,
709                                        const GCNSubtarget &STI) {
710   if (ComponentCount > 4)
711     return 0;
712 
713   const llvm::AMDGPU::GcnBufferFormatInfo *OldFormatInfo =
714       llvm::AMDGPU::getGcnBufferFormatInfo(OldFormat, STI);
715   if (!OldFormatInfo)
716     return 0;
717 
718   const llvm::AMDGPU::GcnBufferFormatInfo *NewFormatInfo =
719       llvm::AMDGPU::getGcnBufferFormatInfo(OldFormatInfo->BitsPerComp,
720                                            ComponentCount,
721                                            OldFormatInfo->NumFormat, STI);
722 
723   if (!NewFormatInfo)
724     return 0;
725 
726   assert(NewFormatInfo->NumFormat == OldFormatInfo->NumFormat &&
727          NewFormatInfo->BitsPerComp == OldFormatInfo->BitsPerComp);
728 
729   return NewFormatInfo->Format;
730 }
731 
732 // Return the value in the inclusive range [Lo,Hi] that is aligned to the
733 // highest power of two. Note that the result is well defined for all inputs
734 // including corner cases like:
735 // - if Lo == Hi, return that value
736 // - if Lo == 0, return 0 (even though the "- 1" below underflows
737 // - if Lo > Hi, return 0 (as if the range wrapped around)
738 static uint32_t mostAlignedValueInRange(uint32_t Lo, uint32_t Hi) {
739   return Hi & maskLeadingOnes<uint32_t>(countLeadingZeros((Lo - 1) ^ Hi) + 1);
740 }
741 
742 bool SILoadStoreOptimizer::offsetsCanBeCombined(CombineInfo &CI,
743                                                 const GCNSubtarget &STI,
744                                                 CombineInfo &Paired,
745                                                 bool Modify) {
746   assert(CI.InstClass != MIMG);
747 
748   // XXX - Would the same offset be OK? Is there any reason this would happen or
749   // be useful?
750   if (CI.Offset == Paired.Offset)
751     return false;
752 
753   // This won't be valid if the offset isn't aligned.
754   if ((CI.Offset % CI.EltSize != 0) || (Paired.Offset % CI.EltSize != 0))
755     return false;
756 
757   if (CI.InstClass == TBUFFER_LOAD || CI.InstClass == TBUFFER_STORE) {
758 
759     const llvm::AMDGPU::GcnBufferFormatInfo *Info0 =
760         llvm::AMDGPU::getGcnBufferFormatInfo(CI.Format, STI);
761     if (!Info0)
762       return false;
763     const llvm::AMDGPU::GcnBufferFormatInfo *Info1 =
764         llvm::AMDGPU::getGcnBufferFormatInfo(Paired.Format, STI);
765     if (!Info1)
766       return false;
767 
768     if (Info0->BitsPerComp != Info1->BitsPerComp ||
769         Info0->NumFormat != Info1->NumFormat)
770       return false;
771 
772     // TODO: Should be possible to support more formats, but if format loads
773     // are not dword-aligned, the merged load might not be valid.
774     if (Info0->BitsPerComp != 32)
775       return false;
776 
777     if (getBufferFormatWithCompCount(CI.Format, CI.Width + Paired.Width, STI) == 0)
778       return false;
779   }
780 
781   uint32_t EltOffset0 = CI.Offset / CI.EltSize;
782   uint32_t EltOffset1 = Paired.Offset / CI.EltSize;
783   CI.UseST64 = false;
784   CI.BaseOff = 0;
785 
786   // Handle all non-DS instructions.
787   if ((CI.InstClass != DS_READ) && (CI.InstClass != DS_WRITE)) {
788     return (EltOffset0 + CI.Width == EltOffset1 ||
789             EltOffset1 + Paired.Width == EltOffset0) &&
790            CI.CPol == Paired.CPol &&
791            (CI.InstClass == S_BUFFER_LOAD_IMM || CI.CPol == Paired.CPol);
792   }
793 
794   // If the offset in elements doesn't fit in 8-bits, we might be able to use
795   // the stride 64 versions.
796   if ((EltOffset0 % 64 == 0) && (EltOffset1 % 64) == 0 &&
797       isUInt<8>(EltOffset0 / 64) && isUInt<8>(EltOffset1 / 64)) {
798     if (Modify) {
799       CI.Offset = EltOffset0 / 64;
800       Paired.Offset = EltOffset1 / 64;
801       CI.UseST64 = true;
802     }
803     return true;
804   }
805 
806   // Check if the new offsets fit in the reduced 8-bit range.
807   if (isUInt<8>(EltOffset0) && isUInt<8>(EltOffset1)) {
808     if (Modify) {
809       CI.Offset = EltOffset0;
810       Paired.Offset = EltOffset1;
811     }
812     return true;
813   }
814 
815   // Try to shift base address to decrease offsets.
816   uint32_t Min = std::min(EltOffset0, EltOffset1);
817   uint32_t Max = std::max(EltOffset0, EltOffset1);
818 
819   const uint32_t Mask = maskTrailingOnes<uint32_t>(8) * 64;
820   if (((Max - Min) & ~Mask) == 0) {
821     if (Modify) {
822       // From the range of values we could use for BaseOff, choose the one that
823       // is aligned to the highest power of two, to maximise the chance that
824       // the same offset can be reused for other load/store pairs.
825       uint32_t BaseOff = mostAlignedValueInRange(Max - 0xff * 64, Min);
826       // Copy the low bits of the offsets, so that when we adjust them by
827       // subtracting BaseOff they will be multiples of 64.
828       BaseOff |= Min & maskTrailingOnes<uint32_t>(6);
829       CI.BaseOff = BaseOff * CI.EltSize;
830       CI.Offset = (EltOffset0 - BaseOff) / 64;
831       Paired.Offset = (EltOffset1 - BaseOff) / 64;
832       CI.UseST64 = true;
833     }
834     return true;
835   }
836 
837   if (isUInt<8>(Max - Min)) {
838     if (Modify) {
839       // From the range of values we could use for BaseOff, choose the one that
840       // is aligned to the highest power of two, to maximise the chance that
841       // the same offset can be reused for other load/store pairs.
842       uint32_t BaseOff = mostAlignedValueInRange(Max - 0xff, Min);
843       CI.BaseOff = BaseOff * CI.EltSize;
844       CI.Offset = EltOffset0 - BaseOff;
845       Paired.Offset = EltOffset1 - BaseOff;
846     }
847     return true;
848   }
849 
850   return false;
851 }
852 
853 bool SILoadStoreOptimizer::widthsFit(const GCNSubtarget &STM,
854                                      const CombineInfo &CI,
855                                      const CombineInfo &Paired) {
856   const unsigned Width = (CI.Width + Paired.Width);
857   switch (CI.InstClass) {
858   default:
859     return (Width <= 4) && (STM.hasDwordx3LoadStores() || (Width != 3));
860   case S_BUFFER_LOAD_IMM:
861     switch (Width) {
862     default:
863       return false;
864     case 2:
865     case 4:
866     case 8:
867       return true;
868     }
869   }
870 }
871 
872 const TargetRegisterClass *
873 SILoadStoreOptimizer::getDataRegClass(const MachineInstr &MI) const {
874   if (const auto *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst)) {
875     return TRI->getRegClassForReg(*MRI, Dst->getReg());
876   }
877   if (const auto *Src = TII->getNamedOperand(MI, AMDGPU::OpName::vdata)) {
878     return TRI->getRegClassForReg(*MRI, Src->getReg());
879   }
880   if (const auto *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) {
881     return TRI->getRegClassForReg(*MRI, Src->getReg());
882   }
883   if (const auto *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::sdst)) {
884     return TRI->getRegClassForReg(*MRI, Dst->getReg());
885   }
886   if (const auto *Src = TII->getNamedOperand(MI, AMDGPU::OpName::sdata)) {
887     return TRI->getRegClassForReg(*MRI, Src->getReg());
888   }
889   return nullptr;
890 }
891 
892 /// This function assumes that CI comes before Paired in a basic block.
893 bool SILoadStoreOptimizer::checkAndPrepareMerge(
894     CombineInfo &CI, CombineInfo &Paired,
895     SmallVectorImpl<MachineInstr *> &InstsToMove) {
896 
897   // Check both offsets (or masks for MIMG) can be combined and fit in the
898   // reduced range.
899   if (CI.InstClass == MIMG && !dmasksCanBeCombined(CI, *TII, Paired))
900     return false;
901 
902   if (CI.InstClass != MIMG &&
903       (!widthsFit(*STM, CI, Paired) || !offsetsCanBeCombined(CI, *STM, Paired)))
904     return false;
905 
906   const unsigned Opc = CI.I->getOpcode();
907   const InstClassEnum InstClass = getInstClass(Opc, *TII);
908 
909   if (InstClass == UNKNOWN) {
910     return false;
911   }
912   const unsigned InstSubclass = getInstSubclass(Opc, *TII);
913 
914   DenseSet<Register> RegDefsToMove;
915   DenseSet<Register> PhysRegUsesToMove;
916   addDefsUsesToList(*CI.I, RegDefsToMove, PhysRegUsesToMove);
917 
918   MachineBasicBlock::iterator E = std::next(Paired.I);
919   MachineBasicBlock::iterator MBBI = std::next(CI.I);
920   MachineBasicBlock::iterator MBBE = CI.I->getParent()->end();
921   for (; MBBI != E; ++MBBI) {
922 
923     if (MBBI == MBBE) {
924       // CombineInfo::Order is a hint on the instruction ordering within the
925       // basic block. This hint suggests that CI precedes Paired, which is
926       // true most of the time. However, moveInstsAfter() processing a
927       // previous list may have changed this order in a situation when it
928       // moves an instruction which exists in some other merge list.
929       // In this case it must be dependent.
930       return false;
931     }
932 
933     if ((getInstClass(MBBI->getOpcode(), *TII) != InstClass) ||
934         (getInstSubclass(MBBI->getOpcode(), *TII) != InstSubclass)) {
935       // This is not a matching instruction, but we can keep looking as
936       // long as one of these conditions are met:
937       // 1. It is safe to move I down past MBBI.
938       // 2. It is safe to move MBBI down past the instruction that I will
939       //    be merged into.
940 
941       if (MBBI->hasUnmodeledSideEffects()) {
942         // We can't re-order this instruction with respect to other memory
943         // operations, so we fail both conditions mentioned above.
944         return false;
945       }
946 
947       if (MBBI->mayLoadOrStore() &&
948           (!memAccessesCanBeReordered(*CI.I, *MBBI, AA) ||
949            !canMoveInstsAcrossMemOp(*MBBI, InstsToMove, AA))) {
950         // We fail condition #1, but we may still be able to satisfy condition
951         // #2.  Add this instruction to the move list and then we will check
952         // if condition #2 holds once we have selected the matching instruction.
953         InstsToMove.push_back(&*MBBI);
954         addDefsUsesToList(*MBBI, RegDefsToMove, PhysRegUsesToMove);
955         continue;
956       }
957 
958       // When we match I with another DS instruction we will be moving I down
959       // to the location of the matched instruction any uses of I will need to
960       // be moved down as well.
961       addToListsIfDependent(*MBBI, RegDefsToMove, PhysRegUsesToMove,
962                             InstsToMove);
963       continue;
964     }
965 
966     // Handle a case like
967     //   DS_WRITE_B32 addr, v, idx0
968     //   w = DS_READ_B32 addr, idx0
969     //   DS_WRITE_B32 addr, f(w), idx1
970     // where the DS_READ_B32 ends up in InstsToMove and therefore prevents
971     // merging of the two writes.
972     if (addToListsIfDependent(*MBBI, RegDefsToMove, PhysRegUsesToMove,
973                               InstsToMove))
974       continue;
975 
976     if (&*MBBI == &*Paired.I) {
977       // FIXME: nothing is illegal in a ds_write2 opcode with two AGPR data
978       //        operands. However we are reporting that ds_write2 shall have
979       //        only VGPR data so that machine copy propagation does not
980       //        create an illegal instruction with a VGPR and AGPR sources.
981       //        Consequenctially if we create such instruction the verifier
982       //        will complain.
983       if (CI.IsAGPR && CI.InstClass == DS_WRITE)
984         return false;
985 
986       // We need to go through the list of instructions that we plan to
987       // move and make sure they are all safe to move down past the merged
988       // instruction.
989       if (canMoveInstsAcrossMemOp(*MBBI, InstsToMove, AA)) {
990 
991         // Call offsetsCanBeCombined with modify = true so that the offsets are
992         // correct for the new instruction.  This should return true, because
993         // this function should only be called on CombineInfo objects that
994         // have already been confirmed to be mergeable.
995         if (CI.InstClass != MIMG)
996           offsetsCanBeCombined(CI, *STM, Paired, true);
997         return true;
998       }
999       return false;
1000     }
1001 
1002     // We've found a load/store that we couldn't merge for some reason.
1003     // We could potentially keep looking, but we'd need to make sure that
1004     // it was safe to move I and also all the instruction in InstsToMove
1005     // down past this instruction.
1006     // check if we can move I across MBBI and if we can move all I's users
1007     if (!memAccessesCanBeReordered(*CI.I, *MBBI, AA) ||
1008         !canMoveInstsAcrossMemOp(*MBBI, InstsToMove, AA))
1009       break;
1010   }
1011   return false;
1012 }
1013 
1014 unsigned SILoadStoreOptimizer::read2Opcode(unsigned EltSize) const {
1015   if (STM->ldsRequiresM0Init())
1016     return (EltSize == 4) ? AMDGPU::DS_READ2_B32 : AMDGPU::DS_READ2_B64;
1017   return (EltSize == 4) ? AMDGPU::DS_READ2_B32_gfx9 : AMDGPU::DS_READ2_B64_gfx9;
1018 }
1019 
1020 unsigned SILoadStoreOptimizer::read2ST64Opcode(unsigned EltSize) const {
1021   if (STM->ldsRequiresM0Init())
1022     return (EltSize == 4) ? AMDGPU::DS_READ2ST64_B32 : AMDGPU::DS_READ2ST64_B64;
1023 
1024   return (EltSize == 4) ? AMDGPU::DS_READ2ST64_B32_gfx9
1025                         : AMDGPU::DS_READ2ST64_B64_gfx9;
1026 }
1027 
1028 MachineBasicBlock::iterator
1029 SILoadStoreOptimizer::mergeRead2Pair(CombineInfo &CI, CombineInfo &Paired,
1030     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1031   MachineBasicBlock *MBB = CI.I->getParent();
1032 
1033   // Be careful, since the addresses could be subregisters themselves in weird
1034   // cases, like vectors of pointers.
1035   const auto *AddrReg = TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr);
1036 
1037   const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdst);
1038   const auto *Dest1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdst);
1039 
1040   unsigned NewOffset0 = CI.Offset;
1041   unsigned NewOffset1 = Paired.Offset;
1042   unsigned Opc =
1043       CI.UseST64 ? read2ST64Opcode(CI.EltSize) : read2Opcode(CI.EltSize);
1044 
1045   unsigned SubRegIdx0 = (CI.EltSize == 4) ? AMDGPU::sub0 : AMDGPU::sub0_sub1;
1046   unsigned SubRegIdx1 = (CI.EltSize == 4) ? AMDGPU::sub1 : AMDGPU::sub2_sub3;
1047 
1048   if (NewOffset0 > NewOffset1) {
1049     // Canonicalize the merged instruction so the smaller offset comes first.
1050     std::swap(NewOffset0, NewOffset1);
1051     std::swap(SubRegIdx0, SubRegIdx1);
1052   }
1053 
1054   assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
1055          (NewOffset0 != NewOffset1) && "Computed offset doesn't fit");
1056 
1057   const MCInstrDesc &Read2Desc = TII->get(Opc);
1058 
1059   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1060   Register DestReg = MRI->createVirtualRegister(SuperRC);
1061 
1062   DebugLoc DL = CI.I->getDebugLoc();
1063 
1064   Register BaseReg = AddrReg->getReg();
1065   unsigned BaseSubReg = AddrReg->getSubReg();
1066   unsigned BaseRegFlags = 0;
1067   if (CI.BaseOff) {
1068     Register ImmReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1069     BuildMI(*MBB, Paired.I, DL, TII->get(AMDGPU::S_MOV_B32), ImmReg)
1070         .addImm(CI.BaseOff);
1071 
1072     BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1073     BaseRegFlags = RegState::Kill;
1074 
1075     TII->getAddNoCarry(*MBB, Paired.I, DL, BaseReg)
1076         .addReg(ImmReg)
1077         .addReg(AddrReg->getReg(), 0, BaseSubReg)
1078         .addImm(0); // clamp bit
1079     BaseSubReg = 0;
1080   }
1081 
1082   MachineInstrBuilder Read2 =
1083       BuildMI(*MBB, Paired.I, DL, Read2Desc, DestReg)
1084           .addReg(BaseReg, BaseRegFlags, BaseSubReg) // addr
1085           .addImm(NewOffset0)                        // offset0
1086           .addImm(NewOffset1)                        // offset1
1087           .addImm(0)                                 // gds
1088           .cloneMergedMemRefs({&*CI.I, &*Paired.I});
1089 
1090   (void)Read2;
1091 
1092   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1093 
1094   // Copy to the old destination registers.
1095   BuildMI(*MBB, Paired.I, DL, CopyDesc)
1096       .add(*Dest0) // Copy to same destination including flags and sub reg.
1097       .addReg(DestReg, 0, SubRegIdx0);
1098   MachineInstr *Copy1 = BuildMI(*MBB, Paired.I, DL, CopyDesc)
1099                             .add(*Dest1)
1100                             .addReg(DestReg, RegState::Kill, SubRegIdx1);
1101 
1102   moveInstsAfter(Copy1, InstsToMove);
1103 
1104   CI.I->eraseFromParent();
1105   Paired.I->eraseFromParent();
1106 
1107   LLVM_DEBUG(dbgs() << "Inserted read2: " << *Read2 << '\n');
1108   return Read2;
1109 }
1110 
1111 unsigned SILoadStoreOptimizer::write2Opcode(unsigned EltSize) const {
1112   if (STM->ldsRequiresM0Init())
1113     return (EltSize == 4) ? AMDGPU::DS_WRITE2_B32 : AMDGPU::DS_WRITE2_B64;
1114   return (EltSize == 4) ? AMDGPU::DS_WRITE2_B32_gfx9
1115                         : AMDGPU::DS_WRITE2_B64_gfx9;
1116 }
1117 
1118 unsigned SILoadStoreOptimizer::write2ST64Opcode(unsigned EltSize) const {
1119   if (STM->ldsRequiresM0Init())
1120     return (EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32
1121                           : AMDGPU::DS_WRITE2ST64_B64;
1122 
1123   return (EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32_gfx9
1124                         : AMDGPU::DS_WRITE2ST64_B64_gfx9;
1125 }
1126 
1127 MachineBasicBlock::iterator
1128 SILoadStoreOptimizer::mergeWrite2Pair(CombineInfo &CI, CombineInfo &Paired,
1129                                       const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1130   MachineBasicBlock *MBB = CI.I->getParent();
1131 
1132   // Be sure to use .addOperand(), and not .addReg() with these. We want to be
1133   // sure we preserve the subregister index and any register flags set on them.
1134   const MachineOperand *AddrReg =
1135       TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr);
1136   const MachineOperand *Data0 =
1137       TII->getNamedOperand(*CI.I, AMDGPU::OpName::data0);
1138   const MachineOperand *Data1 =
1139       TII->getNamedOperand(*Paired.I, AMDGPU::OpName::data0);
1140 
1141   unsigned NewOffset0 = CI.Offset;
1142   unsigned NewOffset1 = Paired.Offset;
1143   unsigned Opc =
1144       CI.UseST64 ? write2ST64Opcode(CI.EltSize) : write2Opcode(CI.EltSize);
1145 
1146   if (NewOffset0 > NewOffset1) {
1147     // Canonicalize the merged instruction so the smaller offset comes first.
1148     std::swap(NewOffset0, NewOffset1);
1149     std::swap(Data0, Data1);
1150   }
1151 
1152   assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
1153          (NewOffset0 != NewOffset1) && "Computed offset doesn't fit");
1154 
1155   const MCInstrDesc &Write2Desc = TII->get(Opc);
1156   DebugLoc DL = CI.I->getDebugLoc();
1157 
1158   Register BaseReg = AddrReg->getReg();
1159   unsigned BaseSubReg = AddrReg->getSubReg();
1160   unsigned BaseRegFlags = 0;
1161   if (CI.BaseOff) {
1162     Register ImmReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1163     BuildMI(*MBB, Paired.I, DL, TII->get(AMDGPU::S_MOV_B32), ImmReg)
1164         .addImm(CI.BaseOff);
1165 
1166     BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1167     BaseRegFlags = RegState::Kill;
1168 
1169     TII->getAddNoCarry(*MBB, Paired.I, DL, BaseReg)
1170         .addReg(ImmReg)
1171         .addReg(AddrReg->getReg(), 0, BaseSubReg)
1172         .addImm(0); // clamp bit
1173     BaseSubReg = 0;
1174   }
1175 
1176   MachineInstrBuilder Write2 =
1177       BuildMI(*MBB, Paired.I, DL, Write2Desc)
1178           .addReg(BaseReg, BaseRegFlags, BaseSubReg) // addr
1179           .add(*Data0)                               // data0
1180           .add(*Data1)                               // data1
1181           .addImm(NewOffset0)                        // offset0
1182           .addImm(NewOffset1)                        // offset1
1183           .addImm(0)                                 // gds
1184           .cloneMergedMemRefs({&*CI.I, &*Paired.I});
1185 
1186   moveInstsAfter(Write2, InstsToMove);
1187 
1188   CI.I->eraseFromParent();
1189   Paired.I->eraseFromParent();
1190 
1191   LLVM_DEBUG(dbgs() << "Inserted write2 inst: " << *Write2 << '\n');
1192   return Write2;
1193 }
1194 
1195 MachineBasicBlock::iterator
1196 SILoadStoreOptimizer::mergeImagePair(CombineInfo &CI, CombineInfo &Paired,
1197                            const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1198   MachineBasicBlock *MBB = CI.I->getParent();
1199   DebugLoc DL = CI.I->getDebugLoc();
1200   const unsigned Opcode = getNewOpcode(CI, Paired);
1201 
1202   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1203 
1204   Register DestReg = MRI->createVirtualRegister(SuperRC);
1205   unsigned MergedDMask = CI.DMask | Paired.DMask;
1206   unsigned DMaskIdx =
1207       AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), AMDGPU::OpName::dmask);
1208 
1209   auto MIB = BuildMI(*MBB, Paired.I, DL, TII->get(Opcode), DestReg);
1210   for (unsigned I = 1, E = (*CI.I).getNumOperands(); I != E; ++I) {
1211     if (I == DMaskIdx)
1212       MIB.addImm(MergedDMask);
1213     else
1214       MIB.add((*CI.I).getOperand(I));
1215   }
1216 
1217   // It shouldn't be possible to get this far if the two instructions
1218   // don't have a single memoperand, because MachineInstr::mayAlias()
1219   // will return true if this is the case.
1220   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1221 
1222   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1223   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1224 
1225   MachineInstr *New = MIB.addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1226 
1227   unsigned SubRegIdx0, SubRegIdx1;
1228   std::tie(SubRegIdx0, SubRegIdx1) = getSubRegIdxs(CI, Paired);
1229 
1230   // Copy to the old destination registers.
1231   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1232   const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
1233   const auto *Dest1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdata);
1234 
1235   BuildMI(*MBB, Paired.I, DL, CopyDesc)
1236       .add(*Dest0) // Copy to same destination including flags and sub reg.
1237       .addReg(DestReg, 0, SubRegIdx0);
1238   MachineInstr *Copy1 = BuildMI(*MBB, Paired.I, DL, CopyDesc)
1239                             .add(*Dest1)
1240                             .addReg(DestReg, RegState::Kill, SubRegIdx1);
1241 
1242   moveInstsAfter(Copy1, InstsToMove);
1243 
1244   CI.I->eraseFromParent();
1245   Paired.I->eraseFromParent();
1246   return New;
1247 }
1248 
1249 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeSBufferLoadImmPair(
1250     CombineInfo &CI, CombineInfo &Paired,
1251     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1252   MachineBasicBlock *MBB = CI.I->getParent();
1253   DebugLoc DL = CI.I->getDebugLoc();
1254   const unsigned Opcode = getNewOpcode(CI, Paired);
1255 
1256   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1257 
1258   Register DestReg = MRI->createVirtualRegister(SuperRC);
1259   unsigned MergedOffset = std::min(CI.Offset, Paired.Offset);
1260 
1261   // It shouldn't be possible to get this far if the two instructions
1262   // don't have a single memoperand, because MachineInstr::mayAlias()
1263   // will return true if this is the case.
1264   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1265 
1266   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1267   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1268 
1269   MachineInstr *New =
1270     BuildMI(*MBB, Paired.I, DL, TII->get(Opcode), DestReg)
1271         .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::sbase))
1272         .addImm(MergedOffset) // offset
1273         .addImm(CI.CPol)      // cpol
1274         .addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1275 
1276   std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI, Paired);
1277   const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
1278   const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
1279 
1280   // Copy to the old destination registers.
1281   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1282   const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::sdst);
1283   const auto *Dest1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::sdst);
1284 
1285   BuildMI(*MBB, Paired.I, DL, CopyDesc)
1286       .add(*Dest0) // Copy to same destination including flags and sub reg.
1287       .addReg(DestReg, 0, SubRegIdx0);
1288   MachineInstr *Copy1 = BuildMI(*MBB, Paired.I, DL, CopyDesc)
1289                             .add(*Dest1)
1290                             .addReg(DestReg, RegState::Kill, SubRegIdx1);
1291 
1292   moveInstsAfter(Copy1, InstsToMove);
1293 
1294   CI.I->eraseFromParent();
1295   Paired.I->eraseFromParent();
1296   return New;
1297 }
1298 
1299 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeBufferLoadPair(
1300     CombineInfo &CI, CombineInfo &Paired,
1301     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1302   MachineBasicBlock *MBB = CI.I->getParent();
1303   DebugLoc DL = CI.I->getDebugLoc();
1304 
1305   const unsigned Opcode = getNewOpcode(CI, Paired);
1306 
1307   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1308 
1309   // Copy to the new source register.
1310   Register DestReg = MRI->createVirtualRegister(SuperRC);
1311   unsigned MergedOffset = std::min(CI.Offset, Paired.Offset);
1312 
1313   auto MIB = BuildMI(*MBB, Paired.I, DL, TII->get(Opcode), DestReg);
1314 
1315   AddressRegs Regs = getRegs(Opcode, *TII);
1316 
1317   if (Regs.VAddr)
1318     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1319 
1320   // It shouldn't be possible to get this far if the two instructions
1321   // don't have a single memoperand, because MachineInstr::mayAlias()
1322   // will return true if this is the case.
1323   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1324 
1325   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1326   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1327 
1328   MachineInstr *New =
1329     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1330         .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1331         .addImm(MergedOffset) // offset
1332         .addImm(CI.CPol)      // cpol
1333         .addImm(0)            // tfe
1334         .addImm(0)            // swz
1335         .addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1336 
1337   std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI, Paired);
1338   const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
1339   const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
1340 
1341   // Copy to the old destination registers.
1342   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1343   const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
1344   const auto *Dest1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdata);
1345 
1346   BuildMI(*MBB, Paired.I, DL, CopyDesc)
1347       .add(*Dest0) // Copy to same destination including flags and sub reg.
1348       .addReg(DestReg, 0, SubRegIdx0);
1349   MachineInstr *Copy1 = BuildMI(*MBB, Paired.I, DL, CopyDesc)
1350                             .add(*Dest1)
1351                             .addReg(DestReg, RegState::Kill, SubRegIdx1);
1352 
1353   moveInstsAfter(Copy1, InstsToMove);
1354 
1355   CI.I->eraseFromParent();
1356   Paired.I->eraseFromParent();
1357   return New;
1358 }
1359 
1360 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeTBufferLoadPair(
1361     CombineInfo &CI, CombineInfo &Paired,
1362     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1363   MachineBasicBlock *MBB = CI.I->getParent();
1364   DebugLoc DL = CI.I->getDebugLoc();
1365 
1366   const unsigned Opcode = getNewOpcode(CI, Paired);
1367 
1368   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1369 
1370   // Copy to the new source register.
1371   Register DestReg = MRI->createVirtualRegister(SuperRC);
1372   unsigned MergedOffset = std::min(CI.Offset, Paired.Offset);
1373 
1374   auto MIB = BuildMI(*MBB, Paired.I, DL, TII->get(Opcode), DestReg);
1375 
1376   AddressRegs Regs = getRegs(Opcode, *TII);
1377 
1378   if (Regs.VAddr)
1379     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1380 
1381   unsigned JoinedFormat =
1382       getBufferFormatWithCompCount(CI.Format, CI.Width + Paired.Width, *STM);
1383 
1384   // It shouldn't be possible to get this far if the two instructions
1385   // don't have a single memoperand, because MachineInstr::mayAlias()
1386   // will return true if this is the case.
1387   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1388 
1389   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1390   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1391 
1392   MachineInstr *New =
1393       MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1394           .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1395           .addImm(MergedOffset) // offset
1396           .addImm(JoinedFormat) // format
1397           .addImm(CI.CPol)      // cpol
1398           .addImm(0)            // tfe
1399           .addImm(0)            // swz
1400           .addMemOperand(
1401               combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1402 
1403   std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI, Paired);
1404   const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
1405   const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
1406 
1407   // Copy to the old destination registers.
1408   const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1409   const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
1410   const auto *Dest1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdata);
1411 
1412   BuildMI(*MBB, Paired.I, DL, CopyDesc)
1413       .add(*Dest0) // Copy to same destination including flags and sub reg.
1414       .addReg(DestReg, 0, SubRegIdx0);
1415   MachineInstr *Copy1 = BuildMI(*MBB, Paired.I, DL, CopyDesc)
1416                             .add(*Dest1)
1417                             .addReg(DestReg, RegState::Kill, SubRegIdx1);
1418 
1419   moveInstsAfter(Copy1, InstsToMove);
1420 
1421   CI.I->eraseFromParent();
1422   Paired.I->eraseFromParent();
1423   return New;
1424 }
1425 
1426 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeTBufferStorePair(
1427     CombineInfo &CI, CombineInfo &Paired,
1428     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1429   MachineBasicBlock *MBB = CI.I->getParent();
1430   DebugLoc DL = CI.I->getDebugLoc();
1431 
1432   const unsigned Opcode = getNewOpcode(CI, Paired);
1433 
1434   std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI, Paired);
1435   const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
1436   const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
1437 
1438   // Copy to the new source register.
1439   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1440   Register SrcReg = MRI->createVirtualRegister(SuperRC);
1441 
1442   const auto *Src0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
1443   const auto *Src1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdata);
1444 
1445   BuildMI(*MBB, Paired.I, DL, TII->get(AMDGPU::REG_SEQUENCE), SrcReg)
1446       .add(*Src0)
1447       .addImm(SubRegIdx0)
1448       .add(*Src1)
1449       .addImm(SubRegIdx1);
1450 
1451   auto MIB = BuildMI(*MBB, Paired.I, DL, TII->get(Opcode))
1452                  .addReg(SrcReg, RegState::Kill);
1453 
1454   AddressRegs Regs = getRegs(Opcode, *TII);
1455 
1456   if (Regs.VAddr)
1457     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1458 
1459   unsigned JoinedFormat =
1460       getBufferFormatWithCompCount(CI.Format, CI.Width + Paired.Width, *STM);
1461 
1462   // It shouldn't be possible to get this far if the two instructions
1463   // don't have a single memoperand, because MachineInstr::mayAlias()
1464   // will return true if this is the case.
1465   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1466 
1467   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1468   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1469 
1470   MachineInstr *New =
1471       MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1472           .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1473           .addImm(std::min(CI.Offset, Paired.Offset)) // offset
1474           .addImm(JoinedFormat)                     // format
1475           .addImm(CI.CPol)                          // cpol
1476           .addImm(0)                                // tfe
1477           .addImm(0)                                // swz
1478           .addMemOperand(
1479               combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1480 
1481   moveInstsAfter(MIB, InstsToMove);
1482 
1483   CI.I->eraseFromParent();
1484   Paired.I->eraseFromParent();
1485   return New;
1486 }
1487 
1488 unsigned SILoadStoreOptimizer::getNewOpcode(const CombineInfo &CI,
1489                                             const CombineInfo &Paired) {
1490   const unsigned Width = CI.Width + Paired.Width;
1491 
1492   switch (CI.InstClass) {
1493   default:
1494     assert(CI.InstClass == BUFFER_LOAD || CI.InstClass == BUFFER_STORE);
1495     // FIXME: Handle d16 correctly
1496     return AMDGPU::getMUBUFOpcode(AMDGPU::getMUBUFBaseOpcode(CI.I->getOpcode()),
1497                                   Width);
1498   case TBUFFER_LOAD:
1499   case TBUFFER_STORE:
1500     return AMDGPU::getMTBUFOpcode(AMDGPU::getMTBUFBaseOpcode(CI.I->getOpcode()),
1501                                   Width);
1502 
1503   case UNKNOWN:
1504     llvm_unreachable("Unknown instruction class");
1505   case S_BUFFER_LOAD_IMM:
1506     switch (Width) {
1507     default:
1508       return 0;
1509     case 2:
1510       return AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM;
1511     case 4:
1512       return AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM;
1513     case 8:
1514       return AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM;
1515     }
1516   case MIMG:
1517     assert((countPopulation(CI.DMask | Paired.DMask) == Width) &&
1518            "No overlaps");
1519     return AMDGPU::getMaskedMIMGOp(CI.I->getOpcode(), Width);
1520   }
1521 }
1522 
1523 std::pair<unsigned, unsigned>
1524 SILoadStoreOptimizer::getSubRegIdxs(const CombineInfo &CI,
1525                                     const CombineInfo &Paired) {
1526   bool ReverseOrder;
1527   if (CI.InstClass == MIMG) {
1528     assert(
1529         (countPopulation(CI.DMask | Paired.DMask) == CI.Width + Paired.Width) &&
1530         "No overlaps");
1531     ReverseOrder = CI.DMask > Paired.DMask;
1532   } else {
1533     ReverseOrder = CI.Offset > Paired.Offset;
1534   }
1535 
1536   unsigned Idx0;
1537   unsigned Idx1;
1538 
1539   static const unsigned Idxs[5][4] = {
1540       {AMDGPU::sub0, AMDGPU::sub0_sub1, AMDGPU::sub0_sub1_sub2, AMDGPU::sub0_sub1_sub2_sub3},
1541       {AMDGPU::sub1, AMDGPU::sub1_sub2, AMDGPU::sub1_sub2_sub3, AMDGPU::sub1_sub2_sub3_sub4},
1542       {AMDGPU::sub2, AMDGPU::sub2_sub3, AMDGPU::sub2_sub3_sub4, AMDGPU::sub2_sub3_sub4_sub5},
1543       {AMDGPU::sub3, AMDGPU::sub3_sub4, AMDGPU::sub3_sub4_sub5, AMDGPU::sub3_sub4_sub5_sub6},
1544       {AMDGPU::sub4, AMDGPU::sub4_sub5, AMDGPU::sub4_sub5_sub6, AMDGPU::sub4_sub5_sub6_sub7},
1545   };
1546 
1547   assert(CI.Width >= 1 && CI.Width <= 4);
1548   assert(Paired.Width >= 1 && Paired.Width <= 4);
1549 
1550   if (ReverseOrder) {
1551     Idx1 = Idxs[0][Paired.Width - 1];
1552     Idx0 = Idxs[Paired.Width][CI.Width - 1];
1553   } else {
1554     Idx0 = Idxs[0][CI.Width - 1];
1555     Idx1 = Idxs[CI.Width][Paired.Width - 1];
1556   }
1557 
1558   return std::make_pair(Idx0, Idx1);
1559 }
1560 
1561 const TargetRegisterClass *
1562 SILoadStoreOptimizer::getTargetRegisterClass(const CombineInfo &CI,
1563                                              const CombineInfo &Paired) {
1564   if (CI.InstClass == S_BUFFER_LOAD_IMM) {
1565     switch (CI.Width + Paired.Width) {
1566     default:
1567       return nullptr;
1568     case 2:
1569       return &AMDGPU::SReg_64_XEXECRegClass;
1570     case 4:
1571       return &AMDGPU::SGPR_128RegClass;
1572     case 8:
1573       return &AMDGPU::SGPR_256RegClass;
1574     case 16:
1575       return &AMDGPU::SGPR_512RegClass;
1576     }
1577   }
1578 
1579   unsigned BitWidth = 32 * (CI.Width + Paired.Width);
1580   return TRI->isAGPRClass(getDataRegClass(*CI.I))
1581              ? TRI->getAGPRClassForBitWidth(BitWidth)
1582              : TRI->getVGPRClassForBitWidth(BitWidth);
1583 }
1584 
1585 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeBufferStorePair(
1586     CombineInfo &CI, CombineInfo &Paired,
1587     const SmallVectorImpl<MachineInstr *> &InstsToMove) {
1588   MachineBasicBlock *MBB = CI.I->getParent();
1589   DebugLoc DL = CI.I->getDebugLoc();
1590 
1591   const unsigned Opcode = getNewOpcode(CI, Paired);
1592 
1593   std::pair<unsigned, unsigned> SubRegIdx = getSubRegIdxs(CI, Paired);
1594   const unsigned SubRegIdx0 = std::get<0>(SubRegIdx);
1595   const unsigned SubRegIdx1 = std::get<1>(SubRegIdx);
1596 
1597   // Copy to the new source register.
1598   const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1599   Register SrcReg = MRI->createVirtualRegister(SuperRC);
1600 
1601   const auto *Src0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
1602   const auto *Src1 = TII->getNamedOperand(*Paired.I, AMDGPU::OpName::vdata);
1603 
1604   BuildMI(*MBB, Paired.I, DL, TII->get(AMDGPU::REG_SEQUENCE), SrcReg)
1605       .add(*Src0)
1606       .addImm(SubRegIdx0)
1607       .add(*Src1)
1608       .addImm(SubRegIdx1);
1609 
1610   auto MIB = BuildMI(*MBB, Paired.I, DL, TII->get(Opcode))
1611                  .addReg(SrcReg, RegState::Kill);
1612 
1613   AddressRegs Regs = getRegs(Opcode, *TII);
1614 
1615   if (Regs.VAddr)
1616     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1617 
1618 
1619   // It shouldn't be possible to get this far if the two instructions
1620   // don't have a single memoperand, because MachineInstr::mayAlias()
1621   // will return true if this is the case.
1622   assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1623 
1624   const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
1625   const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
1626 
1627   MachineInstr *New =
1628     MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1629         .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1630         .addImm(std::min(CI.Offset, Paired.Offset)) // offset
1631         .addImm(CI.CPol)      // cpol
1632         .addImm(0)            // tfe
1633         .addImm(0)            // swz
1634         .addMemOperand(combineKnownAdjacentMMOs(*MBB->getParent(), MMOa, MMOb));
1635 
1636   moveInstsAfter(MIB, InstsToMove);
1637 
1638   CI.I->eraseFromParent();
1639   Paired.I->eraseFromParent();
1640   return New;
1641 }
1642 
1643 MachineOperand
1644 SILoadStoreOptimizer::createRegOrImm(int32_t Val, MachineInstr &MI) const {
1645   APInt V(32, Val, true);
1646   if (TII->isInlineConstant(V))
1647     return MachineOperand::CreateImm(Val);
1648 
1649   Register Reg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1650   MachineInstr *Mov =
1651   BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
1652           TII->get(AMDGPU::S_MOV_B32), Reg)
1653     .addImm(Val);
1654   (void)Mov;
1655   LLVM_DEBUG(dbgs() << "    "; Mov->dump());
1656   return MachineOperand::CreateReg(Reg, false);
1657 }
1658 
1659 // Compute base address using Addr and return the final register.
1660 Register SILoadStoreOptimizer::computeBase(MachineInstr &MI,
1661                                            const MemAddress &Addr) const {
1662   MachineBasicBlock *MBB = MI.getParent();
1663   MachineBasicBlock::iterator MBBI = MI.getIterator();
1664   DebugLoc DL = MI.getDebugLoc();
1665 
1666   assert((TRI->getRegSizeInBits(Addr.Base.LoReg, *MRI) == 32 ||
1667           Addr.Base.LoSubReg) &&
1668          "Expected 32-bit Base-Register-Low!!");
1669 
1670   assert((TRI->getRegSizeInBits(Addr.Base.HiReg, *MRI) == 32 ||
1671           Addr.Base.HiSubReg) &&
1672          "Expected 32-bit Base-Register-Hi!!");
1673 
1674   LLVM_DEBUG(dbgs() << "  Re-Computed Anchor-Base:\n");
1675   MachineOperand OffsetLo = createRegOrImm(static_cast<int32_t>(Addr.Offset), MI);
1676   MachineOperand OffsetHi =
1677     createRegOrImm(static_cast<int32_t>(Addr.Offset >> 32), MI);
1678 
1679   const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
1680   Register CarryReg = MRI->createVirtualRegister(CarryRC);
1681   Register DeadCarryReg = MRI->createVirtualRegister(CarryRC);
1682 
1683   Register DestSub0 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1684   Register DestSub1 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1685   MachineInstr *LoHalf =
1686     BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::V_ADD_CO_U32_e64), DestSub0)
1687       .addReg(CarryReg, RegState::Define)
1688       .addReg(Addr.Base.LoReg, 0, Addr.Base.LoSubReg)
1689       .add(OffsetLo)
1690       .addImm(0); // clamp bit
1691   (void)LoHalf;
1692   LLVM_DEBUG(dbgs() << "    "; LoHalf->dump(););
1693 
1694   MachineInstr *HiHalf =
1695   BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::V_ADDC_U32_e64), DestSub1)
1696     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
1697     .addReg(Addr.Base.HiReg, 0, Addr.Base.HiSubReg)
1698     .add(OffsetHi)
1699     .addReg(CarryReg, RegState::Kill)
1700     .addImm(0); // clamp bit
1701   (void)HiHalf;
1702   LLVM_DEBUG(dbgs() << "    "; HiHalf->dump(););
1703 
1704   Register FullDestReg = MRI->createVirtualRegister(TRI->getVGPR64Class());
1705   MachineInstr *FullBase =
1706     BuildMI(*MBB, MBBI, DL, TII->get(TargetOpcode::REG_SEQUENCE), FullDestReg)
1707       .addReg(DestSub0)
1708       .addImm(AMDGPU::sub0)
1709       .addReg(DestSub1)
1710       .addImm(AMDGPU::sub1);
1711   (void)FullBase;
1712   LLVM_DEBUG(dbgs() << "    "; FullBase->dump(); dbgs() << "\n";);
1713 
1714   return FullDestReg;
1715 }
1716 
1717 // Update base and offset with the NewBase and NewOffset in MI.
1718 void SILoadStoreOptimizer::updateBaseAndOffset(MachineInstr &MI,
1719                                                Register NewBase,
1720                                                int32_t NewOffset) const {
1721   auto Base = TII->getNamedOperand(MI, AMDGPU::OpName::vaddr);
1722   Base->setReg(NewBase);
1723   Base->setIsKill(false);
1724   TII->getNamedOperand(MI, AMDGPU::OpName::offset)->setImm(NewOffset);
1725 }
1726 
1727 Optional<int32_t>
1728 SILoadStoreOptimizer::extractConstOffset(const MachineOperand &Op) const {
1729   if (Op.isImm())
1730     return Op.getImm();
1731 
1732   if (!Op.isReg())
1733     return None;
1734 
1735   MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
1736   if (!Def || Def->getOpcode() != AMDGPU::S_MOV_B32 ||
1737       !Def->getOperand(1).isImm())
1738     return None;
1739 
1740   return Def->getOperand(1).getImm();
1741 }
1742 
1743 // Analyze Base and extracts:
1744 //  - 32bit base registers, subregisters
1745 //  - 64bit constant offset
1746 // Expecting base computation as:
1747 //   %OFFSET0:sgpr_32 = S_MOV_B32 8000
1748 //   %LO:vgpr_32, %c:sreg_64_xexec =
1749 //       V_ADD_CO_U32_e64 %BASE_LO:vgpr_32, %103:sgpr_32,
1750 //   %HI:vgpr_32, = V_ADDC_U32_e64 %BASE_HI:vgpr_32, 0, killed %c:sreg_64_xexec
1751 //   %Base:vreg_64 =
1752 //       REG_SEQUENCE %LO:vgpr_32, %subreg.sub0, %HI:vgpr_32, %subreg.sub1
1753 void SILoadStoreOptimizer::processBaseWithConstOffset(const MachineOperand &Base,
1754                                                       MemAddress &Addr) const {
1755   if (!Base.isReg())
1756     return;
1757 
1758   MachineInstr *Def = MRI->getUniqueVRegDef(Base.getReg());
1759   if (!Def || Def->getOpcode() != AMDGPU::REG_SEQUENCE
1760       || Def->getNumOperands() != 5)
1761     return;
1762 
1763   MachineOperand BaseLo = Def->getOperand(1);
1764   MachineOperand BaseHi = Def->getOperand(3);
1765   if (!BaseLo.isReg() || !BaseHi.isReg())
1766     return;
1767 
1768   MachineInstr *BaseLoDef = MRI->getUniqueVRegDef(BaseLo.getReg());
1769   MachineInstr *BaseHiDef = MRI->getUniqueVRegDef(BaseHi.getReg());
1770 
1771   if (!BaseLoDef || BaseLoDef->getOpcode() != AMDGPU::V_ADD_CO_U32_e64 ||
1772       !BaseHiDef || BaseHiDef->getOpcode() != AMDGPU::V_ADDC_U32_e64)
1773     return;
1774 
1775   const auto *Src0 = TII->getNamedOperand(*BaseLoDef, AMDGPU::OpName::src0);
1776   const auto *Src1 = TII->getNamedOperand(*BaseLoDef, AMDGPU::OpName::src1);
1777 
1778   auto Offset0P = extractConstOffset(*Src0);
1779   if (Offset0P)
1780     BaseLo = *Src1;
1781   else {
1782     if (!(Offset0P = extractConstOffset(*Src1)))
1783       return;
1784     BaseLo = *Src0;
1785   }
1786 
1787   Src0 = TII->getNamedOperand(*BaseHiDef, AMDGPU::OpName::src0);
1788   Src1 = TII->getNamedOperand(*BaseHiDef, AMDGPU::OpName::src1);
1789 
1790   if (Src0->isImm())
1791     std::swap(Src0, Src1);
1792 
1793   if (!Src1->isImm())
1794     return;
1795 
1796   uint64_t Offset1 = Src1->getImm();
1797   BaseHi = *Src0;
1798 
1799   Addr.Base.LoReg = BaseLo.getReg();
1800   Addr.Base.HiReg = BaseHi.getReg();
1801   Addr.Base.LoSubReg = BaseLo.getSubReg();
1802   Addr.Base.HiSubReg = BaseHi.getSubReg();
1803   Addr.Offset = (*Offset0P & 0x00000000ffffffff) | (Offset1 << 32);
1804 }
1805 
1806 bool SILoadStoreOptimizer::promoteConstantOffsetToImm(
1807     MachineInstr &MI,
1808     MemInfoMap &Visited,
1809     SmallPtrSet<MachineInstr *, 4> &AnchorList) const {
1810 
1811   if (!(MI.mayLoad() ^ MI.mayStore()))
1812     return false;
1813 
1814   // TODO: Support flat and scratch.
1815   if (AMDGPU::getGlobalSaddrOp(MI.getOpcode()) < 0)
1816     return false;
1817 
1818   if (MI.mayLoad() &&
1819       TII->getNamedOperand(MI, AMDGPU::OpName::vdata) != nullptr)
1820     return false;
1821 
1822   if (AnchorList.count(&MI))
1823     return false;
1824 
1825   LLVM_DEBUG(dbgs() << "\nTryToPromoteConstantOffsetToImmFor "; MI.dump());
1826 
1827   if (TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm()) {
1828     LLVM_DEBUG(dbgs() << "  Const-offset is already promoted.\n";);
1829     return false;
1830   }
1831 
1832   // Step1: Find the base-registers and a 64bit constant offset.
1833   MachineOperand &Base = *TII->getNamedOperand(MI, AMDGPU::OpName::vaddr);
1834   MemAddress MAddr;
1835   if (Visited.find(&MI) == Visited.end()) {
1836     processBaseWithConstOffset(Base, MAddr);
1837     Visited[&MI] = MAddr;
1838   } else
1839     MAddr = Visited[&MI];
1840 
1841   if (MAddr.Offset == 0) {
1842     LLVM_DEBUG(dbgs() << "  Failed to extract constant-offset or there are no"
1843                          " constant offsets that can be promoted.\n";);
1844     return false;
1845   }
1846 
1847   LLVM_DEBUG(dbgs() << "  BASE: {" << MAddr.Base.HiReg << ", "
1848              << MAddr.Base.LoReg << "} Offset: " << MAddr.Offset << "\n\n";);
1849 
1850   // Step2: Traverse through MI's basic block and find an anchor(that has the
1851   // same base-registers) with the highest 13bit distance from MI's offset.
1852   // E.g. (64bit loads)
1853   // bb:
1854   //   addr1 = &a + 4096;   load1 = load(addr1,  0)
1855   //   addr2 = &a + 6144;   load2 = load(addr2,  0)
1856   //   addr3 = &a + 8192;   load3 = load(addr3,  0)
1857   //   addr4 = &a + 10240;  load4 = load(addr4,  0)
1858   //   addr5 = &a + 12288;  load5 = load(addr5,  0)
1859   //
1860   // Starting from the first load, the optimization will try to find a new base
1861   // from which (&a + 4096) has 13 bit distance. Both &a + 6144 and &a + 8192
1862   // has 13bit distance from &a + 4096. The heuristic considers &a + 8192
1863   // as the new-base(anchor) because of the maximum distance which can
1864   // accomodate more intermediate bases presumeably.
1865   //
1866   // Step3: move (&a + 8192) above load1. Compute and promote offsets from
1867   // (&a + 8192) for load1, load2, load4.
1868   //   addr = &a + 8192
1869   //   load1 = load(addr,       -4096)
1870   //   load2 = load(addr,       -2048)
1871   //   load3 = load(addr,       0)
1872   //   load4 = load(addr,       2048)
1873   //   addr5 = &a + 12288;  load5 = load(addr5,  0)
1874   //
1875   MachineInstr *AnchorInst = nullptr;
1876   MemAddress AnchorAddr;
1877   uint32_t MaxDist = std::numeric_limits<uint32_t>::min();
1878   SmallVector<std::pair<MachineInstr *, int64_t>, 4> InstsWCommonBase;
1879 
1880   MachineBasicBlock *MBB = MI.getParent();
1881   MachineBasicBlock::iterator E = MBB->end();
1882   MachineBasicBlock::iterator MBBI = MI.getIterator();
1883   ++MBBI;
1884   const SITargetLowering *TLI =
1885     static_cast<const SITargetLowering *>(STM->getTargetLowering());
1886 
1887   for ( ; MBBI != E; ++MBBI) {
1888     MachineInstr &MINext = *MBBI;
1889     // TODO: Support finding an anchor(with same base) from store addresses or
1890     // any other load addresses where the opcodes are different.
1891     if (MINext.getOpcode() != MI.getOpcode() ||
1892         TII->getNamedOperand(MINext, AMDGPU::OpName::offset)->getImm())
1893       continue;
1894 
1895     const MachineOperand &BaseNext =
1896       *TII->getNamedOperand(MINext, AMDGPU::OpName::vaddr);
1897     MemAddress MAddrNext;
1898     if (Visited.find(&MINext) == Visited.end()) {
1899       processBaseWithConstOffset(BaseNext, MAddrNext);
1900       Visited[&MINext] = MAddrNext;
1901     } else
1902       MAddrNext = Visited[&MINext];
1903 
1904     if (MAddrNext.Base.LoReg != MAddr.Base.LoReg ||
1905         MAddrNext.Base.HiReg != MAddr.Base.HiReg ||
1906         MAddrNext.Base.LoSubReg != MAddr.Base.LoSubReg ||
1907         MAddrNext.Base.HiSubReg != MAddr.Base.HiSubReg)
1908       continue;
1909 
1910     InstsWCommonBase.push_back(std::make_pair(&MINext, MAddrNext.Offset));
1911 
1912     int64_t Dist = MAddr.Offset - MAddrNext.Offset;
1913     TargetLoweringBase::AddrMode AM;
1914     AM.HasBaseReg = true;
1915     AM.BaseOffs = Dist;
1916     if (TLI->isLegalGlobalAddressingMode(AM) &&
1917         (uint32_t)std::abs(Dist) > MaxDist) {
1918       MaxDist = std::abs(Dist);
1919 
1920       AnchorAddr = MAddrNext;
1921       AnchorInst = &MINext;
1922     }
1923   }
1924 
1925   if (AnchorInst) {
1926     LLVM_DEBUG(dbgs() << "  Anchor-Inst(with max-distance from Offset): ";
1927                AnchorInst->dump());
1928     LLVM_DEBUG(dbgs() << "  Anchor-Offset from BASE: "
1929                <<  AnchorAddr.Offset << "\n\n");
1930 
1931     // Instead of moving up, just re-compute anchor-instruction's base address.
1932     Register Base = computeBase(MI, AnchorAddr);
1933 
1934     updateBaseAndOffset(MI, Base, MAddr.Offset - AnchorAddr.Offset);
1935     LLVM_DEBUG(dbgs() << "  After promotion: "; MI.dump(););
1936 
1937     for (auto P : InstsWCommonBase) {
1938       TargetLoweringBase::AddrMode AM;
1939       AM.HasBaseReg = true;
1940       AM.BaseOffs = P.second - AnchorAddr.Offset;
1941 
1942       if (TLI->isLegalGlobalAddressingMode(AM)) {
1943         LLVM_DEBUG(dbgs() << "  Promote Offset(" << P.second;
1944                    dbgs() << ")"; P.first->dump());
1945         updateBaseAndOffset(*P.first, Base, P.second - AnchorAddr.Offset);
1946         LLVM_DEBUG(dbgs() << "     After promotion: "; P.first->dump());
1947       }
1948     }
1949     AnchorList.insert(AnchorInst);
1950     return true;
1951   }
1952 
1953   return false;
1954 }
1955 
1956 void SILoadStoreOptimizer::addInstToMergeableList(const CombineInfo &CI,
1957                  std::list<std::list<CombineInfo> > &MergeableInsts) const {
1958   for (std::list<CombineInfo> &AddrList : MergeableInsts) {
1959     if (AddrList.front().InstClass == CI.InstClass &&
1960         AddrList.front().IsAGPR == CI.IsAGPR &&
1961         AddrList.front().hasSameBaseAddress(*CI.I)) {
1962       AddrList.emplace_back(CI);
1963       return;
1964     }
1965   }
1966 
1967   // Base address not found, so add a new list.
1968   MergeableInsts.emplace_back(1, CI);
1969 }
1970 
1971 std::pair<MachineBasicBlock::iterator, bool>
1972 SILoadStoreOptimizer::collectMergeableInsts(
1973     MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End,
1974     MemInfoMap &Visited, SmallPtrSet<MachineInstr *, 4> &AnchorList,
1975     std::list<std::list<CombineInfo>> &MergeableInsts) const {
1976   bool Modified = false;
1977 
1978   // Sort potential mergeable instructions into lists.  One list per base address.
1979   unsigned Order = 0;
1980   MachineBasicBlock::iterator BlockI = Begin;
1981   for (; BlockI != End; ++BlockI) {
1982     MachineInstr &MI = *BlockI;
1983 
1984     // We run this before checking if an address is mergeable, because it can produce
1985     // better code even if the instructions aren't mergeable.
1986     if (promoteConstantOffsetToImm(MI, Visited, AnchorList))
1987       Modified = true;
1988 
1989     // Don't combine if volatile. We also won't be able to merge across this, so
1990     // break the search. We can look after this barrier for separate merges.
1991     if (MI.hasOrderedMemoryRef()) {
1992       LLVM_DEBUG(dbgs() << "Breaking search on memory fence: " << MI);
1993 
1994       // Search will resume after this instruction in a separate merge list.
1995       ++BlockI;
1996       break;
1997     }
1998 
1999     const InstClassEnum InstClass = getInstClass(MI.getOpcode(), *TII);
2000     if (InstClass == UNKNOWN)
2001       continue;
2002 
2003     // Do not merge VMEM buffer instructions with "swizzled" bit set.
2004     int Swizzled =
2005         AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::swz);
2006     if (Swizzled != -1 && MI.getOperand(Swizzled).getImm())
2007       continue;
2008 
2009     CombineInfo CI;
2010     CI.setMI(MI, *this);
2011     CI.Order = Order++;
2012 
2013     if (!CI.hasMergeableAddress(*MRI))
2014       continue;
2015 
2016     LLVM_DEBUG(dbgs() << "Mergeable: " << MI);
2017 
2018     addInstToMergeableList(CI, MergeableInsts);
2019   }
2020 
2021   // At this point we have lists of Mergeable instructions.
2022   //
2023   // Part 2: Sort lists by offset and then for each CombineInfo object in the
2024   // list try to find an instruction that can be merged with I.  If an instruction
2025   // is found, it is stored in the Paired field.  If no instructions are found, then
2026   // the CombineInfo object is deleted from the list.
2027 
2028   for (std::list<std::list<CombineInfo>>::iterator I = MergeableInsts.begin(),
2029                                                    E = MergeableInsts.end(); I != E;) {
2030 
2031     std::list<CombineInfo> &MergeList = *I;
2032     if (MergeList.size() <= 1) {
2033       // This means we have found only one instruction with a given address
2034       // that can be merged, and we need at least 2 instructions to do a merge,
2035       // so this list can be discarded.
2036       I = MergeableInsts.erase(I);
2037       continue;
2038     }
2039 
2040     // Sort the lists by offsets, this way mergeable instructions will be
2041     // adjacent to each other in the list, which will make it easier to find
2042     // matches.
2043     MergeList.sort(
2044         [] (const CombineInfo &A, const CombineInfo &B) {
2045           return A.Offset < B.Offset;
2046         });
2047     ++I;
2048   }
2049 
2050   return std::make_pair(BlockI, Modified);
2051 }
2052 
2053 // Scan through looking for adjacent LDS operations with constant offsets from
2054 // the same base register. We rely on the scheduler to do the hard work of
2055 // clustering nearby loads, and assume these are all adjacent.
2056 bool SILoadStoreOptimizer::optimizeBlock(
2057                        std::list<std::list<CombineInfo> > &MergeableInsts) {
2058   bool Modified = false;
2059 
2060   for (std::list<std::list<CombineInfo>>::iterator I = MergeableInsts.begin(),
2061                                                    E = MergeableInsts.end(); I != E;) {
2062     std::list<CombineInfo> &MergeList = *I;
2063 
2064     bool OptimizeListAgain = false;
2065     if (!optimizeInstsWithSameBaseAddr(MergeList, OptimizeListAgain)) {
2066       // We weren't able to make any changes, so delete the list so we don't
2067       // process the same instructions the next time we try to optimize this
2068       // block.
2069       I = MergeableInsts.erase(I);
2070       continue;
2071     }
2072 
2073     Modified = true;
2074 
2075     // We made changes, but also determined that there were no more optimization
2076     // opportunities, so we don't need to reprocess the list
2077     if (!OptimizeListAgain) {
2078       I = MergeableInsts.erase(I);
2079       continue;
2080     }
2081     OptimizeAgain = true;
2082   }
2083   return Modified;
2084 }
2085 
2086 bool
2087 SILoadStoreOptimizer::optimizeInstsWithSameBaseAddr(
2088                                           std::list<CombineInfo> &MergeList,
2089                                           bool &OptimizeListAgain) {
2090   if (MergeList.empty())
2091     return false;
2092 
2093   bool Modified = false;
2094 
2095   for (auto I = MergeList.begin(), Next = std::next(I); Next != MergeList.end();
2096        Next = std::next(I)) {
2097 
2098     auto First = I;
2099     auto Second = Next;
2100 
2101     if ((*First).Order > (*Second).Order)
2102       std::swap(First, Second);
2103     CombineInfo &CI = *First;
2104     CombineInfo &Paired = *Second;
2105 
2106     SmallVector<MachineInstr *, 8> InstsToMove;
2107     if (!checkAndPrepareMerge(CI, Paired, InstsToMove)) {
2108       ++I;
2109       continue;
2110     }
2111 
2112     Modified = true;
2113 
2114     LLVM_DEBUG(dbgs() << "Merging: " << *CI.I << "   with: " << *Paired.I);
2115 
2116     switch (CI.InstClass) {
2117     default:
2118       llvm_unreachable("unknown InstClass");
2119       break;
2120     case DS_READ: {
2121       MachineBasicBlock::iterator NewMI =
2122           mergeRead2Pair(CI, Paired, InstsToMove);
2123       CI.setMI(NewMI, *this);
2124       break;
2125     }
2126     case DS_WRITE: {
2127       MachineBasicBlock::iterator NewMI =
2128           mergeWrite2Pair(CI, Paired, InstsToMove);
2129       CI.setMI(NewMI, *this);
2130       break;
2131     }
2132     case S_BUFFER_LOAD_IMM: {
2133       MachineBasicBlock::iterator NewMI =
2134           mergeSBufferLoadImmPair(CI, Paired, InstsToMove);
2135       CI.setMI(NewMI, *this);
2136       OptimizeListAgain |= (CI.Width + Paired.Width) < 8;
2137       break;
2138     }
2139     case BUFFER_LOAD: {
2140       MachineBasicBlock::iterator NewMI =
2141           mergeBufferLoadPair(CI, Paired, InstsToMove);
2142       CI.setMI(NewMI, *this);
2143       OptimizeListAgain |= (CI.Width + Paired.Width) < 4;
2144       break;
2145     }
2146     case BUFFER_STORE: {
2147       MachineBasicBlock::iterator NewMI =
2148           mergeBufferStorePair(CI, Paired, InstsToMove);
2149       CI.setMI(NewMI, *this);
2150       OptimizeListAgain |= (CI.Width + Paired.Width) < 4;
2151       break;
2152     }
2153     case MIMG: {
2154       MachineBasicBlock::iterator NewMI =
2155           mergeImagePair(CI, Paired, InstsToMove);
2156       CI.setMI(NewMI, *this);
2157       OptimizeListAgain |= (CI.Width + Paired.Width) < 4;
2158       break;
2159     }
2160     case TBUFFER_LOAD: {
2161       MachineBasicBlock::iterator NewMI =
2162           mergeTBufferLoadPair(CI, Paired, InstsToMove);
2163       CI.setMI(NewMI, *this);
2164       OptimizeListAgain |= (CI.Width + Paired.Width) < 4;
2165       break;
2166     }
2167     case TBUFFER_STORE: {
2168       MachineBasicBlock::iterator NewMI =
2169           mergeTBufferStorePair(CI, Paired, InstsToMove);
2170       CI.setMI(NewMI, *this);
2171       OptimizeListAgain |= (CI.Width + Paired.Width) < 4;
2172       break;
2173     }
2174     }
2175     CI.Order = Paired.Order;
2176     if (I == Second)
2177       I = Next;
2178 
2179     MergeList.erase(Second);
2180   }
2181 
2182   return Modified;
2183 }
2184 
2185 bool SILoadStoreOptimizer::runOnMachineFunction(MachineFunction &MF) {
2186   if (skipFunction(MF.getFunction()))
2187     return false;
2188 
2189   STM = &MF.getSubtarget<GCNSubtarget>();
2190   if (!STM->loadStoreOptEnabled())
2191     return false;
2192 
2193   TII = STM->getInstrInfo();
2194   TRI = &TII->getRegisterInfo();
2195 
2196   MRI = &MF.getRegInfo();
2197   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2198 
2199   LLVM_DEBUG(dbgs() << "Running SILoadStoreOptimizer\n");
2200 
2201   bool Modified = false;
2202 
2203   // Contains the list of instructions for which constant offsets are being
2204   // promoted to the IMM. This is tracked for an entire block at time.
2205   SmallPtrSet<MachineInstr *, 4> AnchorList;
2206   MemInfoMap Visited;
2207 
2208   for (MachineBasicBlock &MBB : MF) {
2209     MachineBasicBlock::iterator SectionEnd;
2210     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
2211          I = SectionEnd) {
2212       bool CollectModified;
2213       std::list<std::list<CombineInfo>> MergeableInsts;
2214 
2215       // First pass: Collect list of all instructions we know how to merge in a
2216       // subset of the block.
2217       std::tie(SectionEnd, CollectModified) =
2218           collectMergeableInsts(I, E, Visited, AnchorList, MergeableInsts);
2219 
2220       Modified |= CollectModified;
2221 
2222       do {
2223         OptimizeAgain = false;
2224         Modified |= optimizeBlock(MergeableInsts);
2225       } while (OptimizeAgain);
2226     }
2227 
2228     Visited.clear();
2229     AnchorList.clear();
2230   }
2231 
2232   return Modified;
2233 }
2234