LLVM 22.0.0git
SILowerControlFlow.cpp
Go to the documentation of this file.
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 writing to the 64-bit EXEC register (each bit corresponds to a
17/// single vector ALU). Typically, for predicates, a vector ALU will write
18/// to its bit of the VCC register (like EXEC VCC is 64-bits, one for each
19/// Vector ALU) and then the ScalarALU will AND the VCC register with the
20/// EXEC to update the predicates.
21///
22/// For example:
23/// %vcc = V_CMP_GT_F32 %vgpr1, %vgpr2
24/// %sgpr0 = SI_IF %vcc
25/// %vgpr0 = V_ADD_F32 %vgpr0, %vgpr0
26/// %sgpr0 = SI_ELSE %sgpr0
27/// %vgpr0 = V_SUB_F32 %vgpr0, %vgpr0
28/// SI_END_CF %sgpr0
29///
30/// becomes:
31///
32/// %sgpr0 = S_AND_SAVEEXEC_B64 %vcc // Save and update the exec mask
33/// %sgpr0 = S_XOR_B64 %sgpr0, %exec // Clear live bits from saved exec mask
34/// S_CBRANCH_EXECZ label0 // This instruction is an optional
35/// // optimization which allows us to
36/// // branch if all the bits of
37/// // EXEC are zero.
38/// %vgpr0 = V_ADD_F32 %vgpr0, %vgpr0 // Do the IF block of the branch
39///
40/// label0:
41/// %sgpr0 = S_OR_SAVEEXEC_B64 %sgpr0 // Restore the exec mask for the Then
42/// // block
43/// %exec = S_XOR_B64 %sgpr0, %exec // Update the exec mask
44/// S_CBRANCH_EXECZ label1 // Use our branch optimization
45/// // instruction again.
46/// %vgpr0 = V_SUB_F32 %vgpr0, %vgpr // Do the ELSE block
47/// label1:
48/// %exec = S_OR_B64 %exec, %sgpr0 // Re-enable saved exec mask bits
49//===----------------------------------------------------------------------===//
50
51#include "SILowerControlFlow.h"
52#include "AMDGPU.h"
53#include "AMDGPULaneMaskUtils.h"
54#include "GCNSubtarget.h"
56#include "llvm/ADT/SmallSet.h"
63
64using namespace llvm;
65
66#define DEBUG_TYPE "si-lower-control-flow"
67
68static cl::opt<bool>
69RemoveRedundantEndcf("amdgpu-remove-redundant-endcf",
71
72namespace {
73
74class SILowerControlFlow {
75private:
76 const SIRegisterInfo *TRI = nullptr;
77 const SIInstrInfo *TII = nullptr;
78 LiveIntervals *LIS = nullptr;
79 LiveVariables *LV = nullptr;
80 MachineDominatorTree *MDT = nullptr;
81 MachinePostDominatorTree *PDT = nullptr;
82 MachineRegisterInfo *MRI = nullptr;
83 SetVector<MachineInstr*> LoweredEndCf;
84 DenseSet<Register> LoweredIf;
86 SmallSet<Register, 8> RecomputeRegs;
87
88 const TargetRegisterClass *BoolRC = nullptr;
90
91 bool EnableOptimizeEndCf = false;
92
93 bool hasKill(const MachineBasicBlock *Begin, const MachineBasicBlock *End);
94
95 void emitIf(MachineInstr &MI);
96 void emitElse(MachineInstr &MI);
97 void emitIfBreak(MachineInstr &MI);
98 void emitLoop(MachineInstr &MI);
99
100 MachineBasicBlock *emitEndCf(MachineInstr &MI);
101
102 void findMaskOperands(MachineInstr &MI, unsigned OpNo,
104
105 void combineMasks(MachineInstr &MI);
106
107 bool removeMBBifRedundant(MachineBasicBlock &MBB);
108
110
111 // Skip to the next instruction, ignoring debug instructions, and trivial
112 // block boundaries (blocks that have one (typically fallthrough) successor,
113 // and the successor has one predecessor.
115 skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
117
118 /// Find the insertion point for a new conditional branch.
120 skipToUncondBrOrEnd(MachineBasicBlock &MBB,
122 assert(I->isTerminator());
123
124 // FIXME: What if we had multiple pre-existing conditional branches?
126 while (I != End && !I->isUnconditionalBranch())
127 ++I;
128 return I;
129 }
130
131 // Remove redundant SI_END_CF instructions.
132 void optimizeEndCf();
133
134public:
135 SILowerControlFlow(const GCNSubtarget *ST, LiveIntervals *LIS,
136 LiveVariables *LV, MachineDominatorTree *MDT,
137 MachinePostDominatorTree *PDT)
138 : LIS(LIS), LV(LV), MDT(MDT), PDT(PDT),
139 LMC(AMDGPU::LaneMaskConstants::get(*ST)) {}
140 bool run(MachineFunction &MF);
141};
142
143class SILowerControlFlowLegacy : public MachineFunctionPass {
144public:
145 static char ID;
146
147 SILowerControlFlowLegacy() : MachineFunctionPass(ID) {}
148
149 bool runOnMachineFunction(MachineFunction &MF) override;
150
151 StringRef getPassName() const override {
152 return "SI Lower control flow pseudo instructions";
153 }
154
155 void getAnalysisUsage(AnalysisUsage &AU) const override {
156 AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
157 // Should preserve the same set that TwoAddressInstructions does.
158 AU.addPreserved<MachineDominatorTreeWrapperPass>();
159 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
160 AU.addPreserved<SlotIndexesWrapperPass>();
161 AU.addPreserved<LiveIntervalsWrapperPass>();
162 AU.addPreserved<LiveVariablesWrapperPass>();
164 }
165};
166
167} // end anonymous namespace
168
169char SILowerControlFlowLegacy::ID = 0;
170
171INITIALIZE_PASS(SILowerControlFlowLegacy, DEBUG_TYPE, "SI lower control flow",
172 false, false)
173
174static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
175 MachineOperand &ImpDefSCC = MI.getOperand(3);
176 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
177
178 ImpDefSCC.setIsDead(IsDead);
179}
180
181char &llvm::SILowerControlFlowLegacyID = SILowerControlFlowLegacy::ID;
182
183bool SILowerControlFlow::hasKill(const MachineBasicBlock *Begin,
184 const MachineBasicBlock *End) {
187
188 while (!Worklist.empty()) {
189 MachineBasicBlock *MBB = Worklist.pop_back_val();
190
191 if (MBB == End || !Visited.insert(MBB).second)
192 continue;
193 if (KillBlocks.contains(MBB))
194 return true;
195
196 Worklist.append(MBB->succ_begin(), MBB->succ_end());
197 }
198
199 return false;
200}
201
202static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
203 Register SaveExecReg = MI.getOperand(0).getReg();
204 auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
205
206 if (U == MRI->use_instr_nodbg_end() ||
207 std::next(U) != MRI->use_instr_nodbg_end() ||
208 U->getOpcode() != AMDGPU::SI_END_CF)
209 return false;
210
211 return true;
212}
213
214void SILowerControlFlow::emitIf(MachineInstr &MI) {
215 MachineBasicBlock &MBB = *MI.getParent();
216 const DebugLoc &DL = MI.getDebugLoc();
218 Register SaveExecReg = MI.getOperand(0).getReg();
219 MachineOperand& Cond = MI.getOperand(1);
220 assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
221
222 MachineOperand &ImpDefSCC = MI.getOperand(4);
223 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
224
225 // If there is only one use of save exec register and that use is SI_END_CF,
226 // we can optimize SI_IF by returning the full saved exec mask instead of
227 // just cleared bits.
228 bool SimpleIf = isSimpleIf(MI, MRI);
229
230 if (SimpleIf) {
231 // Check for SI_KILL_*_TERMINATOR on path from if to endif.
232 // if there is any such terminator simplifications are not safe.
233 auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
234 SimpleIf = !hasKill(MI.getParent(), UseMI->getParent());
235 }
236
237 // Add an implicit def of exec to discourage scheduling VALU after this which
238 // will interfere with trying to form s_and_saveexec_b64 later.
239 Register CopyReg = SimpleIf ? SaveExecReg
240 : MRI->createVirtualRegister(BoolRC);
241 MachineInstr *CopyExec = BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
242 .addReg(LMC.ExecReg)
244 LoweredIf.insert(CopyReg);
245
246 Register Tmp = MRI->createVirtualRegister(BoolRC);
247
248 MachineInstr *And =
249 BuildMI(MBB, I, DL, TII->get(LMC.AndOpc), Tmp).addReg(CopyReg).add(Cond);
250 if (LV)
251 LV->replaceKillInstruction(Cond.getReg(), MI, *And);
252
253 setImpSCCDefDead(*And, true);
254
255 MachineInstr *Xor = nullptr;
256 if (!SimpleIf) {
257 Xor = BuildMI(MBB, I, DL, TII->get(LMC.XorOpc), SaveExecReg)
258 .addReg(Tmp)
259 .addReg(CopyReg);
260 setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
261 }
262
263 // Use a copy that is a terminator to get correct spill code placement it with
264 // fast regalloc.
265 MachineInstr *SetExec =
266 BuildMI(MBB, I, DL, TII->get(LMC.MovTermOpc), LMC.ExecReg)
267 .addReg(Tmp, RegState::Kill);
268 if (LV)
269 LV->getVarInfo(Tmp).Kills.push_back(SetExec);
270
271 // Skip ahead to the unconditional branch in case there are other terminators
272 // present.
273 I = skipToUncondBrOrEnd(MBB, I);
274
275 // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
276 // during SIPreEmitPeephole.
277 MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
278 .add(MI.getOperand(2));
279
280 if (!LIS) {
281 MI.eraseFromParent();
282 return;
283 }
284
285 LIS->InsertMachineInstrInMaps(*CopyExec);
286
287 // Replace with and so we don't need to fix the live interval for condition
288 // register.
290
291 if (!SimpleIf)
293 LIS->InsertMachineInstrInMaps(*SetExec);
294 LIS->InsertMachineInstrInMaps(*NewBr);
295
296 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
297 MI.eraseFromParent();
298
299 // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
300 // hard to add another def here but I'm not sure how to correctly update the
301 // valno.
302 RecomputeRegs.insert(SaveExecReg);
304 if (!SimpleIf)
306}
307
308void SILowerControlFlow::emitElse(MachineInstr &MI) {
309 MachineBasicBlock &MBB = *MI.getParent();
310 const DebugLoc &DL = MI.getDebugLoc();
311
312 Register DstReg = MI.getOperand(0).getReg();
313 Register SrcReg = MI.getOperand(1).getReg();
314
316
317 // This must be inserted before phis and any spill code inserted before the
318 // else.
319 Register SaveReg = MRI->createVirtualRegister(BoolRC);
320 MachineInstr *OrSaveExec =
321 BuildMI(MBB, Start, DL, TII->get(LMC.OrSaveExecOpc), SaveReg)
322 .add(MI.getOperand(1)); // Saved EXEC
323 if (LV)
324 LV->replaceKillInstruction(SrcReg, MI, *OrSaveExec);
325
326 MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
327
329
330 // This accounts for any modification of the EXEC mask within the block and
331 // can be optimized out pre-RA when not required.
332 MachineInstr *And = BuildMI(MBB, ElsePt, DL, TII->get(LMC.AndOpc), DstReg)
333 .addReg(LMC.ExecReg)
334 .addReg(SaveReg);
335
336 MachineInstr *Xor =
337 BuildMI(MBB, ElsePt, DL, TII->get(LMC.XorTermOpc), LMC.ExecReg)
338 .addReg(LMC.ExecReg)
339 .addReg(DstReg);
340
341 // Skip ahead to the unconditional branch in case there are other terminators
342 // present.
343 ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
344
345 MachineInstr *Branch =
346 BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
347 .addMBB(DestBB);
348
349 if (!LIS) {
350 MI.eraseFromParent();
351 return;
352 }
353
355 MI.eraseFromParent();
356
357 LIS->InsertMachineInstrInMaps(*OrSaveExec);
359
361 LIS->InsertMachineInstrInMaps(*Branch);
362
363 RecomputeRegs.insert(SrcReg);
364 RecomputeRegs.insert(DstReg);
366
367 // Let this be recomputed.
368 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
369}
370
371void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
372 MachineBasicBlock &MBB = *MI.getParent();
373 const DebugLoc &DL = MI.getDebugLoc();
374 auto Dst = MI.getOperand(0).getReg();
375
376 // Skip ANDing with exec if the break condition is already masked by exec
377 // because it is a V_CMP in the same basic block. (We know the break
378 // condition operand was an i1 in IR, so if it is a VALU instruction it must
379 // be one with a carry-out.)
380 bool SkipAnding = false;
381 if (MI.getOperand(1).isReg()) {
382 if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
383 SkipAnding = Def->getParent() == MI.getParent()
384 && SIInstrInfo::isVALU(*Def);
385 }
386 }
387
388 // AND the break condition operand with exec, then OR that into the "loop
389 // exit" mask.
390 MachineInstr *And = nullptr, *Or = nullptr;
391 Register AndReg;
392 if (!SkipAnding) {
393 AndReg = MRI->createVirtualRegister(BoolRC);
394 And = BuildMI(MBB, &MI, DL, TII->get(LMC.AndOpc), AndReg)
395 .addReg(LMC.ExecReg)
396 .add(MI.getOperand(1));
397 if (LV)
398 LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *And);
399 Or = BuildMI(MBB, &MI, DL, TII->get(LMC.OrOpc), Dst)
400 .addReg(AndReg)
401 .add(MI.getOperand(2));
402 } else {
403 Or = BuildMI(MBB, &MI, DL, TII->get(LMC.OrOpc), Dst)
404 .add(MI.getOperand(1))
405 .add(MI.getOperand(2));
406 if (LV)
407 LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *Or);
408 }
409 if (LV)
410 LV->replaceKillInstruction(MI.getOperand(2).getReg(), MI, *Or);
411
412 if (LIS) {
414 if (And) {
415 // Read of original operand 1 is on And now not Or.
416 RecomputeRegs.insert(And->getOperand(2).getReg());
419 }
420 }
421
422 MI.eraseFromParent();
423}
424
425void SILowerControlFlow::emitLoop(MachineInstr &MI) {
426 MachineBasicBlock &MBB = *MI.getParent();
427 const DebugLoc &DL = MI.getDebugLoc();
428
429 MachineInstr *AndN2 =
430 BuildMI(MBB, &MI, DL, TII->get(LMC.AndN2TermOpc), LMC.ExecReg)
431 .addReg(LMC.ExecReg)
432 .add(MI.getOperand(0));
433 if (LV)
434 LV->replaceKillInstruction(MI.getOperand(0).getReg(), MI, *AndN2);
435
436 auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
437 MachineInstr *Branch =
438 BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
439 .add(MI.getOperand(1));
440
441 if (LIS) {
442 RecomputeRegs.insert(MI.getOperand(0).getReg());
443 LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
444 LIS->InsertMachineInstrInMaps(*Branch);
445 }
446
447 MI.eraseFromParent();
448}
449
451SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
452 MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
453
454 SmallPtrSet<const MachineBasicBlock *, 4> Visited;
455 MachineBasicBlock *B = &MBB;
456 do {
457 if (!Visited.insert(B).second)
458 return MBB.end();
459
460 auto E = B->end();
461 for ( ; It != E; ++It) {
462 if (TII->mayReadEXEC(*MRI, *It))
463 break;
464 }
465
466 if (It != E)
467 return It;
468
469 if (B->succ_size() != 1)
470 return MBB.end();
471
472 // If there is one trivial successor, advance to the next block.
473 MachineBasicBlock *Succ = *B->succ_begin();
474
475 It = Succ->begin();
476 B = Succ;
477 } while (true);
478}
479
480MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &MI) {
481 MachineBasicBlock &MBB = *MI.getParent();
482 const DebugLoc &DL = MI.getDebugLoc();
483
485
486 // If we have instructions that aren't prolog instructions, split the block
487 // and emit a terminator instruction. This ensures correct spill placement.
488 // FIXME: We should unconditionally split the block here.
489 bool NeedBlockSplit = false;
490 Register DataReg = MI.getOperand(0).getReg();
491 for (MachineBasicBlock::iterator I = InsPt, E = MI.getIterator();
492 I != E; ++I) {
493 if (I->modifiesRegister(DataReg, TRI)) {
494 NeedBlockSplit = true;
495 break;
496 }
497 }
498
499 unsigned Opcode = LMC.OrOpc;
500 MachineBasicBlock *SplitBB = &MBB;
501 if (NeedBlockSplit) {
502 SplitBB = MBB.splitAt(MI, /*UpdateLiveIns*/true, LIS);
503 if (SplitBB != &MBB && (MDT || PDT)) {
504 using DomTreeT = DomTreeBase<MachineBasicBlock>;
506 for (MachineBasicBlock *Succ : SplitBB->successors()) {
507 DTUpdates.push_back({DomTreeT::Insert, SplitBB, Succ});
508 DTUpdates.push_back({DomTreeT::Delete, &MBB, Succ});
509 }
510 DTUpdates.push_back({DomTreeT::Insert, &MBB, SplitBB});
511 if (MDT)
512 MDT->applyUpdates(DTUpdates);
513 if (PDT)
514 PDT->applyUpdates(DTUpdates);
515 }
516 Opcode = LMC.OrTermOpc;
517 InsPt = MI;
518 }
519
520 MachineInstr *NewMI = BuildMI(MBB, InsPt, DL, TII->get(Opcode), LMC.ExecReg)
521 .addReg(LMC.ExecReg)
522 .add(MI.getOperand(0));
523 if (LV) {
524 LV->replaceKillInstruction(DataReg, MI, *NewMI);
525
526 if (SplitBB != &MBB) {
527 // Track the set of registers defined in the original block so we don't
528 // accidentally add the original block to AliveBlocks. AliveBlocks only
529 // includes blocks which are live through, which excludes live outs and
530 // local defs.
531 DenseSet<Register> DefInOrigBlock;
532
533 for (MachineBasicBlock *BlockPiece : {&MBB, SplitBB}) {
534 for (MachineInstr &X : *BlockPiece) {
535 for (MachineOperand &Op : X.all_defs()) {
536 if (Op.getReg().isVirtual())
537 DefInOrigBlock.insert(Op.getReg());
538 }
539 }
540 }
541
542 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
543 Register Reg = Register::index2VirtReg(i);
544 LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
545
546 if (VI.AliveBlocks.test(MBB.getNumber()))
547 VI.AliveBlocks.set(SplitBB->getNumber());
548 else {
549 for (MachineInstr *Kill : VI.Kills) {
550 if (Kill->getParent() == SplitBB && !DefInOrigBlock.contains(Reg))
551 VI.AliveBlocks.set(MBB.getNumber());
552 }
553 }
554 }
555 }
556 }
557
558 LoweredEndCf.insert(NewMI);
559
560 if (LIS)
561 LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
562
563 MI.eraseFromParent();
564
565 if (LIS)
566 LIS->handleMove(*NewMI);
567 return SplitBB;
568}
569
570// Returns replace operands for a logical operation, either single result
571// for exec or two operands if source was another equivalent operation.
572void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
573 SmallVectorImpl<MachineOperand> &Src) const {
574 MachineOperand &Op = MI.getOperand(OpNo);
575 if (!Op.isReg() || !Op.getReg().isVirtual()) {
576 Src.push_back(Op);
577 return;
578 }
579
580 MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
581 if (!Def || Def->getParent() != MI.getParent() ||
582 !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
583 return;
584
585 // Make sure we do not modify exec between def and use.
586 // A copy with implicitly defined exec inserted earlier is an exclusion, it
587 // does not really modify exec.
588 for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
589 if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
590 !(I->isCopy() && I->getOperand(0).getReg() != LMC.ExecReg))
591 return;
592
593 for (const auto &SrcOp : Def->explicit_operands())
594 if (SrcOp.isReg() && SrcOp.isUse() &&
595 (SrcOp.getReg().isVirtual() || SrcOp.getReg() == LMC.ExecReg))
596 Src.push_back(SrcOp);
597}
598
599// Search and combine pairs of equivalent instructions, like
600// S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
601// S_OR_B64 x, (S_OR_B64 x, y) => S_OR_B64 x, y
602// One of the operands is exec mask.
603void SILowerControlFlow::combineMasks(MachineInstr &MI) {
604 assert(MI.getNumExplicitOperands() == 3);
606 unsigned OpToReplace = 1;
607 findMaskOperands(MI, 1, Ops);
608 if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
609 findMaskOperands(MI, 2, Ops);
610 if (Ops.size() != 3) return;
611
612 unsigned UniqueOpndIdx;
613 if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
614 else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
615 else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
616 else return;
617
618 Register Reg = MI.getOperand(OpToReplace).getReg();
619 MI.removeOperand(OpToReplace);
620 MI.addOperand(Ops[UniqueOpndIdx]);
621 if (MRI->use_empty(Reg))
622 MRI->getUniqueVRegDef(Reg)->eraseFromParent();
623}
624
625void SILowerControlFlow::optimizeEndCf() {
626 // If the only instruction immediately following this END_CF is another
627 // END_CF in the only successor we can avoid emitting exec mask restore here.
628 if (!EnableOptimizeEndCf)
629 return;
630
631 for (MachineInstr *MI : reverse(LoweredEndCf)) {
632 MachineBasicBlock &MBB = *MI->getParent();
633 auto Next =
634 skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
635 if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
636 continue;
637 // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
638 // If that belongs to SI_ELSE then saved mask has an inverted value.
639 Register SavedExec
640 = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
641 assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
642
643 const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
644 if (Def && LoweredIf.count(SavedExec)) {
645 LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
646 if (LIS)
649 if (LV)
650 Reg = TII->getNamedOperand(*MI, AMDGPU::OpName::src1)->getReg();
651 MI->eraseFromParent();
652 if (LV)
654 removeMBBifRedundant(MBB);
655 }
656 }
657}
658
659MachineBasicBlock *SILowerControlFlow::process(MachineInstr &MI) {
660 MachineBasicBlock &MBB = *MI.getParent();
662 MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
663
664 MachineBasicBlock *SplitBB = &MBB;
665
666 switch (MI.getOpcode()) {
667 case AMDGPU::SI_IF:
668 emitIf(MI);
669 break;
670
671 case AMDGPU::SI_ELSE:
672 emitElse(MI);
673 break;
674
675 case AMDGPU::SI_IF_BREAK:
676 emitIfBreak(MI);
677 break;
678
679 case AMDGPU::SI_LOOP:
680 emitLoop(MI);
681 break;
682
683 case AMDGPU::SI_WATERFALL_LOOP:
684 MI.setDesc(TII->get(AMDGPU::S_CBRANCH_EXECNZ));
685 break;
686
687 case AMDGPU::SI_END_CF:
688 SplitBB = emitEndCf(MI);
689 break;
690
691 default:
692 assert(false && "Attempt to process unsupported instruction");
693 break;
694 }
695
697 for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
698 Next = std::next(I);
699 MachineInstr &MaskMI = *I;
700 switch (MaskMI.getOpcode()) {
701 case AMDGPU::S_AND_B64:
702 case AMDGPU::S_OR_B64:
703 case AMDGPU::S_AND_B32:
704 case AMDGPU::S_OR_B32:
705 // Cleanup bit manipulations on exec mask
706 combineMasks(MaskMI);
707 break;
708 default:
709 I = MBB.end();
710 break;
711 }
712 }
713
714 return SplitBB;
715}
716
717bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &MBB) {
718 for (auto &I : MBB.instrs()) {
719 if (!I.isDebugInstr() && !I.isUnconditionalBranch())
720 return false;
721 }
722
723 assert(MBB.succ_size() == 1 && "MBB has more than one successor");
724
725 MachineBasicBlock *Succ = *MBB.succ_begin();
726 MachineBasicBlock *FallThrough = nullptr;
727
728 using DomTreeT = DomTreeBase<MachineBasicBlock>;
730
731 while (!MBB.predecessors().empty()) {
732 MachineBasicBlock *P = *MBB.pred_begin();
733 if (P->getFallThrough(false) == &MBB)
734 FallThrough = P;
736 DTUpdates.push_back({DomTreeT::Insert, P, Succ});
737 DTUpdates.push_back({DomTreeT::Delete, P, &MBB});
738 }
739 MBB.removeSuccessor(Succ);
740 if (LIS) {
741 for (auto &I : MBB.instrs())
743 }
744 if (MDT)
745 MDT->applyUpdates(DTUpdates);
746 if (PDT)
747 PDT->applyUpdates(DTUpdates);
748
749 MBB.clear();
751 if (FallThrough && !FallThrough->isLayoutSuccessor(Succ)) {
752 // Note: we cannot update block layout and preserve live intervals;
753 // hence we must insert a branch.
754 MachineInstr *BranchMI = BuildMI(*FallThrough, FallThrough->end(),
755 FallThrough->findBranchDebugLoc(), TII->get(AMDGPU::S_BRANCH))
756 .addMBB(Succ);
757 if (LIS)
758 LIS->InsertMachineInstrInMaps(*BranchMI);
759 }
760
761 return true;
762}
763
764bool SILowerControlFlow::run(MachineFunction &MF) {
765 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
766 TII = ST.getInstrInfo();
767 TRI = &TII->getRegisterInfo();
768 EnableOptimizeEndCf = RemoveRedundantEndcf &&
769 MF.getTarget().getOptLevel() > CodeGenOptLevel::None;
770
771 MRI = &MF.getRegInfo();
772 BoolRC = TRI->getBoolRC();
773
774 // Compute set of blocks with kills
775 const bool CanDemote =
776 MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
777 for (auto &MBB : MF) {
778 bool IsKillBlock = false;
779 for (auto &Term : MBB.terminators()) {
780 if (TII->isKillTerminator(Term.getOpcode())) {
781 KillBlocks.insert(&MBB);
782 IsKillBlock = true;
783 break;
784 }
785 }
786 if (CanDemote && !IsKillBlock) {
787 for (auto &MI : MBB) {
788 if (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1) {
789 KillBlocks.insert(&MBB);
790 break;
791 }
792 }
793 }
794 }
795
796 bool Changed = false;
798 for (MachineFunction::iterator BI = MF.begin();
799 BI != MF.end(); BI = NextBB) {
800 NextBB = std::next(BI);
801 MachineBasicBlock *MBB = &*BI;
802
804 E = MBB->end();
805 for (I = MBB->begin(); I != E; I = Next) {
806 Next = std::next(I);
807 MachineInstr &MI = *I;
808 MachineBasicBlock *SplitMBB = MBB;
809
810 switch (MI.getOpcode()) {
811 case AMDGPU::SI_IF:
812 case AMDGPU::SI_ELSE:
813 case AMDGPU::SI_IF_BREAK:
814 case AMDGPU::SI_WATERFALL_LOOP:
815 case AMDGPU::SI_LOOP:
816 case AMDGPU::SI_END_CF:
817 SplitMBB = process(MI);
818 Changed = true;
819 break;
820 }
821
822 if (SplitMBB != MBB) {
823 MBB = Next->getParent();
824 E = MBB->end();
825 }
826 }
827 }
828
829 optimizeEndCf();
830
831 if (LIS) {
832 for (Register Reg : RecomputeRegs) {
833 LIS->removeInterval(Reg);
835 }
836 }
837
838 RecomputeRegs.clear();
839 LoweredEndCf.clear();
840 LoweredIf.clear();
841 KillBlocks.clear();
842
843 return Changed;
844}
845
846bool SILowerControlFlowLegacy::runOnMachineFunction(MachineFunction &MF) {
847 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
848 // This doesn't actually need LiveIntervals, but we can preserve them.
849 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
850 LiveIntervals *LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
851 // This doesn't actually need LiveVariables, but we can preserve them.
852 auto *LVWrapper = getAnalysisIfAvailable<LiveVariablesWrapperPass>();
853 LiveVariables *LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
854 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
855 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
856 auto *PDTWrapper =
857 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
858 MachinePostDominatorTree *PDT =
859 PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
860 return SILowerControlFlow(ST, LIS, LV, MDT, PDT).run(MF);
861}
862
863PreservedAnalyses
866 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
873
874 bool Changed = SILowerControlFlow(ST, LIS, LV, MDT, PDT).run(MF);
875 if (!Changed)
876 return PreservedAnalyses::all();
877
879 PA.preserve<MachineDominatorTreeAnalysis>();
881 PA.preserve<SlotIndexesAnalysis>();
882 PA.preserve<LiveIntervalsAnalysis>();
883 PA.preserve<LiveVariablesAnalysis>();
884 return PA;
885}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:58
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< bool > RemoveRedundantEndcf("amdgpu-remove-redundant-endcf", cl::init(true), cl::ReallyHidden)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool IsDead
static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI)
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Implements a dense probed hash-table based set.
Definition DenseSet.h:269
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:270
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
void removeInterval(Register Reg)
Interval removal.
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
LLVM_ABI void replaceKillInstruction(Register Reg, MachineInstr &OldMI, MachineInstr &NewMI)
replaceKillInstruction - Update register kill info by replacing a kill instruction with a new one.
LLVM_ABI void recomputeForSingleDefVirtReg(Register Reg)
Recompute liveness from scratch for a virtual register Reg that is known to have a single def that do...
LLVM_ABI VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Given a machine basic block that branched to 'Old', change the code and CFG so that it branches to 'N...
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
LLVM_ABI MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
iterator_range< iterator > terminators()
LLVM_ABI DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
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.
BasicBlockListType::iterator iterator
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
MachineOperand class - Representation of each machine instruction operand.
void setIsDead(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
void dump() const
Definition Pass.cpp:146
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:19
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:74
static bool isVALU(const MachineInstr &MI)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A vector that has set insertion semantics.
Definition SetVector.h:59
void clear()
Completely clear the SetVector.
Definition SetVector.h:284
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:279
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:168
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:133
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:181
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:194
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:169
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:174
self_iterator getIterator()
Definition ilist_node.h:130
Changed
@ Kill
The last use of a register.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
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
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
DominatorTreeBase< T, false > DomTreeBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
char & SILowerControlFlowLegacyID
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
DWARFExpression::Operation Op
std::vector< MachineInstr * > Kills
Kills - List of MachineInstruction's which are the last use of this virtual register (kill it) in the...