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