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