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 "GCNSubtarget.h"
55#include "llvm/ADT/SmallSet.h"
62
63using namespace llvm;
64
65#define DEBUG_TYPE "si-lower-control-flow"
66
67static cl::opt<bool>
68RemoveRedundantEndcf("amdgpu-remove-redundant-endcf",
70
71namespace {
72
73class SILowerControlFlow {
74private:
75 const SIRegisterInfo *TRI = nullptr;
76 const SIInstrInfo *TII = nullptr;
77 LiveIntervals *LIS = nullptr;
78 LiveVariables *LV = nullptr;
79 MachineDominatorTree *MDT = nullptr;
80 MachinePostDominatorTree *PDT = nullptr;
81 MachineRegisterInfo *MRI = nullptr;
82 SetVector<MachineInstr*> LoweredEndCf;
83 DenseSet<Register> LoweredIf;
85 SmallSet<Register, 8> RecomputeRegs;
86
87 const TargetRegisterClass *BoolRC = nullptr;
88 unsigned AndOpc;
89 unsigned OrOpc;
90 unsigned XorOpc;
91 unsigned MovTermOpc;
92 unsigned Andn2TermOpc;
93 unsigned XorTermrOpc;
94 unsigned OrTermrOpc;
95 unsigned OrSaveExecOpc;
96 unsigned Exec;
97
98 bool EnableOptimizeEndCf = false;
99
100 bool hasKill(const MachineBasicBlock *Begin, const MachineBasicBlock *End);
101
102 void emitIf(MachineInstr &MI);
103 void emitElse(MachineInstr &MI);
104 void emitIfBreak(MachineInstr &MI);
105 void emitLoop(MachineInstr &MI);
106
107 MachineBasicBlock *emitEndCf(MachineInstr &MI);
108
109 void findMaskOperands(MachineInstr &MI, unsigned OpNo,
111
112 void combineMasks(MachineInstr &MI);
113
114 bool removeMBBifRedundant(MachineBasicBlock &MBB);
115
117
118 // Skip to the next instruction, ignoring debug instructions, and trivial
119 // block boundaries (blocks that have one (typically fallthrough) successor,
120 // and the successor has one predecessor.
122 skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
124
125 /// Find the insertion point for a new conditional branch.
127 skipToUncondBrOrEnd(MachineBasicBlock &MBB,
129 assert(I->isTerminator());
130
131 // FIXME: What if we had multiple pre-existing conditional branches?
133 while (I != End && !I->isUnconditionalBranch())
134 ++I;
135 return I;
136 }
137
138 // Remove redundant SI_END_CF instructions.
139 void optimizeEndCf();
140
141public:
142 SILowerControlFlow(LiveIntervals *LIS, LiveVariables *LV,
144 : LIS(LIS), LV(LV), MDT(MDT), PDT(PDT) {}
145 bool run(MachineFunction &MF);
146};
147
148class SILowerControlFlowLegacy : public MachineFunctionPass {
149public:
150 static char ID;
151
152 SILowerControlFlowLegacy() : MachineFunctionPass(ID) {}
153
154 bool runOnMachineFunction(MachineFunction &MF) override;
155
156 StringRef getPassName() const override {
157 return "SI Lower control flow pseudo instructions";
158 }
159
160 void getAnalysisUsage(AnalysisUsage &AU) const override {
162 // Should preserve the same set that TwoAddressInstructions does.
169 }
170};
171
172} // end anonymous namespace
173
174char SILowerControlFlowLegacy::ID = 0;
175
176INITIALIZE_PASS(SILowerControlFlowLegacy, DEBUG_TYPE, "SI lower control flow",
177 false, false)
178
179static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
180 MachineOperand &ImpDefSCC = MI.getOperand(3);
181 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
182
183 ImpDefSCC.setIsDead(IsDead);
184}
185
186char &llvm::SILowerControlFlowLegacyID = SILowerControlFlowLegacy::ID;
187
188bool SILowerControlFlow::hasKill(const MachineBasicBlock *Begin,
189 const MachineBasicBlock *End) {
192
193 while (!Worklist.empty()) {
194 MachineBasicBlock *MBB = Worklist.pop_back_val();
195
196 if (MBB == End || !Visited.insert(MBB).second)
197 continue;
198 if (KillBlocks.contains(MBB))
199 return true;
200
201 Worklist.append(MBB->succ_begin(), MBB->succ_end());
202 }
203
204 return false;
205}
206
207static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
208 Register SaveExecReg = MI.getOperand(0).getReg();
209 auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
210
211 if (U == MRI->use_instr_nodbg_end() ||
212 std::next(U) != MRI->use_instr_nodbg_end() ||
213 U->getOpcode() != AMDGPU::SI_END_CF)
214 return false;
215
216 return true;
217}
218
219void SILowerControlFlow::emitIf(MachineInstr &MI) {
220 MachineBasicBlock &MBB = *MI.getParent();
221 const DebugLoc &DL = MI.getDebugLoc();
223 Register SaveExecReg = MI.getOperand(0).getReg();
224 MachineOperand& Cond = MI.getOperand(1);
225 assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
226
227 MachineOperand &ImpDefSCC = MI.getOperand(4);
228 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
229
230 // If there is only one use of save exec register and that use is SI_END_CF,
231 // we can optimize SI_IF by returning the full saved exec mask instead of
232 // just cleared bits.
233 bool SimpleIf = isSimpleIf(MI, MRI);
234
235 if (SimpleIf) {
236 // Check for SI_KILL_*_TERMINATOR on path from if to endif.
237 // if there is any such terminator simplifications are not safe.
238 auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
239 SimpleIf = !hasKill(MI.getParent(), UseMI->getParent());
240 }
241
242 // Add an implicit def of exec to discourage scheduling VALU after this which
243 // will interfere with trying to form s_and_saveexec_b64 later.
244 Register CopyReg = SimpleIf ? SaveExecReg
245 : MRI->createVirtualRegister(BoolRC);
246 MachineInstr *CopyExec =
247 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
248 .addReg(Exec)
250 LoweredIf.insert(CopyReg);
251
252 Register Tmp = MRI->createVirtualRegister(BoolRC);
253
255 BuildMI(MBB, I, DL, TII->get(AndOpc), Tmp)
256 .addReg(CopyReg)
257 .add(Cond);
258 if (LV)
259 LV->replaceKillInstruction(Cond.getReg(), MI, *And);
260
261 setImpSCCDefDead(*And, true);
262
263 MachineInstr *Xor = nullptr;
264 if (!SimpleIf) {
265 Xor =
266 BuildMI(MBB, I, DL, TII->get(XorOpc), SaveExecReg)
267 .addReg(Tmp)
268 .addReg(CopyReg);
269 setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
270 }
271
272 // Use a copy that is a terminator to get correct spill code placement it with
273 // fast regalloc.
274 MachineInstr *SetExec =
275 BuildMI(MBB, I, DL, TII->get(MovTermOpc), Exec)
276 .addReg(Tmp, RegState::Kill);
277 if (LV)
278 LV->getVarInfo(Tmp).Kills.push_back(SetExec);
279
280 // Skip ahead to the unconditional branch in case there are other terminators
281 // present.
282 I = skipToUncondBrOrEnd(MBB, I);
283
284 // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
285 // during SIPreEmitPeephole.
286 MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
287 .add(MI.getOperand(2));
288
289 if (!LIS) {
290 MI.eraseFromParent();
291 return;
292 }
293
294 LIS->InsertMachineInstrInMaps(*CopyExec);
295
296 // Replace with and so we don't need to fix the live interval for condition
297 // register.
299
300 if (!SimpleIf)
302 LIS->InsertMachineInstrInMaps(*SetExec);
303 LIS->InsertMachineInstrInMaps(*NewBr);
304
305 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
306 MI.eraseFromParent();
307
308 // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
309 // hard to add another def here but I'm not sure how to correctly update the
310 // valno.
311 RecomputeRegs.insert(SaveExecReg);
313 if (!SimpleIf)
315}
316
317void SILowerControlFlow::emitElse(MachineInstr &MI) {
318 MachineBasicBlock &MBB = *MI.getParent();
319 const DebugLoc &DL = MI.getDebugLoc();
320
321 Register DstReg = MI.getOperand(0).getReg();
322 Register SrcReg = MI.getOperand(1).getReg();
323
325
326 // This must be inserted before phis and any spill code inserted before the
327 // else.
328 Register SaveReg = MRI->createVirtualRegister(BoolRC);
329 MachineInstr *OrSaveExec =
330 BuildMI(MBB, Start, DL, TII->get(OrSaveExecOpc), SaveReg)
331 .add(MI.getOperand(1)); // Saved EXEC
332 if (LV)
333 LV->replaceKillInstruction(SrcReg, MI, *OrSaveExec);
334
335 MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
336
338
339 // This accounts for any modification of the EXEC mask within the block and
340 // can be optimized out pre-RA when not required.
341 MachineInstr *And = BuildMI(MBB, ElsePt, DL, TII->get(AndOpc), DstReg)
342 .addReg(Exec)
343 .addReg(SaveReg);
344
346 BuildMI(MBB, ElsePt, DL, TII->get(XorTermrOpc), Exec)
347 .addReg(Exec)
348 .addReg(DstReg);
349
350 // Skip ahead to the unconditional branch in case there are other terminators
351 // present.
352 ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
353
355 BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
356 .addMBB(DestBB);
357
358 if (!LIS) {
359 MI.eraseFromParent();
360 return;
361 }
362
364 MI.eraseFromParent();
365
366 LIS->InsertMachineInstrInMaps(*OrSaveExec);
368
370 LIS->InsertMachineInstrInMaps(*Branch);
371
372 RecomputeRegs.insert(SrcReg);
373 RecomputeRegs.insert(DstReg);
375
376 // Let this be recomputed.
377 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
378}
379
380void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
381 MachineBasicBlock &MBB = *MI.getParent();
382 const DebugLoc &DL = MI.getDebugLoc();
383 auto Dst = MI.getOperand(0).getReg();
384
385 // Skip ANDing with exec if the break condition is already masked by exec
386 // because it is a V_CMP in the same basic block. (We know the break
387 // condition operand was an i1 in IR, so if it is a VALU instruction it must
388 // be one with a carry-out.)
389 bool SkipAnding = false;
390 if (MI.getOperand(1).isReg()) {
391 if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
392 SkipAnding = Def->getParent() == MI.getParent()
393 && SIInstrInfo::isVALU(*Def);
394 }
395 }
396
397 // AND the break condition operand with exec, then OR that into the "loop
398 // exit" mask.
399 MachineInstr *And = nullptr, *Or = nullptr;
400 Register AndReg;
401 if (!SkipAnding) {
402 AndReg = MRI->createVirtualRegister(BoolRC);
403 And = BuildMI(MBB, &MI, DL, TII->get(AndOpc), AndReg)
404 .addReg(Exec)
405 .add(MI.getOperand(1));
406 if (LV)
407 LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *And);
408 Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
409 .addReg(AndReg)
410 .add(MI.getOperand(2));
411 } else {
412 Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
413 .add(MI.getOperand(1))
414 .add(MI.getOperand(2));
415 if (LV)
416 LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *Or);
417 }
418 if (LV)
419 LV->replaceKillInstruction(MI.getOperand(2).getReg(), MI, *Or);
420
421 if (LIS) {
423 if (And) {
424 // Read of original operand 1 is on And now not Or.
425 RecomputeRegs.insert(And->getOperand(2).getReg());
428 }
429 }
430
431 MI.eraseFromParent();
432}
433
434void SILowerControlFlow::emitLoop(MachineInstr &MI) {
435 MachineBasicBlock &MBB = *MI.getParent();
436 const DebugLoc &DL = MI.getDebugLoc();
437
438 MachineInstr *AndN2 =
439 BuildMI(MBB, &MI, DL, TII->get(Andn2TermOpc), Exec)
440 .addReg(Exec)
441 .add(MI.getOperand(0));
442 if (LV)
443 LV->replaceKillInstruction(MI.getOperand(0).getReg(), MI, *AndN2);
444
445 auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
447 BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
448 .add(MI.getOperand(1));
449
450 if (LIS) {
451 RecomputeRegs.insert(MI.getOperand(0).getReg());
452 LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
453 LIS->InsertMachineInstrInMaps(*Branch);
454 }
455
456 MI.eraseFromParent();
457}
458
460SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
462
465 do {
466 if (!Visited.insert(B).second)
467 return MBB.end();
468
469 auto E = B->end();
470 for ( ; It != E; ++It) {
471 if (TII->mayReadEXEC(*MRI, *It))
472 break;
473 }
474
475 if (It != E)
476 return It;
477
478 if (B->succ_size() != 1)
479 return MBB.end();
480
481 // If there is one trivial successor, advance to the next block.
482 MachineBasicBlock *Succ = *B->succ_begin();
483
484 It = Succ->begin();
485 B = Succ;
486 } while (true);
487}
488
489MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &MI) {
490 MachineBasicBlock &MBB = *MI.getParent();
491 const DebugLoc &DL = MI.getDebugLoc();
492
494
495 // If we have instructions that aren't prolog instructions, split the block
496 // and emit a terminator instruction. This ensures correct spill placement.
497 // FIXME: We should unconditionally split the block here.
498 bool NeedBlockSplit = false;
499 Register DataReg = MI.getOperand(0).getReg();
500 for (MachineBasicBlock::iterator I = InsPt, E = MI.getIterator();
501 I != E; ++I) {
502 if (I->modifiesRegister(DataReg, TRI)) {
503 NeedBlockSplit = true;
504 break;
505 }
506 }
507
508 unsigned Opcode = OrOpc;
509 MachineBasicBlock *SplitBB = &MBB;
510 if (NeedBlockSplit) {
511 SplitBB = MBB.splitAt(MI, /*UpdateLiveIns*/true, LIS);
512 if (SplitBB != &MBB && (MDT || PDT)) {
513 using DomTreeT = DomTreeBase<MachineBasicBlock>;
515 for (MachineBasicBlock *Succ : SplitBB->successors()) {
516 DTUpdates.push_back({DomTreeT::Insert, SplitBB, Succ});
517 DTUpdates.push_back({DomTreeT::Delete, &MBB, Succ});
518 }
519 DTUpdates.push_back({DomTreeT::Insert, &MBB, SplitBB});
520 if (MDT)
521 MDT->applyUpdates(DTUpdates);
522 if (PDT)
523 PDT->applyUpdates(DTUpdates);
524 }
525 Opcode = OrTermrOpc;
526 InsPt = MI;
527 }
528
529 MachineInstr *NewMI =
530 BuildMI(MBB, InsPt, DL, TII->get(Opcode), Exec)
531 .addReg(Exec)
532 .add(MI.getOperand(0));
533 if (LV) {
534 LV->replaceKillInstruction(DataReg, MI, *NewMI);
535
536 if (SplitBB != &MBB) {
537 // Track the set of registers defined in the original block so we don't
538 // accidentally add the original block to AliveBlocks. AliveBlocks only
539 // includes blocks which are live through, which excludes live outs and
540 // local defs.
541 DenseSet<Register> DefInOrigBlock;
542
543 for (MachineBasicBlock *BlockPiece : {&MBB, SplitBB}) {
544 for (MachineInstr &X : *BlockPiece) {
545 for (MachineOperand &Op : X.all_defs()) {
546 if (Op.getReg().isVirtual())
547 DefInOrigBlock.insert(Op.getReg());
548 }
549 }
550 }
551
552 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
555
556 if (VI.AliveBlocks.test(MBB.getNumber()))
557 VI.AliveBlocks.set(SplitBB->getNumber());
558 else {
559 for (MachineInstr *Kill : VI.Kills) {
560 if (Kill->getParent() == SplitBB && !DefInOrigBlock.contains(Reg))
561 VI.AliveBlocks.set(MBB.getNumber());
562 }
563 }
564 }
565 }
566 }
567
568 LoweredEndCf.insert(NewMI);
569
570 if (LIS)
571 LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
572
573 MI.eraseFromParent();
574
575 if (LIS)
576 LIS->handleMove(*NewMI);
577 return SplitBB;
578}
579
580// Returns replace operands for a logical operation, either single result
581// for exec or two operands if source was another equivalent operation.
582void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
584 MachineOperand &Op = MI.getOperand(OpNo);
585 if (!Op.isReg() || !Op.getReg().isVirtual()) {
586 Src.push_back(Op);
587 return;
588 }
589
590 MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
591 if (!Def || Def->getParent() != MI.getParent() ||
592 !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
593 return;
594
595 // Make sure we do not modify exec between def and use.
596 // A copy with implicitly defined exec inserted earlier is an exclusion, it
597 // does not really modify exec.
598 for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
599 if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
600 !(I->isCopy() && I->getOperand(0).getReg() != Exec))
601 return;
602
603 for (const auto &SrcOp : Def->explicit_operands())
604 if (SrcOp.isReg() && SrcOp.isUse() &&
605 (SrcOp.getReg().isVirtual() || SrcOp.getReg() == Exec))
606 Src.push_back(SrcOp);
607}
608
609// Search and combine pairs of equivalent instructions, like
610// S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
611// S_OR_B64 x, (S_OR_B64 x, y) => S_OR_B64 x, y
612// One of the operands is exec mask.
613void SILowerControlFlow::combineMasks(MachineInstr &MI) {
614 assert(MI.getNumExplicitOperands() == 3);
616 unsigned OpToReplace = 1;
617 findMaskOperands(MI, 1, Ops);
618 if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
619 findMaskOperands(MI, 2, Ops);
620 if (Ops.size() != 3) return;
621
622 unsigned UniqueOpndIdx;
623 if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
624 else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
625 else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
626 else return;
627
628 Register Reg = MI.getOperand(OpToReplace).getReg();
629 MI.removeOperand(OpToReplace);
630 MI.addOperand(Ops[UniqueOpndIdx]);
631 if (MRI->use_empty(Reg))
632 MRI->getUniqueVRegDef(Reg)->eraseFromParent();
633}
634
635void SILowerControlFlow::optimizeEndCf() {
636 // If the only instruction immediately following this END_CF is another
637 // END_CF in the only successor we can avoid emitting exec mask restore here.
638 if (!EnableOptimizeEndCf)
639 return;
640
641 for (MachineInstr *MI : reverse(LoweredEndCf)) {
642 MachineBasicBlock &MBB = *MI->getParent();
643 auto Next =
644 skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
645 if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
646 continue;
647 // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
648 // If that belongs to SI_ELSE then saved mask has an inverted value.
649 Register SavedExec
650 = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
651 assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
652
653 const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
654 if (Def && LoweredIf.count(SavedExec)) {
655 LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
656 if (LIS)
659 if (LV)
660 Reg = TII->getNamedOperand(*MI, AMDGPU::OpName::src1)->getReg();
661 MI->eraseFromParent();
662 if (LV)
664 removeMBBifRedundant(MBB);
665 }
666 }
667}
668
669MachineBasicBlock *SILowerControlFlow::process(MachineInstr &MI) {
670 MachineBasicBlock &MBB = *MI.getParent();
672 MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
673
674 MachineBasicBlock *SplitBB = &MBB;
675
676 switch (MI.getOpcode()) {
677 case AMDGPU::SI_IF:
678 emitIf(MI);
679 break;
680
681 case AMDGPU::SI_ELSE:
682 emitElse(MI);
683 break;
684
685 case AMDGPU::SI_IF_BREAK:
686 emitIfBreak(MI);
687 break;
688
689 case AMDGPU::SI_LOOP:
690 emitLoop(MI);
691 break;
692
693 case AMDGPU::SI_WATERFALL_LOOP:
694 MI.setDesc(TII->get(AMDGPU::S_CBRANCH_EXECNZ));
695 break;
696
697 case AMDGPU::SI_END_CF:
698 SplitBB = emitEndCf(MI);
699 break;
700
701 default:
702 assert(false && "Attempt to process unsupported instruction");
703 break;
704 }
705
707 for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
708 Next = std::next(I);
709 MachineInstr &MaskMI = *I;
710 switch (MaskMI.getOpcode()) {
711 case AMDGPU::S_AND_B64:
712 case AMDGPU::S_OR_B64:
713 case AMDGPU::S_AND_B32:
714 case AMDGPU::S_OR_B32:
715 // Cleanup bit manipulations on exec mask
716 combineMasks(MaskMI);
717 break;
718 default:
719 I = MBB.end();
720 break;
721 }
722 }
723
724 return SplitBB;
725}
726
727bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &MBB) {
728 for (auto &I : MBB.instrs()) {
729 if (!I.isDebugInstr() && !I.isUnconditionalBranch())
730 return false;
731 }
732
733 assert(MBB.succ_size() == 1 && "MBB has more than one successor");
734
736 MachineBasicBlock *FallThrough = nullptr;
737
738 using DomTreeT = DomTreeBase<MachineBasicBlock>;
740
741 while (!MBB.predecessors().empty()) {
743 if (P->getFallThrough(false) == &MBB)
744 FallThrough = P;
745 P->ReplaceUsesOfBlockWith(&MBB, Succ);
746 DTUpdates.push_back({DomTreeT::Insert, P, Succ});
747 DTUpdates.push_back({DomTreeT::Delete, P, &MBB});
748 }
749 MBB.removeSuccessor(Succ);
750 if (LIS) {
751 for (auto &I : MBB.instrs())
753 }
754 if (MDT)
755 MDT->applyUpdates(DTUpdates);
756 if (PDT)
757 PDT->applyUpdates(DTUpdates);
758
759 MBB.clear();
761 if (FallThrough && !FallThrough->isLayoutSuccessor(Succ)) {
762 // Note: we cannot update block layout and preserve live intervals;
763 // hence we must insert a branch.
764 MachineInstr *BranchMI = BuildMI(*FallThrough, FallThrough->end(),
765 FallThrough->findBranchDebugLoc(), TII->get(AMDGPU::S_BRANCH))
766 .addMBB(Succ);
767 if (LIS)
768 LIS->InsertMachineInstrInMaps(*BranchMI);
769 }
770
771 return true;
772}
773
774bool SILowerControlFlow::run(MachineFunction &MF) {
776 TII = ST.getInstrInfo();
777 TRI = &TII->getRegisterInfo();
778 EnableOptimizeEndCf = RemoveRedundantEndcf &&
779 MF.getTarget().getOptLevel() > CodeGenOptLevel::None;
780
781 MRI = &MF.getRegInfo();
782 BoolRC = TRI->getBoolRC();
783
784 if (ST.isWave32()) {
785 AndOpc = AMDGPU::S_AND_B32;
786 OrOpc = AMDGPU::S_OR_B32;
787 XorOpc = AMDGPU::S_XOR_B32;
788 MovTermOpc = AMDGPU::S_MOV_B32_term;
789 Andn2TermOpc = AMDGPU::S_ANDN2_B32_term;
790 XorTermrOpc = AMDGPU::S_XOR_B32_term;
791 OrTermrOpc = AMDGPU::S_OR_B32_term;
792 OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B32;
793 Exec = AMDGPU::EXEC_LO;
794 } else {
795 AndOpc = AMDGPU::S_AND_B64;
796 OrOpc = AMDGPU::S_OR_B64;
797 XorOpc = AMDGPU::S_XOR_B64;
798 MovTermOpc = AMDGPU::S_MOV_B64_term;
799 Andn2TermOpc = AMDGPU::S_ANDN2_B64_term;
800 XorTermrOpc = AMDGPU::S_XOR_B64_term;
801 OrTermrOpc = AMDGPU::S_OR_B64_term;
802 OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B64;
803 Exec = AMDGPU::EXEC;
804 }
805
806 // Compute set of blocks with kills
807 const bool CanDemote =
809 for (auto &MBB : MF) {
810 bool IsKillBlock = false;
811 for (auto &Term : MBB.terminators()) {
812 if (TII->isKillTerminator(Term.getOpcode())) {
813 KillBlocks.insert(&MBB);
814 IsKillBlock = true;
815 break;
816 }
817 }
818 if (CanDemote && !IsKillBlock) {
819 for (auto &MI : MBB) {
820 if (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1) {
821 KillBlocks.insert(&MBB);
822 break;
823 }
824 }
825 }
826 }
827
828 bool Changed = false;
830 for (MachineFunction::iterator BI = MF.begin();
831 BI != MF.end(); BI = NextBB) {
832 NextBB = std::next(BI);
833 MachineBasicBlock *MBB = &*BI;
834
836 E = MBB->end();
837 for (I = MBB->begin(); I != E; I = Next) {
838 Next = std::next(I);
839 MachineInstr &MI = *I;
840 MachineBasicBlock *SplitMBB = MBB;
841
842 switch (MI.getOpcode()) {
843 case AMDGPU::SI_IF:
844 case AMDGPU::SI_ELSE:
845 case AMDGPU::SI_IF_BREAK:
846 case AMDGPU::SI_WATERFALL_LOOP:
847 case AMDGPU::SI_LOOP:
848 case AMDGPU::SI_END_CF:
849 SplitMBB = process(MI);
850 Changed = true;
851 break;
852 }
853
854 if (SplitMBB != MBB) {
855 MBB = Next->getParent();
856 E = MBB->end();
857 }
858 }
859 }
860
861 optimizeEndCf();
862
863 if (LIS) {
864 for (Register Reg : RecomputeRegs) {
865 LIS->removeInterval(Reg);
867 }
868 }
869
870 RecomputeRegs.clear();
871 LoweredEndCf.clear();
872 LoweredIf.clear();
873 KillBlocks.clear();
874
875 return Changed;
876}
877
878bool SILowerControlFlowLegacy::runOnMachineFunction(MachineFunction &MF) {
879 // This doesn't actually need LiveIntervals, but we can preserve them.
880 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
881 LiveIntervals *LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
882 // This doesn't actually need LiveVariables, but we can preserve them.
883 auto *LVWrapper = getAnalysisIfAvailable<LiveVariablesWrapperPass>();
884 LiveVariables *LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
885 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
886 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
887 auto *PDTWrapper =
888 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
890 PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
891 return SILowerControlFlow(LIS, LV, MDT, PDT).run(MF);
892}
893
903
904 bool Changed = SILowerControlFlow(LIS, LV, MDT, PDT).run(MF);
905 if (!Changed)
906 return PreservedAnalyses::all();
907
909 PA.preserve<MachineDominatorTreeAnalysis>();
911 PA.preserve<SlotIndexesAnalysis>();
912 PA.preserve<LiveIntervalsAnalysis>();
913 PA.preserve<LiveVariablesAnalysis>();
914 return PA;
915}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
bool End
Definition: ELF_riscv.cpp:480
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
Register const TargetRegisterInfo * TRI
#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)
#define DEBUG_TYPE
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition: Debug.h:119
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:431
Represent the analysis usage information of a pass.
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.
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:124
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
Core dominator tree base class.
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...
unsigned succ_size() const
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
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()
Analysis pass which computes a MachineDominatorTree.
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.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
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 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.
Definition: MachineInstr.h:72
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:587
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:359
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
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:85
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:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:67
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)
Definition: SIInstrInfo.h:448
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.
Definition: SmallPtrSet.h:401
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:476
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
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:182
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:684
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
Register getReg() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
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:134
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:194
@ Kill
The last use of a register.
Reg
All possible values of the reg field in the ModR/M byte.
@ ReallyHidden
Definition: CommandLine.h:139
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
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.
Definition: AddressRanges.h:18
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:428
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
char & SILowerControlFlowLegacyID
@ Xor
Bitwise or logical XOR of integers.
VarInfo - This represents the regions where a virtual register is live in the program.
Definition: LiveVariables.h:79
std::vector< MachineInstr * > Kills
Kills - List of MachineInstruction's which are the last use of this virtual register (kill it) in the...
Definition: LiveVariables.h:89
Matching combinators.