1 //===-- SIWholeQuadMode.cpp - enter and suspend whole quad mode -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This pass adds instructions to enable whole quad mode for pixel
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.
20 /// When necessary, this pass creates a function prolog
22 /// S_MOV_B64 LiveMask, EXEC
23 /// S_WQM_B64 EXEC, EXEC
25 /// to enter WQM at the top of the function and surrounds blocks of Exact
28 /// S_AND_SAVEEXEC_B64 Tmp, LiveMask
30 /// S_MOV_B64 EXEC, Tmp
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
37 /// Basic blocks are always exited in WQM as long as some successor needs WQM.
39 /// There is room for improvement given better control flow analysis:
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).
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.
50 //===----------------------------------------------------------------------===//
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"
63 #define DEBUG_TYPE "si-wqm"
84 MachineBasicBlock *MBB = nullptr;
85 MachineInstr *MI = nullptr;
88 WorkItem(MachineBasicBlock *MBB) : MBB(MBB) {}
89 WorkItem(MachineInstr *MI) : MI(MI) {}
92 class SIWholeQuadMode : public MachineFunctionPass {
94 const SIInstrInfo *TII;
95 const SIRegisterInfo *TRI;
96 MachineRegisterInfo *MRI;
99 DenseMap<const MachineInstr *, InstrInfo> Instructions;
100 DenseMap<MachineBasicBlock *, BlockInfo> Blocks;
101 SmallVector<const MachineInstr *, 2> ExecExports;
102 SmallVector<MachineInstr *, 1> LiveMaskQueries;
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);
111 void toExact(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
112 unsigned SaveWQM, unsigned LiveMaskReg);
113 void toWQM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
115 void processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg, bool isEntry);
117 void lowerLiveMaskQueries(unsigned LiveMaskReg);
123 MachineFunctionPass(ID) { }
125 bool runOnMachineFunction(MachineFunction &MF) override;
127 const char *getPassName() const override {
128 return "SI Whole Quad Mode";
131 void getAnalysisUsage(AnalysisUsage &AU) const override {
132 AU.addRequired<LiveIntervals>();
133 AU.setPreservesCFG();
134 MachineFunctionPass::getAnalysisUsage(AU);
138 } // End anonymous namespace
140 char SIWholeQuadMode::ID = 0;
142 INITIALIZE_PASS_BEGIN(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false,
144 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
145 INITIALIZE_PASS_END(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false,
148 char &llvm::SIWholeQuadModeID = SIWholeQuadMode::ID;
150 FunctionPass *llvm::createSIWholeQuadModePass() {
151 return new SIWholeQuadMode;
154 void SIWholeQuadMode::markInstruction(MachineInstr &MI, char Flag,
155 std::vector<WorkItem> &Worklist) {
156 InstrInfo &II = Instructions[&MI];
158 assert(Flag == StateWQM || Flag == StateExact);
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.
168 Worklist.push_back(&MI);
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");
178 for (auto BI = MF.begin(), BE = MF.end(); BI != BE; ++BI) {
179 MachineBasicBlock &MBB = *BI;
181 for (auto II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
182 MachineInstr &MI = *II;
183 unsigned Opcode = MI.getOpcode();
186 if (TII->isWQM(Opcode) || TII->isDS(Opcode)) {
188 } else if (TII->isDisableWQM(MI)) {
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()) {
205 unsigned Reg = MO.getReg();
207 if (!TRI->isVirtualRegister(Reg) &&
208 TRI->hasVGPRs(TRI->getPhysRegClass(Reg))) {
219 markInstruction(MI, Flags, Worklist);
220 GlobalFlags |= Flags;
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];
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;
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);
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);
260 // Propagate WQM flag to instruction inputs
261 assert(II.Needs != (StateWQM | StateExact));
262 if (II.Needs != StateWQM)
265 for (const MachineOperand &Use : MI.uses()) {
266 if (!Use.isReg() || !Use.isUse())
269 unsigned Reg = Use.getReg();
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)
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();
284 // Since we're in machine SSA, we do not need to track physical
285 // registers across basic blocks.
286 if (Value->isPHIDef())
289 markInstruction(*LIS->getInstructionFromIndex(Value->def), StateWQM,
296 for (MachineInstr &DefMI : MRI->def_instructions(Use.getReg()))
297 markInstruction(DefMI, StateWQM, Worklist);
301 void SIWholeQuadMode::propagateBlock(MachineBasicBlock &MBB,
302 std::vector<WorkItem>& Worklist) {
303 BlockInfo BI = Blocks[&MBB]; // Make a copy to prevent dangling references.
305 // Propagate through instructions
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);
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)
321 PredBI.OutNeeds |= BI.InNeeds;
322 PredBI.InNeeds |= BI.InNeeds;
323 Worklist.push_back(Pred);
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)
332 SuccBI.InNeeds |= BI.OutNeeds;
333 Worklist.push_back(Succ);
337 char SIWholeQuadMode::analyzeFunction(MachineFunction &MF) {
338 std::vector<WorkItem> Worklist;
339 char GlobalFlags = scanInstructions(MF, Worklist);
341 while (!Worklist.empty()) {
342 WorkItem WI = Worklist.back();
346 propagateInstruction(*WI.MI, Worklist);
348 propagateBlock(*WI.MBB, Worklist);
354 void SIWholeQuadMode::toExact(MachineBasicBlock &MBB,
355 MachineBasicBlock::iterator Before,
356 unsigned SaveWQM, unsigned LiveMaskReg) {
358 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_AND_SAVEEXEC_B64),
360 .addReg(LiveMaskReg);
362 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_AND_B64),
364 .addReg(AMDGPU::EXEC)
365 .addReg(LiveMaskReg);
369 void SIWholeQuadMode::toWQM(MachineBasicBlock &MBB,
370 MachineBasicBlock::iterator Before,
373 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::EXEC)
376 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_WQM_B64),
378 .addReg(AMDGPU::EXEC);
382 void SIWholeQuadMode::processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg,
384 auto BII = Blocks.find(&MBB);
385 if (BII == Blocks.end())
388 const BlockInfo &BI = BII->second;
390 if (!(BI.InNeeds & StateWQM))
393 // This is a non-entry block that is WQM throughout, so no need to do
395 if (!isEntry && !(BI.Needs & StateExact) && BI.OutNeeds != StateExact)
398 unsigned SavedWQMReg = 0;
399 bool WQMFromExec = isEntry;
400 char State = isEntry ? StateExact : StateWQM;
402 auto II = MBB.getFirstNonPHI(), IE = MBB.end();
404 MachineInstr &MI = *II;
407 // Skip instructions that are not affected by EXEC
408 if (TII->isScalarUnit(MI) && !MI.isTerminator())
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);
417 if (TRI->isSGPRReg(*MRI, Op.getReg())) {
418 // SGPR instructions are not affected by EXEC
427 auto InstrInfoIt = Instructions.find(&MI);
428 if (InstrInfoIt != Instructions.end()) {
429 Needs = InstrInfoIt->second.Needs;
430 OutNeeds = InstrInfoIt->second.OutNeeds;
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()) {
441 if (Needs && State != Needs) {
442 if (Needs == StateExact) {
443 assert(!SavedWQMReg);
445 if (!WQMFromExec && (OutNeeds & StateWQM))
446 SavedWQMReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
448 toExact(MBB, &MI, SavedWQMReg, LiveMaskReg);
450 assert(WQMFromExec == (SavedWQMReg == 0));
451 toWQM(MBB, &MI, SavedWQMReg);
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);
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();
477 bool SIWholeQuadMode::runOnMachineFunction(MachineFunction &MF) {
478 if (MF.getFunction()->getCallingConv() != CallingConv::AMDGPU_PS)
481 Instructions.clear();
484 LiveMaskQueries.clear();
486 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
488 TII = ST.getInstrInfo();
489 TRI = &TII->getRegisterInfo();
490 MRI = &MF.getRegInfo();
491 LIS = &getAnalysis<LiveIntervals>();
493 char GlobalFlags = analyzeFunction(MF);
494 if (!(GlobalFlags & StateWQM)) {
495 lowerLiveMaskQueries(AMDGPU::EXEC);
496 return !LiveMaskQueries.empty();
499 // Store a copy of the original live mask when required
500 unsigned LiveMaskReg = 0;
502 MachineBasicBlock &Entry = MF.front();
503 MachineBasicBlock::iterator EntryMI = Entry.getFirstNonPHI();
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);
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),
515 .addReg(AMDGPU::EXEC);
517 lowerLiveMaskQueries(LiveMaskReg);
518 // EntryMI may become invalid here
523 lowerLiveMaskQueries(LiveMaskReg);
525 // Handle the general case
526 for (auto BII : Blocks)
527 processBlock(*BII.first, LiveMaskReg, BII.first == &*MF.begin());