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