LLVM 24.0.0git
SILowerI1Copies.cpp
Go to the documentation of this file.
1//===-- SILowerI1Copies.cpp - Lower I1 Copies -----------------------------===//
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// This pass lowers all occurrences of i1 values (with a vreg_1 register class)
10// to lane masks (32 / 64-bit scalar registers). The pass assumes machine SSA
11// form and a wave-level control flow graph.
12//
13// Before this pass, values that are semantically i1 and are defined and used
14// within the same basic block are already represented as lane masks in scalar
15// registers. However, values that cross basic blocks are always transferred
16// between basic blocks in vreg_1 virtual registers and are lowered by this
17// pass.
18//
19// The only instructions that use or define vreg_1 virtual registers are COPY,
20// PHI, and IMPLICIT_DEF.
21//
22//===----------------------------------------------------------------------===//
23
24#include "SILowerI1Copies.h"
25#include "AMDGPU.h"
28
29#define DEBUG_TYPE "si-i1-copies"
30
31using namespace llvm;
32
33static Register
35 MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs);
36
37namespace {
38
39class Vreg1LoweringHelper : public AMDGPU::PhiLoweringHelper {
40public:
41 Vreg1LoweringHelper(MachineFunction &MF, MachineDominatorTree &DT,
43
44private:
45 DenseSet<Register> ConstrainRegs;
46
47public:
48 void markAsLaneMask(Register DstReg) const override;
49 void getCandidatesForLowering(
50 SmallVectorImpl<MachineInstr *> &Vreg1Phis) const override;
51 void collectIncomingValuesFromPhi(
52 const MachineInstr *MI,
53 SmallVectorImpl<AMDGPU::Incoming> &Incomings) const override;
54 void replaceDstReg(Register NewReg, Register OldReg,
55 MachineBasicBlock *MBB) override;
56 void buildMergeLaneMasks(MachineBasicBlock &MBB,
58 Register DstReg, Register PrevReg,
59 Register CurReg) override;
60 void constrainAsLaneMask(AMDGPU::Incoming &In) override;
61
62 bool lowerCopiesFromI1();
63 bool lowerCopiesToI1();
64 bool cleanConstrainRegs(bool Changed);
65 bool isVreg1(Register Reg) const {
66 return Reg.isVirtual() && MRI->getRegClass(Reg) == &AMDGPU::VReg_1RegClass;
67 }
68};
69
70Vreg1LoweringHelper::Vreg1LoweringHelper(MachineFunction &MF,
73 : PhiLoweringHelper(MF, DT, PDT) {}
74
75bool Vreg1LoweringHelper::cleanConstrainRegs(bool Changed) {
76 assert(Changed || ConstrainRegs.empty());
77 for (Register Reg : ConstrainRegs)
78 MRI->constrainRegClass(Reg, TII->getRegisterInfo().getWaveMaskRegClass());
79 ConstrainRegs.clear();
80
81 return Changed;
82}
83
84} // end anonymous namespace
85
86/// Return true if \p Latch -> \p Header is the only back-edge of a loop that
87/// is left as a whole, so that EXEC is the same on every iteration at the
88/// header and at the end of the latch.
89///
90/// This relies on the control flow being structurized: lanes can only leave a
91/// loop at different times through SI_IF_BREAK/SI_LOOP on a back-edge, and a
92/// divergent SI_IF/SI_ELSE region is closed by its SI_END_CF before any edge
93/// leaves it. So if the only back-edge ends in a uniform branch, every exit,
94/// including a uniform early exit, is taken by the whole wave, and EXEC at the
95/// end of the latch is EXEC at the header.
97 const MachineBasicBlock &Header,
98 const MachineDominatorTree &DT,
99 const SIInstrInfo &TII) {
100 assert(Latch.isSuccessor(&Header) && "expected a CFG edge");
101 return !TII.hasDivergentBranch(&Latch) &&
102 all_of(Header.predecessors(),
103 [&](const MachineBasicBlock *Pred) {
104 return Pred == &Latch || !DT.dominates(&Header, Pred);
105 }) &&
106 DT.dominates(&Header, &Latch);
107}
108
109namespace llvm {
110namespace AMDGPU {
111
112/// Helper class that determines the relationship between incoming values of a
113/// phi in the control flow graph to determine where an incoming value can
114/// simply be taken as a scalar lane mask as-is, and where it needs to be
115/// merged with another, previously defined lane mask.
116///
117/// The approach is as follows:
118/// - Determine all basic blocks which, starting from the incoming blocks,
119/// a wave may reach before entering the def block (the block containing the
120/// phi).
121/// - If an incoming block has no predecessors in this set, we can take the
122/// incoming value as a scalar lane mask as-is.
123/// -- A special case of this is when the def block has a self-loop.
124/// -- An edge from the def block to an incoming block does not count, since
125/// it starts a new trip around a loop through the def block.
126/// - Otherwise, the incoming value needs to be merged with a previously
127/// defined lane mask.
128/// - If there is a path into the set of reachable blocks that does _not_ go
129/// through an incoming block where we can take the scalar lane mask as-is,
130/// we need to invent an available value for the SSAUpdater. Choices are
131/// 0 and undef, with differing consequences for how to merge values etc.
132///
133/// TODO: We could use region analysis to quickly skip over SESE regions during
134/// the traversal.
135///
138 const SIInstrInfo *TII;
139
140 // For each reachable basic block, whether it is a source in the induced
141 // subgraph of the CFG.
145
146public:
148 : PDT(PDT), TII(TII) {}
149
150 /// Returns whether \p MBB is a source in the induced subgraph of reachable
151 /// blocks.
153 return ReachableMap.find(&MBB)->second;
154 }
155
156 ArrayRef<MachineBasicBlock *> predecessors() const { return Predecessors; }
157
159 ArrayRef<AMDGPU::Incoming> Incomings) {
160 assert(Stack.empty());
161 ReachableMap.clear();
162 Predecessors.clear();
163
164 // Insert the def block first, so that it acts as an end point for the
165 // traversal.
166 ReachableMap.try_emplace(&DefBlock, false);
167
168 for (auto Incoming : Incomings) {
170 if (MBB == &DefBlock) {
171 ReachableMap[&DefBlock] = true; // self-loop on DefBlock
172 continue;
173 }
174
175 // If this block has a divergent terminator and the def block is its
176 // post-dominator, the wave may first visit the other successors.
177 if (TII->hasDivergentBranch(MBB) && PDT.dominates(&DefBlock, MBB))
178 Stack.push_back(MBB);
179 }
180
181 while (!Stack.empty()) {
182 MachineBasicBlock *MBB = Stack.pop_back_val();
183 if (ReachableMap.try_emplace(MBB, false).second)
184 append_range(Stack, MBB->successors());
185 }
186
187 // Insert remaining incoming blocks.
188 for (auto Incoming : Incomings) {
190 ReachableMap.try_emplace(MBB, false);
191 }
192
193 for (auto &[MBB, IsSource] : ReachableMap) {
194 bool HaveReachablePred = false;
195 for (MachineBasicBlock *Pred : MBB->predecessors()) {
196 // An edge from the def block starts a new trip around a cycle through
197 // the def block. Every lane that is active at the def block at the end
198 // of that trip was active at the end of MBB, since MBB's terminator
199 // cannot enable more lanes.
200 if (Pred == &DefBlock) {
201 assert(llvm::none_of(MBB->terminators(),
202 [](const MachineInstr &MI) {
203 return MI.getOpcode() == AMDGPU::SI_ELSE;
204 }) &&
205 "SI_ELSE block in a cycle through the def block");
206 continue;
207 }
208 if (ReachableMap.count(Pred)) {
209 HaveReachablePred = true;
210 } else {
211 Stack.push_back(Pred);
212 }
213 }
214 if (!HaveReachablePred)
215 IsSource = true;
216 if (HaveReachablePred) {
217 for (MachineBasicBlock *UnreachablePred : Stack) {
218 if (!llvm::is_contained(Predecessors, UnreachablePred))
219 Predecessors.push_back(UnreachablePred);
220 }
221 }
222 Stack.clear();
223 }
224 }
225};
226
227/// Helper class that detects loops which require us to lower an i1 COPY into
228/// bitwise manipulation.
229///
230/// Unfortunately, we cannot use LoopInfo because LoopInfo does not distinguish
231/// between loops with the same header. Consider this example:
232///
233/// A-+-+
234/// | | |
235/// B-+ |
236/// | |
237/// C---+
238///
239/// A is the header of a loop containing A, B, and C as far as LoopInfo is
240/// concerned. However, an i1 COPY in B that is used in C must be lowered to
241/// bitwise operations to combine results from different loop iterations when
242/// B has a divergent branch (since by default we will compile this code such
243/// that threads in a wave are merged at the entry of C).
244///
245/// The following rule is implemented to determine whether bitwise operations
246/// are required: use the bitwise lowering for a def in block B if a backward
247/// edge to B is reachable without going through the nearest common
248/// post-dominator of B and all uses of the def.
249///
250/// Back-edges of loops whose EXEC is the same on every iteration (see
251/// isExecInvariantBackEdge) are not followed: all lanes run every iteration
252/// and leave the loop together, so no lane can observe a value from an older
253/// iteration.
254///
255/// TODO: This rule is conservative because it does not check whether the
256/// relevant branches are actually divergent, apart from the case above.
257///
258/// The class is designed to cache the CFG traversal so that it can be re-used
259/// for multiple defs within the same basic block.
260///
261/// TODO: We could use region analysis to quickly skip over SESE regions during
262/// the traversal.
263///
267 const SIInstrInfo *TII;
268
269 // All visited / reachable block, tagged by level (level 0 is the def block,
270 // level 1 are all blocks reachable including but not going through the def
271 // block's IPDOM, etc.).
273
274 // Nearest common dominator of all visited blocks by level (level 0 is the
275 // def block). Used for seeding the SSAUpdater.
277
278 // Post-dominator of all visited blocks.
279 MachineBasicBlock *VisitedPostDom = nullptr;
280
281 // Level at which a loop was found: 0 is not possible; 1 = a backward edge is
282 // reachable without going through the IPDOM of the def block (if the IPDOM
283 // itself has an edge to the def block, the loop level is 2), etc.
284 unsigned FoundLoopLevel = ~0u;
285
286 MachineBasicBlock *DefBlock = nullptr;
289
290public:
292 const SIInstrInfo *TII)
293 : DT(DT), PDT(PDT), TII(TII) {}
294
296 Visited.clear();
297 CommonDominators.clear();
298 Stack.clear();
299 NextLevel.clear();
300 VisitedPostDom = nullptr;
301 FoundLoopLevel = ~0u;
302
303 DefBlock = &MBB;
304 }
305
306 /// Check whether a backward edge can be reached without going through the
307 /// given \p PostDom of the def block.
308 ///
309 /// Return the level of \p PostDom if a loop was found, or 0 otherwise.
310 unsigned findLoop(MachineBasicBlock *PostDom) {
311 MachineDomTreeNode *PDNode = PDT.getNode(DefBlock);
312
313 if (!VisitedPostDom)
314 advanceLevel();
315
316 unsigned Level = 0;
317 while (PDNode->getBlock() != PostDom) {
318 if (PDNode->getBlock() == VisitedPostDom)
319 advanceLevel();
320 PDNode = PDNode->getIDom();
321 Level++;
322 if (FoundLoopLevel == Level)
323 return Level;
324 }
325
326 return 0;
327 }
328
329 /// Add undef values dominating the loop and the optionally given additional
330 /// blocks, so that the SSA updater doesn't have to search all the way to the
331 /// function entry.
334 MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs,
335 ArrayRef<AMDGPU::Incoming> Incomings = {}) {
336 assert(LoopLevel < CommonDominators.size());
337
338 MachineBasicBlock *Dom = CommonDominators[LoopLevel];
339 for (auto &Incoming : Incomings)
341
342 if (!inLoopLevel(*Dom, LoopLevel, Incomings)) {
343 SSAUpdater.addAvailableValue(
344 Dom, insertUndefLaneMask(Dom, &MRI, LaneMaskRegAttrs));
345 } else {
346 // The dominator is part of the loop or the given blocks, so add the
347 // undef value to unreachable predecessors instead.
348 for (MachineBasicBlock *Pred : Dom->predecessors()) {
349 if (!inLoopLevel(*Pred, LoopLevel, Incomings))
350 SSAUpdater.addAvailableValue(
351 Pred, insertUndefLaneMask(Pred, &MRI, LaneMaskRegAttrs));
352 }
353 }
354 }
355
356private:
357 bool inLoopLevel(MachineBasicBlock &MBB, unsigned LoopLevel,
358 ArrayRef<AMDGPU::Incoming> Incomings) const {
359 auto DomIt = Visited.find(&MBB);
360 if (DomIt != Visited.end() && DomIt->second <= LoopLevel)
361 return true;
362
363 for (auto &Incoming : Incomings)
364 if (Incoming.Block == &MBB)
365 return true;
366
367 return false;
368 }
369
370 void advanceLevel() {
371 MachineBasicBlock *VisitedDom;
372
373 if (!VisitedPostDom) {
374 VisitedPostDom = DefBlock;
375 VisitedDom = DefBlock;
376 Stack.push_back(DefBlock);
377 } else {
378 VisitedPostDom = PDT.getNode(VisitedPostDom)->getIDom()->getBlock();
379 VisitedDom = CommonDominators.back();
380
381 for (unsigned i = 0; i < NextLevel.size();) {
382 if (PDT.dominates(VisitedPostDom, NextLevel[i])) {
383 Stack.push_back(NextLevel[i]);
384
385 NextLevel[i] = NextLevel.back();
386 NextLevel.pop_back();
387 } else {
388 i++;
389 }
390 }
391 }
392
393 unsigned Level = CommonDominators.size();
394 while (!Stack.empty()) {
395 MachineBasicBlock *MBB = Stack.pop_back_val();
396 if (!PDT.dominates(VisitedPostDom, MBB))
397 NextLevel.push_back(MBB);
398
399 Visited[MBB] = Level;
400 VisitedDom = DT.findNearestCommonDominator(VisitedDom, MBB);
401
402 for (MachineBasicBlock *Succ : MBB->successors()) {
403 if (isExecInvariantBackEdge(*MBB, *Succ, DT, *TII))
404 continue;
405
406 if (Succ == DefBlock) {
407 if (MBB == VisitedPostDom)
408 FoundLoopLevel = std::min(FoundLoopLevel, Level + 1);
409 else
410 FoundLoopLevel = std::min(FoundLoopLevel, Level);
411 continue;
412 }
413
414 if (Visited.try_emplace(Succ, ~0u).second) {
415 if (MBB == VisitedPostDom)
416 NextLevel.push_back(Succ);
417 else
418 Stack.push_back(Succ);
419 }
420 }
421 }
422
423 CommonDominators.push_back(VisitedDom);
424 }
425};
426
427} // namespace AMDGPU
428} // namespace llvm
429
432 return MRI->createVirtualRegister(LaneMaskRegAttrs);
433}
434
435static Register
437 MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs) {
438 MachineFunction &MF = *MBB->getParent();
439 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
440 const SIInstrInfo *TII = ST.getInstrInfo();
441 Register UndefReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
442 BuildMI(*MBB, MBB->getFirstTerminator(), {}, TII->get(AMDGPU::IMPLICIT_DEF),
443 UndefReg);
444 return UndefReg;
445}
446
447#ifndef NDEBUG
450 Register Reg) {
451 unsigned Size = TRI.getRegSizeInBits(Reg, MRI);
452 return Size == 1 || Size == 32;
453}
454#endif
455
456bool Vreg1LoweringHelper::lowerCopiesFromI1() {
457 bool Changed = false;
458 SmallVector<MachineInstr *, 4> DeadCopies;
459
460 for (MachineBasicBlock &MBB : MF) {
461 for (MachineInstr &MI : MBB) {
462 if (MI.getOpcode() != AMDGPU::COPY)
463 continue;
464
465 Register DstReg = MI.getOperand(0).getReg();
466 Register SrcReg = MI.getOperand(1).getReg();
467 if (!isVreg1(SrcReg))
468 continue;
469
470 if (isLaneMaskReg(DstReg) || isVreg1(DstReg))
471 continue;
472
473 Changed = true;
474
475 // Copy into a 32-bit vector register.
476 LLVM_DEBUG(dbgs() << "Lower copy from i1: " << MI);
477 const DebugLoc &DL = MI.getDebugLoc();
478
480 assert(!MI.getOperand(0).getSubReg());
481
482 ConstrainRegs.insert(SrcReg);
483 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
484 .addImm(0)
485 .addImm(0)
486 .addImm(0)
487 .addImm(-1)
488 .addReg(SrcReg);
489 DeadCopies.push_back(&MI);
490 }
491
492 for (MachineInstr *MI : DeadCopies)
493 MI->eraseFromParent();
494 DeadCopies.clear();
495 }
496 return Changed;
497}
498
502 : MF(MF), DT(DT), PDT(PDT), ST(&MF.getSubtarget<GCNSubtarget>()),
504 MRI = &MF.getRegInfo();
505
506 TII = ST->getInstrInfo();
507}
508
513 LF.initialize(MBB);
514
515 // Sort the incomings such that incoming values that dominate other incoming
516 // values are sorted earlier. This allows us to do some amount of on-the-fly
517 // constant folding.
518 // Incoming with smaller DFSNumIn goes first, DFSNumIn is 0 for entry block.
519 llvm::sort(Incomings, [this](Incoming LHS, Incoming RHS) {
520 return DT.getNode(LHS.Block)->getDFSNumIn() <
521 DT.getNode(RHS.Block)->getDFSNumIn();
522 });
523
524 // Values in a loop that are observed outside the loop receive a simple but
525 // conservatively correct treatment.
527 for (MachineInstr &Use : MRI->use_nodbg_instructions(DstReg))
528 DomBlocks.push_back(Use.getParent());
529
530 MachineBasicBlock *PostDomBound = PDT.findNearestCommonDominator(DomBlocks);
531
532 // FIXME: This fails to find irreducible cycles. If we have a def (other
533 // than a constant) in a pair of blocks that end up looping back to each
534 // other, it will be mishandle. Due to structurization this shouldn't occur
535 // in practice.
536 unsigned FoundLoopLevel = LF.findLoop(PostDomBound);
537
538 SSAUpdater.addUseBlock(&MBB);
539
540 if (FoundLoopLevel) {
541 LF.addLoopEntries(FoundLoopLevel, SSAUpdater, *MRI, LaneMaskRegAttrs,
542 Incomings);
543
544 for (auto &Incoming : Incomings) {
545 SSAUpdater.addUseBlock(Incoming.Block);
547 SSAUpdater.addAvailableValue(Incoming.Block, Incoming.UpdatedReg);
548 }
549
550 SSAUpdater.calculate();
551
552 for (auto &Incoming : Incomings) {
556 SSAUpdater.getValueInMiddleOfBlock(&IMBB), Incoming.Reg);
557 }
558 } else {
559 // The value is not observed from outside a loop. Use a more accurate
560 // lowering.
561 PIA.analyze(MBB, Incomings);
562
563 for (MachineBasicBlock *PredMBB : PIA.predecessors())
564 SSAUpdater.addAvailableValue(
565 PredMBB, insertUndefLaneMask(PredMBB, MRI, LaneMaskRegAttrs));
566
567 for (auto &Incoming : Incomings) {
569 if (PIA.isSource(IMBB)) {
571 SSAUpdater.addAvailableValue(&IMBB, Incoming.Reg);
572 } else {
573 SSAUpdater.addUseBlock(&IMBB);
575 SSAUpdater.addAvailableValue(&IMBB, Incoming.UpdatedReg);
576 }
577 }
578
579 SSAUpdater.calculate();
580
581 for (auto &Incoming : Incomings) {
583 continue;
584
588 SSAUpdater.getValueInMiddleOfBlock(&IMBB), Incoming.Reg);
589 }
590 }
591}
592
595 SmallVector<Incoming, 4> Incomings;
596
597 getCandidatesForLowering(Vreg1Phis);
598 if (Vreg1Phis.empty())
599 return false;
600
601 LoopFinder LF(DT, PDT, TII);
603
604 DT.updateDFSNumbers();
605 for (MachineInstr *MI : Vreg1Phis) {
606 MachineBasicBlock &MBB = *MI->getParent();
607 LLVM_DEBUG(dbgs() << "Lower PHI: " << *MI);
608
609 Register DstReg = MI->getOperand(0).getReg();
610 markAsLaneMask(DstReg);
612
614
615#ifndef NDEBUG
616 PhiRegisters.insert(DstReg);
617#endif
618
620 mergeIncomingLaneMasks(DstReg, MBB, Incomings, SSAUpdater, LF, PIA);
621
622 Register NewReg = SSAUpdater.getValueInMiddleOfBlock(&MBB);
623 replaceDstReg(NewReg, DstReg, &MBB);
624 MI->eraseFromParent();
625
626 Incomings.clear();
627 }
628 return true;
629}
630
631bool Vreg1LoweringHelper::lowerCopiesToI1() {
632 bool Changed = false;
633 AMDGPU::LoopFinder LF(DT, PDT, TII);
635
636 for (MachineBasicBlock &MBB : MF) {
637 LF.initialize(MBB);
638
639 for (MachineInstr &MI : MBB) {
640 if (MI.getOpcode() != AMDGPU::IMPLICIT_DEF &&
641 MI.getOpcode() != AMDGPU::COPY)
642 continue;
643
644 Register DstReg = MI.getOperand(0).getReg();
645 if (!isVreg1(DstReg))
646 continue;
647
648 Changed = true;
649
650 if (MRI->use_empty(DstReg)) {
651 DeadCopies.push_back(&MI);
652 continue;
653 }
654
655 LLVM_DEBUG(dbgs() << "Lower Other: " << MI);
656
657 markAsLaneMask(DstReg);
658 initializeLaneMaskRegisterAttributes(DstReg);
659
660 if (MI.getOpcode() == AMDGPU::IMPLICIT_DEF)
661 continue;
662
663 const DebugLoc &DL = MI.getDebugLoc();
664 Register SrcReg = MI.getOperand(1).getReg();
665 assert(!MI.getOperand(1).getSubReg());
666
667 if (!SrcReg.isVirtual() || (!isLaneMaskReg(SrcReg) && !isVreg1(SrcReg))) {
668 assert(TII->getRegisterInfo().getRegSizeInBits(SrcReg, *MRI) == 32);
669 Register TmpReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
670 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_CMP_NE_U32_e64), TmpReg)
671 .addReg(SrcReg)
672 .addImm(0);
673 MI.getOperand(1).setReg(TmpReg);
674 SrcReg = TmpReg;
675 } else {
676 // SrcReg needs to be live beyond copy.
677 MI.getOperand(1).setIsKill(false);
678 }
679
680 // Defs in a loop that are observed outside the loop must be transformed
681 // into appropriate bit manipulation.
682 std::vector<MachineBasicBlock *> DomBlocks = {&MBB};
683 for (MachineInstr &Use : MRI->use_nodbg_instructions(DstReg))
684 DomBlocks.push_back(Use.getParent());
685
686 MachineBasicBlock *PostDomBound =
687 PDT.findNearestCommonDominator(DomBlocks);
688 unsigned FoundLoopLevel = LF.findLoop(PostDomBound);
689 if (FoundLoopLevel) {
690 MachineIDFSSAUpdater SSAUpdater(DT, MF, DstReg);
691 SSAUpdater.addUseBlock(&MBB);
692 SSAUpdater.addAvailableValue(&MBB, DstReg);
693 LF.addLoopEntries(FoundLoopLevel, SSAUpdater, *MRI, LaneMaskRegAttrs);
694
695 SSAUpdater.calculate();
696 buildMergeLaneMasks(MBB, MI, DL, DstReg,
697 SSAUpdater.getValueInMiddleOfBlock(&MBB), SrcReg);
698 DeadCopies.push_back(&MI);
699 }
700 }
701
702 for (MachineInstr *MI : DeadCopies)
703 MI->eraseFromParent();
704 DeadCopies.clear();
705 }
706 return Changed;
707}
708
710 bool &Val) const {
711 const MachineInstr *MI;
712 for (;;) {
713 MI = MRI->getVRegDef(Reg);
714 if (MI->getOpcode() == AMDGPU::IMPLICIT_DEF)
715 return true;
716
717 if (MI->getOpcode() != AMDGPU::COPY)
718 break;
719
720 Reg = MI->getOperand(1).getReg();
721 if (!Reg.isVirtual())
722 return false;
723 if (!isLaneMaskReg(Reg))
724 return false;
725 }
726
727 if (MI->getOpcode() != LMC->MovOpc)
728 return false;
729
730 if (!MI->getOperand(1).isImm())
731 return false;
732
733 int64_t Imm = MI->getOperand(1).getImm();
734 if (Imm == 0) {
735 Val = false;
736 return true;
737 }
738 if (Imm == -1) {
739 Val = true;
740 return true;
741 }
742
743 return false;
744}
745
746static void instrDefsUsesSCC(const MachineInstr &MI, bool &Def, bool &Use) {
747 Def = false;
748 Use = false;
749
750 for (const MachineOperand &MO : MI.operands()) {
751 if (MO.isReg() && MO.getReg() == AMDGPU::SCC) {
752 if (MO.isUse())
753 Use = true;
754 else
755 Def = true;
756 }
757 }
758}
759
760/// Return a point at the end of the given \p MBB to insert SALU instructions
761/// for lane mask calculation. Take terminators and SCC into account.
764 auto InsertionPt = MBB.getFirstTerminator();
765 bool TerminatorsUseSCC = false;
766 for (auto I = InsertionPt, E = MBB.end(); I != E; ++I) {
767 bool DefsSCC;
768 instrDefsUsesSCC(*I, DefsSCC, TerminatorsUseSCC);
769 if (TerminatorsUseSCC || DefsSCC)
770 break;
771 }
772
773 if (!TerminatorsUseSCC)
774 return InsertionPt;
775
776 while (InsertionPt != MBB.begin()) {
777 InsertionPt--;
778
779 bool DefSCC, UseSCC;
780 instrDefsUsesSCC(*InsertionPt, DefSCC, UseSCC);
781 if (DefSCC)
782 return InsertionPt;
783 }
784
785 // We should have at least seen an IMPLICIT_DEF or COPY
786 llvm_unreachable("SCC used by terminator but no def in block");
787}
788
789// VReg_1 -> SReg_32 or SReg_64
790void Vreg1LoweringHelper::markAsLaneMask(Register DstReg) const {
791 MRI->setRegClass(DstReg, ST->getBoolRC());
792}
793
794void Vreg1LoweringHelper::getCandidatesForLowering(
795 SmallVectorImpl<MachineInstr *> &Vreg1Phis) const {
796 for (MachineBasicBlock &MBB : MF) {
797 for (MachineInstr &MI : MBB.phis()) {
798 if (isVreg1(MI.getOperand(0).getReg()))
799 Vreg1Phis.push_back(&MI);
800 }
801 }
802}
803
804void Vreg1LoweringHelper::collectIncomingValuesFromPhi(
805 const MachineInstr *MI,
806 SmallVectorImpl<AMDGPU::Incoming> &Incomings) const {
807 for (unsigned i = 1; i < MI->getNumOperands(); i += 2) {
808 assert(i + 1 < MI->getNumOperands());
809 Register IncomingReg = MI->getOperand(i).getReg();
810 MachineBasicBlock *IncomingMBB = MI->getOperand(i + 1).getMBB();
811 MachineInstr *IncomingDef = MRI->getVRegDef(IncomingReg);
812
813 if (IncomingDef->getOpcode() == AMDGPU::COPY) {
814 IncomingReg = IncomingDef->getOperand(1).getReg();
815 assert(isLaneMaskReg(IncomingReg) || isVreg1(IncomingReg));
816 assert(!IncomingDef->getOperand(1).getSubReg());
817 } else if (IncomingDef->getOpcode() == AMDGPU::IMPLICIT_DEF) {
818 continue;
819 } else {
820 assert(IncomingDef->isPHI() || PhiRegisters.count(IncomingReg));
821 }
822
823 Incomings.emplace_back(IncomingReg, IncomingMBB, Register());
824 }
825}
826
827void Vreg1LoweringHelper::replaceDstReg(Register NewReg, Register OldReg,
828 MachineBasicBlock *MBB) {
829 MRI->replaceRegWith(NewReg, OldReg);
830}
831
832void Vreg1LoweringHelper::buildMergeLaneMasks(MachineBasicBlock &MBB,
834 const DebugLoc &DL,
835 Register DstReg, Register PrevReg,
836 Register CurReg) {
837 bool PrevVal = false;
838 bool PrevConstant = isConstantLaneMask(PrevReg, PrevVal);
839 bool CurVal = false;
840 bool CurConstant = isConstantLaneMask(CurReg, CurVal);
841
842 if (PrevConstant && CurConstant) {
843 if (PrevVal == CurVal) {
844 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg).addReg(CurReg);
845 } else if (CurVal) {
846 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg).addReg(LMC->ExecReg);
847 } else {
848 BuildMI(MBB, I, DL, TII->get(LMC->XorOpc), DstReg)
849 .addReg(LMC->ExecReg)
850 .addImm(-1)
851 .setOperandDead(3);
852 }
853 return;
854 }
855
856 Register PrevMaskedReg;
857 Register CurMaskedReg;
858 if (!PrevConstant) {
859 if (CurConstant && CurVal) {
860 PrevMaskedReg = PrevReg;
861 } else {
862 PrevMaskedReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
863 BuildMI(MBB, I, DL, TII->get(LMC->AndN2Opc), PrevMaskedReg)
864 .addReg(PrevReg)
865 .addReg(LMC->ExecReg)
866 .setOperandDead(3);
867 }
868 }
869 if (!CurConstant) {
870 // TODO: check whether CurReg is already masked by EXEC
871 if (PrevConstant && PrevVal) {
872 CurMaskedReg = CurReg;
873 } else {
874 CurMaskedReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
875 BuildMI(MBB, I, DL, TII->get(LMC->AndOpc), CurMaskedReg)
876 .addReg(CurReg)
877 .addReg(LMC->ExecReg)
878 .setOperandDead(3);
879 }
880 }
881
882 if (PrevConstant && !PrevVal) {
883 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg)
884 .addReg(CurMaskedReg);
885 } else if (CurConstant && !CurVal) {
886 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg)
887 .addReg(PrevMaskedReg);
888 } else if (PrevConstant && PrevVal) {
889 BuildMI(MBB, I, DL, TII->get(LMC->OrN2Opc), DstReg)
890 .addReg(CurMaskedReg)
891 .addReg(LMC->ExecReg)
892 .setOperandDead(3);
893 } else {
894 BuildMI(MBB, I, DL, TII->get(LMC->OrOpc), DstReg)
895 .addReg(PrevMaskedReg)
896 .addReg(CurMaskedReg ? CurMaskedReg : LMC->ExecReg)
897 .setOperandDead(3);
898 }
899}
900
901void Vreg1LoweringHelper::constrainAsLaneMask(AMDGPU::Incoming &In) {}
902
903/// Lower all instructions that def or use vreg_1 registers.
904///
905/// In a first pass, we lower COPYs from vreg_1 to vector registers, as can
906/// occur around inline assembly. We do this first, before vreg_1 registers
907/// are changed to scalar mask registers.
908///
909/// Then we lower all defs of vreg_1 registers. Phi nodes are lowered before
910/// all others, because phi lowering looks through copies and can therefore
911/// often make copy lowering unnecessary.
914 // Only need to run this in SelectionDAG path.
915 if (MF.getProperties().hasSelected())
916 return false;
917
918 Vreg1LoweringHelper Helper(MF, MDT, MPDT);
919 bool Changed = false;
920 Changed |= Helper.lowerCopiesFromI1();
921 Changed |= Helper.lowerPhis();
922 Changed |= Helper.lowerCopiesToI1();
923 return Helper.cleanConstrainRegs(Changed);
924}
925
926PreservedAnalyses
939
941public:
942 static char ID;
943
945
946 bool runOnMachineFunction(MachineFunction &MF) override;
947
948 StringRef getPassName() const override { return "SI Lower i1 Copies"; }
949
956};
957
965
967 false, false)
972
973char SILowerI1CopiesLegacy::ID = 0;
974
976
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define DEBUG_TYPE
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 INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
static void instrDefsUsesSCC(const MachineInstr &MI, bool &Def, bool &Use)
static Register insertUndefLaneMask(MachineBasicBlock *MBB, MachineRegisterInfo *MRI, MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs)
static bool isExecInvariantBackEdge(const MachineBasicBlock &Latch, const MachineBasicBlock &Header, const MachineDominatorTree &DT, const SIInstrInfo &TII)
Return true if Latch -> Header is the only back-edge of a loop that is left as a whole,...
static bool runFixI1Copies(MachineFunction &MF, MachineDominatorTree &MDT, MachinePostDominatorTree &MPDT)
Lower all instructions that def or use vreg_1 registers.
static bool isVRegCompatibleReg(const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI, Register Reg)
Interface definition of the PhiLoweringHelper class that implements lane mask merging algorithm for d...
#define LLVM_DEBUG(...)
Definition Debug.h:119
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const AArch64RegisterInfo & getRegisterInfo() const
getRegisterInfo - TargetInstrInfo is a superset of MRegister info.
Helper class that detects loops which require us to lower an i1 COPY into bitwise manipulation.
void initialize(MachineBasicBlock &MBB)
LoopFinder(MachineDominatorTree &DT, MachinePostDominatorTree &PDT, const SIInstrInfo *TII)
unsigned findLoop(MachineBasicBlock *PostDom)
Check whether a backward edge can be reached without going through the given PostDom of the def block...
void addLoopEntries(unsigned LoopLevel, MachineIDFSSAUpdater &SSAUpdater, MachineRegisterInfo &MRI, MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs, ArrayRef< AMDGPU::Incoming > Incomings={})
Add undef values dominating the loop and the optionally given additional blocks, so that the SSA upda...
Helper class that determines the relationship between incoming values of a phi in the control flow gr...
bool isSource(MachineBasicBlock &MBB) const
Returns whether MBB is a source in the induced subgraph of reachable blocks.
ArrayRef< MachineBasicBlock * > predecessors() const
PhiIncomingAnalysis(MachinePostDominatorTree &PDT, const SIInstrInfo *TII)
void analyze(MachineBasicBlock &DefBlock, ArrayRef< AMDGPU::Incoming > Incomings)
bool isLaneMaskReg(Register Reg) const
virtual void replaceDstReg(Register NewReg, Register OldReg, MachineBasicBlock *MBB)=0
MachineBasicBlock::iterator getSaluInsertionAtEnd(MachineBasicBlock &MBB) const
Return a point at the end of the given MBB to insert SALU instructions for lane mask calculation.
bool isConstantLaneMask(Register Reg, bool &Val) const
MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs
void initializeLaneMaskRegisterAttributes(Register LaneMask)
virtual void buildMergeLaneMasks(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DstReg, Register PrevReg, Register CurReg)=0
virtual void getCandidatesForLowering(SmallVectorImpl< MachineInstr * > &Vreg1Phis) const =0
const AMDGPU::LaneMaskConstants * LMC
PhiLoweringHelper(MachineFunction &MF, MachineDominatorTree &DT, MachinePostDominatorTree &PDT)
DenseSet< Register > PhiRegisters
virtual void markAsLaneMask(Register DstReg) const =0
virtual void constrainAsLaneMask(Incoming &In)=0
virtual void collectIncomingValuesFromPhi(const MachineInstr *MI, SmallVectorImpl< Incoming > &Incomings) const =0
void mergeIncomingLaneMasks(Register DstReg, MachineBasicBlock &MBB, SmallVectorImpl< Incoming > &Incomings, MachineIDFSSAUpdater &SSAUpdater, LoopFinder &LF, PhiIncomingAnalysis &PIA)
Merge the Incomings lane masks into DstReg, the value owned by MBB.
MachinePostDominatorTree & PDT
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
void push_back(MachineInstr *MI)
iterator_range< succ_iterator > successors()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
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.
const MachineFunctionProperties & getProperties() const
Get the function properties.
LLVM_ABI Register getValueInMiddleOfBlock(MachineBasicBlock *BB)
See SSAUpdater::GetValueInMiddleOfBlock description.
void addAvailableValue(MachineBasicBlock *BB, Register V)
Indicate that a rewritten value is available in the specified block with the specified value.
LLVM_ABI void calculate()
Calculate and insert necessary PHI nodes for SSA form.
void addUseBlock(MachineBasicBlock *BB)
Record a basic block that uses the value.
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
LLVM_ABI MachineBasicBlock * findNearestCommonDominator(ArrayRef< MachineBasicBlock * > Blocks) const
Returns the nearest common dominator of the given blocks.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Register createLaneMaskReg(MachineRegisterInfo *MRI, MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs)
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
ArrayRef(const T &OneElt) -> ArrayRef< T >
FunctionPass * createSILowerI1CopiesLegacyPass()
char & SILowerI1CopiesLegacyID
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Incoming for lane mask phi as machine instruction, incoming register Reg and incoming block Block are...
MachineBasicBlock * Block
All attributes(register class or bank and low-level type) a virtual register can have.