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
86namespace llvm {
87namespace AMDGPU {
88
89/// Helper class that determines the relationship between incoming values of a
90/// phi in the control flow graph to determine where an incoming value can
91/// simply be taken as a scalar lane mask as-is, and where it needs to be
92/// merged with another, previously defined lane mask.
93///
94/// The approach is as follows:
95/// - Determine all basic blocks which, starting from the incoming blocks,
96/// a wave may reach before entering the def block (the block containing the
97/// phi).
98/// - If an incoming block has no predecessors in this set, we can take the
99/// incoming value as a scalar lane mask as-is.
100/// -- A special case of this is when the def block has a self-loop.
101/// - Otherwise, the incoming value needs to be merged with a previously
102/// defined lane mask.
103/// - If there is a path into the set of reachable blocks that does _not_ go
104/// through an incoming block where we can take the scalar lane mask as-is,
105/// we need to invent an available value for the SSAUpdater. Choices are
106/// 0 and undef, with differing consequences for how to merge values etc.
107///
108/// TODO: We could use region analysis to quickly skip over SESE regions during
109/// the traversal.
110///
113 const SIInstrInfo *TII;
114
115 // For each reachable basic block, whether it is a source in the induced
116 // subgraph of the CFG.
120
121public:
123 : PDT(PDT), TII(TII) {}
124
125 /// Returns whether \p MBB is a source in the induced subgraph of reachable
126 /// blocks.
128 return ReachableMap.find(&MBB)->second;
129 }
130
131 ArrayRef<MachineBasicBlock *> predecessors() const { return Predecessors; }
132
134 ArrayRef<AMDGPU::Incoming> Incomings) {
135 assert(Stack.empty());
136 ReachableMap.clear();
137 Predecessors.clear();
138
139 // Insert the def block first, so that it acts as an end point for the
140 // traversal.
141 ReachableMap.try_emplace(&DefBlock, false);
142
143 for (auto Incoming : Incomings) {
145 if (MBB == &DefBlock) {
146 ReachableMap[&DefBlock] = true; // self-loop on DefBlock
147 continue;
148 }
149
150 // If this block has a divergent terminator and the def block is its
151 // post-dominator, the wave may first visit the other successors.
152 if (TII->hasDivergentBranch(MBB) && PDT.dominates(&DefBlock, MBB))
153 Stack.push_back(MBB);
154 }
155
156 while (!Stack.empty()) {
157 MachineBasicBlock *MBB = Stack.pop_back_val();
158 if (ReachableMap.try_emplace(MBB, false).second)
159 append_range(Stack, MBB->successors());
160 }
161
162 // Insert remaining incoming blocks.
163 for (auto Incoming : Incomings) {
165 ReachableMap.try_emplace(MBB, false);
166 }
167
168 for (auto &[MBB, IsSource] : ReachableMap) {
169 bool HaveReachablePred = false;
170 for (MachineBasicBlock *Pred : MBB->predecessors()) {
171 if (ReachableMap.count(Pred)) {
172 HaveReachablePred = true;
173 } else {
174 Stack.push_back(Pred);
175 }
176 }
177 if (!HaveReachablePred)
178 IsSource = true;
179 if (HaveReachablePred) {
180 for (MachineBasicBlock *UnreachablePred : Stack) {
181 if (!llvm::is_contained(Predecessors, UnreachablePred))
182 Predecessors.push_back(UnreachablePred);
183 }
184 }
185 Stack.clear();
186 }
187 }
188};
189
190/// Helper class that detects loops which require us to lower an i1 COPY into
191/// bitwise manipulation.
192///
193/// Unfortunately, we cannot use LoopInfo because LoopInfo does not distinguish
194/// between loops with the same header. Consider this example:
195///
196/// A-+-+
197/// | | |
198/// B-+ |
199/// | |
200/// C---+
201///
202/// A is the header of a loop containing A, B, and C as far as LoopInfo is
203/// concerned. However, an i1 COPY in B that is used in C must be lowered to
204/// bitwise operations to combine results from different loop iterations when
205/// B has a divergent branch (since by default we will compile this code such
206/// that threads in a wave are merged at the entry of C).
207///
208/// The following rule is implemented to determine whether bitwise operations
209/// are required: use the bitwise lowering for a def in block B if a backward
210/// edge to B is reachable without going through the nearest common
211/// post-dominator of B and all uses of the def.
212///
213/// TODO: This rule is conservative because it does not check whether the
214/// relevant branches are actually divergent.
215///
216/// The class is designed to cache the CFG traversal so that it can be re-used
217/// for multiple defs within the same basic block.
218///
219/// TODO: We could use region analysis to quickly skip over SESE regions during
220/// the traversal.
221///
225
226 // All visited / reachable block, tagged by level (level 0 is the def block,
227 // level 1 are all blocks reachable including but not going through the def
228 // block's IPDOM, etc.).
230
231 // Nearest common dominator of all visited blocks by level (level 0 is the
232 // def block). Used for seeding the SSAUpdater.
234
235 // Post-dominator of all visited blocks.
236 MachineBasicBlock *VisitedPostDom = nullptr;
237
238 // Level at which a loop was found: 0 is not possible; 1 = a backward edge is
239 // reachable without going through the IPDOM of the def block (if the IPDOM
240 // itself has an edge to the def block, the loop level is 2), etc.
241 unsigned FoundLoopLevel = ~0u;
242
243 MachineBasicBlock *DefBlock = nullptr;
246
247public:
249 : DT(DT), PDT(PDT) {}
250
252 Visited.clear();
253 CommonDominators.clear();
254 Stack.clear();
255 NextLevel.clear();
256 VisitedPostDom = nullptr;
257 FoundLoopLevel = ~0u;
258
259 DefBlock = &MBB;
260 }
261
262 /// Check whether a backward edge can be reached without going through the
263 /// given \p PostDom of the def block.
264 ///
265 /// Return the level of \p PostDom if a loop was found, or 0 otherwise.
266 unsigned findLoop(MachineBasicBlock *PostDom) {
267 MachineDomTreeNode *PDNode = PDT.getNode(DefBlock);
268
269 if (!VisitedPostDom)
270 advanceLevel();
271
272 unsigned Level = 0;
273 while (PDNode->getBlock() != PostDom) {
274 if (PDNode->getBlock() == VisitedPostDom)
275 advanceLevel();
276 PDNode = PDNode->getIDom();
277 Level++;
278 if (FoundLoopLevel == Level)
279 return Level;
280 }
281
282 return 0;
283 }
284
285 /// Add undef values dominating the loop and the optionally given additional
286 /// blocks, so that the SSA updater doesn't have to search all the way to the
287 /// function entry.
290 MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs,
291 ArrayRef<AMDGPU::Incoming> Incomings = {}) {
292 assert(LoopLevel < CommonDominators.size());
293
294 MachineBasicBlock *Dom = CommonDominators[LoopLevel];
295 for (auto &Incoming : Incomings)
297
298 if (!inLoopLevel(*Dom, LoopLevel, Incomings)) {
299 SSAUpdater.addAvailableValue(
300 Dom, insertUndefLaneMask(Dom, &MRI, LaneMaskRegAttrs));
301 } else {
302 // The dominator is part of the loop or the given blocks, so add the
303 // undef value to unreachable predecessors instead.
304 for (MachineBasicBlock *Pred : Dom->predecessors()) {
305 if (!inLoopLevel(*Pred, LoopLevel, Incomings))
306 SSAUpdater.addAvailableValue(
307 Pred, insertUndefLaneMask(Pred, &MRI, LaneMaskRegAttrs));
308 }
309 }
310 }
311
312private:
313 bool inLoopLevel(MachineBasicBlock &MBB, unsigned LoopLevel,
314 ArrayRef<AMDGPU::Incoming> Incomings) const {
315 auto DomIt = Visited.find(&MBB);
316 if (DomIt != Visited.end() && DomIt->second <= LoopLevel)
317 return true;
318
319 for (auto &Incoming : Incomings)
320 if (Incoming.Block == &MBB)
321 return true;
322
323 return false;
324 }
325
326 void advanceLevel() {
327 MachineBasicBlock *VisitedDom;
328
329 if (!VisitedPostDom) {
330 VisitedPostDom = DefBlock;
331 VisitedDom = DefBlock;
332 Stack.push_back(DefBlock);
333 } else {
334 VisitedPostDom = PDT.getNode(VisitedPostDom)->getIDom()->getBlock();
335 VisitedDom = CommonDominators.back();
336
337 for (unsigned i = 0; i < NextLevel.size();) {
338 if (PDT.dominates(VisitedPostDom, NextLevel[i])) {
339 Stack.push_back(NextLevel[i]);
340
341 NextLevel[i] = NextLevel.back();
342 NextLevel.pop_back();
343 } else {
344 i++;
345 }
346 }
347 }
348
349 unsigned Level = CommonDominators.size();
350 while (!Stack.empty()) {
351 MachineBasicBlock *MBB = Stack.pop_back_val();
352 if (!PDT.dominates(VisitedPostDom, MBB))
353 NextLevel.push_back(MBB);
354
355 Visited[MBB] = Level;
356 VisitedDom = DT.findNearestCommonDominator(VisitedDom, MBB);
357
358 for (MachineBasicBlock *Succ : MBB->successors()) {
359 if (Succ == DefBlock) {
360 if (MBB == VisitedPostDom)
361 FoundLoopLevel = std::min(FoundLoopLevel, Level + 1);
362 else
363 FoundLoopLevel = std::min(FoundLoopLevel, Level);
364 continue;
365 }
366
367 if (Visited.try_emplace(Succ, ~0u).second) {
368 if (MBB == VisitedPostDom)
369 NextLevel.push_back(Succ);
370 else
371 Stack.push_back(Succ);
372 }
373 }
374 }
375
376 CommonDominators.push_back(VisitedDom);
377 }
378};
379
380} // namespace AMDGPU
381} // namespace llvm
382
385 return MRI->createVirtualRegister(LaneMaskRegAttrs);
386}
387
388static Register
390 MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs) {
391 MachineFunction &MF = *MBB->getParent();
392 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
393 const SIInstrInfo *TII = ST.getInstrInfo();
394 Register UndefReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
395 BuildMI(*MBB, MBB->getFirstTerminator(), {}, TII->get(AMDGPU::IMPLICIT_DEF),
396 UndefReg);
397 return UndefReg;
398}
399
400#ifndef NDEBUG
402 const MachineRegisterInfo &MRI,
403 Register Reg) {
404 unsigned Size = TRI.getRegSizeInBits(Reg, MRI);
405 return Size == 1 || Size == 32;
406}
407#endif
408
409bool Vreg1LoweringHelper::lowerCopiesFromI1() {
410 bool Changed = false;
411 SmallVector<MachineInstr *, 4> DeadCopies;
412
413 for (MachineBasicBlock &MBB : MF) {
414 for (MachineInstr &MI : MBB) {
415 if (MI.getOpcode() != AMDGPU::COPY)
416 continue;
417
418 Register DstReg = MI.getOperand(0).getReg();
419 Register SrcReg = MI.getOperand(1).getReg();
420 if (!isVreg1(SrcReg))
421 continue;
422
423 if (isLaneMaskReg(DstReg) || isVreg1(DstReg))
424 continue;
425
426 Changed = true;
427
428 // Copy into a 32-bit vector register.
429 LLVM_DEBUG(dbgs() << "Lower copy from i1: " << MI);
430 const DebugLoc &DL = MI.getDebugLoc();
431
433 assert(!MI.getOperand(0).getSubReg());
434
435 ConstrainRegs.insert(SrcReg);
436 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
437 .addImm(0)
438 .addImm(0)
439 .addImm(0)
440 .addImm(-1)
441 .addReg(SrcReg);
442 DeadCopies.push_back(&MI);
443 }
444
445 for (MachineInstr *MI : DeadCopies)
446 MI->eraseFromParent();
447 DeadCopies.clear();
448 }
449 return Changed;
450}
451
455 : MF(MF), DT(DT), PDT(PDT), ST(&MF.getSubtarget<GCNSubtarget>()),
457 MRI = &MF.getRegInfo();
458
459 TII = ST->getInstrInfo();
460}
461
466 LF.initialize(MBB);
467
468 // Sort the incomings such that incoming values that dominate other incoming
469 // values are sorted earlier. This allows us to do some amount of on-the-fly
470 // constant folding.
471 // Incoming with smaller DFSNumIn goes first, DFSNumIn is 0 for entry block.
472 llvm::sort(Incomings, [this](Incoming LHS, Incoming RHS) {
473 return DT.getNode(LHS.Block)->getDFSNumIn() <
474 DT.getNode(RHS.Block)->getDFSNumIn();
475 });
476
477 // Values in a loop that are observed outside the loop receive a simple but
478 // conservatively correct treatment.
480 for (MachineInstr &Use : MRI->use_instructions(DstReg))
481 DomBlocks.push_back(Use.getParent());
482
483 MachineBasicBlock *PostDomBound = PDT.findNearestCommonDominator(DomBlocks);
484
485 // FIXME: This fails to find irreducible cycles. If we have a def (other
486 // than a constant) in a pair of blocks that end up looping back to each
487 // other, it will be mishandle. Due to structurization this shouldn't occur
488 // in practice.
489 unsigned FoundLoopLevel = LF.findLoop(PostDomBound);
490
491 SSAUpdater.addUseBlock(&MBB);
492
493 if (FoundLoopLevel) {
494 LF.addLoopEntries(FoundLoopLevel, SSAUpdater, *MRI, LaneMaskRegAttrs,
495 Incomings);
496
497 for (auto &Incoming : Incomings) {
498 SSAUpdater.addUseBlock(Incoming.Block);
500 SSAUpdater.addAvailableValue(Incoming.Block, Incoming.UpdatedReg);
501 }
502
503 SSAUpdater.calculate();
504
505 for (auto &Incoming : Incomings) {
509 SSAUpdater.getValueInMiddleOfBlock(&IMBB), Incoming.Reg);
510 }
511 } else {
512 // The value is not observed from outside a loop. Use a more accurate
513 // lowering.
514 PIA.analyze(MBB, Incomings);
515
516 for (MachineBasicBlock *PredMBB : PIA.predecessors())
517 SSAUpdater.addAvailableValue(
518 PredMBB, insertUndefLaneMask(PredMBB, MRI, LaneMaskRegAttrs));
519
520 for (auto &Incoming : Incomings) {
522 if (PIA.isSource(IMBB)) {
524 SSAUpdater.addAvailableValue(&IMBB, Incoming.Reg);
525 } else {
526 SSAUpdater.addUseBlock(&IMBB);
528 SSAUpdater.addAvailableValue(&IMBB, Incoming.UpdatedReg);
529 }
530 }
531
532 SSAUpdater.calculate();
533
534 for (auto &Incoming : Incomings) {
536 continue;
537
541 SSAUpdater.getValueInMiddleOfBlock(&IMBB), Incoming.Reg);
542 }
543 }
544}
545
548 SmallVector<Incoming, 4> Incomings;
549
550 getCandidatesForLowering(Vreg1Phis);
551 if (Vreg1Phis.empty())
552 return false;
553
554 LoopFinder LF(DT, PDT);
556
557 DT.updateDFSNumbers();
558 for (MachineInstr *MI : Vreg1Phis) {
559 MachineBasicBlock &MBB = *MI->getParent();
560 LLVM_DEBUG(dbgs() << "Lower PHI: " << *MI);
561
562 Register DstReg = MI->getOperand(0).getReg();
563 markAsLaneMask(DstReg);
565
567
568#ifndef NDEBUG
569 PhiRegisters.insert(DstReg);
570#endif
571
573 mergeIncomingLaneMasks(DstReg, MBB, Incomings, SSAUpdater, LF, PIA);
574
575 Register NewReg = SSAUpdater.getValueInMiddleOfBlock(&MBB);
576 replaceDstReg(NewReg, DstReg, &MBB);
577 MI->eraseFromParent();
578
579 Incomings.clear();
580 }
581 return true;
582}
583
584bool Vreg1LoweringHelper::lowerCopiesToI1() {
585 bool Changed = false;
586 AMDGPU::LoopFinder LF(DT, PDT);
588
589 for (MachineBasicBlock &MBB : MF) {
590 LF.initialize(MBB);
591
592 for (MachineInstr &MI : MBB) {
593 if (MI.getOpcode() != AMDGPU::IMPLICIT_DEF &&
594 MI.getOpcode() != AMDGPU::COPY)
595 continue;
596
597 Register DstReg = MI.getOperand(0).getReg();
598 if (!isVreg1(DstReg))
599 continue;
600
601 Changed = true;
602
603 if (MRI->use_empty(DstReg)) {
604 DeadCopies.push_back(&MI);
605 continue;
606 }
607
608 LLVM_DEBUG(dbgs() << "Lower Other: " << MI);
609
610 markAsLaneMask(DstReg);
611 initializeLaneMaskRegisterAttributes(DstReg);
612
613 if (MI.getOpcode() == AMDGPU::IMPLICIT_DEF)
614 continue;
615
616 const DebugLoc &DL = MI.getDebugLoc();
617 Register SrcReg = MI.getOperand(1).getReg();
618 assert(!MI.getOperand(1).getSubReg());
619
620 if (!SrcReg.isVirtual() || (!isLaneMaskReg(SrcReg) && !isVreg1(SrcReg))) {
621 assert(TII->getRegisterInfo().getRegSizeInBits(SrcReg, *MRI) == 32);
622 Register TmpReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
623 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_CMP_NE_U32_e64), TmpReg)
624 .addReg(SrcReg)
625 .addImm(0);
626 MI.getOperand(1).setReg(TmpReg);
627 SrcReg = TmpReg;
628 } else {
629 // SrcReg needs to be live beyond copy.
630 MI.getOperand(1).setIsKill(false);
631 }
632
633 // Defs in a loop that are observed outside the loop must be transformed
634 // into appropriate bit manipulation.
635 std::vector<MachineBasicBlock *> DomBlocks = {&MBB};
636 for (MachineInstr &Use : MRI->use_instructions(DstReg))
637 DomBlocks.push_back(Use.getParent());
638
639 MachineBasicBlock *PostDomBound =
640 PDT.findNearestCommonDominator(DomBlocks);
641 unsigned FoundLoopLevel = LF.findLoop(PostDomBound);
642 if (FoundLoopLevel) {
643 MachineIDFSSAUpdater SSAUpdater(DT, MF, DstReg);
644 SSAUpdater.addUseBlock(&MBB);
645 SSAUpdater.addAvailableValue(&MBB, DstReg);
646 LF.addLoopEntries(FoundLoopLevel, SSAUpdater, *MRI, LaneMaskRegAttrs);
647
648 SSAUpdater.calculate();
649 buildMergeLaneMasks(MBB, MI, DL, DstReg,
650 SSAUpdater.getValueInMiddleOfBlock(&MBB), SrcReg);
651 DeadCopies.push_back(&MI);
652 }
653 }
654
655 for (MachineInstr *MI : DeadCopies)
656 MI->eraseFromParent();
657 DeadCopies.clear();
658 }
659 return Changed;
660}
661
663 bool &Val) const {
664 const MachineInstr *MI;
665 for (;;) {
666 MI = MRI->getUniqueVRegDef(Reg);
667 if (MI->getOpcode() == AMDGPU::IMPLICIT_DEF)
668 return true;
669
670 if (MI->getOpcode() != AMDGPU::COPY)
671 break;
672
673 Reg = MI->getOperand(1).getReg();
674 if (!Reg.isVirtual())
675 return false;
676 if (!isLaneMaskReg(Reg))
677 return false;
678 }
679
680 if (MI->getOpcode() != LMC->MovOpc)
681 return false;
682
683 if (!MI->getOperand(1).isImm())
684 return false;
685
686 int64_t Imm = MI->getOperand(1).getImm();
687 if (Imm == 0) {
688 Val = false;
689 return true;
690 }
691 if (Imm == -1) {
692 Val = true;
693 return true;
694 }
695
696 return false;
697}
698
699static void instrDefsUsesSCC(const MachineInstr &MI, bool &Def, bool &Use) {
700 Def = false;
701 Use = false;
702
703 for (const MachineOperand &MO : MI.operands()) {
704 if (MO.isReg() && MO.getReg() == AMDGPU::SCC) {
705 if (MO.isUse())
706 Use = true;
707 else
708 Def = true;
709 }
710 }
711}
712
713/// Return a point at the end of the given \p MBB to insert SALU instructions
714/// for lane mask calculation. Take terminators and SCC into account.
717 auto InsertionPt = MBB.getFirstTerminator();
718 bool TerminatorsUseSCC = false;
719 for (auto I = InsertionPt, E = MBB.end(); I != E; ++I) {
720 bool DefsSCC;
721 instrDefsUsesSCC(*I, DefsSCC, TerminatorsUseSCC);
722 if (TerminatorsUseSCC || DefsSCC)
723 break;
724 }
725
726 if (!TerminatorsUseSCC)
727 return InsertionPt;
728
729 while (InsertionPt != MBB.begin()) {
730 InsertionPt--;
731
732 bool DefSCC, UseSCC;
733 instrDefsUsesSCC(*InsertionPt, DefSCC, UseSCC);
734 if (DefSCC)
735 return InsertionPt;
736 }
737
738 // We should have at least seen an IMPLICIT_DEF or COPY
739 llvm_unreachable("SCC used by terminator but no def in block");
740}
741
742// VReg_1 -> SReg_32 or SReg_64
743void Vreg1LoweringHelper::markAsLaneMask(Register DstReg) const {
744 MRI->setRegClass(DstReg, ST->getBoolRC());
745}
746
747void Vreg1LoweringHelper::getCandidatesForLowering(
748 SmallVectorImpl<MachineInstr *> &Vreg1Phis) const {
749 for (MachineBasicBlock &MBB : MF) {
750 for (MachineInstr &MI : MBB.phis()) {
751 if (isVreg1(MI.getOperand(0).getReg()))
752 Vreg1Phis.push_back(&MI);
753 }
754 }
755}
756
757void Vreg1LoweringHelper::collectIncomingValuesFromPhi(
758 const MachineInstr *MI,
759 SmallVectorImpl<AMDGPU::Incoming> &Incomings) const {
760 for (unsigned i = 1; i < MI->getNumOperands(); i += 2) {
761 assert(i + 1 < MI->getNumOperands());
762 Register IncomingReg = MI->getOperand(i).getReg();
763 MachineBasicBlock *IncomingMBB = MI->getOperand(i + 1).getMBB();
764 MachineInstr *IncomingDef = MRI->getUniqueVRegDef(IncomingReg);
765
766 if (IncomingDef->getOpcode() == AMDGPU::COPY) {
767 IncomingReg = IncomingDef->getOperand(1).getReg();
768 assert(isLaneMaskReg(IncomingReg) || isVreg1(IncomingReg));
769 assert(!IncomingDef->getOperand(1).getSubReg());
770 } else if (IncomingDef->getOpcode() == AMDGPU::IMPLICIT_DEF) {
771 continue;
772 } else {
773 assert(IncomingDef->isPHI() || PhiRegisters.count(IncomingReg));
774 }
775
776 Incomings.emplace_back(IncomingReg, IncomingMBB, Register());
777 }
778}
779
780void Vreg1LoweringHelper::replaceDstReg(Register NewReg, Register OldReg,
781 MachineBasicBlock *MBB) {
782 MRI->replaceRegWith(NewReg, OldReg);
783}
784
785void Vreg1LoweringHelper::buildMergeLaneMasks(MachineBasicBlock &MBB,
787 const DebugLoc &DL,
788 Register DstReg, Register PrevReg,
789 Register CurReg) {
790 bool PrevVal = false;
791 bool PrevConstant = isConstantLaneMask(PrevReg, PrevVal);
792 bool CurVal = false;
793 bool CurConstant = isConstantLaneMask(CurReg, CurVal);
794
795 if (PrevConstant && CurConstant) {
796 if (PrevVal == CurVal) {
797 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg).addReg(CurReg);
798 } else if (CurVal) {
799 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg).addReg(LMC->ExecReg);
800 } else {
801 BuildMI(MBB, I, DL, TII->get(LMC->XorOpc), DstReg)
802 .addReg(LMC->ExecReg)
803 .addImm(-1)
804 .setOperandDead(3);
805 }
806 return;
807 }
808
809 Register PrevMaskedReg;
810 Register CurMaskedReg;
811 if (!PrevConstant) {
812 if (CurConstant && CurVal) {
813 PrevMaskedReg = PrevReg;
814 } else {
815 PrevMaskedReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
816 BuildMI(MBB, I, DL, TII->get(LMC->AndN2Opc), PrevMaskedReg)
817 .addReg(PrevReg)
818 .addReg(LMC->ExecReg)
819 .setOperandDead(3);
820 }
821 }
822 if (!CurConstant) {
823 // TODO: check whether CurReg is already masked by EXEC
824 if (PrevConstant && PrevVal) {
825 CurMaskedReg = CurReg;
826 } else {
827 CurMaskedReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
828 BuildMI(MBB, I, DL, TII->get(LMC->AndOpc), CurMaskedReg)
829 .addReg(CurReg)
830 .addReg(LMC->ExecReg)
831 .setOperandDead(3);
832 }
833 }
834
835 if (PrevConstant && !PrevVal) {
836 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg)
837 .addReg(CurMaskedReg);
838 } else if (CurConstant && !CurVal) {
839 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg)
840 .addReg(PrevMaskedReg);
841 } else if (PrevConstant && PrevVal) {
842 BuildMI(MBB, I, DL, TII->get(LMC->OrN2Opc), DstReg)
843 .addReg(CurMaskedReg)
844 .addReg(LMC->ExecReg)
845 .setOperandDead(3);
846 } else {
847 BuildMI(MBB, I, DL, TII->get(LMC->OrOpc), DstReg)
848 .addReg(PrevMaskedReg)
849 .addReg(CurMaskedReg ? CurMaskedReg : LMC->ExecReg)
850 .setOperandDead(3);
851 }
852}
853
854void Vreg1LoweringHelper::constrainAsLaneMask(AMDGPU::Incoming &In) {}
855
856/// Lower all instructions that def or use vreg_1 registers.
857///
858/// In a first pass, we lower COPYs from vreg_1 to vector registers, as can
859/// occur around inline assembly. We do this first, before vreg_1 registers
860/// are changed to scalar mask registers.
861///
862/// Then we lower all defs of vreg_1 registers. Phi nodes are lowered before
863/// all others, because phi lowering looks through copies and can therefore
864/// often make copy lowering unnecessary.
867 // Only need to run this in SelectionDAG path.
868 if (MF.getProperties().hasSelected())
869 return false;
870
871 Vreg1LoweringHelper Helper(MF, MDT, MPDT);
872 bool Changed = false;
873 Changed |= Helper.lowerCopiesFromI1();
874 Changed |= Helper.lowerPhis();
875 Changed |= Helper.lowerCopiesToI1();
876 return Helper.cleanConstrainRegs(Changed);
877}
878
879PreservedAnalyses
892
894public:
895 static char ID;
896
898
899 bool runOnMachineFunction(MachineFunction &MF) override;
900
901 StringRef getPassName() const override { return "SI Lower i1 Copies"; }
902
909};
910
918
920 false, false)
925
926char SILowerI1CopiesLegacy::ID = 0;
927
929
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#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 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
static void instrDefsUsesSCC(const MachineInstr &MI, bool &Def, bool &Use)
static Register insertUndefLaneMask(MachineBasicBlock *MBB, MachineRegisterInfo *MRI, MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs)
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...
Helper class that detects loops which require us to lower an i1 COPY into bitwise manipulation.
void initialize(MachineBasicBlock &MBB)
unsigned findLoop(MachineBasicBlock *PostDom)
Check whether a backward edge can be reached without going through the given PostDom of the def block...
LoopFinder(MachineDominatorTree &DT, MachinePostDominatorTree &PDT)
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:281
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
const HexagonRegisterInfo & getRegisterInfo() const
void push_back(MachineInstr *MI)
iterator_range< succ_iterator > successors()
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...
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 Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
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:112
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
Changed
#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.
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:2224
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
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.