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