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 if (WQMOutputs && MBB.succ_empty()) { 224 // This is a prolog shader. Make sure we go back to exact mode at the end. 225 Blocks[&MBB].OutNeeds = StateExact; 226 Worklist.push_back(&MBB); 227 GlobalFlags |= StateExact; 228 } 229 } 230 231 return GlobalFlags; 232 } 233 234 void SIWholeQuadMode::propagateInstruction(MachineInstr &MI, 235 std::vector<WorkItem>& Worklist) { 236 MachineBasicBlock *MBB = MI.getParent(); 237 InstrInfo II = Instructions[&MI]; // take a copy to prevent dangling references 238 BlockInfo &BI = Blocks[MBB]; 239 240 // Control flow-type instructions and stores to temporary memory that are 241 // followed by WQM computations must themselves be in WQM. 242 if ((II.OutNeeds & StateWQM) && !II.Needs && 243 (MI.isTerminator() || (TII->usesVM_CNT(MI) && MI.mayStore()))) { 244 Instructions[&MI].Needs = StateWQM; 245 II.Needs = StateWQM; 246 } 247 248 // Propagate to block level 249 BI.Needs |= II.Needs; 250 if ((BI.InNeeds | II.Needs) != BI.InNeeds) { 251 BI.InNeeds |= II.Needs; 252 Worklist.push_back(MBB); 253 } 254 255 // Propagate backwards within block 256 if (MachineInstr *PrevMI = MI.getPrevNode()) { 257 char InNeeds = II.Needs | II.OutNeeds; 258 if (!PrevMI->isPHI()) { 259 InstrInfo &PrevII = Instructions[PrevMI]; 260 if ((PrevII.OutNeeds | InNeeds) != PrevII.OutNeeds) { 261 PrevII.OutNeeds |= InNeeds; 262 Worklist.push_back(PrevMI); 263 } 264 } 265 } 266 267 // Propagate WQM flag to instruction inputs 268 assert(II.Needs != (StateWQM | StateExact)); 269 if (II.Needs != StateWQM) 270 return; 271 272 for (const MachineOperand &Use : MI.uses()) { 273 if (!Use.isReg() || !Use.isUse()) 274 continue; 275 276 unsigned Reg = Use.getReg(); 277 278 // Handle physical registers that we need to track; this is mostly relevant 279 // for VCC, which can appear as the (implicit) input of a uniform branch, 280 // e.g. when a loop counter is stored in a VGPR. 281 if (!TargetRegisterInfo::isVirtualRegister(Reg)) { 282 if (Reg == AMDGPU::EXEC) 283 continue; 284 285 for (MCRegUnitIterator RegUnit(Reg, TRI); RegUnit.isValid(); ++RegUnit) { 286 LiveRange &LR = LIS->getRegUnit(*RegUnit); 287 const VNInfo *Value = LR.Query(LIS->getInstructionIndex(MI)).valueIn(); 288 if (!Value) 289 continue; 290 291 // Since we're in machine SSA, we do not need to track physical 292 // registers across basic blocks. 293 if (Value->isPHIDef()) 294 continue; 295 296 markInstruction(*LIS->getInstructionFromIndex(Value->def), StateWQM, 297 Worklist); 298 } 299 300 continue; 301 } 302 303 for (MachineInstr &DefMI : MRI->def_instructions(Use.getReg())) 304 markInstruction(DefMI, StateWQM, Worklist); 305 } 306 } 307 308 void SIWholeQuadMode::propagateBlock(MachineBasicBlock &MBB, 309 std::vector<WorkItem>& Worklist) { 310 BlockInfo BI = Blocks[&MBB]; // Make a copy to prevent dangling references. 311 312 // Propagate through instructions 313 if (!MBB.empty()) { 314 MachineInstr *LastMI = &*MBB.rbegin(); 315 InstrInfo &LastII = Instructions[LastMI]; 316 if ((LastII.OutNeeds | BI.OutNeeds) != LastII.OutNeeds) { 317 LastII.OutNeeds |= BI.OutNeeds; 318 Worklist.push_back(LastMI); 319 } 320 } 321 322 // Predecessor blocks must provide for our WQM/Exact needs. 323 for (MachineBasicBlock *Pred : MBB.predecessors()) { 324 BlockInfo &PredBI = Blocks[Pred]; 325 if ((PredBI.OutNeeds | BI.InNeeds) == PredBI.OutNeeds) 326 continue; 327 328 PredBI.OutNeeds |= BI.InNeeds; 329 PredBI.InNeeds |= BI.InNeeds; 330 Worklist.push_back(Pred); 331 } 332 333 // All successors must be prepared to accept the same set of WQM/Exact data. 334 for (MachineBasicBlock *Succ : MBB.successors()) { 335 BlockInfo &SuccBI = Blocks[Succ]; 336 if ((SuccBI.InNeeds | BI.OutNeeds) == SuccBI.InNeeds) 337 continue; 338 339 SuccBI.InNeeds |= BI.OutNeeds; 340 Worklist.push_back(Succ); 341 } 342 } 343 344 char SIWholeQuadMode::analyzeFunction(MachineFunction &MF) { 345 std::vector<WorkItem> Worklist; 346 char GlobalFlags = scanInstructions(MF, Worklist); 347 348 while (!Worklist.empty()) { 349 WorkItem WI = Worklist.back(); 350 Worklist.pop_back(); 351 352 if (WI.MI) 353 propagateInstruction(*WI.MI, Worklist); 354 else 355 propagateBlock(*WI.MBB, Worklist); 356 } 357 358 return GlobalFlags; 359 } 360 361 void SIWholeQuadMode::toExact(MachineBasicBlock &MBB, 362 MachineBasicBlock::iterator Before, 363 unsigned SaveWQM, unsigned LiveMaskReg) { 364 if (SaveWQM) { 365 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_AND_SAVEEXEC_B64), 366 SaveWQM) 367 .addReg(LiveMaskReg); 368 } else { 369 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_AND_B64), 370 AMDGPU::EXEC) 371 .addReg(AMDGPU::EXEC) 372 .addReg(LiveMaskReg); 373 } 374 } 375 376 void SIWholeQuadMode::toWQM(MachineBasicBlock &MBB, 377 MachineBasicBlock::iterator Before, 378 unsigned SavedWQM) { 379 if (SavedWQM) { 380 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::EXEC) 381 .addReg(SavedWQM); 382 } else { 383 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_WQM_B64), 384 AMDGPU::EXEC) 385 .addReg(AMDGPU::EXEC); 386 } 387 } 388 389 void SIWholeQuadMode::processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg, 390 bool isEntry) { 391 auto BII = Blocks.find(&MBB); 392 if (BII == Blocks.end()) 393 return; 394 395 const BlockInfo &BI = BII->second; 396 397 if (!(BI.InNeeds & StateWQM)) 398 return; 399 400 // This is a non-entry block that is WQM throughout, so no need to do 401 // anything. 402 if (!isEntry && !(BI.Needs & StateExact) && BI.OutNeeds != StateExact) 403 return; 404 405 unsigned SavedWQMReg = 0; 406 bool WQMFromExec = isEntry; 407 char State = isEntry ? StateExact : StateWQM; 408 409 auto II = MBB.getFirstNonPHI(), IE = MBB.end(); 410 while (II != IE) { 411 MachineInstr &MI = *II; 412 ++II; 413 414 // Skip instructions that are not affected by EXEC 415 if (TII->isScalarUnit(MI) && !MI.isTerminator()) 416 continue; 417 418 // Generic instructions such as COPY will either disappear by register 419 // coalescing or be lowered to SALU or VALU instructions. 420 if (TargetInstrInfo::isGenericOpcode(MI.getOpcode())) { 421 if (MI.getNumExplicitOperands() >= 1) { 422 const MachineOperand &Op = MI.getOperand(0); 423 if (Op.isReg()) { 424 if (TRI->isSGPRReg(*MRI, Op.getReg())) { 425 // SGPR instructions are not affected by EXEC 426 continue; 427 } 428 } 429 } 430 } 431 432 char Needs = 0; 433 char OutNeeds = 0; 434 auto InstrInfoIt = Instructions.find(&MI); 435 if (InstrInfoIt != Instructions.end()) { 436 Needs = InstrInfoIt->second.Needs; 437 OutNeeds = InstrInfoIt->second.OutNeeds; 438 439 // Make sure to switch to Exact mode before the end of the block when 440 // Exact and only Exact is needed further downstream. 441 if (OutNeeds == StateExact && MI.isTerminator()) { 442 assert(Needs == 0); 443 Needs = StateExact; 444 } 445 } 446 447 // State switching 448 if (Needs && State != Needs) { 449 if (Needs == StateExact) { 450 assert(!SavedWQMReg); 451 452 if (!WQMFromExec && (OutNeeds & StateWQM)) 453 SavedWQMReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass); 454 455 toExact(MBB, &MI, SavedWQMReg, LiveMaskReg); 456 } else { 457 assert(WQMFromExec == (SavedWQMReg == 0)); 458 toWQM(MBB, &MI, SavedWQMReg); 459 SavedWQMReg = 0; 460 } 461 462 State = Needs; 463 } 464 465 if (MI.getOpcode() == AMDGPU::SI_ELSE && State == StateExact) 466 MI.getOperand(3).setImm(1); 467 } 468 469 if ((BI.OutNeeds & StateWQM) && State != StateWQM) { 470 assert(WQMFromExec == (SavedWQMReg == 0)); 471 toWQM(MBB, MBB.end(), SavedWQMReg); 472 } else if (BI.OutNeeds == StateExact && State != StateExact) { 473 toExact(MBB, MBB.end(), 0, LiveMaskReg); 474 } 475 } 476 477 void SIWholeQuadMode::lowerLiveMaskQueries(unsigned LiveMaskReg) { 478 for (MachineInstr *MI : LiveMaskQueries) { 479 const DebugLoc &DL = MI->getDebugLoc(); 480 unsigned Dest = MI->getOperand(0).getReg(); 481 BuildMI(*MI->getParent(), MI, DL, TII->get(AMDGPU::COPY), Dest) 482 .addReg(LiveMaskReg); 483 MI->eraseFromParent(); 484 } 485 } 486 487 bool SIWholeQuadMode::runOnMachineFunction(MachineFunction &MF) { 488 if (MF.getFunction()->getCallingConv() != CallingConv::AMDGPU_PS) 489 return false; 490 491 Instructions.clear(); 492 Blocks.clear(); 493 ExecExports.clear(); 494 LiveMaskQueries.clear(); 495 496 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 497 498 TII = ST.getInstrInfo(); 499 TRI = &TII->getRegisterInfo(); 500 MRI = &MF.getRegInfo(); 501 LIS = &getAnalysis<LiveIntervals>(); 502 503 char GlobalFlags = analyzeFunction(MF); 504 if (!(GlobalFlags & StateWQM)) { 505 lowerLiveMaskQueries(AMDGPU::EXEC); 506 return !LiveMaskQueries.empty(); 507 } 508 509 // Store a copy of the original live mask when required 510 unsigned LiveMaskReg = 0; 511 { 512 MachineBasicBlock &Entry = MF.front(); 513 MachineBasicBlock::iterator EntryMI = Entry.getFirstNonPHI(); 514 515 if (GlobalFlags & StateExact || !LiveMaskQueries.empty()) { 516 LiveMaskReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass); 517 BuildMI(Entry, EntryMI, DebugLoc(), TII->get(AMDGPU::COPY), LiveMaskReg) 518 .addReg(AMDGPU::EXEC); 519 } 520 521 if (GlobalFlags == StateWQM) { 522 // For a shader that needs only WQM, we can just set it once. 523 BuildMI(Entry, EntryMI, DebugLoc(), TII->get(AMDGPU::S_WQM_B64), 524 AMDGPU::EXEC) 525 .addReg(AMDGPU::EXEC); 526 527 lowerLiveMaskQueries(LiveMaskReg); 528 // EntryMI may become invalid here 529 return true; 530 } 531 } 532 533 lowerLiveMaskQueries(LiveMaskReg); 534 535 // Handle the general case 536 for (auto BII : Blocks) 537 processBlock(*BII.first, LiveMaskReg, BII.first == &*MF.begin()); 538 539 return true; 540 } 541