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