1 //===-- SIFormMemoryClauses.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 /// \file 10 /// This pass creates bundles of SMEM and VMEM instructions forming memory 11 /// clauses if XNACK is enabled. Def operands of clauses are marked as early 12 /// clobber to make sure we will not override any source within a clause. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #include "AMDGPU.h" 17 #include "GCNRegPressure.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "llvm/InitializePasses.h" 20 21 using namespace llvm; 22 23 #define DEBUG_TYPE "si-form-memory-clauses" 24 25 // Clauses longer then 15 instructions would overflow one of the counters 26 // and stall. They can stall even earlier if there are outstanding counters. 27 static cl::opt<unsigned> 28 MaxClause("amdgpu-max-memory-clause", cl::Hidden, cl::init(15), 29 cl::desc("Maximum length of a memory clause, instructions")); 30 31 namespace { 32 33 class SIFormMemoryClauses : public MachineFunctionPass { 34 typedef DenseMap<unsigned, std::pair<unsigned, LaneBitmask>> RegUse; 35 36 public: 37 static char ID; 38 39 public: 40 SIFormMemoryClauses() : MachineFunctionPass(ID) { 41 initializeSIFormMemoryClausesPass(*PassRegistry::getPassRegistry()); 42 } 43 44 bool runOnMachineFunction(MachineFunction &MF) override; 45 46 StringRef getPassName() const override { 47 return "SI Form memory clauses"; 48 } 49 50 void getAnalysisUsage(AnalysisUsage &AU) const override { 51 AU.addRequired<LiveIntervals>(); 52 AU.setPreservesAll(); 53 MachineFunctionPass::getAnalysisUsage(AU); 54 } 55 56 MachineFunctionProperties getClearedProperties() const override { 57 return MachineFunctionProperties().set( 58 MachineFunctionProperties::Property::IsSSA); 59 } 60 61 private: 62 template <typename Callable> 63 void forAllLanes(Register Reg, LaneBitmask LaneMask, Callable Func) const; 64 65 bool canBundle(const MachineInstr &MI, const RegUse &Defs, 66 const RegUse &Uses) const; 67 bool checkPressure(const MachineInstr &MI, GCNDownwardRPTracker &RPT, 68 bool IsVMEMClause); 69 void collectRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses) const; 70 bool processRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses, 71 GCNDownwardRPTracker &RPT, bool IsVMEMClause); 72 73 const GCNSubtarget *ST; 74 const SIRegisterInfo *TRI; 75 const MachineRegisterInfo *MRI; 76 SIMachineFunctionInfo *MFI; 77 78 unsigned LastRecordedOccupancy; 79 unsigned MaxVGPRs; 80 unsigned MaxSGPRs; 81 }; 82 83 } // End anonymous namespace. 84 85 INITIALIZE_PASS_BEGIN(SIFormMemoryClauses, DEBUG_TYPE, 86 "SI Form memory clauses", false, false) 87 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 88 INITIALIZE_PASS_END(SIFormMemoryClauses, DEBUG_TYPE, 89 "SI Form memory clauses", false, false) 90 91 92 char SIFormMemoryClauses::ID = 0; 93 94 char &llvm::SIFormMemoryClausesID = SIFormMemoryClauses::ID; 95 96 FunctionPass *llvm::createSIFormMemoryClausesPass() { 97 return new SIFormMemoryClauses(); 98 } 99 100 static bool isVMEMClauseInst(const MachineInstr &MI) { 101 return SIInstrInfo::isFLAT(MI) || SIInstrInfo::isVMEM(MI); 102 } 103 104 static bool isSMEMClauseInst(const MachineInstr &MI) { 105 return SIInstrInfo::isSMRD(MI); 106 } 107 108 // There no sense to create store clauses, they do not define anything, 109 // thus there is nothing to set early-clobber. 110 static bool isValidClauseInst(const MachineInstr &MI, bool IsVMEMClause) { 111 assert(!MI.isDebugInstr() && "debug instructions should not reach here"); 112 if (MI.isBundled()) 113 return false; 114 if (!MI.mayLoad() || MI.mayStore()) 115 return false; 116 if (AMDGPU::getAtomicNoRetOp(MI.getOpcode()) != -1 || 117 AMDGPU::getAtomicRetOp(MI.getOpcode()) != -1) 118 return false; 119 if (IsVMEMClause && !isVMEMClauseInst(MI)) 120 return false; 121 if (!IsVMEMClause && !isSMEMClauseInst(MI)) 122 return false; 123 // If this is a load instruction where the result has been coalesced with an operand, then we cannot clause it. 124 for (const MachineOperand &ResMO : MI.defs()) { 125 Register ResReg = ResMO.getReg(); 126 for (const MachineOperand &MO : MI.uses()) { 127 if (!MO.isReg() || MO.isDef()) 128 continue; 129 if (MO.getReg() == ResReg) 130 return false; 131 } 132 break; // Only check the first def. 133 } 134 return true; 135 } 136 137 static unsigned getMopState(const MachineOperand &MO) { 138 unsigned S = 0; 139 if (MO.isImplicit()) 140 S |= RegState::Implicit; 141 if (MO.isDead()) 142 S |= RegState::Dead; 143 if (MO.isUndef()) 144 S |= RegState::Undef; 145 if (MO.isKill()) 146 S |= RegState::Kill; 147 if (MO.isEarlyClobber()) 148 S |= RegState::EarlyClobber; 149 if (MO.getReg().isPhysical() && MO.isRenamable()) 150 S |= RegState::Renamable; 151 return S; 152 } 153 154 template <typename Callable> 155 void SIFormMemoryClauses::forAllLanes(Register Reg, LaneBitmask LaneMask, 156 Callable Func) const { 157 if (LaneMask.all() || Reg.isPhysical() || 158 LaneMask == MRI->getMaxLaneMaskForVReg(Reg)) { 159 Func(0); 160 return; 161 } 162 163 const TargetRegisterClass *RC = MRI->getRegClass(Reg); 164 unsigned E = TRI->getNumSubRegIndices(); 165 SmallVector<unsigned, AMDGPU::NUM_TARGET_SUBREGS> CoveringSubregs; 166 for (unsigned Idx = 1; Idx < E; ++Idx) { 167 // Is this index even compatible with the given class? 168 if (TRI->getSubClassWithSubReg(RC, Idx) != RC) 169 continue; 170 LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(Idx); 171 // Early exit if we found a perfect match. 172 if (SubRegMask == LaneMask) { 173 Func(Idx); 174 return; 175 } 176 177 if ((SubRegMask & ~LaneMask).any() || (SubRegMask & LaneMask).none()) 178 continue; 179 180 CoveringSubregs.push_back(Idx); 181 } 182 183 llvm::sort(CoveringSubregs, [this](unsigned A, unsigned B) { 184 LaneBitmask MaskA = TRI->getSubRegIndexLaneMask(A); 185 LaneBitmask MaskB = TRI->getSubRegIndexLaneMask(B); 186 unsigned NA = MaskA.getNumLanes(); 187 unsigned NB = MaskB.getNumLanes(); 188 if (NA != NB) 189 return NA > NB; 190 return MaskA.getHighestLane() > MaskB.getHighestLane(); 191 }); 192 193 for (unsigned Idx : CoveringSubregs) { 194 LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(Idx); 195 if ((SubRegMask & ~LaneMask).any() || (SubRegMask & LaneMask).none()) 196 continue; 197 198 Func(Idx); 199 LaneMask &= ~SubRegMask; 200 if (LaneMask.none()) 201 return; 202 } 203 204 llvm_unreachable("Failed to find all subregs to cover lane mask"); 205 } 206 207 // Returns false if there is a use of a def already in the map. 208 // In this case we must break the clause. 209 bool SIFormMemoryClauses::canBundle(const MachineInstr &MI, const RegUse &Defs, 210 const RegUse &Uses) const { 211 // Check interference with defs. 212 for (const MachineOperand &MO : MI.operands()) { 213 // TODO: Prologue/Epilogue Insertion pass does not process bundled 214 // instructions. 215 if (MO.isFI()) 216 return false; 217 218 if (!MO.isReg()) 219 continue; 220 221 Register Reg = MO.getReg(); 222 223 // If it is tied we will need to write same register as we read. 224 if (MO.isTied()) 225 return false; 226 227 const RegUse &Map = MO.isDef() ? Uses : Defs; 228 auto Conflict = Map.find(Reg); 229 if (Conflict == Map.end()) 230 continue; 231 232 if (Reg.isPhysical()) 233 return false; 234 235 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(MO.getSubReg()); 236 if ((Conflict->second.second & Mask).any()) 237 return false; 238 } 239 240 return true; 241 } 242 243 // Since all defs in the clause are early clobber we can run out of registers. 244 // Function returns false if pressure would hit the limit if instruction is 245 // bundled into a memory clause. 246 bool SIFormMemoryClauses::checkPressure(const MachineInstr &MI, 247 GCNDownwardRPTracker &RPT, 248 bool IsVMEMClause) { 249 unsigned OldOccupancy = RPT.getCurrentOccupancy(*ST); 250 251 // NB: skip advanceBeforeNext() call. Since all defs will be marked 252 // early-clobber they will all stay alive at least to the end of the 253 // clause. Therefore we should not decrease pressure even if load pointer 254 // becomes dead and could otherwise be reused for destination. 255 RPT.advanceToNext(); 256 257 unsigned NewOccupancy = RPT.getCurrentOccupancy(*ST); 258 if (NewOccupancy < OldOccupancy && 259 NewOccupancy < MFI->getMinAllowedOccupancy()) 260 return false; 261 262 // Scalar loads/clauses cannot def VGPRs, and vector loads/clauses cannot def 263 // SGPRs (ignoring artificial implicit operands). 264 if (IsVMEMClause) { 265 if (RPT.getCurrentNumVGPR() > MaxVGPRs) 266 return false; 267 } else { 268 if (RPT.getCurrentNumSGPR() > MaxSGPRs) 269 return false; 270 } 271 272 LastRecordedOccupancy = NewOccupancy; 273 return true; 274 } 275 276 // Collect register defs and uses along with their lane masks and states. 277 void SIFormMemoryClauses::collectRegUses(const MachineInstr &MI, 278 RegUse &Defs, RegUse &Uses) const { 279 for (const MachineOperand &MO : MI.operands()) { 280 if (!MO.isReg()) 281 continue; 282 Register Reg = MO.getReg(); 283 if (!Reg) 284 continue; 285 286 LaneBitmask Mask = Reg.isVirtual() 287 ? TRI->getSubRegIndexLaneMask(MO.getSubReg()) 288 : LaneBitmask::getAll(); 289 RegUse &Map = MO.isDef() ? Defs : Uses; 290 291 auto Loc = Map.find(Reg); 292 unsigned State = getMopState(MO); 293 if (Loc == Map.end()) { 294 Map[Reg] = std::make_pair(State, Mask); 295 } else { 296 Loc->second.first |= State; 297 Loc->second.second |= Mask; 298 } 299 } 300 } 301 302 // Check register def/use conflicts, occupancy limits and collect def/use maps. 303 // Return true if instruction can be bundled with previous. It it cannot 304 // def/use maps are not updated. 305 bool SIFormMemoryClauses::processRegUses(const MachineInstr &MI, RegUse &Defs, 306 RegUse &Uses, 307 GCNDownwardRPTracker &RPT, 308 bool IsVMEMClause) { 309 if (!canBundle(MI, Defs, Uses)) 310 return false; 311 312 if (!checkPressure(MI, RPT, IsVMEMClause)) 313 return false; 314 315 collectRegUses(MI, Defs, Uses); 316 return true; 317 } 318 319 bool SIFormMemoryClauses::runOnMachineFunction(MachineFunction &MF) { 320 if (skipFunction(MF.getFunction())) 321 return false; 322 323 ST = &MF.getSubtarget<GCNSubtarget>(); 324 if (!ST->isXNACKEnabled()) 325 return false; 326 327 const SIInstrInfo *TII = ST->getInstrInfo(); 328 TRI = ST->getRegisterInfo(); 329 MRI = &MF.getRegInfo(); 330 MFI = MF.getInfo<SIMachineFunctionInfo>(); 331 LiveIntervals *LIS = &getAnalysis<LiveIntervals>(); 332 SlotIndexes *Ind = LIS->getSlotIndexes(); 333 bool Changed = false; 334 335 MaxVGPRs = TRI->getAllocatableSet(MF, &AMDGPU::VGPR_32RegClass).count(); 336 MaxSGPRs = TRI->getAllocatableSet(MF, &AMDGPU::SGPR_32RegClass).count(); 337 unsigned FuncMaxClause = AMDGPU::getIntegerAttribute( 338 MF.getFunction(), "amdgpu-max-memory-clause", MaxClause); 339 340 SmallVector<MachineInstr *> DbgInstrs; 341 342 for (MachineBasicBlock &MBB : MF) { 343 GCNDownwardRPTracker RPT(*LIS); 344 MachineBasicBlock::instr_iterator Next; 345 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; I = Next) { 346 MachineInstr &MI = *I; 347 Next = std::next(I); 348 349 if (MI.isDebugInstr()) 350 continue; 351 352 bool IsVMEM = isVMEMClauseInst(MI); 353 354 if (!isValidClauseInst(MI, IsVMEM)) 355 continue; 356 357 if (!RPT.getNext().isValid()) 358 RPT.reset(MI); 359 else { // Advance the state to the current MI. 360 RPT.advance(MachineBasicBlock::const_iterator(MI)); 361 RPT.advanceBeforeNext(); 362 } 363 364 const GCNRPTracker::LiveRegSet LiveRegsCopy(RPT.getLiveRegs()); 365 RegUse Defs, Uses; 366 if (!processRegUses(MI, Defs, Uses, RPT, IsVMEM)) { 367 RPT.reset(MI, &LiveRegsCopy); 368 continue; 369 } 370 371 unsigned Length = 1; 372 for ( ; Next != E && Length < FuncMaxClause; ++Next) { 373 // Debug instructions should not change the bundling. We need to move 374 // these after the bundle 375 if (Next->isDebugInstr()) 376 continue; 377 378 if (!isValidClauseInst(*Next, IsVMEM)) 379 break; 380 381 // A load from pointer which was loaded inside the same bundle is an 382 // impossible clause because we will need to write and read the same 383 // register inside. In this case processRegUses will return false. 384 if (!processRegUses(*Next, Defs, Uses, RPT, IsVMEM)) 385 break; 386 387 ++Length; 388 } 389 if (Length < 2) { 390 RPT.reset(MI, &LiveRegsCopy); 391 continue; 392 } 393 394 Changed = true; 395 MFI->limitOccupancy(LastRecordedOccupancy); 396 397 auto B = BuildMI(MBB, I, DebugLoc(), TII->get(TargetOpcode::BUNDLE)); 398 Ind->insertMachineInstrInMaps(*B); 399 400 // Restore the state after processing the bundle. 401 RPT.reset(*B, &LiveRegsCopy); 402 DbgInstrs.clear(); 403 404 auto BundleNext = I; 405 for (auto BI = I; BI != Next; BI = BundleNext) { 406 BundleNext = std::next(BI); 407 408 if (BI->isDebugValue()) { 409 DbgInstrs.push_back(BI->removeFromParent()); 410 continue; 411 } 412 413 BI->bundleWithPred(); 414 Ind->removeSingleMachineInstrFromMaps(*BI); 415 416 for (MachineOperand &MO : BI->defs()) 417 if (MO.readsReg()) 418 MO.setIsInternalRead(true); 419 } 420 421 // Replace any debug instructions after the new bundle. 422 for (MachineInstr *DbgInst : DbgInstrs) 423 MBB.insert(Next, DbgInst); 424 425 for (auto &&R : Defs) { 426 forAllLanes(R.first, R.second.second, [&R, &B](unsigned SubReg) { 427 unsigned S = R.second.first | RegState::EarlyClobber; 428 if (!SubReg) 429 S &= ~(RegState::Undef | RegState::Dead); 430 B.addDef(R.first, S, SubReg); 431 }); 432 } 433 434 for (auto &&R : Uses) { 435 forAllLanes(R.first, R.second.second, [&R, &B](unsigned SubReg) { 436 B.addUse(R.first, R.second.first & ~RegState::Kill, SubReg); 437 }); 438 } 439 440 for (auto &&R : Defs) { 441 Register Reg = R.first; 442 Uses.erase(Reg); 443 if (Reg.isPhysical()) 444 continue; 445 LIS->removeInterval(Reg); 446 LIS->createAndComputeVirtRegInterval(Reg); 447 } 448 449 for (auto &&R : Uses) { 450 Register Reg = R.first; 451 if (Reg.isPhysical()) 452 continue; 453 LIS->removeInterval(Reg); 454 LIS->createAndComputeVirtRegInterval(Reg); 455 } 456 } 457 } 458 459 return Changed; 460 } 461