xref: /llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp (revision fde8351743d5a7ee38ef8838adcfcd59f5ca6e4b)
1 //===-- SIOptimizeExecMasking.cpp -----------------------------------------===//
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 #include "AMDGPU.h"
10 #include "AMDGPUSubtarget.h"
11 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
12 #include "SIInstrInfo.h"
13 #include "llvm/ADT/SmallSet.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineInstrBuilder.h"
16 #include "llvm/CodeGen/MachineRegisterInfo.h"
17 #include "llvm/InitializePasses.h"
18 #include "llvm/Support/Debug.h"
19 
20 using namespace llvm;
21 
22 #define DEBUG_TYPE "si-optimize-exec-masking"
23 
24 namespace {
25 
26 class SIOptimizeExecMasking : public MachineFunctionPass {
27 public:
28   static char ID;
29 
30 public:
31   SIOptimizeExecMasking() : MachineFunctionPass(ID) {
32     initializeSIOptimizeExecMaskingPass(*PassRegistry::getPassRegistry());
33   }
34 
35   bool runOnMachineFunction(MachineFunction &MF) override;
36 
37   StringRef getPassName() const override {
38     return "SI optimize exec mask operations";
39   }
40 
41   void getAnalysisUsage(AnalysisUsage &AU) const override {
42     AU.setPreservesCFG();
43     MachineFunctionPass::getAnalysisUsage(AU);
44   }
45 };
46 
47 } // End anonymous namespace.
48 
49 INITIALIZE_PASS_BEGIN(SIOptimizeExecMasking, DEBUG_TYPE,
50                       "SI optimize exec mask operations", false, false)
51 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
52 INITIALIZE_PASS_END(SIOptimizeExecMasking, DEBUG_TYPE,
53                     "SI optimize exec mask operations", false, false)
54 
55 char SIOptimizeExecMasking::ID = 0;
56 
57 char &llvm::SIOptimizeExecMaskingID = SIOptimizeExecMasking::ID;
58 
59 /// If \p MI is a copy from exec, return the register copied to.
60 static Register isCopyFromExec(const MachineInstr &MI, const GCNSubtarget &ST) {
61   switch (MI.getOpcode()) {
62   case AMDGPU::COPY:
63   case AMDGPU::S_MOV_B64:
64   case AMDGPU::S_MOV_B64_term:
65   case AMDGPU::S_MOV_B32:
66   case AMDGPU::S_MOV_B32_term: {
67     const MachineOperand &Src = MI.getOperand(1);
68     if (Src.isReg() &&
69         Src.getReg() == (ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC))
70       return MI.getOperand(0).getReg();
71   }
72   }
73 
74   return AMDGPU::NoRegister;
75 }
76 
77 /// If \p MI is a copy to exec, return the register copied from.
78 static Register isCopyToExec(const MachineInstr &MI, const GCNSubtarget &ST) {
79   switch (MI.getOpcode()) {
80   case AMDGPU::COPY:
81   case AMDGPU::S_MOV_B64:
82   case AMDGPU::S_MOV_B32: {
83     const MachineOperand &Dst = MI.getOperand(0);
84     if (Dst.isReg() &&
85         Dst.getReg() == (ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC) &&
86         MI.getOperand(1).isReg())
87       return MI.getOperand(1).getReg();
88     break;
89   }
90   case AMDGPU::S_MOV_B64_term:
91   case AMDGPU::S_MOV_B32_term:
92     llvm_unreachable("should have been replaced");
93   }
94 
95   return Register();
96 }
97 
98 /// If \p MI is a logical operation on an exec value,
99 /// return the register copied to.
100 static Register isLogicalOpOnExec(const MachineInstr &MI) {
101   switch (MI.getOpcode()) {
102   case AMDGPU::S_AND_B64:
103   case AMDGPU::S_OR_B64:
104   case AMDGPU::S_XOR_B64:
105   case AMDGPU::S_ANDN2_B64:
106   case AMDGPU::S_ORN2_B64:
107   case AMDGPU::S_NAND_B64:
108   case AMDGPU::S_NOR_B64:
109   case AMDGPU::S_XNOR_B64: {
110     const MachineOperand &Src1 = MI.getOperand(1);
111     if (Src1.isReg() && Src1.getReg() == AMDGPU::EXEC)
112       return MI.getOperand(0).getReg();
113     const MachineOperand &Src2 = MI.getOperand(2);
114     if (Src2.isReg() && Src2.getReg() == AMDGPU::EXEC)
115       return MI.getOperand(0).getReg();
116     break;
117   }
118   case AMDGPU::S_AND_B32:
119   case AMDGPU::S_OR_B32:
120   case AMDGPU::S_XOR_B32:
121   case AMDGPU::S_ANDN2_B32:
122   case AMDGPU::S_ORN2_B32:
123   case AMDGPU::S_NAND_B32:
124   case AMDGPU::S_NOR_B32:
125   case AMDGPU::S_XNOR_B32: {
126     const MachineOperand &Src1 = MI.getOperand(1);
127     if (Src1.isReg() && Src1.getReg() == AMDGPU::EXEC_LO)
128       return MI.getOperand(0).getReg();
129     const MachineOperand &Src2 = MI.getOperand(2);
130     if (Src2.isReg() && Src2.getReg() == AMDGPU::EXEC_LO)
131       return MI.getOperand(0).getReg();
132     break;
133   }
134   }
135 
136   return AMDGPU::NoRegister;
137 }
138 
139 static unsigned getSaveExecOp(unsigned Opc) {
140   switch (Opc) {
141   case AMDGPU::S_AND_B64:
142     return AMDGPU::S_AND_SAVEEXEC_B64;
143   case AMDGPU::S_OR_B64:
144     return AMDGPU::S_OR_SAVEEXEC_B64;
145   case AMDGPU::S_XOR_B64:
146     return AMDGPU::S_XOR_SAVEEXEC_B64;
147   case AMDGPU::S_ANDN2_B64:
148     return AMDGPU::S_ANDN2_SAVEEXEC_B64;
149   case AMDGPU::S_ORN2_B64:
150     return AMDGPU::S_ORN2_SAVEEXEC_B64;
151   case AMDGPU::S_NAND_B64:
152     return AMDGPU::S_NAND_SAVEEXEC_B64;
153   case AMDGPU::S_NOR_B64:
154     return AMDGPU::S_NOR_SAVEEXEC_B64;
155   case AMDGPU::S_XNOR_B64:
156     return AMDGPU::S_XNOR_SAVEEXEC_B64;
157   case AMDGPU::S_AND_B32:
158     return AMDGPU::S_AND_SAVEEXEC_B32;
159   case AMDGPU::S_OR_B32:
160     return AMDGPU::S_OR_SAVEEXEC_B32;
161   case AMDGPU::S_XOR_B32:
162     return AMDGPU::S_XOR_SAVEEXEC_B32;
163   case AMDGPU::S_ANDN2_B32:
164     return AMDGPU::S_ANDN2_SAVEEXEC_B32;
165   case AMDGPU::S_ORN2_B32:
166     return AMDGPU::S_ORN2_SAVEEXEC_B32;
167   case AMDGPU::S_NAND_B32:
168     return AMDGPU::S_NAND_SAVEEXEC_B32;
169   case AMDGPU::S_NOR_B32:
170     return AMDGPU::S_NOR_SAVEEXEC_B32;
171   case AMDGPU::S_XNOR_B32:
172     return AMDGPU::S_XNOR_SAVEEXEC_B32;
173   default:
174     return AMDGPU::INSTRUCTION_LIST_END;
175   }
176 }
177 
178 // These are only terminators to get correct spill code placement during
179 // register allocation, so turn them back into normal instructions.
180 static bool removeTerminatorBit(const SIInstrInfo &TII, MachineInstr &MI) {
181   switch (MI.getOpcode()) {
182   case AMDGPU::S_MOV_B32_term: {
183     bool RegSrc = MI.getOperand(1).isReg();
184     MI.setDesc(TII.get(RegSrc ? AMDGPU::COPY : AMDGPU::S_MOV_B32));
185     return true;
186   }
187   case AMDGPU::S_MOV_B64_term: {
188     bool RegSrc = MI.getOperand(1).isReg();
189     MI.setDesc(TII.get(RegSrc ? AMDGPU::COPY : AMDGPU::S_MOV_B64));
190     return true;
191   }
192   case AMDGPU::S_XOR_B64_term: {
193     // This is only a terminator to get the correct spill code placement during
194     // register allocation.
195     MI.setDesc(TII.get(AMDGPU::S_XOR_B64));
196     return true;
197   }
198   case AMDGPU::S_XOR_B32_term: {
199     // This is only a terminator to get the correct spill code placement during
200     // register allocation.
201     MI.setDesc(TII.get(AMDGPU::S_XOR_B32));
202     return true;
203   }
204   case AMDGPU::S_OR_B64_term: {
205     // This is only a terminator to get the correct spill code placement during
206     // register allocation.
207     MI.setDesc(TII.get(AMDGPU::S_OR_B64));
208     return true;
209   }
210   case AMDGPU::S_OR_B32_term: {
211     // This is only a terminator to get the correct spill code placement during
212     // register allocation.
213     MI.setDesc(TII.get(AMDGPU::S_OR_B32));
214     return true;
215   }
216   case AMDGPU::S_ANDN2_B64_term: {
217     // This is only a terminator to get the correct spill code placement during
218     // register allocation.
219     MI.setDesc(TII.get(AMDGPU::S_ANDN2_B64));
220     return true;
221   }
222   case AMDGPU::S_ANDN2_B32_term: {
223     // This is only a terminator to get the correct spill code placement during
224     // register allocation.
225     MI.setDesc(TII.get(AMDGPU::S_ANDN2_B32));
226     return true;
227   }
228   default:
229     return false;
230   }
231 }
232 
233 // Turn all pseudoterminators in the block into their equivalent non-terminator
234 // instructions. Returns the reverse iterator to the first non-terminator
235 // instruction in the block.
236 static MachineBasicBlock::reverse_iterator fixTerminators(
237   const SIInstrInfo &TII,
238   MachineBasicBlock &MBB) {
239   MachineBasicBlock::reverse_iterator I = MBB.rbegin(), E = MBB.rend();
240 
241   bool Seen = false;
242   MachineBasicBlock::reverse_iterator FirstNonTerm = I;
243   for (; I != E; ++I) {
244     if (!I->isTerminator())
245       return Seen ? FirstNonTerm : I;
246 
247     if (removeTerminatorBit(TII, *I)) {
248       if (!Seen) {
249         FirstNonTerm = I;
250         Seen = true;
251       }
252     }
253   }
254 
255   return FirstNonTerm;
256 }
257 
258 static MachineBasicBlock::reverse_iterator findExecCopy(
259   const SIInstrInfo &TII,
260   const GCNSubtarget &ST,
261   MachineBasicBlock &MBB,
262   MachineBasicBlock::reverse_iterator I,
263   unsigned CopyToExec) {
264   const unsigned InstLimit = 25;
265 
266   auto E = MBB.rend();
267   for (unsigned N = 0; N <= InstLimit && I != E; ++I, ++N) {
268     Register CopyFromExec = isCopyFromExec(*I, ST);
269     if (CopyFromExec.isValid())
270       return I;
271   }
272 
273   return E;
274 }
275 
276 // XXX - Seems LivePhysRegs doesn't work correctly since it will incorrectly
277 // report the register as unavailable because a super-register with a lane mask
278 // is unavailable.
279 static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg) {
280   for (MachineBasicBlock *Succ : MBB.successors()) {
281     if (Succ->isLiveIn(Reg))
282       return true;
283   }
284 
285   return false;
286 }
287 
288 bool SIOptimizeExecMasking::runOnMachineFunction(MachineFunction &MF) {
289   if (skipFunction(MF.getFunction()))
290     return false;
291 
292   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
293   const SIRegisterInfo *TRI = ST.getRegisterInfo();
294   const SIInstrInfo *TII = ST.getInstrInfo();
295   MCRegister Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
296 
297   // Optimize sequences emitted for control flow lowering. They are originally
298   // emitted as the separate operations because spill code may need to be
299   // inserted for the saved copy of exec.
300   //
301   //     x = copy exec
302   //     z = s_<op>_b64 x, y
303   //     exec = copy z
304   // =>
305   //     x = s_<op>_saveexec_b64 y
306   //
307 
308   for (MachineBasicBlock &MBB : MF) {
309     MachineBasicBlock::reverse_iterator I = fixTerminators(*TII, MBB);
310     MachineBasicBlock::reverse_iterator E = MBB.rend();
311     if (I == E)
312       continue;
313 
314     // It's possible to see other terminator copies after the exec copy. This
315     // can happen if control flow pseudos had their outputs used by phis.
316     Register CopyToExec;
317 
318     unsigned SearchCount = 0;
319     const unsigned SearchLimit = 5;
320     while (I != E && SearchCount++ < SearchLimit) {
321       CopyToExec = isCopyToExec(*I, ST);
322       if (CopyToExec)
323         break;
324       ++I;
325     }
326 
327     if (!CopyToExec)
328       continue;
329 
330     // Scan backwards to find the def.
331     auto CopyToExecInst = &*I;
332     auto CopyFromExecInst = findExecCopy(*TII, ST, MBB, I, CopyToExec);
333     if (CopyFromExecInst == E) {
334       auto PrepareExecInst = std::next(I);
335       if (PrepareExecInst == E)
336         continue;
337       // Fold exec = COPY (S_AND_B64 reg, exec) -> exec = S_AND_B64 reg, exec
338       if (CopyToExecInst->getOperand(1).isKill() &&
339           isLogicalOpOnExec(*PrepareExecInst) == CopyToExec) {
340         LLVM_DEBUG(dbgs() << "Fold exec copy: " << *PrepareExecInst);
341 
342         PrepareExecInst->getOperand(0).setReg(Exec);
343 
344         LLVM_DEBUG(dbgs() << "into: " << *PrepareExecInst << '\n');
345 
346         CopyToExecInst->eraseFromParent();
347       }
348 
349       continue;
350     }
351 
352     if (isLiveOut(MBB, CopyToExec)) {
353       // The copied register is live out and has a second use in another block.
354       LLVM_DEBUG(dbgs() << "Exec copy source register is live out\n");
355       continue;
356     }
357 
358     Register CopyFromExec = CopyFromExecInst->getOperand(0).getReg();
359     MachineInstr *SaveExecInst = nullptr;
360     SmallVector<MachineInstr *, 4> OtherUseInsts;
361 
362     for (MachineBasicBlock::iterator J
363            = std::next(CopyFromExecInst->getIterator()), JE = I->getIterator();
364          J != JE; ++J) {
365       if (SaveExecInst && J->readsRegister(Exec, TRI)) {
366         LLVM_DEBUG(dbgs() << "exec read prevents saveexec: " << *J << '\n');
367         // Make sure this is inserted after any VALU ops that may have been
368         // scheduled in between.
369         SaveExecInst = nullptr;
370         break;
371       }
372 
373       bool ReadsCopyFromExec = J->readsRegister(CopyFromExec, TRI);
374 
375       if (J->modifiesRegister(CopyToExec, TRI)) {
376         if (SaveExecInst) {
377           LLVM_DEBUG(dbgs() << "Multiple instructions modify "
378                             << printReg(CopyToExec, TRI) << '\n');
379           SaveExecInst = nullptr;
380           break;
381         }
382 
383         unsigned SaveExecOp = getSaveExecOp(J->getOpcode());
384         if (SaveExecOp == AMDGPU::INSTRUCTION_LIST_END)
385           break;
386 
387         if (ReadsCopyFromExec) {
388           SaveExecInst = &*J;
389           LLVM_DEBUG(dbgs() << "Found save exec op: " << *SaveExecInst << '\n');
390           continue;
391         } else {
392           LLVM_DEBUG(dbgs()
393                      << "Instruction does not read exec copy: " << *J << '\n');
394           break;
395         }
396       } else if (ReadsCopyFromExec && !SaveExecInst) {
397         // Make sure no other instruction is trying to use this copy, before it
398         // will be rewritten by the saveexec, i.e. hasOneUse. There may have
399         // been another use, such as an inserted spill. For example:
400         //
401         // %sgpr0_sgpr1 = COPY %exec
402         // spill %sgpr0_sgpr1
403         // %sgpr2_sgpr3 = S_AND_B64 %sgpr0_sgpr1
404         //
405         LLVM_DEBUG(dbgs() << "Found second use of save inst candidate: " << *J
406                           << '\n');
407         break;
408       }
409 
410       if (SaveExecInst && J->readsRegister(CopyToExec, TRI)) {
411         assert(SaveExecInst != &*J);
412         OtherUseInsts.push_back(&*J);
413       }
414     }
415 
416     if (!SaveExecInst)
417       continue;
418 
419     LLVM_DEBUG(dbgs() << "Insert save exec op: " << *SaveExecInst << '\n');
420 
421     MachineOperand &Src0 = SaveExecInst->getOperand(1);
422     MachineOperand &Src1 = SaveExecInst->getOperand(2);
423 
424     MachineOperand *OtherOp = nullptr;
425 
426     if (Src0.isReg() && Src0.getReg() == CopyFromExec) {
427       OtherOp = &Src1;
428     } else if (Src1.isReg() && Src1.getReg() == CopyFromExec) {
429       if (!SaveExecInst->isCommutable())
430         break;
431 
432       OtherOp = &Src0;
433     } else
434       llvm_unreachable("unexpected");
435 
436     CopyFromExecInst->eraseFromParent();
437 
438     auto InsPt = SaveExecInst->getIterator();
439     const DebugLoc &DL = SaveExecInst->getDebugLoc();
440 
441     BuildMI(MBB, InsPt, DL, TII->get(getSaveExecOp(SaveExecInst->getOpcode())),
442             CopyFromExec)
443       .addReg(OtherOp->getReg());
444     SaveExecInst->eraseFromParent();
445 
446     CopyToExecInst->eraseFromParent();
447 
448     for (MachineInstr *OtherInst : OtherUseInsts) {
449       OtherInst->substituteRegister(CopyToExec, Exec,
450                                     AMDGPU::NoSubRegister, *TRI);
451     }
452   }
453 
454   return true;
455 
456 }
457