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   DenseMap<const MachineInstr *, InstrInfo> Instructions;
158   MapVector<MachineBasicBlock *, BlockInfo> Blocks;
159   SmallVector<MachineInstr *, 1> LiveMaskQueries;
160   SmallVector<MachineInstr *, 4> LowerToMovInstrs;
161   SmallVector<MachineInstr *, 4> LowerToCopyInstrs;
162 
163   void printInfo();
164 
165   void markInstruction(MachineInstr &MI, char Flag,
166                        std::vector<WorkItem> &Worklist);
167   void markInstructionUses(const MachineInstr &MI, char Flag,
168                            std::vector<WorkItem> &Worklist);
169   char scanInstructions(MachineFunction &MF, std::vector<WorkItem> &Worklist);
170   void propagateInstruction(MachineInstr &MI, std::vector<WorkItem> &Worklist);
171   void propagateBlock(MachineBasicBlock &MBB, std::vector<WorkItem> &Worklist);
172   char analyzeFunction(MachineFunction &MF);
173 
174   bool requiresCorrectState(const MachineInstr &MI) const;
175 
176   MachineBasicBlock::iterator saveSCC(MachineBasicBlock &MBB,
177                                       MachineBasicBlock::iterator Before);
178   MachineBasicBlock::iterator
179   prepareInsertion(MachineBasicBlock &MBB, MachineBasicBlock::iterator First,
180                    MachineBasicBlock::iterator Last, bool PreferLast,
181                    bool SaveSCC);
182   void toExact(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
183                unsigned SaveWQM, unsigned LiveMaskReg);
184   void toWQM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
185              unsigned SavedWQM);
186   void toWWM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
187              unsigned SaveOrig);
188   void fromWWM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
189                unsigned SavedOrig);
190   void processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg, bool isEntry);
191 
192   void lowerLiveMaskQueries(unsigned LiveMaskReg);
193   void lowerCopyInstrs();
194 
195 public:
196   static char ID;
197 
198   SIWholeQuadMode() :
199     MachineFunctionPass(ID) { }
200 
201   bool runOnMachineFunction(MachineFunction &MF) override;
202 
203   StringRef getPassName() const override { return "SI Whole Quad Mode"; }
204 
205   void getAnalysisUsage(AnalysisUsage &AU) const override {
206     AU.addRequired<LiveIntervals>();
207     AU.addPreserved<SlotIndexes>();
208     AU.addPreserved<LiveIntervals>();
209     AU.setPreservesCFG();
210     MachineFunctionPass::getAnalysisUsage(AU);
211   }
212 };
213 
214 } // end anonymous namespace
215 
216 char SIWholeQuadMode::ID = 0;
217 
218 INITIALIZE_PASS_BEGIN(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false,
219                       false)
220 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
221 INITIALIZE_PASS_END(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false,
222                     false)
223 
224 char &llvm::SIWholeQuadModeID = SIWholeQuadMode::ID;
225 
226 FunctionPass *llvm::createSIWholeQuadModePass() {
227   return new SIWholeQuadMode;
228 }
229 
230 #ifndef NDEBUG
231 LLVM_DUMP_METHOD void SIWholeQuadMode::printInfo() {
232   for (const auto &BII : Blocks) {
233     dbgs() << "\n"
234            << printMBBReference(*BII.first) << ":\n"
235            << "  InNeeds = " << PrintState(BII.second.InNeeds)
236            << ", Needs = " << PrintState(BII.second.Needs)
237            << ", OutNeeds = " << PrintState(BII.second.OutNeeds) << "\n\n";
238 
239     for (const MachineInstr &MI : *BII.first) {
240       auto III = Instructions.find(&MI);
241       if (III == Instructions.end())
242         continue;
243 
244       dbgs() << "  " << MI << "    Needs = " << PrintState(III->second.Needs)
245              << ", OutNeeds = " << PrintState(III->second.OutNeeds) << '\n';
246     }
247   }
248 }
249 #endif
250 
251 void SIWholeQuadMode::markInstruction(MachineInstr &MI, char Flag,
252                                       std::vector<WorkItem> &Worklist) {
253   InstrInfo &II = Instructions[&MI];
254 
255   assert(!(Flag & StateExact) && Flag != 0);
256 
257   // Remove any disabled states from the flag. The user that required it gets
258   // an undefined value in the helper lanes. For example, this can happen if
259   // the result of an atomic is used by instruction that requires WQM, where
260   // ignoring the request for WQM is correct as per the relevant specs.
261   Flag &= ~II.Disabled;
262 
263   // Ignore if the flag is already encompassed by the existing needs, or we
264   // just disabled everything.
265   if ((II.Needs & Flag) == Flag)
266     return;
267 
268   II.Needs |= Flag;
269   Worklist.push_back(&MI);
270 }
271 
272 /// Mark all instructions defining the uses in \p MI with \p Flag.
273 void SIWholeQuadMode::markInstructionUses(const MachineInstr &MI, char Flag,
274                                           std::vector<WorkItem> &Worklist) {
275   for (const MachineOperand &Use : MI.uses()) {
276     if (!Use.isReg() || !Use.isUse())
277       continue;
278 
279     Register Reg = Use.getReg();
280 
281     // Handle physical registers that we need to track; this is mostly relevant
282     // for VCC, which can appear as the (implicit) input of a uniform branch,
283     // e.g. when a loop counter is stored in a VGPR.
284     if (!Register::isVirtualRegister(Reg)) {
285       if (Reg == AMDGPU::EXEC || Reg == AMDGPU::EXEC_LO)
286         continue;
287 
288       for (MCRegUnitIterator RegUnit(Reg, TRI); RegUnit.isValid(); ++RegUnit) {
289         LiveRange &LR = LIS->getRegUnit(*RegUnit);
290         const VNInfo *Value = LR.Query(LIS->getInstructionIndex(MI)).valueIn();
291         if (!Value)
292           continue;
293 
294         // Since we're in machine SSA, we do not need to track physical
295         // registers across basic blocks.
296         if (Value->isPHIDef())
297           continue;
298 
299         markInstruction(*LIS->getInstructionFromIndex(Value->def), Flag,
300                         Worklist);
301       }
302 
303       continue;
304     }
305 
306     for (MachineInstr &DefMI : MRI->def_instructions(Use.getReg()))
307       markInstruction(DefMI, Flag, Worklist);
308   }
309 }
310 
311 // Scan instructions to determine which ones require an Exact execmask and
312 // which ones seed WQM requirements.
313 char SIWholeQuadMode::scanInstructions(MachineFunction &MF,
314                                        std::vector<WorkItem> &Worklist) {
315   char GlobalFlags = 0;
316   bool WQMOutputs = MF.getFunction().hasFnAttribute("amdgpu-ps-wqm-outputs");
317   SmallVector<MachineInstr *, 4> SetInactiveInstrs;
318   SmallVector<MachineInstr *, 4> SoftWQMInstrs;
319 
320   // We need to visit the basic blocks in reverse post-order so that we visit
321   // defs before uses, in particular so that we don't accidentally mark an
322   // instruction as needing e.g. WQM before visiting it and realizing it needs
323   // WQM disabled.
324   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
325   for (auto BI = RPOT.begin(), BE = RPOT.end(); BI != BE; ++BI) {
326     MachineBasicBlock &MBB = **BI;
327     BlockInfo &BBI = Blocks[&MBB];
328 
329     for (auto II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
330       MachineInstr &MI = *II;
331       InstrInfo &III = Instructions[&MI];
332       unsigned Opcode = MI.getOpcode();
333       char Flags = 0;
334 
335       if (TII->isWQM(Opcode)) {
336         // Sampling instructions don't need to produce results for all pixels
337         // in a quad, they just require all inputs of a quad to have been
338         // computed for derivatives.
339         markInstructionUses(MI, StateWQM, Worklist);
340         GlobalFlags |= StateWQM;
341         continue;
342       } else if (Opcode == AMDGPU::WQM) {
343         // The WQM intrinsic requires its output to have all the helper lanes
344         // correct, so we need it to be in WQM.
345         Flags = StateWQM;
346         LowerToCopyInstrs.push_back(&MI);
347       } else if (Opcode == AMDGPU::SOFT_WQM) {
348         LowerToCopyInstrs.push_back(&MI);
349         SoftWQMInstrs.push_back(&MI);
350         continue;
351       } else if (Opcode == AMDGPU::WWM) {
352         // The WWM intrinsic doesn't make the same guarantee, and plus it needs
353         // to be executed in WQM or Exact so that its copy doesn't clobber
354         // inactive lanes.
355         markInstructionUses(MI, StateWWM, Worklist);
356         GlobalFlags |= StateWWM;
357         LowerToMovInstrs.push_back(&MI);
358         continue;
359       } else if (Opcode == AMDGPU::V_SET_INACTIVE_B32 ||
360                  Opcode == AMDGPU::V_SET_INACTIVE_B64) {
361         III.Disabled = StateWWM;
362         MachineOperand &Inactive = MI.getOperand(2);
363         if (Inactive.isReg()) {
364           if (Inactive.isUndef()) {
365             LowerToCopyInstrs.push_back(&MI);
366           } else {
367             Register Reg = Inactive.getReg();
368             if (Register::isVirtualRegister(Reg)) {
369               for (MachineInstr &DefMI : MRI->def_instructions(Reg))
370                 markInstruction(DefMI, StateWWM, Worklist);
371             }
372           }
373         }
374         SetInactiveInstrs.push_back(&MI);
375         continue;
376       } else if (TII->isDisableWQM(MI)) {
377         BBI.Needs |= StateExact;
378         if (!(BBI.InNeeds & StateExact)) {
379           BBI.InNeeds |= StateExact;
380           Worklist.push_back(&MBB);
381         }
382         GlobalFlags |= StateExact;
383         III.Disabled = StateWQM | StateWWM;
384         continue;
385       } else {
386         if (Opcode == AMDGPU::SI_PS_LIVE) {
387           LiveMaskQueries.push_back(&MI);
388         } else if (WQMOutputs) {
389           // The function is in machine SSA form, which means that physical
390           // VGPRs correspond to shader inputs and outputs. Inputs are
391           // only used, outputs are only defined.
392           for (const MachineOperand &MO : MI.defs()) {
393             if (!MO.isReg())
394               continue;
395 
396             Register Reg = MO.getReg();
397 
398             if (!Register::isVirtualRegister(Reg) &&
399                 TRI->hasVectorRegisters(TRI->getPhysRegClass(Reg))) {
400               Flags = StateWQM;
401               break;
402             }
403           }
404         }
405 
406         if (!Flags)
407           continue;
408       }
409 
410       markInstruction(MI, Flags, Worklist);
411       GlobalFlags |= Flags;
412     }
413   }
414 
415   // Mark sure that any SET_INACTIVE instructions are computed in WQM if WQM is
416   // ever used anywhere in the function. This implements the corresponding
417   // semantics of @llvm.amdgcn.set.inactive.
418   // Similarly for SOFT_WQM instructions, implementing @llvm.amdgcn.softwqm.
419   if (GlobalFlags & StateWQM) {
420     for (MachineInstr *MI : SetInactiveInstrs)
421       markInstruction(*MI, StateWQM, Worklist);
422     for (MachineInstr *MI : SoftWQMInstrs)
423       markInstruction(*MI, StateWQM, Worklist);
424   }
425 
426   return GlobalFlags;
427 }
428 
429 void SIWholeQuadMode::propagateInstruction(MachineInstr &MI,
430                                            std::vector<WorkItem>& Worklist) {
431   MachineBasicBlock *MBB = MI.getParent();
432   InstrInfo II = Instructions[&MI]; // take a copy to prevent dangling references
433   BlockInfo &BI = Blocks[MBB];
434 
435   // Control flow-type instructions and stores to temporary memory that are
436   // followed by WQM computations must themselves be in WQM.
437   if ((II.OutNeeds & StateWQM) && !(II.Disabled & StateWQM) &&
438       (MI.isTerminator() || (TII->usesVM_CNT(MI) && MI.mayStore()))) {
439     Instructions[&MI].Needs = StateWQM;
440     II.Needs = StateWQM;
441   }
442 
443   // Propagate to block level
444   if (II.Needs & StateWQM) {
445     BI.Needs |= StateWQM;
446     if (!(BI.InNeeds & StateWQM)) {
447       BI.InNeeds |= StateWQM;
448       Worklist.push_back(MBB);
449     }
450   }
451 
452   // Propagate backwards within block
453   if (MachineInstr *PrevMI = MI.getPrevNode()) {
454     char InNeeds = (II.Needs & ~StateWWM) | II.OutNeeds;
455     if (!PrevMI->isPHI()) {
456       InstrInfo &PrevII = Instructions[PrevMI];
457       if ((PrevII.OutNeeds | InNeeds) != PrevII.OutNeeds) {
458         PrevII.OutNeeds |= InNeeds;
459         Worklist.push_back(PrevMI);
460       }
461     }
462   }
463 
464   // Propagate WQM flag to instruction inputs
465   assert(!(II.Needs & StateExact));
466 
467   if (II.Needs != 0)
468     markInstructionUses(MI, II.Needs, Worklist);
469 
470   // Ensure we process a block containing WWM, even if it does not require any
471   // WQM transitions.
472   if (II.Needs & StateWWM)
473     BI.Needs |= StateWWM;
474 }
475 
476 void SIWholeQuadMode::propagateBlock(MachineBasicBlock &MBB,
477                                      std::vector<WorkItem>& Worklist) {
478   BlockInfo BI = Blocks[&MBB]; // Make a copy to prevent dangling references.
479 
480   // Propagate through instructions
481   if (!MBB.empty()) {
482     MachineInstr *LastMI = &*MBB.rbegin();
483     InstrInfo &LastII = Instructions[LastMI];
484     if ((LastII.OutNeeds | BI.OutNeeds) != LastII.OutNeeds) {
485       LastII.OutNeeds |= BI.OutNeeds;
486       Worklist.push_back(LastMI);
487     }
488   }
489 
490   // Predecessor blocks must provide for our WQM/Exact needs.
491   for (MachineBasicBlock *Pred : MBB.predecessors()) {
492     BlockInfo &PredBI = Blocks[Pred];
493     if ((PredBI.OutNeeds | BI.InNeeds) == PredBI.OutNeeds)
494       continue;
495 
496     PredBI.OutNeeds |= BI.InNeeds;
497     PredBI.InNeeds |= BI.InNeeds;
498     Worklist.push_back(Pred);
499   }
500 
501   // All successors must be prepared to accept the same set of WQM/Exact data.
502   for (MachineBasicBlock *Succ : MBB.successors()) {
503     BlockInfo &SuccBI = Blocks[Succ];
504     if ((SuccBI.InNeeds | BI.OutNeeds) == SuccBI.InNeeds)
505       continue;
506 
507     SuccBI.InNeeds |= BI.OutNeeds;
508     Worklist.push_back(Succ);
509   }
510 }
511 
512 char SIWholeQuadMode::analyzeFunction(MachineFunction &MF) {
513   std::vector<WorkItem> Worklist;
514   char GlobalFlags = scanInstructions(MF, Worklist);
515 
516   while (!Worklist.empty()) {
517     WorkItem WI = Worklist.back();
518     Worklist.pop_back();
519 
520     if (WI.MI)
521       propagateInstruction(*WI.MI, Worklist);
522     else
523       propagateBlock(*WI.MBB, Worklist);
524   }
525 
526   return GlobalFlags;
527 }
528 
529 /// Whether \p MI really requires the exec state computed during analysis.
530 ///
531 /// Scalar instructions must occasionally be marked WQM for correct propagation
532 /// (e.g. thread masks leading up to branches), but when it comes to actual
533 /// execution, they don't care about EXEC.
534 bool SIWholeQuadMode::requiresCorrectState(const MachineInstr &MI) const {
535   if (MI.isTerminator())
536     return true;
537 
538   // Skip instructions that are not affected by EXEC
539   if (TII->isScalarUnit(MI))
540     return false;
541 
542   // Generic instructions such as COPY will either disappear by register
543   // coalescing or be lowered to SALU or VALU instructions.
544   if (MI.isTransient()) {
545     if (MI.getNumExplicitOperands() >= 1) {
546       const MachineOperand &Op = MI.getOperand(0);
547       if (Op.isReg()) {
548         if (TRI->isSGPRReg(*MRI, Op.getReg())) {
549           // SGPR instructions are not affected by EXEC
550           return false;
551         }
552       }
553     }
554   }
555 
556   return true;
557 }
558 
559 MachineBasicBlock::iterator
560 SIWholeQuadMode::saveSCC(MachineBasicBlock &MBB,
561                          MachineBasicBlock::iterator Before) {
562   Register SaveReg = MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
563 
564   MachineInstr *Save =
565       BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), SaveReg)
566           .addReg(AMDGPU::SCC);
567   MachineInstr *Restore =
568       BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::SCC)
569           .addReg(SaveReg);
570 
571   LIS->InsertMachineInstrInMaps(*Save);
572   LIS->InsertMachineInstrInMaps(*Restore);
573   LIS->createAndComputeVirtRegInterval(SaveReg);
574 
575   return Restore;
576 }
577 
578 // Return an iterator in the (inclusive) range [First, Last] at which
579 // instructions can be safely inserted, keeping in mind that some of the
580 // instructions we want to add necessarily clobber SCC.
581 MachineBasicBlock::iterator SIWholeQuadMode::prepareInsertion(
582     MachineBasicBlock &MBB, MachineBasicBlock::iterator First,
583     MachineBasicBlock::iterator Last, bool PreferLast, bool SaveSCC) {
584   if (!SaveSCC)
585     return PreferLast ? Last : First;
586 
587   LiveRange &LR = LIS->getRegUnit(*MCRegUnitIterator(AMDGPU::SCC, TRI));
588   auto MBBE = MBB.end();
589   SlotIndex FirstIdx = First != MBBE ? LIS->getInstructionIndex(*First)
590                                      : LIS->getMBBEndIdx(&MBB);
591   SlotIndex LastIdx =
592       Last != MBBE ? LIS->getInstructionIndex(*Last) : LIS->getMBBEndIdx(&MBB);
593   SlotIndex Idx = PreferLast ? LastIdx : FirstIdx;
594   const LiveRange::Segment *S;
595 
596   for (;;) {
597     S = LR.getSegmentContaining(Idx);
598     if (!S)
599       break;
600 
601     if (PreferLast) {
602       SlotIndex Next = S->start.getBaseIndex();
603       if (Next < FirstIdx)
604         break;
605       Idx = Next;
606     } else {
607       SlotIndex Next = S->end.getNextIndex().getBaseIndex();
608       if (Next > LastIdx)
609         break;
610       Idx = Next;
611     }
612   }
613 
614   MachineBasicBlock::iterator MBBI;
615 
616   if (MachineInstr *MI = LIS->getInstructionFromIndex(Idx))
617     MBBI = MI;
618   else {
619     assert(Idx == LIS->getMBBEndIdx(&MBB));
620     MBBI = MBB.end();
621   }
622 
623   if (S)
624     MBBI = saveSCC(MBB, MBBI);
625 
626   return MBBI;
627 }
628 
629 void SIWholeQuadMode::toExact(MachineBasicBlock &MBB,
630                               MachineBasicBlock::iterator Before,
631                               unsigned SaveWQM, unsigned LiveMaskReg) {
632   MachineInstr *MI;
633 
634   if (SaveWQM) {
635     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(ST->isWave32() ?
636                    AMDGPU::S_AND_SAVEEXEC_B32 : AMDGPU::S_AND_SAVEEXEC_B64),
637                  SaveWQM)
638              .addReg(LiveMaskReg);
639   } else {
640     unsigned Exec = ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
641     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(ST->isWave32() ?
642                    AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64),
643                  Exec)
644              .addReg(Exec)
645              .addReg(LiveMaskReg);
646   }
647 
648   LIS->InsertMachineInstrInMaps(*MI);
649 }
650 
651 void SIWholeQuadMode::toWQM(MachineBasicBlock &MBB,
652                             MachineBasicBlock::iterator Before,
653                             unsigned SavedWQM) {
654   MachineInstr *MI;
655 
656   unsigned Exec = ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
657   if (SavedWQM) {
658     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), Exec)
659              .addReg(SavedWQM);
660   } else {
661     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(ST->isWave32() ?
662                    AMDGPU::S_WQM_B32 : AMDGPU::S_WQM_B64),
663                  Exec)
664              .addReg(Exec);
665   }
666 
667   LIS->InsertMachineInstrInMaps(*MI);
668 }
669 
670 void SIWholeQuadMode::toWWM(MachineBasicBlock &MBB,
671                             MachineBasicBlock::iterator Before,
672                             unsigned SaveOrig) {
673   MachineInstr *MI;
674 
675   assert(SaveOrig);
676   MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::ENTER_WWM), SaveOrig)
677            .addImm(-1);
678   LIS->InsertMachineInstrInMaps(*MI);
679 }
680 
681 void SIWholeQuadMode::fromWWM(MachineBasicBlock &MBB,
682                               MachineBasicBlock::iterator Before,
683                               unsigned SavedOrig) {
684   MachineInstr *MI;
685 
686   assert(SavedOrig);
687   MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::EXIT_WWM),
688                ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC)
689            .addReg(SavedOrig);
690   LIS->InsertMachineInstrInMaps(*MI);
691 }
692 
693 void SIWholeQuadMode::processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg,
694                                    bool isEntry) {
695   auto BII = Blocks.find(&MBB);
696   if (BII == Blocks.end())
697     return;
698 
699   const BlockInfo &BI = BII->second;
700 
701   // This is a non-entry block that is WQM throughout, so no need to do
702   // anything.
703   if (!isEntry && BI.Needs == StateWQM && BI.OutNeeds != StateExact)
704     return;
705 
706   LLVM_DEBUG(dbgs() << "\nProcessing block " << printMBBReference(MBB)
707                     << ":\n");
708 
709   unsigned SavedWQMReg = 0;
710   unsigned SavedNonWWMReg = 0;
711   bool WQMFromExec = isEntry;
712   char State = (isEntry || !(BI.InNeeds & StateWQM)) ? StateExact : StateWQM;
713   char NonWWMState = 0;
714   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
715 
716   auto II = MBB.getFirstNonPHI(), IE = MBB.end();
717   if (isEntry)
718     ++II; // Skip the instruction that saves LiveMask
719 
720   // This stores the first instruction where it's safe to switch from WQM to
721   // Exact or vice versa.
722   MachineBasicBlock::iterator FirstWQM = IE;
723 
724   // This stores the first instruction where it's safe to switch from WWM to
725   // Exact/WQM or to switch to WWM. It must always be the same as, or after,
726   // FirstWQM since if it's safe to switch to/from WWM, it must be safe to
727   // switch to/from WQM as well.
728   MachineBasicBlock::iterator FirstWWM = IE;
729   for (;;) {
730     MachineBasicBlock::iterator Next = II;
731     char Needs = StateExact | StateWQM; // WWM is disabled by default
732     char OutNeeds = 0;
733 
734     if (FirstWQM == IE)
735       FirstWQM = II;
736 
737     if (FirstWWM == IE)
738       FirstWWM = II;
739 
740     // First, figure out the allowed states (Needs) based on the propagated
741     // flags.
742     if (II != IE) {
743       MachineInstr &MI = *II;
744 
745       if (requiresCorrectState(MI)) {
746         auto III = Instructions.find(&MI);
747         if (III != Instructions.end()) {
748           if (III->second.Needs & StateWWM)
749             Needs = StateWWM;
750           else if (III->second.Needs & StateWQM)
751             Needs = StateWQM;
752           else
753             Needs &= ~III->second.Disabled;
754           OutNeeds = III->second.OutNeeds;
755         }
756       } else {
757         // If the instruction doesn't actually need a correct EXEC, then we can
758         // safely leave WWM enabled.
759         Needs = StateExact | StateWQM | StateWWM;
760       }
761 
762       if (MI.isTerminator() && OutNeeds == StateExact)
763         Needs = StateExact;
764 
765       if (MI.getOpcode() == AMDGPU::SI_ELSE && BI.OutNeeds == StateExact)
766         MI.getOperand(3).setImm(1);
767 
768       ++Next;
769     } else {
770       // End of basic block
771       if (BI.OutNeeds & StateWQM)
772         Needs = StateWQM;
773       else if (BI.OutNeeds == StateExact)
774         Needs = StateExact;
775       else
776         Needs = StateWQM | StateExact;
777     }
778 
779     // Now, transition if necessary.
780     if (!(Needs & State)) {
781       MachineBasicBlock::iterator First;
782       if (State == StateWWM || Needs == StateWWM) {
783         // We must switch to or from WWM
784         First = FirstWWM;
785       } else {
786         // We only need to switch to/from WQM, so we can use FirstWQM
787         First = FirstWQM;
788       }
789 
790       MachineBasicBlock::iterator Before =
791           prepareInsertion(MBB, First, II, Needs == StateWQM,
792                            Needs == StateExact || WQMFromExec);
793 
794       if (State == StateWWM) {
795         assert(SavedNonWWMReg);
796         fromWWM(MBB, Before, SavedNonWWMReg);
797         State = NonWWMState;
798       }
799 
800       if (Needs == StateWWM) {
801         NonWWMState = State;
802         SavedNonWWMReg = MRI->createVirtualRegister(BoolRC);
803         toWWM(MBB, Before, SavedNonWWMReg);
804         State = StateWWM;
805       } else {
806         if (State == StateWQM && (Needs & StateExact) && !(Needs & StateWQM)) {
807           if (!WQMFromExec && (OutNeeds & StateWQM))
808             SavedWQMReg = MRI->createVirtualRegister(BoolRC);
809 
810           toExact(MBB, Before, SavedWQMReg, LiveMaskReg);
811           State = StateExact;
812         } else if (State == StateExact && (Needs & StateWQM) &&
813                    !(Needs & StateExact)) {
814           assert(WQMFromExec == (SavedWQMReg == 0));
815 
816           toWQM(MBB, Before, SavedWQMReg);
817 
818           if (SavedWQMReg) {
819             LIS->createAndComputeVirtRegInterval(SavedWQMReg);
820             SavedWQMReg = 0;
821           }
822           State = StateWQM;
823         } else {
824           // We can get here if we transitioned from WWM to a non-WWM state that
825           // already matches our needs, but we shouldn't need to do anything.
826           assert(Needs & State);
827         }
828       }
829     }
830 
831     if (Needs != (StateExact | StateWQM | StateWWM)) {
832       if (Needs != (StateExact | StateWQM))
833         FirstWQM = IE;
834       FirstWWM = IE;
835     }
836 
837     if (II == IE)
838       break;
839     II = Next;
840   }
841 }
842 
843 void SIWholeQuadMode::lowerLiveMaskQueries(unsigned LiveMaskReg) {
844   for (MachineInstr *MI : LiveMaskQueries) {
845     const DebugLoc &DL = MI->getDebugLoc();
846     Register Dest = MI->getOperand(0).getReg();
847     MachineInstr *Copy =
848         BuildMI(*MI->getParent(), MI, DL, TII->get(AMDGPU::COPY), Dest)
849             .addReg(LiveMaskReg);
850 
851     LIS->ReplaceMachineInstrInMaps(*MI, *Copy);
852     MI->eraseFromParent();
853   }
854 }
855 
856 void SIWholeQuadMode::lowerCopyInstrs() {
857   for (MachineInstr *MI : LowerToMovInstrs) {
858     assert(MI->getNumExplicitOperands() == 2);
859 
860     const Register Reg = MI->getOperand(0).getReg();
861 
862     if (TRI->isVGPR(*MRI, Reg)) {
863       const TargetRegisterClass *regClass = Register::isVirtualRegister(Reg)
864                                                 ? MRI->getRegClass(Reg)
865                                                 : TRI->getPhysRegClass(Reg);
866 
867       const unsigned MovOp = TII->getMovOpcode(regClass);
868       MI->setDesc(TII->get(MovOp));
869 
870       // And make it implicitly depend on exec (like all VALU movs should do).
871       MI->addOperand(MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
872     } else {
873       MI->setDesc(TII->get(AMDGPU::COPY));
874     }
875   }
876   for (MachineInstr *MI : LowerToCopyInstrs) {
877     if (MI->getOpcode() == AMDGPU::V_SET_INACTIVE_B32 ||
878         MI->getOpcode() == AMDGPU::V_SET_INACTIVE_B64) {
879       assert(MI->getNumExplicitOperands() == 3);
880       // the only reason we should be here is V_SET_INACTIVE has
881       // an undef input so it is being replaced by a simple copy.
882       // There should be a second undef source that we should remove.
883       assert(MI->getOperand(2).isUndef());
884       MI->RemoveOperand(2);
885       MI->untieRegOperand(1);
886     } else {
887       assert(MI->getNumExplicitOperands() == 2);
888     }
889 
890     MI->setDesc(TII->get(AMDGPU::COPY));
891   }
892 }
893 
894 bool SIWholeQuadMode::runOnMachineFunction(MachineFunction &MF) {
895   Instructions.clear();
896   Blocks.clear();
897   LiveMaskQueries.clear();
898   LowerToCopyInstrs.clear();
899   LowerToMovInstrs.clear();
900   CallingConv = MF.getFunction().getCallingConv();
901 
902   ST = &MF.getSubtarget<GCNSubtarget>();
903 
904   TII = ST->getInstrInfo();
905   TRI = &TII->getRegisterInfo();
906   MRI = &MF.getRegInfo();
907   LIS = &getAnalysis<LiveIntervals>();
908 
909   char GlobalFlags = analyzeFunction(MF);
910   unsigned LiveMaskReg = 0;
911   unsigned Exec = ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
912   if (!(GlobalFlags & StateWQM)) {
913     lowerLiveMaskQueries(Exec);
914     if (!(GlobalFlags & StateWWM) && LowerToCopyInstrs.empty() && LowerToMovInstrs.empty())
915       return !LiveMaskQueries.empty();
916   } else {
917     // Store a copy of the original live mask when required
918     MachineBasicBlock &Entry = MF.front();
919     MachineBasicBlock::iterator EntryMI = Entry.getFirstNonPHI();
920 
921     if (GlobalFlags & StateExact || !LiveMaskQueries.empty()) {
922       LiveMaskReg = MRI->createVirtualRegister(TRI->getBoolRC());
923       MachineInstr *MI = BuildMI(Entry, EntryMI, DebugLoc(),
924                                  TII->get(AMDGPU::COPY), LiveMaskReg)
925                              .addReg(Exec);
926       LIS->InsertMachineInstrInMaps(*MI);
927     }
928 
929     lowerLiveMaskQueries(LiveMaskReg);
930 
931     if (GlobalFlags == StateWQM) {
932       // For a shader that needs only WQM, we can just set it once.
933       BuildMI(Entry, EntryMI, DebugLoc(), TII->get(ST->isWave32() ?
934                 AMDGPU::S_WQM_B32 : AMDGPU::S_WQM_B64),
935               Exec)
936           .addReg(Exec);
937 
938       lowerCopyInstrs();
939       // EntryMI may become invalid here
940       return true;
941     }
942   }
943 
944   LLVM_DEBUG(printInfo());
945 
946   lowerCopyInstrs();
947 
948   // Handle the general case
949   for (auto BII : Blocks)
950     processBlock(*BII.first, LiveMaskReg, BII.first == &*MF.begin());
951 
952   // Physical registers like SCC aren't tracked by default anyway, so just
953   // removing the ranges we computed is the simplest option for maintaining
954   // the analysis results.
955   LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::SCC, TRI));
956 
957   return true;
958 }
959