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