xref: /llvm-project/llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp (revision 0576f436e577cede25810729aef236ec8c649446)
1 //===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===//
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 lowers the pseudo control flow instructions to real
11 /// machine instructions.
12 ///
13 /// All control flow is handled using predicated instructions and
14 /// a predicate stack.  Each Scalar ALU controls the operations of 64 Vector
15 /// ALUs.  The Scalar ALU can update the predicate for any of the Vector ALUs
16 /// by writting to the 64-bit EXEC register (each bit corresponds to a
17 /// single vector ALU).  Typically, for predicates, a vector ALU will write
18 /// to its bit of the VCC register (like EXEC VCC is 64-bits, one for each
19 /// Vector ALU) and then the ScalarALU will AND the VCC register with the
20 /// EXEC to update the predicates.
21 ///
22 /// For example:
23 /// %vcc = V_CMP_GT_F32 %vgpr1, %vgpr2
24 /// %sgpr0 = SI_IF %vcc
25 ///   %vgpr0 = V_ADD_F32 %vgpr0, %vgpr0
26 /// %sgpr0 = SI_ELSE %sgpr0
27 ///   %vgpr0 = V_SUB_F32 %vgpr0, %vgpr0
28 /// SI_END_CF %sgpr0
29 ///
30 /// becomes:
31 ///
32 /// %sgpr0 = S_AND_SAVEEXEC_B64 %vcc  // Save and update the exec mask
33 /// %sgpr0 = S_XOR_B64 %sgpr0, %exec  // Clear live bits from saved exec mask
34 /// S_CBRANCH_EXECZ label0            // This instruction is an optional
35 ///                                   // optimization which allows us to
36 ///                                   // branch if all the bits of
37 ///                                   // EXEC are zero.
38 /// %vgpr0 = V_ADD_F32 %vgpr0, %vgpr0 // Do the IF block of the branch
39 ///
40 /// label0:
41 /// %sgpr0 = S_OR_SAVEEXEC_B64 %sgpr0  // Restore the exec mask for the Then block
42 /// %exec = S_XOR_B64 %sgpr0, %exec    // Update the exec mask
43 /// S_BRANCH_EXECZ label1              // Use our branch optimization
44 ///                                    // instruction again.
45 /// %vgpr0 = V_SUB_F32 %vgpr0, %vgpr   // Do the THEN block
46 /// label1:
47 /// %exec = S_OR_B64 %exec, %sgpr0     // Re-enable saved exec mask bits
48 //===----------------------------------------------------------------------===//
49 
50 #include "AMDGPU.h"
51 #include "AMDGPUSubtarget.h"
52 #include "SIInstrInfo.h"
53 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
54 #include "llvm/ADT/SetVector.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringRef.h"
58 #include "llvm/CodeGen/LiveIntervals.h"
59 #include "llvm/CodeGen/MachineBasicBlock.h"
60 #include "llvm/CodeGen/MachineFunction.h"
61 #include "llvm/CodeGen/MachineFunctionPass.h"
62 #include "llvm/CodeGen/MachineInstr.h"
63 #include "llvm/CodeGen/MachineInstrBuilder.h"
64 #include "llvm/CodeGen/MachineOperand.h"
65 #include "llvm/CodeGen/MachineRegisterInfo.h"
66 #include "llvm/CodeGen/Passes.h"
67 #include "llvm/CodeGen/SlotIndexes.h"
68 #include "llvm/CodeGen/TargetRegisterInfo.h"
69 #include "llvm/MC/MCRegisterInfo.h"
70 #include "llvm/Pass.h"
71 #include <cassert>
72 #include <iterator>
73 
74 using namespace llvm;
75 
76 #define DEBUG_TYPE "si-lower-control-flow"
77 
78 static cl::opt<bool>
79 RemoveRedundantEndcf("amdgpu-remove-redundant-endcf",
80     cl::init(true), cl::ReallyHidden);
81 
82 namespace {
83 
84 class SILowerControlFlow : public MachineFunctionPass {
85 private:
86   const SIRegisterInfo *TRI = nullptr;
87   const SIInstrInfo *TII = nullptr;
88   LiveIntervals *LIS = nullptr;
89   MachineRegisterInfo *MRI = nullptr;
90   SetVector<MachineInstr*> LoweredEndCf;
91   DenseSet<Register> LoweredIf;
92   SmallSet<MachineInstr *, 16> NeedsKillCleanup;
93 
94   const TargetRegisterClass *BoolRC = nullptr;
95   bool InsertKillCleanups;
96   unsigned AndOpc;
97   unsigned OrOpc;
98   unsigned XorOpc;
99   unsigned MovTermOpc;
100   unsigned Andn2TermOpc;
101   unsigned XorTermrOpc;
102   unsigned OrTermrOpc;
103   unsigned OrSaveExecOpc;
104   unsigned Exec;
105 
106   void emitIf(MachineInstr &MI);
107   void emitElse(MachineInstr &MI);
108   void emitIfBreak(MachineInstr &MI);
109   void emitLoop(MachineInstr &MI);
110 
111   MachineBasicBlock *splitBlock(MachineInstr &MI, MachineBasicBlock *BB,
112                                 LiveIntervals *LIS);
113   MachineBasicBlock *emitEndCf(MachineInstr &MI);
114 
115   void findMaskOperands(MachineInstr &MI, unsigned OpNo,
116                         SmallVectorImpl<MachineOperand> &Src) const;
117 
118   void combineMasks(MachineInstr &MI);
119 
120   bool removeMBBifRedundant(MachineBasicBlock &MBB);
121 
122   MachineBasicBlock *process(MachineInstr &MI);
123 
124   // Skip to the next instruction, ignoring debug instructions, and trivial
125   // block boundaries (blocks that have one (typically fallthrough) successor,
126   // and the successor has one predecessor.
127   MachineBasicBlock::iterator
128   skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
129                                  MachineBasicBlock::iterator It) const;
130 
131   /// Find the insertion point for a new conditional branch.
132   MachineBasicBlock::iterator
133   skipToUncondBrOrEnd(MachineBasicBlock &MBB,
134                       MachineBasicBlock::iterator I) const {
135     assert(I->isTerminator());
136 
137     // FIXME: What if we had multiple pre-existing conditional branches?
138     MachineBasicBlock::iterator End = MBB.end();
139     while (I != End && !I->isUnconditionalBranch())
140       ++I;
141     return I;
142   }
143 
144   // Remove redundant SI_END_CF instructions.
145   void optimizeEndCf();
146 
147 public:
148   static char ID;
149 
150   SILowerControlFlow() : MachineFunctionPass(ID) {}
151 
152   bool runOnMachineFunction(MachineFunction &MF) override;
153 
154   StringRef getPassName() const override {
155     return "SI Lower control flow pseudo instructions";
156   }
157 
158   void getAnalysisUsage(AnalysisUsage &AU) const override {
159     // Should preserve the same set that TwoAddressInstructions does.
160     AU.addPreserved<SlotIndexes>();
161     AU.addPreserved<LiveIntervals>();
162     AU.addPreservedID(LiveVariablesID);
163     MachineFunctionPass::getAnalysisUsage(AU);
164   }
165 };
166 
167 } // end anonymous namespace
168 
169 char SILowerControlFlow::ID = 0;
170 
171 INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE,
172                "SI lower control flow", false, false)
173 
174 static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
175   MachineOperand &ImpDefSCC = MI.getOperand(3);
176   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
177 
178   ImpDefSCC.setIsDead(IsDead);
179 }
180 
181 char &llvm::SILowerControlFlowID = SILowerControlFlow::ID;
182 
183 static bool hasKill(const MachineBasicBlock *Begin,
184                     const MachineBasicBlock *End, const SIInstrInfo *TII) {
185   DenseSet<const MachineBasicBlock*> Visited;
186   SmallVector<MachineBasicBlock *, 4> Worklist(Begin->succ_begin(),
187                                                Begin->succ_end());
188 
189   while (!Worklist.empty()) {
190     MachineBasicBlock *MBB = Worklist.pop_back_val();
191 
192     if (MBB == End || !Visited.insert(MBB).second)
193       continue;
194     for (auto &Term : MBB->terminators())
195       if (TII->isKillTerminator(Term.getOpcode()))
196         return true;
197 
198     Worklist.append(MBB->succ_begin(), MBB->succ_end());
199   }
200 
201   return false;
202 }
203 
204 static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
205   Register SaveExecReg = MI.getOperand(0).getReg();
206   auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
207 
208   if (U == MRI->use_instr_nodbg_end() ||
209       std::next(U) != MRI->use_instr_nodbg_end() ||
210       U->getOpcode() != AMDGPU::SI_END_CF)
211     return false;
212 
213   return true;
214 }
215 
216 void SILowerControlFlow::emitIf(MachineInstr &MI) {
217   MachineBasicBlock &MBB = *MI.getParent();
218   const DebugLoc &DL = MI.getDebugLoc();
219   MachineBasicBlock::iterator I(&MI);
220   Register SaveExecReg = MI.getOperand(0).getReg();
221   MachineOperand& Cond = MI.getOperand(1);
222   assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
223 
224   MachineOperand &ImpDefSCC = MI.getOperand(4);
225   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
226 
227   // If there is only one use of save exec register and that use is SI_END_CF,
228   // we can optimize SI_IF by returning the full saved exec mask instead of
229   // just cleared bits.
230   bool SimpleIf = isSimpleIf(MI, MRI);
231 
232   if (InsertKillCleanups) {
233     // Check for SI_KILL_*_TERMINATOR on full path of control flow and
234     // flag the associated SI_END_CF for insertion of a kill cleanup.
235     auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
236     while (UseMI->getOpcode() != AMDGPU::SI_END_CF) {
237       assert(std::next(UseMI) == MRI->use_instr_nodbg_end());
238       assert(UseMI->getOpcode() == AMDGPU::SI_ELSE);
239       MachineOperand &NextExec = UseMI->getOperand(0);
240       Register NextExecReg = NextExec.getReg();
241       if (NextExec.isDead()) {
242         assert(!SimpleIf);
243         break;
244       }
245       UseMI = MRI->use_instr_nodbg_begin(NextExecReg);
246     }
247     if (UseMI->getOpcode() == AMDGPU::SI_END_CF) {
248       if (hasKill(MI.getParent(), UseMI->getParent(), TII)) {
249         NeedsKillCleanup.insert(&*UseMI);
250         SimpleIf = false;
251       }
252     }
253   } else if (SimpleIf) {
254     // Check for SI_KILL_*_TERMINATOR on path from if to endif.
255     // if there is any such terminator simplifications are not safe.
256     auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
257     SimpleIf = !hasKill(MI.getParent(), UseMI->getParent(), TII);
258   }
259 
260   // Add an implicit def of exec to discourage scheduling VALU after this which
261   // will interfere with trying to form s_and_saveexec_b64 later.
262   Register CopyReg = SimpleIf ? SaveExecReg
263                        : MRI->createVirtualRegister(BoolRC);
264   MachineInstr *CopyExec =
265     BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
266     .addReg(Exec)
267     .addReg(Exec, RegState::ImplicitDefine);
268   LoweredIf.insert(CopyReg);
269 
270   Register Tmp = MRI->createVirtualRegister(BoolRC);
271 
272   MachineInstr *And =
273     BuildMI(MBB, I, DL, TII->get(AndOpc), Tmp)
274     .addReg(CopyReg)
275     .add(Cond);
276 
277   setImpSCCDefDead(*And, true);
278 
279   MachineInstr *Xor = nullptr;
280   if (!SimpleIf) {
281     Xor =
282       BuildMI(MBB, I, DL, TII->get(XorOpc), SaveExecReg)
283       .addReg(Tmp)
284       .addReg(CopyReg);
285     setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
286   }
287 
288   // Use a copy that is a terminator to get correct spill code placement it with
289   // fast regalloc.
290   MachineInstr *SetExec =
291     BuildMI(MBB, I, DL, TII->get(MovTermOpc), Exec)
292     .addReg(Tmp, RegState::Kill);
293 
294   // Skip ahead to the unconditional branch in case there are other terminators
295   // present.
296   I = skipToUncondBrOrEnd(MBB, I);
297 
298   // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
299   // during SIRemoveShortExecBranches.
300   MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
301                             .add(MI.getOperand(2));
302 
303   if (!LIS) {
304     MI.eraseFromParent();
305     return;
306   }
307 
308   LIS->InsertMachineInstrInMaps(*CopyExec);
309 
310   // Replace with and so we don't need to fix the live interval for condition
311   // register.
312   LIS->ReplaceMachineInstrInMaps(MI, *And);
313 
314   if (!SimpleIf)
315     LIS->InsertMachineInstrInMaps(*Xor);
316   LIS->InsertMachineInstrInMaps(*SetExec);
317   LIS->InsertMachineInstrInMaps(*NewBr);
318 
319   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
320   MI.eraseFromParent();
321 
322   // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
323   // hard to add another def here but I'm not sure how to correctly update the
324   // valno.
325   LIS->removeInterval(SaveExecReg);
326   LIS->createAndComputeVirtRegInterval(SaveExecReg);
327   LIS->createAndComputeVirtRegInterval(Tmp);
328   if (!SimpleIf)
329     LIS->createAndComputeVirtRegInterval(CopyReg);
330 }
331 
332 void SILowerControlFlow::emitElse(MachineInstr &MI) {
333   MachineBasicBlock &MBB = *MI.getParent();
334   const DebugLoc &DL = MI.getDebugLoc();
335 
336   Register DstReg = MI.getOperand(0).getReg();
337 
338   bool ExecModified = MI.getOperand(3).getImm() != 0;
339   MachineBasicBlock::iterator Start = MBB.begin();
340 
341   // This must be inserted before phis and any spill code inserted before the
342   // else.
343   Register SaveReg = ExecModified ?
344     MRI->createVirtualRegister(BoolRC) : DstReg;
345   MachineInstr *OrSaveExec =
346     BuildMI(MBB, Start, DL, TII->get(OrSaveExecOpc), SaveReg)
347     .add(MI.getOperand(1)); // Saved EXEC
348 
349   MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
350 
351   MachineBasicBlock::iterator ElsePt(MI);
352 
353   if (ExecModified) {
354     MachineInstr *And =
355       BuildMI(MBB, ElsePt, DL, TII->get(AndOpc), DstReg)
356       .addReg(Exec)
357       .addReg(SaveReg);
358 
359     if (LIS)
360       LIS->InsertMachineInstrInMaps(*And);
361   }
362 
363   MachineInstr *Xor =
364     BuildMI(MBB, ElsePt, DL, TII->get(XorTermrOpc), Exec)
365     .addReg(Exec)
366     .addReg(DstReg);
367 
368   // Skip ahead to the unconditional branch in case there are other terminators
369   // present.
370   ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
371 
372   MachineInstr *Branch =
373       BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
374           .addMBB(DestBB);
375 
376   if (!LIS) {
377     MI.eraseFromParent();
378     return;
379   }
380 
381   LIS->RemoveMachineInstrFromMaps(MI);
382   MI.eraseFromParent();
383 
384   LIS->InsertMachineInstrInMaps(*OrSaveExec);
385 
386   LIS->InsertMachineInstrInMaps(*Xor);
387   LIS->InsertMachineInstrInMaps(*Branch);
388 
389   LIS->removeInterval(DstReg);
390   LIS->createAndComputeVirtRegInterval(DstReg);
391   if (ExecModified)
392     LIS->createAndComputeVirtRegInterval(SaveReg);
393 
394   // Let this be recomputed.
395   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
396 }
397 
398 void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
399   MachineBasicBlock &MBB = *MI.getParent();
400   const DebugLoc &DL = MI.getDebugLoc();
401   auto Dst = MI.getOperand(0).getReg();
402 
403   // Skip ANDing with exec if the break condition is already masked by exec
404   // because it is a V_CMP in the same basic block. (We know the break
405   // condition operand was an i1 in IR, so if it is a VALU instruction it must
406   // be one with a carry-out.)
407   bool SkipAnding = false;
408   if (MI.getOperand(1).isReg()) {
409     if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
410       SkipAnding = Def->getParent() == MI.getParent()
411           && SIInstrInfo::isVALU(*Def);
412     }
413   }
414 
415   // AND the break condition operand with exec, then OR that into the "loop
416   // exit" mask.
417   MachineInstr *And = nullptr, *Or = nullptr;
418   if (!SkipAnding) {
419     Register AndReg = MRI->createVirtualRegister(BoolRC);
420     And = BuildMI(MBB, &MI, DL, TII->get(AndOpc), AndReg)
421              .addReg(Exec)
422              .add(MI.getOperand(1));
423     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
424              .addReg(AndReg)
425              .add(MI.getOperand(2));
426     if (LIS)
427       LIS->createAndComputeVirtRegInterval(AndReg);
428   } else
429     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
430              .add(MI.getOperand(1))
431              .add(MI.getOperand(2));
432 
433   if (LIS) {
434     if (And)
435       LIS->InsertMachineInstrInMaps(*And);
436     LIS->ReplaceMachineInstrInMaps(MI, *Or);
437   }
438 
439   MI.eraseFromParent();
440 }
441 
442 void SILowerControlFlow::emitLoop(MachineInstr &MI) {
443   MachineBasicBlock &MBB = *MI.getParent();
444   const DebugLoc &DL = MI.getDebugLoc();
445 
446   MachineInstr *AndN2 =
447       BuildMI(MBB, &MI, DL, TII->get(Andn2TermOpc), Exec)
448           .addReg(Exec)
449           .add(MI.getOperand(0));
450 
451   auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
452   MachineInstr *Branch =
453       BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
454           .add(MI.getOperand(1));
455 
456   if (LIS) {
457     LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
458     LIS->InsertMachineInstrInMaps(*Branch);
459   }
460 
461   MI.eraseFromParent();
462 }
463 
464 MachineBasicBlock::iterator
465 SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
466   MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
467 
468   SmallSet<const MachineBasicBlock *, 4> Visited;
469   MachineBasicBlock *B = &MBB;
470   do {
471     if (!Visited.insert(B).second)
472       return MBB.end();
473 
474     auto E = B->end();
475     for ( ; It != E; ++It) {
476       if (It->getOpcode() == AMDGPU::SI_KILL_CLEANUP)
477         continue;
478       if (TII->mayReadEXEC(*MRI, *It))
479         break;
480     }
481 
482     if (It != E)
483       return It;
484 
485     if (B->succ_size() != 1)
486       return MBB.end();
487 
488     // If there is one trivial successor, advance to the next block.
489     MachineBasicBlock *Succ = *B->succ_begin();
490 
491     It = Succ->begin();
492     B = Succ;
493   } while (true);
494 }
495 
496 MachineBasicBlock *SILowerControlFlow::splitBlock(MachineInstr &MI,
497                                                   MachineBasicBlock *BB,
498                                                   LiveIntervals *LIS) {
499   MachineBasicBlock::iterator SplitPoint(&MI);
500   ++SplitPoint;
501 
502   if (SplitPoint == BB->end()) {
503     // Don't bother with a new block.
504     return BB;
505   }
506 
507   // Make sure we add any physregs we define in the block as liveins to the new
508   // block.
509   LivePhysRegs LiveRegs(*TRI);
510   LiveRegs.addLiveOuts(*BB);
511   for (auto I = BB->rbegin(), E = SplitPoint.getReverse(); I != E; ++I)
512     LiveRegs.stepBackward(*I);
513 
514   MachineFunction *MF = BB->getParent();
515   MachineBasicBlock *SplitBB
516     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
517 
518   MF->insert(++MachineFunction::iterator(BB), SplitBB);
519   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
520 
521   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
522   BB->addSuccessor(SplitBB);
523 
524   addLiveIns(*SplitBB, LiveRegs);
525 
526   if (LIS)
527     LIS->insertMBBInMaps(SplitBB, &MI);
528 
529   return SplitBB;
530 }
531 
532 MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &MI) {
533   MachineBasicBlock &MBB = *MI.getParent();
534   const DebugLoc &DL = MI.getDebugLoc();
535 
536   MachineBasicBlock::iterator InsPt = MBB.begin();
537 
538   // If we have instructions that aren't prolog instructions, split the block
539   // and emit a terminator instruction. This ensures correct spill placement.
540   // FIXME: We should unconditionally split the block here.
541   bool NeedBlockSplit = false;
542   Register DataReg = MI.getOperand(0).getReg();
543   for (MachineBasicBlock::iterator I = InsPt, E = MI.getIterator();
544        I != E; ++I) {
545     if (I->modifiesRegister(DataReg, TRI)) {
546       NeedBlockSplit = true;
547       break;
548     }
549   }
550 
551   unsigned Opcode = OrOpc;
552   MachineBasicBlock *SplitBB = &MBB;
553   if (NeedBlockSplit) {
554     SplitBB = splitBlock(MI, &MBB, LIS);
555     Opcode = OrTermrOpc;
556     InsPt = MI;
557   }
558 
559   MachineInstr *NewMI =
560     BuildMI(MBB, InsPt, DL, TII->get(Opcode), Exec)
561     .addReg(Exec)
562     .add(MI.getOperand(0));
563 
564   LoweredEndCf.insert(NewMI);
565 
566   // If this ends control flow which contains kills (as flagged in emitIf)
567   // then insert an SI_KILL_CLEANUP immediately following the exec mask
568   // manipulation.  This can be lowered to early termination if appropriate.
569   MachineInstr *CleanUpMI = nullptr;
570   if (NeedsKillCleanup.count(&MI))
571     CleanUpMI = BuildMI(MBB, InsPt, DL, TII->get(AMDGPU::SI_KILL_CLEANUP));
572 
573   if (LIS) {
574     LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
575     if (CleanUpMI)
576       LIS->InsertMachineInstrInMaps(*CleanUpMI);
577   }
578 
579   MI.eraseFromParent();
580 
581   if (LIS)
582     LIS->handleMove(*NewMI);
583   return SplitBB;
584 }
585 
586 // Returns replace operands for a logical operation, either single result
587 // for exec or two operands if source was another equivalent operation.
588 void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
589        SmallVectorImpl<MachineOperand> &Src) const {
590   MachineOperand &Op = MI.getOperand(OpNo);
591   if (!Op.isReg() || !Op.getReg().isVirtual()) {
592     Src.push_back(Op);
593     return;
594   }
595 
596   MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
597   if (!Def || Def->getParent() != MI.getParent() ||
598       !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
599     return;
600 
601   // Make sure we do not modify exec between def and use.
602   // A copy with implcitly defined exec inserted earlier is an exclusion, it
603   // does not really modify exec.
604   for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
605     if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
606         !(I->isCopy() && I->getOperand(0).getReg() != Exec))
607       return;
608 
609   for (const auto &SrcOp : Def->explicit_operands())
610     if (SrcOp.isReg() && SrcOp.isUse() &&
611         (SrcOp.getReg().isVirtual() || SrcOp.getReg() == Exec))
612       Src.push_back(SrcOp);
613 }
614 
615 // Search and combine pairs of equivalent instructions, like
616 // S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
617 // S_OR_B64  x, (S_OR_B64  x, y) => S_OR_B64  x, y
618 // One of the operands is exec mask.
619 void SILowerControlFlow::combineMasks(MachineInstr &MI) {
620   assert(MI.getNumExplicitOperands() == 3);
621   SmallVector<MachineOperand, 4> Ops;
622   unsigned OpToReplace = 1;
623   findMaskOperands(MI, 1, Ops);
624   if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
625   findMaskOperands(MI, 2, Ops);
626   if (Ops.size() != 3) return;
627 
628   unsigned UniqueOpndIdx;
629   if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
630   else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
631   else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
632   else return;
633 
634   Register Reg = MI.getOperand(OpToReplace).getReg();
635   MI.RemoveOperand(OpToReplace);
636   MI.addOperand(Ops[UniqueOpndIdx]);
637   if (MRI->use_empty(Reg))
638     MRI->getUniqueVRegDef(Reg)->eraseFromParent();
639 }
640 
641 void SILowerControlFlow::optimizeEndCf() {
642   // If the only instruction immediately following this END_CF is an another
643   // END_CF in the only successor we can avoid emitting exec mask restore here.
644   if (!RemoveRedundantEndcf)
645     return;
646 
647   for (MachineInstr *MI : LoweredEndCf) {
648     MachineBasicBlock &MBB = *MI->getParent();
649     auto Next =
650       skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
651     if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
652       continue;
653     // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
654     // If that belongs to SI_ELSE then saved mask has an inverted value.
655     Register SavedExec
656       = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
657     assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
658 
659     const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
660     if (Def && LoweredIf.count(SavedExec)) {
661       LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
662       if (LIS)
663         LIS->RemoveMachineInstrFromMaps(*MI);
664       MI->eraseFromParent();
665       removeMBBifRedundant(MBB);
666     }
667   }
668 }
669 
670 MachineBasicBlock *SILowerControlFlow::process(MachineInstr &MI) {
671   MachineBasicBlock &MBB = *MI.getParent();
672   MachineBasicBlock::iterator I(MI);
673   MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
674 
675   MachineBasicBlock *SplitBB = &MBB;
676 
677   switch (MI.getOpcode()) {
678   case AMDGPU::SI_IF:
679     emitIf(MI);
680     break;
681 
682   case AMDGPU::SI_ELSE:
683     emitElse(MI);
684     break;
685 
686   case AMDGPU::SI_IF_BREAK:
687     emitIfBreak(MI);
688     break;
689 
690   case AMDGPU::SI_LOOP:
691     emitLoop(MI);
692     break;
693 
694   case AMDGPU::SI_END_CF:
695     SplitBB = emitEndCf(MI);
696     break;
697 
698   default:
699     assert(false && "Attempt to process unsupported instruction");
700     break;
701   }
702 
703   MachineBasicBlock::iterator Next;
704   for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
705     Next = std::next(I);
706     MachineInstr &MaskMI = *I;
707     switch (MaskMI.getOpcode()) {
708     case AMDGPU::S_AND_B64:
709     case AMDGPU::S_OR_B64:
710     case AMDGPU::S_AND_B32:
711     case AMDGPU::S_OR_B32:
712       // Cleanup bit manipulations on exec mask
713       combineMasks(MaskMI);
714       break;
715     default:
716       I = MBB.end();
717       break;
718     }
719   }
720 
721   return SplitBB;
722 }
723 
724 bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &MBB) {
725   bool Redundant = true;
726   for (auto &I : MBB.instrs()) {
727     if (!I.isDebugInstr() && !I.isUnconditionalBranch())
728       Redundant = false;
729   }
730   if (Redundant) {
731     MachineBasicBlock *Succ = *MBB.succ_begin();
732     SmallVector<MachineBasicBlock *, 2> Preds(MBB.predecessors());
733     for (auto P : Preds) {
734       P->replaceSuccessor(&MBB, Succ);
735       MachineBasicBlock::iterator I(P->getFirstInstrTerminator());
736       while (I != P->end()) {
737         if (I->isBranch()) {
738           if (TII->getBranchDestBlock(*I) == &MBB) {
739             I->getOperand(0).setMBB(Succ);
740             break;
741           }
742         }
743         I++;
744       }
745       if (I == P->end()) {
746         MachineFunction *MF = P->getParent();
747         MachineFunction::iterator InsertPt =
748             P->getNextNode() ? MachineFunction::iterator(P->getNextNode())
749                              : MF->end();
750         MF->splice(InsertPt, Succ);
751       }
752     }
753     MBB.removeSuccessor(Succ);
754     if (LIS) {
755       for (auto &I : MBB.instrs())
756         LIS->RemoveMachineInstrFromMaps(I);
757     }
758     MBB.clear();
759     MBB.eraseFromParent();
760     return true;
761   }
762   return false;
763 }
764 
765 bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) {
766   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
767   TII = ST.getInstrInfo();
768   TRI = &TII->getRegisterInfo();
769 
770   // This doesn't actually need LiveIntervals, but we can preserve them.
771   LIS = getAnalysisIfAvailable<LiveIntervals>();
772   MRI = &MF.getRegInfo();
773   BoolRC = TRI->getBoolRC();
774   InsertKillCleanups =
775       MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
776 
777   if (ST.isWave32()) {
778     AndOpc = AMDGPU::S_AND_B32;
779     OrOpc = AMDGPU::S_OR_B32;
780     XorOpc = AMDGPU::S_XOR_B32;
781     MovTermOpc = AMDGPU::S_MOV_B32_term;
782     Andn2TermOpc = AMDGPU::S_ANDN2_B32_term;
783     XorTermrOpc = AMDGPU::S_XOR_B32_term;
784     OrTermrOpc = AMDGPU::S_OR_B32_term;
785     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B32;
786     Exec = AMDGPU::EXEC_LO;
787   } else {
788     AndOpc = AMDGPU::S_AND_B64;
789     OrOpc = AMDGPU::S_OR_B64;
790     XorOpc = AMDGPU::S_XOR_B64;
791     MovTermOpc = AMDGPU::S_MOV_B64_term;
792     Andn2TermOpc = AMDGPU::S_ANDN2_B64_term;
793     XorTermrOpc = AMDGPU::S_XOR_B64_term;
794     OrTermrOpc = AMDGPU::S_OR_B64_term;
795     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B64;
796     Exec = AMDGPU::EXEC;
797   }
798 
799   SmallVector<MachineInstr *, 32> Worklist;
800 
801   MachineFunction::iterator NextBB;
802   for (MachineFunction::iterator BI = MF.begin();
803        BI != MF.end(); BI = NextBB) {
804     NextBB = std::next(BI);
805     MachineBasicBlock *MBB = &*BI;
806 
807     MachineBasicBlock::iterator I, E, Next;
808     E = MBB->end();
809     for (I = MBB->begin(); I != E; I = Next) {
810       Next = std::next(I);
811       MachineInstr &MI = *I;
812       MachineBasicBlock *SplitMBB = MBB;
813 
814       switch (MI.getOpcode()) {
815       case AMDGPU::SI_IF:
816         SplitMBB = process(MI);
817         break;
818 
819       case AMDGPU::SI_ELSE:
820       case AMDGPU::SI_IF_BREAK:
821       case AMDGPU::SI_LOOP:
822       case AMDGPU::SI_END_CF:
823         // Only build worklist if SI_IF instructions must be processed first.
824         if (InsertKillCleanups)
825           Worklist.push_back(&MI);
826         else
827           SplitMBB = process(MI);
828         break;
829 
830       default:
831         break;
832       }
833 
834       if (SplitMBB != MBB) {
835         MBB = Next->getParent();
836         E = MBB->end();
837       }
838     }
839   }
840 
841   for (MachineInstr *MI : Worklist)
842     process(*MI);
843 
844   optimizeEndCf();
845 
846   LoweredEndCf.clear();
847   LoweredIf.clear();
848   NeedsKillCleanup.clear();
849 
850   return true;
851 }
852