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