xref: /llvm-project/llvm/lib/Target/AMDGPU/SIWholeQuadMode.cpp (revision 92638ab62559ce082c02680efca7280344ca05dd)
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, and whole wavefront mode for all programs.
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 /// We also compute when a sequence of instructions requires Whole Wavefront
33 /// Mode (WWM) and insert instructions to save and restore it:
34 ///
35 /// S_OR_SAVEEXEC_B64 Tmp, -1
36 /// ...
37 /// S_MOV_B64 EXEC, Tmp
38 ///
39 /// In order to avoid excessive switching during sequences of Exact
40 /// instructions, the pass first analyzes which instructions must be run in WQM
41 /// (aka which instructions produce values that lead to derivative
42 /// computations).
43 ///
44 /// Basic blocks are always exited in WQM as long as some successor needs WQM.
45 ///
46 /// There is room for improvement given better control flow analysis:
47 ///
48 ///  (1) at the top level (outside of control flow statements, and as long as
49 ///      kill hasn't been used), one SGPR can be saved by recovering WQM from
50 ///      the LiveMask (this is implemented for the entry block).
51 ///
52 ///  (2) when entire regions (e.g. if-else blocks or entire loops) only
53 ///      consist of exact and don't-care instructions, the switch only has to
54 ///      be done at the entry and exit points rather than potentially in each
55 ///      block of the region.
56 ///
57 //===----------------------------------------------------------------------===//
58 
59 #include "AMDGPU.h"
60 #include "AMDGPUSubtarget.h"
61 #include "SIInstrInfo.h"
62 #include "SIMachineFunctionInfo.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/PostOrderIterator.h"
65 #include "llvm/ADT/SmallVector.h"
66 #include "llvm/ADT/StringRef.h"
67 #include "llvm/CodeGen/LiveInterval.h"
68 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
69 #include "llvm/CodeGen/MachineBasicBlock.h"
70 #include "llvm/CodeGen/MachineFunction.h"
71 #include "llvm/CodeGen/MachineFunctionPass.h"
72 #include "llvm/CodeGen/MachineInstr.h"
73 #include "llvm/CodeGen/MachineInstrBuilder.h"
74 #include "llvm/CodeGen/MachineOperand.h"
75 #include "llvm/CodeGen/MachineRegisterInfo.h"
76 #include "llvm/CodeGen/SlotIndexes.h"
77 #include "llvm/IR/CallingConv.h"
78 #include "llvm/IR/DebugLoc.h"
79 #include "llvm/MC/MCRegisterInfo.h"
80 #include "llvm/Pass.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include "llvm/Target/TargetRegisterInfo.h"
84 #include <cassert>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-wqm"
90 
91 namespace {
92 
93 enum {
94   StateWQM = 0x1,
95   StateWWM = 0x2,
96   StateExact = 0x4,
97 };
98 
99 struct PrintState {
100 public:
101   int State;
102 
103   explicit PrintState(int State) : State(State) {}
104 };
105 
106 static raw_ostream &operator<<(raw_ostream &OS, const PrintState &PS) {
107   if (PS.State & StateWQM)
108     OS << "WQM";
109   if (PS.State & StateWWM) {
110     if (PS.State & StateWQM)
111       OS << '|';
112     OS << "WWM";
113   }
114   if (PS.State & StateExact) {
115     if (PS.State & (StateWQM | StateWWM))
116       OS << '|';
117     OS << "Exact";
118   }
119 
120   return OS;
121 }
122 
123 struct InstrInfo {
124   char Needs = 0;
125   char Disabled = 0;
126   char OutNeeds = 0;
127 };
128 
129 struct BlockInfo {
130   char Needs = 0;
131   char InNeeds = 0;
132   char OutNeeds = 0;
133 };
134 
135 struct WorkItem {
136   MachineBasicBlock *MBB = nullptr;
137   MachineInstr *MI = nullptr;
138 
139   WorkItem() = default;
140   WorkItem(MachineBasicBlock *MBB) : MBB(MBB) {}
141   WorkItem(MachineInstr *MI) : MI(MI) {}
142 };
143 
144 class SIWholeQuadMode : public MachineFunctionPass {
145 private:
146   CallingConv::ID CallingConv;
147   const SIInstrInfo *TII;
148   const SIRegisterInfo *TRI;
149   MachineRegisterInfo *MRI;
150   LiveIntervals *LIS;
151 
152   DenseMap<const MachineInstr *, InstrInfo> Instructions;
153   DenseMap<MachineBasicBlock *, BlockInfo> Blocks;
154   SmallVector<MachineInstr *, 1> LiveMaskQueries;
155   SmallVector<MachineInstr *, 4> LowerToCopyInstrs;
156 
157   void printInfo();
158 
159   void markInstruction(MachineInstr &MI, char Flag,
160                        std::vector<WorkItem> &Worklist);
161   void markInstructionUses(const MachineInstr &MI, char Flag,
162                            std::vector<WorkItem> &Worklist);
163   char scanInstructions(MachineFunction &MF, std::vector<WorkItem> &Worklist);
164   void propagateInstruction(MachineInstr &MI, std::vector<WorkItem> &Worklist);
165   void propagateBlock(MachineBasicBlock &MBB, std::vector<WorkItem> &Worklist);
166   char analyzeFunction(MachineFunction &MF);
167 
168   bool requiresCorrectState(const MachineInstr &MI) const;
169 
170   MachineBasicBlock::iterator saveSCC(MachineBasicBlock &MBB,
171                                       MachineBasicBlock::iterator Before);
172   MachineBasicBlock::iterator
173   prepareInsertion(MachineBasicBlock &MBB, MachineBasicBlock::iterator First,
174                    MachineBasicBlock::iterator Last, bool PreferLast,
175                    bool SaveSCC);
176   void toExact(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
177                unsigned SaveWQM, unsigned LiveMaskReg);
178   void toWQM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
179              unsigned SavedWQM);
180   void toWWM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
181              unsigned SaveOrig);
182   void fromWWM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
183                unsigned SavedOrig);
184   void processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg, bool isEntry);
185 
186   void lowerLiveMaskQueries(unsigned LiveMaskReg);
187   void lowerCopyInstrs();
188 
189 public:
190   static char ID;
191 
192   SIWholeQuadMode() :
193     MachineFunctionPass(ID) { }
194 
195   bool runOnMachineFunction(MachineFunction &MF) override;
196 
197   StringRef getPassName() const override { return "SI Whole Quad Mode"; }
198 
199   void getAnalysisUsage(AnalysisUsage &AU) const override {
200     AU.addRequired<LiveIntervals>();
201     AU.setPreservesCFG();
202     MachineFunctionPass::getAnalysisUsage(AU);
203   }
204 };
205 
206 } // end anonymous namespace
207 
208 char SIWholeQuadMode::ID = 0;
209 
210 INITIALIZE_PASS_BEGIN(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false,
211                       false)
212 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
213 INITIALIZE_PASS_END(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false,
214                     false)
215 
216 char &llvm::SIWholeQuadModeID = SIWholeQuadMode::ID;
217 
218 FunctionPass *llvm::createSIWholeQuadModePass() {
219   return new SIWholeQuadMode;
220 }
221 
222 void SIWholeQuadMode::printInfo() {
223   for (const auto &BII : Blocks) {
224     dbgs() << "\nBB#" << BII.first->getNumber() << ":\n"
225            << "  InNeeds = " << PrintState(BII.second.InNeeds)
226            << ", Needs = " << PrintState(BII.second.Needs)
227            << ", OutNeeds = " << PrintState(BII.second.OutNeeds) << "\n\n";
228 
229     for (const MachineInstr &MI : *BII.first) {
230       auto III = Instructions.find(&MI);
231       if (III == Instructions.end())
232         continue;
233 
234       dbgs() << "  " << MI << "    Needs = " << PrintState(III->second.Needs)
235              << ", OutNeeds = " << PrintState(III->second.OutNeeds) << '\n';
236     }
237   }
238 }
239 
240 void SIWholeQuadMode::markInstruction(MachineInstr &MI, char Flag,
241                                       std::vector<WorkItem> &Worklist) {
242   InstrInfo &II = Instructions[&MI];
243 
244   assert(!(Flag & StateExact) && Flag != 0);
245 
246   // Remove any disabled states from the flag. The user that required it gets
247   // an undefined value in the helper lanes. For example, this can happen if
248   // the result of an atomic is used by instruction that requires WQM, where
249   // ignoring the request for WQM is correct as per the relevant specs.
250   Flag &= ~II.Disabled;
251 
252   // Ignore if the flag is already encompassed by the existing needs, or we
253   // just disabled everything.
254   if ((II.Needs & Flag) == Flag)
255     return;
256 
257   II.Needs |= Flag;
258   Worklist.push_back(&MI);
259 }
260 
261 /// Mark all instructions defining the uses in \p MI with \p Flag.
262 void SIWholeQuadMode::markInstructionUses(const MachineInstr &MI, char Flag,
263                                           std::vector<WorkItem> &Worklist) {
264   for (const MachineOperand &Use : MI.uses()) {
265     if (!Use.isReg() || !Use.isUse())
266       continue;
267 
268     unsigned Reg = Use.getReg();
269 
270     // Handle physical registers that we need to track; this is mostly relevant
271     // for VCC, which can appear as the (implicit) input of a uniform branch,
272     // e.g. when a loop counter is stored in a VGPR.
273     if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
274       if (Reg == AMDGPU::EXEC)
275         continue;
276 
277       for (MCRegUnitIterator RegUnit(Reg, TRI); RegUnit.isValid(); ++RegUnit) {
278         LiveRange &LR = LIS->getRegUnit(*RegUnit);
279         const VNInfo *Value = LR.Query(LIS->getInstructionIndex(MI)).valueIn();
280         if (!Value)
281           continue;
282 
283         // Since we're in machine SSA, we do not need to track physical
284         // registers across basic blocks.
285         if (Value->isPHIDef())
286           continue;
287 
288         markInstruction(*LIS->getInstructionFromIndex(Value->def), Flag,
289                         Worklist);
290       }
291 
292       continue;
293     }
294 
295     for (MachineInstr &DefMI : MRI->def_instructions(Use.getReg()))
296       markInstruction(DefMI, Flag, Worklist);
297   }
298 }
299 
300 // Scan instructions to determine which ones require an Exact execmask and
301 // which ones seed WQM requirements.
302 char SIWholeQuadMode::scanInstructions(MachineFunction &MF,
303                                        std::vector<WorkItem> &Worklist) {
304   char GlobalFlags = 0;
305   bool WQMOutputs = MF.getFunction()->hasFnAttribute("amdgpu-ps-wqm-outputs");
306 
307   // We need to visit the basic blocks in reverse post-order so that we visit
308   // defs before uses, in particular so that we don't accidentally mark an
309   // instruction as needing e.g. WQM before visiting it and realizing it needs
310   // WQM disabled.
311   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
312   for (auto BI = RPOT.begin(), BE = RPOT.end(); BI != BE; ++BI) {
313     MachineBasicBlock &MBB = **BI;
314     BlockInfo &BBI = Blocks[&MBB];
315 
316     for (auto II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
317       MachineInstr &MI = *II;
318       InstrInfo &III = Instructions[&MI];
319       unsigned Opcode = MI.getOpcode();
320       char Flags = 0;
321 
322       if (TII->isDS(Opcode) && CallingConv == CallingConv::AMDGPU_PS) {
323         Flags = StateWQM;
324       } else if (TII->isWQM(Opcode)) {
325         // Sampling instructions don't need to produce results for all pixels
326         // in a quad, they just require all inputs of a quad to have been
327         // computed for derivatives.
328         markInstructionUses(MI, StateWQM, Worklist);
329         GlobalFlags |= StateWQM;
330         continue;
331       } else if (Opcode == AMDGPU::WQM) {
332         // The WQM intrinsic requires its output to have all the helper lanes
333         // correct, so we need it to be in WQM.
334         Flags = StateWQM;
335         LowerToCopyInstrs.push_back(&MI);
336       } else if (Opcode == AMDGPU::WWM) {
337         // The WWM intrinsic doesn't make the same guarantee, and plus it needs
338         // to be executed in WQM or Exact so that its copy doesn't clobber
339         // inactive lanes.
340         markInstructionUses(MI, StateWWM, Worklist);
341         GlobalFlags |= StateWWM;
342         LowerToCopyInstrs.push_back(&MI);
343         continue;
344       } else if (TII->isDisableWQM(MI)) {
345         BBI.Needs |= StateExact;
346         if (!(BBI.InNeeds & StateExact)) {
347           BBI.InNeeds |= StateExact;
348           Worklist.push_back(&MBB);
349         }
350         GlobalFlags |= StateExact;
351         III.Disabled = StateWQM | StateWWM;
352         continue;
353       } else {
354         if (Opcode == AMDGPU::SI_PS_LIVE) {
355           LiveMaskQueries.push_back(&MI);
356         } else if (WQMOutputs) {
357           // The function is in machine SSA form, which means that physical
358           // VGPRs correspond to shader inputs and outputs. Inputs are
359           // only used, outputs are only defined.
360           for (const MachineOperand &MO : MI.defs()) {
361             if (!MO.isReg())
362               continue;
363 
364             unsigned Reg = MO.getReg();
365 
366             if (!TRI->isVirtualRegister(Reg) &&
367                 TRI->hasVGPRs(TRI->getPhysRegClass(Reg))) {
368               Flags = StateWQM;
369               break;
370             }
371           }
372         }
373 
374         if (!Flags)
375           continue;
376       }
377 
378       markInstruction(MI, Flags, Worklist);
379       GlobalFlags |= Flags;
380     }
381   }
382 
383   return GlobalFlags;
384 }
385 
386 void SIWholeQuadMode::propagateInstruction(MachineInstr &MI,
387                                            std::vector<WorkItem>& Worklist) {
388   MachineBasicBlock *MBB = MI.getParent();
389   InstrInfo II = Instructions[&MI]; // take a copy to prevent dangling references
390   BlockInfo &BI = Blocks[MBB];
391 
392   // Control flow-type instructions and stores to temporary memory that are
393   // followed by WQM computations must themselves be in WQM.
394   if ((II.OutNeeds & StateWQM) && !(II.Disabled & StateWQM) &&
395       (MI.isTerminator() || (TII->usesVM_CNT(MI) && MI.mayStore()))) {
396     Instructions[&MI].Needs = StateWQM;
397     II.Needs = StateWQM;
398   }
399 
400   // Propagate to block level
401   if (II.Needs & StateWQM) {
402     BI.Needs |= StateWQM;
403     if (!(BI.InNeeds & StateWQM)) {
404       BI.InNeeds |= StateWQM;
405       Worklist.push_back(MBB);
406     }
407   }
408 
409   // Propagate backwards within block
410   if (MachineInstr *PrevMI = MI.getPrevNode()) {
411     char InNeeds = (II.Needs & ~StateWWM) | II.OutNeeds;
412     if (!PrevMI->isPHI()) {
413       InstrInfo &PrevII = Instructions[PrevMI];
414       if ((PrevII.OutNeeds | InNeeds) != PrevII.OutNeeds) {
415         PrevII.OutNeeds |= InNeeds;
416         Worklist.push_back(PrevMI);
417       }
418     }
419   }
420 
421   // Propagate WQM flag to instruction inputs
422   assert(!(II.Needs & StateExact));
423 
424   if (II.Needs != 0)
425     markInstructionUses(MI, II.Needs, Worklist);
426 }
427 
428 void SIWholeQuadMode::propagateBlock(MachineBasicBlock &MBB,
429                                      std::vector<WorkItem>& Worklist) {
430   BlockInfo BI = Blocks[&MBB]; // Make a copy to prevent dangling references.
431 
432   // Propagate through instructions
433   if (!MBB.empty()) {
434     MachineInstr *LastMI = &*MBB.rbegin();
435     InstrInfo &LastII = Instructions[LastMI];
436     if ((LastII.OutNeeds | BI.OutNeeds) != LastII.OutNeeds) {
437       LastII.OutNeeds |= BI.OutNeeds;
438       Worklist.push_back(LastMI);
439     }
440   }
441 
442   // Predecessor blocks must provide for our WQM/Exact needs.
443   for (MachineBasicBlock *Pred : MBB.predecessors()) {
444     BlockInfo &PredBI = Blocks[Pred];
445     if ((PredBI.OutNeeds | BI.InNeeds) == PredBI.OutNeeds)
446       continue;
447 
448     PredBI.OutNeeds |= BI.InNeeds;
449     PredBI.InNeeds |= BI.InNeeds;
450     Worklist.push_back(Pred);
451   }
452 
453   // All successors must be prepared to accept the same set of WQM/Exact data.
454   for (MachineBasicBlock *Succ : MBB.successors()) {
455     BlockInfo &SuccBI = Blocks[Succ];
456     if ((SuccBI.InNeeds | BI.OutNeeds) == SuccBI.InNeeds)
457       continue;
458 
459     SuccBI.InNeeds |= BI.OutNeeds;
460     Worklist.push_back(Succ);
461   }
462 }
463 
464 char SIWholeQuadMode::analyzeFunction(MachineFunction &MF) {
465   std::vector<WorkItem> Worklist;
466   char GlobalFlags = scanInstructions(MF, Worklist);
467 
468   while (!Worklist.empty()) {
469     WorkItem WI = Worklist.back();
470     Worklist.pop_back();
471 
472     if (WI.MI)
473       propagateInstruction(*WI.MI, Worklist);
474     else
475       propagateBlock(*WI.MBB, Worklist);
476   }
477 
478   return GlobalFlags;
479 }
480 
481 /// Whether \p MI really requires the exec state computed during analysis.
482 ///
483 /// Scalar instructions must occasionally be marked WQM for correct propagation
484 /// (e.g. thread masks leading up to branches), but when it comes to actual
485 /// execution, they don't care about EXEC.
486 bool SIWholeQuadMode::requiresCorrectState(const MachineInstr &MI) const {
487   if (MI.isTerminator())
488     return true;
489 
490   // Skip instructions that are not affected by EXEC
491   if (TII->isScalarUnit(MI))
492     return false;
493 
494   // Generic instructions such as COPY will either disappear by register
495   // coalescing or be lowered to SALU or VALU instructions.
496   if (MI.isTransient()) {
497     if (MI.getNumExplicitOperands() >= 1) {
498       const MachineOperand &Op = MI.getOperand(0);
499       if (Op.isReg()) {
500         if (TRI->isSGPRReg(*MRI, Op.getReg())) {
501           // SGPR instructions are not affected by EXEC
502           return false;
503         }
504       }
505     }
506   }
507 
508   return true;
509 }
510 
511 MachineBasicBlock::iterator
512 SIWholeQuadMode::saveSCC(MachineBasicBlock &MBB,
513                          MachineBasicBlock::iterator Before) {
514   unsigned SaveReg = MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
515 
516   MachineInstr *Save =
517       BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), SaveReg)
518           .addReg(AMDGPU::SCC);
519   MachineInstr *Restore =
520       BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::SCC)
521           .addReg(SaveReg);
522 
523   LIS->InsertMachineInstrInMaps(*Save);
524   LIS->InsertMachineInstrInMaps(*Restore);
525   LIS->createAndComputeVirtRegInterval(SaveReg);
526 
527   return Restore;
528 }
529 
530 // Return an iterator in the (inclusive) range [First, Last] at which
531 // instructions can be safely inserted, keeping in mind that some of the
532 // instructions we want to add necessarily clobber SCC.
533 MachineBasicBlock::iterator SIWholeQuadMode::prepareInsertion(
534     MachineBasicBlock &MBB, MachineBasicBlock::iterator First,
535     MachineBasicBlock::iterator Last, bool PreferLast, bool SaveSCC) {
536   if (!SaveSCC)
537     return PreferLast ? Last : First;
538 
539   LiveRange &LR = LIS->getRegUnit(*MCRegUnitIterator(AMDGPU::SCC, TRI));
540   auto MBBE = MBB.end();
541   SlotIndex FirstIdx = First != MBBE ? LIS->getInstructionIndex(*First)
542                                      : LIS->getMBBEndIdx(&MBB);
543   SlotIndex LastIdx =
544       Last != MBBE ? LIS->getInstructionIndex(*Last) : LIS->getMBBEndIdx(&MBB);
545   SlotIndex Idx = PreferLast ? LastIdx : FirstIdx;
546   const LiveRange::Segment *S;
547 
548   for (;;) {
549     S = LR.getSegmentContaining(Idx);
550     if (!S)
551       break;
552 
553     if (PreferLast) {
554       SlotIndex Next = S->start.getBaseIndex();
555       if (Next < FirstIdx)
556         break;
557       Idx = Next;
558     } else {
559       SlotIndex Next = S->end.getNextIndex().getBaseIndex();
560       if (Next > LastIdx)
561         break;
562       Idx = Next;
563     }
564   }
565 
566   MachineBasicBlock::iterator MBBI;
567 
568   if (MachineInstr *MI = LIS->getInstructionFromIndex(Idx))
569     MBBI = MI;
570   else {
571     assert(Idx == LIS->getMBBEndIdx(&MBB));
572     MBBI = MBB.end();
573   }
574 
575   if (S)
576     MBBI = saveSCC(MBB, MBBI);
577 
578   return MBBI;
579 }
580 
581 void SIWholeQuadMode::toExact(MachineBasicBlock &MBB,
582                               MachineBasicBlock::iterator Before,
583                               unsigned SaveWQM, unsigned LiveMaskReg) {
584   MachineInstr *MI;
585 
586   if (SaveWQM) {
587     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_AND_SAVEEXEC_B64),
588                  SaveWQM)
589              .addReg(LiveMaskReg);
590   } else {
591     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_AND_B64),
592                  AMDGPU::EXEC)
593              .addReg(AMDGPU::EXEC)
594              .addReg(LiveMaskReg);
595   }
596 
597   LIS->InsertMachineInstrInMaps(*MI);
598 }
599 
600 void SIWholeQuadMode::toWQM(MachineBasicBlock &MBB,
601                             MachineBasicBlock::iterator Before,
602                             unsigned SavedWQM) {
603   MachineInstr *MI;
604 
605   if (SavedWQM) {
606     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::EXEC)
607              .addReg(SavedWQM);
608   } else {
609     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_WQM_B64),
610                  AMDGPU::EXEC)
611              .addReg(AMDGPU::EXEC);
612   }
613 
614   LIS->InsertMachineInstrInMaps(*MI);
615 }
616 
617 void SIWholeQuadMode::toWWM(MachineBasicBlock &MBB,
618                             MachineBasicBlock::iterator Before,
619                             unsigned SaveOrig) {
620   MachineInstr *MI;
621 
622   assert(SaveOrig);
623   MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::S_OR_SAVEEXEC_B64),
624                SaveOrig)
625            .addImm(-1);
626   LIS->InsertMachineInstrInMaps(*MI);
627 }
628 
629 void SIWholeQuadMode::fromWWM(MachineBasicBlock &MBB,
630                               MachineBasicBlock::iterator Before,
631                               unsigned SavedOrig) {
632   MachineInstr *MI;
633 
634   assert(SavedOrig);
635   MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::EXIT_WWM), AMDGPU::EXEC)
636            .addReg(SavedOrig);
637   LIS->InsertMachineInstrInMaps(*MI);
638 }
639 
640 void SIWholeQuadMode::processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg,
641                                    bool isEntry) {
642   auto BII = Blocks.find(&MBB);
643   if (BII == Blocks.end())
644     return;
645 
646   const BlockInfo &BI = BII->second;
647 
648   // This is a non-entry block that is WQM throughout, so no need to do
649   // anything.
650   if (!isEntry && BI.Needs == StateWQM && BI.OutNeeds != StateExact)
651     return;
652 
653   DEBUG(dbgs() << "\nProcessing block BB#" << MBB.getNumber() << ":\n");
654 
655   unsigned SavedWQMReg = 0;
656   unsigned SavedNonWWMReg = 0;
657   bool WQMFromExec = isEntry;
658   char State = (isEntry || !(BI.InNeeds & StateWQM)) ? StateExact : StateWQM;
659   char NonWWMState = 0;
660 
661   auto II = MBB.getFirstNonPHI(), IE = MBB.end();
662   if (isEntry)
663     ++II; // Skip the instruction that saves LiveMask
664 
665   // This stores the first instruction where it's safe to switch from WQM to
666   // Exact or vice versa.
667   MachineBasicBlock::iterator FirstWQM = IE;
668 
669   // This stores the first instruction where it's safe to switch from WWM to
670   // Exact/WQM or to switch to WWM. It must always be the same as, or after,
671   // FirstWQM since if it's safe to switch to/from WWM, it must be safe to
672   // switch to/from WQM as well.
673   MachineBasicBlock::iterator FirstWWM = IE;
674   for (;;) {
675     MachineBasicBlock::iterator Next = II;
676     char Needs = StateExact | StateWQM; // WWM is disabled by default
677     char OutNeeds = 0;
678 
679     if (FirstWQM == IE)
680       FirstWQM = II;
681 
682     if (FirstWWM == IE)
683       FirstWWM = II;
684 
685     // First, figure out the allowed states (Needs) based on the propagated
686     // flags.
687     if (II != IE) {
688       MachineInstr &MI = *II;
689 
690       if (requiresCorrectState(MI)) {
691         auto III = Instructions.find(&MI);
692         if (III != Instructions.end()) {
693           if (III->second.Needs & StateWWM)
694             Needs = StateWWM;
695           else if (III->second.Needs & StateWQM)
696             Needs = StateWQM;
697           else
698             Needs &= ~III->second.Disabled;
699           OutNeeds = III->second.OutNeeds;
700         }
701       } else {
702         // If the instruction doesn't actually need a correct EXEC, then we can
703         // safely leave WWM enabled.
704         Needs = StateExact | StateWQM | StateWWM;
705       }
706 
707       if (MI.isTerminator() && OutNeeds == StateExact)
708         Needs = StateExact;
709 
710       if (MI.getOpcode() == AMDGPU::SI_ELSE && BI.OutNeeds == StateExact)
711         MI.getOperand(3).setImm(1);
712 
713       ++Next;
714     } else {
715       // End of basic block
716       if (BI.OutNeeds & StateWQM)
717         Needs = StateWQM;
718       else if (BI.OutNeeds == StateExact)
719         Needs = StateExact;
720       else
721         Needs = StateWQM | StateExact;
722     }
723 
724     // Now, transition if necessary.
725     if (!(Needs & State)) {
726       MachineBasicBlock::iterator First;
727       if (State == StateWWM || Needs == StateWWM) {
728         // We must switch to or from WWM
729         First = FirstWWM;
730       } else {
731         // We only need to switch to/from WQM, so we can use FirstWQM
732         First = FirstWQM;
733       }
734 
735       MachineBasicBlock::iterator Before =
736           prepareInsertion(MBB, First, II, Needs == StateWQM,
737                            Needs == StateExact || WQMFromExec);
738 
739       if (State == StateWWM) {
740         assert(SavedNonWWMReg);
741         fromWWM(MBB, Before, SavedNonWWMReg);
742         State = NonWWMState;
743       }
744 
745       if (Needs == StateWWM) {
746         NonWWMState = State;
747         SavedNonWWMReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
748         toWWM(MBB, Before, SavedNonWWMReg);
749         State = StateWWM;
750       } else {
751         if (State == StateWQM && (Needs & StateExact) && !(Needs & StateWQM)) {
752           if (!WQMFromExec && (OutNeeds & StateWQM))
753             SavedWQMReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
754 
755           toExact(MBB, Before, SavedWQMReg, LiveMaskReg);
756           State = StateExact;
757         } else if (State == StateExact && (Needs & StateWQM) &&
758                    !(Needs & StateExact)) {
759           assert(WQMFromExec == (SavedWQMReg == 0));
760 
761           toWQM(MBB, Before, SavedWQMReg);
762 
763           if (SavedWQMReg) {
764             LIS->createAndComputeVirtRegInterval(SavedWQMReg);
765             SavedWQMReg = 0;
766           }
767           State = StateWQM;
768         } else {
769           // We can get here if we transitioned from WWM to a non-WWM state that
770           // already matches our needs, but we shouldn't need to do anything.
771           assert(Needs & State);
772         }
773       }
774     }
775 
776     if (Needs != (StateExact | StateWQM | StateWWM)) {
777       if (Needs != (StateExact | StateWQM))
778         FirstWQM = IE;
779       FirstWWM = IE;
780     }
781 
782     if (II == IE)
783       break;
784     II = Next;
785   }
786 }
787 
788 void SIWholeQuadMode::lowerLiveMaskQueries(unsigned LiveMaskReg) {
789   for (MachineInstr *MI : LiveMaskQueries) {
790     const DebugLoc &DL = MI->getDebugLoc();
791     unsigned Dest = MI->getOperand(0).getReg();
792     MachineInstr *Copy =
793         BuildMI(*MI->getParent(), MI, DL, TII->get(AMDGPU::COPY), Dest)
794             .addReg(LiveMaskReg);
795 
796     LIS->ReplaceMachineInstrInMaps(*MI, *Copy);
797     MI->eraseFromParent();
798   }
799 }
800 
801 void SIWholeQuadMode::lowerCopyInstrs() {
802   for (MachineInstr *MI : LowerToCopyInstrs)
803     MI->setDesc(TII->get(AMDGPU::COPY));
804 }
805 
806 bool SIWholeQuadMode::runOnMachineFunction(MachineFunction &MF) {
807   Instructions.clear();
808   Blocks.clear();
809   LiveMaskQueries.clear();
810   LowerToCopyInstrs.clear();
811   CallingConv = MF.getFunction()->getCallingConv();
812 
813   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
814 
815   TII = ST.getInstrInfo();
816   TRI = &TII->getRegisterInfo();
817   MRI = &MF.getRegInfo();
818   LIS = &getAnalysis<LiveIntervals>();
819 
820   char GlobalFlags = analyzeFunction(MF);
821   unsigned LiveMaskReg = 0;
822   if (!(GlobalFlags & StateWQM)) {
823     lowerLiveMaskQueries(AMDGPU::EXEC);
824     if (!(GlobalFlags & StateWWM))
825       return !LiveMaskQueries.empty();
826   } else {
827     // Store a copy of the original live mask when required
828     MachineBasicBlock &Entry = MF.front();
829     MachineBasicBlock::iterator EntryMI = Entry.getFirstNonPHI();
830 
831     if (GlobalFlags & StateExact || !LiveMaskQueries.empty()) {
832       LiveMaskReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
833       MachineInstr *MI = BuildMI(Entry, EntryMI, DebugLoc(),
834                                  TII->get(AMDGPU::COPY), LiveMaskReg)
835                              .addReg(AMDGPU::EXEC);
836       LIS->InsertMachineInstrInMaps(*MI);
837     }
838 
839     lowerLiveMaskQueries(LiveMaskReg);
840 
841     if (GlobalFlags == StateWQM) {
842       // For a shader that needs only WQM, we can just set it once.
843       BuildMI(Entry, EntryMI, DebugLoc(), TII->get(AMDGPU::S_WQM_B64),
844               AMDGPU::EXEC)
845           .addReg(AMDGPU::EXEC);
846 
847       lowerCopyInstrs();
848       // EntryMI may become invalid here
849       return true;
850     }
851   }
852 
853   DEBUG(printInfo());
854 
855   lowerCopyInstrs();
856 
857   // Handle the general case
858   for (auto BII : Blocks)
859     processBlock(*BII.first, LiveMaskReg, BII.first == &*MF.begin());
860 
861   // Physical registers like SCC aren't tracked by default anyway, so just
862   // removing the ranges we computed is the simplest option for maintaining
863   // the analysis results.
864   LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::SCC, TRI));
865 
866   return true;
867 }
868