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