1 //===-- SIWholeQuadMode.cpp - enter and suspend whole quad mode -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This pass adds instructions to enable whole quad mode for pixel
11 /// shaders, and whole wavefront mode for all programs.
12 ///
13 /// Whole quad mode is required for derivative computations, but it interferes
14 /// with shader side effects (stores and atomics). This pass is run on the
15 /// scheduled machine IR but before register coalescing, so that machine SSA is
16 /// available for analysis. It ensures that WQM is enabled when necessary, but
17 /// disabled around stores and atomics.
18 ///
19 /// When necessary, this pass creates a function prolog
20 ///
21 ///   S_MOV_B64 LiveMask, EXEC
22 ///   S_WQM_B64 EXEC, EXEC
23 ///
24 /// to enter WQM at the top of the function and surrounds blocks of Exact
25 /// instructions by
26 ///
27 ///   S_AND_SAVEEXEC_B64 Tmp, LiveMask
28 ///   ...
29 ///   S_MOV_B64 EXEC, Tmp
30 ///
31 /// We also compute when a sequence of instructions requires Whole Wavefront
32 /// Mode (WWM) and insert instructions to save and restore it:
33 ///
34 /// S_OR_SAVEEXEC_B64 Tmp, -1
35 /// ...
36 /// S_MOV_B64 EXEC, Tmp
37 ///
38 /// In order to avoid excessive switching during sequences of Exact
39 /// instructions, the pass first analyzes which instructions must be run in WQM
40 /// (aka which instructions produce values that lead to derivative
41 /// computations).
42 ///
43 /// Basic blocks are always exited in WQM as long as some successor needs WQM.
44 ///
45 /// There is room for improvement given better control flow analysis:
46 ///
47 ///  (1) at the top level (outside of control flow statements, and as long as
48 ///      kill hasn't been used), one SGPR can be saved by recovering WQM from
49 ///      the LiveMask (this is implemented for the entry block).
50 ///
51 ///  (2) when entire regions (e.g. if-else blocks or entire loops) only
52 ///      consist of exact and don't-care instructions, the switch only has to
53 ///      be done at the entry and exit points rather than potentially in each
54 ///      block of the region.
55 ///
56 //===----------------------------------------------------------------------===//
57 
58 #include "AMDGPU.h"
59 #include "AMDGPUSubtarget.h"
60 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
61 #include "SIInstrInfo.h"
62 #include "SIMachineFunctionInfo.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/MapVector.h"
65 #include "llvm/ADT/PostOrderIterator.h"
66 #include "llvm/ADT/SmallVector.h"
67 #include "llvm/ADT/StringRef.h"
68 #include "llvm/CodeGen/LiveInterval.h"
69 #include "llvm/CodeGen/LiveIntervals.h"
70 #include "llvm/CodeGen/MachineBasicBlock.h"
71 #include "llvm/CodeGen/MachineFunction.h"
72 #include "llvm/CodeGen/MachineFunctionPass.h"
73 #include "llvm/CodeGen/MachineInstr.h"
74 #include "llvm/CodeGen/MachineInstrBuilder.h"
75 #include "llvm/CodeGen/MachineOperand.h"
76 #include "llvm/CodeGen/MachineRegisterInfo.h"
77 #include "llvm/CodeGen/SlotIndexes.h"
78 #include "llvm/CodeGen/TargetRegisterInfo.h"
79 #include "llvm/IR/CallingConv.h"
80 #include "llvm/IR/DebugLoc.h"
81 #include "llvm/InitializePasses.h"
82 #include "llvm/MC/MCRegisterInfo.h"
83 #include "llvm/Pass.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/raw_ostream.h"
86 #include <cassert>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "si-wqm"
92 
93 namespace {
94 
95 enum {
96   StateWQM = 0x1,
97   StateWWM = 0x2,
98   StateExact = 0x4,
99 };
100 
101 struct PrintState {
102 public:
103   int State;
104 
105   explicit PrintState(int State) : State(State) {}
106 };
107 
108 #ifndef NDEBUG
109 static raw_ostream &operator<<(raw_ostream &OS, const PrintState &PS) {
110   if (PS.State & StateWQM)
111     OS << "WQM";
112   if (PS.State & StateWWM) {
113     if (PS.State & StateWQM)
114       OS << '|';
115     OS << "WWM";
116   }
117   if (PS.State & StateExact) {
118     if (PS.State & (StateWQM | StateWWM))
119       OS << '|';
120     OS << "Exact";
121   }
122 
123   return OS;
124 }
125 #endif
126 
127 struct InstrInfo {
128   char Needs = 0;
129   char Disabled = 0;
130   char OutNeeds = 0;
131 };
132 
133 struct BlockInfo {
134   char Needs = 0;
135   char InNeeds = 0;
136   char OutNeeds = 0;
137 };
138 
139 struct WorkItem {
140   MachineBasicBlock *MBB = nullptr;
141   MachineInstr *MI = nullptr;
142 
143   WorkItem() = default;
144   WorkItem(MachineBasicBlock *MBB) : MBB(MBB) {}
145   WorkItem(MachineInstr *MI) : MI(MI) {}
146 };
147 
148 class SIWholeQuadMode : public MachineFunctionPass {
149 private:
150   CallingConv::ID CallingConv;
151   const SIInstrInfo *TII;
152   const SIRegisterInfo *TRI;
153   const GCNSubtarget *ST;
154   MachineRegisterInfo *MRI;
155   LiveIntervals *LIS;
156 
157   unsigned AndOpc;
158   unsigned XorTermrOpc;
159   unsigned OrSaveExecOpc;
160   unsigned Exec;
161 
162   DenseMap<const MachineInstr *, InstrInfo> Instructions;
163   MapVector<MachineBasicBlock *, BlockInfo> Blocks;
164   SmallVector<MachineInstr *, 1> LiveMaskQueries;
165   SmallVector<MachineInstr *, 4> LowerToMovInstrs;
166   SmallVector<MachineInstr *, 4> LowerToCopyInstrs;
167 
168   void printInfo();
169 
170   void markInstruction(MachineInstr &MI, char Flag,
171                        std::vector<WorkItem> &Worklist);
172   void markDefs(const MachineInstr &UseMI, LiveRange &LR, Register Reg,
173                 unsigned SubReg, char Flag, std::vector<WorkItem> &Worklist);
174   void markInstructionUses(const MachineInstr &MI, char Flag,
175                            std::vector<WorkItem> &Worklist);
176   char scanInstructions(MachineFunction &MF, std::vector<WorkItem> &Worklist);
177   void propagateInstruction(MachineInstr &MI, std::vector<WorkItem> &Worklist);
178   void propagateBlock(MachineBasicBlock &MBB, std::vector<WorkItem> &Worklist);
179   char analyzeFunction(MachineFunction &MF);
180 
181   MachineBasicBlock::iterator saveSCC(MachineBasicBlock &MBB,
182                                       MachineBasicBlock::iterator Before);
183   MachineBasicBlock::iterator
184   prepareInsertion(MachineBasicBlock &MBB, MachineBasicBlock::iterator First,
185                    MachineBasicBlock::iterator Last, bool PreferLast,
186                    bool SaveSCC);
187   void toExact(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
188                unsigned SaveWQM, unsigned LiveMaskReg);
189   void toWQM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
190              unsigned SavedWQM);
191   void toWWM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
192              unsigned SaveOrig);
193   void fromWWM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
194                unsigned SavedOrig);
195   void processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg, bool isEntry);
196 
197   void lowerLiveMaskQueries(unsigned LiveMaskReg);
198   void lowerCopyInstrs();
199 
200 public:
201   static char ID;
202 
203   SIWholeQuadMode() :
204     MachineFunctionPass(ID) { }
205 
206   bool runOnMachineFunction(MachineFunction &MF) override;
207 
208   StringRef getPassName() const override { return "SI Whole Quad Mode"; }
209 
210   void getAnalysisUsage(AnalysisUsage &AU) const override {
211     AU.addRequired<LiveIntervals>();
212     AU.addPreserved<SlotIndexes>();
213     AU.addPreserved<LiveIntervals>();
214     AU.setPreservesCFG();
215     MachineFunctionPass::getAnalysisUsage(AU);
216   }
217 };
218 
219 } // end anonymous namespace
220 
221 char SIWholeQuadMode::ID = 0;
222 
223 INITIALIZE_PASS_BEGIN(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false,
224                       false)
225 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
226 INITIALIZE_PASS_END(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false,
227                     false)
228 
229 char &llvm::SIWholeQuadModeID = SIWholeQuadMode::ID;
230 
231 FunctionPass *llvm::createSIWholeQuadModePass() {
232   return new SIWholeQuadMode;
233 }
234 
235 #ifndef NDEBUG
236 LLVM_DUMP_METHOD void SIWholeQuadMode::printInfo() {
237   for (const auto &BII : Blocks) {
238     dbgs() << "\n"
239            << printMBBReference(*BII.first) << ":\n"
240            << "  InNeeds = " << PrintState(BII.second.InNeeds)
241            << ", Needs = " << PrintState(BII.second.Needs)
242            << ", OutNeeds = " << PrintState(BII.second.OutNeeds) << "\n\n";
243 
244     for (const MachineInstr &MI : *BII.first) {
245       auto III = Instructions.find(&MI);
246       if (III == Instructions.end())
247         continue;
248 
249       dbgs() << "  " << MI << "    Needs = " << PrintState(III->second.Needs)
250              << ", OutNeeds = " << PrintState(III->second.OutNeeds) << '\n';
251     }
252   }
253 }
254 #endif
255 
256 void SIWholeQuadMode::markInstruction(MachineInstr &MI, char Flag,
257                                       std::vector<WorkItem> &Worklist) {
258   InstrInfo &II = Instructions[&MI];
259 
260   assert(!(Flag & StateExact) && Flag != 0);
261 
262   LLVM_DEBUG(dbgs() << "markInstruction " << PrintState(Flag) << ": " << MI);
263 
264   // Remove any disabled states from the flag. The user that required it gets
265   // an undefined value in the helper lanes. For example, this can happen if
266   // the result of an atomic is used by instruction that requires WQM, where
267   // ignoring the request for WQM is correct as per the relevant specs.
268   Flag &= ~II.Disabled;
269 
270   // Ignore if the flag is already encompassed by the existing needs, or we
271   // just disabled everything.
272   if ((II.Needs & Flag) == Flag)
273     return;
274 
275   II.Needs |= Flag;
276   Worklist.push_back(&MI);
277 }
278 
279 /// Mark all relevant definitions of register \p Reg in usage \p UseMI.
280 void SIWholeQuadMode::markDefs(const MachineInstr &UseMI, LiveRange &LR,
281                                Register Reg, unsigned SubReg, char Flag,
282                                std::vector<WorkItem> &Worklist) {
283   assert(!MRI->isSSA());
284 
285   LLVM_DEBUG(dbgs() << "markDefs " << PrintState(Flag) << ": " << UseMI);
286 
287   LiveQueryResult UseLRQ = LR.Query(LIS->getInstructionIndex(UseMI));
288   if (!UseLRQ.valueIn())
289     return;
290 
291   SmallPtrSet<const VNInfo *, 4> Visited;
292   SmallVector<const VNInfo *, 4> ToProcess;
293   ToProcess.push_back(UseLRQ.valueIn());
294   do {
295     const VNInfo *Value = ToProcess.pop_back_val();
296     Visited.insert(Value);
297 
298     if (Value->isPHIDef()) {
299       // Need to mark all defs used in the PHI node
300       const MachineBasicBlock *MBB = LIS->getMBBFromIndex(Value->def);
301       assert(MBB && "Phi-def has no defining MBB");
302       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
303                                                   PE = MBB->pred_end();
304            PI != PE; ++PI) {
305         if (const VNInfo *VN = LR.getVNInfoBefore(LIS->getMBBEndIdx(*PI))) {
306           if (!Visited.count(VN))
307             ToProcess.push_back(VN);
308         }
309       }
310     } else {
311       MachineInstr *MI = LIS->getInstructionFromIndex(Value->def);
312       assert(MI && "Def has no defining instruction");
313       markInstruction(*MI, Flag, Worklist);
314 
315       // Iterate over all operands to find relevant definitions
316       for (const MachineOperand &Op : MI->operands()) {
317         if (!(Op.isReg() && Op.getReg() == Reg))
318           continue;
319 
320         // Does this def cover whole register?
321         bool DefinesFullReg =
322             Op.isUndef() || !Op.getSubReg() || Op.getSubReg() == SubReg;
323         if (!DefinesFullReg) {
324           // Partial definition; need to follow and mark input value
325           LiveQueryResult LRQ = LR.Query(LIS->getInstructionIndex(*MI));
326           if (const VNInfo *VN = LRQ.valueIn()) {
327             if (!Visited.count(VN))
328               ToProcess.push_back(VN);
329           }
330         }
331       }
332     }
333   } while (!ToProcess.empty());
334 }
335 
336 /// Mark all instructions defining the uses in \p MI with \p Flag.
337 void SIWholeQuadMode::markInstructionUses(const MachineInstr &MI, char Flag,
338                                           std::vector<WorkItem> &Worklist) {
339 
340   LLVM_DEBUG(dbgs() << "markInstructionUses " << PrintState(Flag) << ": "
341                     << MI);
342 
343   for (const MachineOperand &Use : MI.uses()) {
344     if (!Use.isReg() || !Use.isUse())
345       continue;
346 
347     Register Reg = Use.getReg();
348 
349     // Handle physical registers that we need to track; this is mostly relevant
350     // for VCC, which can appear as the (implicit) input of a uniform branch,
351     // e.g. when a loop counter is stored in a VGPR.
352     if (!Reg.isVirtual()) {
353       if (Reg == AMDGPU::EXEC || Reg == AMDGPU::EXEC_LO)
354         continue;
355 
356       for (MCRegUnitIterator RegUnit(Reg, TRI); RegUnit.isValid(); ++RegUnit) {
357         LiveRange &LR = LIS->getRegUnit(*RegUnit);
358         const VNInfo *Value = LR.Query(LIS->getInstructionIndex(MI)).valueIn();
359         if (!Value)
360           continue;
361 
362         if (MRI->isSSA()) {
363           // Since we're in machine SSA, we do not need to track physical
364           // registers across basic blocks.
365           if (Value->isPHIDef())
366             continue;
367           markInstruction(*LIS->getInstructionFromIndex(Value->def), Flag,
368                           Worklist);
369         } else {
370           markDefs(MI, LR, *RegUnit, AMDGPU::NoSubRegister, Flag, Worklist);
371         }
372       }
373 
374       continue;
375     }
376 
377     if (MRI->isSSA()) {
378       for (MachineInstr &DefMI : MRI->def_instructions(Use.getReg()))
379         markInstruction(DefMI, Flag, Worklist);
380     } else {
381       LiveRange &LR = LIS->getInterval(Reg);
382       markDefs(MI, LR, Reg, Use.getSubReg(), Flag, Worklist);
383     }
384   }
385 }
386 
387 // Scan instructions to determine which ones require an Exact execmask and
388 // which ones seed WQM requirements.
389 char SIWholeQuadMode::scanInstructions(MachineFunction &MF,
390                                        std::vector<WorkItem> &Worklist) {
391   char GlobalFlags = 0;
392   bool WQMOutputs = MF.getFunction().hasFnAttribute("amdgpu-ps-wqm-outputs");
393   SmallVector<MachineInstr *, 4> SetInactiveInstrs;
394   SmallVector<MachineInstr *, 4> SoftWQMInstrs;
395 
396   // We need to visit the basic blocks in reverse post-order so that we visit
397   // defs before uses, in particular so that we don't accidentally mark an
398   // instruction as needing e.g. WQM before visiting it and realizing it needs
399   // WQM disabled.
400   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
401   for (auto BI = RPOT.begin(), BE = RPOT.end(); BI != BE; ++BI) {
402     MachineBasicBlock &MBB = **BI;
403     BlockInfo &BBI = Blocks[&MBB];
404 
405     for (auto II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
406       MachineInstr &MI = *II;
407       InstrInfo &III = Instructions[&MI];
408       unsigned Opcode = MI.getOpcode();
409       char Flags = 0;
410 
411       if (TII->isWQM(Opcode)) {
412         // Sampling instructions don't need to produce results for all pixels
413         // in a quad, they just require all inputs of a quad to have been
414         // computed for derivatives.
415         markInstructionUses(MI, StateWQM, Worklist);
416         GlobalFlags |= StateWQM;
417         continue;
418       } else if (Opcode == AMDGPU::WQM) {
419         // The WQM intrinsic requires its output to have all the helper lanes
420         // correct, so we need it to be in WQM.
421         Flags = StateWQM;
422         LowerToCopyInstrs.push_back(&MI);
423       } else if (Opcode == AMDGPU::SOFT_WQM) {
424         LowerToCopyInstrs.push_back(&MI);
425         SoftWQMInstrs.push_back(&MI);
426         continue;
427       } else if (Opcode == AMDGPU::WWM) {
428         // The WWM intrinsic doesn't make the same guarantee, and plus it needs
429         // to be executed in WQM or Exact so that its copy doesn't clobber
430         // inactive lanes.
431         markInstructionUses(MI, StateWWM, Worklist);
432         GlobalFlags |= StateWWM;
433         LowerToMovInstrs.push_back(&MI);
434         continue;
435       } else if (Opcode == AMDGPU::V_SET_INACTIVE_B32 ||
436                  Opcode == AMDGPU::V_SET_INACTIVE_B64) {
437         III.Disabled = StateWWM;
438         MachineOperand &Inactive = MI.getOperand(2);
439         if (Inactive.isReg()) {
440           if (Inactive.isUndef()) {
441             LowerToCopyInstrs.push_back(&MI);
442           } else {
443             Register Reg = Inactive.getReg();
444             if (Reg.isVirtual()) {
445               for (MachineInstr &DefMI : MRI->def_instructions(Reg))
446                 markInstruction(DefMI, StateWWM, Worklist);
447             }
448           }
449         }
450         SetInactiveInstrs.push_back(&MI);
451         continue;
452       } else if (TII->isDisableWQM(MI)) {
453         BBI.Needs |= StateExact;
454         if (!(BBI.InNeeds & StateExact)) {
455           BBI.InNeeds |= StateExact;
456           Worklist.push_back(&MBB);
457         }
458         GlobalFlags |= StateExact;
459         III.Disabled = StateWQM | StateWWM;
460         continue;
461       } else {
462         if (Opcode == AMDGPU::SI_PS_LIVE) {
463           LiveMaskQueries.push_back(&MI);
464         } else if (WQMOutputs) {
465           // The function is in machine SSA form, which means that physical
466           // VGPRs correspond to shader inputs and outputs. Inputs are
467           // only used, outputs are only defined.
468           for (const MachineOperand &MO : MI.defs()) {
469             if (!MO.isReg())
470               continue;
471 
472             Register Reg = MO.getReg();
473 
474             if (!Reg.isVirtual() &&
475                 TRI->hasVectorRegisters(TRI->getPhysRegClass(Reg))) {
476               Flags = StateWQM;
477               break;
478             }
479           }
480         }
481 
482         if (!Flags)
483           continue;
484       }
485 
486       markInstruction(MI, Flags, Worklist);
487       GlobalFlags |= Flags;
488     }
489   }
490 
491   // Mark sure that any SET_INACTIVE instructions are computed in WQM if WQM is
492   // ever used anywhere in the function. This implements the corresponding
493   // semantics of @llvm.amdgcn.set.inactive.
494   // Similarly for SOFT_WQM instructions, implementing @llvm.amdgcn.softwqm.
495   if (GlobalFlags & StateWQM) {
496     for (MachineInstr *MI : SetInactiveInstrs)
497       markInstruction(*MI, StateWQM, Worklist);
498     for (MachineInstr *MI : SoftWQMInstrs)
499       markInstruction(*MI, StateWQM, Worklist);
500   }
501 
502   return GlobalFlags;
503 }
504 
505 void SIWholeQuadMode::propagateInstruction(MachineInstr &MI,
506                                            std::vector<WorkItem>& Worklist) {
507   MachineBasicBlock *MBB = MI.getParent();
508   InstrInfo II = Instructions[&MI]; // take a copy to prevent dangling references
509   BlockInfo &BI = Blocks[MBB];
510 
511   // Control flow-type instructions and stores to temporary memory that are
512   // followed by WQM computations must themselves be in WQM.
513   if ((II.OutNeeds & StateWQM) && !(II.Disabled & StateWQM) &&
514       (MI.isTerminator() || (TII->usesVM_CNT(MI) && MI.mayStore()))) {
515     Instructions[&MI].Needs = StateWQM;
516     II.Needs = StateWQM;
517   }
518 
519   // Propagate to block level
520   if (II.Needs & StateWQM) {
521     BI.Needs |= StateWQM;
522     if (!(BI.InNeeds & StateWQM)) {
523       BI.InNeeds |= StateWQM;
524       Worklist.push_back(MBB);
525     }
526   }
527 
528   // Propagate backwards within block
529   if (MachineInstr *PrevMI = MI.getPrevNode()) {
530     char InNeeds = (II.Needs & ~StateWWM) | II.OutNeeds;
531     if (!PrevMI->isPHI()) {
532       InstrInfo &PrevII = Instructions[PrevMI];
533       if ((PrevII.OutNeeds | InNeeds) != PrevII.OutNeeds) {
534         PrevII.OutNeeds |= InNeeds;
535         Worklist.push_back(PrevMI);
536       }
537     }
538   }
539 
540   // Propagate WQM flag to instruction inputs
541   assert(!(II.Needs & StateExact));
542 
543   if (II.Needs != 0)
544     markInstructionUses(MI, II.Needs, Worklist);
545 
546   // Ensure we process a block containing WWM, even if it does not require any
547   // WQM transitions.
548   if (II.Needs & StateWWM)
549     BI.Needs |= StateWWM;
550 }
551 
552 void SIWholeQuadMode::propagateBlock(MachineBasicBlock &MBB,
553                                      std::vector<WorkItem>& Worklist) {
554   BlockInfo BI = Blocks[&MBB]; // Make a copy to prevent dangling references.
555 
556   // Propagate through instructions
557   if (!MBB.empty()) {
558     MachineInstr *LastMI = &*MBB.rbegin();
559     InstrInfo &LastII = Instructions[LastMI];
560     if ((LastII.OutNeeds | BI.OutNeeds) != LastII.OutNeeds) {
561       LastII.OutNeeds |= BI.OutNeeds;
562       Worklist.push_back(LastMI);
563     }
564   }
565 
566   // Predecessor blocks must provide for our WQM/Exact needs.
567   for (MachineBasicBlock *Pred : MBB.predecessors()) {
568     BlockInfo &PredBI = Blocks[Pred];
569     if ((PredBI.OutNeeds | BI.InNeeds) == PredBI.OutNeeds)
570       continue;
571 
572     PredBI.OutNeeds |= BI.InNeeds;
573     PredBI.InNeeds |= BI.InNeeds;
574     Worklist.push_back(Pred);
575   }
576 
577   // All successors must be prepared to accept the same set of WQM/Exact data.
578   for (MachineBasicBlock *Succ : MBB.successors()) {
579     BlockInfo &SuccBI = Blocks[Succ];
580     if ((SuccBI.InNeeds | BI.OutNeeds) == SuccBI.InNeeds)
581       continue;
582 
583     SuccBI.InNeeds |= BI.OutNeeds;
584     Worklist.push_back(Succ);
585   }
586 }
587 
588 char SIWholeQuadMode::analyzeFunction(MachineFunction &MF) {
589   std::vector<WorkItem> Worklist;
590   char GlobalFlags = scanInstructions(MF, Worklist);
591 
592   while (!Worklist.empty()) {
593     WorkItem WI = Worklist.back();
594     Worklist.pop_back();
595 
596     if (WI.MI)
597       propagateInstruction(*WI.MI, Worklist);
598     else
599       propagateBlock(*WI.MBB, Worklist);
600   }
601 
602   return GlobalFlags;
603 }
604 
605 MachineBasicBlock::iterator
606 SIWholeQuadMode::saveSCC(MachineBasicBlock &MBB,
607                          MachineBasicBlock::iterator Before) {
608   Register SaveReg = MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
609 
610   MachineInstr *Save =
611       BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), SaveReg)
612           .addReg(AMDGPU::SCC);
613   MachineInstr *Restore =
614       BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::SCC)
615           .addReg(SaveReg);
616 
617   LIS->InsertMachineInstrInMaps(*Save);
618   LIS->InsertMachineInstrInMaps(*Restore);
619   LIS->createAndComputeVirtRegInterval(SaveReg);
620 
621   return Restore;
622 }
623 
624 // Return an iterator in the (inclusive) range [First, Last] at which
625 // instructions can be safely inserted, keeping in mind that some of the
626 // instructions we want to add necessarily clobber SCC.
627 MachineBasicBlock::iterator SIWholeQuadMode::prepareInsertion(
628     MachineBasicBlock &MBB, MachineBasicBlock::iterator First,
629     MachineBasicBlock::iterator Last, bool PreferLast, bool SaveSCC) {
630   if (!SaveSCC)
631     return PreferLast ? Last : First;
632 
633   LiveRange &LR = LIS->getRegUnit(*MCRegUnitIterator(AMDGPU::SCC, TRI));
634   auto MBBE = MBB.end();
635   SlotIndex FirstIdx = First != MBBE ? LIS->getInstructionIndex(*First)
636                                      : LIS->getMBBEndIdx(&MBB);
637   SlotIndex LastIdx =
638       Last != MBBE ? LIS->getInstructionIndex(*Last) : LIS->getMBBEndIdx(&MBB);
639   SlotIndex Idx = PreferLast ? LastIdx : FirstIdx;
640   const LiveRange::Segment *S;
641 
642   for (;;) {
643     S = LR.getSegmentContaining(Idx);
644     if (!S)
645       break;
646 
647     if (PreferLast) {
648       SlotIndex Next = S->start.getBaseIndex();
649       if (Next < FirstIdx)
650         break;
651       Idx = Next;
652     } else {
653       MachineInstr *EndMI = LIS->getInstructionFromIndex(S->end.getBaseIndex());
654       assert(EndMI && "Segment does not end on valid instruction");
655       auto NextI = std::next(EndMI->getIterator());
656       if (NextI == MBB.end())
657         break;
658       SlotIndex Next = LIS->getInstructionIndex(*NextI);
659       if (Next > LastIdx)
660         break;
661       Idx = Next;
662     }
663   }
664 
665   MachineBasicBlock::iterator MBBI;
666 
667   if (MachineInstr *MI = LIS->getInstructionFromIndex(Idx))
668     MBBI = MI;
669   else {
670     assert(Idx == LIS->getMBBEndIdx(&MBB));
671     MBBI = MBB.end();
672   }
673 
674   // Move insertion point past any operations modifying EXEC.
675   // This assumes that the value of SCC defined by any of these operations
676   // does not need to be preserved.
677   while (MBBI != Last) {
678     bool IsExecDef = false;
679     for (const MachineOperand &MO : MBBI->operands()) {
680       if (MO.isReg() && MO.isDef()) {
681         IsExecDef |=
682             MO.getReg() == AMDGPU::EXEC_LO || MO.getReg() == AMDGPU::EXEC;
683       }
684     }
685     if (!IsExecDef)
686       break;
687     MBBI++;
688     S = nullptr;
689   }
690 
691   if (S)
692     MBBI = saveSCC(MBB, MBBI);
693 
694   return MBBI;
695 }
696 
697 void SIWholeQuadMode::toExact(MachineBasicBlock &MBB,
698                               MachineBasicBlock::iterator Before,
699                               unsigned SaveWQM, unsigned LiveMaskReg) {
700   MachineInstr *MI;
701 
702   if (SaveWQM) {
703     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(ST->isWave32() ?
704                    AMDGPU::S_AND_SAVEEXEC_B32 : AMDGPU::S_AND_SAVEEXEC_B64),
705                  SaveWQM)
706              .addReg(LiveMaskReg);
707   } else {
708     unsigned Exec = ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
709     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(ST->isWave32() ?
710                    AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64),
711                  Exec)
712              .addReg(Exec)
713              .addReg(LiveMaskReg);
714   }
715 
716   LIS->InsertMachineInstrInMaps(*MI);
717 }
718 
719 void SIWholeQuadMode::toWQM(MachineBasicBlock &MBB,
720                             MachineBasicBlock::iterator Before,
721                             unsigned SavedWQM) {
722   MachineInstr *MI;
723 
724   unsigned Exec = ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
725   if (SavedWQM) {
726     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), Exec)
727              .addReg(SavedWQM);
728   } else {
729     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(ST->isWave32() ?
730                    AMDGPU::S_WQM_B32 : AMDGPU::S_WQM_B64),
731                  Exec)
732              .addReg(Exec);
733   }
734 
735   LIS->InsertMachineInstrInMaps(*MI);
736 }
737 
738 void SIWholeQuadMode::toWWM(MachineBasicBlock &MBB,
739                             MachineBasicBlock::iterator Before,
740                             unsigned SaveOrig) {
741   MachineInstr *MI;
742 
743   assert(SaveOrig);
744   MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::ENTER_WWM), SaveOrig)
745            .addImm(-1);
746   LIS->InsertMachineInstrInMaps(*MI);
747 }
748 
749 void SIWholeQuadMode::fromWWM(MachineBasicBlock &MBB,
750                               MachineBasicBlock::iterator Before,
751                               unsigned SavedOrig) {
752   MachineInstr *MI;
753 
754   assert(SavedOrig);
755   MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::EXIT_WWM),
756                ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC)
757            .addReg(SavedOrig);
758   LIS->InsertMachineInstrInMaps(*MI);
759 }
760 
761 void SIWholeQuadMode::processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg,
762                                    bool isEntry) {
763   auto BII = Blocks.find(&MBB);
764   if (BII == Blocks.end())
765     return;
766 
767   const BlockInfo &BI = BII->second;
768 
769   // This is a non-entry block that is WQM throughout, so no need to do
770   // anything.
771   if (!isEntry && BI.Needs == StateWQM && BI.OutNeeds != StateExact)
772     return;
773 
774   LLVM_DEBUG(dbgs() << "\nProcessing block " << printMBBReference(MBB)
775                     << ":\n");
776 
777   unsigned SavedWQMReg = 0;
778   unsigned SavedNonWWMReg = 0;
779   bool WQMFromExec = isEntry;
780   char State = (isEntry || !(BI.InNeeds & StateWQM)) ? StateExact : StateWQM;
781   char NonWWMState = 0;
782   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
783 
784   auto II = MBB.getFirstNonPHI(), IE = MBB.end();
785   if (isEntry) {
786     // Skip the instruction that saves LiveMask
787     if (II != IE && II->getOpcode() == AMDGPU::COPY)
788       ++II;
789   }
790 
791   // This stores the first instruction where it's safe to switch from WQM to
792   // Exact or vice versa.
793   MachineBasicBlock::iterator FirstWQM = IE;
794 
795   // This stores the first instruction where it's safe to switch from WWM to
796   // Exact/WQM or to switch to WWM. It must always be the same as, or after,
797   // FirstWQM since if it's safe to switch to/from WWM, it must be safe to
798   // switch to/from WQM as well.
799   MachineBasicBlock::iterator FirstWWM = IE;
800 
801   for (;;) {
802     MachineBasicBlock::iterator Next = II;
803     char Needs = StateExact | StateWQM; // WWM is disabled by default
804     char OutNeeds = 0;
805 
806     if (FirstWQM == IE)
807       FirstWQM = II;
808 
809     if (FirstWWM == IE)
810       FirstWWM = II;
811 
812     // First, figure out the allowed states (Needs) based on the propagated
813     // flags.
814     if (II != IE) {
815       MachineInstr &MI = *II;
816 
817       if (MI.isTerminator() || TII->mayReadEXEC(*MRI, MI)) {
818         auto III = Instructions.find(&MI);
819         if (III != Instructions.end()) {
820           if (III->second.Needs & StateWWM)
821             Needs = StateWWM;
822           else if (III->second.Needs & StateWQM)
823             Needs = StateWQM;
824           else
825             Needs &= ~III->second.Disabled;
826           OutNeeds = III->second.OutNeeds;
827         }
828       } else {
829         // If the instruction doesn't actually need a correct EXEC, then we can
830         // safely leave WWM enabled.
831         Needs = StateExact | StateWQM | StateWWM;
832       }
833 
834       if (MI.isTerminator() && OutNeeds == StateExact)
835         Needs = StateExact;
836 
837       ++Next;
838     } else {
839       // End of basic block
840       if (BI.OutNeeds & StateWQM)
841         Needs = StateWQM;
842       else if (BI.OutNeeds == StateExact)
843         Needs = StateExact;
844       else
845         Needs = StateWQM | StateExact;
846     }
847 
848     // Now, transition if necessary.
849     if (!(Needs & State)) {
850       MachineBasicBlock::iterator First;
851       if (State == StateWWM || Needs == StateWWM) {
852         // We must switch to or from WWM
853         First = FirstWWM;
854       } else {
855         // We only need to switch to/from WQM, so we can use FirstWQM
856         First = FirstWQM;
857       }
858 
859       MachineBasicBlock::iterator Before =
860           prepareInsertion(MBB, First, II, Needs == StateWQM,
861                            Needs == StateExact || WQMFromExec);
862 
863       if (State == StateWWM) {
864         assert(SavedNonWWMReg);
865         fromWWM(MBB, Before, SavedNonWWMReg);
866         LIS->createAndComputeVirtRegInterval(SavedNonWWMReg);
867         SavedNonWWMReg = 0;
868         State = NonWWMState;
869       }
870 
871       if (Needs == StateWWM) {
872         NonWWMState = State;
873         assert(!SavedNonWWMReg);
874         SavedNonWWMReg = MRI->createVirtualRegister(BoolRC);
875         toWWM(MBB, Before, SavedNonWWMReg);
876         State = StateWWM;
877       } else {
878         if (State == StateWQM && (Needs & StateExact) && !(Needs & StateWQM)) {
879           if (!WQMFromExec && (OutNeeds & StateWQM)) {
880             assert(!SavedWQMReg);
881             SavedWQMReg = MRI->createVirtualRegister(BoolRC);
882           }
883 
884           toExact(MBB, Before, SavedWQMReg, LiveMaskReg);
885           State = StateExact;
886         } else if (State == StateExact && (Needs & StateWQM) &&
887                    !(Needs & StateExact)) {
888           assert(WQMFromExec == (SavedWQMReg == 0));
889 
890           toWQM(MBB, Before, SavedWQMReg);
891 
892           if (SavedWQMReg) {
893             LIS->createAndComputeVirtRegInterval(SavedWQMReg);
894             SavedWQMReg = 0;
895           }
896           State = StateWQM;
897         } else {
898           // We can get here if we transitioned from WWM to a non-WWM state that
899           // already matches our needs, but we shouldn't need to do anything.
900           assert(Needs & State);
901         }
902       }
903     }
904 
905     if (Needs != (StateExact | StateWQM | StateWWM)) {
906       if (Needs != (StateExact | StateWQM))
907         FirstWQM = IE;
908       FirstWWM = IE;
909     }
910 
911     if (II == IE)
912       break;
913 
914     II = Next;
915   }
916   assert(!SavedWQMReg);
917   assert(!SavedNonWWMReg);
918 }
919 
920 void SIWholeQuadMode::lowerLiveMaskQueries(unsigned LiveMaskReg) {
921   for (MachineInstr *MI : LiveMaskQueries) {
922     const DebugLoc &DL = MI->getDebugLoc();
923     Register Dest = MI->getOperand(0).getReg();
924 
925     MachineInstr *Copy =
926         BuildMI(*MI->getParent(), MI, DL, TII->get(AMDGPU::COPY), Dest)
927             .addReg(LiveMaskReg);
928 
929     LIS->ReplaceMachineInstrInMaps(*MI, *Copy);
930     MI->eraseFromParent();
931   }
932 }
933 
934 void SIWholeQuadMode::lowerCopyInstrs() {
935   for (MachineInstr *MI : LowerToMovInstrs) {
936     assert(MI->getNumExplicitOperands() == 2);
937 
938     const Register Reg = MI->getOperand(0).getReg();
939     const unsigned SubReg = MI->getOperand(0).getSubReg();
940 
941     if (TRI->isVGPR(*MRI, Reg)) {
942       const TargetRegisterClass *regClass =
943           Reg.isVirtual() ? MRI->getRegClass(Reg) : TRI->getPhysRegClass(Reg);
944       if (SubReg)
945         regClass = TRI->getSubRegClass(regClass, SubReg);
946 
947       const unsigned MovOp = TII->getMovOpcode(regClass);
948       MI->setDesc(TII->get(MovOp));
949 
950       // And make it implicitly depend on exec (like all VALU movs should do).
951       MI->addOperand(MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
952     } else if (!MRI->isSSA()) {
953       // Remove early-clobber and exec dependency from simple SGPR copies.
954       // This allows some to be eliminated during/post RA.
955       LLVM_DEBUG(dbgs() << "simplify SGPR copy: " << *MI);
956       if (MI->getOperand(0).isEarlyClobber()) {
957         LIS->removeInterval(Reg);
958         MI->getOperand(0).setIsEarlyClobber(false);
959         LIS->createAndComputeVirtRegInterval(Reg);
960       }
961       int Index = MI->findRegisterUseOperandIdx(AMDGPU::EXEC);
962       while (Index >= 0) {
963         MI->RemoveOperand(Index);
964         Index = MI->findRegisterUseOperandIdx(AMDGPU::EXEC);
965       }
966       MI->setDesc(TII->get(AMDGPU::COPY));
967       LLVM_DEBUG(dbgs() << "  -> " << *MI);
968     }
969   }
970   for (MachineInstr *MI : LowerToCopyInstrs) {
971     if (MI->getOpcode() == AMDGPU::V_SET_INACTIVE_B32 ||
972         MI->getOpcode() == AMDGPU::V_SET_INACTIVE_B64) {
973       assert(MI->getNumExplicitOperands() == 3);
974       // the only reason we should be here is V_SET_INACTIVE has
975       // an undef input so it is being replaced by a simple copy.
976       // There should be a second undef source that we should remove.
977       assert(MI->getOperand(2).isUndef());
978       MI->RemoveOperand(2);
979       MI->untieRegOperand(1);
980     } else {
981       assert(MI->getNumExplicitOperands() == 2);
982     }
983 
984     MI->setDesc(TII->get(AMDGPU::COPY));
985   }
986 }
987 
988 bool SIWholeQuadMode::runOnMachineFunction(MachineFunction &MF) {
989   Instructions.clear();
990   Blocks.clear();
991   LiveMaskQueries.clear();
992   LowerToCopyInstrs.clear();
993   LowerToMovInstrs.clear();
994   CallingConv = MF.getFunction().getCallingConv();
995 
996   ST = &MF.getSubtarget<GCNSubtarget>();
997 
998   TII = ST->getInstrInfo();
999   TRI = &TII->getRegisterInfo();
1000   MRI = &MF.getRegInfo();
1001   LIS = &getAnalysis<LiveIntervals>();
1002 
1003   if (ST->isWave32()) {
1004     AndOpc = AMDGPU::S_AND_B32;
1005     XorTermrOpc = AMDGPU::S_XOR_B32_term;
1006     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B32;
1007     Exec = AMDGPU::EXEC_LO;
1008   } else {
1009     AndOpc = AMDGPU::S_AND_B64;
1010     XorTermrOpc = AMDGPU::S_XOR_B64_term;
1011     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B64;
1012     Exec = AMDGPU::EXEC;
1013   }
1014 
1015   char GlobalFlags = analyzeFunction(MF);
1016   unsigned LiveMaskReg = 0;
1017   if (!(GlobalFlags & StateWQM)) {
1018     lowerLiveMaskQueries(Exec);
1019     if (!(GlobalFlags & StateWWM) && LowerToCopyInstrs.empty() && LowerToMovInstrs.empty())
1020       return !LiveMaskQueries.empty();
1021   } else {
1022     // Store a copy of the original live mask when required
1023     MachineBasicBlock &Entry = MF.front();
1024     MachineBasicBlock::iterator EntryMI = Entry.getFirstNonPHI();
1025 
1026     if (GlobalFlags & StateExact || !LiveMaskQueries.empty()) {
1027       LiveMaskReg = MRI->createVirtualRegister(TRI->getBoolRC());
1028       MachineInstr *MI = BuildMI(Entry, EntryMI, DebugLoc(),
1029                                  TII->get(AMDGPU::COPY), LiveMaskReg)
1030                              .addReg(Exec);
1031       LIS->InsertMachineInstrInMaps(*MI);
1032     }
1033 
1034     lowerLiveMaskQueries(LiveMaskReg);
1035 
1036     if (GlobalFlags == StateWQM) {
1037       // For a shader that needs only WQM, we can just set it once.
1038       auto MI = BuildMI(Entry, EntryMI, DebugLoc(),
1039                         TII->get(ST->isWave32() ? AMDGPU::S_WQM_B32
1040                                                 : AMDGPU::S_WQM_B64),
1041                         Exec)
1042                     .addReg(Exec);
1043       LIS->InsertMachineInstrInMaps(*MI);
1044 
1045       lowerCopyInstrs();
1046       // EntryMI may become invalid here
1047       return true;
1048     }
1049   }
1050 
1051   LLVM_DEBUG(printInfo());
1052 
1053   lowerCopyInstrs();
1054 
1055   // Handle the general case
1056   for (auto BII : Blocks)
1057     processBlock(*BII.first, LiveMaskReg, BII.first == &*MF.begin());
1058 
1059   if (LiveMaskReg)
1060     LIS->createAndComputeVirtRegInterval(LiveMaskReg);
1061 
1062   // Physical registers like SCC aren't tracked by default anyway, so just
1063   // removing the ranges we computed is the simplest option for maintaining
1064   // the analysis results.
1065   LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::SCC, TRI));
1066 
1067   return true;
1068 }
1069