LLVM 20.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_BRANCH_EXECZ label1 // Use our branch optimization
45/// // instruction again.
46/// %vgpr0 = V_SUB_F32 %vgpr0, %vgpr // Do the THEN block
47/// label1:
48/// %exec = S_OR_B64 %exec, %sgpr0 // Re-enable saved exec mask bits
49//===----------------------------------------------------------------------===//
50
51#include "AMDGPU.h"
52#include "GCNSubtarget.h"
54#include "llvm/ADT/SmallSet.h"
60
61using namespace llvm;
62
63#define DEBUG_TYPE "si-lower-control-flow"
64
65static cl::opt<bool>
66RemoveRedundantEndcf("amdgpu-remove-redundant-endcf",
68
69namespace {
70
71class SILowerControlFlow : public MachineFunctionPass {
72private:
73 const SIRegisterInfo *TRI = nullptr;
74 const SIInstrInfo *TII = nullptr;
75 LiveIntervals *LIS = nullptr;
76 LiveVariables *LV = nullptr;
77 MachineDominatorTree *MDT = nullptr;
78 MachineRegisterInfo *MRI = nullptr;
79 SetVector<MachineInstr*> LoweredEndCf;
80 DenseSet<Register> LoweredIf;
82 SmallSet<Register, 8> RecomputeRegs;
83
84 const TargetRegisterClass *BoolRC = nullptr;
85 unsigned AndOpc;
86 unsigned OrOpc;
87 unsigned XorOpc;
88 unsigned MovTermOpc;
89 unsigned Andn2TermOpc;
90 unsigned XorTermrOpc;
91 unsigned OrTermrOpc;
92 unsigned OrSaveExecOpc;
93 unsigned Exec;
94
95 bool EnableOptimizeEndCf = false;
96
97 bool hasKill(const MachineBasicBlock *Begin, const MachineBasicBlock *End);
98
99 void emitIf(MachineInstr &MI);
100 void emitElse(MachineInstr &MI);
101 void emitIfBreak(MachineInstr &MI);
102 void emitLoop(MachineInstr &MI);
103
104 MachineBasicBlock *emitEndCf(MachineInstr &MI);
105
106 void findMaskOperands(MachineInstr &MI, unsigned OpNo,
108
109 void combineMasks(MachineInstr &MI);
110
111 bool removeMBBifRedundant(MachineBasicBlock &MBB);
112
114
115 // Skip to the next instruction, ignoring debug instructions, and trivial
116 // block boundaries (blocks that have one (typically fallthrough) successor,
117 // and the successor has one predecessor.
119 skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
121
122 /// Find the insertion point for a new conditional branch.
124 skipToUncondBrOrEnd(MachineBasicBlock &MBB,
126 assert(I->isTerminator());
127
128 // FIXME: What if we had multiple pre-existing conditional branches?
130 while (I != End && !I->isUnconditionalBranch())
131 ++I;
132 return I;
133 }
134
135 // Remove redundant SI_END_CF instructions.
136 void optimizeEndCf();
137
138public:
139 static char ID;
140
141 SILowerControlFlow() : MachineFunctionPass(ID) {}
142
143 bool runOnMachineFunction(MachineFunction &MF) override;
144
145 StringRef getPassName() const override {
146 return "SI Lower control flow pseudo instructions";
147 }
148
149 void getAnalysisUsage(AnalysisUsage &AU) const override {
151 // Should preserve the same set that TwoAddressInstructions does.
157 }
158};
159
160} // end anonymous namespace
161
162char SILowerControlFlow::ID = 0;
163
164INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE,
165 "SI lower control flow", false, false)
166
167static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
168 MachineOperand &ImpDefSCC = MI.getOperand(3);
169 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
170
171 ImpDefSCC.setIsDead(IsDead);
172}
173
174char &llvm::SILowerControlFlowID = SILowerControlFlow::ID;
175
176bool SILowerControlFlow::hasKill(const MachineBasicBlock *Begin,
177 const MachineBasicBlock *End) {
180
181 while (!Worklist.empty()) {
182 MachineBasicBlock *MBB = Worklist.pop_back_val();
183
184 if (MBB == End || !Visited.insert(MBB).second)
185 continue;
186 if (KillBlocks.contains(MBB))
187 return true;
188
189 Worklist.append(MBB->succ_begin(), MBB->succ_end());
190 }
191
192 return false;
193}
194
195static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
196 Register SaveExecReg = MI.getOperand(0).getReg();
197 auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
198
199 if (U == MRI->use_instr_nodbg_end() ||
200 std::next(U) != MRI->use_instr_nodbg_end() ||
201 U->getOpcode() != AMDGPU::SI_END_CF)
202 return false;
203
204 return true;
205}
206
207void SILowerControlFlow::emitIf(MachineInstr &MI) {
208 MachineBasicBlock &MBB = *MI.getParent();
209 const DebugLoc &DL = MI.getDebugLoc();
211 Register SaveExecReg = MI.getOperand(0).getReg();
212 MachineOperand& Cond = MI.getOperand(1);
213 assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
214
215 MachineOperand &ImpDefSCC = MI.getOperand(4);
216 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
217
218 // If there is only one use of save exec register and that use is SI_END_CF,
219 // we can optimize SI_IF by returning the full saved exec mask instead of
220 // just cleared bits.
221 bool SimpleIf = isSimpleIf(MI, MRI);
222
223 if (SimpleIf) {
224 // Check for SI_KILL_*_TERMINATOR on path from if to endif.
225 // if there is any such terminator simplifications are not safe.
226 auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
227 SimpleIf = !hasKill(MI.getParent(), UseMI->getParent());
228 }
229
230 // Add an implicit def of exec to discourage scheduling VALU after this which
231 // will interfere with trying to form s_and_saveexec_b64 later.
232 Register CopyReg = SimpleIf ? SaveExecReg
233 : MRI->createVirtualRegister(BoolRC);
234 MachineInstr *CopyExec =
235 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
236 .addReg(Exec)
238 LoweredIf.insert(CopyReg);
239
240 Register Tmp = MRI->createVirtualRegister(BoolRC);
241
243 BuildMI(MBB, I, DL, TII->get(AndOpc), Tmp)
244 .addReg(CopyReg)
245 .add(Cond);
246 if (LV)
247 LV->replaceKillInstruction(Cond.getReg(), MI, *And);
248
249 setImpSCCDefDead(*And, true);
250
251 MachineInstr *Xor = nullptr;
252 if (!SimpleIf) {
253 Xor =
254 BuildMI(MBB, I, DL, TII->get(XorOpc), SaveExecReg)
255 .addReg(Tmp)
256 .addReg(CopyReg);
257 setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
258 }
259
260 // Use a copy that is a terminator to get correct spill code placement it with
261 // fast regalloc.
262 MachineInstr *SetExec =
263 BuildMI(MBB, I, DL, TII->get(MovTermOpc), Exec)
264 .addReg(Tmp, RegState::Kill);
265 if (LV)
266 LV->getVarInfo(Tmp).Kills.push_back(SetExec);
267
268 // Skip ahead to the unconditional branch in case there are other terminators
269 // present.
270 I = skipToUncondBrOrEnd(MBB, I);
271
272 // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
273 // during SIRemoveShortExecBranches.
274 MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
275 .add(MI.getOperand(2));
276
277 if (!LIS) {
278 MI.eraseFromParent();
279 return;
280 }
281
282 LIS->InsertMachineInstrInMaps(*CopyExec);
283
284 // Replace with and so we don't need to fix the live interval for condition
285 // register.
287
288 if (!SimpleIf)
290 LIS->InsertMachineInstrInMaps(*SetExec);
291 LIS->InsertMachineInstrInMaps(*NewBr);
292
293 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
294 MI.eraseFromParent();
295
296 // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
297 // hard to add another def here but I'm not sure how to correctly update the
298 // valno.
299 RecomputeRegs.insert(SaveExecReg);
301 if (!SimpleIf)
303}
304
305void SILowerControlFlow::emitElse(MachineInstr &MI) {
306 MachineBasicBlock &MBB = *MI.getParent();
307 const DebugLoc &DL = MI.getDebugLoc();
308
309 Register DstReg = MI.getOperand(0).getReg();
310 Register SrcReg = MI.getOperand(1).getReg();
311
313
314 // This must be inserted before phis and any spill code inserted before the
315 // else.
316 Register SaveReg = MRI->createVirtualRegister(BoolRC);
317 MachineInstr *OrSaveExec =
318 BuildMI(MBB, Start, DL, TII->get(OrSaveExecOpc), SaveReg)
319 .add(MI.getOperand(1)); // Saved EXEC
320 if (LV)
321 LV->replaceKillInstruction(SrcReg, MI, *OrSaveExec);
322
323 MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
324
326
327 // This accounts for any modification of the EXEC mask within the block and
328 // can be optimized out pre-RA when not required.
329 MachineInstr *And = BuildMI(MBB, ElsePt, DL, TII->get(AndOpc), DstReg)
330 .addReg(Exec)
331 .addReg(SaveReg);
332
334 BuildMI(MBB, ElsePt, DL, TII->get(XorTermrOpc), Exec)
335 .addReg(Exec)
336 .addReg(DstReg);
337
338 // Skip ahead to the unconditional branch in case there are other terminators
339 // present.
340 ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
341
343 BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
344 .addMBB(DestBB);
345
346 if (!LIS) {
347 MI.eraseFromParent();
348 return;
349 }
350
352 MI.eraseFromParent();
353
354 LIS->InsertMachineInstrInMaps(*OrSaveExec);
356
358 LIS->InsertMachineInstrInMaps(*Branch);
359
360 RecomputeRegs.insert(SrcReg);
361 RecomputeRegs.insert(DstReg);
363
364 // Let this be recomputed.
365 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
366}
367
368void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
369 MachineBasicBlock &MBB = *MI.getParent();
370 const DebugLoc &DL = MI.getDebugLoc();
371 auto Dst = MI.getOperand(0).getReg();
372
373 // Skip ANDing with exec if the break condition is already masked by exec
374 // because it is a V_CMP in the same basic block. (We know the break
375 // condition operand was an i1 in IR, so if it is a VALU instruction it must
376 // be one with a carry-out.)
377 bool SkipAnding = false;
378 if (MI.getOperand(1).isReg()) {
379 if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
380 SkipAnding = Def->getParent() == MI.getParent()
381 && SIInstrInfo::isVALU(*Def);
382 }
383 }
384
385 // AND the break condition operand with exec, then OR that into the "loop
386 // exit" mask.
387 MachineInstr *And = nullptr, *Or = nullptr;
388 Register AndReg;
389 if (!SkipAnding) {
390 AndReg = MRI->createVirtualRegister(BoolRC);
391 And = BuildMI(MBB, &MI, DL, TII->get(AndOpc), AndReg)
392 .addReg(Exec)
393 .add(MI.getOperand(1));
394 if (LV)
395 LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *And);
396 Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
397 .addReg(AndReg)
398 .add(MI.getOperand(2));
399 } else {
400 Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
401 .add(MI.getOperand(1))
402 .add(MI.getOperand(2));
403 if (LV)
404 LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *Or);
405 }
406 if (LV)
407 LV->replaceKillInstruction(MI.getOperand(2).getReg(), MI, *Or);
408
409 if (LIS) {
411 if (And) {
412 // Read of original operand 1 is on And now not Or.
413 RecomputeRegs.insert(And->getOperand(2).getReg());
416 }
417 }
418
419 MI.eraseFromParent();
420}
421
422void SILowerControlFlow::emitLoop(MachineInstr &MI) {
423 MachineBasicBlock &MBB = *MI.getParent();
424 const DebugLoc &DL = MI.getDebugLoc();
425
426 MachineInstr *AndN2 =
427 BuildMI(MBB, &MI, DL, TII->get(Andn2TermOpc), Exec)
428 .addReg(Exec)
429 .add(MI.getOperand(0));
430 if (LV)
431 LV->replaceKillInstruction(MI.getOperand(0).getReg(), MI, *AndN2);
432
433 auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
435 BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
436 .add(MI.getOperand(1));
437
438 if (LIS) {
439 RecomputeRegs.insert(MI.getOperand(0).getReg());
440 LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
441 LIS->InsertMachineInstrInMaps(*Branch);
442 }
443
444 MI.eraseFromParent();
445}
446
448SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
450
453 do {
454 if (!Visited.insert(B).second)
455 return MBB.end();
456
457 auto E = B->end();
458 for ( ; It != E; ++It) {
459 if (TII->mayReadEXEC(*MRI, *It))
460 break;
461 }
462
463 if (It != E)
464 return It;
465
466 if (B->succ_size() != 1)
467 return MBB.end();
468
469 // If there is one trivial successor, advance to the next block.
470 MachineBasicBlock *Succ = *B->succ_begin();
471
472 It = Succ->begin();
473 B = Succ;
474 } while (true);
475}
476
477MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &MI) {
478 MachineBasicBlock &MBB = *MI.getParent();
479 const DebugLoc &DL = MI.getDebugLoc();
480
482
483 // If we have instructions that aren't prolog instructions, split the block
484 // and emit a terminator instruction. This ensures correct spill placement.
485 // FIXME: We should unconditionally split the block here.
486 bool NeedBlockSplit = false;
487 Register DataReg = MI.getOperand(0).getReg();
488 for (MachineBasicBlock::iterator I = InsPt, E = MI.getIterator();
489 I != E; ++I) {
490 if (I->modifiesRegister(DataReg, TRI)) {
491 NeedBlockSplit = true;
492 break;
493 }
494 }
495
496 unsigned Opcode = OrOpc;
497 MachineBasicBlock *SplitBB = &MBB;
498 if (NeedBlockSplit) {
499 SplitBB = MBB.splitAt(MI, /*UpdateLiveIns*/true, LIS);
500 if (MDT && SplitBB != &MBB) {
501 MachineDomTreeNode *MBBNode = (*MDT)[&MBB];
503 MBBNode->end());
504 MachineDomTreeNode *SplitBBNode = MDT->addNewBlock(SplitBB, &MBB);
505 for (MachineDomTreeNode *Child : Children)
506 MDT->changeImmediateDominator(Child, SplitBBNode);
507 }
508 Opcode = OrTermrOpc;
509 InsPt = MI;
510 }
511
512 MachineInstr *NewMI =
513 BuildMI(MBB, InsPt, DL, TII->get(Opcode), Exec)
514 .addReg(Exec)
515 .add(MI.getOperand(0));
516 if (LV) {
517 LV->replaceKillInstruction(DataReg, MI, *NewMI);
518
519 if (SplitBB != &MBB) {
520 // Track the set of registers defined in the original block so we don't
521 // accidentally add the original block to AliveBlocks. AliveBlocks only
522 // includes blocks which are live through, which excludes live outs and
523 // local defs.
524 DenseSet<Register> DefInOrigBlock;
525
526 for (MachineBasicBlock *BlockPiece : {&MBB, SplitBB}) {
527 for (MachineInstr &X : *BlockPiece) {
528 for (MachineOperand &Op : X.all_defs()) {
529 if (Op.getReg().isVirtual())
530 DefInOrigBlock.insert(Op.getReg());
531 }
532 }
533 }
534
535 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
538
539 if (VI.AliveBlocks.test(MBB.getNumber()))
540 VI.AliveBlocks.set(SplitBB->getNumber());
541 else {
542 for (MachineInstr *Kill : VI.Kills) {
543 if (Kill->getParent() == SplitBB && !DefInOrigBlock.contains(Reg))
544 VI.AliveBlocks.set(MBB.getNumber());
545 }
546 }
547 }
548 }
549 }
550
551 LoweredEndCf.insert(NewMI);
552
553 if (LIS)
554 LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
555
556 MI.eraseFromParent();
557
558 if (LIS)
559 LIS->handleMove(*NewMI);
560 return SplitBB;
561}
562
563// Returns replace operands for a logical operation, either single result
564// for exec or two operands if source was another equivalent operation.
565void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
567 MachineOperand &Op = MI.getOperand(OpNo);
568 if (!Op.isReg() || !Op.getReg().isVirtual()) {
569 Src.push_back(Op);
570 return;
571 }
572
573 MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
574 if (!Def || Def->getParent() != MI.getParent() ||
575 !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
576 return;
577
578 // Make sure we do not modify exec between def and use.
579 // A copy with implicitly defined exec inserted earlier is an exclusion, it
580 // does not really modify exec.
581 for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
582 if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
583 !(I->isCopy() && I->getOperand(0).getReg() != Exec))
584 return;
585
586 for (const auto &SrcOp : Def->explicit_operands())
587 if (SrcOp.isReg() && SrcOp.isUse() &&
588 (SrcOp.getReg().isVirtual() || SrcOp.getReg() == Exec))
589 Src.push_back(SrcOp);
590}
591
592// Search and combine pairs of equivalent instructions, like
593// S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
594// S_OR_B64 x, (S_OR_B64 x, y) => S_OR_B64 x, y
595// One of the operands is exec mask.
596void SILowerControlFlow::combineMasks(MachineInstr &MI) {
597 assert(MI.getNumExplicitOperands() == 3);
599 unsigned OpToReplace = 1;
600 findMaskOperands(MI, 1, Ops);
601 if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
602 findMaskOperands(MI, 2, Ops);
603 if (Ops.size() != 3) return;
604
605 unsigned UniqueOpndIdx;
606 if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
607 else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
608 else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
609 else return;
610
611 Register Reg = MI.getOperand(OpToReplace).getReg();
612 MI.removeOperand(OpToReplace);
613 MI.addOperand(Ops[UniqueOpndIdx]);
614 if (MRI->use_empty(Reg))
615 MRI->getUniqueVRegDef(Reg)->eraseFromParent();
616}
617
618void SILowerControlFlow::optimizeEndCf() {
619 // If the only instruction immediately following this END_CF is another
620 // END_CF in the only successor we can avoid emitting exec mask restore here.
621 if (!EnableOptimizeEndCf)
622 return;
623
624 for (MachineInstr *MI : reverse(LoweredEndCf)) {
625 MachineBasicBlock &MBB = *MI->getParent();
626 auto Next =
627 skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
628 if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
629 continue;
630 // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
631 // If that belongs to SI_ELSE then saved mask has an inverted value.
632 Register SavedExec
633 = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
634 assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
635
636 const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
637 if (Def && LoweredIf.count(SavedExec)) {
638 LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
639 if (LIS)
642 if (LV)
643 Reg = TII->getNamedOperand(*MI, AMDGPU::OpName::src1)->getReg();
644 MI->eraseFromParent();
645 if (LV)
647 removeMBBifRedundant(MBB);
648 }
649 }
650}
651
652MachineBasicBlock *SILowerControlFlow::process(MachineInstr &MI) {
653 MachineBasicBlock &MBB = *MI.getParent();
655 MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
656
657 MachineBasicBlock *SplitBB = &MBB;
658
659 switch (MI.getOpcode()) {
660 case AMDGPU::SI_IF:
661 emitIf(MI);
662 break;
663
664 case AMDGPU::SI_ELSE:
665 emitElse(MI);
666 break;
667
668 case AMDGPU::SI_IF_BREAK:
669 emitIfBreak(MI);
670 break;
671
672 case AMDGPU::SI_LOOP:
673 emitLoop(MI);
674 break;
675
676 case AMDGPU::SI_WATERFALL_LOOP:
677 MI.setDesc(TII->get(AMDGPU::S_CBRANCH_EXECNZ));
678 break;
679
680 case AMDGPU::SI_END_CF:
681 SplitBB = emitEndCf(MI);
682 break;
683
684 default:
685 assert(false && "Attempt to process unsupported instruction");
686 break;
687 }
688
690 for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
691 Next = std::next(I);
692 MachineInstr &MaskMI = *I;
693 switch (MaskMI.getOpcode()) {
694 case AMDGPU::S_AND_B64:
695 case AMDGPU::S_OR_B64:
696 case AMDGPU::S_AND_B32:
697 case AMDGPU::S_OR_B32:
698 // Cleanup bit manipulations on exec mask
699 combineMasks(MaskMI);
700 break;
701 default:
702 I = MBB.end();
703 break;
704 }
705 }
706
707 return SplitBB;
708}
709
710bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &MBB) {
711 for (auto &I : MBB.instrs()) {
712 if (!I.isDebugInstr() && !I.isUnconditionalBranch())
713 return false;
714 }
715
716 assert(MBB.succ_size() == 1 && "MBB has more than one successor");
717
719 MachineBasicBlock *FallThrough = nullptr;
720
721 while (!MBB.predecessors().empty()) {
723 if (P->getFallThrough(false) == &MBB)
724 FallThrough = P;
725 P->ReplaceUsesOfBlockWith(&MBB, Succ);
726 }
727 MBB.removeSuccessor(Succ);
728 if (LIS) {
729 for (auto &I : MBB.instrs())
731 }
732 if (MDT) {
733 // If Succ, the single successor of MBB, is dominated by MBB, MDT needs
734 // updating by changing Succ's idom to the one of MBB; otherwise, MBB must
735 // be a leaf node in MDT and could be erased directly.
736 if (MDT->dominates(&MBB, Succ))
737 MDT->changeImmediateDominator(MDT->getNode(Succ),
738 MDT->getNode(&MBB)->getIDom());
739 MDT->eraseNode(&MBB);
740 }
741 MBB.clear();
743 if (FallThrough && !FallThrough->isLayoutSuccessor(Succ)) {
744 // Note: we cannot update block layout and preserve live intervals;
745 // hence we must insert a branch.
746 MachineInstr *BranchMI = BuildMI(*FallThrough, FallThrough->end(),
747 FallThrough->findBranchDebugLoc(), TII->get(AMDGPU::S_BRANCH))
748 .addMBB(Succ);
749 if (LIS)
750 LIS->InsertMachineInstrInMaps(*BranchMI);
751 }
752
753 return true;
754}
755
756bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) {
758 TII = ST.getInstrInfo();
759 TRI = &TII->getRegisterInfo();
760 EnableOptimizeEndCf = RemoveRedundantEndcf &&
761 MF.getTarget().getOptLevel() > CodeGenOptLevel::None;
762
763 // This doesn't actually need LiveIntervals, but we can preserve them.
764 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
765 LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
766 // This doesn't actually need LiveVariables, but we can preserve them.
767 auto *LVWrapper = getAnalysisIfAvailable<LiveVariablesWrapperPass>();
768 LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
769 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
770 MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
771 MRI = &MF.getRegInfo();
772 BoolRC = TRI->getBoolRC();
773
774 if (ST.isWave32()) {
775 AndOpc = AMDGPU::S_AND_B32;
776 OrOpc = AMDGPU::S_OR_B32;
777 XorOpc = AMDGPU::S_XOR_B32;
778 MovTermOpc = AMDGPU::S_MOV_B32_term;
779 Andn2TermOpc = AMDGPU::S_ANDN2_B32_term;
780 XorTermrOpc = AMDGPU::S_XOR_B32_term;
781 OrTermrOpc = AMDGPU::S_OR_B32_term;
782 OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B32;
783 Exec = AMDGPU::EXEC_LO;
784 } else {
785 AndOpc = AMDGPU::S_AND_B64;
786 OrOpc = AMDGPU::S_OR_B64;
787 XorOpc = AMDGPU::S_XOR_B64;
788 MovTermOpc = AMDGPU::S_MOV_B64_term;
789 Andn2TermOpc = AMDGPU::S_ANDN2_B64_term;
790 XorTermrOpc = AMDGPU::S_XOR_B64_term;
791 OrTermrOpc = AMDGPU::S_OR_B64_term;
792 OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B64;
793 Exec = AMDGPU::EXEC;
794 }
795
796 // Compute set of blocks with kills
797 const bool CanDemote =
799 for (auto &MBB : MF) {
800 bool IsKillBlock = false;
801 for (auto &Term : MBB.terminators()) {
802 if (TII->isKillTerminator(Term.getOpcode())) {
803 KillBlocks.insert(&MBB);
804 IsKillBlock = true;
805 break;
806 }
807 }
808 if (CanDemote && !IsKillBlock) {
809 for (auto &MI : MBB) {
810 if (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1) {
811 KillBlocks.insert(&MBB);
812 break;
813 }
814 }
815 }
816 }
817
818 bool Changed = false;
820 for (MachineFunction::iterator BI = MF.begin();
821 BI != MF.end(); BI = NextBB) {
822 NextBB = std::next(BI);
823 MachineBasicBlock *MBB = &*BI;
824
826 E = MBB->end();
827 for (I = MBB->begin(); I != E; I = Next) {
828 Next = std::next(I);
829 MachineInstr &MI = *I;
830 MachineBasicBlock *SplitMBB = MBB;
831
832 switch (MI.getOpcode()) {
833 case AMDGPU::SI_IF:
834 case AMDGPU::SI_ELSE:
835 case AMDGPU::SI_IF_BREAK:
836 case AMDGPU::SI_WATERFALL_LOOP:
837 case AMDGPU::SI_LOOP:
838 case AMDGPU::SI_END_CF:
839 SplitMBB = process(MI);
840 Changed = true;
841 break;
842 }
843
844 if (SplitMBB != MBB) {
845 MBB = Next->getParent();
846 E = MBB->end();
847 }
848 }
849 }
850
851 optimizeEndCf();
852
853 if (LIS) {
854 for (Register Reg : RecomputeRegs) {
855 LIS->removeInterval(Reg);
857 }
858 }
859
860 RecomputeRegs.clear();
861 LoweredEndCf.clear();
862 LoweredIf.clear();
863 KillBlocks.clear();
864
865 return Changed;
866}
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")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
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
unsigned const TargetRegisterInfo * TRI
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
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.
Represent the analysis usage information of a pass.
AnalysisUsage & addPreservedID(const void *ID)
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:33
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
Base class for the actual dominator tree node.
DomTreeNodeBase * getIDom() const
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:281
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
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)
void replaceKillInstruction(Register Reg, MachineInstr &OldMI, MachineInstr &NewMI)
replaceKillInstruction - Update register kill info by replacing a kill instruction with a new one.
void recomputeForSingleDefVirtReg(Register Reg)
Recompute liveness from scratch for a virtual register Reg that is known to have a single def that do...
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
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
iterator_range< iterator > terminators()
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.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineDomTreeNode * addNewBlock(MachineBasicBlock *BB, MachineBasicBlock *DomBB)
addNewBlock - Add a new node to the dominator tree information.
MachineDomTreeNode * getNode(MachineBasicBlock *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void eraseNode(MachineBasicBlock *BB)
eraseNode - Removes a node from the dominator tree.
bool dominates(const MachineDomTreeNode *A, const MachineDomTreeNode *B) const
void changeImmediateDominator(MachineBasicBlock *N, MachineBasicBlock *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
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 LLVMTargetMachine & 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:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:569
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:346
MachineOperand class - Representation of each machine instruction operand.
void setIsDead(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
void dump() const
Definition: Pass.cpp:136
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
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:84
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
static bool isVALU(const MachineInstr &MI)
Definition: SIInstrInfo.h:416
A vector that has set insertion semantics.
Definition: SetVector.h:57
void clear()
Completely clear the SetVector.
Definition: SetVector.h:273
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:264
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
void clear()
Definition: SmallSet.h:218
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition: SmallSet.h:236
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:179
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:696
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
Register getReg() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:185
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:97
self_iterator getIterator()
Definition: ilist_node.h:132
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:138
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
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.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
char & LiveVariablesID
LiveVariables pass - This pass computes the set of blocks in which each variable is life and sets mac...
char & SILowerControlFlowID
VarInfo - This represents the regions where a virtual register is live in the program.
Definition: LiveVariables.h:78
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:88