1//===- SIFixSGPRCopies.cpp - Remove potential VGPR => SGPR 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/// \file
10/// Copies from VGPR to SGPR registers are illegal and the register coalescer
11/// will sometimes generate these illegal copies in situations like this:
12///
13/// Register Class <vsrc> is the union of <vgpr> and <sgpr>
14///
15/// BB0:
16/// %0 <sgpr> = SCALAR_INST
17/// %1 <vsrc> = COPY %0 <sgpr>
18/// ...
19/// BRANCH %cond BB1, BB2
20/// BB1:
21/// %2 <vgpr> = VECTOR_INST
22/// %3 <vsrc> = COPY %2 <vgpr>
23/// BB2:
24/// %4 <vsrc> = PHI %1 <vsrc>, <%bb.0>, %3 <vrsc>, <%bb.1>
25/// %5 <vgpr> = VECTOR_INST %4 <vsrc>
26///
27///
28/// The coalescer will begin at BB0 and eliminate its copy, then the resulting
29/// code will look like this:
30///
31/// BB0:
32/// %0 <sgpr> = SCALAR_INST
33/// ...
34/// BRANCH %cond BB1, BB2
35/// BB1:
36/// %2 <vgpr> = VECTOR_INST
37/// %3 <vsrc> = COPY %2 <vgpr>
38/// BB2:
39/// %4 <sgpr> = PHI %0 <sgpr>, <%bb.0>, %3 <vsrc>, <%bb.1>
40/// %5 <vgpr> = VECTOR_INST %4 <sgpr>
41///
42/// Now that the result of the PHI instruction is an SGPR, the register
43/// allocator is now forced to constrain the register class of %3 to
44/// <sgpr> so we end up with final code like this:
45///
46/// BB0:
47/// %0 <sgpr> = SCALAR_INST
48/// ...
49/// BRANCH %cond BB1, BB2
50/// BB1:
51/// %2 <vgpr> = VECTOR_INST
52/// %3 <sgpr> = COPY %2 <vgpr>
53/// BB2:
54/// %4 <sgpr> = PHI %0 <sgpr>, <%bb.0>, %3 <sgpr>, <%bb.1>
55/// %5 <vgpr> = VECTOR_INST %4 <sgpr>
56///
57/// Now this code contains an illegal copy from a VGPR to an SGPR.
58///
59/// In order to avoid this problem, this pass searches for PHI instructions
60/// which define a <vsrc> register and constrains its definition class to
61/// <vgpr> if the user of the PHI's definition register is a vector instruction.
62/// If the PHI's definition class is constrained to <vgpr> then the coalescer
63/// will be unable to perform the COPY removal from the above example which
64/// ultimately led to the creation of an illegal COPY.
65//===----------------------------------------------------------------------===//
66
67#include "SIFixSGPRCopies.h"
68#include "AMDGPU.h"
69#include "AMDGPULaneMaskUtils.h"
70#include "GCNSubtarget.h"
71#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
72#include "llvm/CodeGen/MachineDominators.h"
73#include "llvm/InitializePasses.h"
74#include "llvm/Target/TargetMachine.h"
75
76using namespace llvm;
77
78#define DEBUG_TYPE "si-fix-sgpr-copies"
79
80static cl::opt<bool> EnableM0Merge(
81 "amdgpu-enable-merge-m0",
82 cl::desc("Merge and hoist M0 initializations"),
83 cl::init(Val: true));
84
85namespace {
86
87class V2SCopyInfo {
88public:
89 // VGPR to SGPR copy being processed
90 MachineInstr *Copy;
91 // All SALU instructions reachable from this copy in SSA graph
92 SetVector<MachineInstr *> SChain;
93 // Number of SGPR to VGPR copies that are used to put the SALU computation
94 // results back to VALU.
95 unsigned NumSVCopies = 0;
96
97 unsigned Score = 0;
98 // Actual count of v_readfirstlane_b32
99 // which need to be inserted to keep SChain SALU
100 unsigned NumReadfirstlanes = 0;
101 // Current score state. To speedup selection V2SCopyInfos for processing
102 bool NeedToBeConvertedToVALU = false;
103 // Unique ID. Used as a key for mapping to keep permanent order.
104 unsigned ID;
105
106 // Count of another VGPR to SGPR copies that contribute to the
107 // current copy SChain
108 unsigned SiblingPenalty = 0;
109 SetVector<unsigned> Siblings;
110 V2SCopyInfo() : Copy(nullptr), ID(0){};
111 V2SCopyInfo(unsigned Id, MachineInstr *C, unsigned Width)
112 : Copy(C), NumReadfirstlanes(Width / 32), ID(Id){};
113#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
114 void dump() const {
115 dbgs() << ID << " : " << *Copy << "\n\tS:" << SChain.size()
116 << "\n\tSV:" << NumSVCopies << "\n\tSP: " << SiblingPenalty
117 << "\nScore: " << Score << "\n";
118 }
119#endif
120};
121
122class SIFixSGPRCopies {
123 MachineDominatorTree *MDT;
124 SmallVector<MachineInstr*, 4> SCCCopies;
125 SmallVector<MachineInstr*, 4> RegSequences;
126 SmallVector<MachineInstr*, 4> PHINodes;
127 SmallVector<MachineInstr*, 4> S2VCopies;
128 unsigned NextVGPRToSGPRCopyID = 0;
129 MapVector<unsigned, V2SCopyInfo> V2SCopies;
130 DenseMap<MachineInstr *, SetVector<unsigned>> SiblingPenalty;
131 DenseSet<MachineInstr *> PHISources;
132
133public:
134 MachineRegisterInfo *MRI;
135 const SIRegisterInfo *TRI;
136 const SIInstrInfo *TII;
137
138 SIFixSGPRCopies(MachineDominatorTree *MDT) : MDT(MDT) {}
139
140 bool run(MachineFunction &MF);
141 void fixSCCCopies(MachineFunction &MF);
142 void prepareRegSequenceAndPHIs(MachineFunction &MF);
143 unsigned getNextVGPRToSGPRCopyId() { return ++NextVGPRToSGPRCopyID; }
144 bool needToBeConvertedToVALU(V2SCopyInfo *I);
145 void analyzeVGPRToSGPRCopy(MachineInstr *MI);
146 void lowerVGPR2SGPRCopies(MachineFunction &MF);
147 // Handles copies which source register is:
148 // 1. Physical register
149 // 2. AGPR
150 // 3. Defined by the instruction the merely moves the immediate
151 bool lowerSpecialCase(MachineInstr &MI, MachineBasicBlock::iterator &I);
152
153 void processPHINode(MachineInstr &MI);
154
155 // Check if MO is an immediate materialized into a VGPR, and if so replace it
156 // with an SGPR immediate. The VGPR immediate is also deleted if it does not
157 // have any other uses.
158 bool tryMoveVGPRConstToSGPR(MachineOperand &MO, Register NewDst,
159 MachineBasicBlock *BlockToInsertTo,
160 MachineBasicBlock::iterator PointToInsertTo,
161 const DebugLoc &DL);
162};
163
164class SIFixSGPRCopiesLegacy : public MachineFunctionPass {
165public:
166 static char ID;
167
168 SIFixSGPRCopiesLegacy() : MachineFunctionPass(ID) {}
169
170 bool runOnMachineFunction(MachineFunction &MF) override {
171 MachineDominatorTree *MDT =
172 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
173 SIFixSGPRCopies Impl(MDT);
174 return Impl.run(MF);
175 }
176
177 StringRef getPassName() const override { return "SI Fix SGPR copies"; }
178
179 void getAnalysisUsage(AnalysisUsage &AU) const override {
180 AU.addRequired<MachineDominatorTreeWrapperPass>();
181 AU.addPreserved<MachineDominatorTreeWrapperPass>();
182 AU.setPreservesCFG();
183 MachineFunctionPass::getAnalysisUsage(AU);
184 }
185
186 // Waterfall expansion may introduce Phi nodes and -verify-machineinstrs will
187 // fail.
188 MachineFunctionProperties getClearedProperties() const override {
189 return MachineFunctionProperties().setNoPHIs();
190 }
191};
192
193} // end anonymous namespace
194
195INITIALIZE_PASS_BEGIN(SIFixSGPRCopiesLegacy, DEBUG_TYPE, "SI Fix SGPR copies",
196 false, false)
197INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
198INITIALIZE_PASS_END(SIFixSGPRCopiesLegacy, DEBUG_TYPE, "SI Fix SGPR copies",
199 false, false)
200
201char SIFixSGPRCopiesLegacy::ID = 0;
202
203char &llvm::SIFixSGPRCopiesLegacyID = SIFixSGPRCopiesLegacy::ID;
204
205FunctionPass *llvm::createSIFixSGPRCopiesLegacyPass() {
206 return new SIFixSGPRCopiesLegacy();
207}
208
209static std::pair<const TargetRegisterClass *, const TargetRegisterClass *>
210getCopyRegClasses(const MachineInstr &Copy,
211 const SIRegisterInfo &TRI,
212 const MachineRegisterInfo &MRI) {
213 Register DstReg = Copy.getOperand(i: 0).getReg();
214 Register SrcReg = Copy.getOperand(i: 1).getReg();
215
216 const TargetRegisterClass *SrcRC = SrcReg.isVirtual()
217 ? MRI.getRegClass(Reg: SrcReg)
218 : TRI.getPhysRegBaseClass(Reg: SrcReg);
219
220 // We don't really care about the subregister here.
221 // SrcRC = TRI.getSubRegClass(SrcRC, Copy.getOperand(1).getSubReg());
222
223 const TargetRegisterClass *DstRC = DstReg.isVirtual()
224 ? MRI.getRegClass(Reg: DstReg)
225 : TRI.getPhysRegBaseClass(Reg: DstReg);
226
227 return std::pair(SrcRC, DstRC);
228}
229
230static bool isVGPRToSGPRCopy(const TargetRegisterClass *SrcRC,
231 const TargetRegisterClass *DstRC,
232 const SIRegisterInfo &TRI) {
233 return SrcRC != &AMDGPU::VReg_1RegClass && TRI.isSGPRClass(RC: DstRC) &&
234 TRI.hasVectorRegisters(RC: SrcRC);
235}
236
237static bool isSGPRToVGPRCopy(const TargetRegisterClass *SrcRC,
238 const TargetRegisterClass *DstRC,
239 const SIRegisterInfo &TRI) {
240 return DstRC != &AMDGPU::VReg_1RegClass && TRI.isSGPRClass(RC: SrcRC) &&
241 TRI.hasVectorRegisters(RC: DstRC);
242}
243
244static bool tryChangeVGPRtoSGPRinCopy(MachineInstr &MI,
245 const SIRegisterInfo *TRI,
246 const SIInstrInfo *TII) {
247 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
248 auto &Src = MI.getOperand(i: 1);
249 Register DstReg = MI.getOperand(i: 0).getReg();
250 Register SrcReg = Src.getReg();
251 if (!SrcReg.isVirtual() || !DstReg.isVirtual())
252 return false;
253
254 for (const auto &MO : MRI.reg_nodbg_operands(Reg: DstReg)) {
255 const auto *UseMI = MO.getParent();
256 if (UseMI == &MI)
257 continue;
258 if (MO.isDef() || UseMI->getParent() != MI.getParent() ||
259 UseMI->getOpcode() <= TargetOpcode::GENERIC_OP_END)
260 return false;
261
262 unsigned OpIdx = MO.getOperandNo();
263 if (OpIdx >= UseMI->getDesc().getNumOperands() ||
264 !TII->isOperandLegal(MI: *UseMI, OpIdx, MO: &Src))
265 return false;
266 }
267 // Change VGPR to SGPR destination.
268 MRI.setRegClass(Reg: DstReg, RC: TRI->getEquivalentSGPRClass(VRC: MRI.getRegClass(Reg: DstReg)));
269 return true;
270}
271
272// Distribute an SGPR->VGPR copy of a REG_SEQUENCE into a VGPR REG_SEQUENCE.
273//
274// SGPRx = ...
275// SGPRy = REG_SEQUENCE SGPRx, sub0 ...
276// VGPRz = COPY SGPRy
277//
278// ==>
279//
280// VGPRx = COPY SGPRx
281// VGPRz = REG_SEQUENCE VGPRx, sub0
282//
283// This exposes immediate folding opportunities when materializing 64-bit
284// immediates.
285static bool foldVGPRCopyIntoRegSequence(MachineInstr &MI,
286 const SIRegisterInfo *TRI,
287 const SIInstrInfo *TII,
288 MachineRegisterInfo &MRI) {
289 assert(MI.isRegSequence());
290
291 Register DstReg = MI.getOperand(i: 0).getReg();
292 if (!TRI->isSGPRClass(RC: MRI.getRegClass(Reg: DstReg)))
293 return false;
294
295 if (!MRI.hasOneUse(RegNo: DstReg))
296 return false;
297
298 MachineInstr &CopyUse = *MRI.use_instr_begin(RegNo: DstReg);
299 if (!CopyUse.isCopy())
300 return false;
301
302 // It is illegal to have vreg inputs to a physreg defining reg_sequence.
303 if (CopyUse.getOperand(i: 0).getReg().isPhysical())
304 return false;
305
306 const TargetRegisterClass *SrcRC, *DstRC;
307 std::tie(args&: SrcRC, args&: DstRC) = getCopyRegClasses(Copy: CopyUse, TRI: *TRI, MRI);
308
309 if (!isSGPRToVGPRCopy(SrcRC, DstRC, TRI: *TRI))
310 return false;
311
312 if (tryChangeVGPRtoSGPRinCopy(MI&: CopyUse, TRI, TII))
313 return true;
314
315 // TODO: Could have multiple extracts?
316 unsigned SubReg = CopyUse.getOperand(i: 1).getSubReg();
317 if (SubReg != AMDGPU::NoSubRegister)
318 return false;
319
320 MRI.setRegClass(Reg: DstReg, RC: DstRC);
321
322 // SGPRx = ...
323 // SGPRy = REG_SEQUENCE SGPRx, sub0 ...
324 // VGPRz = COPY SGPRy
325
326 // =>
327 // VGPRx = COPY SGPRx
328 // VGPRz = REG_SEQUENCE VGPRx, sub0
329
330 MI.getOperand(i: 0).setReg(CopyUse.getOperand(i: 0).getReg());
331 bool IsAGPR = TRI->isAGPRClass(RC: DstRC);
332
333 for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
334 const TargetRegisterClass *SrcRC =
335 TRI->getRegClassForOperandReg(MRI, MO: MI.getOperand(i: I));
336 assert(TRI->isSGPRClass(SrcRC) &&
337 "Expected SGPR REG_SEQUENCE to only have SGPR inputs");
338 const TargetRegisterClass *NewSrcRC = TRI->getEquivalentVGPRClass(SRC: SrcRC);
339
340 Register TmpReg = MRI.createVirtualRegister(RegClass: NewSrcRC);
341
342 BuildMI(BB&: *MI.getParent(), I: &MI, MIMD: MI.getDebugLoc(), MCID: TII->get(Opcode: AMDGPU::COPY),
343 DestReg: TmpReg)
344 .add(MO: MI.getOperand(i: I));
345
346 if (IsAGPR) {
347 const TargetRegisterClass *NewSrcRC = TRI->getEquivalentAGPRClass(SRC: SrcRC);
348 Register TmpAReg = MRI.createVirtualRegister(RegClass: NewSrcRC);
349 unsigned Opc = NewSrcRC == &AMDGPU::AGPR_32RegClass ?
350 AMDGPU::V_ACCVGPR_WRITE_B32_e64 : AMDGPU::COPY;
351 BuildMI(BB&: *MI.getParent(), I: &MI, MIMD: MI.getDebugLoc(), MCID: TII->get(Opcode: Opc),
352 DestReg: TmpAReg)
353 .addReg(RegNo: TmpReg, Flags: RegState::Kill);
354 TmpReg = TmpAReg;
355 }
356
357 MI.getOperand(i: I).setReg(TmpReg);
358 }
359
360 CopyUse.eraseFromParent();
361 return true;
362}
363
364static bool isSafeToFoldImmIntoCopy(const MachineInstr *Copy,
365 const MachineInstr *MoveImm,
366 const SIInstrInfo *TII,
367 unsigned &SMovOp,
368 int64_t &Imm) {
369 if (Copy->getOpcode() != AMDGPU::COPY)
370 return false;
371
372 if (!MoveImm->isMoveImmediate())
373 return false;
374
375 const MachineOperand *ImmOp =
376 TII->getNamedOperand(MI: *MoveImm, OperandName: AMDGPU::OpName::src0);
377 if (!ImmOp->isImm())
378 return false;
379
380 // FIXME: Handle copies with sub-regs.
381 if (Copy->getOperand(i: 1).getSubReg())
382 return false;
383
384 switch (MoveImm->getOpcode()) {
385 default:
386 return false;
387 case AMDGPU::V_MOV_B32_e32:
388 case AMDGPU::AV_MOV_B32_IMM_PSEUDO:
389 SMovOp = AMDGPU::S_MOV_B32;
390 break;
391 case AMDGPU::V_MOV_B64_e32:
392 case AMDGPU::V_MOV_B64_PSEUDO:
393 SMovOp = AMDGPU::S_MOV_B64_IMM_PSEUDO;
394 break;
395 }
396 Imm = ImmOp->getImm();
397 return true;
398}
399
400template <class UnaryPredicate>
401bool searchPredecessors(const MachineBasicBlock *MBB,
402 const MachineBasicBlock *CutOff,
403 UnaryPredicate Predicate) {
404 if (MBB == CutOff)
405 return false;
406
407 DenseSet<const MachineBasicBlock *> Visited;
408 SmallVector<MachineBasicBlock *, 4> Worklist(MBB->predecessors());
409
410 while (!Worklist.empty()) {
411 MachineBasicBlock *MBB = Worklist.pop_back_val();
412
413 if (!Visited.insert(V: MBB).second)
414 continue;
415 if (MBB == CutOff)
416 continue;
417 if (Predicate(MBB))
418 return true;
419
420 Worklist.append(in_start: MBB->pred_begin(), in_end: MBB->pred_end());
421 }
422
423 return false;
424}
425
426// Checks if there is potential path From instruction To instruction.
427// If CutOff is specified and it sits in between of that path we ignore
428// a higher portion of the path and report it is not reachable.
429static bool isReachable(const MachineInstr *From,
430 const MachineInstr *To,
431 const MachineBasicBlock *CutOff,
432 MachineDominatorTree &MDT) {
433 if (MDT.dominates(A: From, B: To))
434 return true;
435
436 const MachineBasicBlock *MBBFrom = From->getParent();
437 const MachineBasicBlock *MBBTo = To->getParent();
438
439 // Do predecessor search.
440 // We should almost never get here since we do not usually produce M0 stores
441 // other than -1.
442 return searchPredecessors(MBB: MBBTo, CutOff, Predicate: [MBBFrom]
443 (const MachineBasicBlock *MBB) { return MBB == MBBFrom; });
444}
445
446// Return the first non-prologue instruction in the block.
447static MachineBasicBlock::iterator
448getFirstNonPrologue(MachineBasicBlock *MBB, const TargetInstrInfo *TII) {
449 MachineBasicBlock::iterator I = MBB->getFirstNonPHI();
450 while (I != MBB->end() && TII->isBasicBlockPrologue(MI: *I))
451 ++I;
452
453 return I;
454}
455
456// Hoist and merge identical SGPR initializations into a common predecessor.
457// This is intended to combine M0 initializations, but can work with any
458// SGPR. A VGPR cannot be processed since we cannot guarantee vector
459// executioon.
460static bool hoistAndMergeSGPRInits(unsigned Reg,
461 const MachineRegisterInfo &MRI,
462 const TargetRegisterInfo *TRI,
463 MachineDominatorTree &MDT,
464 const TargetInstrInfo *TII) {
465 // List of inits by immediate value.
466 using InitListMap = std::map<unsigned, std::list<MachineInstr *>>;
467 InitListMap Inits;
468 // List of clobbering instructions.
469 SmallVector<MachineInstr*, 8> Clobbers;
470 // List of instructions marked for deletion.
471 SmallPtrSet<MachineInstr *, 8> MergedInstrs;
472
473 bool Changed = false;
474
475 for (auto &MI : MRI.def_instructions(Reg)) {
476 MachineOperand *Imm = nullptr;
477 for (auto &MO : MI.operands()) {
478 if ((MO.isReg() && ((MO.isDef() && MO.getReg() != Reg) || !MO.isDef())) ||
479 (!MO.isImm() && !MO.isReg()) || (MO.isImm() && Imm)) {
480 Imm = nullptr;
481 break;
482 }
483 if (MO.isImm())
484 Imm = &MO;
485 }
486 if (Imm)
487 Inits[Imm->getImm()].push_front(x: &MI);
488 else
489 Clobbers.push_back(Elt: &MI);
490 }
491
492 for (auto &Init : Inits) {
493 auto &Defs = Init.second;
494
495 for (auto I1 = Defs.begin(), E = Defs.end(); I1 != E; ) {
496 MachineInstr *MI1 = *I1;
497
498 for (auto I2 = std::next(x: I1); I2 != E; ) {
499 MachineInstr *MI2 = *I2;
500
501 // Check any possible interference
502 auto interferes = [&](MachineBasicBlock::iterator From,
503 MachineBasicBlock::iterator To) -> bool {
504
505 assert(MDT.dominates(&*To, &*From));
506
507 auto interferes = [&MDT, From, To](MachineInstr* &Clobber) -> bool {
508 const MachineBasicBlock *MBBFrom = From->getParent();
509 const MachineBasicBlock *MBBTo = To->getParent();
510 bool MayClobberFrom = isReachable(From: Clobber, To: &*From, CutOff: MBBTo, MDT);
511 bool MayClobberTo = isReachable(From: Clobber, To: &*To, CutOff: MBBTo, MDT);
512 if (!MayClobberFrom && !MayClobberTo)
513 return false;
514 if ((MayClobberFrom && !MayClobberTo) ||
515 (!MayClobberFrom && MayClobberTo))
516 return true;
517 // Both can clobber, this is not an interference only if both are
518 // dominated by Clobber and belong to the same block or if Clobber
519 // properly dominates To, given that To >> From, so it dominates
520 // both and located in a common dominator.
521 return !((MBBFrom == MBBTo &&
522 MDT.dominates(A: Clobber, B: &*From) &&
523 MDT.dominates(A: Clobber, B: &*To)) ||
524 MDT.properlyDominates(A: Clobber->getParent(), B: MBBTo));
525 };
526
527 return (llvm::any_of(Range&: Clobbers, P: interferes)) ||
528 (llvm::any_of(Range&: Inits, P: [&](InitListMap::value_type &C) {
529 return C.first != Init.first &&
530 llvm::any_of(Range&: C.second, P: interferes);
531 }));
532 };
533
534 if (MDT.dominates(A: MI1, B: MI2)) {
535 if (!interferes(MI2, MI1)) {
536 LLVM_DEBUG(dbgs()
537 << "Erasing from "
538 << printMBBReference(*MI2->getParent()) << " " << *MI2);
539 MergedInstrs.insert(Ptr: MI2);
540 Changed = true;
541 ++I2;
542 continue;
543 }
544 } else if (MDT.dominates(A: MI2, B: MI1)) {
545 if (!interferes(MI1, MI2)) {
546 LLVM_DEBUG(dbgs()
547 << "Erasing from "
548 << printMBBReference(*MI1->getParent()) << " " << *MI1);
549 MergedInstrs.insert(Ptr: MI1);
550 Changed = true;
551 ++I1;
552 break;
553 }
554 } else {
555 auto *MBB = MDT.findNearestCommonDominator(A: MI1->getParent(),
556 B: MI2->getParent());
557 if (!MBB) {
558 ++I2;
559 continue;
560 }
561
562 MachineBasicBlock::iterator I = getFirstNonPrologue(MBB, TII);
563 if (!interferes(MI1, I) && !interferes(MI2, I)) {
564 LLVM_DEBUG(dbgs()
565 << "Erasing from "
566 << printMBBReference(*MI1->getParent()) << " " << *MI1
567 << "and moving from "
568 << printMBBReference(*MI2->getParent()) << " to "
569 << printMBBReference(*I->getParent()) << " " << *MI2);
570 I->getParent()->splice(Where: I, Other: MI2->getParent(), From: MI2);
571 MergedInstrs.insert(Ptr: MI1);
572 Changed = true;
573 ++I1;
574 break;
575 }
576 }
577 ++I2;
578 }
579 ++I1;
580 }
581 }
582
583 // Remove initializations that were merged into another.
584 for (auto &Init : Inits) {
585 auto &Defs = Init.second;
586 auto I = Defs.begin();
587 while (I != Defs.end()) {
588 if (MergedInstrs.count(Ptr: *I)) {
589 (*I)->eraseFromParent();
590 I = Defs.erase(position: I);
591 } else
592 ++I;
593 }
594 }
595
596 // Try to schedule SGPR initializations as early as possible in the MBB.
597 for (auto &Init : Inits) {
598 auto &Defs = Init.second;
599 for (auto *MI : Defs) {
600 auto *MBB = MI->getParent();
601 MachineInstr &BoundaryMI = *getFirstNonPrologue(MBB, TII);
602 MachineBasicBlock::reverse_iterator B(BoundaryMI);
603 // Check if B should actually be a boundary. If not set the previous
604 // instruction as the boundary instead.
605 if (!TII->isBasicBlockPrologue(MI: *B))
606 B++;
607
608 auto R = std::next(x: MI->getReverseIterator());
609 const unsigned Threshold = 50;
610 // Search until B or Threshold for a place to insert the initialization.
611 for (unsigned I = 0; R != B && I < Threshold; ++R, ++I)
612 if (R->readsRegister(Reg, TRI) || R->definesRegister(Reg, TRI) ||
613 TII->isSchedulingBoundary(MI: *R, MBB, MF: *MBB->getParent()))
614 break;
615
616 // Move to directly after R.
617 if (&*--R != MI)
618 MBB->splice(Where: *R, Other: MBB, From: MI);
619 }
620 }
621
622 if (Changed)
623 MRI.clearKillFlags(Reg);
624
625 return Changed;
626}
627
628bool SIFixSGPRCopies::run(MachineFunction &MF) {
629 // Only need to run this in SelectionDAG path.
630 if (MF.getProperties().hasSelected())
631 return false;
632
633 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
634 MRI = &MF.getRegInfo();
635 TRI = ST.getRegisterInfo();
636 TII = ST.getInstrInfo();
637
638 // Instructions to re-legalize after changing register classes
639 SmallVector<MachineInstr *, 8> Relegalize;
640
641 for (MachineBasicBlock &MBB : MF) {
642 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
643 ++I) {
644 MachineInstr &MI = *I;
645
646 switch (MI.getOpcode()) {
647 default:
648 // scale_src has a register class restricted to low 256 VGPRs, changing
649 // registers to VGPR may not take it into acount.
650 if (TII->isWMMA(MI) &&
651 AMDGPU::hasNamedOperand(Opcode: MI.getOpcode(), NamedIdx: AMDGPU::OpName::scale_src0))
652 Relegalize.push_back(Elt: &MI);
653 continue;
654 case AMDGPU::COPY: {
655 const TargetRegisterClass *SrcRC, *DstRC;
656 std::tie(args&: SrcRC, args&: DstRC) = getCopyRegClasses(Copy: MI, TRI: *TRI, MRI: *MRI);
657
658 if (isSGPRToVGPRCopy(SrcRC, DstRC, TRI: *TRI)) {
659 // Since VGPR to SGPR copies affect VGPR to SGPR copy
660 // score and, hence the lowering decision, let's try to get rid of
661 // them as early as possible
662 if (tryChangeVGPRtoSGPRinCopy(MI, TRI, TII))
663 continue;
664
665 // Collect those not changed to try them after VGPR to SGPR copies
666 // lowering as there will be more opportunities.
667 S2VCopies.push_back(Elt: &MI);
668 }
669 if (!isVGPRToSGPRCopy(SrcRC, DstRC, TRI: *TRI))
670 continue;
671 if (lowerSpecialCase(MI, I))
672 continue;
673
674 analyzeVGPRToSGPRCopy(MI: &MI);
675
676 break;
677 }
678 case AMDGPU::WQM:
679 case AMDGPU::STRICT_WQM:
680 case AMDGPU::SOFT_WQM:
681 case AMDGPU::STRICT_WWM:
682 case AMDGPU::INSERT_SUBREG:
683 case AMDGPU::PHI:
684 case AMDGPU::REG_SEQUENCE: {
685 if (TRI->isSGPRClass(RC: TII->getOpRegClass(MI, OpNo: 0))) {
686 for (MachineOperand &MO : MI.operands()) {
687 if (!MO.isReg() || !MO.getReg().isVirtual())
688 continue;
689 const TargetRegisterClass *SrcRC = MRI->getRegClass(Reg: MO.getReg());
690 if (SrcRC == &AMDGPU::VReg_1RegClass)
691 continue;
692
693 if (TRI->hasVectorRegisters(RC: SrcRC)) {
694 const TargetRegisterClass *DestRC =
695 TRI->getEquivalentSGPRClass(VRC: SrcRC);
696 Register NewDst = MRI->createVirtualRegister(RegClass: DestRC);
697 MachineBasicBlock *BlockToInsertCopy =
698 MI.isPHI() ? MI.getOperand(i: MO.getOperandNo() + 1).getMBB()
699 : &MBB;
700 MachineBasicBlock::iterator PointToInsertCopy =
701 MI.isPHI() ? BlockToInsertCopy->getFirstInstrTerminator() : I;
702
703 const DebugLoc &DL = MI.getDebugLoc();
704 if (!tryMoveVGPRConstToSGPR(MO, NewDst, BlockToInsertTo: BlockToInsertCopy,
705 PointToInsertTo: PointToInsertCopy, DL)) {
706 MachineInstr *NewCopy =
707 BuildMI(BB&: *BlockToInsertCopy, I: PointToInsertCopy, MIMD: DL,
708 MCID: TII->get(Opcode: AMDGPU::COPY), DestReg: NewDst)
709 .addReg(RegNo: MO.getReg());
710 MO.setReg(NewDst);
711 analyzeVGPRToSGPRCopy(MI: NewCopy);
712 PHISources.insert(V: NewCopy);
713 }
714 }
715 }
716 }
717
718 if (MI.isPHI())
719 PHINodes.push_back(Elt: &MI);
720 else if (MI.isRegSequence())
721 RegSequences.push_back(Elt: &MI);
722
723 break;
724 }
725 case AMDGPU::V_WRITELANE_B32: {
726 // Some architectures allow more than one constant bus access without
727 // SGPR restriction
728 if (ST.getConstantBusLimit(Opcode: MI.getOpcode()) != 1)
729 break;
730
731 // Writelane is special in that it can use SGPR and M0 (which would
732 // normally count as using the constant bus twice - but in this case it
733 // is allowed since the lane selector doesn't count as a use of the
734 // constant bus). However, it is still required to abide by the 1 SGPR
735 // rule. Apply a fix here as we might have multiple SGPRs after
736 // legalizing VGPRs to SGPRs
737 int Src0Idx =
738 AMDGPU::getNamedOperandIdx(Opcode: MI.getOpcode(), Name: AMDGPU::OpName::src0);
739 int Src1Idx =
740 AMDGPU::getNamedOperandIdx(Opcode: MI.getOpcode(), Name: AMDGPU::OpName::src1);
741 MachineOperand &Src0 = MI.getOperand(i: Src0Idx);
742 MachineOperand &Src1 = MI.getOperand(i: Src1Idx);
743
744 // Check to see if the instruction violates the 1 SGPR rule
745 if ((Src0.isReg() && TRI->isSGPRReg(MRI: *MRI, Reg: Src0.getReg()) &&
746 Src0.getReg() != AMDGPU::M0) &&
747 (Src1.isReg() && TRI->isSGPRReg(MRI: *MRI, Reg: Src1.getReg()) &&
748 Src1.getReg() != AMDGPU::M0)) {
749
750 // Check for trivially easy constant prop into one of the operands
751 // If this is the case then perform the operation now to resolve SGPR
752 // issue. If we don't do that here we will always insert a mov to m0
753 // that can't be resolved in later operand folding pass
754 bool Resolved = false;
755 for (MachineOperand *MO : {&Src0, &Src1}) {
756 if (MO->getReg().isVirtual()) {
757 MachineInstr *DefMI = MRI->getVRegDef(Reg: MO->getReg());
758 if (DefMI && TII->isFoldableCopy(MI: *DefMI)) {
759 const MachineOperand &Def = DefMI->getOperand(i: 0);
760 if (Def.isReg() &&
761 MO->getReg() == Def.getReg() &&
762 MO->getSubReg() == Def.getSubReg()) {
763 const MachineOperand &Copied = DefMI->getOperand(i: 1);
764 if (Copied.isImm() &&
765 TII->isInlineConstant(Imm: APInt(64, Copied.getImm(), true))) {
766 MO->ChangeToImmediate(ImmVal: Copied.getImm());
767 Resolved = true;
768 break;
769 }
770 }
771 }
772 }
773 }
774
775 if (!Resolved) {
776 // Haven't managed to resolve by replacing an SGPR with an immediate
777 // Move src1 to be in M0
778 BuildMI(BB&: *MI.getParent(), I&: MI, MIMD: MI.getDebugLoc(),
779 MCID: TII->get(Opcode: AMDGPU::COPY), DestReg: AMDGPU::M0)
780 .add(MO: Src1);
781 Src1.ChangeToRegister(Reg: AMDGPU::M0, isDef: false);
782 }
783 }
784 break;
785 }
786 }
787 }
788 }
789
790 lowerVGPR2SGPRCopies(MF);
791 // Postprocessing
792 fixSCCCopies(MF);
793 for (auto *MI : S2VCopies) {
794 // Check if it is still valid
795 if (MI->isCopy()) {
796 const TargetRegisterClass *SrcRC, *DstRC;
797 std::tie(args&: SrcRC, args&: DstRC) = getCopyRegClasses(Copy: *MI, TRI: *TRI, MRI: *MRI);
798 if (isSGPRToVGPRCopy(SrcRC, DstRC, TRI: *TRI))
799 tryChangeVGPRtoSGPRinCopy(MI&: *MI, TRI, TII);
800 }
801 }
802 for (auto *MI : RegSequences) {
803 // Check if it is still valid
804 if (MI->isRegSequence())
805 foldVGPRCopyIntoRegSequence(MI&: *MI, TRI, TII, MRI&: *MRI);
806 }
807 for (auto *MI : PHINodes) {
808 processPHINode(MI&: *MI);
809 }
810 while (!Relegalize.empty())
811 TII->legalizeOperands(MI&: *Relegalize.pop_back_val(), MDT);
812
813 if (MF.getTarget().getOptLevel() > CodeGenOptLevel::None && EnableM0Merge)
814 hoistAndMergeSGPRInits(Reg: AMDGPU::M0, MRI: *MRI, TRI, MDT&: *MDT, TII);
815
816 SiblingPenalty.clear();
817 V2SCopies.clear();
818 SCCCopies.clear();
819 RegSequences.clear();
820 PHINodes.clear();
821 S2VCopies.clear();
822 PHISources.clear();
823
824 return true;
825}
826
827void SIFixSGPRCopies::processPHINode(MachineInstr &MI) {
828 bool AllAGPRUses = true;
829 SetVector<const MachineInstr *> worklist;
830 SmallPtrSet<const MachineInstr *, 4> Visited;
831 SetVector<MachineInstr *> PHIOperands;
832 worklist.insert(X: &MI);
833 Visited.insert(Ptr: &MI);
834 // HACK to make MIR tests with no uses happy
835 bool HasUses = false;
836 while (!worklist.empty()) {
837 const MachineInstr *Instr = worklist.pop_back_val();
838 Register Reg = Instr->getOperand(i: 0).getReg();
839 for (const auto &Use : MRI->use_operands(Reg)) {
840 HasUses = true;
841 const MachineInstr *UseMI = Use.getParent();
842 AllAGPRUses &= (UseMI->isCopy() &&
843 TRI->isAGPR(MRI: *MRI, Reg: UseMI->getOperand(i: 0).getReg())) ||
844 TRI->isAGPR(MRI: *MRI, Reg: Use.getReg());
845 if (UseMI->isCopy() || UseMI->isRegSequence()) {
846 if (Visited.insert(Ptr: UseMI).second)
847 worklist.insert(X: UseMI);
848
849 continue;
850 }
851 }
852 }
853
854 Register PHIRes = MI.getOperand(i: 0).getReg();
855 const TargetRegisterClass *RC0 = MRI->getRegClass(Reg: PHIRes);
856 if (HasUses && AllAGPRUses && !TRI->isAGPRClass(RC: RC0)) {
857 LLVM_DEBUG(dbgs() << "Moving PHI to AGPR: " << MI);
858 MRI->setRegClass(Reg: PHIRes, RC: TRI->getEquivalentAGPRClass(SRC: RC0));
859 for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
860 MachineInstr *DefMI = MRI->getVRegDef(Reg: MI.getOperand(i: I).getReg());
861 if (DefMI && DefMI->isPHI())
862 PHIOperands.insert(X: DefMI);
863 }
864 }
865
866 if (TRI->hasVectorRegisters(RC: MRI->getRegClass(Reg: PHIRes)) ||
867 RC0 == &AMDGPU::VReg_1RegClass) {
868 LLVM_DEBUG(dbgs() << "Legalizing PHI: " << MI);
869 TII->legalizeOperands(MI, MDT);
870 }
871
872 // Propagate register class back to PHI operands which are PHI themselves.
873 while (!PHIOperands.empty()) {
874 processPHINode(MI&: *PHIOperands.pop_back_val());
875 }
876}
877
878bool SIFixSGPRCopies::tryMoveVGPRConstToSGPR(
879 MachineOperand &MaybeVGPRConstMO, Register DstReg,
880 MachineBasicBlock *BlockToInsertTo,
881 MachineBasicBlock::iterator PointToInsertTo, const DebugLoc &DL) {
882
883 MachineInstr *DefMI = MRI->getVRegDef(Reg: MaybeVGPRConstMO.getReg());
884 if (!DefMI || !DefMI->isMoveImmediate())
885 return false;
886
887 MachineOperand *SrcConst = TII->getNamedOperand(MI&: *DefMI, OperandName: AMDGPU::OpName::src0);
888 if (SrcConst->isReg())
889 return false;
890
891 const TargetRegisterClass *SrcRC =
892 MRI->getRegClass(Reg: MaybeVGPRConstMO.getReg());
893 unsigned MoveSize = TRI->getRegSizeInBits(RC: *SrcRC);
894 unsigned MoveOp =
895 MoveSize == 64 ? AMDGPU::S_MOV_B64_IMM_PSEUDO : AMDGPU::S_MOV_B32;
896 BuildMI(BB&: *BlockToInsertTo, I: PointToInsertTo, MIMD: DL, MCID: TII->get(Opcode: MoveOp), DestReg: DstReg)
897 .add(MO: *SrcConst);
898 if (MRI->hasOneUse(RegNo: MaybeVGPRConstMO.getReg()))
899 DefMI->eraseFromParent();
900 MaybeVGPRConstMO.setReg(DstReg);
901 return true;
902}
903
904bool SIFixSGPRCopies::lowerSpecialCase(MachineInstr &MI,
905 MachineBasicBlock::iterator &I) {
906 Register DstReg = MI.getOperand(i: 0).getReg();
907 Register SrcReg = MI.getOperand(i: 1).getReg();
908 if (!DstReg.isVirtual()) {
909 // If the destination register is a physical register there isn't
910 // really much we can do to fix this.
911 // Some special instructions use M0 as an input. Some even only use
912 // the first lane. Insert a readfirstlane and hope for the best.
913 const TargetRegisterClass *SrcRC = MRI->getRegClass(Reg: SrcReg);
914 if (DstReg == AMDGPU::M0 && TRI->hasVectorRegisters(RC: SrcRC)) {
915 Register TmpReg =
916 MRI->createVirtualRegister(RegClass: &AMDGPU::SReg_32_XM0RegClass);
917
918 const MCInstrDesc &ReadFirstLaneDesc =
919 TII->get(Opcode: AMDGPU::V_READFIRSTLANE_B32);
920 BuildMI(BB&: *MI.getParent(), I&: MI, MIMD: MI.getDebugLoc(), MCID: ReadFirstLaneDesc, DestReg: TmpReg)
921 .add(MO: MI.getOperand(i: 1));
922
923 unsigned SubReg = MI.getOperand(i: 1).getSubReg();
924 MI.getOperand(i: 1).setReg(TmpReg);
925 MI.getOperand(i: 1).setSubReg(AMDGPU::NoSubRegister);
926
927 const TargetRegisterClass *OpRC = TII->getRegClass(MCID: ReadFirstLaneDesc, OpNum: 1);
928 const TargetRegisterClass *ConstrainRC =
929 SubReg == AMDGPU::NoSubRegister
930 ? OpRC
931 : TRI->getMatchingSuperRegClass(A: SrcRC, B: OpRC, Idx: SubReg);
932
933 if (!MRI->constrainRegClass(Reg: SrcReg, RC: ConstrainRC))
934 llvm_unreachable("failed to constrain register");
935 return true;
936 }
937
938 if (tryMoveVGPRConstToSGPR(MaybeVGPRConstMO&: MI.getOperand(i: 1), DstReg, BlockToInsertTo: MI.getParent(), PointToInsertTo: MI,
939 DL: MI.getDebugLoc())) {
940 I = MI.eraseFromParent();
941 return true;
942 }
943
944 if (!SrcReg.isVirtual())
945 return true;
946 }
947 if (!SrcReg.isVirtual() || TRI->isAGPR(MRI: *MRI, Reg: SrcReg)) {
948 SIInstrWorklist worklist;
949 worklist.insert(MI: &MI);
950 TII->moveToVALU(Worklist&: worklist, MDT);
951 return true;
952 }
953
954 unsigned SMovOp;
955 int64_t Imm;
956 // If we are just copying an immediate, we can replace the copy with
957 // s_mov_b32.
958 if (isSafeToFoldImmIntoCopy(Copy: &MI, MoveImm: MRI->getVRegDef(Reg: SrcReg), TII, SMovOp, Imm)) {
959 MI.getOperand(i: 1).ChangeToImmediate(ImmVal: Imm);
960 MI.addImplicitDefUseOperands(MF&: *MI.getMF());
961 MI.setDesc(TII->get(Opcode: SMovOp));
962 return true;
963 }
964 return false;
965}
966
967void SIFixSGPRCopies::analyzeVGPRToSGPRCopy(MachineInstr* MI) {
968 if (PHISources.contains(V: MI))
969 return;
970 Register DstReg = MI->getOperand(i: 0).getReg();
971 const TargetRegisterClass *DstRC = TRI->getRegClassForReg(MRI: *MRI, Reg: DstReg);
972
973 V2SCopyInfo Info(getNextVGPRToSGPRCopyId(), MI,
974 TRI->getRegSizeInBits(RC: *DstRC));
975 SmallVector<MachineInstr *, 8> AnalysisWorklist;
976 // Needed because the SSA is not a tree but a graph and may have
977 // forks and joins. We should not then go same way twice.
978 DenseSet<MachineInstr *> Visited;
979 AnalysisWorklist.push_back(Elt: Info.Copy);
980 while (!AnalysisWorklist.empty()) {
981
982 MachineInstr *Inst = AnalysisWorklist.pop_back_val();
983
984 if (!Visited.insert(V: Inst).second)
985 continue;
986
987 // Copies and REG_SEQUENCE do not contribute to the final assembly
988 // So, skip them but take care of the SGPR to VGPR copies bookkeeping.
989 if (Inst->isRegSequence() &&
990 TRI->isVGPR(MRI: *MRI, Reg: Inst->getOperand(i: 0).getReg())) {
991 Info.NumSVCopies++;
992 continue;
993 }
994 if (Inst->isCopy()) {
995 const TargetRegisterClass *SrcRC, *DstRC;
996 std::tie(args&: SrcRC, args&: DstRC) = getCopyRegClasses(Copy: *Inst, TRI: *TRI, MRI: *MRI);
997 if (isSGPRToVGPRCopy(SrcRC, DstRC, TRI: *TRI) &&
998 !tryChangeVGPRtoSGPRinCopy(MI&: *Inst, TRI, TII)) {
999 Info.NumSVCopies++;
1000 continue;
1001 }
1002 }
1003
1004 SiblingPenalty[Inst].insert(X: Info.ID);
1005
1006 SmallVector<MachineInstr *, 4> Users;
1007 if ((TII->isSALU(MI: *Inst) && Inst->isCompare()) ||
1008 (Inst->isCopy() && Inst->getOperand(i: 0).getReg() == AMDGPU::SCC)) {
1009 auto I = Inst->getIterator();
1010 auto E = Inst->getParent()->end();
1011 while (++I != E &&
1012 !I->findRegisterDefOperand(Reg: AMDGPU::SCC, /*TRI=*/nullptr)) {
1013 if (I->readsRegister(Reg: AMDGPU::SCC, /*TRI=*/nullptr))
1014 Users.push_back(Elt: &*I);
1015 }
1016 } else if (Inst->getNumExplicitDefs() != 0) {
1017 Register Reg = Inst->getOperand(i: 0).getReg();
1018 if (Reg.isVirtual() && TRI->isSGPRReg(MRI: *MRI, Reg) &&
1019 !TII->isVALU(MI: *Inst, /*AllowLDSDMA=*/true)) {
1020 for (auto &U : MRI->use_instructions(Reg))
1021 Users.push_back(Elt: &U);
1022 }
1023 }
1024 for (auto *U : Users) {
1025 if (TII->isSALU(MI: *U))
1026 Info.SChain.insert(X: U);
1027 AnalysisWorklist.push_back(Elt: U);
1028 }
1029 }
1030 V2SCopies[Info.ID] = std::move(Info);
1031}
1032
1033// The main function that computes the VGPR to SGPR copy score
1034// and determines copy further lowering way: v_readfirstlane_b32 or moveToVALU
1035bool SIFixSGPRCopies::needToBeConvertedToVALU(V2SCopyInfo *Info) {
1036 if (Info->SChain.empty()) {
1037 Info->Score = 0;
1038 return true;
1039 }
1040 Info->Siblings = SiblingPenalty[*llvm::max_element(
1041 Range&: Info->SChain, C: [&](MachineInstr *A, MachineInstr *B) -> bool {
1042 return SiblingPenalty[A].size() < SiblingPenalty[B].size();
1043 })];
1044 Info->Siblings.remove_if(P: [&](unsigned ID) { return ID == Info->ID; });
1045 // The loop below computes the number of another VGPR to SGPR V2SCopies
1046 // which contribute to the current copy SALU chain. We assume that all the
1047 // V2SCopies with the same source virtual register will be squashed to one
1048 // by regalloc. Also we take care of the V2SCopies of the differnt subregs
1049 // of the same register.
1050 SmallSet<std::pair<Register, unsigned>, 4> SrcRegs;
1051 for (auto J : Info->Siblings) {
1052 auto *InfoIt = V2SCopies.find(Key: J);
1053 if (InfoIt != V2SCopies.end()) {
1054 MachineInstr *SiblingCopy = InfoIt->second.Copy;
1055 if (SiblingCopy->isImplicitDef())
1056 // the COPY has already been MoveToVALUed
1057 continue;
1058
1059 SrcRegs.insert(V: std::pair(SiblingCopy->getOperand(i: 1).getReg(),
1060 SiblingCopy->getOperand(i: 1).getSubReg()));
1061 }
1062 }
1063 Info->SiblingPenalty = SrcRegs.size();
1064
1065 unsigned Penalty =
1066 Info->NumSVCopies + Info->SiblingPenalty + Info->NumReadfirstlanes;
1067 unsigned Profit = Info->SChain.size();
1068 Info->Score = Penalty > Profit ? 0 : Profit - Penalty;
1069 Info->NeedToBeConvertedToVALU = Info->Score < 3;
1070 return Info->NeedToBeConvertedToVALU;
1071}
1072
1073void SIFixSGPRCopies::lowerVGPR2SGPRCopies(MachineFunction &MF) {
1074
1075 SmallVector<unsigned, 8> LoweringWorklist;
1076 for (auto &C : V2SCopies) {
1077 if (needToBeConvertedToVALU(Info: &C.second))
1078 LoweringWorklist.push_back(Elt: C.second.ID);
1079 }
1080
1081 // Store all the V2S copy instructions that need to be moved to VALU
1082 // in the Copies worklist.
1083 SIInstrWorklist Copies;
1084
1085 while (!LoweringWorklist.empty()) {
1086 unsigned CurID = LoweringWorklist.pop_back_val();
1087 auto *CurInfoIt = V2SCopies.find(Key: CurID);
1088 if (CurInfoIt != V2SCopies.end()) {
1089 const V2SCopyInfo &C = CurInfoIt->second;
1090 LLVM_DEBUG(dbgs() << "Processing ...\n"; C.dump());
1091 for (auto S : C.Siblings) {
1092 auto *SibInfoIt = V2SCopies.find(Key: S);
1093 if (SibInfoIt != V2SCopies.end()) {
1094 V2SCopyInfo &SI = SibInfoIt->second;
1095 LLVM_DEBUG(dbgs() << "Sibling:\n"; SI.dump());
1096 if (!SI.NeedToBeConvertedToVALU) {
1097 SI.SChain.set_subtract(C.SChain);
1098 if (needToBeConvertedToVALU(Info: &SI))
1099 LoweringWorklist.push_back(Elt: SI.ID);
1100 }
1101 SI.Siblings.remove_if(P: [&](unsigned ID) { return ID == C.ID; });
1102 }
1103 }
1104 LLVM_DEBUG(dbgs() << "V2S copy " << *C.Copy
1105 << " is being turned to VALU\n");
1106 Copies.insert(MI: C.Copy);
1107 // TODO: MapVector::erase is inefficient. Do bulk removal with remove_if
1108 // instead.
1109 V2SCopies.erase(Key: C.ID);
1110 }
1111 }
1112
1113 TII->moveToVALU(Worklist&: Copies, MDT);
1114 Copies.clear();
1115
1116 // Now do actual lowering
1117 for (auto C : V2SCopies) {
1118 MachineInstr *MI = C.second.Copy;
1119 MachineBasicBlock *MBB = MI->getParent();
1120 // We decide to turn V2S copy to v_readfirstlane_b32
1121 // remove it from the V2SCopies and remove it from all its siblings
1122 LLVM_DEBUG(dbgs() << "V2S copy " << *MI
1123 << " is being turned to v_readfirstlane_b32"
1124 << " Score: " << C.second.Score << "\n");
1125 Register DstReg = MI->getOperand(i: 0).getReg();
1126 MRI->constrainRegClass(Reg: DstReg, RC: &AMDGPU::SReg_32_XM0RegClass);
1127
1128 Register SrcReg = MI->getOperand(i: 1).getReg();
1129 unsigned SubReg = MI->getOperand(i: 1).getSubReg();
1130 const TargetRegisterClass *SrcRC =
1131 TRI->getRegClassForOperandReg(MRI: *MRI, MO: MI->getOperand(i: 1));
1132 size_t SrcSize = TRI->getRegSizeInBits(RC: *SrcRC);
1133 if (SrcSize == 16) {
1134 assert(MF.getSubtarget<GCNSubtarget>().useRealTrue16Insts() &&
1135 "We do not expect to see 16-bit copies from VGPR to SGPR unless "
1136 "we have 16-bit VGPRs");
1137 assert(MRI->getRegClass(DstReg) == &AMDGPU::SReg_32RegClass ||
1138 MRI->getRegClass(DstReg) == &AMDGPU::SReg_32_XM0RegClass);
1139 // There is no V_READFIRSTLANE_B16, so legalize the dst/src reg to 32 bits
1140 MRI->setRegClass(Reg: DstReg, RC: &AMDGPU::SReg_32_XM0RegClass);
1141 Register VReg32 = MRI->createVirtualRegister(RegClass: &AMDGPU::VGPR_32RegClass);
1142 const DebugLoc &DL = MI->getDebugLoc();
1143 Register Undef = MRI->createVirtualRegister(RegClass: &AMDGPU::VGPR_16RegClass);
1144 BuildMI(BB&: *MBB, I: MI, MIMD: DL, MCID: TII->get(Opcode: AMDGPU::IMPLICIT_DEF), DestReg: Undef);
1145 BuildMI(BB&: *MBB, I: MI, MIMD: DL, MCID: TII->get(Opcode: AMDGPU::REG_SEQUENCE), DestReg: VReg32)
1146 .addReg(RegNo: SrcReg, Flags: {}, SubReg)
1147 .addImm(Val: AMDGPU::lo16)
1148 .addReg(RegNo: Undef)
1149 .addImm(Val: AMDGPU::hi16);
1150 BuildMI(BB&: *MBB, I: MI, MIMD: DL, MCID: TII->get(Opcode: AMDGPU::V_READFIRSTLANE_B32), DestReg: DstReg)
1151 .addReg(RegNo: VReg32);
1152 } else if (SrcSize == 32) {
1153 const MCInstrDesc &ReadFirstLaneDesc =
1154 TII->get(Opcode: AMDGPU::V_READFIRSTLANE_B32);
1155 const TargetRegisterClass *OpRC = TII->getRegClass(MCID: ReadFirstLaneDesc, OpNum: 1);
1156 BuildMI(BB&: *MBB, I: MI, MIMD: MI->getDebugLoc(), MCID: ReadFirstLaneDesc, DestReg: DstReg)
1157 .addReg(RegNo: SrcReg, Flags: {}, SubReg);
1158
1159 const TargetRegisterClass *ConstrainRC =
1160 SubReg == AMDGPU::NoSubRegister
1161 ? OpRC
1162 : TRI->getMatchingSuperRegClass(A: MRI->getRegClass(Reg: SrcReg), B: OpRC,
1163 Idx: SubReg);
1164
1165 if (!MRI->constrainRegClass(Reg: SrcReg, RC: ConstrainRC))
1166 llvm_unreachable("failed to constrain register");
1167 } else {
1168 auto Result = BuildMI(BB&: *MBB, I: MI, MIMD: MI->getDebugLoc(),
1169 MCID: TII->get(Opcode: AMDGPU::REG_SEQUENCE), DestReg: DstReg);
1170 int N = TRI->getRegSizeInBits(RC: *SrcRC) / 32;
1171 for (int i = 0; i < N; i++) {
1172 Register PartialSrc = TII->buildExtractSubReg(
1173 MI: Result, MRI&: *MRI, SuperReg: MI->getOperand(i: 1), SuperRC: SrcRC,
1174 SubIdx: TRI->getSubRegFromChannel(Channel: i), SubRC: &AMDGPU::VGPR_32RegClass);
1175 Register PartialDst =
1176 MRI->createVirtualRegister(RegClass: &AMDGPU::SReg_32_XM0RegClass);
1177 BuildMI(BB&: *MBB, I&: *Result, MIMD: Result->getDebugLoc(),
1178 MCID: TII->get(Opcode: AMDGPU::V_READFIRSTLANE_B32), DestReg: PartialDst)
1179 .addReg(RegNo: PartialSrc);
1180 Result.addReg(RegNo: PartialDst).addImm(Val: TRI->getSubRegFromChannel(Channel: i));
1181 }
1182 }
1183 MI->eraseFromParent();
1184 }
1185}
1186
1187void SIFixSGPRCopies::fixSCCCopies(MachineFunction &MF) {
1188 const AMDGPU::LaneMaskConstants &LMC =
1189 AMDGPU::LaneMaskConstants::get(ST: MF.getSubtarget<GCNSubtarget>());
1190 for (MachineBasicBlock &MBB : MF) {
1191 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1192 ++I) {
1193 MachineInstr &MI = *I;
1194 // May already have been lowered.
1195 if (!MI.isCopy())
1196 continue;
1197 Register SrcReg = MI.getOperand(i: 1).getReg();
1198 Register DstReg = MI.getOperand(i: 0).getReg();
1199 if (SrcReg == AMDGPU::SCC) {
1200 Register SCCCopy =
1201 MRI->createVirtualRegister(RegClass: TRI->getWaveMaskRegClass());
1202 I = BuildMI(BB&: *MI.getParent(), I: std::next(x: MachineBasicBlock::iterator(MI)),
1203 MIMD: MI.getDebugLoc(), MCID: TII->get(Opcode: LMC.CSelectOpc), DestReg: SCCCopy)
1204 .addImm(Val: -1)
1205 .addImm(Val: 0);
1206 I = BuildMI(BB&: *MI.getParent(), I: std::next(x: I), MIMD: I->getDebugLoc(),
1207 MCID: TII->get(Opcode: AMDGPU::COPY), DestReg: DstReg)
1208 .addReg(RegNo: SCCCopy);
1209 MI.eraseFromParent();
1210 continue;
1211 }
1212 if (DstReg == AMDGPU::SCC) {
1213 Register Tmp = MRI->createVirtualRegister(RegClass: TRI->getBoolRC());
1214 I = BuildMI(BB&: *MI.getParent(), I: std::next(x: MachineBasicBlock::iterator(MI)),
1215 MIMD: MI.getDebugLoc(), MCID: TII->get(Opcode: LMC.AndOpc))
1216 .addReg(RegNo: Tmp, Flags: getDefRegState(B: true))
1217 .addReg(RegNo: SrcReg)
1218 .addReg(RegNo: LMC.ExecReg);
1219 MI.eraseFromParent();
1220 }
1221 }
1222 }
1223}
1224
1225PreservedAnalyses
1226SIFixSGPRCopiesPass::run(MachineFunction &MF,
1227 MachineFunctionAnalysisManager &MFAM) {
1228 MachineDominatorTree &MDT = MFAM.getResult<MachineDominatorTreeAnalysis>(IR&: MF);
1229 SIFixSGPRCopies Impl(&MDT);
1230 bool Changed = Impl.run(MF);
1231 if (!Changed)
1232 return PreservedAnalyses::all();
1233
1234 // TODO: We could detect CFG changed.
1235 auto PA = getMachineFunctionPassPreservedAnalyses();
1236 return PA;
1237}
1238