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