LLVM 24.0.0git
SIOptimizeExecMasking.cpp
Go to the documentation of this file.
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
10#include "AMDGPU.h"
11#include "AMDGPULaneMaskUtils.h"
12#include "GCNSubtarget.h"
13#include "SIRegisterInfo.h"
20
21using namespace llvm;
22
23#define DEBUG_TYPE "si-optimize-exec-masking"
24
25namespace {
26
27class SIOptimizeExecMasking {
28public:
29 SIOptimizeExecMasking(MachineFunction *MF)
30 : MF(MF), ST(&MF->getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
31 TRI(&TII->getRegisterInfo()), MRI(&MF->getRegInfo()),
33 bool run();
34
35private:
37 const GCNSubtarget *ST;
38 const SIInstrInfo *TII;
39 const SIRegisterInfo *TRI;
42
45 SmallVector<MachineOperand *, 1> KillFlagCandidates;
46
47 Register isCopyFromExec(const MachineInstr &MI) const;
48 Register isCopyToExec(const MachineInstr &MI) const;
49 bool removeTerminatorBit(MachineInstr &MI) const;
51 fixTerminators(MachineBasicBlock &MBB) const;
53 findExecCopy(MachineBasicBlock &MBB,
55 bool isRegisterInUseBetween(MachineInstr &Stop, MachineInstr &Start,
56 MCRegister Reg, bool UseLiveOuts = false,
57 bool IgnoreStart = false) const;
58 bool isRegisterInUseAfter(MachineInstr &Stop, MCRegister Reg) const;
59 MachineInstr *findInstrBackwards(
60 MachineInstr &Origin, std::function<bool(MachineInstr *)> Pred,
61 ArrayRef<MCRegister> NonModifiableRegs,
62 MachineInstr *Terminator = nullptr,
63 SmallVectorImpl<MachineOperand *> *KillFlagCandidates = nullptr,
64 unsigned MaxInstructions = 20) const;
65 bool optimizeExecSequence();
66 bool blocksAndN2Sink(const MachineInstr &MI, Register Dst) const;
67 bool optimizeAndN2WrExecSequence(MachineInstr &CopyToExecInst,
68 Register Dst) const;
69 void tryRecordVCmpxAndSaveexecSequence(MachineInstr &MI);
70 bool optimizeVCMPSaveExecSequence(MachineInstr &SaveExecInstr,
71 MachineInstr &VCmp) const;
72
73 void tryRecordOrSaveexecXorSequence(MachineInstr &MI);
74 bool optimizeOrSaveexecXorSequences();
75};
76
77class SIOptimizeExecMaskingLegacy : public MachineFunctionPass {
78public:
79 static char ID;
80
81 SIOptimizeExecMaskingLegacy() : MachineFunctionPass(ID) {}
82
83 bool runOnMachineFunction(MachineFunction &MF) override;
84
85 StringRef getPassName() const override {
86 return "SI optimize exec mask operations";
87 }
88
89 void getAnalysisUsage(AnalysisUsage &AU) const override {
90 AU.setPreservesCFG();
92 }
93};
94
95} // End anonymous namespace.
96
100 SIOptimizeExecMasking Impl(&MF);
101
102 if (!Impl.run())
103 return PreservedAnalyses::all();
104
106 PA.preserveSet<CFGAnalyses>();
107 return PA;
108}
109
110INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingLegacy, DEBUG_TYPE,
111 "SI optimize exec mask operations", false, false)
113INITIALIZE_PASS_END(SIOptimizeExecMaskingLegacy, DEBUG_TYPE,
114 "SI optimize exec mask operations", false, false)
115
116char SIOptimizeExecMaskingLegacy::ID = 0;
117
118char &llvm::SIOptimizeExecMaskingLegacyID = SIOptimizeExecMaskingLegacy::ID;
119
120/// If \p MI is a copy from exec, return the register copied to.
121Register SIOptimizeExecMasking::isCopyFromExec(const MachineInstr &MI) const {
122 switch (MI.getOpcode()) {
123 case AMDGPU::COPY:
124 case AMDGPU::S_MOV_B64:
125 case AMDGPU::S_MOV_B64_term:
126 case AMDGPU::S_MOV_B32:
127 case AMDGPU::S_MOV_B32_term: {
128 const MachineOperand &Src = MI.getOperand(1);
129 if (Src.isReg() && Src.getReg() == LMC.ExecReg)
130 return MI.getOperand(0).getReg();
131 }
132 }
133
134 return AMDGPU::NoRegister;
135}
136
137/// If \p MI is a copy to exec, return the register copied from.
138Register SIOptimizeExecMasking::isCopyToExec(const MachineInstr &MI) const {
139 switch (MI.getOpcode()) {
140 case AMDGPU::COPY:
141 case AMDGPU::S_MOV_B64:
142 case AMDGPU::S_MOV_B32: {
143 const MachineOperand &Dst = MI.getOperand(0);
144 if (Dst.isReg() && Dst.getReg() == LMC.ExecReg && MI.getOperand(1).isReg())
145 return MI.getOperand(1).getReg();
146 break;
147 }
148 case AMDGPU::S_MOV_B64_term:
149 case AMDGPU::S_MOV_B32_term:
150 llvm_unreachable("should have been replaced");
151 }
152
153 return Register();
154}
155
156/// If \p MI is a logical operation on an exec value,
157/// return the register copied to.
159 switch (MI.getOpcode()) {
160 case AMDGPU::S_AND_B64:
161 case AMDGPU::S_OR_B64:
162 case AMDGPU::S_XOR_B64:
163 case AMDGPU::S_ANDN2_B64:
164 case AMDGPU::S_ORN2_B64:
165 case AMDGPU::S_NAND_B64:
166 case AMDGPU::S_NOR_B64:
167 case AMDGPU::S_XNOR_B64: {
168 const MachineOperand &Src1 = MI.getOperand(1);
169 if (Src1.isReg() && Src1.getReg() == AMDGPU::EXEC)
170 return MI.getOperand(0).getReg();
171 const MachineOperand &Src2 = MI.getOperand(2);
172 if (Src2.isReg() && Src2.getReg() == AMDGPU::EXEC)
173 return MI.getOperand(0).getReg();
174 break;
175 }
176 case AMDGPU::S_AND_B32:
177 case AMDGPU::S_OR_B32:
178 case AMDGPU::S_XOR_B32:
179 case AMDGPU::S_ANDN2_B32:
180 case AMDGPU::S_ORN2_B32:
181 case AMDGPU::S_NAND_B32:
182 case AMDGPU::S_NOR_B32:
183 case AMDGPU::S_XNOR_B32: {
184 const MachineOperand &Src1 = MI.getOperand(1);
185 if (Src1.isReg() && Src1.getReg() == AMDGPU::EXEC_LO)
186 return MI.getOperand(0).getReg();
187 const MachineOperand &Src2 = MI.getOperand(2);
188 if (Src2.isReg() && Src2.getReg() == AMDGPU::EXEC_LO)
189 return MI.getOperand(0).getReg();
190 break;
191 }
192 }
193
194 return AMDGPU::NoRegister;
195}
196
197static unsigned getSaveExecOp(unsigned Opc) {
198 switch (Opc) {
199 case AMDGPU::S_AND_B64:
200 return AMDGPU::S_AND_SAVEEXEC_B64;
201 case AMDGPU::S_OR_B64:
202 return AMDGPU::S_OR_SAVEEXEC_B64;
203 case AMDGPU::S_XOR_B64:
204 return AMDGPU::S_XOR_SAVEEXEC_B64;
205 case AMDGPU::S_ANDN2_B64:
206 return AMDGPU::S_ANDN2_SAVEEXEC_B64;
207 case AMDGPU::S_ORN2_B64:
208 return AMDGPU::S_ORN2_SAVEEXEC_B64;
209 case AMDGPU::S_NAND_B64:
210 return AMDGPU::S_NAND_SAVEEXEC_B64;
211 case AMDGPU::S_NOR_B64:
212 return AMDGPU::S_NOR_SAVEEXEC_B64;
213 case AMDGPU::S_XNOR_B64:
214 return AMDGPU::S_XNOR_SAVEEXEC_B64;
215 case AMDGPU::S_AND_B32:
216 return AMDGPU::S_AND_SAVEEXEC_B32;
217 case AMDGPU::S_OR_B32:
218 return AMDGPU::S_OR_SAVEEXEC_B32;
219 case AMDGPU::S_XOR_B32:
220 return AMDGPU::S_XOR_SAVEEXEC_B32;
221 case AMDGPU::S_ANDN2_B32:
222 return AMDGPU::S_ANDN2_SAVEEXEC_B32;
223 case AMDGPU::S_ORN2_B32:
224 return AMDGPU::S_ORN2_SAVEEXEC_B32;
225 case AMDGPU::S_NAND_B32:
226 return AMDGPU::S_NAND_SAVEEXEC_B32;
227 case AMDGPU::S_NOR_B32:
228 return AMDGPU::S_NOR_SAVEEXEC_B32;
229 case AMDGPU::S_XNOR_B32:
230 return AMDGPU::S_XNOR_SAVEEXEC_B32;
231 default:
232 return AMDGPU::INSTRUCTION_LIST_END;
233 }
234}
235
236// These are only terminators to get correct spill code placement during
237// register allocation, so turn them back into normal instructions.
238bool SIOptimizeExecMasking::removeTerminatorBit(MachineInstr &MI) const {
239 switch (MI.getOpcode()) {
240 case AMDGPU::S_MOV_B32_term: {
241 bool RegSrc = MI.getOperand(1).isReg();
242 MI.setDesc(TII->get(RegSrc ? AMDGPU::COPY : AMDGPU::S_MOV_B32));
243 return true;
244 }
245 case AMDGPU::S_MOV_B64_term: {
246 bool RegSrc = MI.getOperand(1).isReg();
247 MI.setDesc(TII->get(RegSrc ? AMDGPU::COPY : AMDGPU::S_MOV_B64));
248 return true;
249 }
250 case AMDGPU::S_XOR_B64_term: {
251 // This is only a terminator to get the correct spill code placement during
252 // register allocation.
253 MI.setDesc(TII->get(AMDGPU::S_XOR_B64));
254 return true;
255 }
256 case AMDGPU::S_XOR_B32_term: {
257 // This is only a terminator to get the correct spill code placement during
258 // register allocation.
259 MI.setDesc(TII->get(AMDGPU::S_XOR_B32));
260 return true;
261 }
262 case AMDGPU::S_OR_B64_term: {
263 // This is only a terminator to get the correct spill code placement during
264 // register allocation.
265 MI.setDesc(TII->get(AMDGPU::S_OR_B64));
266 return true;
267 }
268 case AMDGPU::S_OR_B32_term: {
269 // This is only a terminator to get the correct spill code placement during
270 // register allocation.
271 MI.setDesc(TII->get(AMDGPU::S_OR_B32));
272 return true;
273 }
274 case AMDGPU::S_ANDN2_B64_term: {
275 // This is only a terminator to get the correct spill code placement during
276 // register allocation.
277 MI.setDesc(TII->get(AMDGPU::S_ANDN2_B64));
278 return true;
279 }
280 case AMDGPU::S_ANDN2_B32_term: {
281 // This is only a terminator to get the correct spill code placement during
282 // register allocation.
283 MI.setDesc(TII->get(AMDGPU::S_ANDN2_B32));
284 return true;
285 }
286 case AMDGPU::S_AND_B64_term: {
287 // This is only a terminator to get the correct spill code placement during
288 // register allocation.
289 MI.setDesc(TII->get(AMDGPU::S_AND_B64));
290 return true;
291 }
292 case AMDGPU::S_AND_B32_term: {
293 // This is only a terminator to get the correct spill code placement during
294 // register allocation.
295 MI.setDesc(TII->get(AMDGPU::S_AND_B32));
296 return true;
297 }
298 case AMDGPU::V_CMPX_EQ_U32_nosdst_e32_term:
299 MI.setDesc(TII->get(AMDGPU::V_CMPX_EQ_U32_nosdst_e32));
300 return true;
301 case AMDGPU::V_CMPX_EQ_U64_nosdst_e32_term:
302 MI.setDesc(TII->get(AMDGPU::V_CMPX_EQ_U64_nosdst_e32));
303 return true;
304 default:
305 return false;
306 }
307}
308
309// Turn all pseudoterminators in the block into their equivalent non-terminator
310// instructions. Returns the reverse iterator to the first non-terminator
311// instruction in the block.
313SIOptimizeExecMasking::fixTerminators(MachineBasicBlock &MBB) const {
315
316 bool Seen = false;
318 for (; I != E; ++I) {
319 if (!I->isTerminator())
320 return Seen ? FirstNonTerm : I;
321
322 if (removeTerminatorBit(*I)) {
323 if (!Seen) {
324 FirstNonTerm = I;
325 Seen = true;
326 }
327 }
328 }
329
330 return FirstNonTerm;
331}
332
333MachineBasicBlock::reverse_iterator SIOptimizeExecMasking::findExecCopy(
335 const unsigned InstLimit = 25;
336
337 auto E = MBB.rend();
338 for (unsigned N = 0; N <= InstLimit && I != E; ++I) {
339 if (I->isDebugInstr())
340 continue;
341 ++N;
342
343 Register CopyFromExec = isCopyFromExec(*I);
344 if (CopyFromExec.isValid())
345 return I;
346 }
347
348 return E;
349}
350
351// XXX - Seems LiveRegUnits doesn't work correctly since it will incorrectly
352// report the register as unavailable because a super-register with a lane mask
353// is unavailable.
354static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg) {
355 for (MachineBasicBlock *Succ : MBB.successors()) {
356 if (Succ->isLiveIn(Reg))
357 return true;
358 }
359
360 return false;
361}
362
363// Backwards-iterate from Origin (for n=MaxInstructions iterations) until either
364// the beginning of the BB is reached or Pred evaluates to true - which can be
365// an arbitrary condition based on the current MachineInstr, for instance an
366// target instruction. Breaks prematurely by returning nullptr if one of the
367// registers given in NonModifiableRegs is modified by the current instruction.
368MachineInstr *SIOptimizeExecMasking::findInstrBackwards(
369 MachineInstr &Origin, std::function<bool(MachineInstr *)> Pred,
370 ArrayRef<MCRegister> NonModifiableRegs, MachineInstr *Terminator,
371 SmallVectorImpl<MachineOperand *> *KillFlagCandidates,
372 unsigned MaxInstructions) const {
374 E = Origin.getParent()->rend();
375 unsigned CurrentIteration = 0;
376
377 for (++A; CurrentIteration < MaxInstructions && A != E; ++A) {
378 if (A->isDebugInstr())
379 continue;
380
381 if (Pred(&*A))
382 return &*A;
383
384 for (MCRegister Reg : NonModifiableRegs) {
385 if (A->modifiesRegister(Reg, TRI))
386 return nullptr;
387
388 // Check for kills that appear after the terminator instruction, that
389 // would not be detected by clearKillFlags, since they will cause the
390 // register to be dead at a later place, causing the verifier to fail.
391 // We use the candidates to clear the kill flags later.
392 if (Terminator && KillFlagCandidates && A != Terminator &&
393 A->killsRegister(Reg, TRI)) {
394 for (MachineOperand &MO : A->operands()) {
395 if (MO.isReg() && MO.isKill()) {
396 Register Candidate = MO.getReg();
397 if (Candidate != Reg && TRI->regsOverlap(Candidate, Reg))
398 KillFlagCandidates->push_back(&MO);
399 }
400 }
401 }
402 }
403
404 ++CurrentIteration;
405 }
406
407 return nullptr;
408}
409
410// Determine if a register Reg is not re-defined and still in use
411// in the range (Stop..Start].
412// It does so by backwards calculating liveness from the end of the BB until
413// either Stop or the beginning of the BB is reached.
414// After liveness is calculated, we can determine if Reg is still in use and not
415// defined inbetween the instructions.
416bool SIOptimizeExecMasking::isRegisterInUseBetween(MachineInstr &Stop,
417 MachineInstr &Start,
419 bool UseLiveOuts,
420 bool IgnoreStart) const {
421 LiveRegUnits LR(*TRI);
422 if (UseLiveOuts)
423 LR.addLiveOuts(*Stop.getParent());
424
426
427 if (IgnoreStart)
428 ++A;
429
430 for (; A != Stop.getParent()->rend() && A != Stop; ++A) {
431 if (!A->isDebugInstr())
432 LR.stepBackward(*A);
433 }
434
435 return !LR.available(Reg) || MRI->isReserved(Reg);
436}
437
438// Determine if a register Reg is not re-defined and still in use
439// in the range (Stop..BB.end].
440bool SIOptimizeExecMasking::isRegisterInUseAfter(MachineInstr &Stop,
441 MCRegister Reg) const {
442 return isRegisterInUseBetween(Stop, *Stop.getParent()->rbegin(), Reg, true);
443}
444
445// Optimize sequences emitted for control flow lowering. They are originally
446// emitted as the separate operations because spill code may need to be
447// inserted for the saved copy of exec.
448//
449// x = copy exec
450// z = s_<op>_b64 x, y
451// exec = copy z
452// =>
453// x = s_<op>_saveexec_b64 y
454//
455bool SIOptimizeExecMasking::optimizeExecSequence() {
456 bool Changed = false;
457 for (MachineBasicBlock &MBB : *MF) {
458 MachineBasicBlock::reverse_iterator I = fixTerminators(MBB);
460 if (I == E)
461 continue;
462
463 // It's possible to see other terminator copies after the exec copy. This
464 // can happen if control flow pseudos had their outputs used by phis.
465 Register CopyToExec;
466
467 for (unsigned SearchCount = 0, SearchLimit = 5;
468 I != E && SearchCount < SearchLimit; ++I) {
469 if (I->isDebugInstr())
470 continue;
471 ++SearchCount;
472 CopyToExec = isCopyToExec(*I);
473 if (CopyToExec)
474 break;
475 }
476
477 if (!CopyToExec)
478 continue;
479
480 // Scan backwards to find the def.
481 auto *CopyToExecInst = &*I;
482 auto CopyFromExecInst = findExecCopy(MBB, I);
483 if (CopyFromExecInst == E) {
484 auto PrepareExecInst = next_nodbg(I, E);
485 if (PrepareExecInst == E)
486 continue;
487 // Fold exec = COPY (S_AND_B64 reg, exec) -> exec = S_AND_B64 reg, exec
488 if (CopyToExecInst->getOperand(1).isKill() &&
489 isLogicalOpOnExec(*PrepareExecInst) == CopyToExec) {
490 LLVM_DEBUG(dbgs() << "Fold exec copy: " << *PrepareExecInst);
491
492 PrepareExecInst->getOperand(0).setReg(LMC.ExecReg);
493
494 LLVM_DEBUG(dbgs() << "into: " << *PrepareExecInst << '\n');
495
496 CopyToExecInst->eraseFromParent();
497 Changed = true;
498 } else if (optimizeAndN2WrExecSequence(*CopyToExecInst, CopyToExec)) {
499 Changed = true;
500 }
501
502 continue;
503 }
504
505 if (isLiveOut(MBB, CopyToExec)) {
506 // The copied register is live out and has a second use in another block.
507 LLVM_DEBUG(dbgs() << "Exec copy source register is live out\n");
508 continue;
509 }
510
511 Register CopyFromExec = CopyFromExecInst->getOperand(0).getReg();
512 MachineInstr *SaveExecInst = nullptr;
513 SmallVector<MachineInstr *, 4> OtherUseInsts;
514
516 J = std::next(CopyFromExecInst->getIterator()),
517 JE = I->getIterator();
518 J != JE; ++J) {
519 if (J->isDebugInstr())
520 continue;
521
522 if (SaveExecInst && J->readsRegister(LMC.ExecReg, TRI)) {
523 LLVM_DEBUG(dbgs() << "exec read prevents saveexec: " << *J << '\n');
524 // Make sure this is inserted after any VALU ops that may have been
525 // scheduled in between.
526 SaveExecInst = nullptr;
527 break;
528 }
529
530 bool ReadsCopyFromExec = J->readsRegister(CopyFromExec, TRI);
531
532 if (J->modifiesRegister(CopyToExec, TRI)) {
533 if (SaveExecInst) {
534 LLVM_DEBUG(dbgs() << "Multiple instructions modify "
535 << printReg(CopyToExec, TRI) << '\n');
536 SaveExecInst = nullptr;
537 break;
538 }
539
540 unsigned SaveExecOp = getSaveExecOp(J->getOpcode());
541 if (SaveExecOp == AMDGPU::INSTRUCTION_LIST_END)
542 break;
543
544 if (ReadsCopyFromExec) {
545 SaveExecInst = &*J;
546 LLVM_DEBUG(dbgs() << "Found save exec op: " << *SaveExecInst << '\n');
547 continue;
548 }
549 LLVM_DEBUG(dbgs() << "Instruction does not read exec copy: " << *J
550 << '\n');
551 break;
552 }
553 if (ReadsCopyFromExec && !SaveExecInst) {
554 // Make sure no other instruction is trying to use this copy, before it
555 // will be rewritten by the saveexec, i.e. hasOneUse. There may have
556 // been another use, such as an inserted spill. For example:
557 //
558 // %sgpr0_sgpr1 = COPY %exec
559 // spill %sgpr0_sgpr1
560 // %sgpr2_sgpr3 = S_AND_B64 %sgpr0_sgpr1
561 //
562 LLVM_DEBUG(dbgs() << "Found second use of save inst candidate: " << *J
563 << '\n');
564 break;
565 }
566
567 if (SaveExecInst && J->readsRegister(CopyToExec, TRI)) {
568 assert(SaveExecInst != &*J);
569 OtherUseInsts.push_back(&*J);
570 }
571 }
572
573 if (!SaveExecInst)
574 continue;
575
576 LLVM_DEBUG(dbgs() << "Insert save exec op: " << *SaveExecInst << '\n');
577
578 MachineOperand &Src0 = SaveExecInst->getOperand(1);
579 MachineOperand &Src1 = SaveExecInst->getOperand(2);
580
581 MachineOperand *OtherOp = nullptr;
582
583 if (Src0.isReg() && Src0.getReg() == CopyFromExec) {
584 OtherOp = &Src1;
585 } else if (Src1.isReg() && Src1.getReg() == CopyFromExec) {
586 if (!SaveExecInst->isCommutable())
587 break;
588
589 OtherOp = &Src0;
590 } else
591 llvm_unreachable("unexpected");
592
593 CopyFromExecInst->eraseFromParent();
594
595 auto InsPt = SaveExecInst->getIterator();
596 const DebugLoc &DL = SaveExecInst->getDebugLoc();
597
598 BuildMI(MBB, InsPt, DL, TII->get(getSaveExecOp(SaveExecInst->getOpcode())),
599 CopyFromExec)
600 .addReg(OtherOp->getReg());
601 SaveExecInst->eraseFromParent();
602
603 CopyToExecInst->eraseFromParent();
604
605 for (MachineInstr *OtherInst : OtherUseInsts) {
606 OtherInst->substituteRegister(CopyToExec, LMC.ExecReg,
607 AMDGPU::NoSubRegister, *TRI);
608 }
609
610 Changed = true;
611 }
612
613 return Changed;
614}
615
616bool SIOptimizeExecMasking::blocksAndN2Sink(const MachineInstr &MI,
617 Register Dst) const {
618 for (const MachineOperand &MO : MI.operands()) {
619 if (!MO.isReg())
620 continue;
621 // Any access to Dst would see a stale value once the def sinks past it,
622 // and a use of SCC would see the s_andn2 result.
623 if (TRI->regsOverlap(MO.getReg(), Dst))
624 return true;
625 if (MO.isUse() && MO.getReg() == AMDGPU::SCC)
626 return true;
627 }
628 return false;
629}
630
631// Fold
632//
633// sdst = S_ANDN2_B32 ssrc, exec
634// exec = COPY sdst
635// =>
636// sdst = S_ANDN2_WREXEC_B32 ssrc
637//
638// The waterfall loop emits the two operations separately so that spill code
639// for sdst can be inserted before exec is narrowed.
640bool SIOptimizeExecMasking::optimizeAndN2WrExecSequence(
641 MachineInstr &CopyToExecInst, Register Dst) const {
642 if (!ST->hasNoSdstCMPX() || TII->pseudoToMCOpcode(LMC.AndN2WrExecOpc) == -1)
643 return false;
644
645 MachineBasicBlock &MBB = *CopyToExecInst.getParent();
646
647 // Keep the fused instruction ahead of any trailing debug instructions, so
648 // DBG_VALUEs of Dst stay after its def.
649 MachineBasicBlock::iterator InsertPt = CopyToExecInst.getIterator();
650 if (InsertPt != MBB.begin())
651 InsertPt = std::next(prev_nodbg(InsertPt, MBB.begin()));
652
653 // Scan back for the s_andn2 computing the new exec value. The scheduler may
654 // have moved it away from the exec write, so allow instructions in between
655 // as long as sinking the s_andn2 past them is safe.
656 auto IsAndN2Def = [&](const MachineInstr &MI) {
657 return MI.getOpcode() == LMC.AndN2Opc && MI.getOperand(0).getReg() == Dst;
658 };
659 MachineInstr *AndN2Inst = findInstrBackwards(
660 CopyToExecInst,
661 [&](MachineInstr *Check) {
662 return IsAndN2Def(*Check) || blocksAndN2Sink(*Check, Dst);
663 },
664 /*NonModifiableRegs=*/{});
665 if (!AndN2Inst || !IsAndN2Def(*AndN2Inst))
666 return false;
667
668 const MachineOperand &Src = AndN2Inst->getOperand(1);
669 const MachineOperand &Mask = AndN2Inst->getOperand(2);
670 if (!Src.isReg() || !Mask.isReg() || Mask.getReg() != LMC.ExecReg)
671 return false;
672
673 for (MachineInstr &MI : make_range(
674 std::next(MachineBasicBlock::iterator(AndN2Inst)), InsertPt)) {
675 if (MI.modifiesRegister(Src.getReg(), TRI))
676 return false;
677 }
678
679 // The fused form also clobbers SCC, at the point the s_andn2 is moved to.
680 if (isRegisterInUseAfter(CopyToExecInst, AMDGPU::SCC))
681 return false;
682
683 LLVM_DEBUG(dbgs() << "Fold exec write: " << *AndN2Inst);
684
685 BuildMI(MBB, InsertPt, AndN2Inst->getDebugLoc(), TII->get(LMC.AndN2WrExecOpc),
686 Dst)
687 .addReg(Src.getReg());
688
689 AndN2Inst->eraseFromParent();
690 CopyToExecInst.eraseFromParent();
691 return true;
692}
693
694// Inserts the optimized s_mov_b32 / v_cmpx sequence based on the
695// operands extracted from a v_cmp ..., s_and_saveexec pattern.
696bool SIOptimizeExecMasking::optimizeVCMPSaveExecSequence(
697 MachineInstr &SaveExecInstr, MachineInstr &VCmp) const {
698 const int NewOpcode = AMDGPU::getVCMPXOpFromVCMP(VCmp.getOpcode());
699
700 if (NewOpcode == -1)
701 return false;
702
703 MachineOperand *Src0 = TII->getNamedOperand(VCmp, AMDGPU::OpName::src0);
704 MachineOperand *Src1 = TII->getNamedOperand(VCmp, AMDGPU::OpName::src1);
705
706 Register MoveDest = SaveExecInstr.getOperand(0).getReg();
707
708 MachineBasicBlock::instr_iterator InsertPosIt = SaveExecInstr.getIterator();
709 if (!SaveExecInstr.uses().empty()) {
710 bool IsSGPR32 = TRI->getRegSizeInBits(MoveDest, *MRI) == 32;
711 unsigned MovOpcode = IsSGPR32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
712 BuildMI(*SaveExecInstr.getParent(), InsertPosIt,
713 SaveExecInstr.getDebugLoc(), TII->get(MovOpcode), MoveDest)
714 .addReg(LMC.ExecReg);
715 }
716
717 // Omit dst as V_CMPX is implicitly writing to EXEC.
718 // Add dummy src and clamp modifiers, if needed.
719 auto Builder = BuildMI(*VCmp.getParent(), std::next(InsertPosIt),
720 VCmp.getDebugLoc(), TII->get(NewOpcode));
721
722 auto TryAddImmediateValueFromNamedOperand =
723 [&](AMDGPU::OpName OperandName) -> void {
724 if (auto *Mod = TII->getNamedOperand(VCmp, OperandName))
725 Builder.addImm(Mod->getImm());
726 };
727
728 TryAddImmediateValueFromNamedOperand(AMDGPU::OpName::src0_modifiers);
729 Builder.add(*Src0);
730
731 TryAddImmediateValueFromNamedOperand(AMDGPU::OpName::src1_modifiers);
732 Builder.add(*Src1);
733
734 TryAddImmediateValueFromNamedOperand(AMDGPU::OpName::clamp);
735
736 TryAddImmediateValueFromNamedOperand(AMDGPU::OpName::op_sel);
737
738 // The kill flags may no longer be correct.
739 if (Src0->isReg())
740 MRI->clearKillFlags(Src0->getReg());
741 if (Src1->isReg())
742 MRI->clearKillFlags(Src1->getReg());
743
744 for (MachineOperand *MO : KillFlagCandidates)
745 MO->setIsKill(false);
746
747 SaveExecInstr.eraseFromParent();
748 VCmp.eraseFromParent();
749
750 return true;
751}
752
753// Record (on GFX10.3 and later) occurences of
754// v_cmp_* SGPR, IMM, VGPR
755// s_and_saveexec_b32 EXEC_SGPR_DEST, SGPR
756// to be replaced with
757// s_mov_b32 EXEC_SGPR_DEST, exec_lo
758// v_cmpx_* IMM, VGPR
759// to reduce pipeline stalls.
760void SIOptimizeExecMasking::tryRecordVCmpxAndSaveexecSequence(
761 MachineInstr &MI) {
762 if (!ST->hasGFX10_3Insts())
763 return;
764
765 if (MI.getOpcode() != LMC.AndSaveExecOpc)
766 return;
767
768 Register SaveExecDest = MI.getOperand(0).getReg();
769 if (!TRI->isSGPRReg(*MRI, SaveExecDest))
770 return;
771
772 MachineOperand *SaveExecSrc0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
773 if (!SaveExecSrc0->isReg())
774 return;
775
776 // Tries to find a possibility to optimize a v_cmp ..., s_and_saveexec
777 // sequence by looking at an instance of an s_and_saveexec instruction.
778 // Returns a pointer to the v_cmp instruction if it is safe to replace the
779 // sequence (see the conditions in the function body). This is after register
780 // allocation, so some checks on operand dependencies need to be considered.
781 MachineInstr *VCmp = nullptr;
782
783 // Try to find the last v_cmp instruction that defs the saveexec input
784 // operand without any write to Exec or the saveexec input operand inbetween.
785 VCmp = findInstrBackwards(
786 MI,
787 [&](MachineInstr *Check) {
788 return AMDGPU::getVCMPXOpFromVCMP(Check->getOpcode()) != -1 &&
789 Check->modifiesRegister(SaveExecSrc0->getReg(), TRI);
790 },
791 {LMC.ExecReg, SaveExecSrc0->getReg()});
792
793 if (!VCmp)
794 return;
795
796 MachineOperand *VCmpDest = TII->getNamedOperand(*VCmp, AMDGPU::OpName::sdst);
797 assert(VCmpDest && "Should have an sdst operand!");
798
799 // Check if any of the v_cmp source operands is written by the saveexec.
800 MachineOperand *Src0 = TII->getNamedOperand(*VCmp, AMDGPU::OpName::src0);
801 if (Src0->isReg() && TRI->isSGPRReg(*MRI, Src0->getReg()) &&
802 MI.modifiesRegister(Src0->getReg(), TRI))
803 return;
804
805 MachineOperand *Src1 = TII->getNamedOperand(*VCmp, AMDGPU::OpName::src1);
806 if (Src1->isReg() && TRI->isSGPRReg(*MRI, Src1->getReg()) &&
807 MI.modifiesRegister(Src1->getReg(), TRI))
808 return;
809
810 // Don't do the transformation if the destination operand is included in
811 // it's MBB Live-outs, meaning it's used in any of its successors, leading
812 // to incorrect code if the v_cmp and therefore the def of
813 // the dest operand is removed.
814 if (isLiveOut(*VCmp->getParent(), VCmpDest->getReg()))
815 return;
816
817 // If the v_cmp target is in use between v_cmp and s_and_saveexec or after the
818 // s_and_saveexec, skip the optimization.
819 if (isRegisterInUseBetween(*VCmp, MI, VCmpDest->getReg(), false, true) ||
820 isRegisterInUseAfter(MI, VCmpDest->getReg()))
821 return;
822
823 // Try to determine if there is a write to any of the VCmp
824 // operands between the saveexec and the vcmp.
825 // If yes, additional VGPR spilling might need to be inserted. In this case,
826 // it's not worth replacing the instruction sequence.
828 if (Src0->isReg())
829 NonDefRegs.push_back(Src0->getReg());
830
831 if (Src1->isReg())
832 NonDefRegs.push_back(Src1->getReg());
833
834 if (!findInstrBackwards(
835 MI, [&](MachineInstr *Check) { return Check == VCmp; }, NonDefRegs,
836 VCmp, &KillFlagCandidates))
837 return;
838
839 if (VCmp)
840 SaveExecVCmpMapping[&MI] = VCmp;
841}
842
843// Record occurences of
844// s_or_saveexec s_o, s_i
845// s_xor exec, exec, s_o
846// to be replaced with
847// s_andn2_saveexec s_o, s_i.
848void SIOptimizeExecMasking::tryRecordOrSaveexecXorSequence(MachineInstr &MI) {
849 if (MI.getOpcode() == LMC.XorOpc && &MI != &MI.getParent()->front()) {
850 const MachineOperand &XorDst = MI.getOperand(0);
851 const MachineOperand &XorSrc0 = MI.getOperand(1);
852 const MachineOperand &XorSrc1 = MI.getOperand(2);
853
854 if (XorDst.isReg() && XorDst.getReg() == LMC.ExecReg && XorSrc0.isReg() &&
855 XorSrc1.isReg() &&
856 (XorSrc0.getReg() == LMC.ExecReg || XorSrc1.getReg() == LMC.ExecReg)) {
857
858 // Peek at the previous non-debug instruction and check if this is a
859 // relevant s_or_saveexec instruction.
860 auto It = prev_nodbg(MI.getIterator(), MI.getParent()->instr_begin());
861 MachineInstr &PossibleOrSaveexec = *It;
862 if (PossibleOrSaveexec.getOpcode() != LMC.OrSaveExecOpc)
863 return;
864
865 const MachineOperand &OrDst = PossibleOrSaveexec.getOperand(0);
866 const MachineOperand &OrSrc0 = PossibleOrSaveexec.getOperand(1);
867 if (OrDst.isReg() && OrSrc0.isReg()) {
868 if ((XorSrc0.getReg() == LMC.ExecReg &&
869 XorSrc1.getReg() == OrDst.getReg()) ||
870 (XorSrc0.getReg() == OrDst.getReg() &&
871 XorSrc1.getReg() == LMC.ExecReg)) {
872 OrXors.emplace_back(&PossibleOrSaveexec, &MI);
873 }
874 }
875 }
876 }
877}
878
879bool SIOptimizeExecMasking::optimizeOrSaveexecXorSequences() {
880 if (OrXors.empty()) {
881 return false;
882 }
883
884 bool Changed = false;
885
886 for (const auto &Pair : OrXors) {
887 MachineInstr *Or = nullptr;
888 MachineInstr *Xor = nullptr;
889 std::tie(Or, Xor) = Pair;
890 BuildMI(*Or->getParent(), Or->getIterator(), Or->getDebugLoc(),
891 TII->get(LMC.AndN2SaveExecOpc), Or->getOperand(0).getReg())
892 .addReg(Or->getOperand(1).getReg());
893
894 Or->eraseFromParent();
895 Xor->eraseFromParent();
896
897 Changed = true;
898 }
899
900 return Changed;
901}
902
903bool SIOptimizeExecMaskingLegacy::runOnMachineFunction(MachineFunction &MF) {
904 if (skipFunction(MF.getFunction()))
905 return false;
906
907 return SIOptimizeExecMasking(&MF).run();
908}
909
910bool SIOptimizeExecMasking::run() {
911 bool Changed = optimizeExecSequence();
912
913 OrXors.clear();
914 SaveExecVCmpMapping.clear();
915 KillFlagCandidates.clear();
916 static unsigned SearchWindow = 10;
917 for (MachineBasicBlock &MBB : *MF) {
918 unsigned SearchCount = 0;
919
920 for (auto &MI : llvm::reverse(MBB)) {
921 if (MI.isDebugInstr())
922 continue;
923
924 if (SearchCount >= SearchWindow) {
925 break;
926 }
927
928 tryRecordOrSaveexecXorSequence(MI);
929 tryRecordVCmpxAndSaveexecSequence(MI);
930
931 if (MI.modifiesRegister(LMC.ExecReg, TRI)) {
932 break;
933 }
934
935 ++SearchCount;
936 }
937 }
938
939 Changed |= optimizeOrSaveexecXorSequences();
940 for (const auto &Entry : SaveExecVCmpMapping) {
941 MachineInstr *SaveExecInstr = Entry.getFirst();
942 MachineInstr *VCmpInstr = Entry.getSecond();
943
944 Changed |= optimizeVCMPSaveExecSequence(*SaveExecInstr, *VCmpInstr);
945 }
946
947 return Changed;
948}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
A set of register units.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
static unsigned getSaveExecOp(unsigned Opc)
static Register isLogicalOpOnExec(const MachineInstr &MI)
If MI is a logical operation on an exec value, return the register copied to.
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
Interface definition for SIRegisterInfo.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const LaneMaskConstants & get(const GCNSubtarget &ST)
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A debug info location.
Definition DebugLoc.h:126
A set of register units used to track register liveness.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
reverse_iterator rbegin()
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
bool isCommutable(QueryType Type=IgnoreBundle) const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z,...
mop_range uses()
Returns all operands which may be register uses.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_READONLY int32_t getVCMPXOpFromVCMP(uint32_t Opcode)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
std::reverse_iterator< iterator > rend() const
Definition BasicBlock.h:96
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
char & SIOptimizeExecMaskingLegacyID
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ Xor
Bitwise or logical XOR of integers.
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
#define N