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