LLVM 24.0.0git
SILoadStoreOptimizer.cpp
Go to the documentation of this file.
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
61#include "AMDGPU.h"
62#include "GCNSubtarget.h"
63#include "SIDefines.h"
67
68using namespace llvm;
69
70#define DEBUG_TYPE "si-load-store-opt"
71
72namespace {
73enum InstClassEnum {
74 UNKNOWN,
75 DS_READ,
76 DS_WRITE,
77 S_BUFFER_LOAD_IMM,
78 S_BUFFER_LOAD_SGPR_IMM,
79 S_LOAD_IMM,
80 BUFFER_LOAD,
81 BUFFER_STORE,
82 MIMG,
83 TBUFFER_LOAD,
84 TBUFFER_STORE,
85 GLOBAL_LOAD_SADDR,
86 GLOBAL_STORE_SADDR,
87 FLAT_LOAD,
88 FLAT_STORE,
89 FLAT_LOAD_SADDR,
90 FLAT_STORE_SADDR,
91 GLOBAL_LOAD, // GLOBAL_LOAD/GLOBAL_STORE are never used as the InstClass of
92 GLOBAL_STORE // any CombineInfo, they are only ever returned by
93 // getCommonInstClass.
94};
95
96struct AddressRegs {
97 unsigned char NumVAddrs = 0;
98 bool SBase = false;
99 bool SRsrc = false;
100 bool SOffset = false;
101 bool SAddr = false;
102 bool VAddr = false;
103 bool Addr = false;
104 bool SSamp = false;
105};
106
107// GFX10 image_sample instructions can have 12 vaddrs + srsrc + ssamp.
108const unsigned MaxAddressRegs = 12 + 1 + 1;
109
110class SILoadStoreOptimizer {
111 struct CombineInfo {
113 unsigned EltSize;
114 unsigned Offset;
115 unsigned Width;
116 unsigned Format;
117 unsigned BaseOff;
118 unsigned DMask;
119 InstClassEnum InstClass;
120 unsigned CPol = 0;
121 bool GDS = false;
122 const TargetRegisterClass *DataRC;
123 bool UseST64;
124 int AddrIdx[MaxAddressRegs];
125 const MachineOperand *AddrReg[MaxAddressRegs];
126 unsigned NumAddresses;
127 unsigned Order;
128
129 bool hasSameBaseAddress(const CombineInfo &CI) {
130 if (NumAddresses != CI.NumAddresses)
131 return false;
132
133 const MachineInstr &MI = *CI.I;
134 for (unsigned i = 0; i < NumAddresses; i++) {
135 const MachineOperand &AddrRegNext = MI.getOperand(AddrIdx[i]);
136
137 if (AddrReg[i]->isImm() || AddrRegNext.isImm()) {
138 if (AddrReg[i]->isImm() != AddrRegNext.isImm() ||
139 AddrReg[i]->getImm() != AddrRegNext.getImm()) {
140 return false;
141 }
142 continue;
143 }
144
145 // Check same base pointer. Be careful of subregisters, which can occur
146 // with vectors of pointers.
147 if (AddrReg[i]->getReg() != AddrRegNext.getReg() ||
148 AddrReg[i]->getSubReg() != AddrRegNext.getSubReg()) {
149 return false;
150 }
151 }
152 return true;
153 }
154
155 bool hasMergeableAddress(const MachineRegisterInfo &MRI) {
156 for (unsigned i = 0; i < NumAddresses; ++i) {
157 const MachineOperand *AddrOp = AddrReg[i];
158 // Immediates are always OK.
159 if (AddrOp->isImm())
160 continue;
161
162 // Don't try to merge addresses that aren't either immediates or registers.
163 // TODO: Should be possible to merge FrameIndexes and maybe some other
164 // non-register
165 if (!AddrOp->isReg())
166 return false;
167
168 // TODO: We should be able to merge instructions with other physical reg
169 // addresses too.
170 if (AddrOp->getReg().isPhysical() &&
171 AddrOp->getReg() != AMDGPU::SGPR_NULL)
172 return false;
173
174 // If an address has only one use then there will be no other
175 // instructions with the same address, so we can't merge this one.
176 if (MRI.hasOneNonDBGUse(AddrOp->getReg()))
177 return false;
178 }
179 return true;
180 }
181
182 void setMI(MachineBasicBlock::iterator MI, const SILoadStoreOptimizer &LSO);
183
184 // Compare by pointer order.
185 bool operator<(const CombineInfo& Other) const {
186 return (InstClass == MIMG) ? DMask < Other.DMask : Offset < Other.Offset;
187 }
188 };
189
190 struct BaseRegisters {
191 Register LoReg;
192 Register HiReg;
193
194 unsigned LoSubReg = 0;
195 unsigned HiSubReg = 0;
196 // True when using V_ADD_U64_e64 pattern
197 bool UseV64Pattern = false;
198 // True when using V_ADD_U32_e64 pattern (32-bit FLAT_SCRATCH vaddr)
199 bool UseScratchVGPRPattern = false;
200 };
201
202 struct MemAddress {
203 BaseRegisters Base;
204 int64_t Offset = 0;
205 };
206
207 using MemInfoMap = DenseMap<MachineInstr *, MemAddress>;
208
209private:
210 const GCNSubtarget *STM = nullptr;
211 const SIInstrInfo *TII = nullptr;
212 const SIRegisterInfo *TRI = nullptr;
213 MachineRegisterInfo *MRI = nullptr;
214 AliasAnalysis *AA = nullptr;
215 bool OptimizeAgain;
216
217 bool canSwapInstructions(const DenseSet<Register> &ARegDefs,
218 const DenseSet<Register> &ARegUses,
219 const MachineInstr &A, const MachineInstr &B) const;
220 static bool dmasksCanBeCombined(const CombineInfo &CI,
221 const SIInstrInfo &TII,
222 const CombineInfo &Paired);
223 static bool offsetsCanBeCombined(CombineInfo &CI, const GCNSubtarget &STI,
224 CombineInfo &Paired, bool Modify = false);
225 static bool widthsFit(const GCNSubtarget &STI, const CombineInfo &CI,
226 const CombineInfo &Paired);
227 unsigned getNewOpcode(const CombineInfo &CI, const CombineInfo &Paired);
228 static std::pair<unsigned, unsigned> getSubRegIdxs(const CombineInfo &CI,
229 const CombineInfo &Paired);
230 const TargetRegisterClass *
231 getTargetRegisterClass(const CombineInfo &CI,
232 const CombineInfo &Paired) const;
233 const TargetRegisterClass *getDataRegClass(const MachineInstr &MI) const;
234
235 CombineInfo *checkAndPrepareMerge(CombineInfo &CI, CombineInfo &Paired);
236
237 void copyToDestRegs(CombineInfo &CI, CombineInfo &Paired,
238 MachineBasicBlock::iterator InsertBefore,
239 const DebugLoc &DL, AMDGPU::OpName OpName,
240 Register DestReg) const;
241 Register copyFromSrcRegs(CombineInfo &CI, CombineInfo &Paired,
242 MachineBasicBlock::iterator InsertBefore,
243 const DebugLoc &DL, AMDGPU::OpName OpName) const;
244
245 unsigned read2Opcode(unsigned EltSize, bool GDS) const;
246 unsigned read2ST64Opcode(unsigned EltSize, bool GDS) const;
248 mergeRead2Pair(CombineInfo &CI, CombineInfo &Paired,
249 MachineBasicBlock::iterator InsertBefore);
250
251 unsigned write2Opcode(unsigned EltSize, bool GDS) const;
252 unsigned write2ST64Opcode(unsigned EltSize, bool GDS) const;
253 unsigned getWrite2Opcode(const CombineInfo &CI) const;
254
256 mergeWrite2Pair(CombineInfo &CI, CombineInfo &Paired,
257 MachineBasicBlock::iterator InsertBefore);
259 mergeImagePair(CombineInfo &CI, CombineInfo &Paired,
260 MachineBasicBlock::iterator InsertBefore);
262 mergeSMemLoadImmPair(CombineInfo &CI, CombineInfo &Paired,
263 MachineBasicBlock::iterator InsertBefore);
265 mergeBufferLoadPair(CombineInfo &CI, CombineInfo &Paired,
266 MachineBasicBlock::iterator InsertBefore);
268 mergeBufferStorePair(CombineInfo &CI, CombineInfo &Paired,
269 MachineBasicBlock::iterator InsertBefore);
271 mergeTBufferLoadPair(CombineInfo &CI, CombineInfo &Paired,
272 MachineBasicBlock::iterator InsertBefore);
274 mergeTBufferStorePair(CombineInfo &CI, CombineInfo &Paired,
275 MachineBasicBlock::iterator InsertBefore);
277 mergeFlatLoadPair(CombineInfo &CI, CombineInfo &Paired,
278 MachineBasicBlock::iterator InsertBefore);
280 mergeFlatStorePair(CombineInfo &CI, CombineInfo &Paired,
281 MachineBasicBlock::iterator InsertBefore);
282
283 void updateBaseAndOffset(MachineInstr &I, Register NewBase,
284 int32_t NewOffset) const;
285 void updateAsyncLDSAddress(MachineInstr &MI, int32_t OffsetDiff) const;
286 Register computeBase(MachineInstr &MI, const MemAddress &Addr) const;
287 MachineOperand createRegOrImm(int32_t Val, MachineInstr &MI) const;
288 bool processBaseWithConstOffset64(MachineInstr *AddDef,
289 const MachineOperand &Base,
290 MemAddress &Addr) const;
291 bool processBaseWithConstOffset32(MachineInstr *AddDef,
292 MemAddress &Addr) const;
293 void processBaseWithConstOffset(const MachineOperand &Base, MemAddress &Addr) const;
294 /// Promotes constant offset to the immediate by adjusting the base. It
295 /// tries to use a base from the nearby instructions that allows it to have
296 /// a 13bit constant offset which gets promoted to the immediate.
297 bool promoteConstantOffsetToImm(MachineInstr &CI,
298 MemInfoMap &Visited,
299 SmallPtrSet<MachineInstr *, 4> &Promoted) const;
300 void addInstToMergeableList(const CombineInfo &CI,
301 std::list<std::list<CombineInfo> > &MergeableInsts) const;
302
303 std::pair<MachineBasicBlock::iterator, bool> collectMergeableInsts(
305 MemInfoMap &Visited, SmallPtrSet<MachineInstr *, 4> &AnchorList,
306 std::list<std::list<CombineInfo>> &MergeableInsts) const;
307
308 static MachineMemOperand *combineKnownAdjacentMMOs(const CombineInfo &CI,
309 const CombineInfo &Paired);
310
311 static InstClassEnum getCommonInstClass(const CombineInfo &CI,
312 const CombineInfo &Paired);
313
314 bool optimizeInstsWithSameBaseAddr(std::list<CombineInfo> &MergeList,
315 bool &OptimizeListAgain);
316 bool optimizeBlock(std::list<std::list<CombineInfo> > &MergeableInsts);
317
318public:
319 SILoadStoreOptimizer(AliasAnalysis *AA) : AA(AA) {}
320 bool run(MachineFunction &MF);
321};
322
323class SILoadStoreOptimizerLegacy : public MachineFunctionPass {
324public:
325 static char ID;
326
327 SILoadStoreOptimizerLegacy() : MachineFunctionPass(ID) {}
328
329 bool runOnMachineFunction(MachineFunction &MF) override;
330
331 StringRef getPassName() const override { return "SI Load Store Optimizer"; }
332
333 void getAnalysisUsage(AnalysisUsage &AU) const override {
334 AU.setPreservesCFG();
336
338 }
339
340 MachineFunctionProperties getRequiredProperties() const override {
341 return MachineFunctionProperties().setIsSSA();
342 }
343};
344
345static unsigned getOpcodeWidth(const MachineInstr &MI, const SIInstrInfo &TII) {
346 const unsigned Opc = MI.getOpcode();
347
348 if (TII.isMUBUF(Opc)) {
349 // FIXME: Handle d16 correctly
351 }
352 if (TII.isImage(MI)) {
353 uint64_t DMaskImm =
354 TII.getNamedOperand(MI, AMDGPU::OpName::dmask)->getImm();
355 return llvm::popcount(DMaskImm);
356 }
357 if (TII.isMTBUF(Opc)) {
359 }
360
361 switch (Opc) {
362 case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
363 case AMDGPU::S_BUFFER_LOAD_DWORD_SGPR_IMM:
364 case AMDGPU::S_LOAD_DWORD_IMM:
365 case AMDGPU::GLOBAL_LOAD_DWORD:
366 case AMDGPU::GLOBAL_LOAD_DWORD_SADDR:
367 case AMDGPU::GLOBAL_STORE_DWORD:
368 case AMDGPU::GLOBAL_STORE_DWORD_SADDR:
369 case AMDGPU::FLAT_LOAD_DWORD:
370 case AMDGPU::FLAT_STORE_DWORD:
371 case AMDGPU::FLAT_LOAD_DWORD_SADDR:
372 case AMDGPU::FLAT_STORE_DWORD_SADDR:
373 return 1;
374 case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
375 case AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR_IMM:
376 case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM_ec:
377 case AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR_IMM_ec:
378 case AMDGPU::S_LOAD_DWORDX2_IMM:
379 case AMDGPU::S_LOAD_DWORDX2_IMM_ec:
380 case AMDGPU::GLOBAL_LOAD_DWORDX2:
381 case AMDGPU::GLOBAL_LOAD_DWORDX2_SADDR:
382 case AMDGPU::GLOBAL_STORE_DWORDX2:
383 case AMDGPU::GLOBAL_STORE_DWORDX2_SADDR:
384 case AMDGPU::FLAT_LOAD_DWORDX2:
385 case AMDGPU::FLAT_STORE_DWORDX2:
386 case AMDGPU::FLAT_LOAD_DWORDX2_SADDR:
387 case AMDGPU::FLAT_STORE_DWORDX2_SADDR:
388 return 2;
389 case AMDGPU::S_BUFFER_LOAD_DWORDX3_IMM:
390 case AMDGPU::S_BUFFER_LOAD_DWORDX3_SGPR_IMM:
391 case AMDGPU::S_BUFFER_LOAD_DWORDX3_IMM_ec:
392 case AMDGPU::S_BUFFER_LOAD_DWORDX3_SGPR_IMM_ec:
393 case AMDGPU::S_LOAD_DWORDX3_IMM:
394 case AMDGPU::S_LOAD_DWORDX3_IMM_ec:
395 case AMDGPU::GLOBAL_LOAD_DWORDX3:
396 case AMDGPU::GLOBAL_LOAD_DWORDX3_SADDR:
397 case AMDGPU::GLOBAL_STORE_DWORDX3:
398 case AMDGPU::GLOBAL_STORE_DWORDX3_SADDR:
399 case AMDGPU::FLAT_LOAD_DWORDX3:
400 case AMDGPU::FLAT_STORE_DWORDX3:
401 case AMDGPU::FLAT_LOAD_DWORDX3_SADDR:
402 case AMDGPU::FLAT_STORE_DWORDX3_SADDR:
403 return 3;
404 case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
405 case AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR_IMM:
406 case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM_ec:
407 case AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR_IMM_ec:
408 case AMDGPU::S_LOAD_DWORDX4_IMM:
409 case AMDGPU::S_LOAD_DWORDX4_IMM_ec:
410 case AMDGPU::GLOBAL_LOAD_DWORDX4:
411 case AMDGPU::GLOBAL_LOAD_DWORDX4_SADDR:
412 case AMDGPU::GLOBAL_STORE_DWORDX4:
413 case AMDGPU::GLOBAL_STORE_DWORDX4_SADDR:
414 case AMDGPU::FLAT_LOAD_DWORDX4:
415 case AMDGPU::FLAT_STORE_DWORDX4:
416 case AMDGPU::FLAT_LOAD_DWORDX4_SADDR:
417 case AMDGPU::FLAT_STORE_DWORDX4_SADDR:
418 return 4;
419 case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM:
420 case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR_IMM:
421 case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM_ec:
422 case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR_IMM_ec:
423 case AMDGPU::S_LOAD_DWORDX8_IMM:
424 case AMDGPU::S_LOAD_DWORDX8_IMM_ec:
425 return 8;
426 case AMDGPU::DS_READ_B32:
427 case AMDGPU::DS_READ_B32_gfx9:
428 case AMDGPU::DS_WRITE_B32:
429 case AMDGPU::DS_WRITE_B32_gfx9:
430 return 1;
431 case AMDGPU::DS_READ_B64:
432 case AMDGPU::DS_READ_B64_gfx9:
433 case AMDGPU::DS_WRITE_B64:
434 case AMDGPU::DS_WRITE_B64_gfx9:
435 return 2;
436 default:
437 return 0;
438 }
439}
440
441/// Maps instruction opcode to enum InstClassEnum.
442static InstClassEnum getInstClass(unsigned Opc, const SIInstrInfo &TII) {
443 switch (Opc) {
444 default:
445 if (TII.isMUBUF(Opc)) {
447 default:
448 return UNKNOWN;
449 case AMDGPU::BUFFER_LOAD_DWORD_BOTHEN:
450 case AMDGPU::BUFFER_LOAD_DWORD_BOTHEN_exact:
451 case AMDGPU::BUFFER_LOAD_DWORD_IDXEN:
452 case AMDGPU::BUFFER_LOAD_DWORD_IDXEN_exact:
453 case AMDGPU::BUFFER_LOAD_DWORD_OFFEN:
454 case AMDGPU::BUFFER_LOAD_DWORD_OFFEN_exact:
455 case AMDGPU::BUFFER_LOAD_DWORD_OFFSET:
456 case AMDGPU::BUFFER_LOAD_DWORD_OFFSET_exact:
457 case AMDGPU::BUFFER_LOAD_DWORD_VBUFFER_BOTHEN:
458 case AMDGPU::BUFFER_LOAD_DWORD_VBUFFER_BOTHEN_exact:
459 case AMDGPU::BUFFER_LOAD_DWORD_VBUFFER_IDXEN:
460 case AMDGPU::BUFFER_LOAD_DWORD_VBUFFER_IDXEN_exact:
461 case AMDGPU::BUFFER_LOAD_DWORD_VBUFFER_OFFEN:
462 case AMDGPU::BUFFER_LOAD_DWORD_VBUFFER_OFFEN_exact:
463 case AMDGPU::BUFFER_LOAD_DWORD_VBUFFER_OFFSET:
464 case AMDGPU::BUFFER_LOAD_DWORD_VBUFFER_OFFSET_exact:
465 return BUFFER_LOAD;
466 case AMDGPU::BUFFER_STORE_DWORD_BOTHEN:
467 case AMDGPU::BUFFER_STORE_DWORD_BOTHEN_exact:
468 case AMDGPU::BUFFER_STORE_DWORD_IDXEN:
469 case AMDGPU::BUFFER_STORE_DWORD_IDXEN_exact:
470 case AMDGPU::BUFFER_STORE_DWORD_OFFEN:
471 case AMDGPU::BUFFER_STORE_DWORD_OFFEN_exact:
472 case AMDGPU::BUFFER_STORE_DWORD_OFFSET:
473 case AMDGPU::BUFFER_STORE_DWORD_OFFSET_exact:
474 case AMDGPU::BUFFER_STORE_DWORD_VBUFFER_BOTHEN:
475 case AMDGPU::BUFFER_STORE_DWORD_VBUFFER_BOTHEN_exact:
476 case AMDGPU::BUFFER_STORE_DWORD_VBUFFER_IDXEN:
477 case AMDGPU::BUFFER_STORE_DWORD_VBUFFER_IDXEN_exact:
478 case AMDGPU::BUFFER_STORE_DWORD_VBUFFER_OFFEN:
479 case AMDGPU::BUFFER_STORE_DWORD_VBUFFER_OFFEN_exact:
480 case AMDGPU::BUFFER_STORE_DWORD_VBUFFER_OFFSET:
481 case AMDGPU::BUFFER_STORE_DWORD_VBUFFER_OFFSET_exact:
482 return BUFFER_STORE;
483 }
484 }
485 if (TII.isImage(Opc)) {
486 // Ignore instructions encoded without vaddr.
487 if (!AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::vaddr) &&
488 !AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::vaddr0))
489 return UNKNOWN;
490 // Ignore BVH instructions
492 return UNKNOWN;
493 // TODO: Support IMAGE_GET_RESINFO and IMAGE_GET_LOD.
494 if (TII.get(Opc).mayStore() || !TII.get(Opc).mayLoad() ||
495 TII.isGather4(Opc))
496 return UNKNOWN;
497 return MIMG;
498 }
499 if (TII.isMTBUF(Opc)) {
501 default:
502 return UNKNOWN;
503 case AMDGPU::TBUFFER_LOAD_FORMAT_X_BOTHEN:
504 case AMDGPU::TBUFFER_LOAD_FORMAT_X_BOTHEN_exact:
505 case AMDGPU::TBUFFER_LOAD_FORMAT_X_IDXEN:
506 case AMDGPU::TBUFFER_LOAD_FORMAT_X_IDXEN_exact:
507 case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFEN:
508 case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFEN_exact:
509 case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFSET:
510 case AMDGPU::TBUFFER_LOAD_FORMAT_X_OFFSET_exact:
511 case AMDGPU::TBUFFER_LOAD_FORMAT_X_VBUFFER_BOTHEN:
512 case AMDGPU::TBUFFER_LOAD_FORMAT_X_VBUFFER_BOTHEN_exact:
513 case AMDGPU::TBUFFER_LOAD_FORMAT_X_VBUFFER_IDXEN:
514 case AMDGPU::TBUFFER_LOAD_FORMAT_X_VBUFFER_IDXEN_exact:
515 case AMDGPU::TBUFFER_LOAD_FORMAT_X_VBUFFER_OFFEN:
516 case AMDGPU::TBUFFER_LOAD_FORMAT_X_VBUFFER_OFFEN_exact:
517 case AMDGPU::TBUFFER_LOAD_FORMAT_X_VBUFFER_OFFSET:
518 case AMDGPU::TBUFFER_LOAD_FORMAT_X_VBUFFER_OFFSET_exact:
519 return TBUFFER_LOAD;
520 case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFEN:
521 case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFEN_exact:
522 case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFSET:
523 case AMDGPU::TBUFFER_STORE_FORMAT_X_OFFSET_exact:
524 case AMDGPU::TBUFFER_STORE_FORMAT_X_VBUFFER_OFFEN:
525 case AMDGPU::TBUFFER_STORE_FORMAT_X_VBUFFER_OFFEN_exact:
526 case AMDGPU::TBUFFER_STORE_FORMAT_X_VBUFFER_OFFSET:
527 case AMDGPU::TBUFFER_STORE_FORMAT_X_VBUFFER_OFFSET_exact:
528 return TBUFFER_STORE;
529 }
530 }
531 return UNKNOWN;
532 case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
533 case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
534 case AMDGPU::S_BUFFER_LOAD_DWORDX3_IMM:
535 case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
536 case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM:
537 case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM_ec:
538 case AMDGPU::S_BUFFER_LOAD_DWORDX3_IMM_ec:
539 case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM_ec:
540 case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM_ec:
541 return S_BUFFER_LOAD_IMM;
542 case AMDGPU::S_BUFFER_LOAD_DWORD_SGPR_IMM:
543 case AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR_IMM:
544 case AMDGPU::S_BUFFER_LOAD_DWORDX3_SGPR_IMM:
545 case AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR_IMM:
546 case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR_IMM:
547 case AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR_IMM_ec:
548 case AMDGPU::S_BUFFER_LOAD_DWORDX3_SGPR_IMM_ec:
549 case AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR_IMM_ec:
550 case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR_IMM_ec:
551 return S_BUFFER_LOAD_SGPR_IMM;
552 case AMDGPU::S_LOAD_DWORD_IMM:
553 case AMDGPU::S_LOAD_DWORDX2_IMM:
554 case AMDGPU::S_LOAD_DWORDX3_IMM:
555 case AMDGPU::S_LOAD_DWORDX4_IMM:
556 case AMDGPU::S_LOAD_DWORDX8_IMM:
557 case AMDGPU::S_LOAD_DWORDX2_IMM_ec:
558 case AMDGPU::S_LOAD_DWORDX3_IMM_ec:
559 case AMDGPU::S_LOAD_DWORDX4_IMM_ec:
560 case AMDGPU::S_LOAD_DWORDX8_IMM_ec:
561 return S_LOAD_IMM;
562 case AMDGPU::DS_READ_B32:
563 case AMDGPU::DS_READ_B32_gfx9:
564 case AMDGPU::DS_READ_B64:
565 case AMDGPU::DS_READ_B64_gfx9:
566 return DS_READ;
567 case AMDGPU::DS_WRITE_B32:
568 case AMDGPU::DS_WRITE_B32_gfx9:
569 case AMDGPU::DS_WRITE_B64:
570 case AMDGPU::DS_WRITE_B64_gfx9:
571 return DS_WRITE;
572 case AMDGPU::GLOBAL_LOAD_DWORD:
573 case AMDGPU::GLOBAL_LOAD_DWORDX2:
574 case AMDGPU::GLOBAL_LOAD_DWORDX3:
575 case AMDGPU::GLOBAL_LOAD_DWORDX4:
576 case AMDGPU::FLAT_LOAD_DWORD:
577 case AMDGPU::FLAT_LOAD_DWORDX2:
578 case AMDGPU::FLAT_LOAD_DWORDX3:
579 case AMDGPU::FLAT_LOAD_DWORDX4:
580 return FLAT_LOAD;
581 case AMDGPU::GLOBAL_LOAD_DWORD_SADDR:
582 case AMDGPU::GLOBAL_LOAD_DWORDX2_SADDR:
583 case AMDGPU::GLOBAL_LOAD_DWORDX3_SADDR:
584 case AMDGPU::GLOBAL_LOAD_DWORDX4_SADDR:
585 return GLOBAL_LOAD_SADDR;
586 case AMDGPU::GLOBAL_STORE_DWORD:
587 case AMDGPU::GLOBAL_STORE_DWORDX2:
588 case AMDGPU::GLOBAL_STORE_DWORDX3:
589 case AMDGPU::GLOBAL_STORE_DWORDX4:
590 case AMDGPU::FLAT_STORE_DWORD:
591 case AMDGPU::FLAT_STORE_DWORDX2:
592 case AMDGPU::FLAT_STORE_DWORDX3:
593 case AMDGPU::FLAT_STORE_DWORDX4:
594 return FLAT_STORE;
595 case AMDGPU::GLOBAL_STORE_DWORD_SADDR:
596 case AMDGPU::GLOBAL_STORE_DWORDX2_SADDR:
597 case AMDGPU::GLOBAL_STORE_DWORDX3_SADDR:
598 case AMDGPU::GLOBAL_STORE_DWORDX4_SADDR:
599 return GLOBAL_STORE_SADDR;
600 case AMDGPU::FLAT_LOAD_DWORD_SADDR:
601 case AMDGPU::FLAT_LOAD_DWORDX2_SADDR:
602 case AMDGPU::FLAT_LOAD_DWORDX3_SADDR:
603 case AMDGPU::FLAT_LOAD_DWORDX4_SADDR:
604 return FLAT_LOAD_SADDR;
605 case AMDGPU::FLAT_STORE_DWORD_SADDR:
606 case AMDGPU::FLAT_STORE_DWORDX2_SADDR:
607 case AMDGPU::FLAT_STORE_DWORDX3_SADDR:
608 case AMDGPU::FLAT_STORE_DWORDX4_SADDR:
609 return FLAT_STORE_SADDR;
610 }
611}
612
613/// Determines instruction subclass from opcode. Only instructions
614/// of the same subclass can be merged together. The merged instruction may have
615/// a different subclass but must have the same class.
616static unsigned getInstSubclass(unsigned Opc, const SIInstrInfo &TII) {
617 switch (Opc) {
618 default:
619 if (TII.isMUBUF(Opc))
621 if (TII.isImage(Opc)) {
623 assert(Info);
624 return Info->BaseOpcode;
625 }
626 if (TII.isMTBUF(Opc))
628 return -1;
629 case AMDGPU::DS_READ_B32:
630 case AMDGPU::DS_READ_B32_gfx9:
631 case AMDGPU::DS_READ_B64:
632 case AMDGPU::DS_READ_B64_gfx9:
633 case AMDGPU::DS_WRITE_B32:
634 case AMDGPU::DS_WRITE_B32_gfx9:
635 case AMDGPU::DS_WRITE_B64:
636 case AMDGPU::DS_WRITE_B64_gfx9:
637 return Opc;
638 case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
639 case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
640 case AMDGPU::S_BUFFER_LOAD_DWORDX3_IMM:
641 case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
642 case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM:
643 case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM_ec:
644 case AMDGPU::S_BUFFER_LOAD_DWORDX3_IMM_ec:
645 case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM_ec:
646 case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM_ec:
647 return AMDGPU::S_BUFFER_LOAD_DWORD_IMM;
648 case AMDGPU::S_BUFFER_LOAD_DWORD_SGPR_IMM:
649 case AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR_IMM:
650 case AMDGPU::S_BUFFER_LOAD_DWORDX3_SGPR_IMM:
651 case AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR_IMM:
652 case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR_IMM:
653 case AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR_IMM_ec:
654 case AMDGPU::S_BUFFER_LOAD_DWORDX3_SGPR_IMM_ec:
655 case AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR_IMM_ec:
656 case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR_IMM_ec:
657 return AMDGPU::S_BUFFER_LOAD_DWORD_SGPR_IMM;
658 case AMDGPU::S_LOAD_DWORD_IMM:
659 case AMDGPU::S_LOAD_DWORDX2_IMM:
660 case AMDGPU::S_LOAD_DWORDX3_IMM:
661 case AMDGPU::S_LOAD_DWORDX4_IMM:
662 case AMDGPU::S_LOAD_DWORDX8_IMM:
663 case AMDGPU::S_LOAD_DWORDX2_IMM_ec:
664 case AMDGPU::S_LOAD_DWORDX3_IMM_ec:
665 case AMDGPU::S_LOAD_DWORDX4_IMM_ec:
666 case AMDGPU::S_LOAD_DWORDX8_IMM_ec:
667 return AMDGPU::S_LOAD_DWORD_IMM;
668 case AMDGPU::GLOBAL_LOAD_DWORD:
669 case AMDGPU::GLOBAL_LOAD_DWORDX2:
670 case AMDGPU::GLOBAL_LOAD_DWORDX3:
671 case AMDGPU::GLOBAL_LOAD_DWORDX4:
672 case AMDGPU::FLAT_LOAD_DWORD:
673 case AMDGPU::FLAT_LOAD_DWORDX2:
674 case AMDGPU::FLAT_LOAD_DWORDX3:
675 case AMDGPU::FLAT_LOAD_DWORDX4:
676 return AMDGPU::FLAT_LOAD_DWORD;
677 case AMDGPU::GLOBAL_LOAD_DWORD_SADDR:
678 case AMDGPU::GLOBAL_LOAD_DWORDX2_SADDR:
679 case AMDGPU::GLOBAL_LOAD_DWORDX3_SADDR:
680 case AMDGPU::GLOBAL_LOAD_DWORDX4_SADDR:
681 return AMDGPU::GLOBAL_LOAD_DWORD_SADDR;
682 case AMDGPU::GLOBAL_STORE_DWORD:
683 case AMDGPU::GLOBAL_STORE_DWORDX2:
684 case AMDGPU::GLOBAL_STORE_DWORDX3:
685 case AMDGPU::GLOBAL_STORE_DWORDX4:
686 case AMDGPU::FLAT_STORE_DWORD:
687 case AMDGPU::FLAT_STORE_DWORDX2:
688 case AMDGPU::FLAT_STORE_DWORDX3:
689 case AMDGPU::FLAT_STORE_DWORDX4:
690 return AMDGPU::FLAT_STORE_DWORD;
691 case AMDGPU::GLOBAL_STORE_DWORD_SADDR:
692 case AMDGPU::GLOBAL_STORE_DWORDX2_SADDR:
693 case AMDGPU::GLOBAL_STORE_DWORDX3_SADDR:
694 case AMDGPU::GLOBAL_STORE_DWORDX4_SADDR:
695 return AMDGPU::GLOBAL_STORE_DWORD_SADDR;
696 case AMDGPU::FLAT_LOAD_DWORD_SADDR:
697 case AMDGPU::FLAT_LOAD_DWORDX2_SADDR:
698 case AMDGPU::FLAT_LOAD_DWORDX3_SADDR:
699 case AMDGPU::FLAT_LOAD_DWORDX4_SADDR:
700 return AMDGPU::FLAT_LOAD_DWORD_SADDR;
701 case AMDGPU::FLAT_STORE_DWORD_SADDR:
702 case AMDGPU::FLAT_STORE_DWORDX2_SADDR:
703 case AMDGPU::FLAT_STORE_DWORDX3_SADDR:
704 case AMDGPU::FLAT_STORE_DWORDX4_SADDR:
705 return AMDGPU::FLAT_STORE_DWORD_SADDR;
706 }
707}
708
709// GLOBAL loads and stores are classified as FLAT initially. If both combined
710// instructions are FLAT GLOBAL adjust the class to GLOBAL_LOAD or GLOBAL_STORE.
711// If either or both instructions are non segment specific FLAT the resulting
712// combined operation will be FLAT, potentially promoting one of the GLOBAL
713// operations to FLAT.
714// For other instructions return the original unmodified class.
715InstClassEnum
716SILoadStoreOptimizer::getCommonInstClass(const CombineInfo &CI,
717 const CombineInfo &Paired) {
718 assert(CI.InstClass == Paired.InstClass);
719
720 if ((CI.InstClass == FLAT_LOAD || CI.InstClass == FLAT_STORE) &&
722 return (CI.InstClass == FLAT_STORE) ? GLOBAL_STORE : GLOBAL_LOAD;
723
724 return CI.InstClass;
725}
726
727static AddressRegs getRegs(unsigned Opc, const SIInstrInfo &TII) {
728 AddressRegs Result;
729
730 if (TII.isMUBUF(Opc)) {
732 Result.VAddr = true;
734 Result.SRsrc = true;
736 Result.SOffset = true;
737
738 return Result;
739 }
740
741 if (TII.isImage(Opc)) {
742 int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
743 if (VAddr0Idx >= 0) {
744 AMDGPU::OpName RsrcName =
745 TII.isMIMG(Opc) ? AMDGPU::OpName::srsrc : AMDGPU::OpName::rsrc;
746 int RsrcIdx = AMDGPU::getNamedOperandIdx(Opc, RsrcName);
747 Result.NumVAddrs = RsrcIdx - VAddr0Idx;
748 } else {
749 Result.VAddr = true;
750 }
751 Result.SRsrc = true;
753 if (Info && AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode)->Sampler)
754 Result.SSamp = true;
755
756 return Result;
757 }
758 if (TII.isMTBUF(Opc)) {
760 Result.VAddr = true;
762 Result.SRsrc = true;
764 Result.SOffset = true;
765
766 return Result;
767 }
768
769 switch (Opc) {
770 default:
771 return Result;
772 case AMDGPU::S_BUFFER_LOAD_DWORD_SGPR_IMM:
773 case AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR_IMM:
774 case AMDGPU::S_BUFFER_LOAD_DWORDX3_SGPR_IMM:
775 case AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR_IMM:
776 case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR_IMM:
777 case AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR_IMM_ec:
778 case AMDGPU::S_BUFFER_LOAD_DWORDX3_SGPR_IMM_ec:
779 case AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR_IMM_ec:
780 case AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR_IMM_ec:
781 Result.SOffset = true;
782 [[fallthrough]];
783 case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
784 case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
785 case AMDGPU::S_BUFFER_LOAD_DWORDX3_IMM:
786 case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
787 case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM:
788 case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM_ec:
789 case AMDGPU::S_BUFFER_LOAD_DWORDX3_IMM_ec:
790 case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM_ec:
791 case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM_ec:
792 case AMDGPU::S_LOAD_DWORD_IMM:
793 case AMDGPU::S_LOAD_DWORDX2_IMM:
794 case AMDGPU::S_LOAD_DWORDX3_IMM:
795 case AMDGPU::S_LOAD_DWORDX4_IMM:
796 case AMDGPU::S_LOAD_DWORDX8_IMM:
797 case AMDGPU::S_LOAD_DWORDX2_IMM_ec:
798 case AMDGPU::S_LOAD_DWORDX3_IMM_ec:
799 case AMDGPU::S_LOAD_DWORDX4_IMM_ec:
800 case AMDGPU::S_LOAD_DWORDX8_IMM_ec:
801 Result.SBase = true;
802 return Result;
803 case AMDGPU::DS_READ_B32:
804 case AMDGPU::DS_READ_B64:
805 case AMDGPU::DS_READ_B32_gfx9:
806 case AMDGPU::DS_READ_B64_gfx9:
807 case AMDGPU::DS_WRITE_B32:
808 case AMDGPU::DS_WRITE_B64:
809 case AMDGPU::DS_WRITE_B32_gfx9:
810 case AMDGPU::DS_WRITE_B64_gfx9:
811 Result.Addr = true;
812 return Result;
813 case AMDGPU::GLOBAL_LOAD_DWORD_SADDR:
814 case AMDGPU::GLOBAL_LOAD_DWORDX2_SADDR:
815 case AMDGPU::GLOBAL_LOAD_DWORDX3_SADDR:
816 case AMDGPU::GLOBAL_LOAD_DWORDX4_SADDR:
817 case AMDGPU::GLOBAL_STORE_DWORD_SADDR:
818 case AMDGPU::GLOBAL_STORE_DWORDX2_SADDR:
819 case AMDGPU::GLOBAL_STORE_DWORDX3_SADDR:
820 case AMDGPU::GLOBAL_STORE_DWORDX4_SADDR:
821 case AMDGPU::FLAT_LOAD_DWORD_SADDR:
822 case AMDGPU::FLAT_LOAD_DWORDX2_SADDR:
823 case AMDGPU::FLAT_LOAD_DWORDX3_SADDR:
824 case AMDGPU::FLAT_LOAD_DWORDX4_SADDR:
825 case AMDGPU::FLAT_STORE_DWORD_SADDR:
826 case AMDGPU::FLAT_STORE_DWORDX2_SADDR:
827 case AMDGPU::FLAT_STORE_DWORDX3_SADDR:
828 case AMDGPU::FLAT_STORE_DWORDX4_SADDR:
829 Result.SAddr = true;
830 [[fallthrough]];
831 case AMDGPU::GLOBAL_LOAD_DWORD:
832 case AMDGPU::GLOBAL_LOAD_DWORDX2:
833 case AMDGPU::GLOBAL_LOAD_DWORDX3:
834 case AMDGPU::GLOBAL_LOAD_DWORDX4:
835 case AMDGPU::GLOBAL_STORE_DWORD:
836 case AMDGPU::GLOBAL_STORE_DWORDX2:
837 case AMDGPU::GLOBAL_STORE_DWORDX3:
838 case AMDGPU::GLOBAL_STORE_DWORDX4:
839 case AMDGPU::FLAT_LOAD_DWORD:
840 case AMDGPU::FLAT_LOAD_DWORDX2:
841 case AMDGPU::FLAT_LOAD_DWORDX3:
842 case AMDGPU::FLAT_LOAD_DWORDX4:
843 case AMDGPU::FLAT_STORE_DWORD:
844 case AMDGPU::FLAT_STORE_DWORDX2:
845 case AMDGPU::FLAT_STORE_DWORDX3:
846 case AMDGPU::FLAT_STORE_DWORDX4:
847 Result.VAddr = true;
848 return Result;
849 }
850}
851
852void SILoadStoreOptimizer::CombineInfo::setMI(MachineBasicBlock::iterator MI,
853 const SILoadStoreOptimizer &LSO) {
854 I = MI;
855 unsigned Opc = MI->getOpcode();
856 InstClass = getInstClass(Opc, *LSO.TII);
857
858 if (InstClass == UNKNOWN)
859 return;
860
861 DataRC = LSO.getDataRegClass(*MI);
862
863 switch (InstClass) {
864 case DS_READ:
865 EltSize =
866 (Opc == AMDGPU::DS_READ_B64 || Opc == AMDGPU::DS_READ_B64_gfx9) ? 8
867 : 4;
868 break;
869 case DS_WRITE:
870 EltSize =
871 (Opc == AMDGPU::DS_WRITE_B64 || Opc == AMDGPU::DS_WRITE_B64_gfx9) ? 8
872 : 4;
873 break;
874 case S_BUFFER_LOAD_IMM:
875 case S_BUFFER_LOAD_SGPR_IMM:
876 case S_LOAD_IMM:
877 EltSize = AMDGPU::convertSMRDOffsetUnits(*LSO.STM, 4);
878 break;
879 default:
880 EltSize = 4;
881 break;
882 }
883
884 if (InstClass == MIMG) {
885 DMask = LSO.TII->getNamedOperand(*I, AMDGPU::OpName::dmask)->getImm();
886 // Offset is not considered for MIMG instructions.
887 Offset = 0;
888 } else {
889 int OffsetIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::offset);
890 Offset = I->getOperand(OffsetIdx).getImm();
891 }
892
893 if (InstClass == TBUFFER_LOAD || InstClass == TBUFFER_STORE) {
894 Format = LSO.TII->getNamedOperand(*I, AMDGPU::OpName::format)->getImm();
895 const AMDGPU::GcnBufferFormatInfo *Info =
896 AMDGPU::getGcnBufferFormatInfo(Format, *LSO.STM);
897 EltSize = Info->BitsPerComp / 8;
898 }
899
900 Width = getOpcodeWidth(*I, *LSO.TII);
901
902 if ((InstClass == DS_READ) || (InstClass == DS_WRITE)) {
903 Offset &= 0xffff;
904 GDS = LSO.TII->getNamedOperand(*I, AMDGPU::OpName::gds)->getImm();
905 } else if (InstClass != MIMG) {
906 CPol = LSO.TII->getNamedOperand(*I, AMDGPU::OpName::cpol)->getImm();
907 }
908
909 AddressRegs Regs = getRegs(Opc, *LSO.TII);
910 bool isVIMAGEorVSAMPLE = LSO.TII->isVIMAGE(*I) || LSO.TII->isVSAMPLE(*I);
911
912 NumAddresses = 0;
913 for (unsigned J = 0; J < Regs.NumVAddrs; J++)
914 AddrIdx[NumAddresses++] =
915 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0) + J;
916 if (Regs.Addr)
917 AddrIdx[NumAddresses++] =
918 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::addr);
919 if (Regs.SBase)
920 AddrIdx[NumAddresses++] =
921 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::sbase);
922 if (Regs.SRsrc)
923 AddrIdx[NumAddresses++] = AMDGPU::getNamedOperandIdx(
924 Opc, isVIMAGEorVSAMPLE ? AMDGPU::OpName::rsrc : AMDGPU::OpName::srsrc);
925 if (Regs.SOffset)
926 AddrIdx[NumAddresses++] =
927 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::soffset);
928 if (Regs.SAddr)
929 AddrIdx[NumAddresses++] =
930 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
931 if (Regs.VAddr)
932 AddrIdx[NumAddresses++] =
933 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
934 if (Regs.SSamp)
935 AddrIdx[NumAddresses++] = AMDGPU::getNamedOperandIdx(
936 Opc, isVIMAGEorVSAMPLE ? AMDGPU::OpName::samp : AMDGPU::OpName::ssamp);
937 assert(NumAddresses <= MaxAddressRegs);
938
939 for (unsigned J = 0; J < NumAddresses; J++)
940 AddrReg[J] = &I->getOperand(AddrIdx[J]);
941}
942
943} // end anonymous namespace.
944
945INITIALIZE_PASS_BEGIN(SILoadStoreOptimizerLegacy, DEBUG_TYPE,
946 "SI Load Store Optimizer", false, false)
948INITIALIZE_PASS_END(SILoadStoreOptimizerLegacy, DEBUG_TYPE,
949 "SI Load Store Optimizer", false, false)
950
951char SILoadStoreOptimizerLegacy::ID = 0;
952
953char &llvm::SILoadStoreOptimizerLegacyID = SILoadStoreOptimizerLegacy::ID;
954
956 DenseSet<Register> &RegDefs,
957 DenseSet<Register> &RegUses) {
958 for (const auto &Op : MI.operands()) {
959 if (!Op.isReg())
960 continue;
961 if (Op.isDef())
962 RegDefs.insert(Op.getReg());
963 if (Op.readsReg())
964 RegUses.insert(Op.getReg());
965 }
966}
967
968bool SILoadStoreOptimizer::canSwapInstructions(
969 const DenseSet<Register> &ARegDefs, const DenseSet<Register> &ARegUses,
970 const MachineInstr &A, const MachineInstr &B) const {
971 if (A.mayLoadOrStore() && B.mayLoadOrStore() &&
972 (A.mayStore() || B.mayStore()) && A.mayAlias(AA, B, true))
973 return false;
974 for (const auto &BOp : B.operands()) {
975 if (!BOp.isReg())
976 continue;
977 if ((BOp.isDef() || BOp.readsReg()) && ARegDefs.contains(BOp.getReg()))
978 return false;
979 if (BOp.isDef() && ARegUses.contains(BOp.getReg()))
980 return false;
981 }
982 return true;
983}
984
985// Given that \p CI and \p Paired are adjacent memory operations produce a new
986// MMO for the combined operation with a new access size.
987MachineMemOperand *
988SILoadStoreOptimizer::combineKnownAdjacentMMOs(const CombineInfo &CI,
989 const CombineInfo &Paired) {
990 const MachineMemOperand *MMOa = *CI.I->memoperands_begin();
991 const MachineMemOperand *MMOb = *Paired.I->memoperands_begin();
992
993 unsigned Size = MMOa->getSize().getValue() + MMOb->getSize().getValue();
994
995 // A base pointer for the combined operation is the same as the leading
996 // operation's pointer.
997 if (Paired < CI)
998 std::swap(MMOa, MMOb);
999
1000 MachinePointerInfo PtrInfo(MMOa->getPointerInfo());
1001 // If merging FLAT and GLOBAL set address space to FLAT.
1002 if (MMOb->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
1003 PtrInfo.AddrSpace = AMDGPUAS::FLAT_ADDRESS;
1004
1005 MachineFunction *MF = CI.I->getMF();
1006 return MF->getMachineMemOperand(MMOa, PtrInfo, Size);
1007}
1008
1009bool SILoadStoreOptimizer::dmasksCanBeCombined(const CombineInfo &CI,
1010 const SIInstrInfo &TII,
1011 const CombineInfo &Paired) {
1012 assert(CI.InstClass == MIMG);
1013
1014 // Ignore instructions with tfe/lwe set.
1015 const auto *TFEOp = TII.getNamedOperand(*CI.I, AMDGPU::OpName::tfe);
1016 const auto *LWEOp = TII.getNamedOperand(*CI.I, AMDGPU::OpName::lwe);
1017
1018 if ((TFEOp && TFEOp->getImm()) || (LWEOp && LWEOp->getImm()))
1019 return false;
1020
1021 // Check other optional immediate operands for equality.
1022 AMDGPU::OpName OperandsToMatch[] = {
1023 AMDGPU::OpName::cpol, AMDGPU::OpName::d16, AMDGPU::OpName::unorm,
1024 AMDGPU::OpName::da, AMDGPU::OpName::r128, AMDGPU::OpName::a16,
1025 AMDGPU::OpName::dim};
1026
1027 for (AMDGPU::OpName op : OperandsToMatch) {
1028 int Idx = AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), op);
1029 if (AMDGPU::getNamedOperandIdx(Paired.I->getOpcode(), op) != Idx)
1030 return false;
1031 if (Idx != -1 &&
1032 CI.I->getOperand(Idx).getImm() != Paired.I->getOperand(Idx).getImm())
1033 return false;
1034 }
1035
1036 // Check DMask for overlaps.
1037 unsigned MaxMask = std::max(CI.DMask, Paired.DMask);
1038 unsigned MinMask = std::min(CI.DMask, Paired.DMask);
1039
1040 if (!MaxMask)
1041 return false;
1042
1043 unsigned AllowedBitsForMin = llvm::countr_zero(MaxMask);
1044 if ((1u << AllowedBitsForMin) <= MinMask)
1045 return false;
1046
1047 return true;
1048}
1049
1050static unsigned getBufferFormatWithCompCount(unsigned OldFormat,
1051 unsigned ComponentCount,
1052 const GCNSubtarget &STI) {
1053 if (ComponentCount > 4)
1054 return 0;
1055
1056 const llvm::AMDGPU::GcnBufferFormatInfo *OldFormatInfo =
1058 if (!OldFormatInfo)
1059 return 0;
1060
1061 const llvm::AMDGPU::GcnBufferFormatInfo *NewFormatInfo =
1063 ComponentCount,
1064 OldFormatInfo->NumFormat, STI);
1065
1066 if (!NewFormatInfo)
1067 return 0;
1068
1069 assert(NewFormatInfo->NumFormat == OldFormatInfo->NumFormat &&
1070 NewFormatInfo->BitsPerComp == OldFormatInfo->BitsPerComp);
1071
1072 return NewFormatInfo->Format;
1073}
1074
1075// Return the value in the inclusive range [Lo,Hi] that is aligned to the
1076// highest power of two. Note that the result is well defined for all inputs
1077// including corner cases like:
1078// - if Lo == Hi, return that value
1079// - if Lo == 0, return 0 (even though the "- 1" below underflows
1080// - if Lo > Hi, return 0 (as if the range wrapped around)
1084
1085bool SILoadStoreOptimizer::offsetsCanBeCombined(CombineInfo &CI,
1086 const GCNSubtarget &STI,
1087 CombineInfo &Paired,
1088 bool Modify) {
1089 assert(CI.InstClass != MIMG);
1090
1091 // XXX - Would the same offset be OK? Is there any reason this would happen or
1092 // be useful?
1093 if (CI.Offset == Paired.Offset)
1094 return false;
1095
1096 if (CI.GDS != Paired.GDS)
1097 return false;
1098
1099 // This won't be valid if the offset isn't aligned.
1100 if ((CI.Offset % CI.EltSize != 0) || (Paired.Offset % CI.EltSize != 0))
1101 return false;
1102
1103 if (CI.InstClass == TBUFFER_LOAD || CI.InstClass == TBUFFER_STORE) {
1104
1105 const llvm::AMDGPU::GcnBufferFormatInfo *Info0 =
1107 const llvm::AMDGPU::GcnBufferFormatInfo *Info1 =
1108 llvm::AMDGPU::getGcnBufferFormatInfo(Paired.Format, STI);
1109
1110 if (Info0->BitsPerComp != Info1->BitsPerComp ||
1111 Info0->NumFormat != Info1->NumFormat)
1112 return false;
1113
1114 // For 8-bit or 16-bit formats there is no 3-component variant.
1115 // If NumCombinedComponents is 3, try the 4-component format and use XYZ.
1116 // Example:
1117 // tbuffer_load_format_x + tbuffer_load_format_x + tbuffer_load_format_x
1118 // ==> tbuffer_load_format_xyz with format:[BUF_FMT_16_16_16_16_SNORM]
1119 unsigned NumCombinedComponents = CI.Width + Paired.Width;
1120 if (NumCombinedComponents == 3 && CI.EltSize <= 2)
1121 NumCombinedComponents = 4;
1122
1123 if (getBufferFormatWithCompCount(CI.Format, NumCombinedComponents, STI) ==
1124 0)
1125 return false;
1126
1127 // Merge only when the two access ranges are strictly back-to-back,
1128 // any gap or overlap can over-write data or leave holes.
1129 unsigned ElemIndex0 = CI.Offset / CI.EltSize;
1130 unsigned ElemIndex1 = Paired.Offset / Paired.EltSize;
1131 if (ElemIndex0 + CI.Width != ElemIndex1 &&
1132 ElemIndex1 + Paired.Width != ElemIndex0)
1133 return false;
1134
1135 // 1-byte formats require 1-byte alignment.
1136 // 2-byte formats require 2-byte alignment.
1137 // 4-byte and larger formats require 4-byte alignment.
1138 unsigned MergedBytes = CI.EltSize * NumCombinedComponents;
1139 Align RequiredAlign(std::min(MergedBytes, 4u));
1140
1141 // The merged access starts at the address of the leading access. The
1142 // leading access must already satisfy the rule above for its own size, so
1143 // its address is aligned to at least the component size.
1144 const CombineInfo &Leading = Paired < CI ? Paired : CI;
1145 Align KnownAlign =
1146 std::max(getSingleElement(Leading.I->memoperands())->getAlign(),
1147 Align(std::min(CI.EltSize, 4u)));
1148 return KnownAlign >= RequiredAlign;
1149 }
1150
1151 uint32_t EltOffset0 = CI.Offset / CI.EltSize;
1152 uint32_t EltOffset1 = Paired.Offset / CI.EltSize;
1153 CI.UseST64 = false;
1154 CI.BaseOff = 0;
1155
1156 // Handle all non-DS instructions.
1157 if ((CI.InstClass != DS_READ) && (CI.InstClass != DS_WRITE)) {
1158 if (EltOffset0 + CI.Width != EltOffset1 &&
1159 EltOffset1 + Paired.Width != EltOffset0)
1160 return false;
1161 // Instructions with scale_offset modifier cannot be combined unless we
1162 // also generate a code to scale the offset and reset that bit.
1163 if (CI.CPol != Paired.CPol || (CI.CPol & AMDGPU::CPol::SCAL))
1164 return false;
1165 if (CI.InstClass == S_LOAD_IMM || CI.InstClass == S_BUFFER_LOAD_IMM ||
1166 CI.InstClass == S_BUFFER_LOAD_SGPR_IMM) {
1167 // Reject cases like:
1168 // dword + dwordx2 -> dwordx3
1169 // dword + dwordx3 -> dwordx4
1170 // If we tried to combine these cases, we would fail to extract a subreg
1171 // for the result of the second load due to SGPR alignment requirements.
1172 if (CI.Width != Paired.Width &&
1173 (CI.Width < Paired.Width) == (CI.Offset < Paired.Offset))
1174 return false;
1175 }
1176 return true;
1177 }
1178
1179 // If the offset in elements doesn't fit in 8-bits, we might be able to use
1180 // the stride 64 versions.
1181 if ((EltOffset0 % 64 == 0) && (EltOffset1 % 64) == 0 &&
1182 isUInt<8>(EltOffset0 / 64) && isUInt<8>(EltOffset1 / 64)) {
1183 if (Modify) {
1184 CI.Offset = EltOffset0 / 64;
1185 Paired.Offset = EltOffset1 / 64;
1186 CI.UseST64 = true;
1187 }
1188 return true;
1189 }
1190
1191 // Check if the new offsets fit in the reduced 8-bit range.
1192 if (isUInt<8>(EltOffset0) && isUInt<8>(EltOffset1)) {
1193 if (Modify) {
1194 CI.Offset = EltOffset0;
1195 Paired.Offset = EltOffset1;
1196 }
1197 return true;
1198 }
1199
1200 // Try to shift base address to decrease offsets.
1201 uint32_t Min = std::min(EltOffset0, EltOffset1);
1202 uint32_t Max = std::max(EltOffset0, EltOffset1);
1203
1204 const uint32_t Mask = maskTrailingOnes<uint32_t>(8) * 64;
1205 if (((Max - Min) & ~Mask) == 0) {
1206 if (Modify) {
1207 // From the range of values we could use for BaseOff, choose the one that
1208 // is aligned to the highest power of two, to maximise the chance that
1209 // the same offset can be reused for other load/store pairs.
1210 uint32_t BaseOff = mostAlignedValueInRange(Max - 0xff * 64, Min);
1211 // Copy the low bits of the offsets, so that when we adjust them by
1212 // subtracting BaseOff they will be multiples of 64.
1213 BaseOff |= Min & maskTrailingOnes<uint32_t>(6);
1214 CI.BaseOff = BaseOff * CI.EltSize;
1215 CI.Offset = (EltOffset0 - BaseOff) / 64;
1216 Paired.Offset = (EltOffset1 - BaseOff) / 64;
1217 CI.UseST64 = true;
1218 }
1219 return true;
1220 }
1221
1222 if (isUInt<8>(Max - Min)) {
1223 if (Modify) {
1224 // From the range of values we could use for BaseOff, choose the one that
1225 // is aligned to the highest power of two, to maximise the chance that
1226 // the same offset can be reused for other load/store pairs.
1227 uint32_t BaseOff = mostAlignedValueInRange(Max - 0xff, Min);
1228 CI.BaseOff = BaseOff * CI.EltSize;
1229 CI.Offset = EltOffset0 - BaseOff;
1230 Paired.Offset = EltOffset1 - BaseOff;
1231 }
1232 return true;
1233 }
1234
1235 return false;
1236}
1237
1238bool SILoadStoreOptimizer::widthsFit(const GCNSubtarget &STM,
1239 const CombineInfo &CI,
1240 const CombineInfo &Paired) {
1241 const unsigned Width = (CI.Width + Paired.Width);
1242 switch (CI.InstClass) {
1243 default:
1244 return (Width <= 4) && (STM.hasDwordx3LoadStores() || (Width != 3));
1245 case S_BUFFER_LOAD_IMM:
1246 case S_BUFFER_LOAD_SGPR_IMM:
1247 case S_LOAD_IMM:
1248 switch (Width) {
1249 default:
1250 return false;
1251 case 2:
1252 case 4:
1253 case 8:
1254 return true;
1255 case 3:
1256 return STM.hasScalarDwordx3Loads();
1257 }
1258 }
1259}
1260
1261const TargetRegisterClass *
1262SILoadStoreOptimizer::getDataRegClass(const MachineInstr &MI) const {
1263 if (const auto *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst)) {
1264 return TRI->getRegClassForReg(*MRI, Dst->getReg());
1265 }
1266 if (const auto *Src = TII->getNamedOperand(MI, AMDGPU::OpName::vdata)) {
1267 return TRI->getRegClassForReg(*MRI, Src->getReg());
1268 }
1269 if (const auto *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) {
1270 return TRI->getRegClassForReg(*MRI, Src->getReg());
1271 }
1272 if (const auto *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::sdst)) {
1273 return TRI->getRegClassForReg(*MRI, Dst->getReg());
1274 }
1275 if (const auto *Src = TII->getNamedOperand(MI, AMDGPU::OpName::sdata)) {
1276 return TRI->getRegClassForReg(*MRI, Src->getReg());
1277 }
1278 return nullptr;
1279}
1280
1281/// This function assumes that CI comes before Paired in a basic block. Return
1282/// an insertion point for the merged instruction or nullptr on failure.
1283SILoadStoreOptimizer::CombineInfo *
1284SILoadStoreOptimizer::checkAndPrepareMerge(CombineInfo &CI,
1285 CombineInfo &Paired) {
1286 // If another instruction has already been merged into CI, it may now be a
1287 // type that we can't do any further merging into.
1288 if (CI.InstClass == UNKNOWN || Paired.InstClass == UNKNOWN)
1289 return nullptr;
1290 assert(CI.InstClass == Paired.InstClass);
1291
1292 if (getInstSubclass(CI.I->getOpcode(), *TII) !=
1293 getInstSubclass(Paired.I->getOpcode(), *TII))
1294 return nullptr;
1295
1296 // Check both offsets (or masks for MIMG) can be combined and fit in the
1297 // reduced range.
1298 if (CI.InstClass == MIMG) {
1299 if (!dmasksCanBeCombined(CI, *TII, Paired))
1300 return nullptr;
1301 } else {
1302 if (!widthsFit(*STM, CI, Paired) || !offsetsCanBeCombined(CI, *STM, Paired))
1303 return nullptr;
1304 }
1305
1306 DenseSet<Register> RegDefs;
1307 DenseSet<Register> RegUses;
1308 CombineInfo *Where;
1309 if (CI.I->mayLoad()) {
1310 // Try to hoist Paired up to CI.
1311 addDefsUsesToList(*Paired.I, RegDefs, RegUses);
1312 for (MachineBasicBlock::iterator MBBI = Paired.I; --MBBI != CI.I;) {
1313 if (!canSwapInstructions(RegDefs, RegUses, *Paired.I, *MBBI))
1314 return nullptr;
1315 }
1316 Where = &CI;
1317 } else {
1318 // Try to sink CI down to Paired.
1319 addDefsUsesToList(*CI.I, RegDefs, RegUses);
1320 for (MachineBasicBlock::iterator MBBI = CI.I; ++MBBI != Paired.I;) {
1321 if (!canSwapInstructions(RegDefs, RegUses, *CI.I, *MBBI))
1322 return nullptr;
1323 }
1324 Where = &Paired;
1325 }
1326
1327 // Call offsetsCanBeCombined with modify = true so that the offsets are
1328 // correct for the new instruction. This should return true, because
1329 // this function should only be called on CombineInfo objects that
1330 // have already been confirmed to be mergeable.
1331 if (CI.InstClass == DS_READ || CI.InstClass == DS_WRITE) {
1332 if (STM->hasNeedsAligned2addrDS() &&
1333 (CI.I->memoperands_empty() ||
1334 (*CI.I->memoperands_begin())->getAlign().value() < CI.Width * 4))
1335 return nullptr;
1336 offsetsCanBeCombined(CI, *STM, Paired, true);
1337 }
1338
1339 if (CI.InstClass == DS_WRITE) {
1340 // Both data operands must be AGPR or VGPR, so the data registers needs to
1341 // be constrained to one or the other. We expect to only emit the VGPR form
1342 // here for now.
1343 //
1344 // FIXME: There is currently a hack in getRegClass to report that the write2
1345 // operands are VGPRs. In the future we should have separate agpr
1346 // instruction definitions.
1347 const MachineOperand *Data0 =
1348 TII->getNamedOperand(*CI.I, AMDGPU::OpName::data0);
1349 const MachineOperand *Data1 =
1350 TII->getNamedOperand(*Paired.I, AMDGPU::OpName::data0);
1351
1352 const MCInstrDesc &Write2Opc = TII->get(getWrite2Opcode(CI));
1353 int Data0Idx = AMDGPU::getNamedOperandIdx(Write2Opc.getOpcode(),
1354 AMDGPU::OpName::data0);
1355 int Data1Idx = AMDGPU::getNamedOperandIdx(Write2Opc.getOpcode(),
1356 AMDGPU::OpName::data1);
1357
1358 const TargetRegisterClass *DataRC0 = TII->getRegClass(Write2Opc, Data0Idx);
1359
1360 const TargetRegisterClass *DataRC1 = TII->getRegClass(Write2Opc, Data1Idx);
1361
1362 if (unsigned SubReg = Data0->getSubReg()) {
1363 DataRC0 = TRI->getMatchingSuperRegClass(MRI->getRegClass(Data0->getReg()),
1364 DataRC0, SubReg);
1365 }
1366
1367 if (unsigned SubReg = Data1->getSubReg()) {
1368 DataRC1 = TRI->getMatchingSuperRegClass(MRI->getRegClass(Data1->getReg()),
1369 DataRC1, SubReg);
1370 }
1371
1372 if (!MRI->constrainRegClass(Data0->getReg(), DataRC0) ||
1373 !MRI->constrainRegClass(Data1->getReg(), DataRC1))
1374 return nullptr;
1375
1376 // TODO: If one register can be constrained, and not the other, insert a
1377 // copy.
1378 }
1379
1380 return Where;
1381}
1382
1383// Copy the merged load result from DestReg to the original dest regs of CI and
1384// Paired.
1385void SILoadStoreOptimizer::copyToDestRegs(
1386 CombineInfo &CI, CombineInfo &Paired,
1387 MachineBasicBlock::iterator InsertBefore, const DebugLoc &DL,
1388 AMDGPU::OpName OpName, Register DestReg) const {
1389 MachineBasicBlock *MBB = CI.I->getParent();
1390
1391 auto [SubRegIdx0, SubRegIdx1] = getSubRegIdxs(CI, Paired);
1392
1393 // Copy to the old destination registers.
1394 const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
1395 auto *Dest0 = TII->getNamedOperand(*CI.I, OpName);
1396 auto *Dest1 = TII->getNamedOperand(*Paired.I, OpName);
1397
1398 // The constrained sload instructions in S_LOAD_IMM class will have
1399 // `early-clobber` flag in the dst operand. Remove the flag before using the
1400 // MOs in copies.
1401 Dest0->setIsEarlyClobber(false);
1402 Dest1->setIsEarlyClobber(false);
1403
1404 BuildMI(*MBB, InsertBefore, DL, CopyDesc)
1405 .add(*Dest0) // Copy to same destination including flags and sub reg.
1406 .addReg(DestReg, {}, SubRegIdx0);
1407 BuildMI(*MBB, InsertBefore, DL, CopyDesc)
1408 .add(*Dest1)
1409 .addReg(DestReg, {}, SubRegIdx1);
1410}
1411
1412// Return a register for the source of the merged store after copying the
1413// original source regs of CI and Paired into it.
1415SILoadStoreOptimizer::copyFromSrcRegs(CombineInfo &CI, CombineInfo &Paired,
1416 MachineBasicBlock::iterator InsertBefore,
1417 const DebugLoc &DL,
1418 AMDGPU::OpName OpName) const {
1419 MachineBasicBlock *MBB = CI.I->getParent();
1420
1421 auto [SubRegIdx0, SubRegIdx1] = getSubRegIdxs(CI, Paired);
1422
1423 // Copy to the new source register.
1424 const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1425 Register SrcReg = MRI->createVirtualRegister(SuperRC);
1426
1427 const auto *Src0 = TII->getNamedOperand(*CI.I, OpName);
1428 const auto *Src1 = TII->getNamedOperand(*Paired.I, OpName);
1429
1430 BuildMI(*MBB, InsertBefore, DL, TII->get(AMDGPU::REG_SEQUENCE), SrcReg)
1431 .add(*Src0)
1432 .addImm(SubRegIdx0)
1433 .add(*Src1)
1434 .addImm(SubRegIdx1);
1435
1436 return SrcReg;
1437}
1438
1439unsigned SILoadStoreOptimizer::read2Opcode(unsigned EltSize, bool GDS) const {
1440 if (GDS || STM->ldsRequiresM0Init())
1441 return (EltSize == 4) ? AMDGPU::DS_READ2_B32 : AMDGPU::DS_READ2_B64;
1442 return (EltSize == 4) ? AMDGPU::DS_READ2_B32_gfx9 : AMDGPU::DS_READ2_B64_gfx9;
1443}
1444
1445unsigned SILoadStoreOptimizer::read2ST64Opcode(unsigned EltSize,
1446 bool GDS) const {
1447 if (GDS || STM->ldsRequiresM0Init())
1448 return (EltSize == 4) ? AMDGPU::DS_READ2ST64_B32 : AMDGPU::DS_READ2ST64_B64;
1449
1450 return (EltSize == 4) ? AMDGPU::DS_READ2ST64_B32_gfx9
1451 : AMDGPU::DS_READ2ST64_B64_gfx9;
1452}
1453
1455SILoadStoreOptimizer::mergeRead2Pair(CombineInfo &CI, CombineInfo &Paired,
1456 MachineBasicBlock::iterator InsertBefore) {
1457 MachineBasicBlock *MBB = CI.I->getParent();
1458
1459 // Be careful, since the addresses could be subregisters themselves in weird
1460 // cases, like vectors of pointers.
1461 const auto *AddrReg = TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr);
1462
1463 unsigned NewOffset0 = std::min(CI.Offset, Paired.Offset);
1464 unsigned NewOffset1 = std::max(CI.Offset, Paired.Offset);
1465 unsigned Opc = CI.UseST64 ? read2ST64Opcode(CI.EltSize, CI.GDS)
1466 : read2Opcode(CI.EltSize, CI.GDS);
1467
1468 assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
1469 (NewOffset0 != NewOffset1) && "Computed offset doesn't fit");
1470
1471 const MCInstrDesc &Read2Desc = TII->get(Opc);
1472
1473 const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1474 Register DestReg = MRI->createVirtualRegister(SuperRC);
1475
1476 DebugLoc DL =
1477 DebugLoc::getMergedLocation(CI.I->getDebugLoc(), Paired.I->getDebugLoc());
1478
1479 Register BaseReg = AddrReg->getReg();
1480 unsigned BaseSubReg = AddrReg->getSubReg();
1481 if (CI.BaseOff) {
1482 Register ImmReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1483 BuildMI(*MBB, InsertBefore, DL, TII->get(AMDGPU::S_MOV_B32), ImmReg)
1484 .addImm(CI.BaseOff);
1485
1486 BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1487
1488 TII->getAddNoCarry(*MBB, InsertBefore, DL, BaseReg)
1489 .addReg(ImmReg)
1490 .addReg(AddrReg->getReg(), {}, BaseSubReg)
1491 .addImm(0); // clamp bit
1492 BaseSubReg = 0;
1493 }
1494
1495 MachineInstrBuilder Read2 =
1496 BuildMI(*MBB, InsertBefore, DL, Read2Desc, DestReg)
1497 .addReg(BaseReg, {}, BaseSubReg) // addr
1498 .addImm(NewOffset0) // offset0
1499 .addImm(NewOffset1) // offset1
1500 .addImm(CI.GDS) // gds
1501 .cloneMergedMemRefs({&*CI.I, &*Paired.I});
1502
1503 copyToDestRegs(CI, Paired, InsertBefore, DL, AMDGPU::OpName::vdst, DestReg);
1504
1505 CI.I->eraseFromParent();
1506 Paired.I->eraseFromParent();
1507
1508 LLVM_DEBUG(dbgs() << "Inserted read2: " << *Read2 << '\n');
1509 return Read2;
1510}
1511
1512unsigned SILoadStoreOptimizer::write2Opcode(unsigned EltSize, bool GDS) const {
1513 if (GDS || STM->ldsRequiresM0Init())
1514 return (EltSize == 4) ? AMDGPU::DS_WRITE2_B32 : AMDGPU::DS_WRITE2_B64;
1515 return (EltSize == 4) ? AMDGPU::DS_WRITE2_B32_gfx9
1516 : AMDGPU::DS_WRITE2_B64_gfx9;
1517}
1518
1519unsigned SILoadStoreOptimizer::write2ST64Opcode(unsigned EltSize,
1520 bool GDS) const {
1521 if (GDS || STM->ldsRequiresM0Init())
1522 return (EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32
1523 : AMDGPU::DS_WRITE2ST64_B64;
1524
1525 return (EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32_gfx9
1526 : AMDGPU::DS_WRITE2ST64_B64_gfx9;
1527}
1528
1529unsigned SILoadStoreOptimizer::getWrite2Opcode(const CombineInfo &CI) const {
1530 return CI.UseST64 ? write2ST64Opcode(CI.EltSize, CI.GDS)
1531 : write2Opcode(CI.EltSize, CI.GDS);
1532}
1533
1534MachineBasicBlock::iterator SILoadStoreOptimizer::mergeWrite2Pair(
1535 CombineInfo &CI, CombineInfo &Paired,
1536 MachineBasicBlock::iterator InsertBefore) {
1537 MachineBasicBlock *MBB = CI.I->getParent();
1538
1539 // Be sure to use .addOperand(), and not .addReg() with these. We want to be
1540 // sure we preserve the subregister index and any register flags set on them.
1541 const MachineOperand *AddrReg =
1542 TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr);
1543 const MachineOperand *Data0 =
1544 TII->getNamedOperand(*CI.I, AMDGPU::OpName::data0);
1545 const MachineOperand *Data1 =
1546 TII->getNamedOperand(*Paired.I, AMDGPU::OpName::data0);
1547
1548 unsigned NewOffset0 = CI.Offset;
1549 unsigned NewOffset1 = Paired.Offset;
1550 unsigned Opc = getWrite2Opcode(CI);
1551
1552 if (NewOffset0 > NewOffset1) {
1553 // Canonicalize the merged instruction so the smaller offset comes first.
1554 std::swap(NewOffset0, NewOffset1);
1555 std::swap(Data0, Data1);
1556 }
1557
1558 assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
1559 (NewOffset0 != NewOffset1) && "Computed offset doesn't fit");
1560
1561 const MCInstrDesc &Write2Desc = TII->get(Opc);
1562 DebugLoc DL =
1563 DebugLoc::getMergedLocation(CI.I->getDebugLoc(), Paired.I->getDebugLoc());
1564
1565 Register BaseReg = AddrReg->getReg();
1566 unsigned BaseSubReg = AddrReg->getSubReg();
1567 if (CI.BaseOff) {
1568 Register ImmReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1569 BuildMI(*MBB, InsertBefore, DL, TII->get(AMDGPU::S_MOV_B32), ImmReg)
1570 .addImm(CI.BaseOff);
1571
1572 BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1573
1574 TII->getAddNoCarry(*MBB, InsertBefore, DL, BaseReg)
1575 .addReg(ImmReg)
1576 .addReg(AddrReg->getReg(), {}, BaseSubReg)
1577 .addImm(0); // clamp bit
1578 BaseSubReg = 0;
1579 }
1580
1581 MachineInstrBuilder Write2 = BuildMI(*MBB, InsertBefore, DL, Write2Desc)
1582 .addReg(BaseReg, {}, BaseSubReg) // addr
1583 .add(*Data0) // data0
1584 .add(*Data1) // data1
1585 .addImm(NewOffset0) // offset0
1586 .addImm(NewOffset1) // offset1
1587 .addImm(CI.GDS) // gds
1588 .cloneMergedMemRefs({&*CI.I, &*Paired.I});
1589
1590 CI.I->eraseFromParent();
1591 Paired.I->eraseFromParent();
1592
1593 LLVM_DEBUG(dbgs() << "Inserted write2 inst: " << *Write2 << '\n');
1594 return Write2;
1595}
1596
1598SILoadStoreOptimizer::mergeImagePair(CombineInfo &CI, CombineInfo &Paired,
1599 MachineBasicBlock::iterator InsertBefore) {
1600 MachineBasicBlock *MBB = CI.I->getParent();
1601 DebugLoc DL =
1602 DebugLoc::getMergedLocation(CI.I->getDebugLoc(), Paired.I->getDebugLoc());
1603
1604 const unsigned Opcode = getNewOpcode(CI, Paired);
1605
1606 const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1607
1608 Register DestReg = MRI->createVirtualRegister(SuperRC);
1609 unsigned MergedDMask = CI.DMask | Paired.DMask;
1610 unsigned DMaskIdx =
1611 AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), AMDGPU::OpName::dmask);
1612
1613 auto MIB = BuildMI(*MBB, InsertBefore, DL, TII->get(Opcode), DestReg);
1614 for (unsigned I = 1, E = (*CI.I).getNumOperands(); I != E; ++I) {
1615 if (I == DMaskIdx)
1616 MIB.addImm(MergedDMask);
1617 else
1618 MIB.add((*CI.I).getOperand(I));
1619 }
1620
1621 // It shouldn't be possible to get this far if the two instructions
1622 // don't have a single memoperand, because MachineInstr::mayAlias()
1623 // will return true if this is the case.
1624 assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1625
1626 MachineInstr *New = MIB.addMemOperand(combineKnownAdjacentMMOs(CI, Paired));
1627
1628 copyToDestRegs(CI, Paired, InsertBefore, DL, AMDGPU::OpName::vdata, DestReg);
1629
1630 CI.I->eraseFromParent();
1631 Paired.I->eraseFromParent();
1632 return New;
1633}
1634
1635MachineBasicBlock::iterator SILoadStoreOptimizer::mergeSMemLoadImmPair(
1636 CombineInfo &CI, CombineInfo &Paired,
1637 MachineBasicBlock::iterator InsertBefore) {
1638 MachineBasicBlock *MBB = CI.I->getParent();
1639 DebugLoc DL =
1640 DebugLoc::getMergedLocation(CI.I->getDebugLoc(), Paired.I->getDebugLoc());
1641
1642 const unsigned Opcode = getNewOpcode(CI, Paired);
1643
1644 const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1645
1646 Register DestReg = MRI->createVirtualRegister(SuperRC);
1647 unsigned MergedOffset = std::min(CI.Offset, Paired.Offset);
1648
1649 // It shouldn't be possible to get this far if the two instructions
1650 // don't have a single memoperand, because MachineInstr::mayAlias()
1651 // will return true if this is the case.
1652 assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1653
1654 MachineInstrBuilder New =
1655 BuildMI(*MBB, InsertBefore, DL, TII->get(Opcode), DestReg)
1656 .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::sbase));
1657 if (CI.InstClass == S_BUFFER_LOAD_SGPR_IMM)
1658 New.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset));
1659 New.addImm(MergedOffset);
1660 New.addImm(CI.CPol).addMemOperand(combineKnownAdjacentMMOs(CI, Paired));
1661
1662 copyToDestRegs(CI, Paired, InsertBefore, DL, AMDGPU::OpName::sdst, DestReg);
1663
1664 CI.I->eraseFromParent();
1665 Paired.I->eraseFromParent();
1666 return New;
1667}
1668
1669MachineBasicBlock::iterator SILoadStoreOptimizer::mergeBufferLoadPair(
1670 CombineInfo &CI, CombineInfo &Paired,
1671 MachineBasicBlock::iterator InsertBefore) {
1672 MachineBasicBlock *MBB = CI.I->getParent();
1673
1674 DebugLoc DL =
1675 DebugLoc::getMergedLocation(CI.I->getDebugLoc(), Paired.I->getDebugLoc());
1676
1677 const unsigned Opcode = getNewOpcode(CI, Paired);
1678
1679 const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1680
1681 // Copy to the new source register.
1682 Register DestReg = MRI->createVirtualRegister(SuperRC);
1683 unsigned MergedOffset = std::min(CI.Offset, Paired.Offset);
1684
1685 auto MIB = BuildMI(*MBB, InsertBefore, DL, TII->get(Opcode), DestReg);
1686
1687 AddressRegs Regs = getRegs(Opcode, *TII);
1688
1689 if (Regs.VAddr)
1690 MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1691
1692 // It shouldn't be possible to get this far if the two instructions
1693 // don't have a single memoperand, because MachineInstr::mayAlias()
1694 // will return true if this is the case.
1695 assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1696
1697 MachineInstr *New =
1698 MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1699 .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1700 .addImm(MergedOffset) // offset
1701 .addImm(CI.CPol) // cpol
1702 .addImm(0) // swz
1703 .addMemOperand(combineKnownAdjacentMMOs(CI, Paired));
1704
1705 copyToDestRegs(CI, Paired, InsertBefore, DL, AMDGPU::OpName::vdata, DestReg);
1706
1707 CI.I->eraseFromParent();
1708 Paired.I->eraseFromParent();
1709 return New;
1710}
1711
1712MachineBasicBlock::iterator SILoadStoreOptimizer::mergeTBufferLoadPair(
1713 CombineInfo &CI, CombineInfo &Paired,
1714 MachineBasicBlock::iterator InsertBefore) {
1715 MachineBasicBlock *MBB = CI.I->getParent();
1716
1717 DebugLoc DL =
1718 DebugLoc::getMergedLocation(CI.I->getDebugLoc(), Paired.I->getDebugLoc());
1719
1720 const unsigned Opcode = getNewOpcode(CI, Paired);
1721
1722 const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1723
1724 // Copy to the new source register.
1725 Register DestReg = MRI->createVirtualRegister(SuperRC);
1726 unsigned MergedOffset = std::min(CI.Offset, Paired.Offset);
1727
1728 auto MIB = BuildMI(*MBB, InsertBefore, DL, TII->get(Opcode), DestReg);
1729
1730 AddressRegs Regs = getRegs(Opcode, *TII);
1731
1732 if (Regs.VAddr)
1733 MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1734
1735 // For 8-bit or 16-bit tbuffer formats there is no 3-component encoding.
1736 // If the combined count is 3 (e.g. X+X+X or XY+X), promote to 4 components
1737 // and use XYZ of XYZW to enable the merge.
1738 unsigned NumCombinedComponents = CI.Width + Paired.Width;
1739 if (NumCombinedComponents == 3 && CI.EltSize <= 2)
1740 NumCombinedComponents = 4;
1741 unsigned JoinedFormat =
1742 getBufferFormatWithCompCount(CI.Format, NumCombinedComponents, *STM);
1743
1744 // It shouldn't be possible to get this far if the two instructions
1745 // don't have a single memoperand, because MachineInstr::mayAlias()
1746 // will return true if this is the case.
1747 assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1748
1749 MachineInstr *New =
1750 MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1751 .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1752 .addImm(MergedOffset) // offset
1753 .addImm(JoinedFormat) // format
1754 .addImm(CI.CPol) // cpol
1755 .addImm(0) // swz
1756 .addMemOperand(combineKnownAdjacentMMOs(CI, Paired));
1757
1758 copyToDestRegs(CI, Paired, InsertBefore, DL, AMDGPU::OpName::vdata, DestReg);
1759
1760 CI.I->eraseFromParent();
1761 Paired.I->eraseFromParent();
1762 return New;
1763}
1764
1765MachineBasicBlock::iterator SILoadStoreOptimizer::mergeTBufferStorePair(
1766 CombineInfo &CI, CombineInfo &Paired,
1767 MachineBasicBlock::iterator InsertBefore) {
1768 MachineBasicBlock *MBB = CI.I->getParent();
1769 DebugLoc DL =
1770 DebugLoc::getMergedLocation(CI.I->getDebugLoc(), Paired.I->getDebugLoc());
1771
1772 const unsigned Opcode = getNewOpcode(CI, Paired);
1773
1774 Register SrcReg =
1775 copyFromSrcRegs(CI, Paired, InsertBefore, DL, AMDGPU::OpName::vdata);
1776
1777 auto MIB = BuildMI(*MBB, InsertBefore, DL, TII->get(Opcode)).addReg(SrcReg);
1778
1779 AddressRegs Regs = getRegs(Opcode, *TII);
1780
1781 if (Regs.VAddr)
1782 MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
1783
1784 // For 8-bit or 16-bit tbuffer formats there is no 3-component encoding.
1785 // If the combined count is 3 (e.g. X+X+X or XY+X), promote to 4 components
1786 // and use XYZ of XYZW to enable the merge.
1787 unsigned NumCombinedComponents = CI.Width + Paired.Width;
1788 if (NumCombinedComponents == 3 && CI.EltSize <= 2)
1789 NumCombinedComponents = 4;
1790 unsigned JoinedFormat =
1791 getBufferFormatWithCompCount(CI.Format, NumCombinedComponents, *STM);
1792
1793 // It shouldn't be possible to get this far if the two instructions
1794 // don't have a single memoperand, because MachineInstr::mayAlias()
1795 // will return true if this is the case.
1796 assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
1797
1798 MachineInstr *New =
1799 MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
1800 .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
1801 .addImm(std::min(CI.Offset, Paired.Offset)) // offset
1802 .addImm(JoinedFormat) // format
1803 .addImm(CI.CPol) // cpol
1804 .addImm(0) // swz
1805 .addMemOperand(combineKnownAdjacentMMOs(CI, Paired));
1806
1807 CI.I->eraseFromParent();
1808 Paired.I->eraseFromParent();
1809 return New;
1810}
1811
1812MachineBasicBlock::iterator SILoadStoreOptimizer::mergeFlatLoadPair(
1813 CombineInfo &CI, CombineInfo &Paired,
1814 MachineBasicBlock::iterator InsertBefore) {
1815 MachineBasicBlock *MBB = CI.I->getParent();
1816
1817 DebugLoc DL =
1818 DebugLoc::getMergedLocation(CI.I->getDebugLoc(), Paired.I->getDebugLoc());
1819
1820 const unsigned Opcode = getNewOpcode(CI, Paired);
1821
1822 const TargetRegisterClass *SuperRC = getTargetRegisterClass(CI, Paired);
1823 Register DestReg = MRI->createVirtualRegister(SuperRC);
1824
1825 auto MIB = BuildMI(*MBB, InsertBefore, DL, TII->get(Opcode), DestReg);
1826
1827 if (auto *SAddr = TII->getNamedOperand(*CI.I, AMDGPU::OpName::saddr))
1828 MIB.add(*SAddr);
1829
1830 MachineInstr *New =
1831 MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr))
1832 .addImm(std::min(CI.Offset, Paired.Offset))
1833 .addImm(CI.CPol)
1834 .addMemOperand(combineKnownAdjacentMMOs(CI, Paired));
1835
1836 copyToDestRegs(CI, Paired, InsertBefore, DL, AMDGPU::OpName::vdst, DestReg);
1837
1838 CI.I->eraseFromParent();
1839 Paired.I->eraseFromParent();
1840 return New;
1841}
1842
1843MachineBasicBlock::iterator SILoadStoreOptimizer::mergeFlatStorePair(
1844 CombineInfo &CI, CombineInfo &Paired,
1845 MachineBasicBlock::iterator InsertBefore) {
1846 MachineBasicBlock *MBB = CI.I->getParent();
1847
1848 DebugLoc DL =
1849 DebugLoc::getMergedLocation(CI.I->getDebugLoc(), Paired.I->getDebugLoc());
1850
1851 const unsigned Opcode = getNewOpcode(CI, Paired);
1852
1853 Register SrcReg =
1854 copyFromSrcRegs(CI, Paired, InsertBefore, DL, AMDGPU::OpName::vdata);
1855
1856 auto MIB = BuildMI(*MBB, InsertBefore, DL, TII->get(Opcode))
1857 .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr))
1858 .addReg(SrcReg);
1859
1860 if (auto *SAddr = TII->getNamedOperand(*CI.I, AMDGPU::OpName::saddr))
1861 MIB.add(*SAddr);
1862
1863 MachineInstr *New =
1864 MIB.addImm(std::min(CI.Offset, Paired.Offset))
1865 .addImm(CI.CPol)
1866 .addMemOperand(combineKnownAdjacentMMOs(CI, Paired));
1867
1868 CI.I->eraseFromParent();
1869 Paired.I->eraseFromParent();
1870 return New;
1871}
1872
1875 unsigned Width) {
1876 // Conservatively returns true if not found the MMO.
1877 return STM.isXNACKEnabled() &&
1878 (MMOs.size() != 1 || MMOs[0]->getAlign().value() < Width * 4);
1879}
1880
1881unsigned SILoadStoreOptimizer::getNewOpcode(const CombineInfo &CI,
1882 const CombineInfo &Paired) {
1883 const unsigned Width = CI.Width + Paired.Width;
1884 const CombineInfo &Leading = Paired < CI ? Paired : CI;
1885 // If XNACK is enabled, use the constrained opcodes when the first load is
1886 // under-aligned.
1887 const bool NeedsConstrainedOpc =
1888 needsConstrainedOpcode(*STM, Leading.I->memoperands(), Width);
1889
1890 switch (getCommonInstClass(CI, Paired)) {
1891 default:
1892 assert(CI.InstClass == BUFFER_LOAD || CI.InstClass == BUFFER_STORE);
1893 // FIXME: Handle d16 correctly
1894 return AMDGPU::getMUBUFOpcode(AMDGPU::getMUBUFBaseOpcode(CI.I->getOpcode()),
1895 Width);
1896 case TBUFFER_LOAD:
1897 case TBUFFER_STORE:
1898 return AMDGPU::getMTBUFOpcode(AMDGPU::getMTBUFBaseOpcode(CI.I->getOpcode()),
1899 Width);
1900
1901 case UNKNOWN:
1902 llvm_unreachable("Unknown instruction class");
1903 case S_BUFFER_LOAD_IMM: {
1904 switch (Width) {
1905 default:
1906 return 0;
1907 case 2:
1908 return NeedsConstrainedOpc ? AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM_ec
1909 : AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM;
1910 case 3:
1911 return NeedsConstrainedOpc ? AMDGPU::S_BUFFER_LOAD_DWORDX3_IMM_ec
1912 : AMDGPU::S_BUFFER_LOAD_DWORDX3_IMM;
1913 case 4:
1914 return NeedsConstrainedOpc ? AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM_ec
1915 : AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM;
1916 case 8:
1917 return NeedsConstrainedOpc ? AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM_ec
1918 : AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM;
1919 }
1920 }
1921 case S_BUFFER_LOAD_SGPR_IMM: {
1922 switch (Width) {
1923 default:
1924 return 0;
1925 case 2:
1926 return NeedsConstrainedOpc ? AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR_IMM_ec
1927 : AMDGPU::S_BUFFER_LOAD_DWORDX2_SGPR_IMM;
1928 case 3:
1929 return NeedsConstrainedOpc ? AMDGPU::S_BUFFER_LOAD_DWORDX3_SGPR_IMM_ec
1930 : AMDGPU::S_BUFFER_LOAD_DWORDX3_SGPR_IMM;
1931 case 4:
1932 return NeedsConstrainedOpc ? AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR_IMM_ec
1933 : AMDGPU::S_BUFFER_LOAD_DWORDX4_SGPR_IMM;
1934 case 8:
1935 return NeedsConstrainedOpc ? AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR_IMM_ec
1936 : AMDGPU::S_BUFFER_LOAD_DWORDX8_SGPR_IMM;
1937 }
1938 }
1939 case S_LOAD_IMM: {
1940 switch (Width) {
1941 default:
1942 return 0;
1943 case 2:
1944 return NeedsConstrainedOpc ? AMDGPU::S_LOAD_DWORDX2_IMM_ec
1945 : AMDGPU::S_LOAD_DWORDX2_IMM;
1946 case 3:
1947 return NeedsConstrainedOpc ? AMDGPU::S_LOAD_DWORDX3_IMM_ec
1948 : AMDGPU::S_LOAD_DWORDX3_IMM;
1949 case 4:
1950 return NeedsConstrainedOpc ? AMDGPU::S_LOAD_DWORDX4_IMM_ec
1951 : AMDGPU::S_LOAD_DWORDX4_IMM;
1952 case 8:
1953 return NeedsConstrainedOpc ? AMDGPU::S_LOAD_DWORDX8_IMM_ec
1954 : AMDGPU::S_LOAD_DWORDX8_IMM;
1955 }
1956 }
1957 case GLOBAL_LOAD:
1958 switch (Width) {
1959 default:
1960 return 0;
1961 case 2:
1962 return AMDGPU::GLOBAL_LOAD_DWORDX2;
1963 case 3:
1964 return AMDGPU::GLOBAL_LOAD_DWORDX3;
1965 case 4:
1966 return AMDGPU::GLOBAL_LOAD_DWORDX4;
1967 }
1968 case GLOBAL_LOAD_SADDR:
1969 switch (Width) {
1970 default:
1971 return 0;
1972 case 2:
1973 return AMDGPU::GLOBAL_LOAD_DWORDX2_SADDR;
1974 case 3:
1975 return AMDGPU::GLOBAL_LOAD_DWORDX3_SADDR;
1976 case 4:
1977 return AMDGPU::GLOBAL_LOAD_DWORDX4_SADDR;
1978 }
1979 case GLOBAL_STORE:
1980 switch (Width) {
1981 default:
1982 return 0;
1983 case 2:
1984 return AMDGPU::GLOBAL_STORE_DWORDX2;
1985 case 3:
1986 return AMDGPU::GLOBAL_STORE_DWORDX3;
1987 case 4:
1988 return AMDGPU::GLOBAL_STORE_DWORDX4;
1989 }
1990 case GLOBAL_STORE_SADDR:
1991 switch (Width) {
1992 default:
1993 return 0;
1994 case 2:
1995 return AMDGPU::GLOBAL_STORE_DWORDX2_SADDR;
1996 case 3:
1997 return AMDGPU::GLOBAL_STORE_DWORDX3_SADDR;
1998 case 4:
1999 return AMDGPU::GLOBAL_STORE_DWORDX4_SADDR;
2000 }
2001 case FLAT_LOAD:
2002 switch (Width) {
2003 default:
2004 return 0;
2005 case 2:
2006 return AMDGPU::FLAT_LOAD_DWORDX2;
2007 case 3:
2008 return AMDGPU::FLAT_LOAD_DWORDX3;
2009 case 4:
2010 return AMDGPU::FLAT_LOAD_DWORDX4;
2011 }
2012 case FLAT_STORE:
2013 switch (Width) {
2014 default:
2015 return 0;
2016 case 2:
2017 return AMDGPU::FLAT_STORE_DWORDX2;
2018 case 3:
2019 return AMDGPU::FLAT_STORE_DWORDX3;
2020 case 4:
2021 return AMDGPU::FLAT_STORE_DWORDX4;
2022 }
2023 case FLAT_LOAD_SADDR:
2024 switch (Width) {
2025 default:
2026 return 0;
2027 case 2:
2028 return AMDGPU::FLAT_LOAD_DWORDX2_SADDR;
2029 case 3:
2030 return AMDGPU::FLAT_LOAD_DWORDX3_SADDR;
2031 case 4:
2032 return AMDGPU::FLAT_LOAD_DWORDX4_SADDR;
2033 }
2034 case FLAT_STORE_SADDR:
2035 switch (Width) {
2036 default:
2037 return 0;
2038 case 2:
2039 return AMDGPU::FLAT_STORE_DWORDX2_SADDR;
2040 case 3:
2041 return AMDGPU::FLAT_STORE_DWORDX3_SADDR;
2042 case 4:
2043 return AMDGPU::FLAT_STORE_DWORDX4_SADDR;
2044 }
2045 case MIMG:
2046 assert(((unsigned)llvm::popcount(CI.DMask | Paired.DMask) == Width) &&
2047 "No overlaps");
2048 return AMDGPU::getMaskedMIMGOp(CI.I->getOpcode(), Width);
2049 }
2050}
2051
2052std::pair<unsigned, unsigned>
2053SILoadStoreOptimizer::getSubRegIdxs(const CombineInfo &CI,
2054 const CombineInfo &Paired) {
2055 assert((CI.InstClass != MIMG ||
2056 ((unsigned)llvm::popcount(CI.DMask | Paired.DMask) ==
2057 CI.Width + Paired.Width)) &&
2058 "No overlaps");
2059
2060 unsigned Idx0;
2061 unsigned Idx1;
2062
2063 static const unsigned Idxs[5][4] = {
2064 {AMDGPU::sub0, AMDGPU::sub0_sub1, AMDGPU::sub0_sub1_sub2, AMDGPU::sub0_sub1_sub2_sub3},
2065 {AMDGPU::sub1, AMDGPU::sub1_sub2, AMDGPU::sub1_sub2_sub3, AMDGPU::sub1_sub2_sub3_sub4},
2066 {AMDGPU::sub2, AMDGPU::sub2_sub3, AMDGPU::sub2_sub3_sub4, AMDGPU::sub2_sub3_sub4_sub5},
2067 {AMDGPU::sub3, AMDGPU::sub3_sub4, AMDGPU::sub3_sub4_sub5, AMDGPU::sub3_sub4_sub5_sub6},
2068 {AMDGPU::sub4, AMDGPU::sub4_sub5, AMDGPU::sub4_sub5_sub6, AMDGPU::sub4_sub5_sub6_sub7},
2069 };
2070
2071 assert(CI.Width >= 1 && CI.Width <= 4);
2072 assert(Paired.Width >= 1 && Paired.Width <= 4);
2073
2074 if (Paired < CI) {
2075 Idx1 = Idxs[0][Paired.Width - 1];
2076 Idx0 = Idxs[Paired.Width][CI.Width - 1];
2077 } else {
2078 Idx0 = Idxs[0][CI.Width - 1];
2079 Idx1 = Idxs[CI.Width][Paired.Width - 1];
2080 }
2081
2082 return {Idx0, Idx1};
2083}
2084
2085const TargetRegisterClass *
2086SILoadStoreOptimizer::getTargetRegisterClass(const CombineInfo &CI,
2087 const CombineInfo &Paired) const {
2088 if (CI.InstClass == S_BUFFER_LOAD_IMM ||
2089 CI.InstClass == S_BUFFER_LOAD_SGPR_IMM || CI.InstClass == S_LOAD_IMM) {
2090 switch (CI.Width + Paired.Width) {
2091 default:
2092 return nullptr;
2093 case 2:
2094 return &AMDGPU::SReg_64_XEXECRegClass;
2095 case 3:
2096 return &AMDGPU::SGPR_96RegClass;
2097 case 4:
2098 return &AMDGPU::SGPR_128RegClass;
2099 case 8:
2100 return &AMDGPU::SGPR_256RegClass;
2101 case 16:
2102 return &AMDGPU::SGPR_512RegClass;
2103 }
2104 }
2105
2106 // FIXME: This should compute the instruction to use, and then use the result
2107 // of TII->getRegClass.
2108 unsigned BitWidth = 32 * (CI.Width + Paired.Width);
2109 return TRI->isAGPRClass(getDataRegClass(*CI.I))
2110 ? TRI->getAGPRClassForBitWidth(BitWidth)
2111 : TRI->getVGPRClassForBitWidth(BitWidth);
2112}
2113
2114MachineBasicBlock::iterator SILoadStoreOptimizer::mergeBufferStorePair(
2115 CombineInfo &CI, CombineInfo &Paired,
2116 MachineBasicBlock::iterator InsertBefore) {
2117 MachineBasicBlock *MBB = CI.I->getParent();
2118 DebugLoc DL =
2119 DebugLoc::getMergedLocation(CI.I->getDebugLoc(), Paired.I->getDebugLoc());
2120
2121 const unsigned Opcode = getNewOpcode(CI, Paired);
2122
2123 Register SrcReg =
2124 copyFromSrcRegs(CI, Paired, InsertBefore, DL, AMDGPU::OpName::vdata);
2125
2126 auto MIB = BuildMI(*MBB, InsertBefore, DL, TII->get(Opcode)).addReg(SrcReg);
2127
2128 AddressRegs Regs = getRegs(Opcode, *TII);
2129
2130 if (Regs.VAddr)
2131 MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));
2132
2133
2134 // It shouldn't be possible to get this far if the two instructions
2135 // don't have a single memoperand, because MachineInstr::mayAlias()
2136 // will return true if this is the case.
2137 assert(CI.I->hasOneMemOperand() && Paired.I->hasOneMemOperand());
2138
2139 MachineInstr *New =
2140 MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
2141 .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
2142 .addImm(std::min(CI.Offset, Paired.Offset)) // offset
2143 .addImm(CI.CPol) // cpol
2144 .addImm(0) // swz
2145 .addMemOperand(combineKnownAdjacentMMOs(CI, Paired));
2146
2147 CI.I->eraseFromParent();
2148 Paired.I->eraseFromParent();
2149 return New;
2150}
2151
2152MachineOperand
2153SILoadStoreOptimizer::createRegOrImm(int32_t Val, MachineInstr &MI) const {
2154 APInt V(32, Val, true);
2155 if (TII->isInlineConstant(V))
2156 return MachineOperand::CreateImm(Val);
2157
2158 Register Reg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2159 MachineInstr *Mov =
2160 BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
2161 TII->get(AMDGPU::S_MOV_B32), Reg)
2162 .addImm(Val);
2163 (void)Mov;
2164 LLVM_DEBUG(dbgs() << " "; Mov->dump());
2165 return MachineOperand::CreateReg(Reg, false);
2166}
2167
2168// Compute base address using Addr and return the final register.
2169Register SILoadStoreOptimizer::computeBase(MachineInstr &MI,
2170 const MemAddress &Addr) const {
2171 MachineBasicBlock *MBB = MI.getParent();
2173 const DebugLoc &DL = MI.getDebugLoc();
2174
2175 LLVM_DEBUG(dbgs() << " Re-Computed Anchor-Base:\n");
2176
2177 // Use V_ADD_U64_e64 when the original pattern used it (gfx1250+)
2178 if (Addr.Base.UseV64Pattern) {
2179 Register FullDestReg = MRI->createVirtualRegister(
2180 TII->getRegClass(TII->get(AMDGPU::V_ADD_U64_e64), 0));
2181
2182 // Load the 64-bit offset into an SGPR pair if needed
2183 Register OffsetReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
2184 MachineInstr *MovOffset =
2185 BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::S_MOV_B64_IMM_PSEUDO),
2186 OffsetReg)
2187 .addImm(Addr.Offset);
2188 MachineInstr *Add64 =
2189 BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::V_ADD_U64_e64), FullDestReg)
2190 .addReg(Addr.Base.LoReg)
2191 .addReg(OffsetReg)
2192 .addImm(0);
2193 (void)MovOffset;
2194 (void)Add64;
2195 LLVM_DEBUG(dbgs() << " " << *MovOffset << "\n";
2196 dbgs() << " " << *Add64 << "\n\n";);
2197
2198 return FullDestReg;
2199 }
2200
2201 // Use V_ADD_U32_e64 for the 32-bit FLAT_SCRATCH vaddr base.
2202 if (Addr.Base.UseScratchVGPRPattern) {
2203 MachineOperand OffsetOp =
2204 createRegOrImm(static_cast<int32_t>(Addr.Offset), MI);
2205
2206 Register FullDestReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2207 MachineInstr *Add32 =
2208 BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::V_ADD_U32_e64), FullDestReg)
2209 .addReg(Addr.Base.LoReg, {}, Addr.Base.LoSubReg)
2210 .add(OffsetOp)
2211 .addImm(0); // clamp bit
2212 (void)Add32;
2213 LLVM_DEBUG(dbgs() << " " << *Add32 << "\n\n";);
2214
2215 return FullDestReg;
2216 }
2217
2218 // Original carry-chain pattern (V_ADD_CO_U32 + V_ADDC_U32)
2219 assert((TRI->getRegSizeInBits(Addr.Base.LoReg, *MRI) == 32 ||
2220 Addr.Base.LoSubReg) &&
2221 "Expected 32-bit Base-Register-Low!!");
2222
2223 assert((TRI->getRegSizeInBits(Addr.Base.HiReg, *MRI) == 32 ||
2224 Addr.Base.HiSubReg) &&
2225 "Expected 32-bit Base-Register-Hi!!");
2226
2227 MachineOperand OffsetLo = createRegOrImm(static_cast<int32_t>(Addr.Offset), MI);
2228 MachineOperand OffsetHi =
2229 createRegOrImm(static_cast<int32_t>(Addr.Offset >> 32), MI);
2230
2231 const auto *CarryRC = TRI->getWaveMaskRegClass();
2232 Register CarryReg = MRI->createVirtualRegister(CarryRC);
2233 Register DeadCarryReg = MRI->createVirtualRegister(CarryRC);
2234
2235 Register DestSub0 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2236 Register DestSub1 = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2237 MachineInstr *LoHalf =
2238 BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::V_ADD_CO_U32_e64), DestSub0)
2239 .addReg(CarryReg, RegState::Define)
2240 .addReg(Addr.Base.LoReg, {}, Addr.Base.LoSubReg)
2241 .add(OffsetLo)
2242 .addImm(0); // clamp bit
2243
2244 MachineInstr *HiHalf =
2245 BuildMI(*MBB, MBBI, DL, TII->get(AMDGPU::V_ADDC_U32_e64), DestSub1)
2246 .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
2247 .addReg(Addr.Base.HiReg, {}, Addr.Base.HiSubReg)
2248 .add(OffsetHi)
2249 .addReg(CarryReg)
2250 .addImm(0); // clamp bit
2251
2252 Register FullDestReg = MRI->createVirtualRegister(TRI->getVGPR64Class());
2253 MachineInstr *FullBase =
2254 BuildMI(*MBB, MBBI, DL, TII->get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2255 .addReg(DestSub0)
2256 .addImm(AMDGPU::sub0)
2257 .addReg(DestSub1)
2258 .addImm(AMDGPU::sub1);
2259
2260 (void)LoHalf;
2261 (void)HiHalf;
2262 (void)FullBase;
2263 LLVM_DEBUG(dbgs() << " " << *LoHalf << "\n";
2264 dbgs() << " " << *HiHalf << "\n";
2265 dbgs() << " " << *FullBase << "\n\n";);
2266
2267 return FullDestReg;
2268}
2269
2270// Update base and offset with the NewBase and NewOffset in MI.
2271void SILoadStoreOptimizer::updateBaseAndOffset(MachineInstr &MI,
2272 Register NewBase,
2273 int32_t NewOffset) const {
2274 auto *Base = TII->getNamedOperand(MI, AMDGPU::OpName::vaddr);
2275 Base->setReg(NewBase);
2276 Base->setIsKill(false);
2277 TII->getNamedOperand(MI, AMDGPU::OpName::offset)->setImm(NewOffset);
2278}
2279
2280// Helper to extract a 64-bit constant offset from a V_ADD_U64_e64 instruction.
2281// Returns true if successful, populating Addr with base register info and
2282// offset.
2283bool SILoadStoreOptimizer::processBaseWithConstOffset64(
2284 MachineInstr *AddDef, const MachineOperand &Base, MemAddress &Addr) const {
2285 if (!Base.isReg())
2286 return false;
2287
2288 MachineOperand *Src0 = TII->getNamedOperand(*AddDef, AMDGPU::OpName::src0);
2289 MachineOperand *Src1 = TII->getNamedOperand(*AddDef, AMDGPU::OpName::src1);
2290
2291 const MachineOperand *BaseOp = nullptr;
2292
2293 auto Offset = TII->getImmOrMaterializedImm(*MRI, *Src1);
2294
2295 if (Offset) {
2296 BaseOp = Src0;
2297 Addr.Offset = *Offset;
2298 } else {
2299 // Both or neither are constants - can't handle this pattern
2300 return false;
2301 }
2302
2303 // Now extract the base register (which should be a 64-bit VGPR).
2304 Addr.Base.LoReg = BaseOp->getReg();
2305 Addr.Base.UseV64Pattern = true;
2306 return true;
2307}
2308
2309// Helper to extract a 32-bit constant offset from a V_ADD_U32_e64 instruction.
2310// This is the pattern used for the 32-bit vaddr of FLAT_SCRATCH instructions.
2311// Returns true if successful, populating Addr with base register info and
2312// offset.
2313bool SILoadStoreOptimizer::processBaseWithConstOffset32(
2314 MachineInstr *AddDef, MemAddress &Addr) const {
2315 // A clamped add saturates, so its constant cannot be split off.
2316 if (TII->getNamedOperand(*AddDef, AMDGPU::OpName::clamp)->getImm())
2317 return false;
2318
2319 MachineOperand *Src0 = TII->getNamedOperand(*AddDef, AMDGPU::OpName::src0);
2320 MachineOperand *Src1 = TII->getNamedOperand(*AddDef, AMDGPU::OpName::src1);
2321
2322 const MachineOperand *BaseOp = nullptr;
2323 std::optional<int64_t> Offset;
2324
2325 if ((Offset = TII->getImmOrMaterializedImm(*MRI, *Src1))) {
2326 BaseOp = Src0;
2327 } else if ((Offset = TII->getImmOrMaterializedImm(*MRI, *Src0))) {
2328 BaseOp = Src1;
2329 } else {
2330 // Both or neither are constants - can't handle this pattern
2331 return false;
2332 }
2333
2334 // An SGPR base could make the rebuilt add read two SGPRs.
2335 if (!BaseOp->isReg() || !TRI->isVGPR(*MRI, BaseOp->getReg()))
2336 return false;
2337
2338 Addr.Base.LoReg = BaseOp->getReg();
2339 Addr.Base.LoSubReg = BaseOp->getSubReg();
2340 Addr.Base.UseScratchVGPRPattern = true;
2341 Addr.Offset = *Offset;
2342 return true;
2343}
2344
2345// Analyze Base and extracts:
2346// - 32bit base registers, subregisters
2347// - 64bit constant offset
2348// Expecting base computation as:
2349// %OFFSET0:sgpr_32 = S_MOV_B32 8000
2350// %LO:vgpr_32, %c:sreg_64_xexec =
2351// V_ADD_CO_U32_e64 %BASE_LO:vgpr_32, %103:sgpr_32,
2352// %HI:vgpr_32, = V_ADDC_U32_e64 %BASE_HI:vgpr_32, 0, killed %c:sreg_64_xexec
2353// %Base:vreg_64 =
2354// REG_SEQUENCE %LO:vgpr_32, %subreg.sub0, %HI:vgpr_32, %subreg.sub1
2355//
2356// Also handles V_ADD_U64_e64 pattern (gfx1250+):
2357// %OFFSET:sreg_64 = S_MOV_B64_IMM_PSEUDO 256
2358// %Base:vreg_64 = V_ADD_U64_e64 %BASE:vreg_64, %OFFSET:sreg_64, 0
2359//
2360// Also handles the 32-bit VGPR pattern used for FLAT_SCRATCH vaddr:
2361// %OFFSET:sreg_32 = S_MOV_B32 4096
2362// %Base:vgpr_32 = V_ADD_U32_e64 %BASE:vgpr_32, %OFFSET:sreg_32, 0
2363void SILoadStoreOptimizer::processBaseWithConstOffset(const MachineOperand &Base,
2364 MemAddress &Addr) const {
2365 if (!Base.isReg())
2366 return;
2367
2368 MachineInstr *Def = MRI->getVRegDef(Base.getReg());
2369 if (!Def)
2370 return;
2371
2372 // Try V_ADD_U64_e64 pattern first (simpler, used on gfx1250+)
2373 if (Def->getOpcode() == AMDGPU::V_ADD_U64_e64) {
2374 if (processBaseWithConstOffset64(Def, Base, Addr))
2375 return;
2376 }
2377
2378 // Try V_ADD_U32_e64 pattern (32-bit base, used for FLAT_SCRATCH vaddr)
2379 // Not GLOBAL saddr: it zero-extends vaddr, so a 32-bit wrap cannot be split.
2380 if (Def->getOpcode() == AMDGPU::V_ADD_U32_e64 &&
2381 SIInstrInfo::isFLATScratch(*Base.getParent())) {
2382 if (processBaseWithConstOffset32(Def, Addr))
2383 return;
2384 }
2385
2386 // Fall through to REG_SEQUENCE + V_ADD_CO_U32 + V_ADDC_U32 pattern
2387 if (Def->getOpcode() != AMDGPU::REG_SEQUENCE || Def->getNumOperands() != 5)
2388 return;
2389
2390 MachineOperand BaseLo = Def->getOperand(1);
2391 MachineOperand BaseHi = Def->getOperand(3);
2392 if (!BaseLo.isReg() || !BaseHi.isReg())
2393 return;
2394
2395 MachineInstr *BaseLoDef = MRI->getVRegDef(BaseLo.getReg());
2396 MachineInstr *BaseHiDef = MRI->getVRegDef(BaseHi.getReg());
2397
2398 if (!BaseLoDef || BaseLoDef->getOpcode() != AMDGPU::V_ADD_CO_U32_e64 ||
2399 !BaseHiDef || BaseHiDef->getOpcode() != AMDGPU::V_ADDC_U32_e64)
2400 return;
2401
2402 MachineOperand *Src0 = TII->getNamedOperand(*BaseLoDef, AMDGPU::OpName::src0);
2403 MachineOperand *Src1 = TII->getNamedOperand(*BaseLoDef, AMDGPU::OpName::src1);
2404
2405 auto Offset0P = TII->getImmOrMaterializedImm(*MRI, *Src0);
2406 if (Offset0P)
2407 BaseLo = *Src1;
2408 else {
2409 if (!(Offset0P = TII->getImmOrMaterializedImm(*MRI, *Src1)))
2410 return;
2411 BaseLo = *Src0;
2412 }
2413
2414 if (!BaseLo.isReg())
2415 return;
2416
2417 Src0 = TII->getNamedOperand(*BaseHiDef, AMDGPU::OpName::src0);
2418 Src1 = TII->getNamedOperand(*BaseHiDef, AMDGPU::OpName::src1);
2419
2420 if (Src0->isImm())
2421 std::swap(Src0, Src1);
2422
2423 if (!Src1->isImm() || Src0->isImm())
2424 return;
2425
2426 uint64_t Offset1 = Src1->getImm();
2427 BaseHi = *Src0;
2428
2429 if (!BaseHi.isReg())
2430 return;
2431
2432 Addr.Base.LoReg = BaseLo.getReg();
2433 Addr.Base.HiReg = BaseHi.getReg();
2434 Addr.Base.LoSubReg = BaseLo.getSubReg();
2435 Addr.Base.HiSubReg = BaseHi.getSubReg();
2436 Addr.Offset = (*Offset0P & 0x00000000ffffffff) | (Offset1 << 32);
2437}
2438
2439// Maintain the correct LDS address for async loads and stores.
2440// It becomes incorrect when promoteConstantOffsetToImm adds an offset only
2441// meant for the global address operand. For async loads the LDS address is in
2442// vdst. For async stores, the LDS address is in vdata.
2443void SILoadStoreOptimizer::updateAsyncLDSAddress(MachineInstr &MI,
2444 int32_t OffsetDiff) const {
2445 if (!TII->usesASYNC_CNT(MI) || OffsetDiff == 0)
2446 return;
2447
2448 MachineOperand *LDSAddr = TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
2449 if (!LDSAddr)
2450 LDSAddr = TII->getNamedOperand(MI, AMDGPU::OpName::vdata);
2451 assert(LDSAddr);
2452
2453 Register OldReg = LDSAddr->getReg();
2454 Register NewReg = MRI->createVirtualRegister(MRI->getRegClass(OldReg));
2455 MachineBasicBlock &MBB = *MI.getParent();
2456 const DebugLoc &DL = MI.getDebugLoc();
2457 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_ADD_U32_e64), NewReg)
2458 .addReg(OldReg)
2459 .addImm(-OffsetDiff)
2460 .addImm(0);
2461
2462 LDSAddr->setReg(NewReg);
2463}
2464
2465bool SILoadStoreOptimizer::promoteConstantOffsetToImm(
2466 MachineInstr &MI,
2467 MemInfoMap &Visited,
2468 SmallPtrSet<MachineInstr *, 4> &AnchorList) const {
2469
2470 if (!STM->hasFlatInstOffsets() || !SIInstrInfo::isFLAT(MI))
2471 return false;
2472
2474 !TII->getNamedOperand(MI, AMDGPU::OpName::vaddr))
2475 return false;
2476
2477 // Moving part of vaddr into the offset can trigger the SVS swizzle bug.
2479 TII->getNamedOperand(MI, AMDGPU::OpName::saddr))
2480 return false;
2481
2485
2486 AMDGPU::FlatAddrSpace FlatVariant =
2487 AS == AMDGPUAS::GLOBAL_ADDRESS ? AMDGPU::FlatAddrSpace::FlatGlobal
2488 : AS == AMDGPUAS::PRIVATE_ADDRESS ? AMDGPU::FlatAddrSpace::FlatScratch
2489 : AMDGPU::FlatAddrSpace::FLAT;
2490 bool AllowNegativeOffset =
2491 TII->allowNegativeFlatOffset(FlatVariant) && !TII->usesASYNC_CNT(MI);
2492 // The async global instructions use i24 offset for global address but u16
2493 // offset for LDS address. In this case, we just only promote when the offset
2494 // is u16.
2495 bool IsOffsetU16 = TII->usesASYNC_CNT(MI);
2496
2497 if (AnchorList.count(&MI))
2498 return false;
2499
2500 LLVM_DEBUG(dbgs() << "\nTryToPromoteConstantOffsetToImmFor "; MI.dump());
2501
2502 if (TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm()) {
2503 LLVM_DEBUG(dbgs() << " Const-offset is already promoted.\n";);
2504 return false;
2505 }
2506
2507 // Step1: Find the base-registers and a 64bit constant offset.
2508 MachineOperand &Base = *TII->getNamedOperand(MI, AMDGPU::OpName::vaddr);
2509 auto [It, Inserted] = Visited.try_emplace(&MI);
2510 MemAddress MAddr;
2511 if (Inserted) {
2512 processBaseWithConstOffset(Base, MAddr);
2513 It->second = MAddr;
2514 } else
2515 MAddr = It->second;
2516
2517 if (MAddr.Offset == 0) {
2518 LLVM_DEBUG(dbgs() << " Failed to extract constant-offset or there are no"
2519 " constant offsets that can be promoted.\n";);
2520 return false;
2521 }
2522
2523 LLVM_DEBUG(dbgs() << " BASE: {" << printReg(MAddr.Base.HiReg, TRI) << ", "
2524 << printReg(MAddr.Base.LoReg, TRI)
2525 << "} Offset: " << MAddr.Offset << "\n\n";);
2526
2527 // Step2: Traverse through MI's basic block and find an anchor(that has the
2528 // same base-registers) with the highest 13bit distance from MI's offset.
2529 // E.g. (64bit loads)
2530 // bb:
2531 // addr1 = &a + 4096; load1 = load(addr1, 0)
2532 // addr2 = &a + 6144; load2 = load(addr2, 0)
2533 // addr3 = &a + 8192; load3 = load(addr3, 0)
2534 // addr4 = &a + 10240; load4 = load(addr4, 0)
2535 // addr5 = &a + 12288; load5 = load(addr5, 0)
2536 //
2537 // Starting from the first load, the optimization will try to find a new base
2538 // from which (&a + 4096) has 13 bit distance. Both &a + 6144 and &a + 8192
2539 // has 13bit distance from &a + 4096. The heuristic considers &a + 8192
2540 // as the new-base(anchor) because of the maximum distance which can
2541 // accommodate more intermediate bases presumably.
2542 //
2543 // Step3: move (&a + 8192) above load1. Compute and promote offsets from
2544 // (&a + 8192) for load1, load2, load4.
2545 // addr = &a + 8192
2546 // load1 = load(addr, -4096)
2547 // load2 = load(addr, -2048)
2548 // load3 = load(addr, 0)
2549 // load4 = load(addr, 2048)
2550 // addr5 = &a + 12288; load5 = load(addr5, 0)
2551 //
2552 MachineInstr *AnchorInst = nullptr;
2553 MemAddress AnchorAddr;
2554 uint32_t MaxDist = std::numeric_limits<uint32_t>::min();
2556 bool MIIsAnchor = false;
2557
2558 MachineBasicBlock *MBB = MI.getParent();
2561 ++MBBI;
2562 const SITargetLowering *TLI = STM->getTargetLowering();
2563
2564 for ( ; MBBI != E; ++MBBI) {
2565 MachineInstr &MINext = *MBBI;
2566 // TODO: Support finding an anchor(with same base) from store addresses or
2567 // any other load addresses where the opcodes are different.
2568 if (MINext.getOpcode() != MI.getOpcode() ||
2569 TII->getNamedOperand(MINext, AMDGPU::OpName::offset)->getImm())
2570 continue;
2571
2572 const MachineOperand &BaseNext =
2573 *TII->getNamedOperand(MINext, AMDGPU::OpName::vaddr);
2574 MemAddress MAddrNext;
2575 auto [It, Inserted] = Visited.try_emplace(&MINext);
2576 if (Inserted) {
2577 processBaseWithConstOffset(BaseNext, MAddrNext);
2578 It->second = MAddrNext;
2579 } else
2580 MAddrNext = It->second;
2581
2582 if (MAddrNext.Base.LoReg != MAddr.Base.LoReg ||
2583 MAddrNext.Base.HiReg != MAddr.Base.HiReg ||
2584 MAddrNext.Base.LoSubReg != MAddr.Base.LoSubReg ||
2585 MAddrNext.Base.HiSubReg != MAddr.Base.HiSubReg)
2586 continue;
2587
2588 InstsWCommonBase.emplace_back(&MINext, MAddrNext.Offset);
2589
2590 if (AllowNegativeOffset) {
2591 int64_t Dist = MAddr.Offset - MAddrNext.Offset;
2592 TargetLoweringBase::AddrMode AM;
2593 AM.HasBaseReg = true;
2594 AM.BaseOffs = Dist;
2595 if (TLI->isLegalFlatAddressingMode(AM, AS) &&
2596 (uint32_t)std::abs(Dist) > MaxDist) {
2597 MaxDist = std::abs(Dist);
2598
2599 AnchorAddr = MAddrNext;
2600 AnchorInst = &MINext;
2601 }
2602 }
2603 }
2604
2605 // When negative offsets are not allowed, pick the candidate with the smallest
2606 // offset as anchor so all promoted offsets are non-negative. If MI itself has
2607 // the smallest offset, MI becomes the reference point (MIIsAnchor).
2608 if (!AllowNegativeOffset && !InstsWCommonBase.empty()) {
2609 for (auto &[Inst, Offset] : InstsWCommonBase) {
2610 int64_t Dist = MAddr.Offset - Offset;
2611 TargetLoweringBase::AddrMode AM;
2612 AM.HasBaseReg = true;
2613 AM.BaseOffs = Dist;
2614 if (Dist >= 0 && TLI->isLegalFlatAddressingMode(AM, AS) &&
2615 (!IsOffsetU16 || isUInt<16>(Dist)) &&
2616 (!AnchorInst || Offset < AnchorAddr.Offset)) {
2617 AnchorAddr = Visited[Inst];
2618 AnchorInst = Inst;
2619 }
2620 }
2621 if (!AnchorInst)
2622 MIIsAnchor = true;
2623 }
2624
2625 if (AnchorInst) {
2626 LLVM_DEBUG(dbgs() << " Anchor-Inst(with max-distance from Offset): ";
2627 AnchorInst->dump());
2628 LLVM_DEBUG(dbgs() << " Anchor-Offset from BASE: "
2629 << AnchorAddr.Offset << "\n\n");
2630
2631 // Instead of moving up, just re-compute anchor-instruction's base address.
2632 Register Base = computeBase(MI, AnchorAddr);
2633
2634 int32_t OffsetDiff = MAddr.Offset - AnchorAddr.Offset;
2635 updateBaseAndOffset(MI, Base, OffsetDiff);
2636 updateAsyncLDSAddress(MI, OffsetDiff);
2637 LLVM_DEBUG(dbgs() << " After promotion: "; MI.dump(););
2638
2639 for (auto [OtherMI, OtherOffset] : InstsWCommonBase) {
2640 TargetLoweringBase::AddrMode AM;
2641 AM.HasBaseReg = true;
2642 AM.BaseOffs = OtherOffset - AnchorAddr.Offset;
2643
2644 if (TLI->isLegalFlatAddressingMode(AM, AS) &&
2645 (AllowNegativeOffset || AM.BaseOffs >= 0) &&
2646 (!IsOffsetU16 || isUInt<16>(AM.BaseOffs))) {
2647 LLVM_DEBUG(dbgs() << " Promote Offset(" << OtherOffset; dbgs() << ")";
2648 OtherMI->dump());
2649 int32_t OtherOffsetDiff = OtherOffset - AnchorAddr.Offset;
2650 updateBaseAndOffset(*OtherMI, Base, OtherOffsetDiff);
2651 updateAsyncLDSAddress(*OtherMI, OtherOffsetDiff);
2652 LLVM_DEBUG(dbgs() << " After promotion: "; OtherMI->dump());
2653 }
2654 }
2655 AnchorList.insert(AnchorInst);
2656 return true;
2657 }
2658
2659 if (MIIsAnchor) {
2660 LLVM_DEBUG(dbgs() << " MI is anchor (smallest offset); promoting "
2661 "candidates relative to MI's base.\n");
2662
2663 Register Base = TII->getNamedOperand(MI, AMDGPU::OpName::vaddr)->getReg();
2664 bool AnyPromoted = false;
2665
2666 for (auto [OtherMI, OtherOffset] : InstsWCommonBase) {
2667 int64_t Dist = OtherOffset - MAddr.Offset;
2668 TargetLoweringBase::AddrMode AM;
2669 AM.HasBaseReg = true;
2670 AM.BaseOffs = Dist;
2671 if (Dist >= 0 && TLI->isLegalFlatAddressingMode(AM, AS) &&
2672 (!IsOffsetU16 || isUInt<16>(Dist))) {
2673 LLVM_DEBUG(dbgs() << " Promote Offset(" << OtherOffset << ")";
2674 OtherMI->dump());
2675 updateBaseAndOffset(*OtherMI, Base, Dist);
2676 updateAsyncLDSAddress(*OtherMI, Dist);
2677 LLVM_DEBUG(dbgs() << " After promotion: "; OtherMI->dump());
2678 AnyPromoted = true;
2679 }
2680 }
2681
2682 if (AnyPromoted) {
2683 TII->getNamedOperand(MI, AMDGPU::OpName::vaddr)->setIsKill(false);
2684 AnchorList.insert(&MI);
2685 return true;
2686 }
2687 }
2688
2689 return false;
2690}
2691
2692void SILoadStoreOptimizer::addInstToMergeableList(const CombineInfo &CI,
2693 std::list<std::list<CombineInfo> > &MergeableInsts) const {
2694 for (std::list<CombineInfo> &AddrList : MergeableInsts) {
2695 if (AddrList.front().InstClass == CI.InstClass &&
2696 AddrList.front().hasSameBaseAddress(CI)) {
2697 AddrList.emplace_back(CI);
2698 return;
2699 }
2700 }
2701
2702 // Base address not found, so add a new list.
2703 MergeableInsts.emplace_back(1, CI);
2704}
2705
2706std::pair<MachineBasicBlock::iterator, bool>
2707SILoadStoreOptimizer::collectMergeableInsts(
2709 MemInfoMap &Visited, SmallPtrSet<MachineInstr *, 4> &AnchorList,
2710 std::list<std::list<CombineInfo>> &MergeableInsts) const {
2711 bool Modified = false;
2712
2713 // Sort potential mergeable instructions into lists. One list per base address.
2714 unsigned Order = 0;
2715 MachineBasicBlock::iterator BlockI = Begin;
2716 for (; BlockI != End; ++BlockI) {
2717 MachineInstr &MI = *BlockI;
2718
2719 // We run this before checking if an address is mergeable, because it can produce
2720 // better code even if the instructions aren't mergeable.
2721 if (promoteConstantOffsetToImm(MI, Visited, AnchorList))
2722 Modified = true;
2723
2724 // Treat volatile accesses, ordered accesses and unmodeled side effects as
2725 // barriers. We can look after this barrier for separate merges.
2726 if (MI.hasOrderedMemoryRef() || MI.hasUnmodeledSideEffects()) {
2727 LLVM_DEBUG(dbgs() << "Breaking search on barrier: " << MI);
2728
2729 // Search will resume after this instruction in a separate merge list.
2730 ++BlockI;
2731 break;
2732 }
2733
2734 const InstClassEnum InstClass = getInstClass(MI.getOpcode(), *TII);
2735 if (InstClass == UNKNOWN)
2736 continue;
2737
2738 // Do not merge VMEM buffer instructions with "swizzled" bit set.
2739 int Swizzled =
2740 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::swz);
2741 if (Swizzled != -1 && MI.getOperand(Swizzled).getImm())
2742 continue;
2743
2744 if (InstClass == TBUFFER_LOAD || InstClass == TBUFFER_STORE) {
2745 if (!STM->hasRelaxedTBufferOOBMode()) {
2746 LLVM_DEBUG(
2747 dbgs() << "Skip tbuffer combine: relaxed OOB mode not enabled\n");
2748 continue;
2749 }
2750
2751 const MachineOperand *Fmt =
2752 TII->getNamedOperand(MI, AMDGPU::OpName::format);
2753 if (!AMDGPU::getGcnBufferFormatInfo(Fmt->getImm(), *STM)) {
2754 LLVM_DEBUG(dbgs() << "Skip tbuffer with unknown format: " << MI);
2755 continue;
2756 }
2757 } else if (InstClass == MIMG) {
2758 // Do not merge MIMG instructions with tfe or lwe enabled.
2759 // TFE/LWE add a status result that the image merge path does not model.
2760 const auto *TFEOp = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
2761 if (TFEOp && TFEOp->getImm())
2762 continue;
2763
2764 const auto *LWEOp = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
2765 if (LWEOp && LWEOp->getImm())
2766 continue;
2767 }
2768
2769 CombineInfo CI;
2770 CI.setMI(MI, *this);
2771 CI.Order = Order++;
2772
2773 if (!CI.hasMergeableAddress(*MRI))
2774 continue;
2775
2776 LLVM_DEBUG(dbgs() << "Mergeable: " << MI);
2777
2778 addInstToMergeableList(CI, MergeableInsts);
2779 }
2780
2781 // At this point we have lists of Mergeable instructions.
2782 //
2783 // Part 2: Sort lists by offset and then for each CombineInfo object in the
2784 // list try to find an instruction that can be merged with I. If an instruction
2785 // is found, it is stored in the Paired field. If no instructions are found, then
2786 // the CombineInfo object is deleted from the list.
2787
2788 for (std::list<std::list<CombineInfo>>::iterator I = MergeableInsts.begin(),
2789 E = MergeableInsts.end(); I != E;) {
2790
2791 std::list<CombineInfo> &MergeList = *I;
2792 if (MergeList.size() <= 1) {
2793 // This means we have found only one instruction with a given address
2794 // that can be merged, and we need at least 2 instructions to do a merge,
2795 // so this list can be discarded.
2796 I = MergeableInsts.erase(I);
2797 continue;
2798 }
2799
2800 // Sort the lists by offsets, this way mergeable instructions will be
2801 // adjacent to each other in the list, which will make it easier to find
2802 // matches.
2803 MergeList.sort(
2804 [] (const CombineInfo &A, const CombineInfo &B) {
2805 return A.Offset < B.Offset;
2806 });
2807 ++I;
2808 }
2809
2810 return {BlockI, Modified};
2811}
2812
2813// Scan through looking for adjacent LDS operations with constant offsets from
2814// the same base register. We rely on the scheduler to do the hard work of
2815// clustering nearby loads, and assume these are all adjacent.
2816bool SILoadStoreOptimizer::optimizeBlock(
2817 std::list<std::list<CombineInfo> > &MergeableInsts) {
2818 bool Modified = false;
2819
2820 for (std::list<std::list<CombineInfo>>::iterator I = MergeableInsts.begin(),
2821 E = MergeableInsts.end(); I != E;) {
2822 std::list<CombineInfo> &MergeList = *I;
2823
2824 bool OptimizeListAgain = false;
2825 if (!optimizeInstsWithSameBaseAddr(MergeList, OptimizeListAgain)) {
2826 // We weren't able to make any changes, so delete the list so we don't
2827 // process the same instructions the next time we try to optimize this
2828 // block.
2829 I = MergeableInsts.erase(I);
2830 continue;
2831 }
2832
2833 Modified = true;
2834
2835 // We made changes, but also determined that there were no more optimization
2836 // opportunities, so we don't need to reprocess the list
2837 if (!OptimizeListAgain) {
2838 I = MergeableInsts.erase(I);
2839 continue;
2840 }
2841 OptimizeAgain = true;
2842 }
2843 return Modified;
2844}
2845
2846bool
2847SILoadStoreOptimizer::optimizeInstsWithSameBaseAddr(
2848 std::list<CombineInfo> &MergeList,
2849 bool &OptimizeListAgain) {
2850 if (MergeList.empty())
2851 return false;
2852
2853 bool Modified = false;
2854
2855 for (auto I = MergeList.begin(), Next = std::next(I); Next != MergeList.end();
2856 Next = std::next(I)) {
2857
2858 auto First = I;
2859 auto Second = Next;
2860
2861 if ((*First).Order > (*Second).Order)
2862 std::swap(First, Second);
2863 CombineInfo &CI = *First;
2864 CombineInfo &Paired = *Second;
2865
2866 CombineInfo *Where = checkAndPrepareMerge(CI, Paired);
2867 if (!Where) {
2868 ++I;
2869 continue;
2870 }
2871
2872 Modified = true;
2873
2874 LLVM_DEBUG(dbgs() << "Merging: " << *CI.I << " with: " << *Paired.I);
2875
2877 switch (CI.InstClass) {
2878 default:
2879 llvm_unreachable("unknown InstClass");
2880 break;
2881 case DS_READ:
2882 NewMI = mergeRead2Pair(CI, Paired, Where->I);
2883 break;
2884 case DS_WRITE:
2885 NewMI = mergeWrite2Pair(CI, Paired, Where->I);
2886 break;
2887 case S_BUFFER_LOAD_IMM:
2888 case S_BUFFER_LOAD_SGPR_IMM:
2889 case S_LOAD_IMM:
2890 NewMI = mergeSMemLoadImmPair(CI, Paired, Where->I);
2891 OptimizeListAgain |= CI.Width + Paired.Width < 8;
2892 break;
2893 case BUFFER_LOAD:
2894 NewMI = mergeBufferLoadPair(CI, Paired, Where->I);
2895 OptimizeListAgain |= CI.Width + Paired.Width < 4;
2896 break;
2897 case BUFFER_STORE:
2898 NewMI = mergeBufferStorePair(CI, Paired, Where->I);
2899 OptimizeListAgain |= CI.Width + Paired.Width < 4;
2900 break;
2901 case MIMG:
2902 NewMI = mergeImagePair(CI, Paired, Where->I);
2903 OptimizeListAgain |= CI.Width + Paired.Width < 4;
2904 break;
2905 case TBUFFER_LOAD:
2906 NewMI = mergeTBufferLoadPair(CI, Paired, Where->I);
2907 OptimizeListAgain |= CI.Width + Paired.Width < 4;
2908 break;
2909 case TBUFFER_STORE:
2910 NewMI = mergeTBufferStorePair(CI, Paired, Where->I);
2911 OptimizeListAgain |= CI.Width + Paired.Width < 4;
2912 break;
2913 case FLAT_LOAD:
2914 case FLAT_LOAD_SADDR:
2915 case GLOBAL_LOAD:
2916 case GLOBAL_LOAD_SADDR:
2917 NewMI = mergeFlatLoadPair(CI, Paired, Where->I);
2918 OptimizeListAgain |= CI.Width + Paired.Width < 4;
2919 break;
2920 case FLAT_STORE:
2921 case FLAT_STORE_SADDR:
2922 case GLOBAL_STORE:
2923 case GLOBAL_STORE_SADDR:
2924 NewMI = mergeFlatStorePair(CI, Paired, Where->I);
2925 OptimizeListAgain |= CI.Width + Paired.Width < 4;
2926 break;
2927 }
2928 CI.setMI(NewMI, *this);
2929 CI.Order = Where->Order;
2930 if (I == Second)
2931 I = Next;
2932
2933 MergeList.erase(Second);
2934 }
2935
2936 return Modified;
2937}
2938
2939bool SILoadStoreOptimizerLegacy::runOnMachineFunction(MachineFunction &MF) {
2940 if (skipFunction(MF.getFunction()))
2941 return false;
2942 return SILoadStoreOptimizer(
2943 &getAnalysis<AAResultsWrapperPass>().getAAResults())
2944 .run(MF);
2945}
2946
2947bool SILoadStoreOptimizer::run(MachineFunction &MF) {
2948 STM = &MF.getSubtarget<GCNSubtarget>();
2949 if (!STM->loadStoreOptEnabled())
2950 return false;
2951
2952 TII = STM->getInstrInfo();
2953 TRI = &TII->getRegisterInfo();
2954
2955 MRI = &MF.getRegInfo();
2956
2957 LLVM_DEBUG(dbgs() << "Running SILoadStoreOptimizer\n");
2958
2959 bool Modified = false;
2960
2961 // Contains the list of instructions for which constant offsets are being
2962 // promoted to the IMM. This is tracked for an entire block at time.
2963 SmallPtrSet<MachineInstr *, 4> AnchorList;
2964 MemInfoMap Visited;
2965
2966 for (MachineBasicBlock &MBB : MF) {
2967 MachineBasicBlock::iterator SectionEnd;
2968 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
2969 I = SectionEnd) {
2970 bool CollectModified;
2971 std::list<std::list<CombineInfo>> MergeableInsts;
2972
2973 // First pass: Collect list of all instructions we know how to merge in a
2974 // subset of the block.
2975 std::tie(SectionEnd, CollectModified) =
2976 collectMergeableInsts(I, E, Visited, AnchorList, MergeableInsts);
2977
2978 Modified |= CollectModified;
2979
2980 do {
2981 OptimizeAgain = false;
2982 Modified |= optimizeBlock(MergeableInsts);
2983 } while (OptimizeAgain);
2984 }
2985
2986 Visited.clear();
2987 AnchorList.clear();
2988 }
2989
2990 return Modified;
2991}
2992
2993PreservedAnalyses
2996 MFPropsModifier _(*this, MF);
2997
2998 if (MF.getFunction().hasOptNone())
2999 return PreservedAnalyses::all();
3000
3002 .getManager();
3003 AAResults &AA = FAM.getResult<AAManager>(MF.getFunction());
3004
3005 bool Changed = SILoadStoreOptimizer(&AA).run(MF);
3006 if (!Changed)
3007 return PreservedAnalyses::all();
3008
3011 return PA;
3012}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
INITIALIZE_PASS(AMDGPUImageIntrinsicOptimizer, DEBUG_TYPE, "AMDGPU Image Intrinsic Optimizer", false, false) char AMDGPUImageIntrinsicOptimizer void addInstToMergeableList(IntrinsicInst *II, SmallVector< SmallVector< IntrinsicInst *, 4 > > &MergeableInsts, const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr)
BasicBlock::iterator collectMergeableInsts(BasicBlock::iterator I, BasicBlock::iterator E, SmallVector< SmallVector< IntrinsicInst *, 4 > > &MergeableInsts)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
#define op(i)
const HexagonInstrInfo * TII
#define _
static MaybeAlign getAlign(Value *Ptr)
IRTranslator LLVM IR MI
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
MachineInstr *& Lo
static uint32_t mostAlignedValueInRange(uint32_t Lo, uint32_t Hi)
static bool needsConstrainedOpcode(const GCNSubtarget &STM, ArrayRef< MachineMemOperand * > MMOs, unsigned Width)
static void addDefsUsesToList(const MachineInstr &MI, DenseSet< Register > &RegDefs, DenseSet< Register > &RegUses)
static unsigned getBufferFormatWithCompCount(unsigned OldFormat, unsigned ComponentCount, const GCNSubtarget &STI)
static bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, bool HasBranchDivergence, DomTreeUpdater *DTU)
#define LLVM_DEBUG(...)
Definition Debug.h:119
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A debug info location.
Definition DebugLoc.h:127
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:186
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:686
bool loadStoreOptEnabled() const
const SIInstrInfo * getInstrInfo() const override
bool hasDwordx3LoadStores() const
const SITargetLowering * getTargetLowering() const override
bool hasRelaxedTBufferOOBMode() const
bool ldsRequiresM0Init() const
Return if most LDS instructions have an m0 use that require m0 to be initialized.
bool hasFlatScratchSVSSwizzleBug() const
bool isXNACKEnabled() const
const HexagonRegisterInfo & getRegisterInfo() const
TypeSize getValue() const
unsigned getOpcode() const
Return the opcode number for this descriptor.
An RAII based helper class to modify MachineFunctionProperties when running pass.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const MachineInstrBuilder & cloneMergedMemRefs(ArrayRef< const MachineInstr * > OtherMIs) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
LLVM_ABI void dump() const
A description of a memory reference used in the backend.
LocationSize getSize() const
Return the size in bytes of the memory reference.
unsigned getAddrSpace() const
const MachinePointerInfo & getPointerInfo() const
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
static MachineOperand CreateImm(int64_t Val)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:152
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
static bool isFLATScratch(const MachineInstr &MI)
static bool isVIMAGE(const MachineInstr &MI)
static bool isFLATGlobal(const MachineInstr &MI)
static bool isVSAMPLE(const MachineInstr &MI)
static bool isFLAT(const MachineInstr &MI)
LLVM_READONLY MachineOperand * getNamedOperand(MachineInstr &MI, AMDGPU::OpName OperandName) const
Returns the operand named Op.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
uint64_t convertSMRDOffsetUnits(const MCSubtargetInfo &ST, uint64_t ByteOffset)
Convert ByteOffset to dwords if the subtarget uses dword SMRD immediate offsets.
bool getMTBUFHasSrsrc(unsigned Opc)
int getMTBUFElements(unsigned Opc)
bool getMTBUFHasSoffset(unsigned Opc)
int getMUBUFOpcode(unsigned BaseOpc, unsigned Elements)
int getMUBUFBaseOpcode(unsigned Opc)
LLVM_READONLY bool hasNamedOperand(uint32_t Opcode, OpName NamedIdx)
int getMTBUFBaseOpcode(unsigned Opc)
bool getMUBUFHasVAddr(unsigned Opc)
int getMTBUFOpcode(unsigned BaseOpc, unsigned Elements)
bool getMUBUFHasSoffset(unsigned Opc)
const MIMGBaseOpcodeInfo * getMIMGBaseOpcode(unsigned Opc)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
int getMaskedMIMGOp(unsigned Opc, unsigned NewChannels)
bool getMTBUFHasVAddr(unsigned Opc)
int getMUBUFElements(unsigned Opc)
const GcnBufferFormatInfo * getGcnBufferFormatInfo(uint8_t BitsPerComp, uint8_t NumComponents, uint8_t NumFormat, const MCSubtargetInfo &STI)
bool getMUBUFHasSrsrc(unsigned Opc)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:89
decltype(auto) getSingleElement(ContainerTy &&C)
Asserts that the given container has a single element and returns that element.
Definition STLExtras.h:309
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
char & SILoadStoreOptimizerLegacyID
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
DWARFExpression::Operation Op
std::vector< std::pair< LineLocation, FunctionId > > AnchorList
constexpr unsigned BitWidth
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881