LLVM 24.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"
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 MachineDominatorTree *MDT = nullptr;
79 MachinePostDominatorTree *PDT = nullptr;
80 MachineRegisterInfo *MRI = nullptr;
81 SetVector<MachineInstr*> LoweredEndCf;
82 DenseSet<Register> LoweredIf;
84 SmallSet<Register, 8> RecomputeRegs;
85
86 const TargetRegisterClass *BoolRC = nullptr;
88
89 bool EnableOptimizeEndCf = false;
90
91 bool hasKill(const MachineBasicBlock *Begin, const MachineBasicBlock *End);
92
93 void emitIf(MachineInstr &MI);
94 void emitElse(MachineInstr &MI);
95 void emitIfBreak(MachineInstr &MI);
96 void emitLoop(MachineInstr &MI);
97
99
100 void findMaskOperands(MachineInstr &MI, unsigned OpNo,
102
103 void combineMasks(MachineInstr &MI);
104
105 bool removeMBBifRedundant(MachineBasicBlock &MBB);
106
108
109 // Skip to the next instruction, ignoring debug instructions, and trivial
110 // block boundaries (blocks that have one (typically fallthrough) successor,
111 // and the successor has one predecessor.
113 skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
115
116 /// Find the insertion point for a new conditional branch.
118 skipToUncondBrOrEnd(MachineBasicBlock &MBB,
120 assert(I->isTerminator());
121
122 // FIXME: What if we had multiple pre-existing conditional branches?
124 while (I != End && !I->isUnconditionalBranch())
125 ++I;
126 return I;
127 }
128
129 // Remove redundant SI_END_CF instructions.
130 void optimizeEndCf();
131
132public:
133 SILowerControlFlow(const GCNSubtarget *ST, LiveIntervals *LIS,
134 MachineDominatorTree *MDT, MachinePostDominatorTree *PDT)
135 : LIS(LIS), MDT(MDT), PDT(PDT), LMC(AMDGPU::LaneMaskConstants::get(*ST)) {
136 }
137 bool run(MachineFunction &MF);
138};
139
140class SILowerControlFlowLegacy : public MachineFunctionPass {
141public:
142 static char ID;
143
144 SILowerControlFlowLegacy() : MachineFunctionPass(ID) {}
145
146 bool runOnMachineFunction(MachineFunction &MF) override;
147
148 StringRef getPassName() const override {
149 return "SI Lower control flow pseudo instructions";
150 }
151
152 void getAnalysisUsage(AnalysisUsage &AU) const override {
153 AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
154 // Should preserve the same set that TwoAddressInstructions does.
155 AU.addPreserved<MachineDominatorTreeWrapperPass>();
156 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
157 AU.addPreserved<SlotIndexesWrapperPass>();
158 AU.addPreserved<LiveIntervalsWrapperPass>();
159 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
160 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
162 }
163};
164
165} // end anonymous namespace
166
167char SILowerControlFlowLegacy::ID = 0;
168
169INITIALIZE_PASS(SILowerControlFlowLegacy, DEBUG_TYPE, "SI lower control flow",
170 false, false)
171
172static void setImpSCCDefDead(MachineInstr &MI, bool IsDead = true) {
173 MachineOperand &ImpDefSCC = MI.getOperand(3);
174 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
175
176 ImpDefSCC.setIsDead(IsDead);
177}
178
179static void copySCCDefDead(MachineInstr &MI, const MachineOperand &OrigSCCDef) {
180 assert(OrigSCCDef.getReg() == AMDGPU::SCC && OrigSCCDef.isDef());
181 setImpSCCDefDead(MI, OrigSCCDef.isDead());
182}
183
184char &llvm::SILowerControlFlowLegacyID = SILowerControlFlowLegacy::ID;
185
186bool SILowerControlFlow::hasKill(const MachineBasicBlock *Begin,
187 const MachineBasicBlock *End) {
188 DenseSet<const MachineBasicBlock*> Visited;
189 SmallVector<MachineBasicBlock *, 4> Worklist(Begin->successors());
190
191 while (!Worklist.empty()) {
192 MachineBasicBlock *MBB = Worklist.pop_back_val();
193
194 if (MBB == End || !Visited.insert(MBB).second)
195 continue;
196 if (KillBlocks.contains(MBB))
197 return true;
198
199 Worklist.append(MBB->succ_begin(), MBB->succ_end());
200 }
201
202 return false;
203}
204
205static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
206 Register SaveExecReg = MI.getOperand(0).getReg();
207 auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
208
209 if (U == MRI->use_instr_nodbg_end() ||
210 std::next(U) != MRI->use_instr_nodbg_end() ||
211 U->getOpcode() != AMDGPU::SI_END_CF)
212 return false;
213
214 return true;
215}
216
217void SILowerControlFlow::emitIf(MachineInstr &MI) {
218 MachineBasicBlock &MBB = *MI.getParent();
219 const DebugLoc &DL = MI.getDebugLoc();
221 Register SaveExecReg = MI.getOperand(0).getReg();
222 MachineOperand& Cond = MI.getOperand(1);
223 assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
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)
243 .addReg(LMC.ExecReg, RegState::ImplicitDefine);
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 setImpSCCDefDead(*And);
251
252 MachineInstr *Xor = nullptr;
253 if (!SimpleIf) {
254 Xor = BuildMI(MBB, I, DL, TII->get(LMC.XorOpc), SaveExecReg)
255 .addReg(Tmp)
256 .addReg(CopyReg);
257 copySCCDefDead(*Xor, MI.getOperand(4));
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(LMC.MovTermOpc), LMC.ExecReg).addReg(Tmp);
264
265 // Skip ahead to the unconditional branch in case there are other terminators
266 // present.
267 I = skipToUncondBrOrEnd(MBB, I);
268
269 // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
270 // during SIPreEmitPeephole.
271 MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
272 .add(MI.getOperand(2));
273
274 if (!LIS) {
275 MI.eraseFromParent();
276 return;
277 }
278
279 LIS->InsertMachineInstrInMaps(*CopyExec);
280
281 // Replace with and so we don't need to fix the live interval for condition
282 // register.
284
285 if (!SimpleIf)
287 LIS->InsertMachineInstrInMaps(*SetExec);
288 LIS->InsertMachineInstrInMaps(*NewBr);
289
290 MI.eraseFromParent();
291
292 // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
293 // hard to add another def here but I'm not sure how to correctly update the
294 // valno.
295 RecomputeRegs.insert(SaveExecReg);
297 if (!SimpleIf)
299}
300
301void SILowerControlFlow::emitElse(MachineInstr &MI) {
302 MachineBasicBlock &MBB = *MI.getParent();
303 const DebugLoc &DL = MI.getDebugLoc();
304
305 Register DstReg = MI.getOperand(0).getReg();
306 Register SrcReg = MI.getOperand(1).getReg();
307
309
310 // This must be inserted before phis and any spill code inserted before the
311 // else.
312 Register SaveReg = MRI->createVirtualRegister(BoolRC);
313 MachineInstr *OrSaveExec =
314 BuildMI(MBB, Start, DL, TII->get(LMC.OrSaveExecOpc), SaveReg)
315 .add(MI.getOperand(1)); // Saved EXEC
316 setImpSCCDefDead(*OrSaveExec, /*IsDead=*/true);
317
318 MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
319
321
322 // This accounts for any modification of the EXEC mask within the block and
323 // can be optimized out pre-RA when not required.
324 MachineInstr *And = BuildMI(MBB, ElsePt, DL, TII->get(LMC.AndOpc), DstReg)
325 .addReg(LMC.ExecReg)
326 .addReg(SaveReg);
327 setImpSCCDefDead(*And, /*IsDead=*/true);
328
329 MachineInstr *Xor =
330 BuildMI(MBB, ElsePt, DL, TII->get(LMC.XorTermOpc), LMC.ExecReg)
331 .addReg(LMC.ExecReg)
332 .addReg(DstReg);
333 copySCCDefDead(*Xor, MI.getOperand(4));
334
335 // Skip ahead to the unconditional branch in case there are other terminators
336 // present.
337 ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
338
339 MachineInstr *Branch =
340 BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
341 .addMBB(DestBB);
342
343 if (!LIS) {
344 MI.eraseFromParent();
345 return;
346 }
347
349 MI.eraseFromParent();
350
351 LIS->InsertMachineInstrInMaps(*OrSaveExec);
353
355 LIS->InsertMachineInstrInMaps(*Branch);
356
357 RecomputeRegs.insert(SrcReg);
358 RecomputeRegs.insert(DstReg);
360}
361
362void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
363 MachineBasicBlock &MBB = *MI.getParent();
364 const DebugLoc &DL = MI.getDebugLoc();
365 auto Dst = MI.getOperand(0).getReg();
366
367 // Skip ANDing with exec if the break condition is already masked by exec
368 // because it is a V_CMP in the same basic block. (We know the break
369 // condition operand was an i1 in IR, so if it is a VALU instruction it must
370 // be one with a carry-out.)
371 bool SkipAnding = false;
372 if (MI.getOperand(1).isReg()) {
373 if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
374 SkipAnding = Def->getParent() == MI.getParent() &&
375 SIInstrInfo::isVALU(*Def, /*AllowLDSDMA=*/false);
376 }
377 }
378
379 // AND the break condition operand with exec, then OR that into the "loop
380 // exit" mask.
381 MachineInstr *And = nullptr, *Or = nullptr;
382 Register AndReg;
383 if (!SkipAnding) {
384 AndReg = MRI->createVirtualRegister(BoolRC);
385 And = BuildMI(MBB, &MI, DL, TII->get(LMC.AndOpc), AndReg)
386 .addReg(LMC.ExecReg)
387 .add(MI.getOperand(1));
388 setImpSCCDefDead(*And, /*IsDead=*/true);
389 Or = BuildMI(MBB, &MI, DL, TII->get(LMC.OrOpc), Dst)
390 .addReg(AndReg)
391 .add(MI.getOperand(2));
392 } else {
393 Or = BuildMI(MBB, &MI, DL, TII->get(LMC.OrOpc), Dst)
394 .add(MI.getOperand(1))
395 .add(MI.getOperand(2));
396 }
397
398 copySCCDefDead(*Or, MI.getOperand(3));
399
400 if (LIS) {
402 if (And) {
403 // Read of original operand 1 is on And now not Or.
404 RecomputeRegs.insert(And->getOperand(2).getReg());
407 }
408 }
409
410 MI.eraseFromParent();
411}
412
413void SILowerControlFlow::emitLoop(MachineInstr &MI) {
414 MachineBasicBlock &MBB = *MI.getParent();
415 const DebugLoc &DL = MI.getDebugLoc();
416
417 MachineInstr *AndN2 =
418 BuildMI(MBB, &MI, DL, TII->get(LMC.AndN2TermOpc), LMC.ExecReg)
419 .addReg(LMC.ExecReg)
420 .add(MI.getOperand(0));
421 copySCCDefDead(*AndN2, MI.getOperand(3));
422
423 auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
424 MachineInstr *Branch =
425 BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
426 .add(MI.getOperand(1));
427
428 if (LIS) {
429 RecomputeRegs.insert(MI.getOperand(0).getReg());
430 LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
431 LIS->InsertMachineInstrInMaps(*Branch);
432 }
433
434 MI.eraseFromParent();
435}
436
438SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
439 MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
440
441 SmallPtrSet<const MachineBasicBlock *, 4> Visited;
442 MachineBasicBlock *B = &MBB;
443 do {
444 if (!Visited.insert(B).second)
445 return MBB.end();
446
447 auto E = B->end();
448 for ( ; It != E; ++It) {
449 if (TII->mayReadEXEC(*MRI, *It))
450 break;
451 }
452
453 if (It != E)
454 return It;
455
456 if (B->succ_size() != 1)
457 return MBB.end();
458
459 // If there is one trivial successor, advance to the next block.
460 MachineBasicBlock *Succ = *B->succ_begin();
461
462 It = Succ->begin();
463 B = Succ;
464 } while (true);
465}
466
467MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &MI) {
468 MachineBasicBlock &MBB = *MI.getParent();
469 const DebugLoc &DL = MI.getDebugLoc();
470
472
473 // If we have instructions that aren't prolog instructions, split the block
474 // and emit a terminator instruction. This ensures correct spill placement.
475 // FIXME: We should unconditionally split the block here.
476 bool NeedBlockSplit = false;
477 Register DataReg = MI.getOperand(0).getReg();
478 for (MachineBasicBlock::iterator I = InsPt, E = MI.getIterator();
479 I != E; ++I) {
480 if (I->modifiesRegister(DataReg, TRI)) {
481 NeedBlockSplit = true;
482 break;
483 }
484 }
485
486 unsigned Opcode = LMC.OrOpc;
487 MachineBasicBlock *SplitBB = &MBB;
488 if (NeedBlockSplit) {
489 SplitBB = MBB.splitAt(MI, /*UpdateLiveIns*/true, LIS);
490 if (SplitBB != &MBB && (MDT || PDT)) {
491 using DomTreeT = DomTreeBase<MachineBasicBlock>;
493 for (MachineBasicBlock *Succ : SplitBB->successors()) {
494 DTUpdates.push_back({DomTreeT::Insert, SplitBB, Succ});
495 DTUpdates.push_back({DomTreeT::Delete, &MBB, Succ});
496 }
497 DTUpdates.push_back({DomTreeT::Insert, &MBB, SplitBB});
498 if (MDT)
499 MDT->applyUpdates(DTUpdates);
500 if (PDT)
501 PDT->applyUpdates(DTUpdates);
502 }
503 Opcode = LMC.OrTermOpc;
504 InsPt = MI;
505 }
506
507 MachineInstr *NewMI = BuildMI(MBB, InsPt, DL, TII->get(Opcode), LMC.ExecReg)
508 .addReg(LMC.ExecReg)
509 .add(MI.getOperand(0));
510 copySCCDefDead(*NewMI, MI.getOperand(2));
511
512 LoweredEndCf.insert(NewMI);
513
514 if (LIS)
515 LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
516
517 MI.eraseFromParent();
518
519 if (LIS)
520 LIS->handleMove(*NewMI);
521 return SplitBB;
522}
523
524// Returns replace operands for a logical operation, either single result
525// for exec or two operands if source was another equivalent operation.
526void SILowerControlFlow::findMaskOperands(
527 MachineInstr &MI, unsigned OpNo,
528 SmallVectorImpl<MachineOperand *> &Src) const {
529 MachineOperand &Op = MI.getOperand(OpNo);
530 if (!Op.isReg() || !Op.getReg().isVirtual()) {
531 Src.push_back(&Op);
532 return;
533 }
534
535 MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
536 if (!Def || Def->getParent() != MI.getParent() ||
537 !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
538 return;
539
540 // Make sure we do not modify exec between def and use.
541 // A copy with implicitly defined exec inserted earlier is an exclusion, it
542 // does not really modify exec.
543 for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
544 if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
545 !(I->isCopy() && I->getOperand(0).getReg() != LMC.ExecReg))
546 return;
547
548 for (MachineOperand &SrcOp : Def->explicit_operands())
549 if (SrcOp.isReg() && SrcOp.isUse() &&
550 (SrcOp.getReg().isVirtual() || SrcOp.getReg() == LMC.ExecReg))
551 Src.push_back(&SrcOp);
552}
553
554// Search and combine pairs of equivalent instructions, like
555// S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
556// S_OR_B64 x, (S_OR_B64 x, y) => S_OR_B64 x, y
557// One of the operands is exec mask.
558void SILowerControlFlow::combineMasks(MachineInstr &MI) {
559 assert(MI.getNumExplicitOperands() == 3);
561 findMaskOperands(MI, 1, Src1);
562 findMaskOperands(MI, 2, Src2);
563
564 // Exactly one of the two operands must resolve to the nested LHS and RHS.
565 // Another one must resolve to a single value, exec or its copy.
566 unsigned OpToReplace;
567 MachineOperand *Leaf, *NestedLHS, *NestedRHS;
568 if (Src1.size() == 2 && Src2.size() == 1) {
569 OpToReplace = 1;
570 NestedLHS = Src1[0];
571 NestedRHS = Src1[1];
572 Leaf = Src2[0];
573 } else if (Src1.size() == 1 && Src2.size() == 2) {
574 OpToReplace = 2;
575 Leaf = Src1[0];
576 NestedLHS = Src2[0];
577 NestedRHS = Src2[1];
578 } else {
579 return;
580 }
581
582 // Always keep a nested operand, never the leaf operand.
583 MachineOperand *KeepOp;
584 if (Leaf->isIdenticalTo(*NestedLHS))
585 KeepOp = NestedRHS;
586 else if (Leaf->isIdenticalTo(*NestedRHS) ||
587 NestedLHS->isIdenticalTo(*NestedRHS))
588 KeepOp = NestedLHS;
589 else
590 return;
591
592 Register Reg = MI.getOperand(OpToReplace).getReg();
593 MI.removeOperand(OpToReplace);
594 MI.addOperand(*KeepOp);
595 if (MRI->use_empty(Reg))
597}
598
599void SILowerControlFlow::optimizeEndCf() {
600 // If the only instruction immediately following this END_CF is another
601 // END_CF in the only successor we can avoid emitting exec mask restore here.
602 if (!EnableOptimizeEndCf)
603 return;
604
605 for (MachineInstr *MI : reverse(LoweredEndCf)) {
606 MachineBasicBlock &MBB = *MI->getParent();
607 auto Next =
608 skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
609 if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
610 continue;
611 // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
612 // If that belongs to SI_ELSE then saved mask has an inverted value.
613 Register SavedExec
614 = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
615 assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
616
617 const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
618 if (Def && LoweredIf.count(SavedExec)) {
619 LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
620 if (LIS)
622 MI->eraseFromParent();
623 removeMBBifRedundant(MBB);
624 }
625 }
626}
627
628MachineBasicBlock *SILowerControlFlow::process(MachineInstr &MI) {
629 MachineBasicBlock &MBB = *MI.getParent();
631 MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
632
633 MachineBasicBlock *SplitBB = &MBB;
634
635 switch (MI.getOpcode()) {
636 case AMDGPU::SI_IF:
637 emitIf(MI);
638 break;
639
640 case AMDGPU::SI_ELSE:
641 emitElse(MI);
642 break;
643
644 case AMDGPU::SI_IF_BREAK:
645 emitIfBreak(MI);
646 break;
647
648 case AMDGPU::SI_LOOP:
649 emitLoop(MI);
650 break;
651
652 case AMDGPU::SI_WATERFALL_LOOP:
653 MI.setDesc(TII->get(AMDGPU::S_CBRANCH_EXECNZ));
654 break;
655
656 case AMDGPU::SI_END_CF:
657 SplitBB = emitEndCf(MI);
658 break;
659
660 default:
661 assert(false && "Attempt to process unsupported instruction");
662 break;
663 }
664
666 for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
667 Next = std::next(I);
668 MachineInstr &MaskMI = *I;
669 switch (MaskMI.getOpcode()) {
670 case AMDGPU::S_AND_B64:
671 case AMDGPU::S_OR_B64:
672 case AMDGPU::S_AND_B32:
673 case AMDGPU::S_OR_B32:
674 // Cleanup bit manipulations on exec mask
675 combineMasks(MaskMI);
676 break;
677 default:
678 I = MBB.end();
679 break;
680 }
681 }
682
683 return SplitBB;
684}
685
686bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &MBB) {
687 for (auto &I : MBB.instrs()) {
688 if (!I.isDebugInstr() && !I.isUnconditionalBranch())
689 return false;
690 }
691
692 assert(MBB.succ_size() == 1 && "MBB has more than one successor");
693
694 MachineBasicBlock *Succ = *MBB.succ_begin();
695 MachineBasicBlock *FallThrough = nullptr;
696
697 using DomTreeT = DomTreeBase<MachineBasicBlock>;
699
700 while (!MBB.predecessors().empty()) {
701 MachineBasicBlock *P = *MBB.pred_begin();
702 if (P->getFallThrough(false) == &MBB)
703 FallThrough = P;
705 DTUpdates.push_back({DomTreeT::Insert, P, Succ});
706 DTUpdates.push_back({DomTreeT::Delete, P, &MBB});
707 }
708 MBB.removeSuccessor(Succ);
709 if (LIS) {
710 // Registers live across MBB have intervals spanning it, which must be
711 // recomputed once it is erased. removeMBBifRedundant only runs from
712 // optimizeEndCf, so defer to the pass-wide RecomputeRegs handling.
713 SlotIndex StartIdx = LIS->getMBBStartIdx(&MBB);
714 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
715 Register Reg = Register::index2VirtReg(I);
716 if (!LIS->hasInterval(Reg))
717 continue;
718 const LiveInterval &LI = LIS->getInterval(Reg);
719 if (LI.liveAt(StartIdx) || LI.liveAt(StartIdx.getPrevSlot()))
720 RecomputeRegs.insert(Reg);
721 }
722
723 for (auto &I : MBB.instrs())
725
726 // Drop MBB from the slot index maps before it is erased.
728 }
729 if (MDT)
730 MDT->applyUpdates(DTUpdates);
731 if (PDT)
732 PDT->applyUpdates(DTUpdates);
733
734 if (MDT && MDT->getNode(&MBB))
735 MDT->eraseNode(&MBB);
736 if (PDT && PDT->getNode(&MBB))
737 PDT->eraseNode(&MBB);
738
739 MBB.clear();
741 if (FallThrough && !FallThrough->isLayoutSuccessor(Succ)) {
742 // Note: we cannot update block layout and preserve live intervals;
743 // hence we must insert a branch.
744 MachineInstr *BranchMI = BuildMI(*FallThrough, FallThrough->end(),
745 FallThrough->findBranchDebugLoc(), TII->get(AMDGPU::S_BRANCH))
746 .addMBB(Succ);
747 if (LIS)
748 LIS->InsertMachineInstrInMaps(*BranchMI);
749 }
750
751 return true;
752}
753
754bool SILowerControlFlow::run(MachineFunction &MF) {
755 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
756 TII = ST.getInstrInfo();
757 TRI = &TII->getRegisterInfo();
758 EnableOptimizeEndCf = RemoveRedundantEndcf &&
759 MF.getTarget().getOptLevel() > CodeGenOptLevel::None;
760
761 MRI = &MF.getRegInfo();
762 BoolRC = TRI->getBoolRC();
763
764 // Compute set of blocks with kills
765 const bool CanDemote =
766 MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
767 for (auto &MBB : MF) {
768 bool IsKillBlock = false;
769 for (auto &Term : MBB.terminators()) {
770 if (TII->isKillTerminator(Term.getOpcode())) {
771 KillBlocks.insert(&MBB);
772 IsKillBlock = true;
773 break;
774 }
775 }
776 if (CanDemote && !IsKillBlock) {
777 for (auto &MI : MBB) {
778 if (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1) {
779 KillBlocks.insert(&MBB);
780 break;
781 }
782 }
783 }
784 }
785
786 bool Changed = false;
788 for (MachineFunction::iterator BI = MF.begin();
789 BI != MF.end(); BI = NextBB) {
790 NextBB = std::next(BI);
791 MachineBasicBlock *MBB = &*BI;
792
794 E = MBB->end();
795 for (I = MBB->begin(); I != E; I = Next) {
796 Next = std::next(I);
797 MachineInstr &MI = *I;
798 MachineBasicBlock *SplitMBB = MBB;
799
800 switch (MI.getOpcode()) {
801 case AMDGPU::SI_IF:
802 case AMDGPU::SI_ELSE:
803 case AMDGPU::SI_IF_BREAK:
804 case AMDGPU::SI_WATERFALL_LOOP:
805 case AMDGPU::SI_LOOP:
806 case AMDGPU::SI_END_CF:
807 SplitMBB = process(MI);
808 Changed = true;
809 break;
810 }
811
812 if (SplitMBB != MBB) {
813 MBB = Next->getParent();
814 E = MBB->end();
815 }
816 }
817 }
818
819 optimizeEndCf();
820
821 if (LIS && Changed) {
822 // These will need to be recomputed for insertions and removals.
823 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
824 LIS->removeAllRegUnitsForPhysReg(AMDGPU::SCC);
825 for (Register Reg : RecomputeRegs) {
826 LIS->removeInterval(Reg);
828 }
829 }
830
831 RecomputeRegs.clear();
832 LoweredEndCf.clear();
833 LoweredIf.clear();
834 KillBlocks.clear();
835
836 return Changed;
837}
838
839bool SILowerControlFlowLegacy::runOnMachineFunction(MachineFunction &MF) {
840 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
841 // This doesn't actually need LiveIntervals, but we can preserve them.
842 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
843 LiveIntervals *LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
844 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
845 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
846 auto *PDTWrapper =
847 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
848 MachinePostDominatorTree *PDT =
849 PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
850 return SILowerControlFlow(ST, LIS, MDT, PDT).run(MF);
851}
852
853PreservedAnalyses
856 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
862
863 bool Changed = SILowerControlFlow(ST, LIS, MDT, PDT).run(MF);
864 if (!Changed)
865 return PreservedAnalyses::all();
866
868 PA.preserve<MachineDominatorTreeAnalysis>();
870 PA.preserve<SlotIndexesAnalysis>();
871 PA.preserve<LiveIntervalsAnalysis>();
872 PA.preserve<MachineBlockFrequencyAnalysis>();
873 return PA;
874}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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
#define I(x, y, z)
Definition MD5.cpp:57
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)
bool IsDead
static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI)
#define LLVM_DEBUG(...)
Definition Debug.h:119
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:281
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
const HexagonRegisterInfo & getRegisterInfo() const
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
bool hasInterval(Register Reg) const
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
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.
SlotIndexes * getSlotIndexes() const
void RemoveMachineInstrFromMaps(MachineInstr &MI)
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
bool liveAt(SlotIndex index) const
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.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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 & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
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
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
void setIsDead(bool Val=true)
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
static use_instr_nodbg_iterator use_instr_nodbg_end()
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
static bool isVALU(const MachineInstr &MI, bool AllowLDSDMA)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
LLVM_ABI void removeMBBFromMaps(MachineBasicBlock &MBB)
Inverse of insertMBBInMaps: merge MBB's slot range into its layout predecessor and drop it from the m...
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: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:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
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:187
self_iterator getIterator()
Definition ilist_node.h:123
Changed
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.
char & SILowerControlFlowLegacyID
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:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
DWARFExpression::Operation Op
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58