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 %exec   // Restore the exec mask for the Then block
42 /// %exec = S_XOR_B64 %sgpr0, %exec    // Clear live bits from saved 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/SmallVector.h"
55 #include "llvm/ADT/StringRef.h"
56 #include "llvm/CodeGen/LiveIntervals.h"
57 #include "llvm/CodeGen/MachineBasicBlock.h"
58 #include "llvm/CodeGen/MachineFunction.h"
59 #include "llvm/CodeGen/MachineFunctionPass.h"
60 #include "llvm/CodeGen/MachineInstr.h"
61 #include "llvm/CodeGen/MachineInstrBuilder.h"
62 #include "llvm/CodeGen/MachineOperand.h"
63 #include "llvm/CodeGen/MachineRegisterInfo.h"
64 #include "llvm/CodeGen/Passes.h"
65 #include "llvm/CodeGen/SlotIndexes.h"
66 #include "llvm/CodeGen/TargetRegisterInfo.h"
67 #include "llvm/MC/MCRegisterInfo.h"
68 #include "llvm/Pass.h"
69 #include <cassert>
70 #include <iterator>
71 
72 using namespace llvm;
73 
74 #define DEBUG_TYPE "si-lower-control-flow"
75 
76 namespace {
77 
78 class SILowerControlFlow : public MachineFunctionPass {
79 private:
80   const SIRegisterInfo *TRI = nullptr;
81   const SIInstrInfo *TII = nullptr;
82   LiveIntervals *LIS = nullptr;
83   MachineRegisterInfo *MRI = nullptr;
84 
85   const TargetRegisterClass *BoolRC = nullptr;
86   unsigned AndOpc;
87   unsigned OrOpc;
88   unsigned XorOpc;
89   unsigned MovTermOpc;
90   unsigned Andn2TermOpc;
91   unsigned XorTermrOpc;
92   unsigned OrSaveExecOpc;
93   unsigned Exec;
94 
95   void emitIf(MachineInstr &MI);
96   void emitElse(MachineInstr &MI);
97   void emitIfBreak(MachineInstr &MI);
98   void emitLoop(MachineInstr &MI);
99   void emitEndCf(MachineInstr &MI);
100 
101   void findMaskOperands(MachineInstr &MI, unsigned OpNo,
102                         SmallVectorImpl<MachineOperand> &Src) const;
103 
104   void combineMasks(MachineInstr &MI);
105 
106 public:
107   static char ID;
108 
109   SILowerControlFlow() : MachineFunctionPass(ID) {}
110 
111   bool runOnMachineFunction(MachineFunction &MF) override;
112 
113   StringRef getPassName() const override {
114     return "SI Lower control flow pseudo instructions";
115   }
116 
117   void getAnalysisUsage(AnalysisUsage &AU) const override {
118     // Should preserve the same set that TwoAddressInstructions does.
119     AU.addPreserved<SlotIndexes>();
120     AU.addPreserved<LiveIntervals>();
121     AU.addPreservedID(LiveVariablesID);
122     AU.addPreservedID(MachineLoopInfoID);
123     AU.addPreservedID(MachineDominatorsID);
124     AU.setPreservesCFG();
125     MachineFunctionPass::getAnalysisUsage(AU);
126   }
127 };
128 
129 } // end anonymous namespace
130 
131 char SILowerControlFlow::ID = 0;
132 
133 INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE,
134                "SI lower control flow", false, false)
135 
136 static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
137   MachineOperand &ImpDefSCC = MI.getOperand(3);
138   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
139 
140   ImpDefSCC.setIsDead(IsDead);
141 }
142 
143 char &llvm::SILowerControlFlowID = SILowerControlFlow::ID;
144 
145 static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI,
146                        const SIInstrInfo *TII) {
147   Register SaveExecReg = MI.getOperand(0).getReg();
148   auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
149 
150   if (U == MRI->use_instr_nodbg_end() ||
151       std::next(U) != MRI->use_instr_nodbg_end() ||
152       U->getOpcode() != AMDGPU::SI_END_CF)
153     return false;
154 
155   // Check for SI_KILL_*_TERMINATOR on path from if to endif.
156   // if there is any such terminator simplififcations are not safe.
157   auto SMBB = MI.getParent();
158   auto EMBB = U->getParent();
159   DenseSet<const MachineBasicBlock*> Visited;
160   SmallVector<MachineBasicBlock*, 4> Worklist(SMBB->succ_begin(),
161                                               SMBB->succ_end());
162 
163   while (!Worklist.empty()) {
164     MachineBasicBlock *MBB = Worklist.pop_back_val();
165 
166     if (MBB == EMBB || !Visited.insert(MBB).second)
167       continue;
168     for(auto &Term : MBB->terminators())
169       if (TII->isKillTerminator(Term.getOpcode()))
170         return false;
171 
172     Worklist.append(MBB->succ_begin(), MBB->succ_end());
173   }
174 
175   return true;
176 }
177 
178 void SILowerControlFlow::emitIf(MachineInstr &MI) {
179   MachineBasicBlock &MBB = *MI.getParent();
180   const DebugLoc &DL = MI.getDebugLoc();
181   MachineBasicBlock::iterator I(&MI);
182   Register SaveExecReg = MI.getOperand(0).getReg();
183   MachineOperand& Cond = MI.getOperand(1);
184   assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
185 
186   MachineOperand &ImpDefSCC = MI.getOperand(4);
187   assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
188 
189   // If there is only one use of save exec register and that use is SI_END_CF,
190   // we can optimize SI_IF by returning the full saved exec mask instead of
191   // just cleared bits.
192   bool SimpleIf = isSimpleIf(MI, MRI, TII);
193 
194   // Add an implicit def of exec to discourage scheduling VALU after this which
195   // will interfere with trying to form s_and_saveexec_b64 later.
196   Register CopyReg = SimpleIf ? SaveExecReg
197                        : MRI->createVirtualRegister(BoolRC);
198   MachineInstr *CopyExec =
199     BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
200     .addReg(Exec)
201     .addReg(Exec, RegState::ImplicitDefine);
202 
203   Register Tmp = MRI->createVirtualRegister(BoolRC);
204 
205   MachineInstr *And =
206     BuildMI(MBB, I, DL, TII->get(AndOpc), Tmp)
207     .addReg(CopyReg)
208     .add(Cond);
209 
210   setImpSCCDefDead(*And, true);
211 
212   MachineInstr *Xor = nullptr;
213   if (!SimpleIf) {
214     Xor =
215       BuildMI(MBB, I, DL, TII->get(XorOpc), SaveExecReg)
216       .addReg(Tmp)
217       .addReg(CopyReg);
218     setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
219   }
220 
221   // Use a copy that is a terminator to get correct spill code placement it with
222   // fast regalloc.
223   MachineInstr *SetExec =
224     BuildMI(MBB, I, DL, TII->get(MovTermOpc), Exec)
225     .addReg(Tmp, RegState::Kill);
226 
227   // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
228   // during SIRemoveShortExecBranches.
229   MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
230                             .add(MI.getOperand(2));
231 
232   if (!LIS) {
233     MI.eraseFromParent();
234     return;
235   }
236 
237   LIS->InsertMachineInstrInMaps(*CopyExec);
238 
239   // Replace with and so we don't need to fix the live interval for condition
240   // register.
241   LIS->ReplaceMachineInstrInMaps(MI, *And);
242 
243   if (!SimpleIf)
244     LIS->InsertMachineInstrInMaps(*Xor);
245   LIS->InsertMachineInstrInMaps(*SetExec);
246   LIS->InsertMachineInstrInMaps(*NewBr);
247 
248   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
249   MI.eraseFromParent();
250 
251   // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
252   // hard to add another def here but I'm not sure how to correctly update the
253   // valno.
254   LIS->removeInterval(SaveExecReg);
255   LIS->createAndComputeVirtRegInterval(SaveExecReg);
256   LIS->createAndComputeVirtRegInterval(Tmp);
257   if (!SimpleIf)
258     LIS->createAndComputeVirtRegInterval(CopyReg);
259 }
260 
261 void SILowerControlFlow::emitElse(MachineInstr &MI) {
262   MachineBasicBlock &MBB = *MI.getParent();
263   const DebugLoc &DL = MI.getDebugLoc();
264 
265   Register DstReg = MI.getOperand(0).getReg();
266 
267   bool ExecModified = MI.getOperand(3).getImm() != 0;
268   MachineBasicBlock::iterator Start = MBB.begin();
269 
270   // We are running before TwoAddressInstructions, and si_else's operands are
271   // tied. In order to correctly tie the registers, split this into a copy of
272   // the src like it does.
273   Register CopyReg = MRI->createVirtualRegister(BoolRC);
274   MachineInstr *CopyExec =
275     BuildMI(MBB, Start, DL, TII->get(AMDGPU::COPY), CopyReg)
276       .add(MI.getOperand(1)); // Saved EXEC
277 
278   // This must be inserted before phis and any spill code inserted before the
279   // else.
280   Register SaveReg = ExecModified ?
281     MRI->createVirtualRegister(BoolRC) : DstReg;
282   MachineInstr *OrSaveExec =
283     BuildMI(MBB, Start, DL, TII->get(OrSaveExecOpc), SaveReg)
284     .addReg(CopyReg);
285 
286   MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
287 
288   MachineBasicBlock::iterator ElsePt(MI);
289 
290   if (ExecModified) {
291     MachineInstr *And =
292       BuildMI(MBB, ElsePt, DL, TII->get(AndOpc), DstReg)
293       .addReg(Exec)
294       .addReg(SaveReg);
295 
296     if (LIS)
297       LIS->InsertMachineInstrInMaps(*And);
298   }
299 
300   MachineInstr *Xor =
301     BuildMI(MBB, ElsePt, DL, TII->get(XorTermrOpc), Exec)
302     .addReg(Exec)
303     .addReg(DstReg);
304 
305   MachineInstr *Branch =
306       BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
307           .addMBB(DestBB);
308 
309   if (!LIS) {
310     MI.eraseFromParent();
311     return;
312   }
313 
314   LIS->RemoveMachineInstrFromMaps(MI);
315   MI.eraseFromParent();
316 
317   LIS->InsertMachineInstrInMaps(*CopyExec);
318   LIS->InsertMachineInstrInMaps(*OrSaveExec);
319 
320   LIS->InsertMachineInstrInMaps(*Xor);
321   LIS->InsertMachineInstrInMaps(*Branch);
322 
323   // src reg is tied to dst reg.
324   LIS->removeInterval(DstReg);
325   LIS->createAndComputeVirtRegInterval(DstReg);
326   LIS->createAndComputeVirtRegInterval(CopyReg);
327   if (ExecModified)
328     LIS->createAndComputeVirtRegInterval(SaveReg);
329 
330   // Let this be recomputed.
331   LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
332 }
333 
334 void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
335   MachineBasicBlock &MBB = *MI.getParent();
336   const DebugLoc &DL = MI.getDebugLoc();
337   auto Dst = MI.getOperand(0).getReg();
338 
339   // Skip ANDing with exec if the break condition is already masked by exec
340   // because it is a V_CMP in the same basic block. (We know the break
341   // condition operand was an i1 in IR, so if it is a VALU instruction it must
342   // be one with a carry-out.)
343   bool SkipAnding = false;
344   if (MI.getOperand(1).isReg()) {
345     if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
346       SkipAnding = Def->getParent() == MI.getParent()
347           && SIInstrInfo::isVALU(*Def);
348     }
349   }
350 
351   // AND the break condition operand with exec, then OR that into the "loop
352   // exit" mask.
353   MachineInstr *And = nullptr, *Or = nullptr;
354   if (!SkipAnding) {
355     Register AndReg = MRI->createVirtualRegister(BoolRC);
356     And = BuildMI(MBB, &MI, DL, TII->get(AndOpc), AndReg)
357              .addReg(Exec)
358              .add(MI.getOperand(1));
359     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
360              .addReg(AndReg)
361              .add(MI.getOperand(2));
362     if (LIS)
363       LIS->createAndComputeVirtRegInterval(AndReg);
364   } else
365     Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
366              .add(MI.getOperand(1))
367              .add(MI.getOperand(2));
368 
369   if (LIS) {
370     if (And)
371       LIS->InsertMachineInstrInMaps(*And);
372     LIS->ReplaceMachineInstrInMaps(MI, *Or);
373   }
374 
375   MI.eraseFromParent();
376 }
377 
378 void SILowerControlFlow::emitLoop(MachineInstr &MI) {
379   MachineBasicBlock &MBB = *MI.getParent();
380   const DebugLoc &DL = MI.getDebugLoc();
381 
382   MachineInstr *AndN2 =
383       BuildMI(MBB, &MI, DL, TII->get(Andn2TermOpc), Exec)
384           .addReg(Exec)
385           .add(MI.getOperand(0));
386 
387   MachineInstr *Branch =
388       BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
389           .add(MI.getOperand(1));
390 
391   if (LIS) {
392     LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
393     LIS->InsertMachineInstrInMaps(*Branch);
394   }
395 
396   MI.eraseFromParent();
397 }
398 
399 void SILowerControlFlow::emitEndCf(MachineInstr &MI) {
400   MachineBasicBlock &MBB = *MI.getParent();
401   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
402   unsigned CFMask = MI.getOperand(0).getReg();
403   MachineInstr *Def = MRI.getUniqueVRegDef(CFMask);
404   const DebugLoc &DL = MI.getDebugLoc();
405 
406   MachineBasicBlock::iterator InsPt =
407       Def && Def->getParent() == &MBB ? std::next(MachineBasicBlock::iterator(Def))
408                                : MBB.begin();
409   MachineInstr *NewMI = BuildMI(MBB, InsPt, DL, TII->get(OrOpc), Exec)
410                             .addReg(Exec)
411                             .add(MI.getOperand(0));
412 
413   if (LIS)
414     LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
415 
416   MI.eraseFromParent();
417 
418   if (LIS)
419     LIS->handleMove(*NewMI);
420 }
421 
422 // Returns replace operands for a logical operation, either single result
423 // for exec or two operands if source was another equivalent operation.
424 void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
425        SmallVectorImpl<MachineOperand> &Src) const {
426   MachineOperand &Op = MI.getOperand(OpNo);
427   if (!Op.isReg() || !Register::isVirtualRegister(Op.getReg())) {
428     Src.push_back(Op);
429     return;
430   }
431 
432   MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
433   if (!Def || Def->getParent() != MI.getParent() ||
434       !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
435     return;
436 
437   // Make sure we do not modify exec between def and use.
438   // A copy with implcitly defined exec inserted earlier is an exclusion, it
439   // does not really modify exec.
440   for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
441     if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
442         !(I->isCopy() && I->getOperand(0).getReg() != Exec))
443       return;
444 
445   for (const auto &SrcOp : Def->explicit_operands())
446     if (SrcOp.isReg() && SrcOp.isUse() &&
447         (Register::isVirtualRegister(SrcOp.getReg()) || SrcOp.getReg() == Exec))
448       Src.push_back(SrcOp);
449 }
450 
451 // Search and combine pairs of equivalent instructions, like
452 // S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
453 // S_OR_B64  x, (S_OR_B64  x, y) => S_OR_B64  x, y
454 // One of the operands is exec mask.
455 void SILowerControlFlow::combineMasks(MachineInstr &MI) {
456   assert(MI.getNumExplicitOperands() == 3);
457   SmallVector<MachineOperand, 4> Ops;
458   unsigned OpToReplace = 1;
459   findMaskOperands(MI, 1, Ops);
460   if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
461   findMaskOperands(MI, 2, Ops);
462   if (Ops.size() != 3) return;
463 
464   unsigned UniqueOpndIdx;
465   if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
466   else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
467   else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
468   else return;
469 
470   Register Reg = MI.getOperand(OpToReplace).getReg();
471   MI.RemoveOperand(OpToReplace);
472   MI.addOperand(Ops[UniqueOpndIdx]);
473   if (MRI->use_empty(Reg))
474     MRI->getUniqueVRegDef(Reg)->eraseFromParent();
475 }
476 
477 bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) {
478   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
479   TII = ST.getInstrInfo();
480   TRI = &TII->getRegisterInfo();
481 
482   // This doesn't actually need LiveIntervals, but we can preserve them.
483   LIS = getAnalysisIfAvailable<LiveIntervals>();
484   MRI = &MF.getRegInfo();
485   BoolRC = TRI->getBoolRC();
486 
487   if (ST.isWave32()) {
488     AndOpc = AMDGPU::S_AND_B32;
489     OrOpc = AMDGPU::S_OR_B32;
490     XorOpc = AMDGPU::S_XOR_B32;
491     MovTermOpc = AMDGPU::S_MOV_B32_term;
492     Andn2TermOpc = AMDGPU::S_ANDN2_B32_term;
493     XorTermrOpc = AMDGPU::S_XOR_B32_term;
494     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B32;
495     Exec = AMDGPU::EXEC_LO;
496   } else {
497     AndOpc = AMDGPU::S_AND_B64;
498     OrOpc = AMDGPU::S_OR_B64;
499     XorOpc = AMDGPU::S_XOR_B64;
500     MovTermOpc = AMDGPU::S_MOV_B64_term;
501     Andn2TermOpc = AMDGPU::S_ANDN2_B64_term;
502     XorTermrOpc = AMDGPU::S_XOR_B64_term;
503     OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B64;
504     Exec = AMDGPU::EXEC;
505   }
506 
507   MachineFunction::iterator NextBB;
508   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
509        BI != BE; BI = NextBB) {
510     NextBB = std::next(BI);
511     MachineBasicBlock &MBB = *BI;
512 
513     MachineBasicBlock::iterator I, Next, Last;
514 
515     for (I = MBB.begin(), Last = MBB.end(); I != MBB.end(); I = Next) {
516       Next = std::next(I);
517       MachineInstr &MI = *I;
518 
519       switch (MI.getOpcode()) {
520       case AMDGPU::SI_IF:
521         emitIf(MI);
522         break;
523 
524       case AMDGPU::SI_ELSE:
525         emitElse(MI);
526         break;
527 
528       case AMDGPU::SI_IF_BREAK:
529         emitIfBreak(MI);
530         break;
531 
532       case AMDGPU::SI_LOOP:
533         emitLoop(MI);
534         break;
535 
536       case AMDGPU::SI_END_CF:
537         emitEndCf(MI);
538         break;
539 
540       case AMDGPU::S_AND_B64:
541       case AMDGPU::S_OR_B64:
542       case AMDGPU::S_AND_B32:
543       case AMDGPU::S_OR_B32:
544         // Cleanup bit manipulations on exec mask
545         combineMasks(MI);
546         Last = I;
547         continue;
548 
549       default:
550         Last = I;
551         continue;
552       }
553 
554       // Replay newly inserted code to combine masks
555       Next = (Last == MBB.end()) ? MBB.begin() : Last;
556     }
557   }
558 
559   return true;
560 }
561