1 //===-- SIWholeQuadMode.cpp - enter and suspend whole quad mode -----------===// 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 /// \file 11 /// \brief This pass adds instructions to enable whole quad mode for pixel 12 /// shaders. 13 /// 14 /// Whole quad mode is required for derivative computations, but it interferes 15 /// with shader side effects (stores and atomics). This pass is run on the 16 /// scheduled machine IR but before register coalescing, so that machine SSA is 17 /// available for analysis. It ensures that WQM is enabled when necessary, but 18 /// disabled around stores and atomics. 19 /// 20 /// When necessary, this pass creates a function prolog 21 /// 22 /// S_MOV_B64 LiveMask, EXEC 23 /// S_WQM_B64 EXEC, EXEC 24 /// 25 /// to enter WQM at the top of the function and surrounds blocks of Exact 26 /// instructions by 27 /// 28 /// S_AND_SAVEEXEC_B64 Tmp, LiveMask 29 /// ... 30 /// S_MOV_B64 EXEC, Tmp 31 /// 32 /// In order to avoid excessive switching during sequences of Exact 33 /// instructions, the pass first analyzes which instructions must be run in WQM 34 /// (aka which instructions produce values that lead to derivative 35 /// computations). 36 /// 37 /// Basic blocks are always exited in WQM as long as some successor needs WQM. 38 /// 39 /// There is room for improvement given better control flow analysis: 40 /// 41 /// (1) at the top level (outside of control flow statements, and as long as 42 /// kill hasn't been used), one SGPR can be saved by recovering WQM from 43 /// the LiveMask (this is implemented for the entry block). 44 /// 45 /// (2) when entire regions (e.g. if-else blocks or entire loops) only 46 /// consist of exact and don't-care instructions, the switch only has to 47 /// be done at the entry and exit points rather than potentially in each 48 /// block of the region. 49 /// 50 //===----------------------------------------------------------------------===// 51 52 #include "AMDGPU.h" 53 #include "AMDGPUSubtarget.h" 54 #include "SIInstrInfo.h" 55 #include "SIMachineFunctionInfo.h" 56 #include "llvm/CodeGen/MachineFunction.h" 57 #include "llvm/CodeGen/MachineFunctionPass.h" 58 #include "llvm/CodeGen/MachineInstrBuilder.h" 59 #include "llvm/CodeGen/MachineRegisterInfo.h" 60 61 using namespace llvm; 62 63 #define DEBUG_TYPE "si-wqm" 64 65 namespace { 66 67 enum { 68 StateWQM = 0x1, 69 StateExact = 0x2, 70 }; 71 72 struct InstrInfo { 73 char Needs = 0; 74 char OutNeeds = 0; 75 }; 76 77 struct BlockInfo { 78 char Needs = 0; 79 char InNeeds = 0; 80 char OutNeeds = 0; 81 }; 82 83 struct WorkItem { 84 MachineBasicBlock *MBB = nullptr; 85 MachineInstr *MI = nullptr; 86 87 WorkItem() {} 88 WorkItem(MachineBasicBlock *MBB) : MBB(MBB) {} 89 WorkItem(MachineInstr *MI) : MI(MI) {} 90 }; 91 92 class SIWholeQuadMode : public MachineFunctionPass { 93 private: 94 const SIInstrInfo *TII; 95 const SIRegisterInfo *TRI; 96 MachineRegisterInfo *MRI; 97 LiveIntervals *LIS; 98 99 DenseMap<const MachineInstr *, InstrInfo> Instructions; 100 DenseMap<MachineBasicBlock *, BlockInfo> Blocks; 101 SmallVector<const MachineInstr *, 2> ExecExports; 102 SmallVector<MachineInstr *, 1> LiveMaskQueries; 103 104 void markInstruction(MachineInstr &MI, char Flag, 105 std::vector<WorkItem> &Worklist); 106 char scanInstructions(MachineFunction &MF, std::vector<WorkItem> &Worklist); 107 void propagateInstruction(MachineInstr &MI, std::vector<WorkItem> &Worklist); 108 void propagateBlock(MachineBasicBlock &MBB, std::vector<WorkItem> &Worklist); 109 char analyzeFunction(MachineFunction &MF); 110 111 void toExact(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before, 112 unsigned SaveWQM, unsigned LiveMaskReg); 113 void toWQM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before, 114 unsigned SavedWQM); 115 void processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg, bool isEntry); 116 117 void lowerLiveMaskQueries(unsigned LiveMaskReg); 118 119 public: 120 static char ID; 121 122 SIWholeQuadMode() : 123 MachineFunctionPass(ID) { } 124 125 bool runOnMachineFunction(MachineFunction &MF) override; 126 127 const char *getPassName() const override { 128 return "SI Whole Quad Mode"; 129 } 130 131 void getAnalysisUsage(AnalysisUsage &AU) const override { 132 AU.addRequired<LiveIntervals>(); 133 AU.setPreservesCFG(); 134 MachineFunctionPass::getAnalysisUsage(AU); 135 } 136 }; 137 138 } // End anonymous namespace 139 140 char SIWholeQuadMode::ID = 0; 141 142 INITIALIZE_PASS_BEGIN(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false, 143 false) 144 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 145 INITIALIZE_PASS_END(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false, 146 false) 147 148 char &llvm::SIWholeQuadModeID = SIWholeQuadMode::ID; 149 150 FunctionPass *llvm::createSIWholeQuadModePass() { 151 return new SIWholeQuadMode; 152 } 153 154 void SIWholeQuadMode::markInstruction(MachineInstr &MI, char Flag, 155 std::vector<WorkItem> &Worklist) { 156 InstrInfo &II = Instructions[&MI]; 157 158 assert(Flag == StateWQM || Flag == StateExact); 159 160 // Ignore if the instruction is already marked. The typical case is that we 161 // mark an instruction WQM multiple times, but for atomics it can happen that 162 // Flag is StateWQM, but Needs is already set to StateExact. In this case, 163 // letting the atomic run in StateExact is correct as per the relevant specs. 164 if (II.Needs) 165 return; 166 167 II.Needs = Flag; 168 Worklist.push_back(&MI); 169 } 170 171 // Scan instructions to determine which ones require an Exact execmask and 172 // which ones seed WQM requirements. 173 char SIWholeQuadMode::scanInstructions(MachineFunction &MF, 174 std::vector<WorkItem> &Worklist) { 175 char GlobalFlags = 0; 176 bool WQMOutputs = MF.getFunction()->hasFnAttribute("amdgpu-ps-wqm-outputs"); 177 178 for (auto BI = MF.begin(), BE = MF.end(); BI != BE; ++BI) { 179 MachineBasicBlock &MBB = *BI; 180 181 for (auto II = MBB.begin(), IE = MBB.end(); II != IE; ++II) { 182 MachineInstr &MI = *II; 183 unsigned Opcode = MI.getOpcode(); 184 char Flags = 0; 185 186 if (TII->isWQM(Opcode) || TII->isDS(Opcode)) { 187 Flags = StateWQM; 188 } else if (TII->isDisableWQM(MI)) { 189 Flags = StateExact; 190 } else { 191 // Handle export instructions with the exec mask valid flag set 192 if (Opcode == AMDGPU::EXP) { 193 if (MI.getOperand(4).getImm() != 0) 194 ExecExports.push_back(&MI); 195 } else if (Opcode == AMDGPU::SI_PS_LIVE) { 196 LiveMaskQueries.push_back(&MI); 197 } else if (WQMOutputs) { 198 // The function is in machine SSA form, which means that physical 199 // VGPRs correspond to shader inputs and outputs. Inputs are 200 // only used, outputs are only defined. 201 for (const MachineOperand &MO : MI.defs()) { 202 if (!MO.isReg()) 203 continue; 204 205 unsigned Reg = MO.getReg(); 206 207 if (!TRI->isVirtualRegister(Reg) && 208 TRI->hasVGPRs(TRI->getPhysRegClass(Reg))) { 209 Flags = StateWQM; 210 break; 211 } 212 } 213 } 214 215 if (!Flags) 216 continue; 217 } 218 219 markInstruction(MI, Flags, Worklist); 220 GlobalFlags |= Flags; 221 } 222 } 223 224 return GlobalFlags; 225 } 226 227 void SIWholeQuadMode::propagateInstruction(MachineInstr &MI, 228 std::vector<WorkItem>& Worklist) { 229 MachineBasicBlock *MBB = MI.getParent(); 230 InstrInfo II = Instructions[&MI]; // take a copy to prevent dangling references 231 BlockInfo &BI = Blocks[MBB]; 232 233 // Control flow-type instructions and stores to temporary memory that are 234 // followed by WQM computations must themselves be in WQM. 235 if ((II.OutNeeds & StateWQM) && !II.Needs && 236 (MI.isTerminator() || (TII->usesVM_CNT(MI) && MI.mayStore()))) { 237 Instructions[&MI].Needs = StateWQM; 238 II.Needs = StateWQM; 239 } 240 241 // Propagate to block level 242 BI.Needs |= II.Needs; 243 if ((BI.InNeeds | II.Needs) != BI.InNeeds) { 244 BI.InNeeds |= II.Needs; 245 Worklist.push_back(MBB); 246 } 247 248 // Propagate backwards within block 249 if (MachineInstr *PrevMI = MI.getPrevNode()) { 250 char InNeeds = II.Needs | II.OutNeeds; 251 if (!PrevMI->isPHI()) { 252 InstrInfo &PrevII = Instructions[PrevMI]; 253 if ((PrevII.OutNeeds | InNeeds) != PrevII.OutNeeds) { 254 PrevII.OutNeeds |= InNeeds; 255 Worklist.push_back(PrevMI); 256 } 257 } 258 } 259 260 // Propagate WQM flag to instruction inputs 261 assert(II.Needs != (StateWQM | StateExact)); 262 if (II.Needs != StateWQM) 263 return; 264 265 for (const MachineOperand &Use : MI.uses()) { 266 if (!Use.isReg() || !Use.isUse()) 267 continue; 268 269 unsigned Reg = Use.getReg(); 270 271 // Handle physical registers that we need to track; this is mostly relevant 272 // for VCC, which can appear as the (implicit) input of a uniform branch, 273 // e.g. when a loop counter is stored in a VGPR. 274 if (!TargetRegisterInfo::isVirtualRegister(Reg)) { 275 if (Reg == AMDGPU::EXEC) 276 continue; 277 278 for (MCRegUnitIterator RegUnit(Reg, TRI); RegUnit.isValid(); ++RegUnit) { 279 LiveRange &LR = LIS->getRegUnit(*RegUnit); 280 const VNInfo *Value = LR.Query(LIS->getInstructionIndex(MI)).valueIn(); 281 if (!Value) 282 continue; 283 284 // Since we're in machine SSA, we do not need to track physical 285 // registers across basic blocks. 286 if (Value->isPHIDef()) 287 continue; 288 289 markInstruction(*LIS->getInstructionFromIndex(Value->def), StateWQM, 290 Worklist); 291 } 292 293 continue; 294 } 295 296 for (MachineInstr &DefMI : MRI->def_instructions(Use.getReg())) 297 markInstruction(DefMI, StateWQM, Worklist); 298 } 299 } 300 301 void SIWholeQuadMode::propagateBlock(MachineBasicBlock &MBB, 302 std::vector<WorkItem>& Worklist) { 303 BlockInfo BI = Blocks[&MBB]; // Make a copy to prevent dangling references. 304 305 // Propagate through instructions 306 if (!MBB.empty()) { 307 MachineInstr *LastMI = &*MBB.rbegin(); 308 InstrInfo &LastII = Instructions[LastMI]; 309 if ((LastII.OutNeeds | BI.OutNeeds) != LastII.OutNeeds) { 310 LastII.OutNeeds |= BI.OutNeeds; 311 Worklist.push_back(LastMI); 312 } 313 } 314 315 // Predecessor blocks must provide for our WQM/Exact needs. 316 for (MachineBasicBlock *Pred : MBB.predecessors()) { 317 BlockInfo &PredBI = Blocks[Pred]; 318 if ((PredBI.OutNeeds | BI.InNeeds) == PredBI.OutNeeds) 319 continue; 320 321 PredBI.OutNeeds |= BI.InNeeds; 322 PredBI.InNeeds |= BI.InNeeds; 323 Worklist.push_back(Pred); 324 } 325 326 // All successors must be prepared to accept the same set of WQM/Exact data. 327 for (MachineBasicBlock *Succ : MBB.successors()) { 328 BlockInfo &SuccBI = Blocks[Succ]; 329 if ((SuccBI.InNeeds | BI.OutNeeds) == SuccBI.InNeeds) 330 continue; 331 332 SuccBI.InNeeds |= BI.OutNeeds; 333 Worklist.push_back(Succ); 334 } 335 } 336 337 char SIWholeQuadMode::analyzeFunction(MachineFunction &MF) { 338 std::vector<WorkItem> Worklist; 339 char GlobalFlags = scanInstructions(MF, Worklist); 340 341 while (!Worklist.empty()) { 342 WorkItem WI = Worklist.back(); 343 Worklist.pop_back(); 344 345 if (WI.MI) 346 propagateInstruction(*WI.MI, Worklist); 347 else 348 propagateBlock(*WI.MBB, Worklist); 349 } 350 351 return GlobalFlags; 352 } 353 354 void SIWholeQuadMode::toExact(MachineBasicBlock &MBB, 355 MachineBasicBlock::iterator Before, 356 unsigned SaveWQM, unsigned LiveMaskReg) { 357 if (SaveWQM) { 358 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_AND_SAVEEXEC_B64), 359 SaveWQM) 360 .addReg(LiveMaskReg); 361 } else { 362 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_AND_B64), 363 AMDGPU::EXEC) 364 .addReg(AMDGPU::EXEC) 365 .addReg(LiveMaskReg); 366 } 367 } 368 369 void SIWholeQuadMode::toWQM(MachineBasicBlock &MBB, 370 MachineBasicBlock::iterator Before, 371 unsigned SavedWQM) { 372 if (SavedWQM) { 373 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::EXEC) 374 .addReg(SavedWQM); 375 } else { 376 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_WQM_B64), 377 AMDGPU::EXEC) 378 .addReg(AMDGPU::EXEC); 379 } 380 } 381 382 void SIWholeQuadMode::processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg, 383 bool isEntry) { 384 auto BII = Blocks.find(&MBB); 385 if (BII == Blocks.end()) 386 return; 387 388 const BlockInfo &BI = BII->second; 389 390 if (!(BI.InNeeds & StateWQM)) 391 return; 392 393 // This is a non-entry block that is WQM throughout, so no need to do 394 // anything. 395 if (!isEntry && !(BI.Needs & StateExact) && BI.OutNeeds != StateExact) 396 return; 397 398 unsigned SavedWQMReg = 0; 399 bool WQMFromExec = isEntry; 400 char State = isEntry ? StateExact : StateWQM; 401 402 auto II = MBB.getFirstNonPHI(), IE = MBB.end(); 403 while (II != IE) { 404 MachineInstr &MI = *II; 405 ++II; 406 407 // Skip instructions that are not affected by EXEC 408 if (TII->isScalarUnit(MI) && !MI.isTerminator()) 409 continue; 410 411 // Generic instructions such as COPY will either disappear by register 412 // coalescing or be lowered to SALU or VALU instructions. 413 if (TargetInstrInfo::isGenericOpcode(MI.getOpcode())) { 414 if (MI.getNumExplicitOperands() >= 1) { 415 const MachineOperand &Op = MI.getOperand(0); 416 if (Op.isReg()) { 417 if (TRI->isSGPRReg(*MRI, Op.getReg())) { 418 // SGPR instructions are not affected by EXEC 419 continue; 420 } 421 } 422 } 423 } 424 425 char Needs = 0; 426 char OutNeeds = 0; 427 auto InstrInfoIt = Instructions.find(&MI); 428 if (InstrInfoIt != Instructions.end()) { 429 Needs = InstrInfoIt->second.Needs; 430 OutNeeds = InstrInfoIt->second.OutNeeds; 431 432 // Make sure to switch to Exact mode before the end of the block when 433 // Exact and only Exact is needed further downstream. 434 if (OutNeeds == StateExact && MI.isTerminator()) { 435 assert(Needs == 0); 436 Needs = StateExact; 437 } 438 } 439 440 // State switching 441 if (Needs && State != Needs) { 442 if (Needs == StateExact) { 443 assert(!SavedWQMReg); 444 445 if (!WQMFromExec && (OutNeeds & StateWQM)) 446 SavedWQMReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass); 447 448 toExact(MBB, &MI, SavedWQMReg, LiveMaskReg); 449 } else { 450 assert(WQMFromExec == (SavedWQMReg == 0)); 451 toWQM(MBB, &MI, SavedWQMReg); 452 SavedWQMReg = 0; 453 } 454 455 State = Needs; 456 } 457 } 458 459 if ((BI.OutNeeds & StateWQM) && State != StateWQM) { 460 assert(WQMFromExec == (SavedWQMReg == 0)); 461 toWQM(MBB, MBB.end(), SavedWQMReg); 462 } else if (BI.OutNeeds == StateExact && State != StateExact) { 463 toExact(MBB, MBB.end(), 0, LiveMaskReg); 464 } 465 } 466 467 void SIWholeQuadMode::lowerLiveMaskQueries(unsigned LiveMaskReg) { 468 for (MachineInstr *MI : LiveMaskQueries) { 469 const DebugLoc &DL = MI->getDebugLoc(); 470 unsigned Dest = MI->getOperand(0).getReg(); 471 BuildMI(*MI->getParent(), MI, DL, TII->get(AMDGPU::COPY), Dest) 472 .addReg(LiveMaskReg); 473 MI->eraseFromParent(); 474 } 475 } 476 477 bool SIWholeQuadMode::runOnMachineFunction(MachineFunction &MF) { 478 if (MF.getFunction()->getCallingConv() != CallingConv::AMDGPU_PS) 479 return false; 480 481 Instructions.clear(); 482 Blocks.clear(); 483 ExecExports.clear(); 484 LiveMaskQueries.clear(); 485 486 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 487 488 TII = ST.getInstrInfo(); 489 TRI = &TII->getRegisterInfo(); 490 MRI = &MF.getRegInfo(); 491 LIS = &getAnalysis<LiveIntervals>(); 492 493 char GlobalFlags = analyzeFunction(MF); 494 if (!(GlobalFlags & StateWQM)) { 495 lowerLiveMaskQueries(AMDGPU::EXEC); 496 return !LiveMaskQueries.empty(); 497 } 498 499 // Store a copy of the original live mask when required 500 unsigned LiveMaskReg = 0; 501 { 502 MachineBasicBlock &Entry = MF.front(); 503 MachineBasicBlock::iterator EntryMI = Entry.getFirstNonPHI(); 504 505 if (GlobalFlags & StateExact || !LiveMaskQueries.empty()) { 506 LiveMaskReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass); 507 BuildMI(Entry, EntryMI, DebugLoc(), TII->get(AMDGPU::COPY), LiveMaskReg) 508 .addReg(AMDGPU::EXEC); 509 } 510 511 if (GlobalFlags == StateWQM) { 512 // For a shader that needs only WQM, we can just set it once. 513 BuildMI(Entry, EntryMI, DebugLoc(), TII->get(AMDGPU::S_WQM_B64), 514 AMDGPU::EXEC) 515 .addReg(AMDGPU::EXEC); 516 517 lowerLiveMaskQueries(LiveMaskReg); 518 // EntryMI may become invalid here 519 return true; 520 } 521 } 522 523 lowerLiveMaskQueries(LiveMaskReg); 524 525 // Handle the general case 526 for (auto BII : Blocks) 527 processBlock(*BII.first, LiveMaskReg, BII.first == &*MF.begin()); 528 529 return true; 530 } 531