1 //===-- SIModeRegister.cpp - Mode Register --------------------------------===// 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 /// \file 9 /// This pass inserts changes to the Mode register settings as required. 10 /// Note that currently it only deals with the Double Precision Floating Point 11 /// rounding mode setting, but is intended to be generic enough to be easily 12 /// expanded. 13 /// 14 //===----------------------------------------------------------------------===// 15 // 16 #include "AMDGPU.h" 17 #include "AMDGPUSubtarget.h" 18 #include "llvm/ADT/Statistic.h" 19 #include <queue> 20 21 #define DEBUG_TYPE "si-mode-register" 22 23 STATISTIC(NumSetregInserted, "Number of setreg of mode register inserted."); 24 25 using namespace llvm; 26 27 struct Status { 28 // Mask is a bitmask where a '1' indicates the corresponding Mode bit has a 29 // known value 30 unsigned Mask; 31 unsigned Mode; 32 33 Status() : Mask(0), Mode(0){}; 34 35 Status(unsigned NewMask, unsigned NewMode) : Mask(NewMask), Mode(NewMode) { 36 Mode &= Mask; 37 }; 38 39 // merge two status values such that only values that don't conflict are 40 // preserved 41 Status merge(const Status &S) const { 42 return Status((Mask | S.Mask), ((Mode & ~S.Mask) | (S.Mode & S.Mask))); 43 } 44 45 // merge an unknown value by using the unknown value's mask to remove bits 46 // from the result 47 Status mergeUnknown(unsigned newMask) { 48 return Status(Mask & ~newMask, Mode & ~newMask); 49 } 50 51 // intersect two Status values to produce a mode and mask that is a subset 52 // of both values 53 Status intersect(const Status &S) const { 54 unsigned NewMask = (Mask & S.Mask) & (Mode ^ ~S.Mode); 55 unsigned NewMode = (Mode & NewMask); 56 return Status(NewMask, NewMode); 57 } 58 59 // produce the delta required to change the Mode to the required Mode 60 Status delta(const Status &S) const { 61 return Status((S.Mask & (Mode ^ S.Mode)) | (~Mask & S.Mask), S.Mode); 62 } 63 64 bool operator==(const Status &S) const { 65 return (Mask == S.Mask) && (Mode == S.Mode); 66 } 67 68 bool operator!=(const Status &S) const { return !(*this == S); } 69 70 bool isCompatible(Status &S) { 71 return ((Mask & S.Mask) == S.Mask) && ((Mode & S.Mask) == S.Mode); 72 } 73 74 bool isCombinable(Status &S) { return !(Mask & S.Mask) || isCompatible(S); } 75 }; 76 77 class BlockData { 78 public: 79 // The Status that represents the mode register settings required by the 80 // FirstInsertionPoint (if any) in this block. Calculated in Phase 1. 81 Status Require; 82 83 // The Status that represents the net changes to the Mode register made by 84 // this block, Calculated in Phase 1. 85 Status Change; 86 87 // The Status that represents the mode register settings on exit from this 88 // block. Calculated in Phase 2. 89 Status Exit; 90 91 // The Status that represents the intersection of exit Mode register settings 92 // from all predecessor blocks. Calculated in Phase 2, and used by Phase 3. 93 Status Pred; 94 95 // In Phase 1 we record the first instruction that has a mode requirement, 96 // which is used in Phase 3 if we need to insert a mode change. 97 MachineInstr *FirstInsertionPoint; 98 99 // A flag to indicate whether an Exit value has been set (we can't tell by 100 // examining the Exit value itself as all values may be valid results). 101 bool ExitSet; 102 103 BlockData() : FirstInsertionPoint(nullptr), ExitSet(false){}; 104 }; 105 106 namespace { 107 108 class SIModeRegister : public MachineFunctionPass { 109 public: 110 static char ID; 111 112 std::vector<std::unique_ptr<BlockData>> BlockInfo; 113 std::queue<MachineBasicBlock *> Phase2List; 114 115 // The default mode register setting currently only caters for the floating 116 // point double precision rounding mode. 117 // We currently assume the default rounding mode is Round to Nearest 118 // NOTE: this should come from a per function rounding mode setting once such 119 // a setting exists. 120 unsigned DefaultMode = FP_ROUND_ROUND_TO_NEAREST; 121 Status DefaultStatus = 122 Status(FP_ROUND_MODE_DP(0x3), FP_ROUND_MODE_DP(DefaultMode)); 123 124 bool Changed = false; 125 126 public: 127 SIModeRegister() : MachineFunctionPass(ID) {} 128 129 bool runOnMachineFunction(MachineFunction &MF) override; 130 131 void getAnalysisUsage(AnalysisUsage &AU) const override { 132 AU.setPreservesCFG(); 133 MachineFunctionPass::getAnalysisUsage(AU); 134 } 135 136 void processBlockPhase1(MachineBasicBlock &MBB, const SIInstrInfo *TII); 137 138 void processBlockPhase2(MachineBasicBlock &MBB, const SIInstrInfo *TII); 139 140 void processBlockPhase3(MachineBasicBlock &MBB, const SIInstrInfo *TII); 141 142 Status getInstructionMode(MachineInstr &MI, const SIInstrInfo *TII); 143 144 void insertSetreg(MachineBasicBlock &MBB, MachineInstr *I, 145 const SIInstrInfo *TII, Status InstrMode); 146 }; 147 } // End anonymous namespace. 148 149 INITIALIZE_PASS(SIModeRegister, DEBUG_TYPE, 150 "Insert required mode register values", false, false) 151 152 char SIModeRegister::ID = 0; 153 154 char &llvm::SIModeRegisterID = SIModeRegister::ID; 155 156 FunctionPass *llvm::createSIModeRegisterPass() { return new SIModeRegister(); } 157 158 // Determine the Mode register setting required for this instruction. 159 // Instructions which don't use the Mode register return a null Status. 160 // Note this currently only deals with instructions that use the floating point 161 // double precision setting. 162 Status SIModeRegister::getInstructionMode(MachineInstr &MI, 163 const SIInstrInfo *TII) { 164 if (TII->usesFPDPRounding(MI)) { 165 switch (MI.getOpcode()) { 166 case AMDGPU::V_INTERP_P1LL_F16: 167 case AMDGPU::V_INTERP_P1LV_F16: 168 case AMDGPU::V_INTERP_P2_F16: 169 // f16 interpolation instructions need double precision round to zero 170 return Status(FP_ROUND_MODE_DP(3), 171 FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_ZERO)); 172 default: 173 return DefaultStatus; 174 } 175 } 176 return Status(); 177 } 178 179 // Insert a setreg instruction to update the Mode register. 180 // It is possible (though unlikely) for an instruction to require a change to 181 // the value of disjoint parts of the Mode register when we don't know the 182 // value of the intervening bits. In that case we need to use more than one 183 // setreg instruction. 184 void SIModeRegister::insertSetreg(MachineBasicBlock &MBB, MachineInstr *MI, 185 const SIInstrInfo *TII, Status InstrMode) { 186 while (InstrMode.Mask) { 187 unsigned Offset = countTrailingZeros<unsigned>(InstrMode.Mask); 188 unsigned Width = countTrailingOnes<unsigned>(InstrMode.Mask >> Offset); 189 unsigned Value = (InstrMode.Mode >> Offset) & ((1 << Width) - 1); 190 BuildMI(MBB, MI, 0, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 191 .addImm(Value) 192 .addImm(((Width - 1) << AMDGPU::Hwreg::WIDTH_M1_SHIFT_) | 193 (Offset << AMDGPU::Hwreg::OFFSET_SHIFT_) | 194 (AMDGPU::Hwreg::ID_MODE << AMDGPU::Hwreg::ID_SHIFT_)); 195 ++NumSetregInserted; 196 Changed = true; 197 InstrMode.Mask &= ~(((1 << Width) - 1) << Offset); 198 } 199 } 200 201 // In Phase 1 we iterate through the instructions of the block and for each 202 // instruction we get its mode usage. If the instruction uses the Mode register 203 // we: 204 // - update the Change status, which tracks the changes to the Mode register 205 // made by this block 206 // - if this instruction's requirements are compatible with the current setting 207 // of the Mode register we merge the modes 208 // - if it isn't compatible and an InsertionPoint isn't set, then we set the 209 // InsertionPoint to the current instruction, and we remember the current 210 // mode 211 // - if it isn't compatible and InsertionPoint is set we insert a seteg before 212 // that instruction (unless this instruction forms part of the block's 213 // entry requirements in which case the insertion is deferred until Phase 3 214 // when predecessor exit values are known), and move the insertion point to 215 // this instruction 216 // - if this is a setreg instruction we treat it as an incompatible instruction. 217 // This is sub-optimal but avoids some nasty corner cases, and is expected to 218 // occur very rarely. 219 // - on exit we have set the Require, Change, and initial Exit modes. 220 void SIModeRegister::processBlockPhase1(MachineBasicBlock &MBB, 221 const SIInstrInfo *TII) { 222 auto NewInfo = std::make_unique<BlockData>(); 223 MachineInstr *InsertionPoint = nullptr; 224 // RequirePending is used to indicate whether we are collecting the initial 225 // requirements for the block, and need to defer the first InsertionPoint to 226 // Phase 3. It is set to false once we have set FirstInsertionPoint, or when 227 // we discover an explict setreg that means this block doesn't have any 228 // initial requirements. 229 bool RequirePending = true; 230 Status IPChange; 231 for (MachineInstr &MI : MBB) { 232 Status InstrMode = getInstructionMode(MI, TII); 233 if (MI.getOpcode() == AMDGPU::S_SETREG_B32 || 234 MI.getOpcode() == AMDGPU::S_SETREG_B32_mode || 235 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 || 236 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32_mode) { 237 // We preserve any explicit mode register setreg instruction we encounter, 238 // as we assume it has been inserted by a higher authority (this is 239 // likely to be a very rare occurrence). 240 unsigned Dst = TII->getNamedOperand(MI, AMDGPU::OpName::simm16)->getImm(); 241 if (((Dst & AMDGPU::Hwreg::ID_MASK_) >> AMDGPU::Hwreg::ID_SHIFT_) != 242 AMDGPU::Hwreg::ID_MODE) 243 continue; 244 245 unsigned Width = ((Dst & AMDGPU::Hwreg::WIDTH_M1_MASK_) >> 246 AMDGPU::Hwreg::WIDTH_M1_SHIFT_) + 247 1; 248 unsigned Offset = 249 (Dst & AMDGPU::Hwreg::OFFSET_MASK_) >> AMDGPU::Hwreg::OFFSET_SHIFT_; 250 unsigned Mask = ((1 << Width) - 1) << Offset; 251 252 // If an InsertionPoint is set we will insert a setreg there. 253 if (InsertionPoint) { 254 insertSetreg(MBB, InsertionPoint, TII, IPChange.delta(NewInfo->Change)); 255 InsertionPoint = nullptr; 256 } 257 // If this is an immediate then we know the value being set, but if it is 258 // not an immediate then we treat the modified bits of the mode register 259 // as unknown. 260 if (MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 || 261 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32_mode) { 262 unsigned Val = TII->getNamedOperand(MI, AMDGPU::OpName::imm)->getImm(); 263 unsigned Mode = (Val << Offset) & Mask; 264 Status Setreg = Status(Mask, Mode); 265 // If we haven't already set the initial requirements for the block we 266 // don't need to as the requirements start from this explicit setreg. 267 RequirePending = false; 268 NewInfo->Change = NewInfo->Change.merge(Setreg); 269 } else { 270 NewInfo->Change = NewInfo->Change.mergeUnknown(Mask); 271 } 272 } else if (!NewInfo->Change.isCompatible(InstrMode)) { 273 // This instruction uses the Mode register and its requirements aren't 274 // compatible with the current mode. 275 if (InsertionPoint) { 276 // If the required mode change cannot be included in the current 277 // InsertionPoint changes, we need a setreg and start a new 278 // InsertionPoint. 279 if (!IPChange.delta(NewInfo->Change).isCombinable(InstrMode)) { 280 if (RequirePending) { 281 // This is the first insertionPoint in the block so we will defer 282 // the insertion of the setreg to Phase 3 where we know whether or 283 // not it is actually needed. 284 NewInfo->FirstInsertionPoint = InsertionPoint; 285 NewInfo->Require = NewInfo->Change; 286 RequirePending = false; 287 } else { 288 insertSetreg(MBB, InsertionPoint, TII, 289 IPChange.delta(NewInfo->Change)); 290 IPChange = NewInfo->Change; 291 } 292 // Set the new InsertionPoint 293 InsertionPoint = &MI; 294 } 295 NewInfo->Change = NewInfo->Change.merge(InstrMode); 296 } else { 297 // No InsertionPoint is currently set - this is either the first in 298 // the block or we have previously seen an explicit setreg. 299 InsertionPoint = &MI; 300 IPChange = NewInfo->Change; 301 NewInfo->Change = NewInfo->Change.merge(InstrMode); 302 } 303 } 304 } 305 if (RequirePending) { 306 // If we haven't yet set the initial requirements for the block we set them 307 // now. 308 NewInfo->FirstInsertionPoint = InsertionPoint; 309 NewInfo->Require = NewInfo->Change; 310 } else if (InsertionPoint) { 311 // We need to insert a setreg at the InsertionPoint 312 insertSetreg(MBB, InsertionPoint, TII, IPChange.delta(NewInfo->Change)); 313 } 314 NewInfo->Exit = NewInfo->Change; 315 BlockInfo[MBB.getNumber()] = std::move(NewInfo); 316 } 317 318 // In Phase 2 we revisit each block and calculate the common Mode register 319 // value provided by all predecessor blocks. If the Exit value for the block 320 // is changed, then we add the successor blocks to the worklist so that the 321 // exit value is propagated. 322 void SIModeRegister::processBlockPhase2(MachineBasicBlock &MBB, 323 const SIInstrInfo *TII) { 324 bool RevisitRequired = false; 325 bool ExitSet = false; 326 unsigned ThisBlock = MBB.getNumber(); 327 if (MBB.pred_empty()) { 328 // There are no predecessors, so use the default starting status. 329 BlockInfo[ThisBlock]->Pred = DefaultStatus; 330 ExitSet = true; 331 } else { 332 // Build a status that is common to all the predecessors by intersecting 333 // all the predecessor exit status values. 334 // Mask bits (which represent the Mode bits with a known value) can only be 335 // added by explicit SETREG instructions or the initial default value - 336 // the intersection process may remove Mask bits. 337 // If we find a predecessor that has not yet had an exit value determined 338 // (this can happen for example if a block is its own predecessor) we defer 339 // use of that value as the Mask will be all zero, and we will revisit this 340 // block again later (unless the only predecessor without an exit value is 341 // this block). 342 MachineBasicBlock::pred_iterator P = MBB.pred_begin(), E = MBB.pred_end(); 343 MachineBasicBlock &PB = *(*P); 344 unsigned PredBlock = PB.getNumber(); 345 if ((ThisBlock == PredBlock) && (std::next(P) == E)) { 346 BlockInfo[ThisBlock]->Pred = DefaultStatus; 347 ExitSet = true; 348 } else if (BlockInfo[PredBlock]->ExitSet) { 349 BlockInfo[ThisBlock]->Pred = BlockInfo[PredBlock]->Exit; 350 ExitSet = true; 351 } else if (PredBlock != ThisBlock) 352 RevisitRequired = true; 353 354 for (P = std::next(P); P != E; P = std::next(P)) { 355 MachineBasicBlock *Pred = *P; 356 unsigned PredBlock = Pred->getNumber(); 357 if (BlockInfo[PredBlock]->ExitSet) { 358 if (BlockInfo[ThisBlock]->ExitSet) { 359 BlockInfo[ThisBlock]->Pred = 360 BlockInfo[ThisBlock]->Pred.intersect(BlockInfo[PredBlock]->Exit); 361 } else { 362 BlockInfo[ThisBlock]->Pred = BlockInfo[PredBlock]->Exit; 363 } 364 ExitSet = true; 365 } else if (PredBlock != ThisBlock) 366 RevisitRequired = true; 367 } 368 } 369 Status TmpStatus = 370 BlockInfo[ThisBlock]->Pred.merge(BlockInfo[ThisBlock]->Change); 371 if (BlockInfo[ThisBlock]->Exit != TmpStatus) { 372 BlockInfo[ThisBlock]->Exit = TmpStatus; 373 // Add the successors to the work list so we can propagate the changed exit 374 // status. 375 for (MachineBasicBlock::succ_iterator S = MBB.succ_begin(), 376 E = MBB.succ_end(); 377 S != E; S = std::next(S)) { 378 MachineBasicBlock &B = *(*S); 379 Phase2List.push(&B); 380 } 381 } 382 BlockInfo[ThisBlock]->ExitSet = ExitSet; 383 if (RevisitRequired) 384 Phase2List.push(&MBB); 385 } 386 387 // In Phase 3 we revisit each block and if it has an insertion point defined we 388 // check whether the predecessor mode meets the block's entry requirements. If 389 // not we insert an appropriate setreg instruction to modify the Mode register. 390 void SIModeRegister::processBlockPhase3(MachineBasicBlock &MBB, 391 const SIInstrInfo *TII) { 392 unsigned ThisBlock = MBB.getNumber(); 393 if (!BlockInfo[ThisBlock]->Pred.isCompatible(BlockInfo[ThisBlock]->Require)) { 394 Status Delta = 395 BlockInfo[ThisBlock]->Pred.delta(BlockInfo[ThisBlock]->Require); 396 if (BlockInfo[ThisBlock]->FirstInsertionPoint) 397 insertSetreg(MBB, BlockInfo[ThisBlock]->FirstInsertionPoint, TII, Delta); 398 else 399 insertSetreg(MBB, &MBB.instr_front(), TII, Delta); 400 } 401 } 402 403 bool SIModeRegister::runOnMachineFunction(MachineFunction &MF) { 404 BlockInfo.resize(MF.getNumBlockIDs()); 405 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 406 const SIInstrInfo *TII = ST.getInstrInfo(); 407 408 // Processing is performed in a number of phases 409 410 // Phase 1 - determine the initial mode required by each block, and add setreg 411 // instructions for intra block requirements. 412 for (MachineBasicBlock &BB : MF) 413 processBlockPhase1(BB, TII); 414 415 // Phase 2 - determine the exit mode from each block. We add all blocks to the 416 // list here, but will also add any that need to be revisited during Phase 2 417 // processing. 418 for (MachineBasicBlock &BB : MF) 419 Phase2List.push(&BB); 420 while (!Phase2List.empty()) { 421 processBlockPhase2(*Phase2List.front(), TII); 422 Phase2List.pop(); 423 } 424 425 // Phase 3 - add an initial setreg to each block where the required entry mode 426 // is not satisfied by the exit mode of all its predecessors. 427 for (MachineBasicBlock &BB : MF) 428 processBlockPhase3(BB, TII); 429 430 BlockInfo.clear(); 431 432 return Changed; 433 } 434