1 //===-- SILoadStoreOptimizer.cpp ------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass tries to fuse DS instructions with close by immediate offsets. 11 // This will fuse operations such as 12 // ds_read_b32 v0, v2 offset:16 13 // ds_read_b32 v1, v2 offset:32 14 // ==> 15 // ds_read2_b32 v[0:1], v2, offset0:4 offset1:8 16 // 17 // 18 // Future improvements: 19 // 20 // - This currently relies on the scheduler to place loads and stores next to 21 // each other, and then only merges adjacent pairs of instructions. It would 22 // be good to be more flexible with interleaved instructions, and possibly run 23 // before scheduling. It currently missing stores of constants because loading 24 // the constant into the data register is placed between the stores, although 25 // this is arguably a scheduling problem. 26 // 27 // - Live interval recomputing seems inefficient. This currently only matches 28 // one pair, and recomputes live intervals and moves on to the next pair. It 29 // would be better to compute a list of all merges that need to occur. 30 // 31 // - With a list of instructions to process, we can also merge more. If a 32 // cluster of loads have offsets that are too large to fit in the 8-bit 33 // offsets, but are close enough to fit in the 8 bits, we can add to the base 34 // pointer and use the new reduced offsets. 35 // 36 //===----------------------------------------------------------------------===// 37 38 #include "AMDGPU.h" 39 #include "AMDGPUSubtarget.h" 40 #include "SIInstrInfo.h" 41 #include "SIRegisterInfo.h" 42 #include "Utils/AMDGPUBaseInfo.h" 43 #include "llvm/ADT/ArrayRef.h" 44 #include "llvm/ADT/SmallVector.h" 45 #include "llvm/ADT/StringRef.h" 46 #include "llvm/Analysis/AliasAnalysis.h" 47 #include "llvm/CodeGen/MachineBasicBlock.h" 48 #include "llvm/CodeGen/MachineFunction.h" 49 #include "llvm/CodeGen/MachineFunctionPass.h" 50 #include "llvm/CodeGen/MachineInstr.h" 51 #include "llvm/CodeGen/MachineInstrBuilder.h" 52 #include "llvm/CodeGen/MachineOperand.h" 53 #include "llvm/CodeGen/MachineRegisterInfo.h" 54 #include "llvm/IR/DebugLoc.h" 55 #include "llvm/Pass.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/MathExtras.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include "llvm/Target/TargetMachine.h" 60 #include <cassert> 61 #include <iterator> 62 #include <utility> 63 64 using namespace llvm; 65 66 #define DEBUG_TYPE "si-load-store-opt" 67 68 namespace { 69 70 class SILoadStoreOptimizer : public MachineFunctionPass { 71 72 typedef struct { 73 MachineBasicBlock::iterator I; 74 MachineBasicBlock::iterator Paired; 75 unsigned EltSize; 76 unsigned Offset0; 77 unsigned Offset1; 78 unsigned BaseOff; 79 bool UseST64; 80 SmallVector<MachineInstr*, 8> InstsToMove; 81 } CombineInfo; 82 83 private: 84 const SIInstrInfo *TII = nullptr; 85 const SIRegisterInfo *TRI = nullptr; 86 MachineRegisterInfo *MRI = nullptr; 87 AliasAnalysis *AA = nullptr; 88 89 static bool offsetsCanBeCombined(CombineInfo &CI); 90 91 bool findMatchingDSInst(CombineInfo &CI); 92 93 MachineBasicBlock::iterator mergeRead2Pair(CombineInfo &CI); 94 95 MachineBasicBlock::iterator mergeWrite2Pair(CombineInfo &CI); 96 97 public: 98 static char ID; 99 100 SILoadStoreOptimizer() : MachineFunctionPass(ID) { 101 initializeSILoadStoreOptimizerPass(*PassRegistry::getPassRegistry()); 102 } 103 104 bool optimizeBlock(MachineBasicBlock &MBB); 105 106 bool runOnMachineFunction(MachineFunction &MF) override; 107 108 StringRef getPassName() const override { return "SI Load / Store Optimizer"; } 109 110 void getAnalysisUsage(AnalysisUsage &AU) const override { 111 AU.setPreservesCFG(); 112 AU.addRequired<AAResultsWrapperPass>(); 113 114 MachineFunctionPass::getAnalysisUsage(AU); 115 } 116 }; 117 118 } // end anonymous namespace. 119 120 INITIALIZE_PASS_BEGIN(SILoadStoreOptimizer, DEBUG_TYPE, 121 "SI Load / Store Optimizer", false, false) 122 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 123 INITIALIZE_PASS_END(SILoadStoreOptimizer, DEBUG_TYPE, 124 "SI Load / Store Optimizer", false, false) 125 126 char SILoadStoreOptimizer::ID = 0; 127 128 char &llvm::SILoadStoreOptimizerID = SILoadStoreOptimizer::ID; 129 130 FunctionPass *llvm::createSILoadStoreOptimizerPass() { 131 return new SILoadStoreOptimizer(); 132 } 133 134 static void moveInstsAfter(MachineBasicBlock::iterator I, 135 ArrayRef<MachineInstr*> InstsToMove) { 136 MachineBasicBlock *MBB = I->getParent(); 137 ++I; 138 for (MachineInstr *MI : InstsToMove) { 139 MI->removeFromParent(); 140 MBB->insert(I, MI); 141 } 142 } 143 144 static void addDefsToList(const MachineInstr &MI, 145 SmallVectorImpl<const MachineOperand *> &Defs) { 146 for (const MachineOperand &Def : MI.defs()) { 147 Defs.push_back(&Def); 148 } 149 } 150 151 static bool memAccessesCanBeReordered(MachineBasicBlock::iterator A, 152 MachineBasicBlock::iterator B, 153 const SIInstrInfo *TII, 154 AliasAnalysis * AA) { 155 return (TII->areMemAccessesTriviallyDisjoint(*A, *B, AA) || 156 // RAW or WAR - cannot reorder 157 // WAW - cannot reorder 158 // RAR - safe to reorder 159 !(A->mayStore() || B->mayStore())); 160 } 161 162 // Add MI and its defs to the lists if MI reads one of the defs that are 163 // already in the list. Returns true in that case. 164 static bool 165 addToListsIfDependent(MachineInstr &MI, 166 SmallVectorImpl<const MachineOperand *> &Defs, 167 SmallVectorImpl<MachineInstr*> &Insts) { 168 for (const MachineOperand *Def : Defs) { 169 bool ReadDef = MI.readsVirtualRegister(Def->getReg()); 170 // If ReadDef is true, then there is a use of Def between I 171 // and the instruction that I will potentially be merged with. We 172 // will need to move this instruction after the merged instructions. 173 if (ReadDef) { 174 Insts.push_back(&MI); 175 addDefsToList(MI, Defs); 176 return true; 177 } 178 } 179 180 return false; 181 } 182 183 static bool 184 canMoveInstsAcrossMemOp(MachineInstr &MemOp, 185 ArrayRef<MachineInstr*> InstsToMove, 186 const SIInstrInfo *TII, 187 AliasAnalysis *AA) { 188 assert(MemOp.mayLoadOrStore()); 189 190 for (MachineInstr *InstToMove : InstsToMove) { 191 if (!InstToMove->mayLoadOrStore()) 192 continue; 193 if (!memAccessesCanBeReordered(MemOp, *InstToMove, TII, AA)) 194 return false; 195 } 196 return true; 197 } 198 199 bool SILoadStoreOptimizer::offsetsCanBeCombined(CombineInfo &CI) { 200 // XXX - Would the same offset be OK? Is there any reason this would happen or 201 // be useful? 202 if (CI.Offset0 == CI.Offset1) 203 return false; 204 205 // This won't be valid if the offset isn't aligned. 206 if ((CI.Offset0 % CI.EltSize != 0) || (CI.Offset1 % CI.EltSize != 0)) 207 return false; 208 209 unsigned EltOffset0 = CI.Offset0 / CI.EltSize; 210 unsigned EltOffset1 = CI.Offset1 / CI.EltSize; 211 CI.UseST64 = false; 212 CI.BaseOff = 0; 213 214 // If the offset in elements doesn't fit in 8-bits, we might be able to use 215 // the stride 64 versions. 216 if ((EltOffset0 % 64 == 0) && (EltOffset1 % 64) == 0 && 217 isUInt<8>(EltOffset0 / 64) && isUInt<8>(EltOffset1 / 64)) { 218 CI.Offset0 = EltOffset0 / 64; 219 CI.Offset1 = EltOffset1 / 64; 220 CI.UseST64 = true; 221 return true; 222 } 223 224 // Check if the new offsets fit in the reduced 8-bit range. 225 if (isUInt<8>(EltOffset0) && isUInt<8>(EltOffset1)) { 226 CI.Offset0 = EltOffset0; 227 CI.Offset1 = EltOffset1; 228 return true; 229 } 230 231 // Try to shift base address to decrease offsets. 232 unsigned OffsetDiff = std::abs((int)EltOffset1 - (int)EltOffset0); 233 CI.BaseOff = std::min(CI.Offset0, CI.Offset1); 234 235 if ((OffsetDiff % 64 == 0) && isUInt<8>(OffsetDiff / 64)) { 236 CI.Offset0 = (EltOffset0 - CI.BaseOff / CI.EltSize) / 64; 237 CI.Offset1 = (EltOffset1 - CI.BaseOff / CI.EltSize) / 64; 238 CI.UseST64 = true; 239 return true; 240 } 241 242 if (isUInt<8>(OffsetDiff)) { 243 CI.Offset0 = EltOffset0 - CI.BaseOff / CI.EltSize; 244 CI.Offset1 = EltOffset1 - CI.BaseOff / CI.EltSize; 245 return true; 246 } 247 248 return false; 249 } 250 251 bool SILoadStoreOptimizer::findMatchingDSInst(CombineInfo &CI) { 252 MachineBasicBlock::iterator E = CI.I->getParent()->end(); 253 MachineBasicBlock::iterator MBBI = CI.I; 254 ++MBBI; 255 256 SmallVector<const MachineOperand *, 8> DefsToMove; 257 addDefsToList(*CI.I, DefsToMove); 258 259 for ( ; MBBI != E; ++MBBI) { 260 if (MBBI->getOpcode() != CI.I->getOpcode()) { 261 262 // This is not a matching DS instruction, but we can keep looking as 263 // long as one of these conditions are met: 264 // 1. It is safe to move I down past MBBI. 265 // 2. It is safe to move MBBI down past the instruction that I will 266 // be merged into. 267 268 if (MBBI->hasUnmodeledSideEffects()) 269 // We can't re-order this instruction with respect to other memory 270 // opeations, so we fail both conditions mentioned above. 271 return false; 272 273 if (MBBI->mayLoadOrStore() && 274 !memAccessesCanBeReordered(*CI.I, *MBBI, TII, AA)) { 275 // We fail condition #1, but we may still be able to satisfy condition 276 // #2. Add this instruction to the move list and then we will check 277 // if condition #2 holds once we have selected the matching instruction. 278 CI.InstsToMove.push_back(&*MBBI); 279 addDefsToList(*MBBI, DefsToMove); 280 continue; 281 } 282 283 // When we match I with another DS instruction we will be moving I down 284 // to the location of the matched instruction any uses of I will need to 285 // be moved down as well. 286 addToListsIfDependent(*MBBI, DefsToMove, CI.InstsToMove); 287 continue; 288 } 289 290 // Don't merge volatiles. 291 if (MBBI->hasOrderedMemoryRef()) 292 return false; 293 294 // Handle a case like 295 // DS_WRITE_B32 addr, v, idx0 296 // w = DS_READ_B32 addr, idx0 297 // DS_WRITE_B32 addr, f(w), idx1 298 // where the DS_READ_B32 ends up in InstsToMove and therefore prevents 299 // merging of the two writes. 300 if (addToListsIfDependent(*MBBI, DefsToMove, CI.InstsToMove)) 301 continue; 302 303 int AddrIdx = AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), 304 AMDGPU::OpName::addr); 305 const MachineOperand &AddrReg0 = CI.I->getOperand(AddrIdx); 306 const MachineOperand &AddrReg1 = MBBI->getOperand(AddrIdx); 307 308 // Check same base pointer. Be careful of subregisters, which can occur with 309 // vectors of pointers. 310 if (AddrReg0.getReg() == AddrReg1.getReg() && 311 AddrReg0.getSubReg() == AddrReg1.getSubReg()) { 312 int OffsetIdx = AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), 313 AMDGPU::OpName::offset); 314 CI.Offset0 = CI.I->getOperand(OffsetIdx).getImm() & 0xffff; 315 CI.Offset1 = MBBI->getOperand(OffsetIdx).getImm() & 0xffff; 316 CI.Paired = MBBI; 317 318 // Check both offsets fit in the reduced range. 319 // We also need to go through the list of instructions that we plan to 320 // move and make sure they are all safe to move down past the merged 321 // instruction. 322 if (offsetsCanBeCombined(CI)) 323 if (canMoveInstsAcrossMemOp(*MBBI, CI.InstsToMove, TII, AA)) 324 return true; 325 } 326 327 // We've found a load/store that we couldn't merge for some reason. 328 // We could potentially keep looking, but we'd need to make sure that 329 // it was safe to move I and also all the instruction in InstsToMove 330 // down past this instruction. 331 // check if we can move I across MBBI and if we can move all I's users 332 if (!memAccessesCanBeReordered(*CI.I, *MBBI, TII, AA) || 333 !canMoveInstsAcrossMemOp(*MBBI, CI.InstsToMove, TII, AA)) 334 break; 335 } 336 return false; 337 } 338 339 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeRead2Pair( 340 CombineInfo &CI) { 341 MachineBasicBlock *MBB = CI.I->getParent(); 342 343 // Be careful, since the addresses could be subregisters themselves in weird 344 // cases, like vectors of pointers. 345 const auto *AddrReg = TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr); 346 347 const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdst); 348 const auto *Dest1 = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::vdst); 349 350 unsigned NewOffset0 = CI.Offset0; 351 unsigned NewOffset1 = CI.Offset1; 352 unsigned Opc = (CI.EltSize == 4) ? AMDGPU::DS_READ2_B32 353 : AMDGPU::DS_READ2_B64; 354 355 if (CI.UseST64) 356 Opc = (CI.EltSize == 4) ? AMDGPU::DS_READ2ST64_B32 357 : AMDGPU::DS_READ2ST64_B64; 358 359 unsigned SubRegIdx0 = (CI.EltSize == 4) ? AMDGPU::sub0 : AMDGPU::sub0_sub1; 360 unsigned SubRegIdx1 = (CI.EltSize == 4) ? AMDGPU::sub1 : AMDGPU::sub2_sub3; 361 362 if (NewOffset0 > NewOffset1) { 363 // Canonicalize the merged instruction so the smaller offset comes first. 364 std::swap(NewOffset0, NewOffset1); 365 std::swap(SubRegIdx0, SubRegIdx1); 366 } 367 368 assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) && 369 (NewOffset0 != NewOffset1) && 370 "Computed offset doesn't fit"); 371 372 const MCInstrDesc &Read2Desc = TII->get(Opc); 373 374 const TargetRegisterClass *SuperRC 375 = (CI.EltSize == 4) ? &AMDGPU::VReg_64RegClass : &AMDGPU::VReg_128RegClass; 376 unsigned DestReg = MRI->createVirtualRegister(SuperRC); 377 378 DebugLoc DL = CI.I->getDebugLoc(); 379 380 unsigned BaseReg = AddrReg->getReg(); 381 unsigned BaseRegFlags = 0; 382 if (CI.BaseOff) { 383 BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass); 384 BaseRegFlags = RegState::Kill; 385 BuildMI(*MBB, CI.Paired, DL, TII->get(AMDGPU::V_ADD_I32_e32), BaseReg) 386 .addImm(CI.BaseOff) 387 .addReg(AddrReg->getReg()); 388 } 389 390 MachineInstrBuilder Read2 = 391 BuildMI(*MBB, CI.Paired, DL, Read2Desc, DestReg) 392 .addReg(BaseReg, BaseRegFlags) // addr 393 .addImm(NewOffset0) // offset0 394 .addImm(NewOffset1) // offset1 395 .addImm(0) // gds 396 .setMemRefs(CI.I->mergeMemRefsWith(*CI.Paired)); 397 398 (void)Read2; 399 400 const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY); 401 402 // Copy to the old destination registers. 403 BuildMI(*MBB, CI.Paired, DL, CopyDesc) 404 .add(*Dest0) // Copy to same destination including flags and sub reg. 405 .addReg(DestReg, 0, SubRegIdx0); 406 MachineInstr *Copy1 = BuildMI(*MBB, CI.Paired, DL, CopyDesc) 407 .add(*Dest1) 408 .addReg(DestReg, RegState::Kill, SubRegIdx1); 409 410 moveInstsAfter(Copy1, CI.InstsToMove); 411 412 MachineBasicBlock::iterator Next = std::next(CI.I); 413 CI.I->eraseFromParent(); 414 CI.Paired->eraseFromParent(); 415 416 DEBUG(dbgs() << "Inserted read2: " << *Read2 << '\n'); 417 return Next; 418 } 419 420 MachineBasicBlock::iterator SILoadStoreOptimizer::mergeWrite2Pair( 421 CombineInfo &CI) { 422 MachineBasicBlock *MBB = CI.I->getParent(); 423 424 // Be sure to use .addOperand(), and not .addReg() with these. We want to be 425 // sure we preserve the subregister index and any register flags set on them. 426 const MachineOperand *Addr = TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr); 427 const MachineOperand *Data0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::data0); 428 const MachineOperand *Data1 429 = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::data0); 430 431 unsigned NewOffset0 = CI.Offset0; 432 unsigned NewOffset1 = CI.Offset1; 433 unsigned Opc = (CI.EltSize == 4) ? AMDGPU::DS_WRITE2_B32 434 : AMDGPU::DS_WRITE2_B64; 435 436 if (CI.UseST64) 437 Opc = (CI.EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32 438 : AMDGPU::DS_WRITE2ST64_B64; 439 440 if (NewOffset0 > NewOffset1) { 441 // Canonicalize the merged instruction so the smaller offset comes first. 442 std::swap(NewOffset0, NewOffset1); 443 std::swap(Data0, Data1); 444 } 445 446 assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) && 447 (NewOffset0 != NewOffset1) && 448 "Computed offset doesn't fit"); 449 450 const MCInstrDesc &Write2Desc = TII->get(Opc); 451 DebugLoc DL = CI.I->getDebugLoc(); 452 453 unsigned BaseReg = Addr->getReg(); 454 unsigned BaseRegFlags = 0; 455 if (CI.BaseOff) { 456 BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass); 457 BaseRegFlags = RegState::Kill; 458 BuildMI(*MBB, CI.Paired, DL, TII->get(AMDGPU::V_ADD_I32_e32), BaseReg) 459 .addImm(CI.BaseOff) 460 .addReg(Addr->getReg()); 461 } 462 463 MachineInstrBuilder Write2 = 464 BuildMI(*MBB, CI.Paired, DL, Write2Desc) 465 .addReg(BaseReg, BaseRegFlags) // addr 466 .add(*Data0) // data0 467 .add(*Data1) // data1 468 .addImm(NewOffset0) // offset0 469 .addImm(NewOffset1) // offset1 470 .addImm(0) // gds 471 .setMemRefs(CI.I->mergeMemRefsWith(*CI.Paired)); 472 473 moveInstsAfter(Write2, CI.InstsToMove); 474 475 MachineBasicBlock::iterator Next = std::next(CI.I); 476 CI.I->eraseFromParent(); 477 CI.Paired->eraseFromParent(); 478 479 DEBUG(dbgs() << "Inserted write2 inst: " << *Write2 << '\n'); 480 return Next; 481 } 482 483 // Scan through looking for adjacent LDS operations with constant offsets from 484 // the same base register. We rely on the scheduler to do the hard work of 485 // clustering nearby loads, and assume these are all adjacent. 486 bool SILoadStoreOptimizer::optimizeBlock(MachineBasicBlock &MBB) { 487 bool Modified = false; 488 489 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) { 490 MachineInstr &MI = *I; 491 492 // Don't combine if volatile. 493 if (MI.hasOrderedMemoryRef()) { 494 ++I; 495 continue; 496 } 497 498 CombineInfo CI; 499 CI.I = I; 500 unsigned Opc = MI.getOpcode(); 501 if (Opc == AMDGPU::DS_READ_B32 || Opc == AMDGPU::DS_READ_B64) { 502 CI.EltSize = (Opc == AMDGPU::DS_READ_B64) ? 8 : 4; 503 if (findMatchingDSInst(CI)) { 504 Modified = true; 505 I = mergeRead2Pair(CI); 506 } else { 507 ++I; 508 } 509 510 continue; 511 } else if (Opc == AMDGPU::DS_WRITE_B32 || Opc == AMDGPU::DS_WRITE_B64) { 512 CI.EltSize = (Opc == AMDGPU::DS_WRITE_B64) ? 8 : 4; 513 if (findMatchingDSInst(CI)) { 514 Modified = true; 515 I = mergeWrite2Pair(CI); 516 } else { 517 ++I; 518 } 519 520 continue; 521 } 522 523 ++I; 524 } 525 526 return Modified; 527 } 528 529 bool SILoadStoreOptimizer::runOnMachineFunction(MachineFunction &MF) { 530 if (skipFunction(*MF.getFunction())) 531 return false; 532 533 const SISubtarget &STM = MF.getSubtarget<SISubtarget>(); 534 if (!STM.loadStoreOptEnabled()) 535 return false; 536 537 TII = STM.getInstrInfo(); 538 TRI = &TII->getRegisterInfo(); 539 540 MRI = &MF.getRegInfo(); 541 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 542 543 DEBUG(dbgs() << "Running SILoadStoreOptimizer\n"); 544 545 bool Modified = false; 546 547 for (MachineBasicBlock &MBB : MF) 548 Modified |= optimizeBlock(MBB); 549 550 return Modified; 551 } 552