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