xref: /src/contrib/llvm-project/llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
14a16efa3SDimitry Andric //===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===//
24a16efa3SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64a16efa3SDimitry Andric //
74a16efa3SDimitry Andric //===----------------------------------------------------------------------===//
84a16efa3SDimitry Andric //
94a16efa3SDimitry Andric /// \file
10eb11fae6SDimitry Andric /// This pass lowers the pseudo control flow instructions to real
114a16efa3SDimitry Andric /// machine instructions.
124a16efa3SDimitry Andric ///
134a16efa3SDimitry Andric /// All control flow is handled using predicated instructions and
144a16efa3SDimitry Andric /// a predicate stack.  Each Scalar ALU controls the operations of 64 Vector
154a16efa3SDimitry Andric /// ALUs.  The Scalar ALU can update the predicate for any of the Vector ALUs
16c0981da4SDimitry Andric /// by writing to the 64-bit EXEC register (each bit corresponds to a
174a16efa3SDimitry Andric /// single vector ALU).  Typically, for predicates, a vector ALU will write
184a16efa3SDimitry Andric /// to its bit of the VCC register (like EXEC VCC is 64-bits, one for each
194a16efa3SDimitry Andric /// Vector ALU) and then the ScalarALU will AND the VCC register with the
204a16efa3SDimitry Andric /// EXEC to update the predicates.
214a16efa3SDimitry Andric ///
224a16efa3SDimitry Andric /// For example:
23044eb2f6SDimitry Andric /// %vcc = V_CMP_GT_F32 %vgpr1, %vgpr2
24044eb2f6SDimitry Andric /// %sgpr0 = SI_IF %vcc
25044eb2f6SDimitry Andric ///   %vgpr0 = V_ADD_F32 %vgpr0, %vgpr0
26044eb2f6SDimitry Andric /// %sgpr0 = SI_ELSE %sgpr0
27044eb2f6SDimitry Andric ///   %vgpr0 = V_SUB_F32 %vgpr0, %vgpr0
28044eb2f6SDimitry Andric /// SI_END_CF %sgpr0
294a16efa3SDimitry Andric ///
304a16efa3SDimitry Andric /// becomes:
314a16efa3SDimitry Andric ///
32044eb2f6SDimitry Andric /// %sgpr0 = S_AND_SAVEEXEC_B64 %vcc  // Save and update the exec mask
33044eb2f6SDimitry Andric /// %sgpr0 = S_XOR_B64 %sgpr0, %exec  // Clear live bits from saved exec mask
344a16efa3SDimitry Andric /// S_CBRANCH_EXECZ label0            // This instruction is an optional
354a16efa3SDimitry Andric ///                                   // optimization which allows us to
364a16efa3SDimitry Andric ///                                   // branch if all the bits of
374a16efa3SDimitry Andric ///                                   // EXEC are zero.
38044eb2f6SDimitry Andric /// %vgpr0 = V_ADD_F32 %vgpr0, %vgpr0 // Do the IF block of the branch
394a16efa3SDimitry Andric ///
404a16efa3SDimitry Andric /// label0:
41c0981da4SDimitry Andric /// %sgpr0 = S_OR_SAVEEXEC_B64 %sgpr0  // Restore the exec mask for the Then
42c0981da4SDimitry Andric ///                                    // block
43cfca06d7SDimitry Andric /// %exec = S_XOR_B64 %sgpr0, %exec    // Update the exec mask
444a16efa3SDimitry Andric /// S_BRANCH_EXECZ label1              // Use our branch optimization
454a16efa3SDimitry Andric ///                                    // instruction again.
46044eb2f6SDimitry Andric /// %vgpr0 = V_SUB_F32 %vgpr0, %vgpr   // Do the THEN block
474a16efa3SDimitry Andric /// label1:
48044eb2f6SDimitry Andric /// %exec = S_OR_B64 %exec, %sgpr0     // Re-enable saved exec mask bits
494a16efa3SDimitry Andric //===----------------------------------------------------------------------===//
504a16efa3SDimitry Andric 
514a16efa3SDimitry Andric #include "AMDGPU.h"
52b60736ecSDimitry Andric #include "GCNSubtarget.h"
53eb11fae6SDimitry Andric #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
54cfca06d7SDimitry Andric #include "llvm/ADT/SmallSet.h"
55044eb2f6SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
56c0981da4SDimitry Andric #include "llvm/CodeGen/LiveVariables.h"
57c0981da4SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
584a16efa3SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
596f8fc217SDimitry Andric #include "llvm/Target/TargetMachine.h"
604a16efa3SDimitry Andric 
614a16efa3SDimitry Andric using namespace llvm;
624a16efa3SDimitry Andric 
6301095a5dSDimitry Andric #define DEBUG_TYPE "si-lower-control-flow"
6401095a5dSDimitry Andric 
65cfca06d7SDimitry Andric static cl::opt<bool>
66cfca06d7SDimitry Andric RemoveRedundantEndcf("amdgpu-remove-redundant-endcf",
67cfca06d7SDimitry Andric     cl::init(true), cl::ReallyHidden);
68cfca06d7SDimitry Andric 
694a16efa3SDimitry Andric namespace {
704a16efa3SDimitry Andric 
7101095a5dSDimitry Andric class SILowerControlFlow : public MachineFunctionPass {
724a16efa3SDimitry Andric private:
7371d5a254SDimitry Andric   const SIRegisterInfo *TRI = nullptr;
7471d5a254SDimitry Andric   const SIInstrInfo *TII = nullptr;
7571d5a254SDimitry Andric   LiveIntervals *LIS = nullptr;
76c0981da4SDimitry Andric   LiveVariables *LV = nullptr;
77c0981da4SDimitry Andric   MachineDominatorTree *MDT = nullptr;
7871d5a254SDimitry Andric   MachineRegisterInfo *MRI = nullptr;
79cfca06d7SDimitry Andric   SetVector<MachineInstr*> LoweredEndCf;
80cfca06d7SDimitry Andric   DenseSet<Register> LoweredIf;
81344a3780SDimitry Andric   SmallSet<MachineBasicBlock *, 4> KillBlocks;
82b1c73532SDimitry Andric   SmallSet<Register, 8> RecomputeRegs;
834a16efa3SDimitry Andric 
84e6d15924SDimitry Andric   const TargetRegisterClass *BoolRC = nullptr;
85e6d15924SDimitry Andric   unsigned AndOpc;
86e6d15924SDimitry Andric   unsigned OrOpc;
87e6d15924SDimitry Andric   unsigned XorOpc;
88e6d15924SDimitry Andric   unsigned MovTermOpc;
89e6d15924SDimitry Andric   unsigned Andn2TermOpc;
90e6d15924SDimitry Andric   unsigned XorTermrOpc;
91b60736ecSDimitry Andric   unsigned OrTermrOpc;
92e6d15924SDimitry Andric   unsigned OrSaveExecOpc;
93e6d15924SDimitry Andric   unsigned Exec;
94e6d15924SDimitry Andric 
956f8fc217SDimitry Andric   bool EnableOptimizeEndCf = false;
966f8fc217SDimitry Andric 
97344a3780SDimitry Andric   bool hasKill(const MachineBasicBlock *Begin, const MachineBasicBlock *End);
98344a3780SDimitry Andric 
99b915e9e0SDimitry Andric   void emitIf(MachineInstr &MI);
100b915e9e0SDimitry Andric   void emitElse(MachineInstr &MI);
101b915e9e0SDimitry Andric   void emitIfBreak(MachineInstr &MI);
102b915e9e0SDimitry Andric   void emitLoop(MachineInstr &MI);
103b60736ecSDimitry Andric 
104b60736ecSDimitry Andric   MachineBasicBlock *emitEndCf(MachineInstr &MI);
105b60736ecSDimitry Andric 
106b915e9e0SDimitry Andric   void findMaskOperands(MachineInstr &MI, unsigned OpNo,
107b915e9e0SDimitry Andric                         SmallVectorImpl<MachineOperand> &Src) const;
1084a16efa3SDimitry Andric 
109b915e9e0SDimitry Andric   void combineMasks(MachineInstr &MI);
1104a16efa3SDimitry Andric 
111b60736ecSDimitry Andric   bool removeMBBifRedundant(MachineBasicBlock &MBB);
112b60736ecSDimitry Andric 
113b60736ecSDimitry Andric   MachineBasicBlock *process(MachineInstr &MI);
114cfca06d7SDimitry Andric 
115cfca06d7SDimitry Andric   // Skip to the next instruction, ignoring debug instructions, and trivial
116cfca06d7SDimitry Andric   // block boundaries (blocks that have one (typically fallthrough) successor,
117cfca06d7SDimitry Andric   // and the successor has one predecessor.
118cfca06d7SDimitry Andric   MachineBasicBlock::iterator
119cfca06d7SDimitry Andric   skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
120cfca06d7SDimitry Andric                                  MachineBasicBlock::iterator It) const;
121cfca06d7SDimitry Andric 
122b60736ecSDimitry Andric   /// Find the insertion point for a new conditional branch.
123b60736ecSDimitry Andric   MachineBasicBlock::iterator
skipToUncondBrOrEnd(MachineBasicBlock & MBB,MachineBasicBlock::iterator I) const124b60736ecSDimitry Andric   skipToUncondBrOrEnd(MachineBasicBlock &MBB,
125b60736ecSDimitry Andric                       MachineBasicBlock::iterator I) const {
126b60736ecSDimitry Andric     assert(I->isTerminator());
127b60736ecSDimitry Andric 
128b60736ecSDimitry Andric     // FIXME: What if we had multiple pre-existing conditional branches?
129b60736ecSDimitry Andric     MachineBasicBlock::iterator End = MBB.end();
130b60736ecSDimitry Andric     while (I != End && !I->isUnconditionalBranch())
131b60736ecSDimitry Andric       ++I;
132b60736ecSDimitry Andric     return I;
133b60736ecSDimitry Andric   }
134b60736ecSDimitry Andric 
135cfca06d7SDimitry Andric   // Remove redundant SI_END_CF instructions.
136cfca06d7SDimitry Andric   void optimizeEndCf();
137cfca06d7SDimitry Andric 
1384a16efa3SDimitry Andric public:
13901095a5dSDimitry Andric   static char ID;
14001095a5dSDimitry Andric 
SILowerControlFlow()14171d5a254SDimitry Andric   SILowerControlFlow() : MachineFunctionPass(ID) {}
1424a16efa3SDimitry Andric 
1435ca98fd9SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
1444a16efa3SDimitry Andric 
getPassName() const145b915e9e0SDimitry Andric   StringRef getPassName() const override {
14601095a5dSDimitry Andric     return "SI Lower control flow pseudo instructions";
147dd58ef01SDimitry Andric   }
148b915e9e0SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const149b915e9e0SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
150ac9a064cSDimitry Andric     AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
151b915e9e0SDimitry Andric     // Should preserve the same set that TwoAddressInstructions does.
152ac9a064cSDimitry Andric     AU.addPreserved<MachineDominatorTreeWrapperPass>();
153ac9a064cSDimitry Andric     AU.addPreserved<SlotIndexesWrapperPass>();
154ac9a064cSDimitry Andric     AU.addPreserved<LiveIntervalsWrapperPass>();
155b915e9e0SDimitry Andric     AU.addPreservedID(LiveVariablesID);
156b915e9e0SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
157b915e9e0SDimitry Andric   }
1584a16efa3SDimitry Andric };
1594a16efa3SDimitry Andric 
16071d5a254SDimitry Andric } // end anonymous namespace
1614a16efa3SDimitry Andric 
16201095a5dSDimitry Andric char SILowerControlFlow::ID = 0;
1634a16efa3SDimitry Andric 
16401095a5dSDimitry Andric INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE,
16501095a5dSDimitry Andric                "SI lower control flow", false, false)
16601095a5dSDimitry Andric 
setImpSCCDefDead(MachineInstr & MI,bool IsDead)167b915e9e0SDimitry Andric static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
168b915e9e0SDimitry Andric   MachineOperand &ImpDefSCC = MI.getOperand(3);
169b915e9e0SDimitry Andric   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
17001095a5dSDimitry Andric 
171b915e9e0SDimitry Andric   ImpDefSCC.setIsDead(IsDead);
1724a16efa3SDimitry Andric }
1734a16efa3SDimitry Andric 
174b915e9e0SDimitry Andric char &llvm::SILowerControlFlowID = SILowerControlFlow::ID;
17501095a5dSDimitry Andric 
hasKill(const MachineBasicBlock * Begin,const MachineBasicBlock * End)176344a3780SDimitry Andric bool SILowerControlFlow::hasKill(const MachineBasicBlock *Begin,
177344a3780SDimitry Andric                                  const MachineBasicBlock *End) {
178cfca06d7SDimitry Andric   DenseSet<const MachineBasicBlock*> Visited;
179b60736ecSDimitry Andric   SmallVector<MachineBasicBlock *, 4> Worklist(Begin->successors());
180cfca06d7SDimitry Andric 
181cfca06d7SDimitry Andric   while (!Worklist.empty()) {
182cfca06d7SDimitry Andric     MachineBasicBlock *MBB = Worklist.pop_back_val();
183cfca06d7SDimitry Andric 
184cfca06d7SDimitry Andric     if (MBB == End || !Visited.insert(MBB).second)
185cfca06d7SDimitry Andric       continue;
186344a3780SDimitry Andric     if (KillBlocks.contains(MBB))
187cfca06d7SDimitry Andric       return true;
188cfca06d7SDimitry Andric 
189cfca06d7SDimitry Andric     Worklist.append(MBB->succ_begin(), MBB->succ_end());
190cfca06d7SDimitry Andric   }
191cfca06d7SDimitry Andric 
192cfca06d7SDimitry Andric   return false;
193cfca06d7SDimitry Andric }
194cfca06d7SDimitry Andric 
isSimpleIf(const MachineInstr & MI,const MachineRegisterInfo * MRI)195cfca06d7SDimitry Andric static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
1961d5ae102SDimitry Andric   Register SaveExecReg = MI.getOperand(0).getReg();
197044eb2f6SDimitry Andric   auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
198044eb2f6SDimitry Andric 
199044eb2f6SDimitry Andric   if (U == MRI->use_instr_nodbg_end() ||
200044eb2f6SDimitry Andric       std::next(U) != MRI->use_instr_nodbg_end() ||
201044eb2f6SDimitry Andric       U->getOpcode() != AMDGPU::SI_END_CF)
202044eb2f6SDimitry Andric     return false;
203044eb2f6SDimitry Andric 
204044eb2f6SDimitry Andric   return true;
205044eb2f6SDimitry Andric }
206044eb2f6SDimitry Andric 
emitIf(MachineInstr & MI)207b915e9e0SDimitry Andric void SILowerControlFlow::emitIf(MachineInstr &MI) {
2084a16efa3SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
209b915e9e0SDimitry Andric   const DebugLoc &DL = MI.getDebugLoc();
210b915e9e0SDimitry Andric   MachineBasicBlock::iterator I(&MI);
211cfca06d7SDimitry Andric   Register SaveExecReg = MI.getOperand(0).getReg();
212b915e9e0SDimitry Andric   MachineOperand& Cond = MI.getOperand(1);
2131d5ae102SDimitry Andric   assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
21401095a5dSDimitry Andric 
215b915e9e0SDimitry Andric   MachineOperand &ImpDefSCC = MI.getOperand(4);
216b915e9e0SDimitry Andric   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
217b915e9e0SDimitry Andric 
218044eb2f6SDimitry Andric   // If there is only one use of save exec register and that use is SI_END_CF,
219044eb2f6SDimitry Andric   // we can optimize SI_IF by returning the full saved exec mask instead of
220044eb2f6SDimitry Andric   // just cleared bits.
221cfca06d7SDimitry Andric   bool SimpleIf = isSimpleIf(MI, MRI);
222cfca06d7SDimitry Andric 
223344a3780SDimitry Andric   if (SimpleIf) {
224cfca06d7SDimitry Andric     // Check for SI_KILL_*_TERMINATOR on path from if to endif.
225cfca06d7SDimitry Andric     // if there is any such terminator simplifications are not safe.
226cfca06d7SDimitry Andric     auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
227344a3780SDimitry Andric     SimpleIf = !hasKill(MI.getParent(), UseMI->getParent());
228cfca06d7SDimitry Andric   }
229044eb2f6SDimitry Andric 
230b915e9e0SDimitry Andric   // Add an implicit def of exec to discourage scheduling VALU after this which
231b915e9e0SDimitry Andric   // will interfere with trying to form s_and_saveexec_b64 later.
232e6d15924SDimitry Andric   Register CopyReg = SimpleIf ? SaveExecReg
233e6d15924SDimitry Andric                        : MRI->createVirtualRegister(BoolRC);
234b915e9e0SDimitry Andric   MachineInstr *CopyExec =
235b915e9e0SDimitry Andric     BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
236e6d15924SDimitry Andric     .addReg(Exec)
237e6d15924SDimitry Andric     .addReg(Exec, RegState::ImplicitDefine);
238cfca06d7SDimitry Andric   LoweredIf.insert(CopyReg);
239b915e9e0SDimitry Andric 
2401d5ae102SDimitry Andric   Register Tmp = MRI->createVirtualRegister(BoolRC);
241b915e9e0SDimitry Andric 
242b915e9e0SDimitry Andric   MachineInstr *And =
243e6d15924SDimitry Andric     BuildMI(MBB, I, DL, TII->get(AndOpc), Tmp)
244b915e9e0SDimitry Andric     .addReg(CopyReg)
245e6d15924SDimitry Andric     .add(Cond);
246c0981da4SDimitry Andric   if (LV)
247c0981da4SDimitry Andric     LV->replaceKillInstruction(Cond.getReg(), MI, *And);
248e6d15924SDimitry Andric 
249b915e9e0SDimitry Andric   setImpSCCDefDead(*And, true);
250b915e9e0SDimitry Andric 
251044eb2f6SDimitry Andric   MachineInstr *Xor = nullptr;
252044eb2f6SDimitry Andric   if (!SimpleIf) {
253044eb2f6SDimitry Andric     Xor =
254e6d15924SDimitry Andric       BuildMI(MBB, I, DL, TII->get(XorOpc), SaveExecReg)
255b915e9e0SDimitry Andric       .addReg(Tmp)
256b915e9e0SDimitry Andric       .addReg(CopyReg);
257b915e9e0SDimitry Andric     setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
258044eb2f6SDimitry Andric   }
259b915e9e0SDimitry Andric 
260b915e9e0SDimitry Andric   // Use a copy that is a terminator to get correct spill code placement it with
261b915e9e0SDimitry Andric   // fast regalloc.
262b915e9e0SDimitry Andric   MachineInstr *SetExec =
263e6d15924SDimitry Andric     BuildMI(MBB, I, DL, TII->get(MovTermOpc), Exec)
264b915e9e0SDimitry Andric     .addReg(Tmp, RegState::Kill);
265c0981da4SDimitry Andric   if (LV)
266c0981da4SDimitry Andric     LV->getVarInfo(Tmp).Kills.push_back(SetExec);
267b915e9e0SDimitry Andric 
268b60736ecSDimitry Andric   // Skip ahead to the unconditional branch in case there are other terminators
269b60736ecSDimitry Andric   // present.
270b60736ecSDimitry Andric   I = skipToUncondBrOrEnd(MBB, I);
271b60736ecSDimitry Andric 
272706b4fc4SDimitry Andric   // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
273706b4fc4SDimitry Andric   // during SIRemoveShortExecBranches.
274706b4fc4SDimitry Andric   MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
27571d5a254SDimitry Andric                             .add(MI.getOperand(2));
276b915e9e0SDimitry Andric 
277b915e9e0SDimitry Andric   if (!LIS) {
278b915e9e0SDimitry Andric     MI.eraseFromParent();
279b915e9e0SDimitry Andric     return;
280b915e9e0SDimitry Andric   }
281b915e9e0SDimitry Andric 
282b915e9e0SDimitry Andric   LIS->InsertMachineInstrInMaps(*CopyExec);
283b915e9e0SDimitry Andric 
284b915e9e0SDimitry Andric   // Replace with and so we don't need to fix the live interval for condition
285b915e9e0SDimitry Andric   // register.
286b915e9e0SDimitry Andric   LIS->ReplaceMachineInstrInMaps(MI, *And);
287b915e9e0SDimitry Andric 
288044eb2f6SDimitry Andric   if (!SimpleIf)
289b915e9e0SDimitry Andric     LIS->InsertMachineInstrInMaps(*Xor);
290b915e9e0SDimitry Andric   LIS->InsertMachineInstrInMaps(*SetExec);
291b915e9e0SDimitry Andric   LIS->InsertMachineInstrInMaps(*NewBr);
292b915e9e0SDimitry Andric 
293e6d15924SDimitry Andric   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
294b915e9e0SDimitry Andric   MI.eraseFromParent();
295b915e9e0SDimitry Andric 
296b915e9e0SDimitry Andric   // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
297b915e9e0SDimitry Andric   // hard to add another def here but I'm not sure how to correctly update the
298b915e9e0SDimitry Andric   // valno.
299b1c73532SDimitry Andric   RecomputeRegs.insert(SaveExecReg);
300b915e9e0SDimitry Andric   LIS->createAndComputeVirtRegInterval(Tmp);
301044eb2f6SDimitry Andric   if (!SimpleIf)
302b915e9e0SDimitry Andric     LIS->createAndComputeVirtRegInterval(CopyReg);
303b915e9e0SDimitry Andric }
304b915e9e0SDimitry Andric 
emitElse(MachineInstr & MI)305b915e9e0SDimitry Andric void SILowerControlFlow::emitElse(MachineInstr &MI) {
306b915e9e0SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
30701095a5dSDimitry Andric   const DebugLoc &DL = MI.getDebugLoc();
3084a16efa3SDimitry Andric 
309cfca06d7SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
310b1c73532SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
31101095a5dSDimitry Andric 
312b915e9e0SDimitry Andric   MachineBasicBlock::iterator Start = MBB.begin();
3134a16efa3SDimitry Andric 
314b915e9e0SDimitry Andric   // This must be inserted before phis and any spill code inserted before the
315b915e9e0SDimitry Andric   // else.
316b60736ecSDimitry Andric   Register SaveReg = MRI->createVirtualRegister(BoolRC);
317b915e9e0SDimitry Andric   MachineInstr *OrSaveExec =
318e6d15924SDimitry Andric     BuildMI(MBB, Start, DL, TII->get(OrSaveExecOpc), SaveReg)
319b60736ecSDimitry Andric     .add(MI.getOperand(1)); // Saved EXEC
320c0981da4SDimitry Andric   if (LV)
321b1c73532SDimitry Andric     LV->replaceKillInstruction(SrcReg, MI, *OrSaveExec);
32201095a5dSDimitry Andric 
323b915e9e0SDimitry Andric   MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
3244a16efa3SDimitry Andric 
325b915e9e0SDimitry Andric   MachineBasicBlock::iterator ElsePt(MI);
3264a16efa3SDimitry Andric 
327b60736ecSDimitry Andric   // This accounts for any modification of the EXEC mask within the block and
328b60736ecSDimitry Andric   // can be optimized out pre-RA when not required.
329b60736ecSDimitry Andric   MachineInstr *And = BuildMI(MBB, ElsePt, DL, TII->get(AndOpc), DstReg)
330e6d15924SDimitry Andric                           .addReg(Exec)
331b915e9e0SDimitry Andric                           .addReg(SaveReg);
332b915e9e0SDimitry Andric 
333b915e9e0SDimitry Andric   MachineInstr *Xor =
334e6d15924SDimitry Andric     BuildMI(MBB, ElsePt, DL, TII->get(XorTermrOpc), Exec)
335e6d15924SDimitry Andric     .addReg(Exec)
336b915e9e0SDimitry Andric     .addReg(DstReg);
3374a16efa3SDimitry Andric 
338b60736ecSDimitry Andric   // Skip ahead to the unconditional branch in case there are other terminators
339b60736ecSDimitry Andric   // present.
340b60736ecSDimitry Andric   ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
341b60736ecSDimitry Andric 
342b915e9e0SDimitry Andric   MachineInstr *Branch =
343706b4fc4SDimitry Andric       BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
344b915e9e0SDimitry Andric           .addMBB(DestBB);
3454a16efa3SDimitry Andric 
346b915e9e0SDimitry Andric   if (!LIS) {
3474a16efa3SDimitry Andric     MI.eraseFromParent();
348b915e9e0SDimitry Andric     return;
3494a16efa3SDimitry Andric   }
3504a16efa3SDimitry Andric 
351b915e9e0SDimitry Andric   LIS->RemoveMachineInstrFromMaps(MI);
352b915e9e0SDimitry Andric   MI.eraseFromParent();
353b915e9e0SDimitry Andric 
354b915e9e0SDimitry Andric   LIS->InsertMachineInstrInMaps(*OrSaveExec);
355b1c73532SDimitry Andric   LIS->InsertMachineInstrInMaps(*And);
356b915e9e0SDimitry Andric 
357b915e9e0SDimitry Andric   LIS->InsertMachineInstrInMaps(*Xor);
358b915e9e0SDimitry Andric   LIS->InsertMachineInstrInMaps(*Branch);
359b915e9e0SDimitry Andric 
360b1c73532SDimitry Andric   RecomputeRegs.insert(SrcReg);
361b1c73532SDimitry Andric   RecomputeRegs.insert(DstReg);
362b915e9e0SDimitry Andric   LIS->createAndComputeVirtRegInterval(SaveReg);
363b915e9e0SDimitry Andric 
364b915e9e0SDimitry Andric   // Let this be recomputed.
365e6d15924SDimitry Andric   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
366b915e9e0SDimitry Andric }
367b915e9e0SDimitry Andric 
emitIfBreak(MachineInstr & MI)368b915e9e0SDimitry Andric void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
369eb11fae6SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
370eb11fae6SDimitry Andric   const DebugLoc &DL = MI.getDebugLoc();
371cfca06d7SDimitry Andric   auto Dst = MI.getOperand(0).getReg();
372eb11fae6SDimitry Andric 
373eb11fae6SDimitry Andric   // Skip ANDing with exec if the break condition is already masked by exec
374eb11fae6SDimitry Andric   // because it is a V_CMP in the same basic block. (We know the break
375eb11fae6SDimitry Andric   // condition operand was an i1 in IR, so if it is a VALU instruction it must
376eb11fae6SDimitry Andric   // be one with a carry-out.)
377eb11fae6SDimitry Andric   bool SkipAnding = false;
378eb11fae6SDimitry Andric   if (MI.getOperand(1).isReg()) {
379eb11fae6SDimitry Andric     if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
380eb11fae6SDimitry Andric       SkipAnding = Def->getParent() == MI.getParent()
381eb11fae6SDimitry Andric           && SIInstrInfo::isVALU(*Def);
382eb11fae6SDimitry Andric     }
383eb11fae6SDimitry Andric   }
384eb11fae6SDimitry Andric 
385eb11fae6SDimitry Andric   // AND the break condition operand with exec, then OR that into the "loop
386eb11fae6SDimitry Andric   // exit" mask.
387eb11fae6SDimitry Andric   MachineInstr *And = nullptr, *Or = nullptr;
388b1c73532SDimitry Andric   Register AndReg;
389eb11fae6SDimitry Andric   if (!SkipAnding) {
390b1c73532SDimitry Andric     AndReg = MRI->createVirtualRegister(BoolRC);
391706b4fc4SDimitry Andric     And = BuildMI(MBB, &MI, DL, TII->get(AndOpc), AndReg)
392e6d15924SDimitry Andric              .addReg(Exec)
393eb11fae6SDimitry Andric              .add(MI.getOperand(1));
394c0981da4SDimitry Andric     if (LV)
395c0981da4SDimitry Andric       LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *And);
396e6d15924SDimitry Andric     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
397706b4fc4SDimitry Andric              .addReg(AndReg)
398eb11fae6SDimitry Andric              .add(MI.getOperand(2));
399c0981da4SDimitry Andric   } else {
400e6d15924SDimitry Andric     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
401eb11fae6SDimitry Andric              .add(MI.getOperand(1))
402eb11fae6SDimitry Andric              .add(MI.getOperand(2));
403c0981da4SDimitry Andric     if (LV)
404c0981da4SDimitry Andric       LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *Or);
405c0981da4SDimitry Andric   }
406c0981da4SDimitry Andric   if (LV)
407c0981da4SDimitry Andric     LV->replaceKillInstruction(MI.getOperand(2).getReg(), MI, *Or);
408eb11fae6SDimitry Andric 
409eb11fae6SDimitry Andric   if (LIS) {
410eb11fae6SDimitry Andric     LIS->ReplaceMachineInstrInMaps(MI, *Or);
411b1c73532SDimitry Andric     if (And) {
412b1c73532SDimitry Andric       // Read of original operand 1 is on And now not Or.
413b1c73532SDimitry Andric       RecomputeRegs.insert(And->getOperand(2).getReg());
414b1c73532SDimitry Andric       LIS->InsertMachineInstrInMaps(*And);
415b1c73532SDimitry Andric       LIS->createAndComputeVirtRegInterval(AndReg);
416b1c73532SDimitry Andric     }
417eb11fae6SDimitry Andric   }
418eb11fae6SDimitry Andric 
419eb11fae6SDimitry Andric   MI.eraseFromParent();
4204a16efa3SDimitry Andric }
4214a16efa3SDimitry Andric 
emitLoop(MachineInstr & MI)422b915e9e0SDimitry Andric void SILowerControlFlow::emitLoop(MachineInstr &MI) {
4234a16efa3SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
424b915e9e0SDimitry Andric   const DebugLoc &DL = MI.getDebugLoc();
4254a16efa3SDimitry Andric 
426b915e9e0SDimitry Andric   MachineInstr *AndN2 =
427e6d15924SDimitry Andric       BuildMI(MBB, &MI, DL, TII->get(Andn2TermOpc), Exec)
428e6d15924SDimitry Andric           .addReg(Exec)
42971d5a254SDimitry Andric           .add(MI.getOperand(0));
4307fa27ce4SDimitry Andric   if (LV)
4317fa27ce4SDimitry Andric     LV->replaceKillInstruction(MI.getOperand(0).getReg(), MI, *AndN2);
4324a16efa3SDimitry Andric 
433b60736ecSDimitry Andric   auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
434b915e9e0SDimitry Andric   MachineInstr *Branch =
435b60736ecSDimitry Andric       BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
43671d5a254SDimitry Andric           .add(MI.getOperand(1));
4374a16efa3SDimitry Andric 
438b915e9e0SDimitry Andric   if (LIS) {
439b1c73532SDimitry Andric     RecomputeRegs.insert(MI.getOperand(0).getReg());
440b915e9e0SDimitry Andric     LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
441b915e9e0SDimitry Andric     LIS->InsertMachineInstrInMaps(*Branch);
4425ca98fd9SDimitry Andric   }
4434a16efa3SDimitry Andric 
4444a16efa3SDimitry Andric   MI.eraseFromParent();
4454a16efa3SDimitry Andric }
4464a16efa3SDimitry Andric 
447cfca06d7SDimitry Andric MachineBasicBlock::iterator
skipIgnoreExecInstsTrivialSucc(MachineBasicBlock & MBB,MachineBasicBlock::iterator It) const448cfca06d7SDimitry Andric SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
449cfca06d7SDimitry Andric   MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
450cfca06d7SDimitry Andric 
451cfca06d7SDimitry Andric   SmallSet<const MachineBasicBlock *, 4> Visited;
452cfca06d7SDimitry Andric   MachineBasicBlock *B = &MBB;
453cfca06d7SDimitry Andric   do {
454cfca06d7SDimitry Andric     if (!Visited.insert(B).second)
455cfca06d7SDimitry Andric       return MBB.end();
456cfca06d7SDimitry Andric 
457cfca06d7SDimitry Andric     auto E = B->end();
458cfca06d7SDimitry Andric     for ( ; It != E; ++It) {
459cfca06d7SDimitry Andric       if (TII->mayReadEXEC(*MRI, *It))
460cfca06d7SDimitry Andric         break;
461cfca06d7SDimitry Andric     }
462cfca06d7SDimitry Andric 
463cfca06d7SDimitry Andric     if (It != E)
464cfca06d7SDimitry Andric       return It;
465cfca06d7SDimitry Andric 
466cfca06d7SDimitry Andric     if (B->succ_size() != 1)
467cfca06d7SDimitry Andric       return MBB.end();
468cfca06d7SDimitry Andric 
469cfca06d7SDimitry Andric     // If there is one trivial successor, advance to the next block.
470cfca06d7SDimitry Andric     MachineBasicBlock *Succ = *B->succ_begin();
471cfca06d7SDimitry Andric 
472cfca06d7SDimitry Andric     It = Succ->begin();
473cfca06d7SDimitry Andric     B = Succ;
474cfca06d7SDimitry Andric   } while (true);
475cfca06d7SDimitry Andric }
476cfca06d7SDimitry Andric 
emitEndCf(MachineInstr & MI)477b60736ecSDimitry Andric MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &MI) {
4784a16efa3SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
47901095a5dSDimitry Andric   const DebugLoc &DL = MI.getDebugLoc();
4804a16efa3SDimitry Andric 
481b60736ecSDimitry Andric   MachineBasicBlock::iterator InsPt = MBB.begin();
482b60736ecSDimitry Andric 
483b60736ecSDimitry Andric   // If we have instructions that aren't prolog instructions, split the block
484b60736ecSDimitry Andric   // and emit a terminator instruction. This ensures correct spill placement.
485b60736ecSDimitry Andric   // FIXME: We should unconditionally split the block here.
486b60736ecSDimitry Andric   bool NeedBlockSplit = false;
487b60736ecSDimitry Andric   Register DataReg = MI.getOperand(0).getReg();
488b60736ecSDimitry Andric   for (MachineBasicBlock::iterator I = InsPt, E = MI.getIterator();
489b60736ecSDimitry Andric        I != E; ++I) {
490b60736ecSDimitry Andric     if (I->modifiesRegister(DataReg, TRI)) {
491b60736ecSDimitry Andric       NeedBlockSplit = true;
492b60736ecSDimitry Andric       break;
493b60736ecSDimitry Andric     }
494b60736ecSDimitry Andric   }
495b60736ecSDimitry Andric 
496b60736ecSDimitry Andric   unsigned Opcode = OrOpc;
497b60736ecSDimitry Andric   MachineBasicBlock *SplitBB = &MBB;
498b60736ecSDimitry Andric   if (NeedBlockSplit) {
499b60736ecSDimitry Andric     SplitBB = MBB.splitAt(MI, /*UpdateLiveIns*/true, LIS);
500c0981da4SDimitry Andric     if (MDT && SplitBB != &MBB) {
501c0981da4SDimitry Andric       MachineDomTreeNode *MBBNode = (*MDT)[&MBB];
502c0981da4SDimitry Andric       SmallVector<MachineDomTreeNode *> Children(MBBNode->begin(),
503c0981da4SDimitry Andric                                                  MBBNode->end());
504c0981da4SDimitry Andric       MachineDomTreeNode *SplitBBNode = MDT->addNewBlock(SplitBB, &MBB);
505c0981da4SDimitry Andric       for (MachineDomTreeNode *Child : Children)
506c0981da4SDimitry Andric         MDT->changeImmediateDominator(Child, SplitBBNode);
507c0981da4SDimitry Andric     }
508b60736ecSDimitry Andric     Opcode = OrTermrOpc;
509b60736ecSDimitry Andric     InsPt = MI;
510b60736ecSDimitry Andric   }
511b60736ecSDimitry Andric 
512b60736ecSDimitry Andric   MachineInstr *NewMI =
513b60736ecSDimitry Andric     BuildMI(MBB, InsPt, DL, TII->get(Opcode), Exec)
514e6d15924SDimitry Andric     .addReg(Exec)
51571d5a254SDimitry Andric     .add(MI.getOperand(0));
516145449b1SDimitry Andric   if (LV) {
517145449b1SDimitry Andric     LV->replaceKillInstruction(DataReg, MI, *NewMI);
518145449b1SDimitry Andric 
519145449b1SDimitry Andric     if (SplitBB != &MBB) {
5207fa27ce4SDimitry Andric       // Track the set of registers defined in the original block so we don't
5217fa27ce4SDimitry Andric       // accidentally add the original block to AliveBlocks. AliveBlocks only
5227fa27ce4SDimitry Andric       // includes blocks which are live through, which excludes live outs and
5237fa27ce4SDimitry Andric       // local defs.
5247fa27ce4SDimitry Andric       DenseSet<Register> DefInOrigBlock;
5257fa27ce4SDimitry Andric 
5267fa27ce4SDimitry Andric       for (MachineBasicBlock *BlockPiece : {&MBB, SplitBB}) {
5277fa27ce4SDimitry Andric         for (MachineInstr &X : *BlockPiece) {
5287fa27ce4SDimitry Andric           for (MachineOperand &Op : X.all_defs()) {
5297fa27ce4SDimitry Andric             if (Op.getReg().isVirtual())
5307fa27ce4SDimitry Andric               DefInOrigBlock.insert(Op.getReg());
5317fa27ce4SDimitry Andric           }
532145449b1SDimitry Andric         }
533145449b1SDimitry Andric       }
534145449b1SDimitry Andric 
535145449b1SDimitry Andric       for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
536145449b1SDimitry Andric         Register Reg = Register::index2VirtReg(i);
537145449b1SDimitry Andric         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
538145449b1SDimitry Andric 
539145449b1SDimitry Andric         if (VI.AliveBlocks.test(MBB.getNumber()))
540145449b1SDimitry Andric           VI.AliveBlocks.set(SplitBB->getNumber());
541145449b1SDimitry Andric         else {
542145449b1SDimitry Andric           for (MachineInstr *Kill : VI.Kills) {
5437fa27ce4SDimitry Andric             if (Kill->getParent() == SplitBB && !DefInOrigBlock.contains(Reg))
544145449b1SDimitry Andric               VI.AliveBlocks.set(MBB.getNumber());
545145449b1SDimitry Andric           }
546145449b1SDimitry Andric         }
547145449b1SDimitry Andric       }
548145449b1SDimitry Andric     }
549145449b1SDimitry Andric   }
550f03b5bedSDimitry Andric 
551cfca06d7SDimitry Andric   LoweredEndCf.insert(NewMI);
552cfca06d7SDimitry Andric 
553344a3780SDimitry Andric   if (LIS)
554b915e9e0SDimitry Andric     LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
55501095a5dSDimitry Andric 
55601095a5dSDimitry Andric   MI.eraseFromParent();
557b915e9e0SDimitry Andric 
558b915e9e0SDimitry Andric   if (LIS)
559b915e9e0SDimitry Andric     LIS->handleMove(*NewMI);
560b60736ecSDimitry Andric   return SplitBB;
56101095a5dSDimitry Andric }
5624a16efa3SDimitry Andric 
563b915e9e0SDimitry Andric // Returns replace operands for a logical operation, either single result
564b915e9e0SDimitry Andric // for exec or two operands if source was another equivalent operation.
findMaskOperands(MachineInstr & MI,unsigned OpNo,SmallVectorImpl<MachineOperand> & Src) const565b915e9e0SDimitry Andric void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
566b915e9e0SDimitry Andric        SmallVectorImpl<MachineOperand> &Src) const {
567b915e9e0SDimitry Andric   MachineOperand &Op = MI.getOperand(OpNo);
568b60736ecSDimitry Andric   if (!Op.isReg() || !Op.getReg().isVirtual()) {
569b915e9e0SDimitry Andric     Src.push_back(Op);
570b915e9e0SDimitry Andric     return;
5714a16efa3SDimitry Andric   }
5724a16efa3SDimitry Andric 
573b915e9e0SDimitry Andric   MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
574b915e9e0SDimitry Andric   if (!Def || Def->getParent() != MI.getParent() ||
575b915e9e0SDimitry Andric       !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
576b915e9e0SDimitry Andric     return;
5774a16efa3SDimitry Andric 
578b915e9e0SDimitry Andric   // Make sure we do not modify exec between def and use.
579145449b1SDimitry Andric   // A copy with implicitly defined exec inserted earlier is an exclusion, it
580b915e9e0SDimitry Andric   // does not really modify exec.
581b915e9e0SDimitry Andric   for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
582b915e9e0SDimitry Andric     if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
583e6d15924SDimitry Andric         !(I->isCopy() && I->getOperand(0).getReg() != Exec))
584b915e9e0SDimitry Andric       return;
585f03b5bedSDimitry Andric 
586b915e9e0SDimitry Andric   for (const auto &SrcOp : Def->explicit_operands())
587eb11fae6SDimitry Andric     if (SrcOp.isReg() && SrcOp.isUse() &&
588b60736ecSDimitry Andric         (SrcOp.getReg().isVirtual() || SrcOp.getReg() == Exec))
589b915e9e0SDimitry Andric       Src.push_back(SrcOp);
5904a16efa3SDimitry Andric }
5914a16efa3SDimitry Andric 
592b915e9e0SDimitry Andric // Search and combine pairs of equivalent instructions, like
593b915e9e0SDimitry Andric // S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
594b915e9e0SDimitry Andric // S_OR_B64  x, (S_OR_B64  x, y) => S_OR_B64  x, y
595b915e9e0SDimitry Andric // One of the operands is exec mask.
combineMasks(MachineInstr & MI)596b915e9e0SDimitry Andric void SILowerControlFlow::combineMasks(MachineInstr &MI) {
597b915e9e0SDimitry Andric   assert(MI.getNumExplicitOperands() == 3);
598b915e9e0SDimitry Andric   SmallVector<MachineOperand, 4> Ops;
599b915e9e0SDimitry Andric   unsigned OpToReplace = 1;
600b915e9e0SDimitry Andric   findMaskOperands(MI, 1, Ops);
601b915e9e0SDimitry Andric   if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
602b915e9e0SDimitry Andric   findMaskOperands(MI, 2, Ops);
603b915e9e0SDimitry Andric   if (Ops.size() != 3) return;
60401095a5dSDimitry Andric 
605b915e9e0SDimitry Andric   unsigned UniqueOpndIdx;
606b915e9e0SDimitry Andric   if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
607b915e9e0SDimitry Andric   else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
608b915e9e0SDimitry Andric   else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
609b915e9e0SDimitry Andric   else return;
610b915e9e0SDimitry Andric 
6111d5ae102SDimitry Andric   Register Reg = MI.getOperand(OpToReplace).getReg();
612145449b1SDimitry Andric   MI.removeOperand(OpToReplace);
613b915e9e0SDimitry Andric   MI.addOperand(Ops[UniqueOpndIdx]);
614b915e9e0SDimitry Andric   if (MRI->use_empty(Reg))
615b915e9e0SDimitry Andric     MRI->getUniqueVRegDef(Reg)->eraseFromParent();
61601095a5dSDimitry Andric }
61701095a5dSDimitry Andric 
optimizeEndCf()618cfca06d7SDimitry Andric void SILowerControlFlow::optimizeEndCf() {
619145449b1SDimitry Andric   // If the only instruction immediately following this END_CF is another
620cfca06d7SDimitry Andric   // END_CF in the only successor we can avoid emitting exec mask restore here.
6216f8fc217SDimitry Andric   if (!EnableOptimizeEndCf)
622cfca06d7SDimitry Andric     return;
62301095a5dSDimitry Andric 
6246f8fc217SDimitry Andric   for (MachineInstr *MI : reverse(LoweredEndCf)) {
625cfca06d7SDimitry Andric     MachineBasicBlock &MBB = *MI->getParent();
626cfca06d7SDimitry Andric     auto Next =
627cfca06d7SDimitry Andric       skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
628cfca06d7SDimitry Andric     if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
629cfca06d7SDimitry Andric       continue;
630cfca06d7SDimitry Andric     // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
631cfca06d7SDimitry Andric     // If that belongs to SI_ELSE then saved mask has an inverted value.
632cfca06d7SDimitry Andric     Register SavedExec
633cfca06d7SDimitry Andric       = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
634cfca06d7SDimitry Andric     assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
635e6d15924SDimitry Andric 
636cfca06d7SDimitry Andric     const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
637cfca06d7SDimitry Andric     if (Def && LoweredIf.count(SavedExec)) {
638cfca06d7SDimitry Andric       LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
639cfca06d7SDimitry Andric       if (LIS)
640cfca06d7SDimitry Andric         LIS->RemoveMachineInstrFromMaps(*MI);
641c0981da4SDimitry Andric       Register Reg;
642c0981da4SDimitry Andric       if (LV)
643c0981da4SDimitry Andric         Reg = TII->getNamedOperand(*MI, AMDGPU::OpName::src1)->getReg();
644cfca06d7SDimitry Andric       MI->eraseFromParent();
645c0981da4SDimitry Andric       if (LV)
646c0981da4SDimitry Andric         LV->recomputeForSingleDefVirtReg(Reg);
647b60736ecSDimitry Andric       removeMBBifRedundant(MBB);
648cfca06d7SDimitry Andric     }
649cfca06d7SDimitry Andric   }
650e6d15924SDimitry Andric }
6514a16efa3SDimitry Andric 
process(MachineInstr & MI)652b60736ecSDimitry Andric MachineBasicBlock *SILowerControlFlow::process(MachineInstr &MI) {
653cfca06d7SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
654cfca06d7SDimitry Andric   MachineBasicBlock::iterator I(MI);
655cfca06d7SDimitry Andric   MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
65667c32a98SDimitry Andric 
657b60736ecSDimitry Andric   MachineBasicBlock *SplitBB = &MBB;
658b60736ecSDimitry Andric 
6594a16efa3SDimitry Andric   switch (MI.getOpcode()) {
6604a16efa3SDimitry Andric   case AMDGPU::SI_IF:
661b915e9e0SDimitry Andric     emitIf(MI);
6624a16efa3SDimitry Andric     break;
6634a16efa3SDimitry Andric 
6644a16efa3SDimitry Andric   case AMDGPU::SI_ELSE:
665b915e9e0SDimitry Andric     emitElse(MI);
6664a16efa3SDimitry Andric     break;
6674a16efa3SDimitry Andric 
6684a16efa3SDimitry Andric   case AMDGPU::SI_IF_BREAK:
669b915e9e0SDimitry Andric     emitIfBreak(MI);
6704a16efa3SDimitry Andric     break;
6714a16efa3SDimitry Andric 
6724a16efa3SDimitry Andric   case AMDGPU::SI_LOOP:
673b915e9e0SDimitry Andric     emitLoop(MI);
6744a16efa3SDimitry Andric     break;
6754a16efa3SDimitry Andric 
676344a3780SDimitry Andric   case AMDGPU::SI_WATERFALL_LOOP:
677344a3780SDimitry Andric     MI.setDesc(TII->get(AMDGPU::S_CBRANCH_EXECNZ));
678344a3780SDimitry Andric     break;
679344a3780SDimitry Andric 
6804a16efa3SDimitry Andric   case AMDGPU::SI_END_CF:
681b60736ecSDimitry Andric     SplitBB = emitEndCf(MI);
6824a16efa3SDimitry Andric     break;
6834a16efa3SDimitry Andric 
684cfca06d7SDimitry Andric   default:
685cfca06d7SDimitry Andric     assert(false && "Attempt to process unsupported instruction");
686cfca06d7SDimitry Andric     break;
687cfca06d7SDimitry Andric   }
688cfca06d7SDimitry Andric 
689cfca06d7SDimitry Andric   MachineBasicBlock::iterator Next;
690cfca06d7SDimitry Andric   for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
691cfca06d7SDimitry Andric     Next = std::next(I);
692cfca06d7SDimitry Andric     MachineInstr &MaskMI = *I;
693cfca06d7SDimitry Andric     switch (MaskMI.getOpcode()) {
694b915e9e0SDimitry Andric     case AMDGPU::S_AND_B64:
695b915e9e0SDimitry Andric     case AMDGPU::S_OR_B64:
696e6d15924SDimitry Andric     case AMDGPU::S_AND_B32:
697e6d15924SDimitry Andric     case AMDGPU::S_OR_B32:
698b915e9e0SDimitry Andric       // Cleanup bit manipulations on exec mask
699cfca06d7SDimitry Andric       combineMasks(MaskMI);
700cfca06d7SDimitry Andric       break;
701cfca06d7SDimitry Andric     default:
702cfca06d7SDimitry Andric       I = MBB.end();
703cfca06d7SDimitry Andric       break;
704cfca06d7SDimitry Andric     }
705cfca06d7SDimitry Andric   }
706b60736ecSDimitry Andric 
707b60736ecSDimitry Andric   return SplitBB;
708b60736ecSDimitry Andric }
709b60736ecSDimitry Andric 
removeMBBifRedundant(MachineBasicBlock & MBB)710b60736ecSDimitry Andric bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &MBB) {
711b60736ecSDimitry Andric   for (auto &I : MBB.instrs()) {
712b60736ecSDimitry Andric     if (!I.isDebugInstr() && !I.isUnconditionalBranch())
713b60736ecSDimitry Andric       return false;
714b60736ecSDimitry Andric   }
715b60736ecSDimitry Andric 
716b60736ecSDimitry Andric   assert(MBB.succ_size() == 1 && "MBB has more than one successor");
717b60736ecSDimitry Andric 
718b60736ecSDimitry Andric   MachineBasicBlock *Succ = *MBB.succ_begin();
719b60736ecSDimitry Andric   MachineBasicBlock *FallThrough = nullptr;
720b60736ecSDimitry Andric 
721b60736ecSDimitry Andric   while (!MBB.predecessors().empty()) {
722b60736ecSDimitry Andric     MachineBasicBlock *P = *MBB.pred_begin();
723b1c73532SDimitry Andric     if (P->getFallThrough(false) == &MBB)
724b60736ecSDimitry Andric       FallThrough = P;
725b60736ecSDimitry Andric     P->ReplaceUsesOfBlockWith(&MBB, Succ);
726b60736ecSDimitry Andric   }
727b60736ecSDimitry Andric   MBB.removeSuccessor(Succ);
728b60736ecSDimitry Andric   if (LIS) {
729b60736ecSDimitry Andric     for (auto &I : MBB.instrs())
730b60736ecSDimitry Andric       LIS->RemoveMachineInstrFromMaps(I);
731b60736ecSDimitry Andric   }
732c0981da4SDimitry Andric   if (MDT) {
733c0981da4SDimitry Andric     // If Succ, the single successor of MBB, is dominated by MBB, MDT needs
734c0981da4SDimitry Andric     // updating by changing Succ's idom to the one of MBB; otherwise, MBB must
735c0981da4SDimitry Andric     // be a leaf node in MDT and could be erased directly.
736c0981da4SDimitry Andric     if (MDT->dominates(&MBB, Succ))
737c0981da4SDimitry Andric       MDT->changeImmediateDominator(MDT->getNode(Succ),
738c0981da4SDimitry Andric                                     MDT->getNode(&MBB)->getIDom());
739c0981da4SDimitry Andric     MDT->eraseNode(&MBB);
740c0981da4SDimitry Andric   }
741b60736ecSDimitry Andric   MBB.clear();
742b60736ecSDimitry Andric   MBB.eraseFromParent();
743b60736ecSDimitry Andric   if (FallThrough && !FallThrough->isLayoutSuccessor(Succ)) {
744b1c73532SDimitry Andric     // Note: we cannot update block layout and preserve live intervals;
745b1c73532SDimitry Andric     // hence we must insert a branch.
746b1c73532SDimitry Andric     MachineInstr *BranchMI = BuildMI(*FallThrough, FallThrough->end(),
747b60736ecSDimitry Andric             FallThrough->findBranchDebugLoc(), TII->get(AMDGPU::S_BRANCH))
748b60736ecSDimitry Andric         .addMBB(Succ);
749b1c73532SDimitry Andric     if (LIS)
750b1c73532SDimitry Andric       LIS->InsertMachineInstrInMaps(*BranchMI);
751b60736ecSDimitry Andric   }
752b60736ecSDimitry Andric 
753b60736ecSDimitry Andric   return true;
754cfca06d7SDimitry Andric }
755cfca06d7SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)756cfca06d7SDimitry Andric bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) {
757cfca06d7SDimitry Andric   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
758cfca06d7SDimitry Andric   TII = ST.getInstrInfo();
759cfca06d7SDimitry Andric   TRI = &TII->getRegisterInfo();
760b1c73532SDimitry Andric   EnableOptimizeEndCf = RemoveRedundantEndcf &&
761b1c73532SDimitry Andric                         MF.getTarget().getOptLevel() > CodeGenOptLevel::None;
762cfca06d7SDimitry Andric 
763cfca06d7SDimitry Andric   // This doesn't actually need LiveIntervals, but we can preserve them.
764ac9a064cSDimitry Andric   auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
765ac9a064cSDimitry Andric   LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
766c0981da4SDimitry Andric   // This doesn't actually need LiveVariables, but we can preserve them.
767ac9a064cSDimitry Andric   auto *LVWrapper = getAnalysisIfAvailable<LiveVariablesWrapperPass>();
768ac9a064cSDimitry Andric   LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
769ac9a064cSDimitry Andric   auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
770ac9a064cSDimitry Andric   MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
771cfca06d7SDimitry Andric   MRI = &MF.getRegInfo();
772cfca06d7SDimitry Andric   BoolRC = TRI->getBoolRC();
773cfca06d7SDimitry Andric 
774cfca06d7SDimitry Andric   if (ST.isWave32()) {
775cfca06d7SDimitry Andric     AndOpc = AMDGPU::S_AND_B32;
776cfca06d7SDimitry Andric     OrOpc = AMDGPU::S_OR_B32;
777cfca06d7SDimitry Andric     XorOpc = AMDGPU::S_XOR_B32;
778cfca06d7SDimitry Andric     MovTermOpc = AMDGPU::S_MOV_B32_term;
779cfca06d7SDimitry Andric     Andn2TermOpc = AMDGPU::S_ANDN2_B32_term;
780cfca06d7SDimitry Andric     XorTermrOpc = AMDGPU::S_XOR_B32_term;
781b60736ecSDimitry Andric     OrTermrOpc = AMDGPU::S_OR_B32_term;
782cfca06d7SDimitry Andric     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B32;
783cfca06d7SDimitry Andric     Exec = AMDGPU::EXEC_LO;
784cfca06d7SDimitry Andric   } else {
785cfca06d7SDimitry Andric     AndOpc = AMDGPU::S_AND_B64;
786cfca06d7SDimitry Andric     OrOpc = AMDGPU::S_OR_B64;
787cfca06d7SDimitry Andric     XorOpc = AMDGPU::S_XOR_B64;
788cfca06d7SDimitry Andric     MovTermOpc = AMDGPU::S_MOV_B64_term;
789cfca06d7SDimitry Andric     Andn2TermOpc = AMDGPU::S_ANDN2_B64_term;
790cfca06d7SDimitry Andric     XorTermrOpc = AMDGPU::S_XOR_B64_term;
791b60736ecSDimitry Andric     OrTermrOpc = AMDGPU::S_OR_B64_term;
792cfca06d7SDimitry Andric     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B64;
793cfca06d7SDimitry Andric     Exec = AMDGPU::EXEC;
794cfca06d7SDimitry Andric   }
795cfca06d7SDimitry Andric 
796344a3780SDimitry Andric   // Compute set of blocks with kills
797344a3780SDimitry Andric   const bool CanDemote =
798344a3780SDimitry Andric       MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
799344a3780SDimitry Andric   for (auto &MBB : MF) {
800344a3780SDimitry Andric     bool IsKillBlock = false;
801344a3780SDimitry Andric     for (auto &Term : MBB.terminators()) {
802344a3780SDimitry Andric       if (TII->isKillTerminator(Term.getOpcode())) {
803344a3780SDimitry Andric         KillBlocks.insert(&MBB);
804344a3780SDimitry Andric         IsKillBlock = true;
805344a3780SDimitry Andric         break;
806344a3780SDimitry Andric       }
807344a3780SDimitry Andric     }
808344a3780SDimitry Andric     if (CanDemote && !IsKillBlock) {
809344a3780SDimitry Andric       for (auto &MI : MBB) {
810344a3780SDimitry Andric         if (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1) {
811344a3780SDimitry Andric           KillBlocks.insert(&MBB);
812344a3780SDimitry Andric           break;
813344a3780SDimitry Andric         }
814344a3780SDimitry Andric       }
815344a3780SDimitry Andric     }
816344a3780SDimitry Andric   }
817cfca06d7SDimitry Andric 
818145449b1SDimitry Andric   bool Changed = false;
819cfca06d7SDimitry Andric   MachineFunction::iterator NextBB;
820b60736ecSDimitry Andric   for (MachineFunction::iterator BI = MF.begin();
821b60736ecSDimitry Andric        BI != MF.end(); BI = NextBB) {
822cfca06d7SDimitry Andric     NextBB = std::next(BI);
823b60736ecSDimitry Andric     MachineBasicBlock *MBB = &*BI;
824cfca06d7SDimitry Andric 
825b60736ecSDimitry Andric     MachineBasicBlock::iterator I, E, Next;
826b60736ecSDimitry Andric     E = MBB->end();
827b60736ecSDimitry Andric     for (I = MBB->begin(); I != E; I = Next) {
828cfca06d7SDimitry Andric       Next = std::next(I);
829cfca06d7SDimitry Andric       MachineInstr &MI = *I;
830b60736ecSDimitry Andric       MachineBasicBlock *SplitMBB = MBB;
831cfca06d7SDimitry Andric 
832cfca06d7SDimitry Andric       switch (MI.getOpcode()) {
833cfca06d7SDimitry Andric       case AMDGPU::SI_IF:
834cfca06d7SDimitry Andric       case AMDGPU::SI_ELSE:
835cfca06d7SDimitry Andric       case AMDGPU::SI_IF_BREAK:
836344a3780SDimitry Andric       case AMDGPU::SI_WATERFALL_LOOP:
837cfca06d7SDimitry Andric       case AMDGPU::SI_LOOP:
838cfca06d7SDimitry Andric       case AMDGPU::SI_END_CF:
839b60736ecSDimitry Andric         SplitMBB = process(MI);
840145449b1SDimitry Andric         Changed = true;
841b60736ecSDimitry Andric         break;
842cfca06d7SDimitry Andric       }
843b60736ecSDimitry Andric 
844b60736ecSDimitry Andric       if (SplitMBB != MBB) {
845b60736ecSDimitry Andric         MBB = Next->getParent();
846b60736ecSDimitry Andric         E = MBB->end();
847b60736ecSDimitry Andric       }
848cfca06d7SDimitry Andric     }
84901095a5dSDimitry Andric   }
85001095a5dSDimitry Andric 
851cfca06d7SDimitry Andric   optimizeEndCf();
852cfca06d7SDimitry Andric 
853b1c73532SDimitry Andric   if (LIS) {
854b1c73532SDimitry Andric     for (Register Reg : RecomputeRegs) {
855b1c73532SDimitry Andric       LIS->removeInterval(Reg);
856b1c73532SDimitry Andric       LIS->createAndComputeVirtRegInterval(Reg);
857b1c73532SDimitry Andric     }
858b1c73532SDimitry Andric   }
859b1c73532SDimitry Andric 
860b1c73532SDimitry Andric   RecomputeRegs.clear();
861cfca06d7SDimitry Andric   LoweredEndCf.clear();
862cfca06d7SDimitry Andric   LoweredIf.clear();
863344a3780SDimitry Andric   KillBlocks.clear();
86467c32a98SDimitry Andric 
865145449b1SDimitry Andric   return Changed;
8664a16efa3SDimitry Andric }
867