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/MachineDominanceFrontier.h"
57 #include "llvm/CodeGen/MachineDominators.h"
58 #include "llvm/CodeGen/MachineFunction.h"
59 #include "llvm/CodeGen/MachineFunctionPass.h"
60 #include "llvm/CodeGen/MachineInstrBuilder.h"
61 #include "llvm/CodeGen/MachineRegisterInfo.h"
62 #include "llvm/IR/Constants.h"
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "si-wqm"
67 
68 namespace {
69 
70 enum {
71   StateWQM = 0x1,
72   StateExact = 0x2,
73 };
74 
75 struct InstrInfo {
76   char Needs = 0;
77   char OutNeeds = 0;
78 };
79 
80 struct BlockInfo {
81   char Needs = 0;
82   char InNeeds = 0;
83   char OutNeeds = 0;
84 };
85 
86 struct WorkItem {
87   const MachineBasicBlock *MBB = nullptr;
88   const MachineInstr *MI = nullptr;
89 
90   WorkItem() {}
91   WorkItem(const MachineBasicBlock *MBB) : MBB(MBB) {}
92   WorkItem(const MachineInstr *MI) : MI(MI) {}
93 };
94 
95 class SIWholeQuadMode : public MachineFunctionPass {
96 private:
97   const SIInstrInfo *TII;
98   const SIRegisterInfo *TRI;
99   MachineRegisterInfo *MRI;
100 
101   DenseMap<const MachineInstr *, InstrInfo> Instructions;
102   DenseMap<const MachineBasicBlock *, BlockInfo> Blocks;
103   SmallVector<const MachineInstr *, 2> ExecExports;
104 
105   char scanInstructions(const MachineFunction &MF, std::vector<WorkItem>& Worklist);
106   void propagateInstruction(const MachineInstr &MI, std::vector<WorkItem>& Worklist);
107   void propagateBlock(const MachineBasicBlock &MBB, std::vector<WorkItem>& Worklist);
108   char analyzeFunction(const MachineFunction &MF);
109 
110   void toExact(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
111                unsigned SaveWQM, unsigned LiveMaskReg);
112   void toWQM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
113              unsigned SavedWQM);
114   void processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg, bool isEntry);
115 
116 public:
117   static char ID;
118 
119   SIWholeQuadMode() :
120     MachineFunctionPass(ID) { }
121 
122   bool runOnMachineFunction(MachineFunction &MF) override;
123 
124   const char *getPassName() const override {
125     return "SI Whole Quad Mode";
126   }
127 
128   void getAnalysisUsage(AnalysisUsage &AU) const override {
129     AU.setPreservesCFG();
130     MachineFunctionPass::getAnalysisUsage(AU);
131   }
132 };
133 
134 } // End anonymous namespace
135 
136 char SIWholeQuadMode::ID = 0;
137 
138 INITIALIZE_PASS_BEGIN(SIWholeQuadMode, DEBUG_TYPE,
139                       "SI Whole Quad Mode", false, false)
140 INITIALIZE_PASS_END(SIWholeQuadMode, DEBUG_TYPE,
141                       "SI Whole Quad Mode", false, false)
142 
143 char &llvm::SIWholeQuadModeID = SIWholeQuadMode::ID;
144 
145 FunctionPass *llvm::createSIWholeQuadModePass() {
146   return new SIWholeQuadMode;
147 }
148 
149 // Scan instructions to determine which ones require an Exact execmask and
150 // which ones seed WQM requirements.
151 char SIWholeQuadMode::scanInstructions(const MachineFunction &MF,
152                                        std::vector<WorkItem> &Worklist) {
153   char GlobalFlags = 0;
154 
155   for (auto BI = MF.begin(), BE = MF.end(); BI != BE; ++BI) {
156     const MachineBasicBlock &MBB = *BI;
157 
158     for (auto II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
159       const MachineInstr &MI = *II;
160       unsigned Opcode = MI.getOpcode();
161       char Flags;
162 
163       if (TII->isWQM(Opcode) || TII->isDS(Opcode)) {
164         Flags = StateWQM;
165       } else if (TII->get(Opcode).mayStore() &&
166                  (MI.getDesc().TSFlags & SIInstrFlags::VM_CNT)) {
167         Flags = StateExact;
168       } else {
169         // Handle export instructions with the exec mask valid flag set
170         if (Opcode == AMDGPU::EXP && MI.getOperand(4).getImm() != 0)
171           ExecExports.push_back(&MI);
172         continue;
173       }
174 
175       Instructions[&MI].Needs = Flags;
176       Worklist.push_back(&MI);
177       GlobalFlags |= Flags;
178     }
179   }
180 
181   return GlobalFlags;
182 }
183 
184 void SIWholeQuadMode::propagateInstruction(const MachineInstr &MI,
185                                            std::vector<WorkItem>& Worklist) {
186   const MachineBasicBlock &MBB = *MI.getParent();
187   InstrInfo II = Instructions[&MI]; // take a copy to prevent dangling references
188   BlockInfo &BI = Blocks[&MBB];
189 
190   // Control flow-type instructions that are followed by WQM computations
191   // must themselves be in WQM.
192   if ((II.OutNeeds & StateWQM) && !(II.Needs & StateWQM) &&
193       (MI.isBranch() || MI.isTerminator() || MI.getOpcode() == AMDGPU::SI_KILL)) {
194     Instructions[&MI].Needs = StateWQM;
195     II.Needs = StateWQM;
196   }
197 
198   // Propagate to block level
199   BI.Needs |= II.Needs;
200   if ((BI.InNeeds | II.Needs) != BI.InNeeds) {
201     BI.InNeeds |= II.Needs;
202     Worklist.push_back(&MBB);
203   }
204 
205   // Propagate backwards within block
206   if (const MachineInstr *PrevMI = MI.getPrevNode()) {
207     char InNeeds = II.Needs | II.OutNeeds;
208     if (!PrevMI->isPHI()) {
209       InstrInfo &PrevII = Instructions[PrevMI];
210       if ((PrevII.OutNeeds | InNeeds) != PrevII.OutNeeds) {
211         PrevII.OutNeeds |= InNeeds;
212         Worklist.push_back(PrevMI);
213       }
214     }
215   }
216 
217   // Propagate WQM flag to instruction inputs
218   assert(II.Needs != (StateWQM | StateExact));
219   if (II.Needs != StateWQM)
220     return;
221 
222   for (const MachineOperand &Use : MI.uses()) {
223     if (!Use.isReg() || !Use.isUse())
224       continue;
225 
226     // At this point, physical registers appear as inputs or outputs
227     // and following them makes no sense (and would in fact be incorrect
228     // when the same VGPR is used as both an output and an input that leads
229     // to a NeedsWQM instruction).
230     //
231     // Note: VCC appears e.g. in 64-bit addition with carry - theoretically we
232     // have to trace this, in practice it happens for 64-bit computations like
233     // pointers where both dwords are followed already anyway.
234     if (!TargetRegisterInfo::isVirtualRegister(Use.getReg()))
235       continue;
236 
237     for (const MachineOperand &Def : MRI->def_operands(Use.getReg())) {
238       const MachineInstr *DefMI = Def.getParent();
239       InstrInfo &DefII = Instructions[DefMI];
240 
241       // Obviously skip if DefMI is already flagged as NeedWQM.
242       //
243       // The instruction might also be flagged as NeedExact. This happens when
244       // the result of an atomic is used in a WQM computation. In this case,
245       // the atomic must not run for helper pixels and the WQM result is
246       // undefined.
247       if (DefII.Needs != 0)
248         continue;
249 
250       DefII.Needs = StateWQM;
251       Worklist.push_back(DefMI);
252     }
253   }
254 }
255 
256 void SIWholeQuadMode::propagateBlock(const MachineBasicBlock &MBB,
257                                      std::vector<WorkItem>& Worklist) {
258   BlockInfo BI = Blocks[&MBB]; // take a copy to prevent dangling references
259 
260   // Propagate through instructions
261   if (!MBB.empty()) {
262     const MachineInstr *LastMI = &*MBB.rbegin();
263     InstrInfo &LastII = Instructions[LastMI];
264     if ((LastII.OutNeeds | BI.OutNeeds) != LastII.OutNeeds) {
265       LastII.OutNeeds |= BI.OutNeeds;
266       Worklist.push_back(LastMI);
267     }
268   }
269 
270   // Predecessor blocks must provide for our WQM/Exact needs.
271   for (const MachineBasicBlock *Pred : MBB.predecessors()) {
272     BlockInfo &PredBI = Blocks[Pred];
273     if ((PredBI.OutNeeds | BI.InNeeds) == PredBI.OutNeeds)
274       continue;
275 
276     PredBI.OutNeeds |= BI.InNeeds;
277     PredBI.InNeeds |= BI.InNeeds;
278     Worklist.push_back(Pred);
279   }
280 
281   // All successors must be prepared to accept the same set of WQM/Exact
282   // data.
283   for (const MachineBasicBlock *Succ : MBB.successors()) {
284     BlockInfo &SuccBI = Blocks[Succ];
285     if ((SuccBI.InNeeds | BI.OutNeeds) == SuccBI.InNeeds)
286       continue;
287 
288     SuccBI.InNeeds |= BI.OutNeeds;
289     Worklist.push_back(Succ);
290   }
291 }
292 
293 char SIWholeQuadMode::analyzeFunction(const MachineFunction &MF) {
294   std::vector<WorkItem> Worklist;
295   char GlobalFlags = scanInstructions(MF, Worklist);
296 
297   while (!Worklist.empty()) {
298     WorkItem WI = Worklist.back();
299     Worklist.pop_back();
300 
301     if (WI.MI)
302       propagateInstruction(*WI.MI, Worklist);
303     else
304       propagateBlock(*WI.MBB, Worklist);
305   }
306 
307   return GlobalFlags;
308 }
309 
310 void SIWholeQuadMode::toExact(MachineBasicBlock &MBB,
311                               MachineBasicBlock::iterator Before,
312                               unsigned SaveWQM, unsigned LiveMaskReg) {
313   if (SaveWQM) {
314     BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_AND_SAVEEXEC_B64),
315             SaveWQM)
316         .addReg(LiveMaskReg);
317   } else {
318     BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_AND_B64),
319             AMDGPU::EXEC)
320         .addReg(AMDGPU::EXEC)
321         .addReg(LiveMaskReg);
322   }
323 }
324 
325 void SIWholeQuadMode::toWQM(MachineBasicBlock &MBB,
326                             MachineBasicBlock::iterator Before,
327                             unsigned SavedWQM) {
328   if (SavedWQM) {
329     BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::EXEC)
330         .addReg(SavedWQM);
331   } else {
332     BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_WQM_B64),
333             AMDGPU::EXEC)
334         .addReg(AMDGPU::EXEC);
335   }
336 }
337 
338 void SIWholeQuadMode::processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg,
339                                    bool isEntry) {
340   auto BII = Blocks.find(&MBB);
341   if (BII == Blocks.end())
342     return;
343 
344   const BlockInfo &BI = BII->second;
345 
346   if (!(BI.InNeeds & StateWQM))
347     return;
348 
349   // This is a non-entry block that is WQM throughout, so no need to do
350   // anything.
351   if (!isEntry && !(BI.Needs & StateExact) && BI.OutNeeds != StateExact)
352     return;
353 
354   unsigned SavedWQMReg = 0;
355   bool WQMFromExec = isEntry;
356   char State = isEntry ? StateExact : StateWQM;
357 
358   auto II = MBB.getFirstNonPHI(), IE = MBB.end();
359   while (II != IE) {
360     MachineInstr &MI = *II;
361     ++II;
362 
363     // Skip instructions that are not affected by EXEC
364     if (MI.getDesc().TSFlags & (SIInstrFlags::SALU | SIInstrFlags::SMRD) &&
365         !MI.isBranch() && !MI.isTerminator())
366       continue;
367 
368     // Generic instructions such as COPY will either disappear by register
369     // coalescing or be lowered to SALU or VALU instructions.
370     if (TargetInstrInfo::isGenericOpcode(MI.getOpcode())) {
371       if (MI.getNumExplicitOperands() >= 1) {
372         const MachineOperand &Op = MI.getOperand(0);
373         if (Op.isReg()) {
374           if (TRI->isSGPRReg(*MRI, Op.getReg())) {
375             // SGPR instructions are not affected by EXEC
376             continue;
377           }
378         }
379       }
380     }
381 
382     char Needs = 0;
383     char OutNeeds = 0;
384     auto InstrInfoIt = Instructions.find(&MI);
385     if (InstrInfoIt != Instructions.end()) {
386       Needs = InstrInfoIt->second.Needs;
387       OutNeeds = InstrInfoIt->second.OutNeeds;
388 
389       // Make sure to switch to Exact mode before the end of the block when
390       // Exact and only Exact is needed further downstream.
391       if (OutNeeds == StateExact && (MI.isBranch() || MI.isTerminator())) {
392         assert(Needs == 0);
393         Needs = StateExact;
394       }
395     }
396 
397     // State switching
398     if (Needs && State != Needs) {
399       if (Needs == StateExact) {
400         assert(!SavedWQMReg);
401 
402         if (!WQMFromExec && (OutNeeds & StateWQM))
403           SavedWQMReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
404 
405         toExact(MBB, &MI, SavedWQMReg, LiveMaskReg);
406       } else {
407         assert(WQMFromExec == (SavedWQMReg == 0));
408         toWQM(MBB, &MI, SavedWQMReg);
409         SavedWQMReg = 0;
410       }
411 
412       State = Needs;
413     }
414 
415     if (MI.getOpcode() == AMDGPU::SI_KILL)
416       WQMFromExec = false;
417   }
418 
419   if ((BI.OutNeeds & StateWQM) && State != StateWQM) {
420     assert(WQMFromExec == (SavedWQMReg == 0));
421     toWQM(MBB, MBB.end(), SavedWQMReg);
422   } else if (BI.OutNeeds == StateExact && State != StateExact) {
423     toExact(MBB, MBB.end(), 0, LiveMaskReg);
424   }
425 }
426 
427 bool SIWholeQuadMode::runOnMachineFunction(MachineFunction &MF) {
428   if (MF.getFunction()->getCallingConv() != CallingConv::AMDGPU_PS)
429     return false;
430 
431   Instructions.clear();
432   Blocks.clear();
433   ExecExports.clear();
434 
435   TII = static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo());
436   TRI = static_cast<const SIRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
437   MRI = &MF.getRegInfo();
438 
439   char GlobalFlags = analyzeFunction(MF);
440   if (!(GlobalFlags & StateWQM))
441     return false;
442 
443   MachineBasicBlock &Entry = MF.front();
444   MachineInstr *EntryMI = Entry.getFirstNonPHI();
445 
446   if (GlobalFlags == StateWQM) {
447     // For a shader that needs only WQM, we can just set it once.
448     BuildMI(Entry, EntryMI, DebugLoc(), TII->get(AMDGPU::S_WQM_B64),
449             AMDGPU::EXEC).addReg(AMDGPU::EXEC);
450     return true;
451   }
452 
453   // Handle the general case
454   unsigned LiveMaskReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
455   BuildMI(Entry, EntryMI, DebugLoc(), TII->get(AMDGPU::COPY), LiveMaskReg)
456       .addReg(AMDGPU::EXEC);
457 
458   for (const auto &BII : Blocks)
459     processBlock(const_cast<MachineBasicBlock &>(*BII.first), LiveMaskReg,
460                  BII.first == &*MF.begin());
461 
462   return true;
463 }
464