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