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