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